问:
Formatting arrays specifically in PHP
I have the following PHP code on my website:

```<code><?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>
</code>```

And I want it to be output like so:

```<code>("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)
</code>```

for an SQL string, which will be:

```<code>INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);
</code>```

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

答:
Since you're just new to PHP, let's not yet get into classes.

An easy way to do this, without destroying or modifying the data you are storing is by using a multidimensional array, like this :

```<code>$myArray = array(
  array( "Jacob", "Collins", 19 ),
  array( "Noah", "Little", 31 )
);

// Displays "Noah little 31"
echo $myArray[1][0]." ".$myArray[1][1]." ".$myArray[1][2];

foreach ($myArray as $row)
{
    //concatenate this to your query string.
    $assembledQuery = "(\"$row[0]\", \"$row[1]\", $row[2])";
}
</code>```

However, PLEASE keep in mind that this way of building queries is VERY VERY dangerous!

Title: Formatting arrays specifically in PHP

Body:
I have the following PHP code on my website:

<?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>

And I want it to be output like so:

("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)

for an SQL string, which will be:

INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

Body:
Since you're just new to PHP, let's not yet get into classes.

An easy way to do this, without destroying or modifying the data you are storing is by using a multidimensional array, like this :

$myArray = array(
  array( "Jacob", "Collins", 19 ),
  array( "Noah", "Little", 31 )
);

// Displays "Noah little 31"
echo $myArray[1][0]." ".$myArray[1][1]." ".$myArray[1][2];

foreach ($myArray as $row)
{
    //concatenate this to your query string.
    $assembledQuery = "(\"$row[0]\", \"$row[1]\", $row[2])";
}

However, PLEASE keep in mind that this way of building queries is VERY VERY dangerous!


来源: stackexchange

问:
Amortization schedule for many rows using Excel Macro
I am new to Excel VBA and looking for help in editing a macro.

I have three columns Sanctioned Amount, Tenure and Rate of Interest for 7328 rows.

Data Looks something like this

I already have a working VBA script(given below) to calculate the amortization schedule but I want it to take the inputs from the 3 columns, calculate it for 7328 rows(instead of manually putting it in) and append the values below each other.

I am requesting changing the script below to take the values from 3 columns.

```<code>Sub one()

Dim intRate, loanLife, initLoan, payment As Double
Dim yearBegBal, intComp, prinComp, yearEndBal, intTot, prinTot, fvloan As Currency

ActiveSheet.UsedRange.Delete

intRateYrs = InputBox("Input Interest rate (Annual):")
loanLifeYrs = InputBox("Input Loan life (Years):")
initLoan = InputBox("Input Loan amount:")

Application.DisplayAlerts = True
Application.ScreenUpdating = True

intRateMths = (intRateYrs / 100) / 12
loanLifeMths = loanLifeYrs * 12

Cells(4, 2).Value = Format(intRateYrs, "#.##") & " %"
Cells(4, 3).Value = Format(intRateMths, "Percent")
Cells(5, 2).Value = loanLifeYrs
Cells(5, 3).Value = loanLifeMths
Cells(6, 2).Value = Format(initLoan, "Currency")

payment = Pmt(intRateMths, loanLifeMths, -initLoan)
Cells(7, 2).Value = Format(payment, "Currency")

outRow = 10
intTot = 0
prinTot = 0
fvloan = 0

Cells(10, 2).Value = "Beginning Balance"
Cells(10, 3).Value = "Payment"
Cells(10, 4).Value = "Interest"
Cells(10, 5).Value = "Principal"
Cells(10, 6).Value = "End Balance"
Cells(10, 7).Value = "Total Interest"
Cells(10, 8).Value = "Total Principal"
Cells(10, 9).Value = "Total Repaid"
yearBegBal = initLoan

For rowNum = 1 To loanLifeMths
    intComp = yearBegBal * intRateMths
    prinComp = payment - intComp
    yearEndBal = yearBegBal - prinComp

    intTot = intTot + intComp
    prinTot = prinTot + prinComp
    fvloan = intTot + prinTot

    Cells(outRow + rowNum, 1).Value = rowNum
    Cells(outRow + rowNum, 2).Value = Format(yearBegBal, "Currency")
    Cells(outRow + rowNum, 3).Value = Format(payment, "Currency")
    Cells(outRow + rowNum, 4).Value = Format(intComp, "Currency")
    Cells(outRow + rowNum, 5).Value = Format(prinComp, "Currency")
    Cells(outRow + rowNum, 6).Value = Format(yearEndBal, "Currency")
    Cells(outRow + rowNum, 7).Value = Format(intTot, "Currency")
    Cells(outRow + rowNum, 8).Value = Format(prinTot, "Currency")
    Cells(outRow + rowNum, 9).Value = Format(fvloan, "Currency")

    yearBegBal = yearEndBal
Next rowNum

ActiveSheet.Range("A:I").EntireColumn.AutoFit
Rows("11:11").Select
ActiveWindow.FreezePanes = True
Range("A1").Select

Application.DisplayAlerts = False
Application.ScreenUpdating = False

End Sub
</code>```

This is how result look like from one iteration

答:
```<code>Sub one()

Dim intRate, loanLife, initLoan, payment As Double
Dim yearBegBal, intComp, prinComp, yearEndBal, intTot, prinTot, fvloan As Currency
Dim cell As Range

For Each cell In ThisWorkbook.Sheets(1).Range("B2:B2001")

    'intRateYrs = InputBox("Input Interest rate (Annual):")
    'loanLifeYrs = InputBox("Input Loan life (Years):")
    'initLoan = InputBox("Input Loan amount:")

    intRateYrs = cell.Offset(0, 1).Value
    loanLifeYrs = cell.Value
    initLoan = cell.Offset(0, 2).Value

    lrow = Sheets(2).Range("A" & Rows.Count).End(xlUp).Row

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    intRateMths = (intRateYrs / 100) / 12
    loanLifeMths = loanLifeYrs * 12
    With Sheets(2)
    Cells(lrow + 4, 2).Value = Format(intRateYrs, "#.##") & " %"
    Cells(lrow + 4, 3).Value = Format(intRateMths, "Percent")
    Cells(lrow + 5, 2).Value = loanLifeYrs
    Cells(lrow + 5, 3).Value = loanLifeMths
    Cells(lrow + 6, 2).Value = Format(initLoan, "Currency")

    payment = Pmt(intRateMths, loanLifeMths, -initLoan)
    Cells(lrow + 7, 2).Value = Format(payment, "Currency")

    outRow = lrow + 10
    intTot = 0
    prinTot = 0
    fvloan = 0

    Cells(lrow + 10, 2).Value = "Beginning Balance"
    Cells(lrow + 10, 3).Value = "Payment"
    Cells(lrow + 10, 4).Value = "Interest"
    Cells(lrow + 10, 5).Value = "Principal"
    Cells(lrow + 10, 6).Value = "End Balance"
    Cells(lrow + 10, 7).Value = "Total Interest"
    Cells(lrow + 10, 8).Value = "Total Principal"
    Cells(lrow + 10, 9).Value = "Total Repaid"
    yearBegBal = initLoan

    For rowNum = 1 To loanLifeMths
        intComp = yearBegBal * intRateMths
        prinComp = payment - intComp
        yearEndBal = yearBegBal - prinComp

        intTot = intTot + intComp
        prinTot = prinTot + prinComp
        fvloan = intTot + prinTot

        Cells(outRow + rowNum, 1).Value = rowNum
        Cells(outRow + rowNum, 2).Value = Format(yearBegBal, "Currency")
        Cells(outRow + rowNum, 3).Value = Format(payment, "Currency")
        Cells(outRow + rowNum, 4).Value = Format(intComp, "Currency")
        Cells(outRow + rowNum, 5).Value = Format(prinComp, "Currency")
        Cells(outRow + rowNum, 6).Value = Format(yearEndBal, "Currency")
        Cells(outRow + rowNum, 7).Value = Format(intTot, "Currency")
        Cells(outRow + rowNum, 8).Value = Format(prinTot, "Currency")
        Cells(outRow + rowNum, 9).Value = Format(fvloan, "Currency")

        yearBegBal = yearEndBal
    Next rowNum

    ActiveSheet.Range("A:I").EntireColumn.AutoFit
    Rows("11:11").Select
    ActiveWindow.FreezePanes = True
    Range("A1").Select
    End With
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

Next cell

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Excel VBA and looking for help in editing a macro.

I have three columns Sanctioned Amount, Tenure and Rate of Interest for 7328 rows.

Data Looks something like this

I already have a working VBA script(given below) to calculate the amortization schedule but I want it to take the inputs from the 3 columns, calculate it for 7328 rows(instead of manually putting it in) and append the values below each other.

I am requesting changing the script below to take the values from 3 columns.

Sub one()

Dim intRate, loanLife, initLoan, payment As Double
Dim yearBegBal, intComp, prinComp, yearEndBal, intTot, prinTot, fvloan As Currency

ActiveSheet.UsedRange.Delete

intRateYrs = InputBox("Input Interest rate (Annual):")
loanLifeYrs = InputBox("Input Loan life (Years):")
initLoan = InputBox("Input Loan amount:")

Application.DisplayAlerts = True
Application.ScreenUpdating = True

intRateMths = (intRateYrs / 100) / 12
loanLifeMths = loanLifeYrs * 12

Cells(4, 2).Value = Format(intRateYrs, "#.##") & " %"
Cells(4, 3).Value = Format(intRateMths, "Percent")
Cells(5, 2).Value = loanLifeYrs
Cells(5, 3).Value = loanLifeMths
Cells(6, 2).Value = Format(initLoan, "Currency")

payment = Pmt(intRateMths, loanLifeMths, -initLoan)
Cells(7, 2).Value = Format(payment, "Currency")

outRow = 10
intTot = 0
prinTot = 0
fvloan = 0

Cells(10, 2).Value = "Beginning Balance"
Cells(10, 3).Value = "Payment"
Cells(10, 4).Value = "Interest"
Cells(10, 5).Value = "Principal"
Cells(10, 6).Value = "End Balance"
Cells(10, 7).Value = "Total Interest"
Cells(10, 8).Value = "Total Principal"
Cells(10, 9).Value = "Total Repaid"
yearBegBal = initLoan

For rowNum = 1 To loanLifeMths
    intComp = yearBegBal * intRateMths
    prinComp = payment - intComp
    yearEndBal = yearBegBal - prinComp

    intTot = intTot + intComp
    prinTot = prinTot + prinComp
    fvloan = intTot + prinTot

    Cells(outRow + rowNum, 1).Value = rowNum
    Cells(outRow + rowNum, 2).Value = Format(yearBegBal, "Currency")
    Cells(outRow + rowNum, 3).Value = Format(payment, "Currency")
    Cells(outRow + rowNum, 4).Value = Format(intComp, "Currency")
    Cells(outRow + rowNum, 5).Value = Format(prinComp, "Currency")
    Cells(outRow + rowNum, 6).Value = Format(yearEndBal, "Currency")
    Cells(outRow + rowNum, 7).Value = Format(intTot, "Currency")
    Cells(outRow + rowNum, 8).Value = Format(prinTot, "Currency")
    Cells(outRow + rowNum, 9).Value = Format(fvloan, "Currency")

    yearBegBal = yearEndBal
Next rowNum

ActiveSheet.Range("A:I").EntireColumn.AutoFit
Rows("11:11").Select
ActiveWindow.FreezePanes = True
Range("A1").Select

Application.DisplayAlerts = False
Application.ScreenUpdating = False

End Sub

This is how result look like from one iteration


问:
No route to host, burp
I'm trying to proxy to any https connection and I have in alert section this message:

No route host
  error

burp certificate add

I have tried to solve it, reinstalled burp, reinstalled the certificate, set a manual network configuration.

Does somebody know how to solve this issue?

答:
The first thing to check is that you can browse these sites directly from your web browser, without Burp.

If you are on a corporate network you may need to use a proxy. In that case you need to set this as an "Upstream proxy" in User options > Connections.

Another possibility is that a host firewall is blocking the outbound connection.

Title: No route to host, burp


问:
Using fadeOut() and fadeIn() on mouseover and mouseout
My problem is that when I am using fadeOut() on mouseover and fadeIn() on mouseout() (on a
 component), I am not getting the results that I am expecting. What happens is that sometimes when the mouse is not on the object, the buttons that I want to fadeOut() just keep fading in and out in a loop and sometimes the loop stops and sometimes it doesn't.

What is the proper way of using fadeOut and fadeIn with mouseover and mouseout?

here is the code:

```<code>comment.onmouseout = function() {mouseOut(comment);};
comment.onmouseover = function() {mouseOver(comment);};
</code>```

where comment is a basic
 with buttons as children

```<code>function mouseOut(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeOut();
        }
    }
}
function mouseOver(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeIn();
        }
    }
}
</code>```

答:
That happens because when the opacity reaches 0 the display is set to none. so the element disappears, trigerring the mouseout.

quote from .fadeOut()

The .fadeOut() method animates the
  opacity of the matched elements. Once
  the opacity reaches 0, the display
  style property is set to none, so the
  element no longer affects the layout
  of the page.

So it would be better to animate the opacity instead

instead of fadeout

```<code>$(children.item(i)).animate({opacity:0},  400);
</code>```

and instead of fadein

```<code>$(children.item(i)).animate({opacity:1},400);
</code>```

another issue is that the animations get queued. So you would be better to stop the current animation before starting the next.

instead of fadeout

```<code>$(children.item(i)).stop().animate({opacity:0},  400);
</code>```

and instead of fadein

```<code>$(children.item(i)).stop().animate({opacity:1},400);
</code>```

If you could post your HTML it would be easier to post pure jquery code to handle the whole issue.

ContentLicense: CC BY-SA 2.5

Body:
My problem is that when I am using fadeOut() on mouseover and fadeIn() on mouseout() (on a
 component), I am not getting the results that I am expecting. What happens is that sometimes when the mouse is not on the object, the buttons that I want to fadeOut() just keep fading in and out in a loop and sometimes the loop stops and sometimes it doesn't.

What is the proper way of using fadeOut and fadeIn with mouseover and mouseout?

here is the code:

comment.onmouseout = function() {mouseOut(comment);};
comment.onmouseover = function() {mouseOver(comment);};

where comment is a basic
 with buttons as children

function mouseOut(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeOut();
        }
    }
}
function mouseOver(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeIn();
        }
    }
}

Body:
That happens because when the opacity reaches 0 the display is set to none. so the element disappears, trigerring the mouseout.

quote from .fadeOut()

The .fadeOut() method animates the
  opacity of the matched elements. Once
  the opacity reaches 0, the display
  style property is set to none, so the
  element no longer affects the layout
  of the page.

So it would be better to animate the opacity instead

instead of fadeout

$(children.item(i)).animate({opacity:0},  400);

and instead of fadein

$(children.item(i)).animate({opacity:1},400);

another issue is that the animations get queued. So you would be better to stop the current animation before starting the next.

instead of fadeout

$(children.item(i)).stop().animate({opacity:0},  400);

and instead of fadein

$(children.item(i)).stop().animate({opacity:1},400);

If you could post your HTML it would be easier to post pure jquery code to handle the whole issue.


问:
Cannot read property 'Promise' of undefined in ice demo
https://doc.zeroc.com/display/Ice36/Writing+an+Ice+Application+with+JavaScript

Just the official website example,when I run node Client.js，

```<code>Ice.Promise.try(
   ^

TypeError: Cannot read property 'Promise' of undefined
    at Object.<anonymous> (/home/lanceloft/learn/ice/Client.js:6:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3
</code>```

system： ubuntu16.04

答:
Looks like a bug in the documentation, require("icejs") should be replaced with require("ice"). Can you try to see if that fixes your problem?

We'll fix the documentation! Otherwise, you can take a look at the JavaScript demos here for some starting points> https://github.com/zeroc-ice/ice-demos/tree/3.6/js

Benoit.

Body:
https://doc.zeroc.com/display/Ice36/Writing+an+Ice+Application+with+JavaScript

Just the official website example,when I run node Client.js，

Ice.Promise.try(
   ^

TypeError: Cannot read property 'Promise' of undefined
    at Object.<anonymous> (/home/lanceloft/learn/ice/Client.js:6:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

system： ubuntu16.04


问:
javascript merge array of objects, resulting object values in array
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

```<code>[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]
</code>```

to this:

```<code>{
  a: [1, 1],
  b: [2],
  c: [3]
}
</code>```

答:
without loadash:</p>

```<code>  var t = [{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}];
var result = {};
debugger;
for(var i=0; i<t.length; i++){
    for(var j in t[i]){
        if(result.hasOwnProperty(j)){
            result[j].push(t[i][j]);
        }else{
            result[j] = [t[i][j]];
        }
    }
}
console.log(result);
</code>```

Body:
Would like to merge an array of objects resulting in an object of unique keys and array of values (duplication of values is ok). Solutions in vanilla JS or lodash preferred.

eg - from this:

[{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}]

to this:

{
  a: [1, 1],
  b: [2],
  c: [3]
}

Body:
without loadash:

  var t = [{
  a: 1,
  b: 2
}, {
  a: 1,
  c: 3
}];
var result = {};
debugger;
for(var i=0; i<t.length; i++){
    for(var j in t[i]){
        if(result.hasOwnProperty(j)){
            result[j].push(t[i][j]);
        }else{
            result[j] = [t[i][j]];
        }
    }
}
console.log(result);


问:
How to set different background color of every three html table rows in alternate
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

Any help is appreciated]1

答:
You can separate the header and body and use nth-child concept

<!DOCTYPE html>

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    a
    b
    c

    a
    b
    c

    a
    b
    c

```

Body:
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    a
    b
    c

    a
    b
    c

    a
    b
    c

Any help is appreciated]1

Body:
You can separate the header and body and use nth-child concept

<!DOCTYPE html>
<html>
<head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

table tbody tr:nth-child(6n+1),table tbody tr:nth-child(6n+2),table tbody
tr:nth-child(6n+3) {
     background: #dddddd;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 1px;
}

</style>
</head>
<body>

<table id="table2">
<thead>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
</thead>
<tbody>
  <tr bgcolor="#dddddd">
    <td >Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td >Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td >Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td >Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td >Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td >Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
<tbody>
</table>

</body>
</html>


问:
How to subtract from list of numbers individually?
What I want to do is subtract from list on numbers just one number.
For example I have in a table following numbers and I want to subtract 4000:

```<code><table>
<thead>
   <tr>
      <td>result</td>
      <td>start</td>
   <tr>
</thead>
<tbody>
   <tr>
      <td>0</td>
      <td>3000</td>
   </tr>
   <tr>
      <td>0</td>
      <td>3500</td>
   </tr>
   <tr>
      <td>0</td>
      <td>4000</td>
   </tr>
</tbody>
</table>
</code>```

A perfect result would look like this:

```<code><table>
<thead>
   <tr>
      <td>result</td>
      <td>start</td>
   <tr>
</thead>
   <tbody>
   <tr>
      <td>0</td>
      <td>3000</td>
   </tr>
   <tr>
      <td>2500</td>
      <td>3500</td>
   </tr>
   <tr>
      <td>4000</td>
      <td>4000</td>
   </tr>
   </tbody>
</table>
</code>```

Here's a link what I've tried already:

http://jsfiddle.net/tiitremmel/LBjVJ/9/

答:
Does this do what you want?  jsFiddle

EDIT: New Version!

```<code>var subtract = 4000;

$('#tbl tbody tr').each(function(){
    var value = parseInt($(this).find('td:eq(1)').text());
    var $result = $(this).find('td:eq(0)');

    if(subtract >= value){
        $result.text(0);
        subtract -= value;
    }
    else if(subtract <= 0){
        $result.text(value);
    }
    else{
        $result.text(value-subtract);
        subtract -= value;
    }
});
</code>```

Body:
What I want to do is subtract from list on numbers just one number.
For example I have in a table following numbers and I want to subtract 4000:

      result
      start

      0
      3000

      0
      3500

      0
      4000

A perfect result would look like this:

      result
      start

      0
      3000

      2500
      3500

      4000
      4000

Here's a link what I've tried already:

http://jsfiddle.net/tiitremmel/LBjVJ/9/

Body:
Does this do what you want?  jsFiddle

EDIT: New Version!

var subtract = 4000;

$('#tbl tbody tr').each(function(){
    var value = parseInt($(this).find('td:eq(1)').text());
    var $result = $(this).find('td:eq(0)');

    if(subtract >= value){
        $result.text(0);
        subtract -= value;
    }
    else if(subtract <= 0){
        $result.text(value);
    }
    else{
        $result.text(value-subtract);
        subtract -= value;
    }
});


问:
ERR_TOO_MANY_REDIRECTS in PHP
My logout.php file is like this. Is there any mistake in my code

logout.php

```<code><?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>
</code>```

Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.

```<code><?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}
else
{
  $wrong = '';
  if(isset($_POST['submit']))
  {
    $checkLogin = "SELECT userName,password,userType
                     FROM user
                    WHERE BINARY userName = '".$_POST['userName']."'
                      AND BINARY password = '".$_REQUEST['password']."'";
    $checkLoginresult = mysql_query($checkLogin);
    if($userLoginRow = mysql_fetch_array($checkLoginresult))
    {
      $_SESSION['s_activId']   = $userLoginRow['userName'];
      $_SESSION['s_password']  = $userLoginRow['password'];
      $_SESSION['hg_userType'] = $userLoginRow['userType'];

     if(!$_SESSION['s_urlRedirectDir'])
      {
        header("Location:index.php");
      }
      else
      {
        header("Location:reminder.php");
      }
    }
    else
    {
      $wrong = "UserId And Password Is Not Valid";
    }
  }
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>
</code>```

答:
The problem arise in the condition below in index.php:

```<code>if(!isset($_SESSION['s_activId']))
{
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}
</code>```

When you logout, you are calling session_destroy() on logout.php and redirecting on index.php and the condition above gets true as s_activId is not set in session and again you are redirecting on index.php (without setting s_activId in session). The above condition will be true until the variable s_activId set in session and because of this you are getting ERR_TOO_MANY_REDIRECTS error.

The solution is, on index.php set the variable s_activId in session before calling the header method. Refer the code below:

```<code>if(!isset($_SESSION['s_activId']))
{
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    $_SESSION['s_activId'] = true;
    header("Location:index.php");
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: ERR_TOO_MANY_REDIRECTS in PHP

Body:
My logout.php file is like this. Is there any mistake in my code

logout.php

<?php
session_start();
session_destroy();
header('Location:index.php');
exit;
?>

Here is my index.php file. If I am set $_SESSION['s_activId'] then it is working properly but when I am trying to put condition if $_SESSION['s_activId'] is not set at that time I want to pass header on index page sometimes it works sometimes it does not work.

<?php
include('include/config.inc.php');
if(!isset($_SESSION['s_activId']))
{
  $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}
else
{
  $wrong = '';
  if(isset($_POST['submit']))
  {
    $checkLogin = "SELECT userName,password,userType
                     FROM user
                    WHERE BINARY userName = '".$_POST['userName']."'
                      AND BINARY password = '".$_REQUEST['password']."'";
    $checkLoginresult = mysql_query($checkLogin);
    if($userLoginRow = mysql_fetch_array($checkLoginresult))
    {
      $_SESSION['s_activId']   = $userLoginRow['userName'];
      $_SESSION['s_password']  = $userLoginRow['password'];
      $_SESSION['hg_userType'] = $userLoginRow['userType'];

     if(!$_SESSION['s_urlRedirectDir'])
      {
        header("Location:index.php");
      }
      else
      {
        header("Location:reminder.php");
      }
    }
    else
    {
      $wrong = "UserId And Password Is Not Valid";
    }
  }
}
include("bottom.php");
$smarty->assign('wrong',$wrong);
$smarty->display("index.tpl");
?>

Body:
The problem arise in the condition below in index.php:

if(!isset($_SESSION['s_activId']))
{
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    header("Location:index.php");
}

When you logout, you are calling session_destroy() on logout.php and redirecting on index.php and the condition above gets true as s_activId is not set in session and again you are redirecting on index.php (without setting s_activId in session). The above condition will be true until the variable s_activId set in session and because of this you are getting ERR_TOO_MANY_REDIRECTS error.

The solution is, on index.php set the variable s_activId in session before calling the header method. Refer the code below:

if(!isset($_SESSION['s_activId']))
{
    $_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
    $_SESSION['s_activId'] = true;
    header("Location:index.php");
}


问:
How can I print a list of characters in a string using a for loop?
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

```<code>string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}
</code>```

I know this code is not correct. Can anyone help me out?

答:
If you'd like to go from "A" to "Z" then you can use a simple for loop with char.

```<code>for (char a = 'A'; a <= 'Z'; a++)
{
    Console.WriteLine(a);
}
</code>```

Body:
I want to print the all the characters from A to Z to display using for loop. This is what I have got so far:

string alpha = "A";

for(int i=0; i <= 25 ; i++)
{
   Console.WriteLine(Convert.ToChar(alpha[i] + 1));
}

I know this code is not correct. Can anyone help me out?

Body:
If you'd like to go from "A" to "Z" then you can use a simple for loop with char.

for (char a = 'A'; a <= 'Z'; a++)
{
    Console.WriteLine(a);
}


问:
String pattern delimiter
I have this code:

```<code>string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = @"\s?(\d+)([-])(\d+)";
</code>```

And I would like to know if there is any way to put the delimiter in the pattern instead of the ([-]) ?

答:
You could use string interpolation:

```<code>string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = $@"\s?(\d+)([{delimiter}])(\d+)";
</code>```

The $ sign (which has to be in front of the @) makes it possible to put a variable (string) in a string by using { }

Note: In older versions of C# however this will not work

In this case you can use string.Format:

```<code>string.Format(@"\s?(\d+)([{0}])(\d+)", delimiter);
</code>```

This works the same way but uses number placeholders for the parameters after the ,

Regex.Escape: (Credits to NtFreX)

Additionally if you are using regex you should escape your character (because they can mean something else in regex).

```<code>$@"\s?(\d+)([{Regex.Escape( delimiter.ToString() )}])(\d+)";
</code>```

Title: String pattern delimiter

Body:
I have this code:

string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = @"\s?(\d+)([-])(\d+)";

And I would like to know if there is any way to put the delimiter in the pattern instead of the ([-]) ?

Body:
You could use string interpolation:

string first = "2-18;1-4; 5-212; 4-99" ;
Char delimiter = '-';

String pattern = $@"\s?(\d+)([{delimiter}])(\d+)";

The $ sign (which has to be in front of the @) makes it possible to put a variable (string) in a string by using { }

Note: In older versions of C# however this will not work

In this case you can use string.Format:

string.Format(@"\s?(\d+)([{0}])(\d+)", delimiter);

This works the same way but uses number placeholders for the parameters after the ,

Regex.Escape: (Credits to NtFreX)

Additionally if you are using regex you should escape your character (because they can mean something else in regex).

$@"\s?(\d+)([{Regex.Escape( delimiter.ToString() )}])(\d+)";


问:
Reconfiguring the DNS to show the SSL certificate online?
So, I am trying to get the SSL certificate to show up on my website but even after following all the steps from the aws documentation and various internet tutorials. The SSL lock sign is still not visible up on my website.

I found this website really helpful and tried to follow all the steps listed there : https://blog.webinista.com/2016/02/enable-https-cloudfront-certificate-manager-s3/index.html

What I think the problem is that I am not quite certain how to reconfigure the DNS server after creating the cloudfront distribution. In this instance, I just created an alias target for my domain name (shamveelahammed.com) to point towards the cloudfront distribution. But this hasn't worked at all for me. At the moment, I only have 4 entries in my domain record set.
https://www.dropbox.com/s/5g2nkyxip1c22oo/Screen%20Shot%202017-07-05%20at%2002.05.31.png?dl=0

Any help with figuring out my next steps will be massively appreciated. (N.B I am very new to this and still learning how to use AWS.)

答:
As you have restricted bucket access when creating cloudfront .So you dont need the additional alias record for s3 in Route53. you have to generate certificate for both domains www.shamveelahammed.com and shamveelahammed.com OR you can generate wildcard certificate for your domain as *.shamveelahammed.com .  </p>

<p>In your case it seems you have generated certificate only for www.shamveelahammed.com Domain only. </p>

Body:
As you have restricted bucket access when creating cloudfront .So you dont need the additional alias record for s3 in Route53. you have to generate certificate for both domains www.shamveelahammed.com and shamveelahammed.com OR you can generate wildcard certificate for your domain as *.shamveelahammed.com .

In your case it seems you have generated certificate only for www.shamveelahammed.com Domain only.


问:
Why do we use functionName: function in javascript return statement
I am completely new to javascript. I saw the below snippet in a tutorial. But i am not sure why do we use funtionName: function  in return statement.

For example, getID:function()  and setID: function() in the below code. Can anybody explain.

```<code>function celebrityID () {
    var celebrityID = 999;

    return {
        getID: function ()  {

          return celebrityID;
        },
        setID: function (theNewID)  {

            celebrityID = theNewID;
        }
    }

}
</code>```

答:
So they can use it as

```<code>var cid = celebrityID();
var celbId = cid.getID();
</code>```

If you do not have the return statement the function getID() will not be useful and also celbId becomes undefined.

If you closely observe, there is no return statement for setter.

Body:
I am completely new to javascript. I saw the below snippet in a tutorial. But i am not sure why do we use funtionName: function  in return statement.

For example, getID:function()  and setID: function() in the below code. Can anybody explain.

function celebrityID () {
    var celebrityID = 999;

    return {
        getID: function ()  {

          return celebrityID;
        },
        setID: function (theNewID)  {

            celebrityID = theNewID;
        }
    }

}

Body:
So they can use it as

var cid = celebrityID();
var celbId = cid.getID();

If you do not have the return statement the function getID() will not be useful and also celbId becomes undefined.

If you closely observe, there is no return statement for setter.


问:
Powermail ext doesn't include css files needed for date picker
TYPO3 7.6.15
Powermail 3.18.0

The date picker field does not open the popup calendar. I have narrowed down the cause being because the necessary CSS files are not being included for this feature. Is there an error in my setup? How do I have them included automatically?

This is what I have in my TS Setup:

```<code>plugin.tx_powermail {
  view {
    templateRootPaths >
    templateRootPaths {
      0 = {$plugin.tx_powermail.view.templateRootPath}
      1 = fileadmin/template/mysite/powermail/Templates/
    }
    partialRootPaths >
    partialRootPaths {
      0 = {$plugin.tx_powermail.view.partialRootPath}
      1 = fileadmin/template/mysite/powermail/Partials/
    }
    layoutRootPaths >
    layoutRootPaths {
      0 = {$plugin.tx_powermail.view.layoutRootPath}
      1 = fileadmin/template/mysite/powermail/Layouts/
    }
  }
  _LOCAL_LANG.default {
    datepicker_format_date = d/m/Y
    datepicker_format_time = H:i
    datepicker_format_datetime = d/m/Y H:i
  }
}
</code>```

The only way I have found to make it work correctly is by manually adding it like this:

```<code>page.includeCSS {
  file4 = EXT:powermail/Resources/Public/Css/Basic.css
}
</code>```

答:
in the Documentation ist a hint:

https://docs.typo3.org/typo3cms/extensions/powermail/ForAdministrators/Installation/Index.html#addbootstrapclassesandcsstopowermail

you should

add the static template Add classes and CSS based on bootstrap (powermail)

There the css is included

Body:
TYPO3 7.6.15
Powermail 3.18.0

The date picker field does not open the popup calendar. I have narrowed down the cause being because the necessary CSS files are not being included for this feature. Is there an error in my setup? How do I have them included automatically?

This is what I have in my TS Setup:

plugin.tx_powermail {
  view {
    templateRootPaths >
    templateRootPaths {
      0 = {$plugin.tx_powermail.view.templateRootPath}
      1 = fileadmin/template/mysite/powermail/Templates/
    }
    partialRootPaths >
    partialRootPaths {
      0 = {$plugin.tx_powermail.view.partialRootPath}
      1 = fileadmin/template/mysite/powermail/Partials/
    }
    layoutRootPaths >
    layoutRootPaths {
      0 = {$plugin.tx_powermail.view.layoutRootPath}
      1 = fileadmin/template/mysite/powermail/Layouts/
    }
  }
  _LOCAL_LANG.default {
    datepicker_format_date = d/m/Y
    datepicker_format_time = H:i
    datepicker_format_datetime = d/m/Y H:i
  }
}

The only way I have found to make it work correctly is by manually adding it like this:

page.includeCSS {
  file4 = EXT:powermail/Resources/Public/Css/Basic.css
}


问:
Shared memory ignores read only flag in Linux c
I'm using shared memory with shmget and shmat for educational purpose.

I'm trying to make a memory chunk to be mutable only by it's creator and all other processes can read only.

But the reader processes can somehow write without any error.

This is my code for the creator of the shared memory:

```<code>#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(){
    int shmid = shmget((key_t)56666, 1, IPC_CREAT | O_RDONLY);
     if (shmid ==-1) {
        perror("Err0:");
        exit(EXIT_FAILURE);
    }
    void* shmaddr = shmat(shmid, (void *)0,0);
    if (shmaddr == (void *)-1) {
        perror("Err:");
        exit(EXIT_FAILURE);
    }
    *(char*)shmaddr = 'a';
    putchar(*(char*)shmaddr);
    while(1);
    return 0;
}
</code>```

And this is my code for the reader:

```<code>#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(){
    int shmid = shmget((key_t)56666, 4, O_RDONLY);
     if (shmid ==-1) {
        perror("Err0:");
        exit(EXIT_FAILURE);
    }
    void* shmaddr = shmat(shmid, (void *)0,0);
    if (shmaddr == (void *)-1) {
        perror("Err:");
        exit(EXIT_FAILURE);
    }
    *(char*)shmaddr = 'b';
    putchar(*(char*)shmaddr);
    return 0;
}
</code>```

As you can see the reader can edit the memory but no error occures even though I open the memory as read only in the reader and created it with read only flag in the creator of the shared memory.

答:
I have not seen any of O_RDONLY or SHM_RDONLY documented as flags for the shmat(2) system call in the linux or freebsd manual pages.  Probably the problem is misuse or a misunderstanding on how it works.  More on this at the end, as after trying I see that SHM_RDONLY is the flag you should use to control read only attachment, instead of O_RDONLY (which is of no use here)

Probably you have to specify permission bits in the creation shmget(2) system call to disable access for other user's processes, to implement what you want.  With permissions, it does work, or you'd have serious security problems with systems that use shared memory (e.g. postgresql database uses sysvipc shared memory segments)

To my knowledge, the best way to implement is to run the writer of the shared memory segment as some user, and the processes allowed to read it as different users, adjusting the permission bits to allow them to read but not to write on the shared memory segment.  Something like having all the processes in the same group id, with the writer process as the user who creates the shared memory segment and the others having only read access, with no permissions to other user ids, would be enough for any application.

```<code>shmget((key_t)56666, 1, IPC_CREAT | 0640);
</code>```

and running the other processes as other different user in the same group id.

EDIT

after testing your code in a freebsd machine (sorry, no linux available, but ipc calls are SysV AT&T unix calls, so everything should be compatible) the creation process stops on error on shmat(2) call with the following message:

```<code>$ shm_creator
Err:: Permission denied
</code>```

most probably because you didn't give permissions on shared memory creation, even to the owner (and I try to imagine you are not developing as root in your machine, are you? ;) )

ipcs(1) shows:

```<code>usr1@host ~$ ipcs -m
Shared Memory:
T           ID          KEY MODE        OWNER    GROUP
m        65537        56666 ----------- usr1     usr1
</code>```

and you see there are no permission bits active for the shared memory segment, but it has been created.  I have modified your program to, instead of doing busywait in a while(1); loop, doing a non consuming cpu wait with sleep(3600); that will put it to sleep for a whole hour.

shm_creator.c

```<code>#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main(){
    int shmid = shmget((key_t)56666, 1, IPC_CREAT | 0640 );
     if (shmid ==-1) {
        perror("Err0:");
        exit(EXIT_FAILURE);
    }
    void* shmaddr = shmat(shmid, (void *)0,0);
    if (shmaddr == (void *)-1) {
        perror("Err:");
        exit(EXIT_FAILURE);
    }
    *(char*)shmaddr = 'a';
    putchar(*(char*)shmaddr);
    puts("");
    sleep(3600);
    return 0;
}
</code>```

which I run as user usr1:

```<code>usr1@host:~/shm$ shm_creator &
[2] 76950
a
</code>```

then I switch to another user usr2, and run:

```<code>$ su usr2
Password:
[usr2@host /home/usr1/shm]$ shm_client &
[1] 76963
[usr2@host /home/usr1/shm]$ Err:: Permission denied
</code>```

and as you labeled it, it happens in the shmat(2) system call.  But if I run it as usr1 i get:

```<code>usr1@host:~/shm$ shm_client
b
</code>```

if using SHM_RDONLY as flag in the shm_client.c source file, on running (either as same or different user) I get the following:

```<code>usr1@host:~/shm$ shm_client
Segmentation fault (generated `core')
</code>```

which is expected behaviour, as you tried to write unwritable memory (it was attached as read only memory)

EDIT 2

After browsing online the linux manual pages, there's a reference to SHM_RDONLY to allow to attach a shared memory segment as readonly.  No support is offered for write only shared memory segments, otherwise.  As it is not documented on freebsd, this option is also available there (the constant is included in the proper include files) and some other imprecisions are found in the freebsd manual (as the use of S_IROWN, S_IWOWN, S_IRGRP, S_IWGRP, S_IROTH and S_IWOTH flags to control the permission bits and no inclusion of #include <sys/stat.h> in the SYNOPSIS of the manual page)

CONCLUSSION

If the SHM_RDONLY is available in your system, then you can use it as a non-preemptive way to disallow write access to you shared memory, but if you want kernel enforced way, you have to switch to the user permission bits approach.

Body:
I'm using shared memory with shmget and shmat for educational purpose.

I'm trying to make a memory chunk to be mutable only by it's creator and all other processes can read only.

But the reader processes can somehow write without any error.

This is my code for the creator of the shared memory:

#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(){
    int shmid = shmget((key_t)56666, 1, IPC_CREAT | O_RDONLY);
     if (shmid ==-1) {
        perror("Err0:");
        exit(EXIT_FAILURE);
    }
    void* shmaddr = shmat(shmid, (void *)0,0);
    if (shmaddr == (void *)-1) {
        perror("Err:");
        exit(EXIT_FAILURE);
    }
    *(char*)shmaddr = 'a';
    putchar(*(char*)shmaddr);
    while(1);
    return 0;
}

