text:
Q: CodeIgniter -> php spark serve Not Working I have just created a new project with CodeIgniter.
I tried to run this command to run the server:
php spark serve

But it is giving me this error:
PHP Warning:  require(/mnt/e/dev/learning/php/codeigniter/001/app/Config/../../vendor/codeigniter4/framework/system/bootstrap.php): failed to open stream: No such file or directory in /mnt/e/dev/learning/php/codeigniter/001/spark on line 44
PHP Fatal error:  require(): Failed opening required '/mnt/e/dev/learning/php/codeigniter/001/app/Config/../../vendor/codeigniter4/framework/system/bootstrap.php' (include_path='.:/usr/share/php') in /mnt/e/dev/learning/php/codeigniter/001/spark on line 44

How can I run this command

A: PHP version 7.2 or newer is required, with the intl extension and mbstring extension installed.
The following PHP extensions should be enabled on your server: php-json, php-mysqlnd, php-xml
And then follow below steps to install and run CI 4 project:

*

*composer create-project codeigniter4/appstarter project-root

*composer clearcache

*composer update

*Config Setting:baseUrl in app/Config/App.php and DB info in app/Config/Database.php

*php spark serve
Note: clear composer cache before updating composer. For detail info follow CI documentation

A: In my case I tried to upgrade my CI setup, and all files I didn't adapt I thought I could easily copy them to retrieve the latest file. Like: cp vendor/codeigniter4/framework/app/Config/Constants.php ./app/Config/
However, I did the same for the app/Config/Paths.php file, but that resulted in your error message as well.
Bottom-line: don't try to replace the Paths.php file from upstream. And the $systemDirectory variable in Paths.php should look like this:
public $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';


text:
Q: Validation expression in asp.net How to disallow use of double quotes " in a textbox

A: Use String.Contains()
Since you can never control what users do the client you might as well just check it on the server, so you would probably use code something like:
if (textBox1.Text.Contains("\""))
{
Response.Write("Dey aint no way I'm letting you type that!");
}

A: use RegularExpressionValidator and set the ValidationExpression='^[^\"]*$', that will allow anything, including empty, other than "

A: If you don't want users to be able to type quotes in the textbox in the first place, consider using a FilteredTextBox from the AJAX Control Toolkit.

A: Use the RegularExpressionValidator for your page input validation. The .NET validation controls will verify your users' input on both sides, the client-side, and the server-side which is important if the user has disabled JavaScript. This article might also help you to implement the validation of your ASP.NET server controls.
Please don't do this just with JavaScript or AJAX. Always perform a server-side input validation! Especially if you are writing the users' input back into a database (SQL Injections).

