Will a failed WD external hard drive deteriorate further by sitting around?

Question: Sorry if this is not the right place to ask this - if anyone knows a better place kindly direct me.
My external hard drive is already failed: it spins up, my machine tries for 20-30 seconds to recognize it, then it clicks and the light goes out.
Past what period of time from initial failure would you guess that my chances of recovering my data (however good or slim to begin with) will drop significantly?
Answer: Years. No further harm will be done to your data unless you do one of the following:

Connect power to the hard drive.
Subject it to shock or vibration, e.g. in transport.
Expose the drive to harmful environmental conditions such as extreme heat, moisture, humidity, electromagnetic fields.
Disclose the drive's location to a hungry Seinfeld.

If the drive is stored safely, your data will deteriorate no more rapidly on a malfunctioning drive's platters than it would on an intact drive stored in the same way.
Answer: The second law of thermodynamics indicates that if you leave the drive sitting and do absolutely nothing with it, the signal on the platter will eventually degrade as the magnetic forces fade toward equilibrium. That process takes an unknown amount of time, but experience suggests that the longevity of the data tends to outlast its relevance.
That said, non-passive environmental factors such as heat and vibration can have a devastating  effect on data recoverability, particularly in the drive's current state where something may already be physically wrong with the drive, the situation tends to deteriorate more quickly. And more importantly, the data will not become easier to recover on its own than it is right now.
If the data is important enough to warrant the cost, then I would recommend sending the drive to a center where they can work around broken components to recover the data.


Powershell Invoke script block - pass proccess check not just text

Question: How can i get: (works)
$Procname = 'notepad'

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if ((Get-Process | Where-Object {$_.Name -eq $Procname}) -eq $null) {
        Write-Host 'null' -ForegroundColor Red
    } else {
        Write-Host running -ForegroundColor Green
    }
}

Too look like this? (no work)
$Procname = 'notepad'
$chk = (Get-Process | Where-Object {$_.Name -eq $Procname})

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if ($chk -eq $null) {
        Write-Host 'null' -ForegroundColor Red
    } else {
        Write-Host running -ForegroundColor Green
    }
}

The trouble i am having is getting the Get-process | where-object to run from outside the scriptblock, I can pass text OK from outside the scriptblock (IE the $Procname) but i am trying to pass the command, what special things do i need to do?
I have asked uncle google, but I think I'm asking the wrong question.
I have also tried $chk as a Param and an arg but they didn't work for me
Comment: Are you trying to see if `$ProcName` is running on the remote server? Or are you trying to reference the results of `$chk` (run on the local server) from within the scriptblock being executed on the remote server?
Comment: Also, you aren't passing `$Procname`, so you aren't really able to access that string like you think you are. All you are doing is getting processes, looking for processes who's name is equal to `$null`, which is nothing (i.e. $null), so you are asking if `$null -eq $null`, which should always be true.
Comment: I'm trying to see if $Procname is running on the remote server, $chk should be executed on the remote side not the local side
Comment: @TheMadTechnician -- THANK YOU
Answer: Ok, it looks like you want to know how to reference a local variable in a remote execution via Invoke-Command. Totally something you can do with the $using: context. For example, to make your script look to see if notepad is running on your computer, and then reference those results on a remote system you could do this:
$Procname = 'notepad'
$chk = (Get-Process | Where-Object {$_.Name -eq $Procname})

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if ($using:chk -eq $null) {
        Write-Host 'null' -ForegroundColor Red
    } else {
        Write-Host 'running' -ForegroundColor Green
    }
}

Similarly, if you want to see if notepad is running on the remote server you could do this:
$Procname = 'notepad'

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if ((Get-Process | Where-Object {$_.Name -eq $using:Procname}) -eq $null) {
        Write-Host 'null' -ForegroundColor Red
    } else {
        Write-Host 'running' -ForegroundColor Green
    }
}

But personally I think that is hard to read, I'd reverse it and do:
$Procname = 'notepad'

Invoke-Command -ComputerName sandbox -ScriptBlock {

    if (Get-Process | Where-Object {$_.Name -eq $using:Procname}) {
        Write-Host 'running' -ForegroundColor Green
    } else {
        Write-Host 'null' -ForegroundColor Red
    }
}

Or without running anything on the remote server directly:
$Procname = 'notepad'
$chk = Get-Process -Computer sandbox | ?{$_.Name -eq $Procname}
If($chk){
    Write-Host 'Running' -ForegroundColor Green
}else{
    Write-Host 'Null' -ForegroundColor Red
}


How do I mark translation strings as non-customized?

Question: Drupal 8 distinguishes between "customized" and "non-customized" translations.
A customized translation is a translation that has been imported from a module and then changed at /admin/config/regional/translate.
So, if I edit a translation that has been imported, it becomes customized.
What if I edited many translations, but then changed my mind and wanted to restore them to the default?
How can I revert a customized string into the original non-customized one?  (And is it possible to do this to strings in batches?)
Comment: I would locate the string in the database table `locales_target` and set **customized** to `0`. Then the next time you update the translations it will be restored to default.
Answer: Based on 4k4's suggestion, I was able to do this with SQL:
drush sqlq < "UPDATE mydb.locales_target SET customized = 0 WHERE customized = 1;"

Warning: This will unset the customized flag for all strings on your site, but leave the customized translations in place.  This is what I wanted, but make sure it's what you want too before running the command.  Always make a backup, etc.


How to count number of published nodes of a specific content type in twig template?

Question: I'm looking for a way to achieve this in my Twig file; if the number of published entities of a content type 'promotions' is at least one, a certain entity should be displayed in a content type Shop. I'm trying to show a banner only if there is at least one published promotion entity.
I could use some help with the if-function. I've written it down with I'm trying to do.
if(published promotion entities > 0){
{{ drupal_entity('node', 2668) }}
}

Any ideas to get me going? Thanks!
Comment: https://twig.symfony.com/doc/3.x/tags/if.html
Comment: You could filter the nodes in a View and then check the results with Twig Tweak, see https://www.drupal.org/docs/contributed-modules/twig-tweak/cheat-sheet#s-drupal-view-result
Comment: Hi Kevin, I know how to use an if-function, but I don't know how to get the total count from entities from another content type. And check if at least one is published?
Comment: @4k4 That's a great idea. Using the result in an if function breaks the page partially, weirdly.
Answer: In a preprocess hook function for your template, you can code something like this.
function MYTHEME_preprocess_TEMPLATE_HOOK(&$variables) {
    $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
    $query->condition('type', 'promotions');
    $query->condition('status', 1);
    $query->range(0, 1); // only need one
    $results = $query->execute();
    $variables['has_published_promotions'] = (bool)count($results);
}

has_published_promotions will be available in your Twig template and will be TRUE only when there are published nodes of that type.
Comment: Hi. alfred, this results in an error:

`ParseError: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in Drupal\Core\Extension\Extension->load() (line 4 of themes/custom/mytheme/mytheme.theme).`
Comment: Hi, I've amended the code to fix the error.
Answer: Create a view with a filter of published nodes of that content type. With the snippet below you can add {{ published_count }} to your page.html.twig
use \Drupal\views\Views;

function MYTHEME_preprocess_page(&$variables) {
  // make the result count available as a variable in page.html.twig
  $view = Views::getView('published_promotions');
  $view->setDisplay('default');
  $view->execute();
  $variables['published_count'] = count($view->result);
}

Now you can do the following in Twig:
{% if published_count > 0 %} // print banner here {% endif %}

More: https://stefvanlooveren.me/blog/get-views-row-count-twig-drupal-8


The Newton Brothers "I'm the candy Man" chord progression analysis

Question: I've been listening to "I'm the candy man" from The Fall of the House of Usher this morning and am hitting a little roadblock trying to think of the theory behind the chord progression.
It goes a bit like this:
Dm A C Bm7(b5) Eb Gm Ab A7 (i believe)
What i have gleamed so far is that it could be considered staring in D minor, shifting into G minor before briefly A flat then with the A7 being the V of Dm to bring it back home.  Am I on target here?  Thank you!
I'm the candy man
Answer: In the key of Gm, Ab can be seen as a Neapolitan chord. Or bII borrowed from G phrygian.
But then it leads to A7, and I'm not aware of a good functional explanation of that. It's a chromatic connection.
Answer: Once again, I offer one of my favourite quotes: 'Notes outside the scale do not necessarily affect the tonality'. Walter Piston, Harmony.
A♭ is a chromatic neighbour to A.  No need to infer a new tonal centre.
Comment: Ab is not a tritone substitution for E. That would be Bb7.
Comment: Indeed.  Answer edited. In my eagerness to find a functional excuse for Ab, I talked rubbish.  A functional excuse is unnecessary, and there isn't one.
Comment: Ab is a chromatic neighbor to G. If it was a chromatic neighbor to A, it would be spelled G#.
Comment: So spell it as G#.
Answer: Firstly, I would write the harmony like this:
Dm A/C# Am7/C Gadd9/B Eb/Bb Gm(add9) Ab A7
You could write the chords without the bass inversion, but this way it looks more natural to me. Notice that in the third chord you can definitely hear an A, and initially there's no G, that's why wrote it as Am7/C and not a C chord, and the fourth chord is a pure G/B until the very end when the A comes in, and there is no F, so it sounds more like a G chord than a B chord.
Anyway, to me, the chords that feel like tonal centers (i.e. resting points, when there is a sense of conclusion) are Dm, Gadd9/B, and Gm(add9). So at the start, Dm A/C# definitely feels like i V in D minor. As we approach G major and rest on it, Am7/C Gadd9/B feels like a Plagal cadence ii I in G major. As Eb/Bb brings notes from a different tonality and appears to resolve to Gm(add9), that sounds like a VI i in G minor. Ab feels like just a chromatic approach to A7, the V of D minor.
Even though you could think the tonality is constantly  shifting between these 3 (D minor, G major, G minor), the whole thing starts and ends at the same place (D minor), and the changes in tonality are very brief, so I think they would be best described by the concepts of "borrowed chords", or "tonicizations".
Thinking of the whole progression in D minor, we could interpret Gadd9/B as being borrowed from the parallel major, Eb/Bb as being a Neapolitan chord, and Ab as a chromatic transition between Gm an A.
Another thing to pay attention to is the chomatic movement of the bass, that moves down (or up at the end) one semitone at a time. This helps explain the appearance of B natural and Ab, that are outside the scale of D minor, but fit this chromatic movement very well.


SQL Replace Multiple Values based on one column value

Question: I need to replace results on up to 9 columns based on one other column value.
If the column "role" is the value "SeniorManagement", I want to replace what would be default hierarchical values with hard values.
Here's how I can accomplish this now:
 , CASE
   WHEN d.Role = 'SeniorManagement'
   THEN (Replace(p.Firstname,'John','Joe')) END as First
 , CASE
   WHEN d.Role = 'SeniorManagement'
   THEN (Replace(p.Lastname,'TopDog','AssignedPerson')) END as Last
 , CASE...