And this is my code for the reader:

#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(){
    int shmid = shmget((key_t)56666, 4, O_RDONLY);
     if (shmid ==-1) {
        perror("Err0:");
        exit(EXIT_FAILURE);
    }
    void* shmaddr = shmat(shmid, (void *)0,0);
    if (shmaddr == (void *)-1) {
        perror("Err:");
        exit(EXIT_FAILURE);
    }
    *(char*)shmaddr = 'b';
    putchar(*(char*)shmaddr);
    return 0;
}

As you can see the reader can edit the memory but no error occures even though I open the memory as read only in the reader and created it with read only flag in the creator of the shared memory.

Body:
I have not seen any of O_RDONLY or SHM_RDONLY documented as flags for the shmat(2) system call in the linux or freebsd manual pages.  Probably the problem is misuse or a misunderstanding on how it works.  More on this at the end, as after trying I see that SHM_RDONLY is the flag you should use to control read only attachment, instead of O_RDONLY (which is of no use here)

Probably you have to specify permission bits in the creation shmget(2) system call to disable access for other user's processes, to implement what you want.  With permissions, it does work, or you'd have serious security problems with systems that use shared memory (e.g. postgresql database uses sysvipc shared memory segments)

To my knowledge, the best way to implement is to run the writer of the shared memory segment as some user, and the processes allowed to read it as different users, adjusting the permission bits to allow them to read but not to write on the shared memory segment.  Something like having all the processes in the same group id, with the writer process as the user who creates the shared memory segment and the others having only read access, with no permissions to other user ids, would be enough for any application.