A: You haven't specified if you're using webforms or MVC, so I'm gonna throw a couple things a'cha.
First off, here's the Regex you'll use in either situation.  ^[^\"]*$
First for WebForms
<asp:TextBox runat="server" id="TextBox1" />
<asp:RegularExpressionValidator runat="server" id="Regex1" controltovalidate="TextBox1" validationexpression="^[^\"]*$" errormessage="Nope!" />
<!-- This will give you client AND server side validation capabilities-->

To ensure you're valid on the SERVER SIDE, you add this to your form submit method
If Page.IsValid Then
    ''# submit the form
Else
    ''# your form was not entered properly.
    ''# Even if the user disables Javascript, we're gonna catch them here
End If

In MVC you should definitely use DataAnnotations on your ViewModel
NOTE: DataAnnotations can also be use for WebForms if you're planning on doing a lot of repeat ctrl + C and ctrl + V
''# fix SO code coloring
''# this is in the view model
<RegularExpression("^[^\"]*$", ErrorMessage:="Nope")>
Public Property TextBox1 As String ''# don't actually call it TextBox1 of course

And in your controller "Post" action, you wanna add the following
If ModelState.IsValid Then
    ''# submit the form
Else
    ''# your form was not entered properly.
    ''# Even if the user disables Javascript, we're gonna catch them here
End If

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to install private repo using glide golang I am using glide as package management for my golang project. I can't able to get private repositories using glide get bezos.gitlab.com/gomock.
It asks username & password even i give correct credentials, it ended up throwing error. Please suggest any idea.

A: It is nothing do with glide or any other package management tools. You have to set create and set gitlab access token in your git http.extraheader.
Go to your gitlab settings -> access token and create new access token, make sure to copy the token it available only once.
Then set these git global variables, now you can install private repositories using glide, go get, godep, etc.

git config --global http.extraheader "PRIVATE-TOKEN: YOUR_ACCESS_TOKEN"
git config --global url."git@bezos.gitlab.com:".insteadOf "https://bezos.gitlab.com/"


text:
Q: How to calculate sum from in Spring Boot JPA repository I'm working on a Spring Boot application and I have encountered the following challenge when trying to find the SUM. I have tried using JPQL and JPA syntax, but I'm still getting a null pointer exception.
@Getter
@Setter
@NoArgsConstructor
@Entity
public class ReportData extends Auditable {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long reportId;
    private Integer tests;
}

@Repository
public interface reportRepository  extends JpaRepository <ReportData, Long>  {
// or "SELECT SUM(m.tests) FROM ReportData m"
  @Query(value = "SELECT SUM(tests) FROM ReportData", nativeQuery = true)
  int totalTest ();
}

@GetMapping(value = "/reports")
public String statisticsPage (Model model){
   model.addAttribute("tests", reportRepository.totalTest());
   return ("statistics");
}

The error I get is:

A: Please note that the error you are getting is not in your query. That NullPointerExceptions is being thrown because the repository is null. Please, share all the code of your controller or ensure you are properly injecting/declaring the repository.
The problem with the query is in your repository interface.
@Repository
public interface reportRepository  extends JpaRepository <ReportData, Long>  {
// or "SELECT SUM(m.tests) FROM ReportData m"
  @Query(value = "SELECT SUM(tests) FROM ReportData", nativeQuery = true)
  int totalTest ();
}

With this syntax in the @Query annotation, you are using JPQL, not SQL. While JPQL is a representation of SQL, they are not the same. Thus, the usage of the nativeQuery flag is unnecesary. If you want to use a native SQL query, then you should do something like
@Query(value = "SELECT SUM(m.tests) FROM report_data m", nativeQuery = true)
  int totalTest ();

Please, change tests and report_data to their respective field and table in your database. You could also use the query you already have, just remove the nativeQuery attribute. Also note that the usage of native queries prevents your code to work with any other database. In other words, you will need to rewrite your queries if you ever change from MySQL to Oracle (for example).


text:
Q: Restore String Interpolation AFTER value replace Given a str: "My name is Gustavo", that was created with "My name is \(foo.name)"
Is it possible to get the string "My name is \(foo.name)" after the value was replaced?

In other words, is it possible to find out "My name is \(foo.name)", having "My name is Gustavo"?

Edit: If I can get to "My name is ", a.k.a. the hard coded string from all strings that were build dynamically, that would be a solution.

A: No, this is not possible. In fact, "My name is \(foo.name)" is not even included in the compiled code. Instead, Swift-5 compiler generates code equivalent to this:
let str = String(stringInterpolation: {
    var temp = String.StringInterpolation(literalCapacity: 11, interpolationCount: 1)
    temp.appendLiteral("My name is ")
    temp.appendInterpolation(foo.name)
    return temp
}())

This article contains details on how string interpolation is implemented in Swift-4 and Swift-5.


text:
Q: How to transform the table in R? here is my data.txt:
country   attitude   count
china   a   52
china   b   58
china   c   25
china   d   12
china   e   3
china   f   1
france  a   35
france  b   48
france  c   40
france  d   21
france  e   9
france  f   2
india   a   96
india   b   28
india   c   13
india   d   7
india   e   10
india   f   0
england a   21
england b   41
england c   50
england d   23
england e   18
england f   3
usa         a   31
usa         b   48
usa         c   45
usa         d   19
usa         e   10
usa         f   3

I want to get the table 1:
attitude    count
a   235
b   223
c   173
d   82
e   50
f   9

And the table 2:
       a    b   c     d   e  f
china   52  58  25  12  3   1
france  35  48  40  21  9   2
india   96  28  13  7   10  0
england 21  41  50  23  18  3
usa 31  48  45  19  10  3

How can i transform data.txt into the two  tables?

A: Table 1:
aggregate(count~attitude,data=data.txt,FUN=sum)
  attitude count
1        a   235
2        b   223
3        c   173
4        d    82
5        e    50
6        f     9

Table 2:
xtabs(count~country+attitude,data.txt)
         attitude
country    a  b  c  d  e  f
  china   52 58 25 12  3  1
  england 21 41 50 23 18  3
  france  35 48 40 21  9  2
  india   96 28 13  7 10  0
  usa     31 48 45 19 10  3

Or if you are wanting a new data.frame:
reshape(data.txt,direction="wide",timevar="attitude",idvar="country")
   country count.a count.b count.c count.d count.e count.f
1    china      52      58      25      12       3       1
7   france      35      48      40      21       9       2
13   india      96      28      13       7      10       0
19 england      21      41      50      23      18       3
25     usa      31      48      45      19      10       3

A: Using Hadley's packages,
plyr::ddply(d, .(attitude), summarise, n = sum(count))

reshape2::dcast(d, country ~ attitude)


text:
Q: BigQuery SQL - Combine multiple rows from 1 column that match rows from another table? I'm new to Big Query and SQL in general, having really on spent a few days with it so far.
I've spent quite a few hours on my current goal and can't seem to find a way to achieve my objective...
I think I've got the Concat right, but am getting duplicated that I can't get rid off as there's one row for each SPECID.
Also not sure once I get rid of them, how I join in the third table without more duplicates?
DATA:
t1
SUMID   Reference   Type    Size
1001    234         Round   120
1002    234         Square  60

t2
DETID   SUMID   SPECID  Value
2001    1001    1       TRUE
2002    1001    2       TRUE
2003    1001    3       FALSE
2004    1001    4       TRUE
2005    1001    5       FALSE
2006    1001    6       TRUE
2007    1002    1       FALSE
2008    1002    2       TRUE
2009    1002    3       FALSE
2010    1002    4       TRUE
2011    1002    5       TRUE
2012    1002    6       TRUE

t3
SPECID  Description
1       Blue
2       Red
3       Green
4       Orange
5       Yellow
6       Purple

OUTPUT
t1.Reference    t1.Type  t1.Size  t3.Description
234             Round     120     Blue, Red, Orange, Purple
234             Square     60     Red, Orange, Yellow, Purple

I've made it as far as the following, but for the life of me, I can't get my head around it.
#standardSQL
SELECT
t1.SUMID, t1.Reference, t1.Type, t1.Size, t2.Description

FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.T2_ID = t2.T2_ID

LEFT JOIN (
SELECT *
FROM (
select SUMID, Value,
  CONCAT(
    STRING_AGG(CAST(SPECID AS STRING), ', ') OVER(PARTITION BY SUMID, Value)
        ) SPEC_IDs

from Table2
)) t2 ON t1.SUMID = t2.SUMID

WHERE t2.Value = TRUE

If anyone could break this down for me I'd be really appreciative?
I'm hoping once I see how it works it'll just click.

A: If I understand correctly, this is some JOINs with aggregation:
SELECT t1.Reference, t1.Type, t1.Size,
       STRING_AGG(t3.Description, ', ')
FROM Table1 t1 LEFT JOIN
     Table2 t2
     ON t2.T2_ID = t1.T2_ID AND
        t2.Value LEFT JOIN
     Table3 t3
     ON t3.SPECID = t2.SPECID
GROUP BY t1.Reference, t1.Type, t1.Size;


text:
Q: How can I merge two dataset one column will be between two columns? Hi I want to merge two dataframes (d1 and d2), the rule is same rows in columns d1 and d2 and d2's St1 and St2 will be between dt1's St1 and St2. the expected output and inputs are below. Thanks
dt1 <- data.frame(ID=c(1,2,3,4), X=c("a","b","c","d"), St1=c(1000,900, 1500, 2500), St2=c(2000,3000, 1800, 4000))
dt2<-data.frame(ID=c(1,4,3,2), X=c("a","e","c","f"), St1=c(1200,2700, 1900, 2000), St2=c(1800,9000, 2650, 2200))

    dt_Exp<-data.frame(ID=c(1), X=c("a"), St1.x=c(1000),
   St2.x=c(2000),St1.y=c(1200), St2.y=c(1800))

A: You can merge the two dataframes using inner_join, then using the by function to group the merge by similar columns.
Such as:
dt1 <- data.frame(ID=c(1,2,3,4), X=c("a","b","c","d"), St1=c(1000,900, 1500, 2500), St2=c(2000,3000, 1800, 4000))
dt2<-data.frame(ID=c(1,4,3,2), X=c("a","e","c","f"), St1=c(1200,2700, 1600, 2000), St2=c(1800,9000, 1650, 2200))

dt_Exp<-data.frame(ID=c(1,3), X=c("a","c"), St1.x=c(1000,1500), St2.x=c(2000, 1800),St1.y=c(1200,1600), St2.y=c(1800, 1650))
dt21

dat <- inner_join(dt1, dt2, by = c("X", "ID"))

A: library(sqldf)

dt_Exp<-sqldf("select * from dt1 inner join dt2 on dt1.ID = dt2.ID and dt1.X=dt2.X where dt2.St1 between dt1.St1 and dt1.St2  and dt2.St2 between dt1.St1 and dt1.St2")

A: It wasn't clear from the whether the merge should match just ID or match both ID and X, so here are two possibilities:
> merge(dt1, dt2, by=c("ID","X"))
  ID X St1.x St2.x St1.y St2.y
1  1 a  1000  2000  1200  1800
2  3 c  1500  1800  1900  2650

> merge(dt1, dt2, by=c("ID"))
  ID X.x St1.x St2.x X.y St1.y St2.y
1  1   a  1000  2000   a  1200  1800
2  2   b   900  3000   f  2000  2200
3  3   c  1500  1800   c  1900  2650
4  4   d  2500  4000   e  2700  9000

The difference is in the names of the 'by'-arguments which can be given as a character vector when using base R's merge-function. (No need for added packages.)


text:
Q: Corda - Testing a Contract with 'at least' One Output I am trying to test a contract command where the rules are:
"Zero input states must be consumed" using (tx.inputs.isEmpty())
"At least one output must be created" using (tx.outputs.isNotEmpty())

How exactly do I test "At least one output must be created"?

*

*If I test with an input, the test fails the first verification (inputs must be zero).

*If I test with zero inputs/outputs, the test fails because a transaction must either consume an input, or produce an output.

*If I test with a reference state, it seems not to work, suggesting an exception was expected but didn't get one.

A: If you run a test with no inputs and no outputs you will get an error before your contract code is run:
java.lang.AssertionError: Expected exception containing 'At least one output must be created' but raised exception was 'java.lang.IllegalStateException: A transaction must contain at least one input or output state'

Which is your second point in the question

If I test with zero inputs/outputs, the test fails because a transaction must either consume an input, or produce an output.

This means that you can't actually test this code in a way that checks for your specific message.
e.g. with
this `fails with` "At least one output must be created"

Essentially, your contract code checking for at least one output state is redundant, whilst you have the code that checks for zero input states.
However, you could write the test to expect the IllegalStateException.
This way, if your code changes and inputs subsequently become valid you will have a failing test that will alert you.
An alternative to checking for at least one output state in your contract code is to check for at least one state of a specific type.
e.g.
"Output states must be Demo States." using (tx.outputsOfType<DemoState>().isNotEmpty())

This way you will be able to write a meaningful test.
e.g.
Contract:
class DemoContract : Contract {
    companion object {
        @JvmStatic
        val DEMO_CONTRACT_ID: String = DemoContract::class.java.name
    }

    interface Commands : CommandData {
        class Issue : TypeOnlyCommandData(), Commands
    }

    override fun verify(tx: LedgerTransaction) {
        val command = tx.commands.requireSingleCommand<Commands>()
        val signers = command.signers.toSet()

        when (command.value) {
            is Commands.Issue -> verifyIssue(tx, signers)
            else -> throw IllegalArgumentException("Unrecognised command.")
        }
    }

    private fun verifyIssue(tx: LedgerTransaction, signers: Set<PublicKey>) = requireThat {
        "No inputs are required when creating a new demo." using (tx.inputStates.isEmpty())
        "Output states must be Demo States." using (tx.outputsOfType<DemoState>().isNotEmpty())
    }

}

Test:
class DemoContractTests {
    private val owner = TestIdentity(CordaX500Name("Series", "London", "GB"))
    private val borrower = TestIdentity(CordaX500Name("One", "London", "GB"))
    private val mockServices = MockServices(owner)

    @Test
    fun `Demo issue must have no inputs`() {
        mockServices.ledger {
            transaction {
                input(DEMO_CONTRACT_ID, DummyState())
                command(listOf(owner.publicKey, borrower.publicKey), DemoContract.Commands.Issue())
                this `fails with` "No inputs are required when creating a new Demo."
            }
        }
    }

    @Test
    fun `There must only be DemoState outputs`() {
        mockServices.ledger {
            transaction {
                output(DEMO_CONTRACT_ID, DummyState(0))
                command(listOf(owner.publicKey, borrower.publicKey), DemoContract.Commands.Issue())
                this `fails with` "Output states must be Demo States."
            }
        }
    }

}


text:
Q: Powershell document.getElementbyID - doesn't pull right information I got a little powershell problem troubling me for quite a while now.
Im trying to get information from a RSS site. I download the XML and go through it. I just want certain stuff from it. That for I use .document.getElementByID().outerText
The problem is that somehow it pulls the first information correctly but after that everything fails he just picks random text or just keeps the one text from the beginning without refreshing the variable. Also Powershell ISE says "You cannot call a method on a null-valued expression." randomly.
Here is my code:
<#
AUTHOR: KOCH,MICHAEL [GRE-IT]
DESCRIPTION: RSS READER
DATE: 28.06.17
DATE LAST WRITTEN: 19.07.17
LAST CHANGE:
#>

$debug = 1 #DEBUG

$receiver="A@MailAdress.com"
$sender="A@MailAdress.com"
$smtp="A.SMTP.SERVER"
$encoding = [System.Text.Encoding]::UTF8

$path_config = "C:\RSS\Zoll\config.txt"
$output = "C:\RSS\Zoll\meldung.html"
$output_edit_path = "C:\RSS\Zoll\meldung_edit.html"
$nmbr=0
$count=0

Invoke-WebRequest -Uri 'http://www.zoll.de/SiteGlobals/Functions/RSSFeed/DE/RSSNewsfeed/RSSZollImFokus.xml' -OutFile C:\RSS\Zoll\meldungen.xml -ErrorAction Stop
[xml]$content = Get-Content C:\RSS\Zoll\meldungen.xml
$feed = $content.rss.channel
$tag = @()

if($lines=Get-Content $path_config | Measure-Object -Line) #gets the number of lines
{
    while($count -ne $lines.Lines)
    {
        if($entrys=(Get-Content $path_config)[$nmbr]) #gets the entrys from config.txt and goes through line by line
        {
            $entrys >> $tag[$nmbr]

            if ($debug -eq 1)
            {
                Write-Output "$tag[$nmbr]"
                Write-Output "$entrys"
                Write-Output "$count"
            }
        }
        $count++
        $nmbr++ #jumps into the next line
    }
}

$ie = New-Object -ComObject "InternetExplorer.Application"

Foreach($msg in $feed.Item)
{
    $link = ($msg.link)
    $subject = ($msg.title)

    $ie.navigate("$link")

    #$return = Invoke-WebRequest -Uri $link -OutFile "C:\RSS\Zoll\link.html"

    $return = $ie.document
    $innertext = $return.documentElement.document.getElementById("main").outerText

    $body = $innertext#.Replace('Ä', 'Ä')
    <#
    $body = $innertext.Replace('ä', 'ä')
    $body = $innertext.Replace('Ö', 'Ö')
    $body = $innertext.Replace('ö', 'ö')
    $body = $innertext.Replace('Ü', 'Ü')
    $body = $innertext.Replace('ü', 'ü')
    $body = $innertext.Replace('ß', 'ß')
    #>
        if ($debug -eq 1)
        {
            Write-Output "Subject $subject"
            Write-Output "Tag $tag"
            Write-Output "Link $link"
            Write-Output $body
            #exit
        }

        if($link -match "Zigaretten") #searchs in the <link> for the string "Zigaretten"
        {
           if($subject -match $tag) #searches for the specified tag in config.txt !!! only one argument per line !!!
           {
               if($mail = Send-MailMessage -From "$sender" -To "$receiver" -Subject "Zoll Meldung: $subject" -Body "$body" -SmtpServer "$smtp" -BodyAsHtml -encoding $encoding)
               {
                   if($debug -eq 1)
                   {
                       Write-Output "$tag"
                       Write-Output "Send. Tag = $tag"
                   }
                       Write-Output "Send."
               }
           }
       }
        else
        {
         Write-Host "Empty."
        }
}

$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)
Remove-Variable ie

A: Added a wait if busy loop to make sure IE loads the full html document. Thats the solution of the problem ! :)
<#
AUTHOR: KOCH,MICHAEL [GRE-IT]
DESCRIPTION: RSS READER
DATE: 28.06.17
DATE LAST WRITTEN: 20.07.17
LAST CHANGE: ADDED WAIT IF BUSY !
#>

$debug = 0 #DEBUG

$receiver="A@MailAdress.de"
$sender="A@MailAdress.de"
$smtp="A.SMTP.SERVER"
$encoding = [System.Text.Encoding]::UTF8