My question is, is there a less verbose way to combine these?
Pseudo ( I know this doens't work :-)
 , CASE
    WHEN d.Role = 'SeniorManagement'
    THEN (Replace(p.Firstname,'John','Joe')) as First
    THEN (Replace(p.Lastname,'TopDog','AssignedPerson')) as Last
    THEN (Replace(p.Email,'TopDog@wherever','AssignedPerson@wherever')) as Email

Thanks
Comment: It might be nice to better understand your need (for example show more of your query), cause with your sample code, I would say : well, just do a `WHERE d.Role='SeniorManagement'`, as you have no else condition in your case when...
Comment: If you want to update records to replace some ppl by other, this way is not really safe it can become a bit messy when people have the same first name. Just use multiple UPDATE statements with different where clauses
Comment: I appreciate the advice. Thanks.  Here's a few extra bits of info.  I am not permitted to overwrite anything.  The reason I am doing this, is the topdog should never be contacted based on any results.  These results will show on a page.  The hierarchy is numeric and each result builds on another. So, if TopDog ends up in these fields - I need to replace with a direct report of his outside the listing.
Answer: what about using a function?
create function dbo.GetColumnValue
(
   @ColumnBasedValue varchar(max),
   @ColumnToReplace varchar(max), --or the type you want
   @ToReplace varchar(max),
   @Replacement varchar(max)
)
as
BEGIN

return (select case @ColumnBasedValue when 'SeniorManagement'
                      then (Replace(@ColumnToReplace,@ToReplace,@Replacement))
                      else @replaceValue END)

END

and use it like
select dbo.GetColumnValue(d.Role, p.Firstname,'John','Joe') as First,
dbo.GetColumnValue(d.Role, p.Lastname,'TopDog','AssignedPerson') as Last..

Comment: This looks good. I am going to play with this for a bit.  Thanks
Comment: I am almost there. This has helped greatly! When the topdog ends up in the results, it works flawlessly.  When the topdog is not in the results, it leaves the fields NULL.
Comment: Sweet! I got it.  You led me down the right path Gonzalo. I really appreciate it. I made one change to the end:

else @ColumnToReplace END) This allows me to retain the original value if the value is not SeniorManagement.
Answer: Depending on what the context is, you might be able to get away with doing raw selects.
Select d.Role, 'Joe' as First, 'AssignedPerson' as Last
and just filter each select with a where clause.
If you want to do multiple ones, use a union.


Fetch data from other Website

Question:
Possible Duplicate:
How do I make a raw HTTP request in Java?

I am monitoring a website which updates transaction data every few seconds, so for having better performance I need to store those data and analyze them (like plotting, etc.).
My question is how I can make a request to that server by Java EE and get the values which are available in a table in that site?
I should add that I do not search a solution by .net or php, and I have tried by JQuery, java HTTPRequest but I did not found the solution.
Any idea will be appreciated.
Answer: If they provide some sort of API/webservice that is best way to communicate,
if not and if the source site doesn't have any issue with the data you are taking from them you could use HTTP requests to get HTML response and parse the portion you want using JSoup
Comment: Thanks, I knew ba JSoup we can get the source code but actually I am searching for the values in the table, for example how I can get a data from following line?
Comment: check jsoup api doc, there is a method to fetch HTML dom by id
Comment: Actually the problem is, by javascript the data will be updated, but Jsoup does not see that
Answer: Have you actually tried anything yourself yet? SO is not a code generation tool.
That being said, this seems to be of interest: How do I make a raw HTTP request in Java?
Comment: It is not the same question, by a simply HTTP request I get timeout error from that site.
Comment: I still stand by my main comment that SO is not a code generation tool. You've not provided any evidence that you have even tried anything yourself yet.

The HTTP request in Java question seemed relevant, hence the link. I didn't say it was the same question, just that it might be of interest.
Comment: Thanks, but it is much better to check the question and the answer of this question and related questions before leaving any comment

Fetch data from other Website


How to generate eBay OAuth user token?

Question: I have been using this ebay-sdk-php from David Sadler to generate a Trading Call to Ebay API, but first I have to create the OAuthUserToken.
I used the gettoken.php example and created the following code:
    $service = new \DTS\eBaySDK\OAuth\Services\OAuthService([
        'credentials'   => config('ebay.'.config('ebay.mode').'.credentials'),
        'ruName' => config('ebay.'.config('ebay.mode').'.ruName'),
        'sandbox'     => true
    ]);

    $token = session('????'); //here I have to retrieve the authorization callback information.
    /**
     * Create the request object.
     */
    $request = new \DTS\eBaySDK\OAuth\Types\GetUserTokenRestRequest();
    $request->code = $token;
    /**
     * Send the request.
     */
    $response = $service->getUserToken($request);