shmget((key_t)56666, 1, IPC_CREAT | 0640);

and running the other processes as other different user in the same group id.

EDIT

after testing your code in a freebsd machine (sorry, no linux available, but ipc calls are SysV AT&T unix calls, so everything should be compatible) the creation process stops on error on shmat(2) call with the following message:

$ shm_creator
Err:: Permission denied

most probably because you didn't give permissions on shared memory creation, even to the owner (and I try to imagine you are not developing as root in your machine, are you? ;) )

ipcs(1) shows:

usr1@host ~$ ipcs -m
Shared Memory:
T           ID          KEY MODE        OWNER    GROUP
m        65537        56666 ----------- usr1     usr1

and you see there are no permission bits active for the shared memory segment, but it has been created.  I have modified your program to, instead of doing busywait in a while(1); loop, doing a non consuming cpu wait with sleep(3600); that will put it to sleep for a whole hour.

shm_creator.c

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

int main(){
    int shmid = shmget((key_t)56666, 1, IPC_CREAT | 0640 );
     if (shmid ==-1) {
        perror("Err0:");
        exit(EXIT_FAILURE);
    }
    void* shmaddr = shmat(shmid, (void *)0,0);
    if (shmaddr == (void *)-1) {
        perror("Err:");
        exit(EXIT_FAILURE);
    }
    *(char*)shmaddr = 'a';
    putchar(*(char*)shmaddr);
    puts("");
    sleep(3600);
    return 0;
}