$path_config = "C:\RSS\Zoll\config.txt"
$output = "C:\RSS\Zoll\meldung.html"
$output_edit_path = "C:\RSS\Zoll\meldung_edit.html"
$nmbr=0
$count=0

Invoke-WebRequest -Uri 'http://www.zoll.de/SiteGlobals/Functions/RSSFeed/DE/RSSNewsfeed/RSSZollImFokus.xml' -OutFile C:\RSS\Zoll\meldungen.xml -ErrorAction Stop
[xml]$content = Get-Content C:\RSS\Zoll\meldungen.xml
$feed = $content.rss.channel
$tag = @()

if($lines=Get-Content $path_config | Measure-Object -Line) #gets the number of lines
{
    while($count -ne $lines.Lines)
    {
        if($entrys=(Get-Content $path_config)[$nmbr]) #gets the entrys from config.txt and goes through line by line
        {
            $entrys >> $tag[$nmbr]

            if ($debug -eq 1)
            {
                Write-Output "$tag[$nmbr]"
                Write-Output "$entrys"
                Write-Output "$count"
            }
        }
        $count++
        $nmbr++ #jumps into the next line
    }
}

$ie = New-Object -ComObject InternetExplorer.Application #creates new ComObject IE

Foreach($msg in $feed.Item)
{
    $link = ($msg.link)
    $subject = ($msg.title)

    if ($debug -eq 1)
    {
        $ie.visible = $true
    }

    $ie.navigate("$link") #navigate with Internetexplorer to the website

    while ($ie.busy -and $ie.ReadyState -ne 4){ sleep -Milliseconds 200 } # if getting the website from IE.navigate is still .busy wait 200 milliseconds

    $return = $ie.document

    $innertext = $return.documentelement.document.IHTMLDocument3_getElementById("main").outerText #gets the outer text from the div with the element ID "main"

    while ($innertext.busy -and $innertext.ReadyState -ne 4){ sleep -Milliseconds 200 } # if getting Text is .busy wait 200 milliseconds

    $body = $innertext

    if ($debug -eq 1)
    {
        Write-Output "Subject $subject"
        Write-Output "Tag $tag"
        Write-Output "Link $link"
        Write-Output "INNERTEXT $innertext"
        Write-Output "BODY $body"
        #exit
    }

    if($link -match "Zigaretten") #searchs in the <link> for the string "Zigaretten"
    {
        if($subject -match $tag) #searches for the specified tag in config.txt !!! only one argument per line !!!
        {
            if($mail = Send-MailMessage -From "$sender" -To "$receiver" -Subject "Zoll Meldung: $subject" -Body "$body" -SmtpServer "$smtp" -BodyAsHtml -encoding $encoding)
            {
                Write-Output "Send."
            }
        }
    }
    else
    {
        Write-Host "Empty."
    }
}

$ie.Quit()                                                               #----|
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie)          #    ---> Quits the Internet Explorer Session otherwise there are to many IE.exe open and no more ID's left
Remove-Variable ie


text:
Q: Server receives POST request twice from Nginx We have a nginx server acting as a reverse proxy between the client and server.
Whenever the server returns a 500 we actually see that the request is being sent to the server twice from the nginx logs:
173.38.209.10 - - [26/Jan/2018:15:15:36 +0000] "POST /api/customer/add HTTP/1.1" 500 115 "http://apiwebsite.com" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
173.38.209.10 - - [26/Jan/2018:15:15:36 +0000] "POST /api/customer/add HTTP/1.1" 500 157 "http://apiwebsite.com" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"

This API is only called twice if the first response is a 500.
If I bypass the nginx proxy and call the server directly, then it's only called once.
What's more strange is after further testing we found out this only happens in our corporate network. If i use my home network to connect to the proxy, then there's no retry even in case of a 500 response.
Anway, here's my nginx configuration:
    server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://127.0.0.1:3000";
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }
    location /api/customer/ {
                proxy_pass "http://127.0.0.1:8080/";
        }
}

Is there anything suspicious which is causing this behaviour?
Thanks


text:
Q: Android Studio 'tools.jar' file is not present in classpath I downloaded the current version of Android Studio (latest as of 4th July 2013)
I also downloaded the JDK version 7u25.
However, it displays error after startup: Please ensure JAVA_HOME points to JDK rather than JRE.
I don't know how to solve this problem, which won't let me run the IDE. I would appreciate any help.

A: Check if java JDK is installed correctly
dpkg --list | grep -i jdk

if not install JDK
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update && sudo apt-get install oracle-jdk7-installer

After the installation you have enable the jdk
update-alternatives --display java

Check if Ubuntu uses Java JDK 7
java -version

If all went right the answer should be something like this:
java version "1.7.0_25″
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) Server VM (build 23.3-b01, mixed mode)

Check what compiler is used
javac -version

It should show something like this
javac 1.7.0_25

Add JAVA_HOME to environment variable
Edit /etc/environment and add JAVA_HOME=/usr/lib/jvm/java-7-oracle to the end of the file
sudo nano /etc/environment

Append to the end of the file
JAVA_HOME=/usr/lib/jvm/java-7-oracle

Log in and out (or reboot) for the changes to take effect.
If you want to remove oracle JDK
sudo apt-get remove oracle-jdk7-installer

A: On Fedora (and other RedHat derivatives, e.g. RHEL 7 and CentOS 7), it was the missing openjdk-devel package that was the issue for me. It's an easy fix and nothing to do with the JAVA_HOME path or the JRE.
sudo yum install java-1.7.0-openjdk-devel.x86_64

A: If you are using Windows, the installation can be confusing for many users...
The installer lets you specify an installation path, but this is only if you have the JRE option selected to install.
The actual JDK installs automatically to...
C:\Program Files\Java\jdkX.XX  on 64-bit
C:\Program Files (x86)\Java\jdkX.XX  on 32-bit
So you need to make sure you set the JAVA_HOME variable in environment variables set to this JDK path, not the JRE path that appears in the installer.

A: read this:
http://arwankhoiruddin.blogspot.co.il/2014/01/android-studio-in-ubuntu-problem.html
in short:
type at the terminal

$ sudo update-alternatives --config java

now you need to choose

usr/lib/jvm/java-7-openjdk/jre/bin/java

by pressing #3

A: In windows Create new environment as STUDIO_JDK which refers to your jdk C:\Program Files\Java\jdk1.7.0

A: I have Ubuntu 14.04 and OpenJDK and for me a fresh install worked.
just did
sudo apt-get install openjdk-7-jdk
or,
sudo apt-get install --reinstall openjdk-7-jdk if it is already installed and giving error,
and everything was fine.

A: On ubuntu I have tried all the methods that are described here but none worked.
What I did in the end was to:

*

*download JDK from oracle and extract the archive

*edit android-studio/bin/studio.sh and add at the top
export JAVA_HOME=/path/to/jdk

*save the file and cd android-studio/bin and launch Android Studio: ./studio.sh

A: This answer may be very specific to a Windows 7 32 bit system:
Even after setting the JAVA_HOME variables, I had problems. After installing the JAVA again from the website, http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
BUT THIS TIME I TRIED "Windows x64  54 MB   jdk-8u51-windows-x64-demos.zip" which seems to be for 64 bit even though my system is 32 bit and the ANDROID STUDIO started working for me. My environment settings are following (under System variables and not under user variables):
JAVA_HOME-C:\Program Files (x86)\Java\jre1.8.0_51
JDK_HOME-C:\Program Files (x86)\Java\jdk1.8.0_51

A: I had the same problem on Linux Mint 17.2 and it was very simple:
In the package manager I found that openjdk-7-jre was installed but not the JDK. All I had to do was to install openjdk-7-jdk.
As I'm new to Linux it took me some time to figure this out though because I assumed by the name of the path /usr/lib/jvm/java-7-openjdk-amd64 that it was already the JDK but it was just the JRE.

A: On Linux Mint 17 (or Ubuntu 14.04):
sudo apt-get install openjdk-7-jdk

Then change the JAVA_HOME env variable.
export JAVA_HOME=JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/

A: Downloading the latest Android Studio resolve this issue / OSX /MAC


text:
Q: Seeding Math::Random::ISAAC from /dev/urandom : How to read/pass 128 bits? There are many ways to create secure random numbers in Perl. Most of these ways involve one or more Perl modules. Many of these Perl modules require even more Perl modules as dependencies.
Since I want to keep things very light-weight and reduce dependencies required, I decided to use Math::Random::ISAAC, and to seed it myself from /dev/urandom.
So, what would be the recommended way to read, say 128 bits (I guess that is a good amount) of data from /dev/urandom, in Perl, without using another module, and then to pass it to ISAAC?
I don't know what the right way of reading and formatting would be, here is a copy of the sub I will be passing the seed to:
sub new {
  my ($class, @seed) = @_;

  my $seedsize = scalar(@seed);

  my @mm;
  $#mm = $#seed = 255; # predeclare arrays with 256 slots

  # Zero-fill our seed data
  for ($seedsize .. 255) {
    $seed[$_] = 0;
  }

  my $self = {
    randrsl   => \@seed,
    randcnt   => 0,
    randmem   => \@mm,

    randa     => 0,
    randb     => 0,
    randc     => 0,
  };

  bless($self, $class);

  $self->_randinit();

  return $self;
}

I am not an expert in the specifics of arrays, scalars, byte strings, etc; so I don't really know how to format the urandom data into @seed appropriately. I do think that 128 bits is plenty of randomness, but I do not know how to make sure that all that entropy makes it into ISAAC, and to prevent it from being truncated to 64 or 32 bits along the way.

A: From looking at the ISAAC code that uses the seed, it appears to want 32 bit values.  So:
use autodie;
open(my $fh,'<','/dev/urandom');
my $buffer;
read($fh, $buffer, 16) == 16 or die "not enough read";
my @seed = unpack 'L4', $buffer;
my $isaac = Math::Random::ISAAC->new(@seed);


text:
Q: Foundation 5 CSS Z-index Top Bar dropdown menu issue
Hi all,
I needed to add z-index:2 to the header elements, now the topbar nav drop down is appearing under.
I tried to add {position:relative;z-index:999} on many elements, but it doesn't work. Any hints?
I am using CSS, margin is added to show the problem
Code here:
    [HTML and CSS][2]
[2]: http://codepen.io/anon/pen/yYKamg

A: Change this:

To this:

The z-index: of 2 on this div is placing it in front of the navigation dropdown. So I think you need to move the container element of the dropdown nav up a level.

A:

This fixed it, Setting the parent container to a higher z-index. I am pretty sure I tried this more than once yesterday. Thanks guys. I will keep you posted if anything pops up.


text:
Q: Getting previous page's results when using skip and limit while querying DocumentDB I have a collection with ~800,000 documents, I am trying to fetch all of them, 5,000 at a time.
When running the following code:
const CHUNK_SIZE = 5000;

let skip = 0;