For some reason I cannot generate a redirect for a UserOauth Token. I supposed that code:
$service = new\DTS\eBaySDK\OAuth\Services\OAuthService([

...automatically generated a redirect to eBay Grant Area, but it was not the case.
Does anyone know how to solve this? I would like to know how to grant the user access and then perform a call (e.g. getEbayTime).
Answer: You can use redirectUrlForUser() function to generate the URL for redirection.
$url =  $service->redirectUrlForUser([
    'state' => '<state>',
    'scope' => [
        'https://api.ebay.com/oauth/api_scope/sell.account',
        'https://api.ebay.com/oauth/api_scope/sell.inventory'
    ]
]);

Then, call e.g. header() to redirect the user. Note that you can't display any text/html before the header call.
header("Location: $url");

After that, your token should be stored in $_GET["code"] when the user returns from ebay website.
$token = $_GET["code"];

So, you can send your request and use the example to get the OAuth token back.
$request = new \DTS\eBaySDK\OAuth\Types\GetUserTokenRestRequest();
$request->code = $token;

$response = $service->getUserToken($request);

// Output the result of calling the service operation.
printf("\nStatus Code: %s\n\n", $response->getStatusCode());
if ($response->getStatusCode() !== 200) {
    // Display information that an error has happened
    printf(
        "%s: %s\n\n",
        $response->error,
        $response->error_description
    );
} else {
    // Use the token to make calls to ebay services or store it.
    printf(
        "%s\n%s\n%s\n%s\n\n",
        $response->access_token,
        $response->token_type,
        $response->expires_in,
        $response->refresh_token
    );
}

Your OAuth token will be in $response->access_token variable. The token is short-lived, so you need to renew it from time to time if you want to use it. To do that, use $response->refresh_token and call $service->refreshUserToken().
$response = $service->refreshUserToken(new Types\RefreshUserTokenRestRequest([
    'refresh_token' => '<REFRESH TOKEN>',
    'scope' => [
        'https://api.ebay.com/oauth/api_scope/sell.account',
        'https://api.ebay.com/oauth/api_scope/sell.inventory'
    ]
]));
// Handle it the same way as above, when you got the first OAuth token

Comment: $token = $_GET["code"]; is not used in your example
Comment: @s_h Updated my answer. It's basically what you have in the question.

How to generate eBay OAuth user token?


Temporarily reduce Cisco trust level

Question: I'm a new network admin and I'm looking through the various config files we have in our routers/switches/asa.  I'm wondering if there is a way to lower trust level that my login has from 15 to something that is read only.
So if I log in to our routers and switches I'm automatically taken to the enable prompt.  I'm wondering if when I log in through SSH/Telnet if that SPECIFIC session can be reduced to read only, but the next login will be back at trust level 15?
Comment: How are you logging in? Local user account or RADIUS?
Answer: You can use the command disable to reduce your privilege level; you can also specify a level to move to, i.e. disable 0 or disable 10.
Comment: Default levels are 1 (can't do almost anything at all) and 15 (can do everything). If you want something in the middle, you need to explicitly define it. More info here: http://www.cisco.com/en/US/docs/ios/12_2/security/configuration/guide/scfpass.html.
Comment: Awesome, thank you.  As to your comment above.  The authentication is handled via our Active Directory, which is the extent of my knowledge on that (at the moment).  Happen to know the default and highest level of trust that is read-only?

Temporarily reduce Cisco trust level


A question about universal coefficient theorem

Question: Assume that $M$ is $n$-dimensional, compact, connected and oriented with boundary manifold. Show that if $H_{k-1}(M,\partial M, Z)$ is torsion-free, then $H_{n-k}(M, Z)$ is torsion-free.
This question is a my PhD. qualification exam question. I didn't solve this question in exam today. Can you help me?
Comment: By Lefschetz duality, $H_{k-1}(M,\partial M) \cong H^{n-k+1}(M)$, and by the universal coefficient theorem, the torsion in $H^{n-k+1}$ is the torsion in $H_{n-k}$.
Answer: By Poincaré-Lefschetz duality, $H_{k-1}(M,\partial M;\mathbb{Z})$ is isomorphic to $H^{n-k+1}(M;\mathbb{Z})$.  The universal coefficient theorem gives that $H^{n-k+1}(M;\mathbb{Z})$ is isomorphic to $\operatorname{Hom}(H_{n-k+1}(M;\mathbb{Z}),\mathbb{Z})\oplus\operatorname{Ext}(H_{n-k}(M;\mathbb{Z}),\mathbb{Z})$.  If $H_{n-k}(M;\mathbb{Z})$ had torsion, then this would appear in the $\operatorname{Ext}$ group, leading to torsion in $H_{k-1}(M,\partial M;\mathbb{Z})$.


Routing different interface

Question: I have a gateway+webserver box with multiple outside interfaces to service multiple SSL sites. I'm using plain simple iptables script as a firewall.
The default outgoing interface is eth0 (220.127.116.11). I need to have the connections initiated from the internal address 172.16.1.2 to be routed out via eth0:2, so that the outside world would see those connections originating from 22.214.171.124.
root@gateway:~# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:50:56:b5:30:22
          inet addr:220.127.116.11  Bcast:126.96.36.199  Mask:255.255.255.224
          inet6 addr: fe80::250:56ff:feb5:3022/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:24106762 errors:0 dropped:0 overruns:0 frame:0
          TX packets:34661833 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4700635137 (4.7 GB)  TX bytes:32948653469 (32.9 GB)

eth0:1    Link encap:Ethernet  HWaddr 00:50:56:b5:30:22
          inet addr:184.108.40.206  Bcast:184.108.40.206  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

eth0:2    Link encap:Ethernet  HWaddr 00:50:56:b5:30:22
          inet addr:188.8.131.52  Bcast:188.8.131.52  Mask:255.255.255.224
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

eth1      Link encap:Ethernet  HWaddr 00:50:56:b5:24:5c
          inet addr:172.16.1.1  Bcast:172.16.1.255  Mask:255.255.255.0
          inet6 addr: fe80::250:56ff:feb5:245c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:34158142 errors:0 dropped:0 overruns:0 frame:0
          TX packets:22922477 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:32020841479 (32.0 GB)  TX bytes:3309207778 (3.3 GB)
...

Comment: Have you seen this: http://serverfault.com/questions/188214/linux-routing-internal-ip-to-use-a-specific-external-ip
Comment: I had not. Had to modify from -A to -I and it worked: iptables -t nat -I POSTROUTING -s 172.16.1.2 -j SNAT --to-source 126.96.36.199. Thanks!
Answer: This should do it, if I understand correctly, and will affect outbound traffic from the box to 172.16.1.2 via 220.127.116.11:
route add -host 172.16.1.2 gw 184.108.40.206
If that isn't what you're after then please explain what you're trying to achieve. If you're looking for 172.16.1.2 to answer on 22.214.171.124 then that's more complex.
Comment: I am sorry. My question indeed could be understood in multiple ways. I will fix that. I was looking for a way which would result the outside world to see connections initiated from the internal IP of 172.16.1.2 to appear as being made from 220.127.116.11. But only in case of that specific internal IP. When a connection is made from any other internal IP, the outside world should see it as originating from 188.8.131.52.
Comment: I rephrased the question to eliminate the possibility for different ways to understand it. Actually I already solved my problem thanks to the comment of Ole_Brun.
Comment: Glad to hear it's fixed.
Answer: iptables -t nat -I POSTROUTING -s 172.16.1.2 -j SNAT --to-source 184.108.40.206

Comment: Shouldn't that be PREROUTING as you want to alter the packet before the kernel makes a routing decision?

Routing different interface


Ember 2.11, Data passed between parent to child components.

Question: I have a parent and a child components such that child component have few radio button options which appears based on a checkbox( defined in parent component). I pass the checkbox as a mutable variable to child component. The groupValue of the radio button changes based on the computed property dependent on checkbox in the child component. Now to my surprise, when the init() method of a child component is called, the computed property is trigged. If I change the value of the radio button and change my checkbox, the computed property is not trigged.
So my question is once a mut data is passed from parent to child component, can't a parent changing that data wouldn't trigger child component computed property?
Comment: Please include your code in your question so we can help you.
Answer:
So my question is once a mut data is passed from parent to child component, can't a parent changing that data wouldn't trigger child component computed property?

Yes. When parent change that data, it will trigger child component computed property for sure.
So please go through ember-twiddle.com come up with code that is not working. that will give us good picture of your question and reason for why is not working.


@Optional in TestNG Parameter is overriding the values that I'm passing in XML

Question: When I try to use multiple parameters using @Parameter, @Optional needs to pass the value only when I'm not providing the value for the parameter in testng XML.
But in the below scenario, no matter what I pass in the XML for the "Optional" parameter the values that I've given in @Optional is being taken into consideration.
XML that I'm using:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
    <suite name="Cross Browser Multi-Paramet - Suite">

    <test name="Cross Browser Multi-Paramet - Firefox Test">
    <parameter name="Browser" value="Firefox" />
    <parameter name="URL" value="https://www.oneplus.in/" />
    <classes>
        <class name="CrossBrowser.CrossBrowserMultipleParamter">
        </class>

    </classes>

</test>
</suite>

And the code is:
package CrossBrowser;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class CrossBrowserMultipleParamter {

public static WebDriver d;

@Test
@Parameters({ "Broswer", "URL" })
public static void cbmultpara(@Optional("Chrome") String browsername, String siteurl) throws Exception {

    if (browsername.equalsIgnoreCase("Firefox")) {
        System.out.println("Browser name is" + browsername);
        d = new FirefoxDriver();
    } else if (browsername.equalsIgnoreCase("Chrome")) {
        System.out.println("Browser name is" + browsername);
        d = new ChromeDriver();
    }
    d.manage().window().maximize();
    d.get(siteurl);
    System.out.println("Loaded the page sucessfully");
    d.quit();
}

}
Though I'm passing value as "Firefox" it is launching Chrome.
Can someone clarify?.
Answer: In order load the parameters from the testng.xml properly, you need to add surefire plugin configuration as shown below in your pom.xml file. Please verify that and let me know if you still face the same issue.
Note: Please mark this answer as accepted, if it is helpful.
POM.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>testng</groupId>
    <artifactId>annotation</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.3.0</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.21.0</version>
                <configuration>

                    <suiteXmlFiles>
                        <suiteXmlFile>testng.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Comment: I'm using the right packages and the browser name is being displayed as "Chrome". No matter what I pass in the XML, it launches Chrome.
Comment: Could you please share the entire test case class content with us.
Comment: So how are you running the project? Have you configured testng.xml in pom file or you are running the class file directly?
Comment: And when I use one parameter using @Parameter, it works like a charm.
Comment: I'm running the xml file.
Comment: If you run pom.xml file without surefire configuration in it then the parameters will not get loaded properly. Please try to update the pom.xml same as mentioned in the answer and let me know if you face the same issue
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221248/discussion-between-surendra-anand-and-unknownbeast).
Comment: Can we have the surefire configured in testng.xml file. I'm trying to implement it without maven.


How to bypass menu link access permission

Question: I have added some links from the admin page to a menu, but these links are not displayed in anonymous.
Certainly anonymous doesn't have access permission to the links, but I want to display the menu.
is there a hook or something that bypass access permission?
Thank you.
Comment: Drupal first verifies the user has access to the linked pages. If the user doesn't have access to those pages, the links aren't shown. It would not make sense to show a link for which the user gets a 403 error when the user clicks on the link.
Comment: Render the menu tree without `menu.default_tree_manipulators:checkAccess`, see https://drupal.stackexchange.com/questions/293080/why-cache-tags-is-different-if-i-am-logged
Comment: I have added another module that redirects user to the login page when anonymous visits restricted pages.
So I want to display a link even on a page that user doesn't have permission.
Comment: I have created a menu block referring to the following link.
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/group/menu/8.8.x#sec_rendering
Overriding the existing menu seems difficult, but I could do what I expected.
Thanks for comments.
Answer: You could create your menu links as /user/login?destination=/my-path and that will mean authenticated users would get taken to /user/login but then instantly redirection to /my-path because they're already logged in
Anonymous users will see the menu links and be taken to the login page if they tried to click them
Answer: I have created a menu block referring to the following link.
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/group/menu/8.8.x#sec_rendering
And by placing that block in the block layout, I achieved my purpose.


Four part writing: How to voice diminished 7th chords?

Question: I am currently doing part writing, and have come into a bit of a conundrum. I want to use a sharp 4 dim 7 (Fsharpdim7), to link up my IV chord (FM) to my V7 chord (G7).
I know that 7ths should usually be prepared in the previous chord, or approached by leap if this is not possible. However, when I adhere to these rules in this case (particularly approaching the dim7th by leap), the end product sounds terrible. So, in the pictured example, I have tried to move the voices as little as possible, only moving by step and maintaining all common notes. When I play this as all 7th chords (FM7, Fsharpdim7, G7) it sounds great, but here my first chord is an FM triad, so we move from F (doubled root) to Eflat (dim7th) then to F (7th of G7). It doesn't sound as good, but is this none-the-less the correct/ best way of voicing this progression? Is there anything else I should know about voicing these passing dim7th chords?
Answer: You're correct that these sevenths should be prepared (by step or by common tone) in the same voice! But also remember that we need to resolve those sevenths down by step, too.
Thus the E♭ in your middle chord, since it's the chordal seventh, needs to resolve down to the D of the next chord.
Regarding preparing the seventh of the G7 chord, there are a few options:

One is to acknowledge that it's mostly impossible to prepare this by step, since there's no G in the prior chord. Thus you could resolve to a V triad, and then a G (probably in the soprano, coming from the A) can quickly move to F to turn this V triad into a V7.
Or you could go the full Beethoven route and have the F♯ in the bass slide down to F, making this V7 a V42. But if this is for a theory class, maybe wait to do this; your teacher probably hasn't talked about this yet.

My preferred solution would be #1 above: when you resolve your alto E♭ to D, you'll see that it's likely best for your tenor C to resolve down to B instead of doubling that D. And since we can't double the leading tone (B), let's also move that soprano down to G before moving it to F to make the V7.
Comment: @EdB123 In my experience, preparing a chordal seventh by a descending leap is actually the least preferable; an ascending leap is more common. Typically, however, we opt for preparing it by step or by common tone.
Comment: thanks for such a great answer! Am trying out all these options.
Comment: Regarding the Beethoven option, I think i have run into a problem in the tenor and bass voices. Chord IV- F-C, chord sharp 4 dim -Fsharp C, chord V42- F B. thats two dim 5th/aug 4th intervals in a row (F sharp and C and then F to B).I can get rid of this problem by doubling the D (5th) in the V 42 chord, but then the chord has no root, and if I move the G to the tenor voice, the Fsharp C interval moves to a 9th interval between F and G., so doesnt resolve. I have a picture but I dont know how to send it on comments! thanks for any help given.
Comment: Those two consecutive tritones are exactly how Beethoven did it. (In fact, in some sequences he just had a string of tritones in one hand.) You've done it exactly right!
Comment: okay, brilliant- I'll give it a listen! Also, this is the first I've heard of 7ths being prepared by step. It was my understanding that 7ths can only be prepared by common tone- or- if this isn't achievable, by leap. I'm fairly new at this so very much willing to be educated!
Answer: Rather than think of the diminished chord as #IV, consider it as viio/V. In that case, scale degree 4 (relative to V: i.e., C is 4 of G) should resolve downward to B. That allows the Eb (chordal 7th) to also resolve downward, to D.
From there you have a choice. If you want a root position V7 chord, then the soprano A moves down to F (you could have the soprano play G either as a passing note or as a resolution before continuing to F). Alternatively, the bass moves to F and the soprano moves to G.
Comment: @EdB123 I'm just using my ear for this comment -- rather than looking up "the rules" -- but I think the issue is the irregular resolution of the Eb-A tritone in the diminished chord. Having the A (a dissonance against the Eb) "resolve" to another dissonance (the F in the G7) chord is jarring. My suggestion to move to G first works better.
Comment: Hi Aaron, thanks yet again for your help. The V42 option works fantastically well. The other option, using G as a passing note, also works really well. However, I'm a bit confused about something. I have learnt that 7ths should either be prepared by leap or common tone. Therefore, in theory, it should be fine for the 7th of V7 (F) to move by leap from the A in the previous chord. However, I have tried this and it sounds jarring. This seems to suggest a gap in my knowledge, can you shine a light? Thanks!
Comment: Ah yes- this makes sense. As the tritone E flat (alto) A (sop), resolves to a minor third D (alt) F (sop), I thought this should be fine on paper. But that 7th is still dissonant with the bass so may well be the explanation!
Answer: I know this isn't exactly what you asked, but Eddie Lang would often move from the IV chord to a diminished chord a whole tone below the root of the IV, and the resolved up to the first inversion of the tonic skipping the V chord altogether, which is a half step above that.

Sorry, I am not a pro at SATB voice leading but I tried my best.
You can hear it here

I set the video to start on measure 20 of this song.
Comment: Thanks for this interesting new perspective! Ed


Passando uma variável de javascript para session

Question: Gostaria de saber, como faço para enviar um valor que tenho em javascript para uma @session. no caso seria mais ou menos assim:
Tenho uma variável:

var id = $(Pessoa).val();

este ID queria utilizar em uma variável de sessão, porém tentei fazer assim:

@Session["Pessoa"] = id;

mas quando rodo a página da erro no javascript. como poderia fazer ?
Comment: Qual o objetivo disso?
Comment: Precisava levar para o controller,  mas já arrumei uma outra solução. Valeu
Answer: Por que não manda esse id pro controller utilizando o json e coloca ele numa viewbag, e usa ela na view?
Comment: Consegui aqui aos 45 do segundo tempo passando por parâmetro no link. Amanhã eu respondo minha pergunta própria pergunta kk Valeu mano boa sorte pra nós
Comment: Ah, aí sim, nice ;)


Elemento Scroll da classe DataGrid WPF C#

Question: Tenho uma função que cria um grid,e precisava saber o valor do scroll desse grid, para poder disparar um evento quando chegasse no fim da página. Mas não sei como conseguir esses valor, a função está aqui em baixo:
using System.Windows.Controls;

     public override FrameworkElement criar()
        {
          if (formulario == null)
            return null;

          DataGrid    grid = new DataGrid();
          ContextMenu menu = new ContextMenu();

          definirStyle(grid, "tema.estiloGradeDados");
          definirBinding(grid, DataGrid.ItemsSourceProperty, "dados", true);

          grid.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
          grid.VerticalScrollBarVisibility   = ScrollBarVisibility.Auto;

          grid.GroupStyle.Add(new GroupStyle() {ContainerStyleSelector = new SeletorEstiloItemGrupo() });
          grid.ContextMenu = menu;

          grid.Height = 800;

          foreach (DskCampo campo in dskFormulario.campos)
          {
            criarItemMenu(menu, campo);
            criarColuna  (grid, campo);
          }

          return grid;
        }

O scroll do DataGrid descende de "ScrollViewer" não? como faço para manipula-lo?
Comment: O `DataGrid` tem um evento `Scroll`, ele não ajuda?
[system.windows.forms.datagrid.scroll](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagrid.scroll(v=vs.110).aspx)
Comment: Não, essa bibilioteca usa o forms, e eu estou usando o DataGrid do "System.Windows.Controls" https://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(v=vs.110).aspx
Answer: O DataGrid tem uma propriedade chamada ScrollViewer, nele você pode adicionar o evento de scroll (ScrollChanged) e tem várias propriedades: ContentVerticalOffset, e várias outras relacionadas ao tamanho e scroll vertical.
Fonte: ScrollViewer.ContentVerticalOffsetProperty Field
Comment: A minha questão é exatamente como pegar essa propriedade então, dada a minha função acima. Não acho nenhum exemplo sobre como fazer isso.
Answer: No seu evento ScrollChanged, você pode usar o código abaixo:
int AlturaTotal = 0;
foreach (DataGridViewRow row in grid.Rows){
    AlturaTotal += row.Height;
}

if (AlturaTotal - grid.Height < grid.VerticalScrollingOffset)
{
    //quando entrar aqui é por que chegou na ultima linha
}

Comment: Estou usando o DataGrid do controls e não do forms, essas propriedades não existem no System.Windows.Controls;


Users cannot login after Upgrade to 7

Question: I have upgraded a D6 to D7 site on my localhost. After upgrade I can login using admin credentials as per usual. I have disabled Clean URLs and I see that users are in detabase. Actually all works well however when I try to log in to a user account, I get:
The website encountered an unexpected error. Please try again later

I get this error also, when I create a user from admin panel.
I tested a lot of suggestions but none helped. So appreciate your hints.
Comment: Well, I found a solution: as per http://stackoverflow.com/a/19113091/727695 I added some description to error and figured out that messaging module causes the problem. I disabled messaging, and could login afterwards
Comment: post it as answer and include the essential part of that link.
Comment: @Bala: the answer added
Answer: To figure out what was the problem, thanks to this post I opened include/error.inc
and replaced
print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.')));

with
print theme('maintenance_page', array('content' => t('The website encountered an unexpected error. Please try again later.'.$fatal.' '.var_export($error,true))));

The new command prints out some useful info that can be used to debug. In my case, it turned out that messaging module caused the problem. I disabled messaging, and could login afterwards.
Note: before going to production, switch back to original error.inc, since the error outputs can be a gift to attackers.

Users cannot login after Upgrade to 7


"Heap size" is growing way faster than "Used heap"

Question: the Heap size of my java application is continuously growing till it reaches the Max Heap sizeof 1G. Why is that so?
I start my application with those parameters:
java -Xmx1G -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC -XX:ShenandoahUncommitDelay=5000 -XX:ShenandoahGuaranteedGCInterval=10000 -Dlog4j.configurationFile=./log4j2.xml -jar applicaiton.jar

Edit:
When I restart my application you see there isn't a gap between "Heap size" and "Used Heap" but this gap is getting bigger and bigger, can I somehow limit that gap?
Comment: may be because this is how your app allocates objects?
Comment: Use VisualVM and check why heap size is growing. Provide more details also.
Comment: @Eugene in my understanding the blue line("Used Heap") is what my application actually needs?
Comment: @user2071938 yes the blue line is what you "actually" need, but yellow is what you "have commited to" at the moment.
Answer: I am not particularly familiar with the way that the new Shenandoah GC normally behaves.  However, there is nothing particularly alarming (to me) with that graph.
According to https://shipilev.net/talks/devoxx-Nov2017-shenandoah.pdf, the modus operandi (MO) of a this GC with regards to memory utilization is a bit different to some other collectors.

"We shall take all the memory when we need it, but we shall also give it back when we don't".

If there is significant load on the allocator (i.e. lots of objects being allocated) Shenandoah will aggressively expand the heap.  This is based on the observation that a low-pause GC is most efficient (and most likely to keep up!) if it has plenty of space to work in.
But the flipside is that if your system is idle, the GC will give memory back to the OS more freely than many other GCs.

This seems to fit the memory graph in your question.
The other thing to note is that the heap size (orange) is nowhere near your max-heap limit.  If you get close to that limit, the GC will stop growing the heap.
Finally, note that you can apparently encourage Shenandoah to give back uncommitted memory faster by using a smaller value for the -XX:ShenandoahUncommitDelay=<millis> option.  However, it is recommended to NOT make it too small because that is liable to slow down the allocator.
(Source: https://www.javacodegeeks.com/2017/11/minimize-java-memory-usage-right-garbage-collector.html)
Comment: hi! There is no significant load, even so the Heap size is increasing till it reaches the Max Heap size. I have running a few java processes, any process can hav a max size of 1G but if every process allocates 1G there is not enough space on my OS. The max heap size is just to manage spikes. So I need the GC to release space when they are not needed anymore!
Comment: There must be sufficient load to make the JVM think that the allocator is not idle for (erm) 5,000 milliseconds.   If you want the GC to give memory back more often, try decreasing the `-XX:ShenandoahUncommitDelay` value.
Comment: I was going to have a look at the source code to see if there were other relevant tuning options.  The repo site is borked at the moment.
Comment: thx! I edited my answer to show how the GC performs when I restart my application
Comment: this does not answer the question as it is. the OP showed the visualVM in minutes and `ShenandoahUncommitDelay` setting is only `5000` ms; the un-commit should have happened, making `ShenandoahUncommitDelay` even smaller will make no difference
Comment: and btw `ShenandoahUncommitDelay` does not have to do much (or directly) with the allocator, it's _when_ to un-commit certain regions that stayed *empty* for the at least this period.


Why isn't the super class of a meta class of a root class a NULL pointer?

Question: In the objective-c runtime, a class is represented by a structure like this:
typedef struct class_t {
    struct class_t *isa;    // Points to the class' meta class
    struct class_t *super;  // Points to the class' super class
    Cache cache;
    IMP *vtable;
    union {
        class_ro_t *rodata;
        class_rw_t *rwdata;
    };
} class_t;

When a MyClass class is a root class and not a meta class, its super member is a NULL pointer (which is understandable, since it is a root class, so it doesn't have a super class).
However, if we get the isa member of that same MyClass root class (which points to MyClass' meta class), and we get the super member of that isa member, it is not a NULL pointer, but a pointer to MyClass (not meta class). Shouldn't the super class of a meta class of a non-meta root class be a NULL pointer (as the super class of a non-meta root class is)?
Since it's not, for what is it supposed not to be?
I'm asking this because, the way things are actually, if methodX is an instance method (not a class method) of a MyClass root class, the statement [MyClass methodX]
would call methodX (and it actually does), what shouldn't happen (again, because methodX is a instance method, not a class method, so it should not respond to the [MyClass methodX] statement).
Answer: The Obective-C language specifically decided that class objects should respond to the instance methods of their root class. This is primarily a pragmatic decision; since NSObject is mostly responsible for handling the fundamentals of how ObjC interacts with objects, it would be annoying to have to implement everything twice; once for class objects and once for instances. Class objects can be put into arrays, etc. so they need to respond to -retain and -release just like instances do.
You can read more about it in the "Methods of the Root Class" section of this document: https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html


Minimal polynomial of complex numbers over field

Question:
Find the minimal polynomial of complex numbers over the given field
(i) $1+i$, over $\mathbb{Q}$

$[\mathbb{Q}(i):\mathbb{Q}]=2$, so $\deg(f)=2$.
$\alpha=1+i \rightarrow \alpha^2=2i $, so $f=x^2-2x+2$

(ii) $-3+ \sqrt{7}$ over $\mathbb{R}$

$[\mathbb{Q}(\sqrt 7):\mathbb{R}]=1$ so it's $f=x+3-\sqrt 7$

(iii) $\frac{1+ \sqrt{5} }{2}$ over $\mathbb{Q}$

$[\mathbb{Q}(\sqrt 5):\mathbb{Q}]=2$ so $f=x^2-\frac{1}{2}x-1$

(iv) $e^{ \frac{2\pi i}{5}}$ over $\mathbb{Q}$

I found polynomial $f=x^4+x^3+x^2+x+1$ but how to show that is minimal?

(v) $e^{ \frac{2\pi i}{5}}$ over $\mathbb{Q}( \sqrt{5})$
Answer: Hints:
(iv): Eisenstein on $f(x+1)$
(v): $2\cos\dfrac{2\pi}5=\dfrac{\sqrt5-1}2$
Comment: Item (iv) in particular has been handled many times on our site. For a general odd prime $p$, not just $p=5$. Item (v) is part of a general result telling that the unique quadratic subfield of $\Bbb{Q}(e^{2\pi i/p})$ is
$\Bbb{Q}(\sqrt{p^*})$, where $p^*=(-1)^{(p-1)/2}p$.


How do i get python to remove the row i search for from csv file

Question: I am able to edit and add new entries but everytime i try to delete the row i search for, it wipes the whole files data.
I need it to just remove that row of data without losing the rest of the rows.
    import csv,os,sys

def helper(file):
    o=csv.reader(open(file,"r"))
    for row in o:
        print row

def delete(filename):
    found=False
    f1=csv.reader(open(filename,'r'))
    f2=csv.writer(open("temp.csv",'a'))
    rid=raw_input("Enter name to find record:")
    for row in f1:
        if rid in row[0]:
            found=True
            f2.writerow()
            print rid, "has been deleted from the database!"
        else:
            found=False
    if found==False:
        print "That name isn't in our database!"
        z=raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
        if z=="1":
            delete(filename)
        if z=="2":
            import program
        if z=="3":
            exit

helping=raw_input("Do you require any help with using this feature?Type y for yes or just hit enter to continue:")
if helping=="y":
    helper('deletehelp.txt')

delete("custdet.csv")
os.remove("custdet.csv")
os.rename("temp.csv","custdet.csv")     #This is the file rename that I mentioned above.
restart=raw_input("Would you like to return to the main menu? Please type Y or just hit enter to exit:")
if restart=="y":
    import program
else: exit

Comment: maybe your f2.writerow() is supposed to be outside the if statement!!! And yes, its empty as well.
Comment: could you show me what you mean?
Comment: if you want to delete the row,that user enters, you surely dont want to write it to your new file! so it should be outside the __if__ block.
Answer: import csv,os,sys

def helper(file):
    o = csv.reader(open(file,"r"))
    for row in o:
        print row

def delete(filename):
    f1 = csv.reader(open(filename,'r'))
    f2 = csv.writer(open("temp.csv",'a'))
    rid = raw_input("Enter name to find record:")
    found = False
    for row in f1:
        if rid not in row[0]:
            f2.writerow(row)
        else:
            found = True
            print rid, "has been deleted from the database!"

    if found == False:
        print "That name isn't in our database!"
        z = raw_input("Please enter 1 to retry, 2 to return to log in, or 3 to close program:")
        if z == "1":
            delete(filename)
        if z == "2":
            import program
        if z == "3":
            exit

Answer: You never actually write to the new csv file.
Look at the main filter/copy loop:
# for every row in the input file
for row in f1:
        # Is this the/a record to delete?
        if rid in row[0]:
            # yes!
            found=True
            # then we do not write anything to the output file (???)
            f2.writerow()
            print rid, "has been deleted from the database!"
        # no else part, so no nothing gets done with
        # the input row `row` ...

So you'll end up with an empty output file ...
Answer: Change the section containing the for loop to this:
    for row in f1:
        if rid in row[0]:
            found=True
            print rid, "has been deleted from the database!"
        else:
            f2.writerow(row)

The changes:

Actually write the row if rid is not in row[0]
Don't reset the found flag to False

The rest of the code also needs some work:

Recursion is not the best way to handle retries, use a loop instead.
import program to return to the login ????? That's not going to
work. Perhaps you should just return from the function.
There is coupling between delete() and the calling code which
relies on a file named temp.csv being created. It would be much
better if delete() performed the renaming of the temporary file itself.


Emails going to spam even though DKIM and SPF records set up and rDNS too in EC2. I am usinf postfix and dovecot

Question: I have set up my own email server in AWS using postfix and dovecot. I have also set up DKIP and SPF and DMARC records. Now the problem is when i send an email from firstname.lastname@example.com, its not flagged as spam in gmail. Infact, its automatically marked as important. Same with email@example.com. But, when I am sending it from any other address like firstname.lastname@example.com, its being flagged as spam. I'm totally confused as to why this is happening. I use roundcube webmail.
EDIT: i created a new gmail test account and in that test account,all the emails from my domain are going to spam regardless of email@example.com, firstname.lastname@example.com etc.
Here is my domain: arcadesite.io
Comment: Every AWS IP has a low reputation.
Comment: No because I have already added DKIM SPF and DMARC records. Its an AWS ellastic IP so it should not have a "low" reputation
Comment: How can I increase reputation of the IP ?because I have configured DKIM and SPF records.....so cannot do anything more I guess.Also, rDNS is configured on that ellasic IP
Comment: Best post your domain name / IP so people can check reputation and such for you. I have my web server hosted on EC2 but I use FastMail for email, because I don't want to have to spend the time managing and maintaining it.
Comment: Yes. Edited the post with my domain name
Comment: i would suggest to setup an vps outsite of aqs for 2eur/m as relay and dont have the pain for paying attention to any Reputation, for fast setup take a Look for mailcow, it needs 4gb RAM but its every bit worth
Comment: So will it solve my problem? And can i install mailcow alongside wordpress etc on a diff folder and using apache vhost?
Answer: Modern spam filters use different signals to classify an email. How exactly it is done differs by implementation, but in general the sender only has indirect control over many of those. Just because an email system is cleanly implemented, does not mean it won't be sending spam; using that as the only signal would defeat the purpose.

SPF and DKIM ensure that the email was emitted by the owning system, preventing spammers from abusing random addresses.
A valid rDNS suggests that you actually have some control over the IP you're sending from.
Then there are blacklists, which some systems, e.g. SpamAssassin, query to identify known bad senders.
Large email services often keep statistics on a sender through their own users feedback. If enough people hit the "spam button" on the first messages of a campaign, it's likely to end up in the spam folder for everyone else.
Some mail providers share IP reputation data with third party services, which in return provide a more detailed analysis of a sender.
Content analysis also plays a role. If an individual message contains questionable content (think Viagra), it may get classified as spam despite originating from a reputable sender.
Sending large amounts of mail to non-existing addresses, i.e. using dirty lists, is another hallmark of spammers and has a negative impact on reputation, too.

In a nutshell, being trusted by the major providers like GMail, Yahoo or MSN takes time and consistent sending of quality content that recipients actually want, and won't get flagged by users or content analysis.
If you use an address from a VPS hoster, where IPs are a dime a dozen and change ownership often, you'll start out with rather low trust. Use reputation and blacklist checks to ensure the IP doesn't already have a bad history. If it does, contact the list maintainers where possible, and explain that the IP is under new ownership. Most will allow a fresh start.
If you send bulk email, you can also participate in feedback loops to remove people who classify your messages as spam from your list, and as such avoid the associated penalties in the future.
Comment: besides all said above, you have issue with DMARC record (2 DMARC records) which need to fixed.  Check here ->  https://easydmarc.com/tools/dmarc/arcadesite.io  https://toolbox.googleapps.com/apps/dig/#TXT/_dmarc.arcadesite.io


Expected number of items looked at

Question: Currently failing at basic probability…
Given a sequence of items, linear search means looking at each in turn and seeing if it's the one we're looking for. (I.e. in the worst case, it's the last item in the sequence or not in the sequence at all and we'll have to look at all items to find it/determine it's not there.)

How many elements of the input sequence need to be checked on average, assuming that the element being searched for is equally likely to be any element in the array?

Ok, we know two things:

the element we're looking for is in the array
P[the i-th item is the one we're looking for] = $\frac{1}{n}$ for all $i\in\{1,..,n\}$

And I think I'm supposed to get $\frac{n+1}{2}$ or $\frac{n}{2}$ or something thereabout.
Let $X$ be the number of items the linear search algorithm is looking at.
$$\begin{align}
P[X=1] &= \frac{1}{n} \\
P[X=2] &= \left(1-\frac{1}{n}\right)\frac{1}{n} \\
P[X=3] &= \left(1-\frac{1}{n}\right)^2\frac{1}{n} \\
& \ \ \vdots \\
\end{align}$$
So
$$\begin{align}
\mathbb{E}(X) &= \sum_{i=1}^n i\left(1-\frac{1}{n}\right)^{i-1}\frac{1}{n} \\
&= \frac{1}{n}\sum_{i=1}^n i\left(1-\frac{1}{n}\right)^{i-1} \\
\end{align}$$
That's not something I want to solve myself, so I gave it to Wolfram Alpha and got
$$\left(1-2\left(\frac{n-1}{n}\right)^n\right)n$$
This doesn't look particularly close.
Where did I go wrong?
Comment: You say the location is uniform, thus the probability that it is in slot $i$ is $p_n=\frac 1n$ for all $i$, yes?  Thus the answer is $\sum i\times \frac 1n=\frac {n+1}2$.  This needs to be altered in a small way if you want to allow for the possibility that it isn;t in the list.  (in that case $p_n$ is greater than all the others and all the others are equal).
Comment: In case you assume $n = 2$ and you are sure that the element is in the array, then $P[X = 1] + P[X = 2] = 1$. But as per your (@User1291) calculation, it is $\dfrac{1}{2} + \dfrac{1}{4} \neq 1$. Hence you should reconsider the calculation of probability for each event.
Answer: Your calculations for $P(X=2), P(X=3)$, etc are incorrect.
For instance you should have, $P(X=2)=P(X=2\mid X\ne 1)\cdot P(X\ne 1)=\frac{1}{n-1}\cdot\frac{n-1}{n}=\frac1n$.
In fact as noted by others $P(X=k)=\frac1n$ for $k=1, 2,\cdots, n$.
Answer: Assuming that there is exactly one item of interest:
$$P[X=i]=\frac1n\text{ for }1\le i\le n$$
$$E[X]=\sum_{i=1}^n\frac in=\frac1n\sum_{i=1}^ni=\frac{n(n+1)}{2n}=\frac{n+1}2$$
If $P[X=i]=\left(1-\frac1n\right)^{i-1}\frac1n$ instead then there is a geometric distribution, which can be realised as (say) there are $n$ rolls of an $n$-sided die and we are searching for the first 1 rolled. Here there is an extra $\left(1-\frac1n\right)^n$ probability of doing $n$ comparisons and not finding the desired item, leading to the expectation in this case as
$$\left(1-2\left(\frac{n-1}n\right)^n+\left(1-\frac1n\right)^n\right)n$$
$$=\left(1-\left(1-\frac1n\right)^n\right)n$$
which is different from $\frac{n+1}2$ because the desired element may appear more than once in the array.
Comment: @ParclyTaxel What should be the statement  in order for his(of @user1291) reasoning to be correct?
Comment: @Magnusseen The calculations in the question body imply something like this: we have $n$ rolls of an $n$-sided die and are looking for the first 1 rolled. A geometric distribution.
Comment: @ParclyTaxel In his reasoning, he computed $P_k,$ the probability that the amount of search is exactly $k.$ That computation seems correct. If we assume that we will find the element in the array, we should have then $\sum_{k=1}^n P_k=1.$
Comment: @Magnusseen There, he makes the mistake. Not all assumptions in the question were used, in particular that there is exactly one item of interest.
Comment: Why is $P[X=i] = \frac{1}{n}$?
Comment: @User1291 Because the sought-after item has a $\frac1n$ chance of appearing at any given position in the list.
Comment: @User1291  You said "the element being searched for is equally likely to be any element of the array."
Comment: That's interesting ...
The way I saw it was every time the algorithm looks at an item, we have

P[done] = 1/n;

P[need to look at the next] = (1-1/n).

But I guess this fails to take into account that in the end, one of the n items WILL be the one we're looking for.
Comment: @ParclyTaxel Would you mind integrating what you just discussed with Magnusseen into your answer? It more clearly answers the question than "the expectation is like that".
Comment: @User1291 I think my edit should have done it.
Answer: This is a matter of conditionality.
In your calculation, you took $1/n$ to be the probability that the element is in the $i$th position under the condition that it was not in any of the positions before $n$.
If this were the case, then your calculation of the probabilities for $i\geq2$ would be correct.
Unfortunately though, the probabilities don't sum up to one.
Instead, the probability to find the element in the $i$th position is precisely $1/n$ for every $i\in\{1,\dots,n\}$.
The probabilities are given, and there is no need to find them.
The probabilities are unconditional; events for $i<j$ have no bearing on $P[X=j]$.
If you want, you can use this information to find the conditional probabilities.
They are not needed in this problem, but you will find that they are not $1/n$.
There is two alarming things in your calculations, hinting at a problem:

You assumed $P[X=2]=\frac1n$ and the calculated that $P[X=2]=(1-\frac1n)\frac1n$.
The probabilities don't sum up to one although they should.
Answer: If you wish to include the possibility that the desired object isn't in the array:
Denote by $\psi$ the probability that the desired object isn't in the array.  Let $p_i$ denote the probability that it is in slot $i$.  Then, since all the $p_i$ are equal, we must have $$\sum_{i=1}^np_i=1-\psi\implies p_i=\frac {1-\psi}n$$
For every $i<n$ the probability that you look at exactly $i$ objects in your search is $p_i$.  For $i=n$ the probability is $p_i+\psi$.  Thus in this case the expected value is $$\sum_{i=1}^n i\times \frac {1-\psi}n+n\times \psi=\frac {(n+1)(1-\psi)}2+n\psi=\frac {n+1+n\psi-\psi}2$$
Sanity checks:  Note that if $\psi=0$ this reduces to the formula we know. Then again, note that if $\psi =1 $ this reduces to $n$, as it should.
Answer: Let us assume that the key is present in the list. The expectations of the "cost" of finding the key equiprobably in every position $k$ are $\dfrac kn$, the sum of which is
$$\frac{n(n+1)}2\frac1n=\frac{n+1}2.$$
The correction for the possibility of the key being absent with probability $q=1-p$ yields
$$p\frac{n+1}2+qn.$$

Expected number of items looked at


do GWT widgets scale?

Question: On a Google IO Talk it was mentioned that widgets make your apps run slow and you should avoid them at all cost. But I would like to use the gwt-bootstrap widget library. This would pollute my ui.xml with a lot of widgets.
The reason I use this library and not the standard gwt bootstrap.js file, is because I don't want to include the library nor do I want to use the customize option of bootstrap. The reason would be the large initial download and the annoyance of having to be aware of possible missing features when added code to the UI.
So my questions are:
- Do the widgets slow down the app significantly?
- What number of widgets should be fine?
In the google IO talk they had a max of around 10, I don't remember well.
Answer:
Do the widgets slow down the app significantly?

It depends. It depends whether you make a mobile app, whether you care about old browsers (IE8, I'm looking at you), etc.

What number of widgets should be fine?

Widgets within a composite widget? widgets displayed at the same time on the screen? Widgets within the whole app?
We use tens of widgets and I don't think they slow us down (server side and moving data across the wire are what take most of the time, not the client side). But our lowest-level widgets, among the ones that we reuse the most, and sometimes a bit complex, aren't (all) composites, and use event delegation.
My rule of thumb is: if an Element is enough (such as a SpanElement to display some data, or an InputElement for a textbox where you don't care about events), then use it. If you need events, then use a widget. The exception to the rule is if you're building a reusable complex widget and using event delegation wouldn't add too much complexity to it compare to composing widgets.
Remember: premature optimization is the root of all evil, and the 3 rules of performance are measure, measure, measure.
BTW, your reasons for using gwt-bootstrap rather than bootstrap.js are misinformed: gwt-boostrap loads bootstrap.js like you could do it yourself, and thus won't save you from that large initial download.
Comment: That's too bad, I assumed gwt-bootstrap would have the same behaviour as gwtQuery.

do GWT widgets scale?


List nodes of children using taxonomy_select_nodes

Question: I want to list nodes from children terms using or editing taxonomy_select_nodes function.
Actually I added these few lines but I get an infinite loop or slow response:
function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'),$promote) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->condition('tid', $tid);
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');

      // This block of code is the custom code I added.
      //SELECT only promoted article
      if($promote==1){
        $query->join('node', 'no', 'no.nid = t.nid');
        $query->condition('promote', 1);
      }
      $taxonomies=array();
      $taxonomies = taxonomy_get_children($tid);
      $taxonomies[]=$tid;
      $query->condition('t.tid', $taxonomies,'IN');

  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

Comment: Can you post all of your code instead of just that one part. We can't tell what the problem is with only part of the code. For example, you have a */ to end a comment but the comment isn't started anywhere and there is no start to or execution of the $query.
Comment: I put the full function
Answer: I would say these are your problems:
taxonomy_get_children() returns term objects, not term IDs, so that is going to break that query. This I would say is your main issue. Instead you could do this:
  $taxonomies = array();
  $taxonomies = taxonomy_get_children($tid);
  // Get the child term tids.
  $taxonomies = array_keys($taxonomies);
  // Add the parent tid.
  $taxonomies[] = $tid;
  $query->condition('t.tid', $taxonomies,'IN');

Your IN statement with the children won't work currently because earlier in the function is this line:
$query->condition('tid', $tid);

So that will only ever return values for $tid, never for the children unless you remove that line also.
Also I would recommend giving the new $promote parameter a default value, like this:
function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'), $promote = 0) {


character image thinning

Question: im doing an ocr application . im confusing that how to do skew an image like this :

Second ,i have a character image with many font size. the problem is :  how to thin them to the same size like this

Answer: For your first point: find the angle by which the text is rotated, and rotate your image by that angle. In your sample you can do this by finding the angles of the lines between the large black patches on the edges and the white areas. Look into edge detection and hough transform to help you find the lines, and then help you find their angle. OpenCV has a good implementation of both algorithms.
For your second point: that is the morphological operation binary skeleton in action.
Answer: you can use the following code for detecting and correcting skew but i need your help if you get any thinning algorithms...asume the input image is on the picture box....
<code>        try
        {
            //Check if there exists an image on the picture box
            if (pictureBox1.Image == null)
            {
                MessageBox.Show("Please load an image first.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                uploadImageToolStripMenuItem.PerformClick();
                return;
            }
            Bitmap image = new Bitmap(pictureBox1.Image);
            BitmapData imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                    ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
            //document image skew detection starts here
            DocumentSkewChecker skewChecker = new DocumentSkewChecker();
            // get documents skew angle
            double angle = skewChecker.GetSkewAngle(imageData);
            // create rotation filter and rotate image applying the filter
            RotateBilinear rotationFilter = new RotateBilinear(-angle);
            rotationFilter.FillColor = Color.White;
            image.UnlockBits(imageData);
            //if the angle is more 90 or 180, consider it as a normal image or if it is not, perform a skew correction
            if (-angle == 90 || -angle == 180)
            {
                pictureBox1.Image = image;
                pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                return;
            }

            //Bitmap rotatedImage = rotationFilter.Apply();
            //draw a bitmap based on the skew angle...
            Bitmap returnBitmap = new Bitmap(image.Width, image.Height);
            Graphics g = Graphics.FromImage(returnBitmap);
            g.TranslateTransform((float)image.Width / 2, (float)image.Height / 2);
            g.RotateTransform(((float)angle));
            g.TranslateTransform(-(float)image.Width / 2, -(float)image.Height / 2);
            g.DrawImage(image, new Point(0, 0));

            pictureBox1.Image = returnBitmap;
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }
</code>

character image thinning


Android: background processing beside an active/sleeping activity + controlling that via start / stop

Question: What is the best alternative for running a task repeatedly even when the App is not active? The task should stop when the App has readlly exited.
1 - Besides my App I would like to perform a task that is executed whether my App is visible or paused / sleeping. So after some kind of event or time interval (for simplicity) the task is executed repeatedly.
2 - AND ... the App, when active, should be able to start/stop the task executed.
First option is using a Local Service.
public void enableTheTaskToBeRepeatedEach10seconds() {
    enableTask = true;
}
public void disableTheTaskToBeRepeatedEach10seconds() {
    enableTask = fasel;
}

Local Service
public void onCreate() {
    readthread = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep( 2000);
                if( enableTask ) {
                    System.out.println( "+++++ DO task - here update counter ++++");
                    counter++;
                } else {
                    System.out.println( "+++++ SKIP task - here update counter ++++");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } });
    readthread.start();
}

Option 2: I see the BackgroundTask. I could create a Thread in it like the one above. Can I interact with the background task to start/stop?
Are there better options?
Comment: Why not use a regular Service?
Comment: What is the advantage of a regular service over a local service?

Communication from the Activity to the (local) service is easier.
ANother advantage is that exiting the App will stop the service. In this case that is what I like.
Answer: Since 2 weeks I have a good working Local Service. This is the rigth solution for me.
When necessary I can stop it, so no battery energy is drained.


Instalador com autoscoll

Question: Bom dia.
Estou criando um atualizador e preciso que fazer com que a cada $rs executado o scroll vá para baixo.
O que acontece atualmente?
Fica uma tela branca, mas executando, e quando acaba mostra tudo de uma vez.
O que gostaria:
Que foce executado cada $rs, mostrando seu echo e o scoll descendo automaticamente quando houver muitas linhas.
Meu código atual

 Aguarde, atualizando banco de dados, não feche

<?php
include("../conexao/conexao.php");

    $rs1 = $mysqli->query("UPDATE ...;");
    if (!$rs1) {echo " - Versão do site
";}else {echo " - Versão do site. Sucesso!
";}
    sleep(2);

    $rs2 = $mysqli->query("INSERT .... ;");
    if (!$rs2) {echo " - Insert erro
";}else {echo " - Insert sucesso!
";}
    sleep(2);

    .
    .
    .

    unlink("updateSQL_v423.php");
?>

 Pronto! Banco de dados atualizado. APERTE F5, para recarregar a tela.

Comment: O php só mostra o resultado final, ou seja, todos os textos apareceriam no final... O que pode ser feito é você fazer um jquer chamar um de cada vez e mostrar os resultados conforme forem sendo terminados, ai daria para fazer
Comment: @adventistaam como fazer para o jquery chamar um de cada vez?
Comment: você faz um backend em php, e na página chamaria com o jquery chamar as respectivas ações
Comment: @adventistaam Teoria estou ciente, mas na pratica, como fazer? ..rsrs
Comment: Você terá que trabalhar com ajax... pode fazer um exemplo para você ter uma ideia
Comment: Vai ajudar a ter um norte
Answer: Você pode fazer um backend em php ter esse retorno,  já que o PHP retorna só quando está tudo pronto..
Segue a sugestão:

var retorno = $('.retorno')
$('[botao]').on('click', function(){
     const aguarde = $('
Aguarde enquanto processamos seu pedido ...
')
     retorno.append( aguarde )
     setTimeout(()=>{
        update()
     },500)

})

function update(){
     const update = $('
- Versão do site
')
     retorno.append( update )
     setTimeout(()=>{
       insert()
     }, 1500)

}

function insert(){
     const update = $('
- Insert erro
')
     retorno.append( update )
     setTimeout(()=>{
       done()
     }, 1500)

}

function done(){
     const update = $('
 Pronto! Banco de dados atualizado. APERTE F5, para recarregar a tela
')
     retorno.append( update )
}

  <button botao>Clique</button>

Funções javascript:
No caso função update seria assim:
function update(){
   $.ajax({
      url: 'seuArquivo.php',
      type: 'post',
      dataType: 'json',
      data: {
        id: 1,
        nome: 'Sei la',
        opcao: 'update'
      }
   }).done( result => {
       const update = $('
'+ result.msg +'
')
       retorno.append( update )
       inserir()
   })
}

function inserir(){
   $.ajax({
      url: 'seuArquivo.php',
      type: 'post',
      dataType: 'json',
      data: {
        nome: 'Dado a inserir',
        opcao: 'inserir'
      }
   }).done( result => {
       const insert = $('
'+ result.version +'
')
       retorno.append( insert )

       const done = $('
 Pronto! Banco de dados atualizado. APERTE F5, para recarregar a tela
')
        retorno.append( done )
   })
}

No php seuArqui.php
$_opcao = $_POST['opcao']

switch($_opcao){
  case 'update':
      //Faça suas operações e retorne com echo json_encode
      $version = array('version' => '- Versão do site')
      echo json_encode( $version )
  break;
  case 'inserir':
     //Faça suas operações e retorne com echo json_encode
      $version = array('version' => 'Inserir result')
      echo json_encode( $version );
   break;
}

Então, essa é a sugestão.

Instalador com autoscoll


Is this proof of uncountability of Cantor set true?

Question: To construct Cantor set $C$, start with $I_1=[0,1]$ and define $$E_1=\{0,1\}=\{x:x\text{ is an  end point of the set }I_1\}.$$ $\operatorname{card}(E)=\#(E)=2$. After deleting the middle open interval $\big(\frac{1}{3},\frac{2}{3}\big)$ we get $I_2=\big[0,\frac{1}{3}\big]\cup\big[\frac{2}{3},1\big]$ and $$E_2=\big\{0,\tfrac{1}{3},\tfrac{2}{3},1\big\}=\{x:x\text{ is an end point of the intervals, consisting remainder set }I_2\}$$ so $\#(E_2)=4=2^2$. Continue in this fashion. The set $I_n$ consists of $2^{n-1}$ intervals so $\#(E_n)=2^n$. Note that if $x$ is an end point of one the intervals in $I_k$ for some $k$ then $x\in C$. Thus $E_k\subset C$ for all $k$ and this implies $E=\cup_{k=1}^\infty E_k\subseteq C$. (I am not sure if $E=C$. The first question is whether or not the two sets are same.)  $\#(E_k)=2^k\leq \#(E)$ for all $k$ so can we deduce that $2^{\aleph_0}\leq\#(E)$?
I searched the proofs for the uncountability of the Cantor set but most of them uses ternary expansion. If this proof is true and if there is a reference for this proof, please give the reference. Thanks for advance.
Answer: No, I'm afraid that this argument doesn't work. It's true that $\#(E_n)=2^n$ for each $n$, and it's true that $E\subseteq C$. However, $E$ is the union of countably many finite sets, so $E$ is only countable: all you've shown is that $C$ is infinite. And no, $E$ is not all of $C$. As a matter of fact, $E$ consists of those numbers in $[0,1]$ having terminating ternary (base three) expansions using only the digits $0$ and $2$, while $C$ consists of those numbers in $[0,1]$ having arbitrary ternary expansions using only $0$ and $2$. For example,
$${0.02020202\ldots}_{\text{three}}=\sum_{n\ge 1}\frac2{3^{2n}}=\frac{2/9}{1-1/9}=\frac14\in C\setminus E\;.$$
Answer: No, the number of disjoint intervals, hence also their endpoints, is countable.


How to call a Bootstrap pop-up Model from JS function?

Question: I want to call a bootstrap Pop-Up Model from JS function with the values which are in my Function if the user press update then back to JS function and update the values if press cancels then nothing.
@using (Html.BeginForm("BulkUpdate", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

                @Html.DisplayNameFor(m => m.First().Id)
                @Html.DisplayNameFor(m => m.First().TagName)
                @Html.DisplayNameFor(m => m.First().TagCategory)
                @Html.DisplayNameFor(m => m.First().TagValue)
                 Action

            @for (int i = 0; i < Model.Count(); i++)
            {

                        @Html.DisplayFor(m => Model[i].Id)
                        @Html.HiddenFor(m => Model[i].Id)

                        @Html.DisplayFor(m => Model[i].TagName)

                        @Html.DisplayFor(m => Model[i].TagCategory)

                        @Html.EditorFor(m => Model[i].TagValue, new { htmlAttributes = new { @id = "TagVaule_" + Model[i].Id, @class = "form-control" } })

                        <button type="button" class="btn btn-secondary" onclick="UpdateRow(@Model[i].Id)">Update</button>

            }

                <button onclick="Cancel()">cancel</button>
                <button onclick="Confirm()">confirm</button>

            <input type="submit" value="Bulk Update" class="btn btn-secondary" />

}
@section Scripts{

}

Currently I using built in confirm function but istead of this confirm function i want to call bootstrap model and want to show tagvalue  and the old value against that tagvalue on pop-up model then if user press update i want to submit it.
Thanks
Answer: One way to do this is to just do what needs to be done when confirm is clicked on the modal
javascript:
var bootStrapId=0;
var tagvalue = 0
function UpdateRow(id)
{
    tagvalue=$("#TagVaule_" + id).val();
    bootStrapId=id;
    DisplayModal();
}

function DisplayModal()
{
    $("#myModal").modal('show')
}

function Cancel()
{
    $("#myModal").modal('hide')
}

function Confirm()
{
    $.ajax({
        type: "POST",
        url: '@Url.Action("Update","Home")',
        data: {
            id: bootStrapID,
            value: tagvalue
        },
    });
    $("#myModal").modal('hide')
}

html:

        <button onclick="Cancel()">cancel</button>
        <button onclick="Confirm()">confirm</button>

Comment: it works fine here.... https://www.w3schools.com/code/tryit.asp?filename=GA4LYUC22UY8
Comment: Hi sir, tried your code but nothing is happing and there is no error in console as well can you please help me more? And I am updating the code in question
Comment: I tried but UpdateRow() click model is not visible?


Observable.FromEventPattern on ObservableCollection

Question: I have a ClassWrapper class and a BaseClassWrapper class. The BaseClassWrapper has an object of type ClassDTO and inside it has an ObservableCollection that is what I want to "observe". When I create an object of type "ClassWrapper" and add an item to the collection ClassWrapper.ClassDTO.MyCollection.Add(new OtherClass()) the observer does not work.
But if I create ClassDTO or an ObservableCollection inside ClassWrapper (not in BaseWrapper) it works perfectly. Why does this happen?
public class ClassWrapper : BaseClassWrapper
{
    public ClassWrapper()
    {
        Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>
                (x => ClassDTO.MyCollection.CollectionChanged += x, x => ClassDTO.MyCollection.CollectionChanged -= x)
            .Where(x => x.EventArgs.Action == NotifyCollectionChangedAction.Add ||
                        x.EventArgs.Action == NotifyCollectionChangedAction.Replace ||
                        x.EventArgs.Action == NotifyCollectionChangedAction.Remove)
            .Throttle(TimeSpan.FromMilliseconds(250))
            .Subscribe(x =>
            {
                RaisePropertyChanged(SomeProperty);
            });
    }
}

public abstract class BaseClassWrapper : ObservableObject // MVVM Light
{
    public ClassDTO ClassDTO { get; set; } = new ClassDTO();
}

public class ClassDTO
{
    public ObservableCollection<OtherClass> MyCollection { get; set; } = new ObservableCollection<OtherClass>();
}

Comment: First, how did you test this? Second, check [this question](https://stackoverflow.com/questions/7260746/using-rx-reactive-extensions-to-watch-for-specific-item-in-observablecollectio) and the quote `The generic ObservableCollection has nothing to do with the IObservable interface`
Comment: If you load multiple items at once you could use a plain-old or array list and raise the notification event when setting that list. If your UI can add items one at a time, you could raise the notification right where the change happens, eg at the top ViewModel, in response to whatever command triggered the change. Otherwise it's a good idea to use `ReactiveUI`
Comment: 1) I create a ClassWrapper object, I add it to an observablecollection that is binded to the view. Then I access that object with var obj = ObservableCollection.FirstOrDefault () and then obj.ClassDTO.MyCollection.Add (...). That does not work (if ClassDTO is in BaseClassWrapper) but if I do this obj.MyCollection.Add (...) or if I add ClassDTO to ClassWrapper, if it works.
2) The generic ObservableCollection has nothing to do with the IObservable interface Exactly, that's why I use Observable from System.Reactive
Comment: But how do you *test* it? How do you add items? When I tried a timer that adds an item every 100ms I found that Throttle didn't behave the way I thought it would. It won't fire if events keep coming inside a 250ms window
Comment: What do you want to do in any case? *Prevent* events until there's a 250 ms lull, or fire if there's an event once every 250 ms?
Comment: What I need is that if I add 1 or 1000 objects at the same time, the properties are updated 250 ms after the last one was added
Comment: Then I can't repro this. I *do* get a single event 250ms after the *last* item is added. That's why I ask how this is tested. *If* you load all items at once though, or if you don't mind rendering all items again, the code would be a lot simpler if you raised the event just once for the entire collection, the same as if a new list was assigned to the property
Comment: I do not get any event. I added a breakpoint inside Throttle and never enter.
Comment: Post your test code. How do you *add* items? `Throttle(TimeSpan.From(..))` will only be called once when the pipeline gets constructed. It's the subscriber callback that should be called after 250ms
Comment: It's very strange that you do not work for me.
public ObservableCollection MyBindingList { get; set; } = new ObservableCollection();

private void UpdateList() {

 MyBindingList.FirstOrDefault().ClassDTO.MyCollection.Add(new OtherClass());

}

I call UpdateList many times from a button in the UI. Later I could create a functional example
Comment: Hi @PanagiotisKanavos I found the error, in your code try this
var c = new ClassWrapper {
      ClassDTO = new ClassDTO() // ofcourse, I need create ClassDTO with custom properties
};
When I do that, the observer "breaks". The problem is that I do not know why it happens
Comment: that's because the property assignment occurs *after* construction has finished. The object initialization syntax calls the default constructor first and only then assings properties to the already constructed object.
Answer: I tried the code and added a new item every 100ms and was ... perplexed to say the least until I accidentally hovered over Throttle and saw :

Ignores elements from an observable sequence which are followed by another element within a specified relative time duration.

I suspect, like me, you expected Throttle() to return the last item in a window. Even though its description in ReactiveX.io is

only emit an item from an Observable if a particular timespan has passed without it emitting another item

And the documentation remarks say :

For streams that never have gaps larger than or equal to dueTime between elements, the resulting stream won't produce any elements.

In fact, I've used it this way in the past, but somehow I trip over the name each time until I remember that the actual operation is debouncing, not throttling.
When I slowed the timer to fire eg every 300 ms I started getting results.
The operator that returns the last event in a window is Sample, not Throttle. If that's what you want, you should use
.Sample( TimeSpan.FromMilliseconds(300))

instead of Throttle.
Use Throttle if you want to update the UI only after notifications stop coming for 250 ms
Update
To test this behaviour I created a console application. I added a couple of fixes to the question's code to allow it to compile :
public class ClassWrapper : BaseClassWrapper
{
    public string SomeProperty { get; set; }
    public ClassWrapper()
    {
        Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>
                (x => ClassDTO.MyCollection.CollectionChanged += x, x => ClassDTO.MyCollection.CollectionChanged -= x)
            .Where(x => x.EventArgs.Action == NotifyCollectionChangedAction.Add ||
                        x.EventArgs.Action == NotifyCollectionChangedAction.Replace ||
                        x.EventArgs.Action == NotifyCollectionChangedAction.Remove)
            .Throttle( TimeSpan.FromMilliseconds(250))
            .Subscribe(x =>
            {
                RaisePropertyChanged( ()=> SomeProperty);
            });
    }
}

The application's Main method adds an item every 100ms. 250ms after the last item is added, a single notification event is raised and a message gets printed:
static async Task Main(string[] args)
{
    Console.WriteLine("Started");
    var c = new ClassWrapper();
    c.PropertyChanged += (sender, e) =>
    {
        Console.WriteLine($"Collection has {c.ClassDTO.MyCollection.Count} items");
    };

    for (int i = 0; i < 100; i++)
    {
        c.ClassDTO.MyCollection.Add(new OtherClass());
        await Task.Delay(100);

    }

    Console.ReadKey();
}


Vector Reflection Matrix over line

Question: I need to find a matrix that reflects vectors over any line y= mx + b. Furthermore, I need to be able to find the components of both of these vectors.
Thanks!
Comment: In general, you can't express reflection about an arbitrary line as a $2\times2$ matrix because translations can't be expressed in them. It is possible with homogeneous coordinates, however, in which case the transformation can be represented by a $3\times3$ matrix.
Answer: Here are two approaches to solving this:

Method 1: Find the equation of the line through a point $P$ that's perpendicular to the given line, then find the distance from $P$ to the given line. $P$'s reflection will be twice that distance along the perpendicular.
The perpendicular line through the point $(x_0,y_0)$ is described by the parametric equations $$\begin{align}x&=x_0-mt \\ y&=y_0+t.\end{align}$$ Substitute into the equation of the given line and solve for $t$:$$
y_0 + t = m(x_0 - mt) + b \\
t = {mx_0-y_0+b \over m^2+1}
$$ and then substitute $2t$ into the parametric equations: $$\begin{align}
x' &= x_0+2m{mx_0-y_0+b \over m^2+1} = -{m^2-1 \over m^2+1} x_0 + {2m \over m^2+1} y_0 - {m \over m^2+1}2b\\
y' &= y_0+2{mx_0-y_0+b \over m^2+1} = {2m \over m^2+1} x_0+{m^2-1 \over m^2+1} y_0+{1 \over m^2+1}2b.
\end{align}$$ The constant terms mean that this transformation can't be represented by a $2\times2$ matrix, but if we use homogeneous coordinates, representing the point $(x,y)$ by the vector $\langle x, y, 1\rangle^T$, we can represent the transformation by the matrix $$
M = \pmatrix{-{m^2-1 \over m^2+1} & {2m \over m^2+1} & -{2mb \over m^2+1} \\
{2m \over m^2+1} & {m^2-1 \over m^2+1} & {2b \over m^2+1} \\
0 & 0 & 1}.
$$

Method 2: Solve a simple case and generalize it by applying suitable transformations.
Reflecting about the $x$-axis is easy—you just negate the $y$-coordinate. Call that transformation $M_x$. If we can find a rigid motion that takes the line $y=mx+b$ onto the $x$-axis, then we simply apply that, reflect, and then move the line back to where it belongs. Translating the line so that it passes through the origin is easy, too: just subtract $b$ from the $y$-coordinate. Call that transformation $T_{-b}$. To get the line to coincide with the $x$-axis, it now needs to be rotated. Using the usual convention for angles, this can be done by rotating clockwise through an angle of $\theta$, where $\tan\theta=m$, that is, rotating through an angle of $-\theta$. We'll call that transformation $R_{-\theta}$. Putting it all together, we get $$
M = \left(R_{-\theta}T_{-b}\right)^{-1}M_x\left(R_{-\theta}T_{-b}\right) = T_bR_\theta M_xR_{-\theta}T_{-b}.
$$ Again, because of those translations, this can't be represented as a $2\times2$ matrix, so we'll need to use homogeneous coordinates, in which a translation matrix is of the form $$\pmatrix{1&0&\Delta x\\0&1&\Delta y\\0&0&1}.$$ The matrix for $M_x$ is just the identity with a $-1$ in the second diagonal entry. The rotation matrices take a bit more work, since we don't actually have the angle $\theta$, but we don't need it. We need its sine and cosine, which we can get from the slope of the line: $$\begin{align}
\sin\theta &= {\Delta y\over\sqrt{\Delta x^2+ \Delta y^2}}={m\Delta x\over\sqrt{\Delta x^2+m^2\Delta x^2}}={m\over\sqrt{1+m^2}}.
\end{align}$$ A similar calculation produces $\cos\theta=1/\sqrt{1+m^2}$. This gives $$
R_\theta = \pmatrix{{1\over\sqrt{1+m^2}} & -{m\over\sqrt{1+m^2}} & 0 \\
{m\over\sqrt{1+m^2}} & {1\over\sqrt{1+m^2}} & 0 \\
0 & 0 & 1},
$$ and $R_{-\theta}$ is this matrix with the signs of the off-diagonal elements flipped. Putting it all together, we have $$
\pmatrix{1&0&0\\0&1&b\\0&0&1} \pmatrix{{1\over\sqrt{1+m^2}} & -{m\over\sqrt{1+m^2}} & 0 \\
{m\over\sqrt{1+m^2}} & {1\over\sqrt{1+m^2}} & 0 \\
0 & 0 & 1} \pmatrix{1&0&0\\0&-1&0\\0&0&1} \pmatrix{{1\over\sqrt{1+m^2}} & {m\over\sqrt{1+m^2}} & 0 \\
{-m\over\sqrt{1+m^2}} & {1\over\sqrt{1+m^2}} & 0 \\
0 & 0 & 1} \pmatrix{1&0&0\\0&1&-b\\0&0&1}.
$$ This isn't as bad as it looks. All of those zeros and ones make the multiplications fairly simple. Once you multiply it all out, you get the same matrix as you did with method 1. It's not too hard to check that the determinant of this matrix is $-1$, which is what we expect for a reflection.

Vector Reflection Matrix over line


TypeError is Null?

Question: This is an error in Firebug I keep seeing.
TypeError: $("#gallery-nav-button") is null
 [Break On This Error]
$('#gallery-nav-button').addClass('animated fadeOutRightBig');

Here is my code:
JS
$(function() {
  $("#close-gallery-nav-button").click(function() {
    $('#gallery-nav-button').addClass('animated fadeOutRightBig');
   });
});

HTML

X

Click Here for Gallery
 Navigation Instructions.

CSS
#close-gallery-nav-button{
  text-indent:-9999px;
  width:20px;
  height:20px;
  position:absolute;
  top:-20px;
  background:url(/images/controls.png) no-repeat 0 0;
}
#close-gallery-nav-button{background-position:-50px 0px; right:0;}
#close-gallery-nav-button:hover{background-position:-50px -25px;}

Comment: Sounds like a jQuery problem. What version are you using? Are you sure jQuery is loaded?
Comment: @alexandernst - I am using 1.8.2 and yes it is loaded.
Answer: I also want to add - because this is the #1 Google search result for the important error message "TypeError: [x] is null" - that the most common reason a JavaScript developer will get this is that they are trying to assign an event handler to a DOM element, but the DOM element hasn't been created yet.
Code is basically run from top to bottom. Most devs put their JavaScript in the head of their HTML file.  The browser has received the HTML, CSS and JavaScript from the server; is "executing"/rendering the Web page; and is executing the JavaScript, but it hasn't gotten further down the HTML file to "execute"/render the HTML.
To handle this, you need to introduce a delay before your JavaScript is executed, like putting it inside a function that isn't called until the browser has "executed" all of the HTML and fires the event "DOM ready."
With raw JavaScript, use window.onload:
window.onload=function() {
   /*your code here*
   /*var date = document.getElementById("date");
   /*alert(date);
}

With jQuery, use document ready:
$(document).ready(function() {
   /*your code here*
   /*var date = document.getElementById("date");
   /*alert(date);
});

This way, your JavaScript won't run until the browser has built the DOM, the HTML element exists (not null :-)  ) and your JavaScript can find it and attach an event handler to it.
Answer: I have several scripts running on this page and evidently one script was conflicting with another. To solve my issue I added jQuery.noConflict();
var $j = jQuery.noConflict();
$j(function() {
  $j("#close-gallery-nav-button").click(function() {
    $j('#gallery-nav-button').addClass('animated fadeOutRightBig');
   });
});

Comment: You can also put your jquery codes within `(function($){//...})(jQuery)`
Comment: Rather the other way round: `jQuery(function($){…})`
Answer: As additional comment on #1 solution:
Another possibility for loading the script after finishing/building the HTML should be placing a defer parameter inside the script tag:

Answer: I agree with the advice given above, relating to the onload event. https://stackoverflow.com/a/18470043/2115934
A more simple solution (though not necessarily a better one) is to put your script tag just before the closing body tag of the document.
<!doctype html>

<meta charset="UTF-8">
<title>Document</title>

Answer: I know this has been answered and it is an old post but wanted to share my experience. I was having the hardest time getting my code to load and was getting this error constantly. I had my javascript external page loading in the head section. Once I moved it to just before the body ended the function fired up right away.
Comment: This should be a comment, not an answer.

TypeError is Null?