which I run as user usr1:

usr1@host:~/shm$ shm_creator &
[2] 76950
a

then I switch to another user usr2, and run:

$ su usr2
Password:
[usr2@host /home/usr1/shm]$ shm_client &
[1] 76963
[usr2@host /home/usr1/shm]$ Err:: Permission denied

and as you labeled it, it happens in the shmat(2) system call.  But if I run it as usr1 i get:

usr1@host:~/shm$ shm_client
b

if using SHM_RDONLY as flag in the shm_client.c source file, on running (either as same or different user) I get the following:

usr1@host:~/shm$ shm_client
Segmentation fault (generated `core')

which is expected behaviour, as you tried to write unwritable memory (it was attached as read only memory)

EDIT 2

After browsing online the linux manual pages, there's a reference to SHM_RDONLY to allow to attach a shared memory segment as readonly.  No support is offered for write only shared memory segments, otherwise.  As it is not documented on freebsd, this option is also available there (the constant is included in the proper include files) and some other imprecisions are found in the freebsd manual (as the use of S_IROWN, S_IWOWN, S_IRGRP, S_IWGRP, S_IROTH and S_IWOTH flags to control the permission bits and no inclusion of #include <sys/stat.h> in the SYNOPSIS of the manual page)

CONCLUSSION

If the SHM_RDONLY is available in your system, then you can use it as a non-preemptive way to disallow write access to you shared memory, but if you want kernel enforced way, you have to switch to the user permission bits approach.


问:
Authenticate and Authorise in Both MVC and Http AuthorizeAttribute
I get follow scenario which is working now:

MVC controller using System.Web.Mvc.AuthorizeAttribute to authenticate user is authenticated or not, it will be using cookie.

API controller using System.Web.Http.AuthorizeAttribute to authorise with bearer token.

I do also have angular http interceptor that verify and get bearer token for API purpose that can use among all angular $http request. But I am confusing how to achieve both after user has login?

This is current workflow

User click login, angular verify and store bears token in local storage.

After complete, manually trigger MVC controller so that it will get cookie for MVC authenticate.

This seem to me really double job, or I should focusing on using one AuthorizeAttribute?

答:
You need you use Authorize key to give permission to those functions where authorization is needed. And those functions can only be accessed when authorization token is generated and passed with http request.

```<code>module.service('tokenservice', function ($http) {
this.get = function () {
    var accesstoken = sessionStorage.getItem('accessToken');
    var logged_in = localStorage.getItem('logged_in').toString().trim() === 'false' ? false : true;
    var authHeaders = {};
    if (accesstoken && logged_in) {
        authHeaders.Authorization = 'Bearer ' + accesstoken;
    }

    return authHeaders;
};
});

module.controller('yourControllerName', function ( $http, tokenservice) {
    $http({
        method: "POST",
        url: '/Controller/MyFucntion',
        headers: tokenservice.get(),
    });
});
</code>```

This will help you to get generated token in user login. After that You need to work with your controller

```<code>[Authorize]
public JsonResult MyFucntion()
{
    //Your logic and calculation
    //return
}
</code>```

Hope that will help

Body:
You need you use Authorize key to give permission to those functions where authorization is needed. And those functions can only be accessed when authorization token is generated and passed with http request.

module.service('tokenservice', function ($http) {
this.get = function () {
    var accesstoken = sessionStorage.getItem('accessToken');
    var logged_in = localStorage.getItem('logged_in').toString().trim() === 'false' ? false : true;
    var authHeaders = {};
    if (accesstoken && logged_in) {
        authHeaders.Authorization = 'Bearer ' + accesstoken;
    }

    return authHeaders;
};
});

module.controller('yourControllerName', function ( $http, tokenservice) {
    $http({
        method: "POST",
        url: '/Controller/MyFucntion',
        headers: tokenservice.get(),
    });
});

This will help you to get generated token in user login. After that You need to work with your controller

[Authorize]
public JsonResult MyFucntion()
{
    //Your logic and calculation
    //return
}

Hope that will help


问:
Asana API - How to add multiple tags when creating task?
As the title says, how do i add multiple asana tags when creating task? I have this </p>

```<code>var task = {
      "data" : {
          "name" : projectName,
          "workspace" : getAsanaWorkspace(),
          "team" : teamId,
          "notes": desc,
          "tags": [{"id: 123245"},{"id: 456987"},{"id: 124589"}]
        }
  };
</code>```

<p>but its not working. </p>

答: Have you tried making the tags list just a list of ids rather than a list of hashes?</p>

Body:
As the title says, how do i add multiple asana tags when creating task? I have this

var task = {
      "data" : {
          "name" : projectName,
          "workspace" : getAsanaWorkspace(),
          "team" : teamId,
          "notes": desc,
          "tags": [{"id: 123245"},{"id: 456987"},{"id: 124589"}]
        }
  };

but its not working.


问:
GWT Keep in sync client and server model
When the user comes to the site, an empty Shopping Cart is created on the client and server side. When he adds a product into the SC a RPC call is done to add the product on the server side. We need to do the same client side to be in sync and update the UI. If we don’t and switch to a view that has a reference to a old SC. The UI won’t be updated accordingly (empty SC whereas there is one product in it).

Solution 1

The RPC call returns the updated SC and do clientSC = returnedSC. It’s not very efficient since it’s a lot of data to transfer over the wire.

Solution 2

The RPC call returns the added product and on the client side, call a method addProduct that add the product to a list instead of storing it in the datastore (like on the server side).

Solution 3

Same as solution 2 but use an event to notify the presenters (I use the MVP pattern) that have a reference to a SC.

Which one is the best, more generally what is the best practice to keep in sync the client and server model?

答:
Use RequestFactory, which comes along with gwt 2.1.

http://code.google.com/webtoolkit/doc/latest/DevGuideRequestFactory.html

RequestFactory makes it easy to
  implement a data access layer on both
  client and server. It allows you to
  structure your server-side code in a
  data-centric way and provides a higher
  level of abstraction than GWT-RPC,
  which is service-oriented rather than
  data-oriented. On the client side,
  RequestFactory keeps track of objects
  that have been modified and sends only
  changes to the server, which results
  in very lightweight network payloads.
  In addition, RequestFactory provides a
  solid foundation for automatic
  batching and caching of requests in
  the future.

RequestFactory uses its own servlet,
  RequestFactoryServlet, and implements
  its own protocol for data exchange
  between client and server. It is not
  designed for general purpose services
  like GWT-RPC, but rather for
  data-oriented services as we will see
  shortly. RequestFactory does not use
  GWT-RPC and is not intended to replace
  it. It is designed specifically for
  implementing a persistence layer on
  both client and server.


问:
Ongoing For Loop - Python
I have a dictionary, with file-/directory paths in it. In the for loop, I do check if the path links to a file or a directory. If it is a directory I have to do the loop again, but one level deeper.

I have to do this until I no longer have any dir paths in the dict.
I do not know how many levels a dir has and I do not want to make redundant code in it.

Can anybody help me?

Example:

```<code># here i do have the top level for loop
for each_path in file_or_dir_paths.keys():
    # then i check if the path links to a dir
    # in dictionary[each_path] the date of the file/dir is stored
    # but this isnt important yet
    status = is_it_dir(each_path, dictionary[each_path])
    # status 0 means an empty dir
    if status == 0:
        del dictionary[each_path]
    # status 1 means a dir with files in it
    if status == 1:
        # and here i do have to do the loop again
        # which is redundant and will get deeper with every loop iteration
        dictionary[each_path] = for_loop_again
    # status 10 means path is a file
    if status == 10:
        # this section is not important right now
        dictionary[each_path] = True
</code>```

答:
It would be better to use Python's buildin function walk(), to traverse the directory structure. walk() will visit all subdirs at any depth. Here's how you can use it.

```<code>from os import walk

# assume variable root contain your root path

for path, dirs, files in walk(root):
   # do what you need to do with the files and dirs
</code>```

If you want to write your own traversal code for some reason, then you would need to use recursion, you cannot have a fixed amount of nested loops (as you seem to suggest)

Title: Ongoing For Loop - Python

Body:
I have a dictionary, with file-/directory paths in it. In the for loop, I do check if the path links to a file or a directory. If it is a directory I have to do the loop again, but one level deeper.

I have to do this until I no longer have any dir paths in the dict.
I do not know how many levels a dir has and I do not want to make redundant code in it.

Can anybody help me?

Example:

# here i do have the top level for loop
for each_path in file_or_dir_paths.keys():
    # then i check if the path links to a dir
    # in dictionary[each_path] the date of the file/dir is stored
    # but this isnt important yet
    status = is_it_dir(each_path, dictionary[each_path])
    # status 0 means an empty dir
    if status == 0:
        del dictionary[each_path]
    # status 1 means a dir with files in it
    if status == 1:
        # and here i do have to do the loop again
        # which is redundant and will get deeper with every loop iteration
        dictionary[each_path] = for_loop_again
    # status 10 means path is a file
    if status == 10:
        # this section is not important right now
        dictionary[each_path] = True

Body:
It would be better to use Python's buildin function walk(), to traverse the directory structure. walk() will visit all subdirs at any depth. Here's how you can use it.

from os import walk

# assume variable root contain your root path

for path, dirs, files in walk(root):
   # do what you need to do with the files and dirs

If you want to write your own traversal code for some reason, then you would need to use recursion, you cannot have a fixed amount of nested loops (as you seem to suggest)


问:
WordPress site malware attack My WordpRESS SITE shown white Blank page
I am updated my Primary domain WordPress Version from 4.7 to 4.8 and after this all of my Addon Domain not live and showing white blank pages. I also got mail from Godaddy that your primary domain has malware attack so please scan and remove it. But I confuse how to scan my Primary Domain in Godaddy Cpanel and remove malware so that all my addon domain will live. I have also not access to all addon domains Wordpress Admin page too. Only primary domain live and access WordPRESS dASHBOARD. If there a solution to solve this issue please submit here and help me to solve it's perfectly. Thanks in Advance.</p>

答:
Install this wordpress plugin, activate it, then register an account, generate an api key, update the malware database definitions and then run a full scan
https://wordpress.org/plugins/gotmls/

This will detect quite a lot of malicious files and malware and provide you with a list with all the infected files. I suggest you manually review each of the files and see if they actually are malware or contain just a bunch of malware code somewhere inside.

Download the latest wordpress version from the official wordpress site:
https://wordpress.org/latest.tar.gz

Extract all the files on your computer and then upload them via FTP on your cpanel account in the public_html/ folder and overwrite the current wordpress files. You basically need to upload wp-admin/ folder, wp-includes folder and wp-content/ folders and the other wp-*.php files (be careful not to overwrite your wp-config.php) file.

Check if after removing the malware and re-uploading the wordpress files from an unaltered wordpress archive makes your site functional again.


问:
How do i use multiple files to access them in viewController?
i am trying to programically create a Stackview that contains a TextField saying "Hello world"

```<code>class stackview: UIViewController {

    func setupview() {

        // Define TextField
        let Textfield = UITextView()
        Textfield.allowsEditingTextAttributes = false
        Textfield.translatesAutoresizingMaskIntoConstraints = false
        Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.isEditable = false

        // Define the stackview, and setting up the attributes
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackview)
        stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        Textfield.text = "hello"

        view.addSubview(Textfield)

    }
</code>```

in my Viewcontroller.swift i want to access this function in ViewDidLoad

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var level = stackview()
        level.setupview()
    }
</code>```

but the Hello world dosnt seem to appear!

答:
Do something like this.

stackview.swift

```<code>import UIKit

class stackview: UIViewController {

    func setupview(myView: UIView) {

        // Define TextField
        let Textfield = UITextView()
        Textfield.allowsEditingTextAttributes = false
        Textfield.translatesAutoresizingMaskIntoConstraints = false
        Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.isEditable = false

        // Define the stackview, and setting up the attributes
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackview)
        stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        Textfield.text = "hello"

        myView.addSubview(Textfield)
    }
</code>```

ViewController.swift

```<code>import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let level = stackview()
        level.setupview(myView: self.view)
    }
}
</code>```

Body:
i am trying to programically create a Stackview that contains a TextField saying "Hello world"

class stackview: UIViewController {

    func setupview() {

        // Define TextField
        let Textfield = UITextView()
        Textfield.allowsEditingTextAttributes = false
        Textfield.translatesAutoresizingMaskIntoConstraints = false
        Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.isEditable = false

        // Define the stackview, and setting up the attributes
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackview)
        stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        Textfield.text = "hello"

        view.addSubview(Textfield)

    }

in my Viewcontroller.swift i want to access this function in ViewDidLoad

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var level = stackview()
        level.setupview()
    }