do {
  matches = await dbClient
    .collection(collectionName)
    .find({})
    .skip(skip)
    .limit(CHUNK_SIZE)
    .toArray();

    // ... some processing
  skip += CHUNK_SIZE;
} while (matches.length)

After about 30 iterations, I start getting documents I already received in a previous iteration.
What am I missing here?

A: As posted in the comments, you'll have to apply a .sort() on the query.
To do so without adding too much performance overhead it would be easiest to do this on the _id e.g.
.sort(
    {
        "_id" : 1.0
    }
)

Neither MongoDB or the AmazonDocumentDB flavor guarantees implicit result sort ordering without it.
Amazon DocumentDB
Mongo Result Ordering


text:
Q: Effects of amount of imports on overall Angular production bundle size I was looking for an answer but couldnt find one on my very basic question. I am building a Angular App and at some point wanted to exchange the angular material components to the ionic web components. In one feature of my app I am depending on the material data table which ionic does not offer a substitute.
To my question: How does it effect my final bundle size if I include angular material to my dependencies just for this table? Does Angular only use the modules I import in production and tree-shake the rest of the angular material package?
I would be very thankful for some information on bundlesizes and imports. Its more of a general question if its "worth" to use a big package just for one component and how the imports work with that.

A: Modern Angular should "tree shake" all unused components when you build the app for production (ionic build --prod if you are using Ionic).
There were issues with the tree shaking in the past when a different approach to packaging was used. You can read more details in this closed issue thread here:
https://github.com/angular/components/issues/4137
If you feel like it's not working in your case - try using a different count of components in your app and monitor build package sizes and then you can ask specific questions with all the context.


text:
Q: How to display MainWindow before the business logic execution has completed So I am new to MVVM with WPF and am having trouble with a few concepts.
So as soon as you run, my MainViewModel will set up the model and will start pulling from the database in order to populate a list which is binded to one of my controls.
Now the problem is that, after it pulls data from the db it then needs to listen to another source which will fire an event and then add to this list. Now, this data source will fire events infinitely, so I would like to display the UI with the DB-pulled data and then update this list as events fire.
My initial idea was to only start this listen for updates once I have loaded and presented my control, but how is this done using the OnLoaded event in MVVM, I think this has been my biggest struggle.
Thanks

A: Decided to go with Clemens' comment.
I now, bind the datasource in code and run the viewModel's listen method when the window is loaded, using the Loaded event. I am still not sure if this is a good MVVM solution so will probably change it again soon if it isn't.


text:
Q: Best database admin software for mac? What's the best database admin software for OSX?

*

*maintain database schema and data

*run queries

*convert schema from one database type to another

*datapump to move data around

*schema diff tools, ideally able build a script to update a schema

*easy to use

Databases I'm interested in are

*

*MSSQL

*PostgreSQL

*MySQL

*Firebird

*(SQLite)

Prefer one tool for all the databases, rather than one for each database.

A: For MySql, use http://www.sequelpro.com/ (foss) or http://www.araelium.com/querious/ (paid)

A: I've used SQuirreL SQL in the past.  It's written in Java, so it works on any platform with a decent JVM and any database with a decent JDBC driver.  I think it'll do most, if not all of what you are asking for.

A: For just postgres, pgAdmin3 has gotten better in the last few releases and works fine in OS X. I've also used SQuirrel, which works on jdbc compliant db's, but it's been a while.

A: I use Aqua Data studio 6 at work on a daily basis, with SQL Server, Sybase IQ and Netezza.  It's convenient not having to switch tools all the time. It also has a handy SQL prettier that helps keep my blood pressure low when people send me mangled SQL to look at.  Netezza is unsupported but works fine with generic ODBC/JDBC.
While it is a java app the only time I really run into problems is when I run a query that returns to many rows (over 100k).  You can set the limits and or play with memory but every once in a while I shoot myself in the foot and bang on my keyboard.
I run windows but linux and mac are also supported.
Nice just noticed that version 7 has built in pivot tables.  That will save me from cutting and pasting datasets to excel!

A: For MySQL, you could try:

*

*MySQL Admin