but the Hello world dosnt seem to appear!

Body:
Do something like this.

stackview.swift

import UIKit

class stackview: UIViewController {

    func setupview(myView: UIView) {

        // Define TextField
        let Textfield = UITextView()
        Textfield.allowsEditingTextAttributes = false
        Textfield.translatesAutoresizingMaskIntoConstraints = false
        Textfield.widthAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.heightAnchor.constraint(equalToConstant: 70).isActive = true
        Textfield.isEditable = false

        // Define the stackview, and setting up the attributes
        let stackview = UIStackView()
        stackview.axis = UILayoutConstraintAxis.horizontal
        stackview.distribution = UIStackViewDistribution.equalCentering
        stackview.alignment = UIStackViewAlignment.center
        stackview.spacing = 5
        stackview.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(stackview)
        stackview.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        stackview.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        Textfield.text = "hello"

        myView.addSubview(Textfield)
    }

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let level = stackview()
        level.setupview(myView: self.view)
    }
}


答:
This is simplest string concatenation. You have several options:

string concatenation:

```<code>Char delimiter = '-';

String pattern = @"\s?(\d+)([" + delimiter + "])(\d+)";
</code>```

string.Format():

```<code>Char delimiter = '-';

String pattern = string.Format(@"\s?(\d+)([{0}])(\d+)", delimiter);
</code>```

new style Format (only works with newer C# versions):

```<code>Char delimiter = '-';

String pattern = $@"\s?(\d+)([{delimiter}])(\d+)";
</code>```

Title: String pattern delimiter

Body:
This is simplest string concatenation. You have several options:

string concatenation:

Char delimiter = '-';

String pattern = @"\s?(\d+)([" + delimiter + "])(\d+)";

string.Format():

Char delimiter = '-';

String pattern = string.Format(@"\s?(\d+)([{0}])(\d+)", delimiter);

new style Format (only works with newer C# versions):

Char delimiter = '-';

String pattern = $@"\s?(\d+)([{delimiter}])(\d+)";


问:
MVC 1 IsValid property equivalent of ModelState.IsValid on the view side
I am trying to display a certain div when an error occur. I'm adding the errors on the controller side and I tried to call the IsValid property of the ViewPage and came up with this error:

```<code>Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
</code>```

Is there a way to verify that easily?

答:
Alright... forget about it.

I just found it under:

```<code>ViewData.ModelState.IsValid
</code>```

Body:
I am trying to display a certain div when an error occur. I'm adding the errors on the controller side and I tried to call the IsValid property of the ViewPage and came up with this error:

Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.

Is there a way to verify that easily?

Body:
Alright... forget about it.

I just found it under:

ViewData.ModelState.IsValid


问:
Android touch event from background service
I would like to generate a scroll event when input is received from an external device connected to Android. Upon receiving the input I would like to call something that either scrolls up or down. I've already taken care of the I/O and now just need to simulate the scroll. Also, this is a service that runs in the background so the scrolling would need to be simulated on whatever is on screen. This is why I thought simulating a touch event would work.

I've been looking at TouchUtils. I'm having doubts because this seems primarily to be used for testing. My application isn't for a test or anything, but rather something that will be permanently connected. Is this the best way to go about doing it? Or is there a better way?

答:
your question is super un-clear.
any way i would suggest you investigate Instrumentation class.
for example:

```<code>Instrumentation m_Instrumentation = new Instrumentation();
m_Instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN, 100, 400, 0));
</code>```

check out this cool article for more

Body:
your question is super un-clear.
any way i would suggest you investigate Instrumentation class.
for example:

Instrumentation m_Instrumentation = new Instrumentation();
m_Instrumentation.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),MotionEvent.ACTION_DOWN, 100, 400, 0));