*PHP Mysql Admin (if you don't mind installing a PHP web app)

*Oracle's SQLDeveloper (works with MySQL also with a little bit of config)

A: I'm a mac developer that wanted some tools for some of these as well, so I built a few tools.

*

*SQLPro for SQLite

*SQLPro for MSSQL and

*SQLPro for MySQL
SQLPro for SQLite is the oldest and has gone over fairly well with a 4 star average rating and great reviews.
SQLPro for MSSQL it a newer app built for connecting to MSSQL databases (specifically I wanted Azure support, but it does other versions as well), which has also been getting great reviews.
I have also been asked by a few people for a Postgres version, so that will be coming in the near future.


text:
Q: Spring Roo unable to generate Selenium tests because of Xerces error After watching Roo Google IO, I decided to try it out using this tutorial, but I'm getting stuck when trying to create Selenium tests.
~.web roo> selenium test --controller ~.web.PizzaOrderController
Created SRC_MAIN_WEBAPP/selenium
Created SRC_MAIN_WEBAPP/selenium/test-pizzaorder.xhtml
Created SRC_MAIN_WEBAPP/selenium/test-suite.xhtml
Undo create SRC_MAIN_WEBAPP/selenium/test-suite.xhtml
Undo create SRC_MAIN_WEBAPP/selenium/test-pizzaorder.xhtml
Undo create SRC_MAIN_WEBAPP/selenium
com.sun.org.apache.xerces.internal.dom.DeferredCommentImpl cannot be cast to org.w3c.dom.Element

A person at this forum suggested removing Xerces from the classpath because Java 6 has its own XML parser based on Xerces. However, I haven't come across a clear way to remove something from the classpath, only setting it (which I think would be tedious each time).
Does anyone know of a clear way to remove jars from the classpath? Has anyone encountered this Roo problem before and solved it another way?

UPDATE
As requested, here is the more verbose output:
roo> development mode
Development mode set to true
roo> selenium test --controller ~.web.PizzaOrderController
Created SRC_MAIN_WEBAPP/selenium
Created SRC_MAIN_WEBAPP/selenium/test-pizzaorder.xhtml
Created SRC_MAIN_WEBAPP/selenium/test-suite.xhtml
Undo create SRC_MAIN_WEBAPP/selenium/test-suite.xhtml
Undo create SRC_MAIN_WEBAPP/selenium/test-pizzaorder.xhtml
Undo create SRC_MAIN_WEBAPP/selenium
com.sun.org.apache.xerces.internal.dom.DeferredCommentImpl cannot be cast to org.w3c.dom.Element
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredCommentImpl cannot be cast to org.w3c.dom.Element
    at org.springframework.roo.addon.web.menu.MenuOperationsImpl.addMenuItem(MenuOperationsImpl.java:88)
    at org.springframework.roo.addon.web.selenium.SeleniumOperationsImpl.manageTestSuite(SeleniumOperationsImpl.java:185)
    at org.springframework.roo.addon.web.selenium.SeleniumOperationsImpl.generateTest(SeleniumOperationsImpl.java:140)
    at org.springframework.roo.addon.web.selenium.SeleniumCommands.generateTest(SeleniumCommands.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.roo.support.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:191)
    at org.springframework.roo.process.manager.ProcessManagerHostedExecutionStrategy$1.callback(ProcessManagerHostedExecutionStrategy.java:34)
    at org.springframework.roo.process.manager.internal.DefaultProcessManager.doTransactionally(DefaultProcessManager.java:169)
    at org.springframework.roo.process.manager.internal.DefaultProcessManager.execute(DefaultProcessManager.java:132)
    at org.springframework.roo.process.manager.ProcessManagerHostedExecutionStrategy.execute(ProcessManagerHostedExecutionStrategy.java:32)
    at org.springframework.roo.shell.AbstractShell.executeCommand(AbstractShell.java:158)
    at org.springframework.roo.shell.jline.JLineShell.promptLoop(JLineShell.java:200)
    at org.springframework.roo.shell.jline.JLineShell.run(JLineShell.java:126)
    at java.lang.Thread.run(Thread.java:619)

A: Can you please type "development mode", press enter, then re-run the Selenium command and include the more detailed stack trace that follows?


text:
Q: Solving $4u_{tt}-3u_{xt}-u_{xx}=0$
Solving $\begin{cases} 4u_{tt}-3u_{xt}-u_{xx}=0\tag1\\u(x,0)=x^2\quad\text{and}\quad  u_t(x,0)=e^x\end{cases}$ in $\mathbf R\times\mathbf R_{>0}$

First I factorized and get for the first line;
$(\partial_x-4\partial_t)(\partial_x+\partial_t)u=0$ and set $v:=(\partial_x+\partial_t)u$
then $v_x-4v_t=0$ is transport equation with solution $f\left(x+\frac{1}{4}t\right)$
hence  $(1)$ is reduced to $u_x+u_t=f\left(x+\frac{1}{4}t\right)$. This is nonhomogeneous transport equation with solution
$$u(x,t)=\displaystyle\int_0^t f\left(x+\frac{1}{4}t+2(s-t)\right)ds+g(x-t)$$
considering initial conditions I get $g(x)=x^2,\ $ $\ f(x)=e^x-2x$
then wolframalpha yields, this
but if I apply $(1)$ to the result it is not true, where is the mistake ?

A: $(\partial_x-4\partial_t)(\partial_x+\partial_t)u=0$ and set $v:=(\partial_x+\partial_t)u$
then $v_x-4v_t=0$ is transport equation with solution $f\left(x+\frac{1}{4}t\right)$
Hence  the problem is reduced to $u_x+u_t=f\left(x+\frac{1}{4}t\right)$.
This is the nonhomogeneous transport equation with solution
$u(x,t)=\int_0^t f(x+s-t+\frac 14 s)ds+g(x-t)\tag{$\star$}$
Initial condition $u(x,0)$ implies $g(x)=x^2$
second initial condition $u_t(x,0)$ yields
$f(x)=e^x+2x$
Inserting in $(\star)$ gives,
This


text:
Q: Use TeamCity environment variable in shell script I have a TeamCity environment variable env.TIER_SUFFIX whose value is set as A. I want to be able to use this in my script build step where the script content is
    #!/bin/bash
    tierSuffix=%env.TIER_SUFFIX%
    echo "TierSuffix is [${'$'}tierSuffix]"
    export ENV_TIER=%env.DEV_tierSuffix%

The build fails because export ENV_TIER=%env.DEV_tierSuffix% creates env.DEV_ and the build stops. Is there a way to use this in the export command so that it substitutes the value of %env.DEV_A%   to ENV_TIER

A: The way I use TeamCity variables in bash scripts is:
buildCounter="%build.counter%"

where build.counter is TeamCity variable.


text:
Q: Recline JS - Grid shows Headings but not the Data So I'm attempting to use Recline. I've followed the tutorial and I can get the grid to show the headings but it doesn't show the data within I currently have:
var data = [
    {id: 0, date: '2011-01-01', x: 1, y: 2, z: 3, country: 'DE', geo: {lat:52.56, lon:13.40} },
    {id: 1, date: '2011-02-02', x: 2, y: 4, z: 24, country: 'UK', geo: {lat:54.97, lon:-1.60}},
    {id: 2, date: '2011-03-03', x: 3, y: 6, z: 9, country: 'US', geo: {lat:40.00, lon:-75.5}},
    {id: 3, date: '2011-04-04', x: 4, y: 8, z: 6, country: 'UK', geo: {lat:57.27, lon:-6.20}},
    {id: 4, date: '2011-05-04', x: 5, y: 10, z: 15, country: 'UK', geo: {lat:51.58, lon:0}},
    {id: 5, date: '2011-06-02', x: 6, y: 12, z: 18, country: 'DE', geo: {lat:51.04, lon:7.9}}
    ];

            var dataset = new recline.Model.Dataset({
                records: data
            });
            var $el = $('#mygrid');
            var grid = new recline.View.SlickGrid({
                model: dataset,
                el: $el
            });
            grid.visible = true;
            grid.render();

And I have all of the dependencies they list in the tutorial. I was wondering what could be causing this to not work as expected?

A: try css
    .recline-slickgrid
    {
      height: 500px;
    }


text:
Q: Get user's location (latitude, longitude) with Bing or Google Maps API is there a way to retrieve a latitude & longitude of the user using Bing Maps API or Google Maps API. I think I saw an code snippet where a "autolocate me" feature was used to mark user on the Map itself:
var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
geoLocationProvider.getCurrentPosition();

But that function doesn't return any data, it simply set location on the map, whereas I need that location to perform some calculations, namely calculate which of predefined list of places is the closest to current user location. Apart from that, does any of this API's can calculate the distance between two locations (lat,lon) that are provided as an input?
Thanks,
Pawel

A: Getting your location isn't part of the Map API. Instead, use the HTML5 GeoLocation API to get your location. An example would be:
 navigator.geolocation.getCurrentPosition(locationHandler);

 function locationHandler(position)
 {
   var lat = position.coords.latitude;
   var lng = position.coords.longitude;
 }

For calculating distance between lat/lng points, have a look at http://www.movable-type.co.uk/scripts/latlong.html.
// Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2011                   - www.movable-type.co.uk/scripts/latlong.html
// where R is earth's radius (mean radius = 6,371km);
// note that angles need to be in radians to pass to trig functions!
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;

A: HTML5 GeoLocation get lat and long of current location.
 http://www.w3schools.com/html/html5_geolocation.asp
<!DOCTYPE html>

Click the button to get your coordinates:

<button onclick="getLocation()">Try It</button>


text:
Q: WCF is very slow I have got a functionality which returns 60,000 objects. An object contains only few properties. This functionality works in couple of seconds if I execute it on non-wcf mode in my local machine. But it takes over 30mins to execute on WCF mode in the local machine with below binding.
Does anyone have any idea on improving the performance of this in WCF mode? Thanks!
   <binding name="ReliableBindingConfig" closeTimeout="00:20:00" receiveTimeout="00:40:00" openTimeout="00:20:00" sendTimeout="00:40:00">
      <transactionFlow />
      <reliableSession maxRetryCount="12" ordered="true" inactivityTimeout="00:40:00" />
      <mtomMessageEncoding maxBufferSize="2147483647" maxReadPoolSize="2147483647" maxWritePoolSize="2147483647">
        <readerQuotas maxDepth="32" maxBytesPerRead="4096" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxNameTableCharCount="16384" />
      </mtomMessageEncoding>
      <httpTransport maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
    </binding>

A: Adjust your maxBufferSize and maxBufferPoolSize to optimise the buffer sizes.
Too big and your service will be too busy loading all of the objects into memory. Too small and there will be too much network traffic and will slow it down.
You could write a simple test harness to record the time taken to find the optimal buffer size.


text:
Q: Construct an example of set $A$ for which $A+A=A $ but $0∉cl(A)$ How to prove that convexity is necessary condition in this question? Need to construct an example of set $A$ for which $A+A=A$ but $0 \notin cl(A)$. From the linked question follows that $A$ must be non-convex.

A: This is merely a distilled version of the answer by coffeemath (hence CW). Pick an irrational number $\alpha$ and let $A=\{(m,n)\in\mathbb Z^2:m\alpha+n>0\}$. This is a discrete set, it does not contain $(0,0)$, and obviously satisfies $A+A\subseteq A$. To prove the reverse inclusion $A\subseteq A+A$, note that for any $(m,n)\in A$ there exists $(m',n')$ such that $0<m'\alpha+n'<m\alpha+n$, and therefore $(m,n)=(m',n')+(m-m',n-n')\in A+A$.
This construction comes up in complex analysis, since the linear combinations of the functions $\{z^mw^n: (m,n)\in A\}$ form an algebra on the torus $|z|=|w|=1$ (here $z,w$ are complex). However, in this case one throws in $(0,0)$ (hence, the constant function) in order to have a unital algebra. See, e.g., Banach spaces of analytic functions by K. Hoffman, pp 54-57.

A: Let $F_n$ denote the $n^{th}$ fibonacci number, with a few terms having nonpositive subscripts, so that $$F_{-2}=-1,\ F_{-1}=1,\ F_0=0,\ F_1=F_2=1,\ F_3=2,\ F_4=3,...$$
Define the points $v_n$ in the $xy$ plane by
$$v_n=[(-1)^n F_{n-3},\ (-1)^n F_{n-1}],$$
so that $$v_1=[1,0],\ v_2=[1,1],\ v_3=[0,-1],\ v_4=[1,2],\ v_5=[-1,-3],\ v_6=[2,5],...$$
Note that these points have the property that $v_n=v_{n+1}+v_{n+2}$ for each $n \ge 1$. In fact they may be generated from this relation, after $n=2$, taking $[1,0],\ [1,1]$ as the first two points and thereafter defining $v_n=v_{n-2}-v_{n-1}.$
Define the set $A$ in the plane as consisting of all (finite) liner combinations of the $v_n$ with nonnegative integer coefficients. Then $A+A=A$. This is because each $v_n$ is the sum of the next two, and $A$ is the closure of the set of $v_n$ under addition.
Now the closure of $A$ can only contain integer pairs, so to show this closure does not contain $[0,0]$ is the same as showing that $[0,0] \notin A.$
Suppose we have a nontrivial relation
[1] $\sum_{k=1}^{m+1} c_k v_k=[0,0].$
Then using the relation $v_n=v_{n+1}+v_{n+2}$ we can transform the sum until it only involves the highest two indices of the sum, namely $k=m,m+1.$ In so transforming the relation, the coefficients remain nonnegative (one only adds such coefficients). So the relation [1] would imply there are nonegative $x,y$ for which
$$x v_m + y v_{m+1}=[0,0]$$
Factoring out $\pm 1$ from this relation we have the left side as
$$x[F_{n-3},F_{n-1}]+y[-F_{n-2},-F_n]=[u,v],$$
where $u=xF_{n-3}-yF_{n-2}$ while using the recurrence for the fibonacci numbers,
$$v=xF_{n-3}+xF_{n-2}-yF_{n-2}-yF_{n-1}.$$
Then  $v-u=xF_{n-2}-yF_{n-1}.$ So from $[u,v]=[0,0]$ would follow the two equations
$$xF_{n-3}-yF_{n-2}=0,\\ xF_{n-2}-yF_{n-1}=0.$$
But the determinant of this system is $-F_{n-3}F_{n-1}+F_{n-2}^2,$ which a fibonacci identity says is always $\pm 1$. This implies that $x,y$ are both zero, which means the supposed relation [1] was trivial after all.
We conclude that $[0,0]$ is not in the set $A$, so that this is an example in two dimensions of a set $A$ for which $A+A=A$, and yet $[0,0]$ is not in the closure of $A$.


text:
Q: Pass file as argument to Docker run is is possible to pass file as an argument to docker . I have an dockerized java application which expects the properties file to be passed as an argument and then it reads file and performs start up and other activities .Is it possible to implement this.

A: Yes, it is possible. You have to set entrypoint and cmd properly.
When additional arguments are passed on the command line, these will be used as command instead and be passed to the entry point.


text:
Q: Dynamically create model validations and attributes in Rails without a database I am new to Rails and I am trying to use some metaprogramming in order to automate a few things. What I am trying to do is essentially generate a database-less Rails model. The reason for this is so I can generate models, validations, forms, etc. based on some metadata in a file.
The problem now is that I probably have some errors in the way I try to do the metaprogramming.
This (simplistic example) works:
class User
  include ActiveModel::Validations

  validates_presence_of :forename, :surname

  def initialize(attrs = {})
    self.class.class_eval { attr_accessor :forename, :surname }

    send("forename=", attrs['forename'])
    send("surname=", attrs['surname'])
  end
end

But this doesn't:
class User
  include ActiveModel::Validations

  def initialize(attrs = {})
    self.class.class_eval { attr_accessor :forename, :surname }

    # moved the validation line in here
    self.class.class_eval { validates_presence_of :forename, :surname }

    send("forename=", attrs['forename'])
    send("surname=", attrs['surname'])
  end
end

The way I realized it doesn't work is because I have a form for this model. When I hit submit multiple times with empty fields, I see error messages from before (ie. the errror messages accumulate over different requests).
I must be doing something really wrong in the code so was wondering if someone more experienced could guide me towards the right direction.


text:
Q: Javascript Prototype General Enquries and Assign Id by Array Index I am trying to learn how to work with javascripts prototype, I am only getting into it now. Please Excuse me if I ask ridiculously stupid questions
I just have a few pre-questions:

*

*Is it worth learning? I mean it looks like a structured/clean
approach to me?

*Do/should you use this with jQuery this?

*is there any major problems or reason not to use it and why isn't it commonly used or am i just slow?

Actual Question:
I have the following code:
var BudgetSection = function BudgetSection(name ) {
    this.id = "";
    this.name = name;
    this.monthlyTotal = 0.00;
    this.yearlyTotal = 0.00;
    this.subTotal = 0.00;
    this.lineItems = [];
};

BudgetSection.prototype.calculateSubTotal = function() {
    this.subTotal = ((12 * this.monthlyTotal) + this.yearlyTotal);
};

function BudgetLineItem(name) {
    this.id = "";
    this.name = name;
    this.monthlyAmount = 0.00;
    this.yearlyAmount = 0.00;
}

BudgetLineItem.prototype = {
    totalAmount : function() {
        var result = ((12 * this.monthlyAmount) + this.yearlyAmount);
    return result;
    }
};

var budgetSections = [];

section = new BudgetSection("test1");
section.lineItems.push(new BudgetLineItem('sub'));
section.lineItems.push(new BudgetLineItem('sub2'));
section.lineItems.push(new BudgetLineItem('sub3'));
budgetSections.push(section);

section = new BudgetSection("test2");
section.lineItems.push(new BudgetLineItem('sub'));
section.lineItems.push(new BudgetLineItem('sub2'));
section.lineItems.push(new BudgetLineItem('sub3'));
budgetSections.push(section);

section = new BudgetSection("test3");
section.lineItems.push(new BudgetLineItem('sub'));
section.lineItems.push(new BudgetLineItem('sub2'));
section.lineItems.push(new BudgetLineItem('sub3'));
budgetSections.push(section);

// first iterate through budgetSections
for ( var t = 0; t < budgetSections.length; t++) {
    var sec = budgetSections[t];
    console.log(sec);
// iterate through each section's lineItems
    for (var q = 0; q< budgetSections[t].lineItems.length ; q++) {
        var li = budgetSections[t].lineItems[q];
    console.log(li);
    }
}

the first BudgetSection "test1" is at index 0 in the budgetSections array. how can i assign the id to "section_".
And then also how can i set the id of BudgetLineItem like so: lineItemRow_<section_index><lineitem_index>
Also finally n the for loop what would be the best way to generate html?

A: Have you tried budgetSections[0].id = 'yourID';?

A: I personally never use the new keyword if I can avoid it and do pure prototype-based programming with Object.create. Here's a simple example. I create a prototype-object called rectangle and then create an object called myRectangle which inherits from rectangle.
var rectangle = {
  init: function( x, y, width, height ) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  },
  move: function( x, y ) {
    this.x += x;
    this.y += y;
  }
};