check out this cool article for more


问:
Regular Expression - 12/22
I want to validate credit card expiration date something like that  Which allows me to input valid current year to future

var regex = /^((0[1-9])|(1[0-2]))\/(0[1-3]|1[0-9])$/

console.log('12/17', regex.test('12/17'))
console.log('12/22', regex.test('12/22'))
console.log('12/25', regex.test('12/25'))
console.log('00/18', regex.test('00/18'))
console.log('01/38', regex.test('01/38'))```

Thank you in advance

Title: Regular Expression - 12/22

Body:
I want to validate credit card expiration date something like that  Which allows me to input valid current year to future

var regex = /^((0[1-9])|(1[0-2]))\/(0[1-3]|1[0-9])$/

console.log('12/17', regex.test('12/17'))
console.log('12/22', regex.test('12/22'))
console.log('12/25', regex.test('12/25'))
console.log('00/18', regex.test('00/18'))
console.log('01/38', regex.test('01/38'))

Thank you in advance

Body:
I think your problem is the year fragment of the regex. Could be something like this?

^(0[1-9]|1[0-2])\/(1[7-9]|[2-4]\d)$

var regex = /^(0[1-9]|1[0-2])\/(1[7-9]|[2-4]\d)$/

console.log('12/25', regex.test('12/25'))
console.log('13/25', regex.test('13/25'))
console.log('01/18', regex.test('01/18'))
console.log('00/18', regex.test('00/18'))
console.log('00/18', regex.test('01/38'))


答:
Adding the static template file would result in a TypoScript like

plugin.tx_powermail.settings.BasicCss
  =EXT:powermail/Resources/Public/Css/Basic.css

this should load everything.
The datepicker styles are originally located in https://github.com/einpraegsam/powermail/blob/develop/Resources/Private/Sass/_DatePicker.scss

Title: Powermail ext doesn't include css files needed for date picker


问:
Java: Convert String to TimeStamp
I have an issue while I try to convert a String to a TimeStamp. I have an array that has the date in the format of yyyy-MM-dd and I want to change it to the format of yyyy-MM-dd HH:mm:ss.SSS. So, I use this code:

```<code>final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;

final DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
final Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);

final Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);
</code>```

and I get the following result.

2009-10-20 00:00:00.000

2009-10-20 00:00:00.0

but when I try to simply do

```<code>final String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);
</code>```

I get the right result:

2011-10-02 18:48:05.123

Do you know what I might be doing wrong?

Thanks for the help.

答:
```<code>DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

Date date = formatter.parse(dateString);

Timestamp timestamp = new Timestamp(date.getTime());

System.out.println(timestamp);
</code>```

Title: Java: Convert String to TimeStamp

Body:
I have an issue while I try to convert a String to a TimeStamp. I have an array that has the date in the format of yyyy-MM-dd and I want to change it to the format of yyyy-MM-dd HH:mm:ss.SSS. So, I use this code:

final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;

final DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
final Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);

final Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);

and I get the following result.

2009-10-20 00:00:00.000

2009-10-20 00:00:00.0

but when I try to simply do

final String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);

I get the right result:

2011-10-02 18:48:05.123

Do you know what I might be doing wrong?

Thanks for the help.


问:
Formatting arrays specifically in PHP
I have the following PHP code on my website:

```<code><?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>
</code>```

And I want it to be output like so:

```<code>("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)
</code>```

for an SQL string, which will be:

```<code>INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);
</code>```

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

答:
you can do using for loops

```<code><?php
$FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
$length = count($FirstName);
for($x=0;$x<$length;$x++)
{
    $custom = array();
    $f = $FirstName[$x];
    $l = $LastName[$x];
    $b = $BirthDay[$x];
    array_push($custom,$f);
    array_push($custom,$l);
    array_push($custom,$b);
    print_r($custom);
}
?>
</code>```

Hope this helps..!

Title: Formatting arrays specifically in PHP

Body:
I have the following PHP code on my website:

<?php
    $FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
?>

And I want it to be output like so:

("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)

for an SQL string, which will be:

INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);

I am quite new to PHP (only started yesterday) and was wondering how I would do this.

Thanks.

Body:
you can do using for loops

<?php
$FirstName = array("Jacob", "Noah", "Frank");
    $LastName = array("Collins", "Little", "Allen");
    $BirthDay = array(19, 31, 06);
$length = count($FirstName);
for($x=0;$x<$length;$x++)
{
    $custom = array();
    $f = $FirstName[$x];
    $l = $LastName[$x];
    $b = $BirthDay[$x];
    array_push($custom,$f);
    array_push($custom,$l);
    array_push($custom,$b);
    print_r($custom);
}
?>

Hope this helps..!


问:
Using fadeOut() and fadeIn() on mouseover and mouseout
My problem is that when I am using fadeOut() on mouseover and fadeIn() on mouseout() (on a
 component), I am not getting the results that I am expecting. What happens is that sometimes when the mouse is not on the object, the buttons that I want to fadeOut() just keep fading in and out in a loop and sometimes the loop stops and sometimes it doesn't.

What is the proper way of using fadeOut and fadeIn with mouseover and mouseout?

here is the code:

```<code>comment.onmouseout = function() {mouseOut(comment);};
comment.onmouseover = function() {mouseOver(comment);};
</code>```

where comment is a basic
 with buttons as children

```<code>function mouseOut(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeOut();
        }
    }
}
function mouseOver(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeIn();
        }
    }
}
</code>```

答: Using mouseenter, mouseleave will solve most of the problems caused by mouseout, mouseover. hover wraps around mouseenter and mouseleave to provide even better handling.

Body:
My problem is that when I am using fadeOut() on mouseover and fadeIn() on mouseout() (on a
 component), I am not getting the results that I am expecting. What happens is that sometimes when the mouse is not on the object, the buttons that I want to fadeOut() just keep fading in and out in a loop and sometimes the loop stops and sometimes it doesn't.

What is the proper way of using fadeOut and fadeIn with mouseover and mouseout?

here is the code:

comment.onmouseout = function() {mouseOut(comment);};
comment.onmouseover = function() {mouseOver(comment);};

where comment is a basic
 with buttons as children

function mouseOut(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeOut();
        }
    }
}
function mouseOver(parent){
    var children = parent.childNodes;
    var i=0;
    for(i=1;i<children.length;i++){
        if(children.item(i).tagName=="INPUT"){
            $(children.item(i)).fadeIn();
        }
    }
}


问:
Buyers structure by registration date query optimisation
I would like to show buyers structure by their registration date e.g.:

```<code>H12016 10.000 buyers
</code>```

from which

```<code>2.000 registered in H12014