var myRectangle = Object.create( rectangle );
myRectangle.init( 0, 0, 2, 4 );
myRectangle.move( 3, 5 );

To explain in more depth what happens here, Object.create makes a new object with a specified prototype. When we access a property on an object (like init or move), it first checks the object itself. If it can't find it there, it moves up to the object's prototype and checks there. If it's not there, it checks the prototype's prototype, and keeps going up the prototype chain until it finds it.
When we call a function on an object (myRectangle.init()), this inside the function refers to that object, even if the function definition is actually on the prototype. This is called delegation - an object can delegate its responsibilities to its prototype.
A more class-like way to do this is:
function Rectangle( x, y, width, height ) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

Rectangle.prototype.move = function( x, y ) {
  this.x +=x;
  this.y +=y;
};

var myRectangle = new Rectangle( 0, 0, 2, 4 );
myRectangle.move( 3, 5 );

The problem is when we need to do a deeper inheritance hierarchy:
function Parent() {
  /* expensive and possibly side-effect inducing initialization */
}

Parent.prototype.parentMethod = function() {};

function Child() {}

Child.prototype = new Parent();

We have to initialize a Parent object when all we really want is to set the Child prototype to an object based on Parent.prototype. Another option is:
Child.prototype = Object.create( Parent.prototype );

But now we've got this confusing, convoluted mess of prototype-based and class-based code. Personally, I like this instead:
var parent = {
  parentMethod: function() {}
};

// Using underscore for stylistic reasons
var child = _.extend( Object.create( parent ), {
  childMethod: function() {}
});

var instance = Object.create( child );
instance.parentMethod();
instance.childMethod();

No new keyword needed. No fake class system. "Objects inherit from objects. What could be more object-oriented than that?"
So what's the catch? Object.create is slow. If you're creating lots of objects, it's better to use new. You can still use Object.create to set up the prototype chain, but we'll have to wait a bit for browsers to optimize it enough for lots of instantiation.


text:
Q: Methods in a class. Should you set properties and have the method use properties or pass arguments? Lets say i have a class to calculate tax. Which is the best practice to design the calcTax method. Option 1 or Option 2. The object pertains to a person and that is why we are storing age and income. I can see the pros and cons of each but just wanted to see if there is a best practice or if one of the two options has a code smell.
Option 1:
    class CalcTax
    {
        private int Age;
        private double Income;

        public void Update(int age, double inc)
        {
            Age = age;
            Income = inc;
        }

        public double calcTax()
        {
            return Age * Income * 0.25;
        }

    }

    CalcTax obj = new CalcTax();
    obj.update(5,500)
    obj.CalcTax();

Option 2:
    class CalcTax
    {

        public double calcTax(int age, int inc)
        {
            return age * inc* 0.25;
        }
    }

    CalcTax obj = new CalcTax();
    obj.calcTax(10,100);

A: Could go either way.  Depends on what the object is supposed to represent.
If it there is one object for one person (I'm assuming Age and Income relate to a person), and that object is going to be doing a variety of things beyond the one calculation you show, then the fundamental attributes of that person (Age, Income, etc.) should be class attributes.  These would likely be set as parameters to new() or perhaps set shortly after the instance was created.
If, however, this is just a calculator object, to be used to process requests for a variety of people, then there is no need to have Age and Income as class attributes at all.  You could delete them your Option 2 example entirely, and just have them in the parameters to calcTax().
It probably ends there, with one of those options best matching your project. But if you're creating more of a library function that other programmers will be using in different ways in different projects, you could straddle the fence a bit...
Take Age and Income as parameters to new() and save them as class attributes.  Then, make the parameters to calcTax() optional, and default to the class attributes if none are provided.  That way, your developers can take whichever approach suits their needs best, and you've got a single codebase to support them both.

A: As the first comment says, the choice is yours.  Try to think about what role your class will play.  Is it just a collection of common math functions that you may want to call.  If so, then methods with passable parameters are great.
However, if you're generating a tax class that will be specific to a certain context, then maybe something like the below would be best for you.  The example below requires the Age and Income and offers up the CalculatedTax as a read-only property.
public class Tax
    {
        public Tax(int Age, int Income) //constructor, class can not be instantiated without these values
        {
            this.Age = Age;
            this.Income = Income;
        }

        public int Age { get; set; }
        public int Income { get; set; }
        public double CalculatedTax //read only property
        {
            get { return double.Parse((Age * Income).ToString()) * 0.25f; }
        }
    }

Tax tax = new Tax(5, 1000);
double calculatedTax = tax.CalculatedTax; //1250

One benefit to the above example is that Age and Income are required to generate the CalculatedTax value.  By forcing these parameters to be entered in the constructor you  make sure they exist, otherwise (for this example) if these were your only three  properties, what would be the point of making a class if you weren't going to include one of the required parameters.


text:
Q: Dig behaving differently after OS change After replacing a SLES12 SP5 server with a SLES15 SP3 server the dig command is behaving differently.  I'm trying to determine if this is a bug or changeable as it breaking some code that would be complicated to update.
SLES12 SP5:
user@server:~> dig +search -t A rtr +short
#.#.#.#
user@server:~> dig +search -t A rtr.site +short
#.#.#.#
user@server:~> dig +search -t A rtr.site.company.com +short
#.#.#.#
user@server:~> dig -v
DiG 9.6-ESV-R7-P4

SLES15 SP3:
user@server:~> dig +search -t A rtr +short
#.#.#.#
user@server:~> dig +search -t A rtr.site +short
user@server:~> dig +search -t A rtr.site.company.com +short
#.#.#.#
user@server:~> dig -v
DiG 9.9.6-P1

As you can see a dig search (with +search) is no longer returning the IP for rtr.site when it did previously.
Resolv.conf:
search site.company.com company.com
nameserver #.#.#.#
nameserver #.#.#.#
nameserver #.#.#.#

Can anyone explain the difference to me and ideally a way to get it behave the way it used to.


text:
Q: Who discards IP packet when TTL becomes 0 If the TTL of a IP packet becomes 0, then who will discard the IP packet i.e., either router or host.

A: The router.
If the TTL is 0, the packet is discarded, and never reaches the host.
More information in wikipedia

A: It's the router that discards it. From this post on CiscoPress:
Time To Live (TTL) is a well-known mechanism thanks to IP. In the IP header is a field of 8 bits that signifies the time that a packet still has before its life ends and is dropped. When an IP packet is sent, its TTL is usually 255 and is then decremented by 1 at each hop. If the TTL reaches 0, the packet is dropped. In such a case, the router that dropped the IP packet for which the TTL reached 0 sends an Internet Control Message Protocol (ICMP) message type 11 and code 0 (time exceeded) to the originator of the IP packet.


text:
Q: How to set a default path to my new Python 3.5 install? I just installed python 3.5 from the official python website. It installed on my computer and it install on my computer under:
/Library/Frameworks/Python.framework/Versions/3.5

However, I am trying to run virtualenv and it will take me to this error message when I try to create a new virtual environment.
-bash: /Users/me/anaconda/bin/virtualenv: No such file or directory

I removed Anaconda from my computer but still unable to create a virtual environment under my python 3.5 path even though it has installed.
Here is my bash_profile.
# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

# Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH

### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"

# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

# Setting PATH for Python 3.4
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}"
export PATH

##
# Your previous /Users/lewismenelaws/.bash_profile file was backed up as /Users/lewismenelaws/.bash_profile.macports-saved_2015-02-25_at_15:58:24
##

# MacPorts Installer addition on 2015-02-25_at_15:58:24: adding an appropriate PATH variable for use with MacPorts.

A: Try adding
PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}"
export PATH

I don't see any path for python 3.5, however.
Honestly I would scratch all this and install python, pip and virtualenv using homebrew so everything is in /usr/local/bin/


text:
Q: Replacing commented line in bash file using sed fails I am trying to update my hadoop-env.sh file such that I replace a commented parameter with a new one. I am new to the whole concept and after a lot of searching I ended up doing the following:
sed -i '/^export JAVA_HOME=/ s:.*:export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_HOME/etc/hadoop/hadoop-env.sh

The part of file that I am trying to update looks like:
# The java implementation to use. By default, this environment
# variable is REQUIRED on ALL platforms except OS X!
# export JAVA_HOME=

And desired outcome is:
# The java implementation to use. By default, this environment
# variable is REQUIRED on ALL platforms except OS X!
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export HADOOP_HOME=/usr/local/hadoop

However, when I cat the hadoop-env.sh file I am getting the same content as before. I have to mention that I am running this in Dockerfile using the following:
RUN sed -i '/^export JAVA_HOME=/ s:.*:export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_HOME/etc/hadoop/hadoop-env.sh

I have no idea what I might be missing and any help is much appreciated.

A: This was answered in the comments.
Change:
sed -i '/^export JAVA_HOME=/ s:.*:export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_HOME/etc/hadoop/hadoop-env.sh
To: (adds 2 characters only)
sed -i '/^# export JAVA_HOME=/ s:.*:export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_HOME/etc/hadoop/hadoop-env.sh


text:
Q: How to uninstall nuget and clear corrupted entries? I want to install AjaxControlToolkit via nuget. But NuGet Package Manager GUI displays error as show below.

Even when I try to install a fresh copy of AjaxControlToolkit, NuGet displays message:
Failed to install or uninstall nuget package.
I checked my project and didn't find any nuget file. Where are the corrupted entries and how to repair it?

A: I've never ran into this specific error but I'd assume it's either packages.config that is malformed (it's an XML) or a .nupkg file is corrupted.
Do you currently have packages installed ?
- Delete the "packages" folder in your solution and packages.config (keep it elsewhere for reference, it's the lift of installed packages), then re-install your packages. Let me know how that goes.


text:
Q: Chrome is ignoring correct css spec for animation I have a bunch of CSS animation properties declared individually on elements. As far as I can see, they are all declared properly. The animation is also working fine, but when I look in Chrome Developer tools, I can see lots of yellow exclamation markers next to the non-prefixed spec versions of the properties. See image below:

I think the yellow marker means the property and value were ignored because they were specified improperly. So why is it doing that here?


text:
Q: Sticky posts per category I need: to have the ability to set one post as sticky in one category and not the others.
Example: So let's say i have this three categories: "one" "two" and "three".
and i have a post named "sticky in one and two" and another post named "sticky in one".
Now i want the "sticky in one and two" post to be sticky in the category "one" and in the category "two" but not in the category "three".
And i want the "sticky in one" post to be sticky in the category "one" but not in the category "two" and not in the category "three".
Thoughts: I thought of trying something like add a taxonomy with the same terms as the categories terms ("one","two","three") and then to make two loops which in the first one i get the posts which have the name of the current category in there custom taxonomy terms (for example when i'm on the category "one" archive it will fetch only the posts that has "one" in this new custom taxonomy) and then a second loop which will get all the current category posts excluding the first loop posts. but it seem very complicated and i'm guessing one could think of a better way to do it, so please share your ideas...
Also a minor problem with this method is that i can check a term in the custom taxonomy which isn't marked in the categories taxonomy which could be confusing...
Thanks!


text:
Q: Creating separate tables dependant on user roles I have created a table called 'users' and within this table users can have one of three roles. I am trying to create three separate tables to group the different users within the one page, or a separate page, according to their role. At the moment I have them displaying in one table.
User index.blade.php
@extends('layouts.app')
@section('content')

                        <button type="button" class="btn btn-success">Create User</button>

Manage Users

                                        ID
                                        Name
                                        Course
                                        Role

                                    @foreach ($users as $user)

                                            {{ $user->id }}
                                            {{ $user->name}}
                                            {{ implode ($user->courses()->pluck('title')->toArray()) }}
                                            {{ implode (', ', $user->roles()->pluck('role_name')->toArray()) }}

                                                @can('edit_users')
                                                id) }}">
                                                    View

                                                @endcan

                                                @can('edit_users')
                                                id) }}">
                                                    Edit

                                                @endcan

                                                @can('delete_users')
                                                <form action="{{ route('admin.users.destroy', $user->id) }}" method="POST" onsubmit="return confirm('Confirm delete?');" style="display: inline-block;">
                                                    <input type="hidden" name="_method" value="DELETE">
                                                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                                                    <input type="submit" class="btn btn-xs btn-danger" value="Delete">
                                                @endcan
                                            </form>

                                        @endforeach

@endsection

I appreciate any help on how I could go about doing this.

A: in controller u need to group users by role_name, and after in index.blade.php create tables with foreach. Or u can use belongTo relashionship, and get users by role, as u wish. $roles->user

A: You can try to make three tables like this
[DATABASE]
users
    id - integer
    name - string

roles
    id - integer
    name - string

role_user
    user_id - integer
    role_id - integer

[MODEL]
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

and you can attach many role with this in your
[CONTROLLER]
$user = App\User::find(1);
$user->roles()->attach($roleId);
``


text:
Q: Outlook inspector events not triggered in contact card edit mode I am developing the outlook add-in for logging the contact changes(what changes added newly). I am used the following code to trigger the outlook events.
//Trigger the new inspector events
_inspectors = Application.Inspectors;
_inspectors.NewInspector += new Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
And the Inspectors_NewInspector events should like follows
private void Inspectors_NewInspector(Outlook.Inspector inspector)
{
if (inspector.CurrentItem is Outlook.ContactItem)
{
    if (((Outlook.ContactItem)inspector.CurrentItem).EntryID != null)
    {
        // Here Capture the contact properties changes
    }
}

}
The above code works as expected while editing the contact as full contact editing mode. But, from the outlook 2013 and 2016, we can edit the contact using the contact card mode. If I edit contact card mode, the NewInspector events not getting triggered. So, I am not able to capture the outlook contact changes.
The contact card view as like below.

Any suggestion to fix this issue.
Thanks in advance.

A: You need to subscribe to the SelectionChange event of the Explorer class which is fired when the user selects a different or additional Microsoft Outlook item programmatically or by interacting with the user interface.
This event also occurs when the user (either programmatically or via the user interface) clicks or switches to a different folder that contains items, because Outlook automatically selects the first item in that folder.
You may find the How to: Display Selected Items in the Active Explorer article helpful.


text:
Q: Print max value with data i want to get data with highest value.
class Mountain:

    def __init__(self, name, height):
        self.name = name
        self.height = height

mountain_01 = Mountain("Mount Everest", 8850)
mountain_02 = Mountain("Mount Kazbek", 5033)
mountain_03 = Mountain("Vinson Massif", 4892)
mountain_04 = Mountain("Kilimanjaro", 5895)

highest_mountain = max(mountain_01.height, mountain_02.height,
mountain_03.height, mountain_04.height)
print(f"Highest is : {highest_mountain}")

i expect output as "Highest is: Mount Everest 8850"

A: You can start by capturting all your mountains in a list, and then calculating max over that list, by using the key as the height of the mountain
#List of mountains
mountains = [mountain_01, mountain_02, mountain_03, mountain_04]

#Get highest mountain based on height of mountain
highest_mountain = max(mountains, key=lambda mountain:mountain.height)

print(highest_mountain.name)
print(highest_mountain.height)

The output will be
Mount Everest
8850


text:
Q: Terrible noises from subwoofer of ACER Aspire 6930 with Realtek sound chip After approximately 5-15 min of listening to music my subwoofer begins to make terrible noises. He's just "coughing". That began after 6 months I had this computer.
Now I found out, that I can temporarily fix this problem by "restarting" the audio stream of the application that plays music. For example reloading last.fm page (reloads the flash file). Another way to reset the audio playback is switching the speaker configuration shown below in the screenshot.

According to many posts on the internet like http://www.tomshardware.co.uk/forum/52918-20-acer-aspire-6935g-speaker-problem

*

*ACER support isn't any help

*Exchanging hardware doesn't fix the problem

*Even the later models have this problem