4.000 registered in H22014
</code>```

etc.

I have two queries for that:

Number 1 (buyers from H12016 (about 50k records)):

```<code>SELECT DISTINCT
r.idUsera as id_usera

FROM
rezerwacje r

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera
</code>```

Number 2 (users_ids and their registration (insert) date (about 3,8M users)):

```<code>SELECT
m.user_id,
date(m.action_date) as data_insert

FROM
mwids m

WHERE
m.`type` = 'insert'
</code>```

Both queries separately run fine, but when I try to combine them like so:

```<code>SELECT DISTINCT
r.idUsera as id_usera,
t1.data_insert

FROM
rezerwacje r

LEFT JOIN
    (
    SELECT
    m.user_id,
    date(m.action_date) as data_insert

    FROM
    mwids m

    WHERE
    m.`type` = 'insert'
    ) t1 ON t1.user_id = r.idUsera

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera
</code>```

this query runs "indefinetely" and I have to kill it after some time.

I do not belive it should run that long. If the query Number 2 was smaller i.e. about 1M users I could combine results in Excel in matter of seconds. So why is it not possible inside the database? What am I doing wrong?

答:
```<code>SELECT DISTINCT
r.idUsera as id_usera,
t1.data_insert

FROM
rezerwacje r

INNER JOIN
    (
    SELECT
    m.user_id,
    date(m.action_date) as data_insert

    FROM
    mwids m

    WHERE
    m.`type` = 'insert'
    ) t1 ON t1.user_id = r.idUsera

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera
</code>```

Try with INNER JOIN.

Body:
I would like to show buyers structure by their registration date e.g.:

H12016 10.000 buyers

from which

2.000 registered in H12014

4.000 registered in H22014

etc.

I have two queries for that:

Number 1 (buyers from H12016 (about 50k records)):

SELECT DISTINCT
r.idUsera as id_usera

FROM
rezerwacje r

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera

Number 2 (users_ids and their registration (insert) date (about 3,8M users)):

SELECT
m.user_id,
date(m.action_date) as data_insert

FROM
mwids m

WHERE
m.`type` = 'insert'

Both queries separately run fine, but when I try to combine them like so:

SELECT DISTINCT
r.idUsera as id_usera,
t1.data_insert

FROM
rezerwacje r

LEFT JOIN
    (
    SELECT
    m.user_id,
    date(m.action_date) as data_insert

    FROM
    mwids m

    WHERE
    m.`type` = 'insert'
    ) t1 ON t1.user_id = r.idUsera

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera

this query runs "indefinetely" and I have to kill it after some time.

I do not belive it should run that long. If the query Number 2 was smaller i.e. about 1M users I could combine results in Excel in matter of seconds. So why is it not possible inside the database? What am I doing wrong?

Body:
SELECT DISTINCT
r.idUsera as id_usera,
t1.data_insert

FROM
rezerwacje r

INNER JOIN
    (
    SELECT
    m.user_id,
    date(m.action_date) as data_insert

    FROM
    mwids m

    WHERE
    m.`type` = 'insert'
    ) t1 ON t1.user_id = r.idUsera

WHERE
r.dataZalozenia between '2016-01-01' and '2016-07-01'
and r.`status` = 'zabookowana'

ORDER BY
id_usera

Try with INNER JOIN.


答:
You need to tell powermail to load the JavaScript libraries by setting a constant in your TypoScript template:

```<code>plugin.tx_powermail.settings.javascript.addAdditionalJavaScript = 1
</code>```

See https://docs.typo3.org/typo3cms/extensions/powermail/Faq/Index.html#datetimepickernotworking for more information.

Body:
TYPO3 7.6.15
Powermail 3.18.0

The date picker field does not open the popup calendar. I have narrowed down the cause being because the necessary CSS files are not being included for this feature. Is there an error in my setup? How do I have them included automatically?

This is what I have in my TS Setup:

plugin.tx_powermail {
  view {
    templateRootPaths >
    templateRootPaths {
      0 = {$plugin.tx_powermail.view.templateRootPath}
      1 = fileadmin/template/mysite/powermail/Templates/
    }
    partialRootPaths >
    partialRootPaths {
      0 = {$plugin.tx_powermail.view.partialRootPath}
      1 = fileadmin/template/mysite/powermail/Partials/
    }
    layoutRootPaths >
    layoutRootPaths {
      0 = {$plugin.tx_powermail.view.layoutRootPath}
      1 = fileadmin/template/mysite/powermail/Layouts/
    }
  }
  _LOCAL_LANG.default {
    datepicker_format_date = d/m/Y
    datepicker_format_time = H:i
    datepicker_format_datetime = d/m/Y H:i
  }
}

The only way I have found to make it work correctly is by manually adding it like this:

page.includeCSS {
  file4 = EXT:powermail/Resources/Public/Css/Basic.css
}

Body:
You need to tell powermail to load the JavaScript libraries by setting a constant in your TypoScript template:

plugin.tx_powermail.settings.javascript.addAdditionalJavaScript = 1

See https://docs.typo3.org/typo3cms/extensions/powermail/Faq/Index.html#datetimepickernotworking for more information.


问:
How to use OFFSET and Fetch without Order by in SQL Server
I want use OFFSET and Fetch in my SQL server 2012 query.But without any order by.I can not use order by.Because my sort order will be lost.
How can I use OFFSET and Fetch without order by and row number and where in my query?
My 2 select tables have same structure.

```<code>INSERT INTO @TempTable [some columns]
select [some columns] from table1 order by col1
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
select * from @TempTable OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY
</code>```

This query has syntax error at OFFSET keyword.

答:
There is an even simpler way of providing a dummy ORDER BY clause:

select * from @TempTable ORDER BY(SELECT NULL) OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY
```

Body:
I want use OFFSET and Fetch in my SQL server 2012 query.But without any order by.I can not use order by.Because my sort order will be lost.
How can I use OFFSET and Fetch without order by and row number and where in my query?
My 2 select tables have same structure.

INSERT INTO @TempTable [some columns]
select [some columns] from table1 order by col1
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
select * from @TempTable OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY

This query has syntax error at OFFSET keyword.


问:
Cannot resolve constructor and method for reason I don't know
```<code>public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
</code>```

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>
</code>```

MainActivity.java

```<code>package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}
</code>```

AndroidManidest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>
</code>```

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

答:
You just declare method "openNumbers" outside the onCreate method in activity</p>

```<code>public void openNumbers (View view) {
    Intent numbers = new Intent(CurrentActivity.this, NumbersActivity.class);
    startActivity(numbers);
}
</code>```

Body:
public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }

Is there something wrong with these lines of code??? I;ve got red line under the (this, NumbersActivity.class); and it says cannot resolve constuctor 'Intent(......)' and red text startActivity saying cannot re[enter image description here][1]solve method 'startActivity(android.content.Intent)'

I'm a totally new to this

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/tan_background"
    android:orientation="vertical"
    tools:context="com.example.android.miwok.MainActivity">

    <TextView
        android:id="@+id/numbers"
        style="@style/CategoryStyle"
        android:background="@color/category_numbers"
        android:text="@string/category_numbers"
        android:onClick="openNumbers"/>

    <TextView
        android:id="@+id/family"
        style="@style/CategoryStyle"
        android:background="@color/category_family"
        android:text="@string/category_family" />

    <TextView
        android:id="@+id/colors"
        style="@style/CategoryStyle"
        android:background="@color/category_colors"
        android:text="@string/category_colors" />

    <TextView
        android:id="@+id/phrases"
        style="@style/CategoryStyle"
        android:background="@color/category_phrases"
        android:text="@string/category_phrases" />

</LinearLayout>

MainActivity.java

package com.example.android.miwok;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);
    }

    public void openNumbers (View view) {
        Intent numbers = new Intent(this, NumbersActivity.class);
        startActivity(numbers);
    }
}

AndroidManidest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.miwok">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NumbersActivity" >

        </activity>
        <activity android:name=".PhrasesActivity" >

        </activity>
        <activity android:name=".FamilyActivity" >

        </activity>
        <activity android:name=".ColorsActivity">

        </activity>
    </application>

</manifest>

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

I know what is the error already! The error is there are no errors... although AS is showing red font but when i adb the app on my phone its just fine even with red font IDK WHY

Body:
You just declare method "openNumbers" outside the onCreate method in activity

public void openNumbers (View view) {
    Intent numbers = new Intent(CurrentActivity.this, NumbersActivity.class);
    startActivity(numbers);
}