Turning off the volume of the subwoofer is not an option to me. I still have warranty (I bought an extension of one year). I already tried about 15 versions of the Realtek driver with no success. I am not sure but MAYBE the problem did not occur on the original windows vista that was shipped with this computer. However, I removed the original windows for good reasons (english).
What do you suggest me? Did anyone fix this problem? Maybe by writing a script which resets the audio streams every 5 minutes? Shall I take the effort to deal with the acer support until they give me another model? (I won't have a computer than for a longer time, will spend money on telephone hotlines (1,30 EUR / min)......)
Here are additional infos, if they are any help:

*

*Windows 7 64 Bit (Original was Windows Vista Home Premium 32 Bit)

*All specs

*Audio driver version:

A: I have the same laptop, I think I know what you mean, for me it was the sub woofer switching off, and the bass frequencies going to the small L/R speakers causing distortion, or just messing up the bass sound.
Go to your "sound", do you have more then one sound card?
[For me, it was SRS sandbox] kept switching the default sound device [my computer still showed the Realtek sound device as the default, but it wasn't actually], causing the sub woofer to sound all crackly and distorted. I'd try disabling all other sound devices.

A: An Update of the Realtek driver, which came out about half a year after my question, solved the problem. So, this was a software problem.


text:
Q: Node, spawn multiple dependent shell commands I'm trying to use gulp to activate a virtualenv for python and launch a django server.
Although I can launch the server correctly I can't activate the virtualenv beforehand.  (this breaks integration with my IDE's gulp tool).
Is there a way to make the virtualenv spawn launch first and be part of the child process that launches the server (as the server depends on being in the virtual environment).
gulpfile.js
gulp.task('runServer', function(cb) {
  var virtualenv = spawn('source venv/bin/activate')
  var cmd = spawn('python', ['manage.py', 'runserver'], {stdio: 'inherit'});
  cmd.on('close', function(code) {
    console.log('runServer exited with code ' + code);
    cb(code);
  });
});

A: Maybe you could try something like this:
child_process.spawn('venv/bin/python', ['manage.py', 'runserver']);

This uses the python env but only requires one command to be executed


text:
Q: update input of user in map function React hooks New to react hooks...
I've brought some data of users from an API and I want to update one or more of the inputs by clicking a submit button.
I can see in the state that the user's last letter changes but I can see the new input on the screen and I can not change the entire word. And I don't know if it is supposed to change also in the whole array of users or it is impossible once I've called them from the API.
Thanks
import { useState } from 'react'
import axios from 'axios'
function UsersComp() {
    const [user, setUser] = useState()
    const [users, setUsers] = useState([])
    const [id, setId] = useState(0)

    const getUsers=async ()=>{
        let resp = await axios.get("https://jsonplaceholder.typicode.com/users")
        setUsers(resp.data);
    }

    const update = async (e) =>
    {
        e.preventDefault();
        let resp = await axios.put("https://jsonplaceholder.typicode.com/users/" + id, user)
    }

    return (

        <form onSubmit={e => update(e)}>
            {
                users.map((item) =>
                {
                    return

                                    ID:{item.id}

                                    Name:<input value={item.name} onChange={e => setUser({...user, name : e.target.value})} type="text" name="name" />

                                    Email:<input value={item.email} onChange={e => setUser({...user, email : e.target.value})} type="text" name="email" />

                                <input type="button" value="Add Data"/>
                                <input type="submit" value="Update"/>
                                <input type="button" value="Delete"/>

                })
            }
        </form>
        <input type="button" value="Get users" onClick={getUsers} />

    );
  }

  export default UsersComp;

A: You can update onChange like this by using map:
onChange={(e) =>
  setUser(
    users.map((eachUser) =>
      item.id === eachUser.id ? { ...eachUser, name: e.target.value } : eachUser,
    ),
  )
}


text:
Q: Spyder python editor: turn off whole-line tab when tabbing mid-line Imagine I am standing (i.e., the cursor is located) somewhere mid-line in a given line of my Spyder editor.
Working always only with interesting integers, I could be at this line, say:
an_interesting_integer = 4

the cursor is right before "=" and thus right after "an_interesting_integer ", say.
Then I press "tab".
What I want is just the equal sign to be tabbed, but what happens in my Spyder editor is that the whole line is tabbed.
So instead of:
an_interesting_integer     = 4

I get:
    an_interesting_integer = 4

How can I turn off this "whole-line-tabbing" thing.
Thank you

A: Spyder v. 4.0 or higher:

Tools >>> Preferences >>> Editor >>> Source code >>> Uncheck "Tab always indent".

Other versions:

Tools >>> Preferences >>> Editor >>> Advanced settings >>> Uncheck "Tab always indent".


text:
Q: noob question about function () I am not sure about this code. This structure is correct?
 success: function(data, data1, data3, .... ) {
                    switch (data.livre) {
                    case 'x':

                        break;
                    }

                    switch (data1.livre1) {
                    case 'y':

                        break;
                    }

                }

thanks

A: For future reference here is a code quality tool : jshint
The above is indeed "correct" code as in it will parse correctly. But it can be improved though.
success: function(data) {
  if (data.livre === 'x') {
    ...
  }
  if (data.livre1 === 'y') {
    ...
  }

}

Be wary that you generally pass one result back. So you should get the server to pass an object or array of data back.
The real question is, do you have a problem? and what are you trying to achieve?

A: I'm not sure which part of the function you're asking about, but maybe you mean either:
function success( ... ) { .... }

Or,
success = function( ... ) { .... }

Using success: function doesn't make sense in isolation, but people are so used to reading that as a JS object property they might think its ok...

A: If that's inside of an object, sure.  Looks right to me.
i.e.
var obj = {
     success: function(...
};


text: Q: is there a way to dump all postgres database from localhost to remote server without restoration in ubuntu? I want to dump all my PostgreSQL databases directly to a remote server from my localhost, just a simple .sql file and create a cronjob for it. Is this possible ?


text:
Q: To show difference between two bars in high charts? I want to show difference values in a new line between the two bar charts in high chart plugins, I've create simple bar chart in high charts, but I need to show difference between two bars in the new line.
I'm explaining this in below image, please refer following image.

please help me to fix this ,
Image 2,
 i want to show that information in below format/design, is it possible in high charts?
Image 2

A: I've got as far as extracting the data from the table to calculate the differences. However, as the example has some negative differences e.g. -1, it will depend what graph you would like to put this information on as it would need to have a negative y axis.
The following jQuery code will exact all values, find the difference between the first and second and then add this to an array called diffChart.
var graphs = $('#datatable tbody tr');

var diffChart = [];

for (var i = 0, len = graphs.length; i < len; i++) {
    var target = $('#datatable tbody tr').eq(i);
    var bar1 = target.find('td').eq(0).text();
  var bar2 = target.find('td').eq(1).text();

  var diff = Number(bar1) - Number(bar2);

  diffChart.push(diff);

}

You can view an example of the console log output in this jsfiddle
Sorry I couldn't be of much help past this.


text:
Q: BoxStay() en C# unity cuando instancio 2 prefabs, los dos vienen con colider, de esta forma si intento cambiarlos de posición con el siguiente código me mueve los dos preabs al mismo punto creando un bucle. ¿Hay alguna forma de diferenciarlos?
private void OnTriggerStay(Collider other)
   {
       int random1 = Random.Range(8, 20);
       int random2 = Random.Range(8, 20);
       gameObject.transform.position = new Vector3(random1, 0, random2);
   }

Lo que pasa es que spwamean con Instantine hay alguna forma de hacer que hagan spwan como gameobjects?


text:
Q: How to fetch a div content based on a inner value contained in it? On  Click on the plus icon  it will increase the quantity of the corresponding  Item and  updates that to the MyOrders tab div .
Now on clcik of the Myorders tab div , how can i extract the  lastItm_Wrap div whose quantity is greater than 1 ?? so that i can add them to the finalorders
http://jsfiddle.net/673h38g9/4/
my sample code
   $(document).on('click', '.icon-plus', function (e) {
        var value = parseInt($(this).closest('div').find('.QtyInput').val());
        $(this).closest('div').find('.QtyInput').val(value+1);

        var currentsellprice =  parseFloat($(this).parent().prev().data('sellprice'));
        // get the data "price" of item

        var currentquantity =parseInt($(this).closest('div').find('.QtyInput').val());
        $(this).closest('.lastItm_Wrap').find('.Itm_right_aside .sellprice')
               .text(currentsellprice*currentquantity);

        if (currentquantity>=1) {
            addquantitytoMyordersfooter();
            var subtotalvalue = parseInt($(".myOrderPanel_footer .subtotal")
                                .data('subtotal'));
            subtotalvalue = subtotalvalue + currentsellprice ;

            $(".myOrderPanel_footer .subtotal").data('subtotal',subtotalvalue);
            $(".myOrderPanel_footer .subtotal").text(subtotalvalue)
        }
        displaylogicforfooter();
  });

A: I added some logic to you displaylogicforfooter function. This could be used as a starting point.  Below data-finalorders div's text is first cleared. After that each div with class lastItm_Wrap is gone through and the QtyInput value is obtained. Currently, there is only alert that prints the quantity if it's more than 1. I hope you find it okay. You still need to add the relevant part that sets the data-finalorders div's content. Fiddle
function displaylogicforfooter()
{    //clear the div value
     $("div[data-finalorders]").text("");

     $(".lastItm_Wrap").each(function (index) {
         //store lastItm_Wrap div into $elem
        $elem = $(this);
        var qtyValue = $elem.find(".QtyInput").val();

         qtyValue = parseInt(qtyValue);

         //if quantity greater than 1
         if (qtyValue > 1 ) {

             //here you can add your logic - comment out the line below
             alert(qtyValue);

             //if you want to access the lastItm_Wrap div's html, use $elem.html()
             //alternative if you wan't find sth within the div use $elem.find()

             //you can set <div data-finalorders="some text"> text by using the line below
             //just remember to create the div above first :-)
             //$("div[data-finalorders]").text("some text")

         }

    });

 // more code ....

}


text:
Q: How can I see the metadata from the MINT NFTs in react after MINT how can I see the metadata from the NFT mint on react? And get access to them as soon as I press the mint button on the page? after clicking on the mint I have access to some information from the transaction, such as "hash", does it help?
mint file function
async function handleMint() {
    if (window.ethereum) {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const contract = new ethers.Contract(
        mintExampleAddress,
        mintExampleABI.abi,
        signer
      );
      try {
        const cost = await contract.cost();
        const response = await contract.mint(mint, {
          value: cost.mul(BigNumber.from(mint)),
        });
        console.log(response);
        toast.success("Mint successfully!", {
          theme: "dark",
        });
      } catch (err) {
        console.log(err);
      }
    }
  }


text:
Q: React Leaflet: setting a polygon's style dynamically How do I change a polygon's color programatically?
The solution I was using for GeoJSONs here doesn't work. Though when I inspect the element, I can see
style:{color: "red"}

nonetheless, the map shows a blue polygon.
Here's the relevant part of my component:
render() {
    const {
        id,
        name,
        geoJSON,
        zoomLevel,
        selectedPlot,
        plotBeingEdited
    } = this.props;
    const markerPosition = position(geoJSON);

    let style = () => {
        return {
            color: 'blue'
        };
    };
    if (selectedPlot === id) {
        style = () => {
            return {
                color: 'red'
            };
        };
    }

    if (zoomLevel > 14 && plotBeingEdited === id) {
        return <PlotPolygon id={id} geoJSON={geoJSON} />;
    } else if (zoomLevel > 14) {
        return (
            <Polygon
                ref="plot"
                style={style()}
                id={id}
                positions={[positions(this.props)]}
                onClick={() => {
                    this.props.selectPlot(id);
                }}
            />
        );
    }

A: Pass on color prop as an object:
<Polygon
   ...
   color={selectedPlot === id ? 'red' : 'blue'}
/>


text:
Q: Initializing a grid of JButton and adding them to a JFrame I'm trying to write a program that plays Yahtzee in a JFrame. Our teacher has a way we're supposed to write it, and it involves adding ConfigurationButtons - a class that extends JButton - to the JFRame. Here is the code I have so far:
builder= new PlayerPanel();

manager = new JFrame("Yahtzee!");
manager.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
manager.setLayout(new GridLayout(TOTAL, numPlayers));
manager.add(builder);
//manager.add(howManyPlayers);
manager.setSize(1200,600);
manager.setVisible(true);

private class PlayerPanel extends JPanel
{
    private final int ROWS = 18;
    private JLabel[]titles;
    private PlayerPanel()
    {
        for(int j=0;j<numPlayers;j++)
        {
            for(int i=0;i<ROWS;i++)
            {
                fields[i][j]=new ConfigurationButton(i,j);
                manager.add(fields[i][j]);
            }
        }
    }

I tried implementing this solution but it didn't work- all I get is a blank JFrame.

A: OK, to fill out your JFrame, see what I have done with the following code, and apply it to your situation.
JFrame manager = new JFrame("Manager");
JPanel panel = new JPanel(new GridLayout(10, 10));

for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < 10; j++)
    {
        JButton button = new JButton(i + " - " + j);

        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                ((JButton)(e.getSource())).setText("Clicked");
            }
        });

        panel.add(button);
    }
}

manager.add(panel);
manager.setSize(750, 750);
manager.setVisible(true);

Take note of how the panel is set up in a GridLayout (as you had), but the panel is then added to the JFrame.
You should be able to build your panel based off this example, substituting your custom components where necessary.


text:
Q: Error: IOException - how to get more specific error How to find out the more specific error situations like whether the error is because of FileNotFoundException , or EOFExceptionor No Internet Access etc....
below is the code that i am using to access the internet and i am getting the IOException and I know this is due to not having permission to access internet.. but how I want to know for SURE that whether this error related with file, or eof or permission related....
below is my code and catching all the exception but none will give me a specific situation exception.
try {
    HttpGet request = new HttpGet(MyConstants.URL);
    HttpResponse response = null;
    response = httpClient.execute(request);
    //HttpResponse httpResponse = httpClient.execute(request);
    HttpEntity httpEntity = response.getEntity();
    xmlList = EntityUtils.toString(httpEntity);
}
catch (MalformedURLException e) {
    xmlList = "URL: is a malformed URL";
    e.printStackTrace();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    xmlList = "URL: UnsupportedEncodingException";
} catch (ClientProtocolException e) {
    e.printStackTrace();
    xmlList = "URL: ClientProtocolException";
} catch (SocketTimeoutException  e) {
    e.printStackTrace();
    xmlList = "URL: SocketTimeoutException";
} catch (ConnectTimeoutException  e) {
    e.printStackTrace();
    xmlList = "URL: ConnectTimeoutException";
} catch (IOException e) {
    xmlList = "URL: IOException";
    e.printStackTrace();
}

A: Catch it!
} catch (FileNotFoundException e) {
    xmlList = "URL: FileNotFoundException";
    e.printStackTrace();
} catch (EOFException e) {
    xmlList = "URL: EOFException";
    e.printStackTrace();
} catch (IOException e) {
    xmlList = "URL: IOException";
    e.printStackTrace();
}

There is no such exception as 'No Internet Access'.