问:
Scrape to get only english text from translated google patent page
```<code>    <section itemprop="claims" itemscope>
   <h2>Claims (<span itemprop="count">20</span>)</h2>
   <aside>Translated from <span itemprop="translatedLanguage">German</span></aside>
   <div itemprop="content" html><div mxw-id="PCLM47023824" lang="DE" load-source="patent-office" class="claims"><div class="claim"><div num="1" class="claim"><div class="claim-text"> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">1. Einrichtung zum Installieren von Versorgungsleitungen und/oder Datenleitungen für mehrere Arbeitsplätze, insbesonde re miteinander und/oder mit einer zentralen Einrichtung ver bundenen Computer-Arbeitsplätze oder dergleichen in einem Räum, <b>dadurch gekennzeichnet</b> , dass ein aus vorbereiteten Ele menten gerüstartig aufbaubares System vorgesehen ist, das un terhalb einer Decke ( <b>12</b> ) des Raumes und oberhalb einer norma len Greifhöhe anbringbare Kanäle ( <b>18</b> , <b>18</b> ') zur Aufnahme von Versorgungsleitungen und/oder Datenleitungen enthält, wobei an die Kanäle ( <b>18</b> , <b>18</b> ') nach unten gerichtete, Arbeitsplätzen zu geordnete Säulen ( <b>21</b> , <b>27</b> ) anschließbar sind, die mit in Greif höhe anzuordnenden Versorgungsanschlüssen ( <b>23</b> ) versehen sind.</span> 1. means for installing supply lines and / or data lines for several jobs, insbesonde re each other and / or with a central facility ver affiliated computer workstations or the like in a cavities, <b>characterized in</b> that a Ele from prepared elements is like a framework to-assemble system provided which 'contains for receiving supply lines and / or data lines, wherein the channels <b>(18,</b> <b>18</b> un terhalb a ceiling <b>(12)</b> of the room and above a norma len picking height attachable channels <b>(18,</b> <b>18)')</b> downward, jobs to subordinate columns <b>(21,</b> <b>27)</b> are connected, which are provided with height in Griffin to be arranged supply terminals <b>(23).</b></span> </div></div></div><div class="claim-dependent"><div num="2" class="claim"> <div class="claim-text"> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">2. Einrichtung nach Anspruch 1, dadurch gekennzeichnet, dass für die Kanäle ( <b>18</b> ) Hängehalter ( <b>19</b> ) zum Aufhängen an der De cke ( <b>12</b> ) des Raumes vorgesehen sind.</span> 2. Device according to claim 1, characterized in that the channels <b>(18)</b> hanging holder <b>(19)</b> for hanging on the De blocks <b>(12)</b> of the space are provided.</span> </div></div></div></div>
 </section>
</code>```

For more reference I you can check source code of this page

The above code is just sample from the above page.
I tried BeautifulSoup(page).findAll('Section')[5].getText(), but it is giving both german and english text.

Can anyone tell me a way to extract only English words either by using functions like BeautifulSoup or by using regular expression?

答:
BeautifulSoup(page).findAll('Section')[5] gets just the content of 6th section tag. You need further parsing. Try doing something like:

```<code>soup = BeautifulSoup(page, 'html.parser')
section = soup.findAll('section')[5]
content = section.find('span', {'class':'notranslate'}) #finds the span with text
eng_text = content.contents[1:] #strips-off German text

print(eng_text[0].strip())
</code>```

Output:

```<code>1. means for installing supply lines and / or data lines for several jobs, insbesonde re each other and / or with a central facility ver affiliated computer workstations or the like in a cavities,
</code>```

Body:
Claims (20)

   Translated from German

 1. Einrichtung zum Installieren von Versorgungsleitungen und/oder Datenleitungen für mehrere Arbeitsplätze, insbesonde re miteinander und/oder mit einer zentralen Einrichtung ver bundenen Computer-Arbeitsplätze oder dergleichen in einem Räum, dadurch gekennzeichnet , dass ein aus vorbereiteten Ele menten gerüstartig aufbaubares System vorgesehen ist, das un terhalb einer Decke ( 12 ) des Raumes und oberhalb einer norma len Greifhöhe anbringbare Kanäle ( 18 , 18 ') zur Aufnahme von Versorgungsleitungen und/oder Datenleitungen enthält, wobei an die Kanäle ( 18 , 18 ') nach unten gerichtete, Arbeitsplätzen zu geordnete Säulen ( 21 , 27 ) anschließbar sind, die mit in Greif höhe anzuordnenden Versorgungsanschlüssen ( 23 ) versehen sind. 1. means for installing supply lines and / or data lines for several jobs, insbesonde re each other and / or with a central facility ver affiliated computer workstations or the like in a cavities, characterized in that a Ele from prepared elements is like a framework to-assemble system provided which 'contains for receiving supply lines and / or data lines, wherein the channels (18, 18 un terhalb a ceiling (12) of the room and above a norma len picking height attachable channels (18, 18)') downward, jobs to subordinate columns (21, 27) are connected, which are provided with height in Griffin to be arranged supply terminals (23).

 2. Einrichtung nach Anspruch 1, dadurch gekennzeichnet, dass für die Kanäle ( 18 ) Hängehalter ( 19 ) zum Aufhängen an der De cke ( 12 ) des Raumes vorgesehen sind. 2. Device according to claim 1, characterized in that the channels (18) hanging holder (19) for hanging on the De blocks (12) of the space are provided.

For more reference I you can check source code of this page

The above code is just sample from the above page.
I tried BeautifulSoup(page).findAll('Section')[5].getText(), but it is giving both german and english text.

Can anyone tell me a way to extract only English words either by using functions like BeautifulSoup or by using regular expression?

Body:
BeautifulSoup(page).findAll('Section')[5] gets just the content of 6th section tag. You need further parsing. Try doing something like:

soup = BeautifulSoup(page, 'html.parser')
section = soup.findAll('section')[5]
content = section.find('span', {'class':'notranslate'}) #finds the span with text
eng_text = content.contents[1:] #strips-off German text

print(eng_text[0].strip())

Output:

1. means for installing supply lines and / or data lines for several jobs, insbesonde re each other and / or with a central facility ver affiliated computer workstations or the like in a cavities,


来源: stackexchange

问:
Dataweave Mulesoft Skip XML tags
I am using dataweave to transform a csv file to xml file. At some places there is no value for a certain xml tag and I am getting an empty tag.

What I want is if there is no value than that tag must not be present in xml at all.

It's a long mapping so I don't want to write the entire mapping in the when otherwise tag but just the mapping for that tag in the when otherwise condition.

Data mapping

```<code>    name: ((payload01.name) when payload01.name != ""
    otherwise {}),
</code>```

Output:
If there is value for name in input

```<code>    <name>Kittu</name>
</code>```

Otherwise

```<code>    <name/>
</code>```

What I want is that in the otherwise condition, no tag should come at all.

All help is appreciated. Thanks.

答:
If you use skipNullOn="everywhere" tag will be there in output field eventhough the it has no value . So it won't work in this case.
Try writing seperate function for checking and skipping the null values with that entire tag.</p>

ContentLicense: CC BY-SA 3.0

Title: Dataweave Mulesoft Skip XML tags

Body:
I am using dataweave to transform a csv file to xml file. At some places there is no value for a certain xml tag and I am getting an empty tag.

What I want is if there is no value than that tag must not be present in xml at all.

It's a long mapping so I don't want to write the entire mapping in the when otherwise tag but just the mapping for that tag in the when otherwise condition.

Data mapping

    name: ((payload01.name) when payload01.name != ""
    otherwise {}),

Output:
If there is value for name in input

    <name>Kittu</name>

Otherwise

    <name/>

What I want is that in the otherwise condition, no tag should come at all.

All help is appreciated. Thanks.


问:
Combine to table without joins
I have two these two tables

TableA

```<code>       Col1 Col2
        1     A
        5     B
        3     A
</code>```

TableB

```<code> Column1 Column2
    11     Aa
    15     Bb
</code>```

How can i get this resultset, while ordering by TableA.col1 desc and TableB.Column1 desc

```<code>       Col1 Col2 Column1 Column2
        1     A    11     Aa
        3     B    15     Bb
        5     A
</code>```

Tried this SELECT * FROM (SELECT*, 1 sortby    FROM TableA ) a,(SELECT *, 2 sortby FROM TableB ) b ORDER BY a.sortby

Thanks in advance

答:
Something like this... (did not test it)</p>

```<code>SELECT
  a.col1,
  a.col2,
  b.column1,
  b.column2
FROM
(
      SELECT
        col1,
        col2,
        ROW_NUMBER() OVER (ORDER BY col1 DESC) AS rownum
      FROM tableA
) AS a
FULL OUTER JOIN
(
      SELECT
        column1,
        column2,
        ROW_NUMBER() OVER (ORDER BY column1 DESC) AS rownum
      FROM tableB
) AS b
ON a.rownum = b.rownum
</code>```

Title: Combine to table without joins

Body:
I have two these two tables

TableA

       Col1 Col2
        1     A
        5     B
        3     A

TableB

 Column1 Column2
    11     Aa
    15     Bb

How can i get this resultset, while ordering by TableA.col1 desc and TableB.Column1 desc

       Col1 Col2 Column1 Column2
        1     A    11     Aa
        3     B    15     Bb
        5     A

Tried this SELECT * FROM (SELECT*, 1 sortby    FROM TableA ) a,(SELECT *, 2 sortby FROM TableB ) b ORDER BY a.sortby

Thanks in advance

Body:
Something like this... (did not test it)

SELECT
  a.col1,
  a.col2,
  b.column1,
  b.column2
FROM
(
      SELECT
        col1,
        col2,
        ROW_NUMBER() OVER (ORDER BY col1 DESC) AS rownum
      FROM tableA
) AS a
FULL OUTER JOIN
(
      SELECT
        column1,
        column2,
        ROW_NUMBER() OVER (ORDER BY column1 DESC) AS rownum
      FROM tableB
) AS b
ON a.rownum = b.rownum


问:
GDax API GET request always returns Error 400
I'm trying to get the order book from GDAX (link to documentation of the call) but when doing it from the c# executable I always get Error 400 - Bad request.

When taking the actual URL and pasting it into my browser, it works fine.

```<code>String URL = "https://api.gdax.com/products/BTC-USD/book?level=2";
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();
</code>```

答:
You need to Accept the certificarte, Google for access to a https webrequest.

Like this

Body:
I'm trying to get the order book from GDAX (link to documentation of the call) but when doing it from the c# executable I always get Error 400 - Bad request.

When taking the actual URL and pasting it into my browser, it works fine.

String URL = "https://api.gdax.com/products/BTC-USD/book?level=2";
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();


问:
Force Inner-iframe Content to Scroll To Top On Pageload
All of my website's 'content pages' open inside of an iframe on my index page.

I am using a onload="scroll(0,0);" code in that iframe which successfully forces all of my 'content pages' to start at the 'top'.

```<code>  <iframe id="iframe_A" name="iframe_A" onload="scroll(0,0);" src="Page1.html"></iframe>
</code>```

So far, so good.

However... within my website, I also have a 'subsite' (which also open's inside of iframe_A), yet has it's own iframe [iframe_B].

All of the subsite's content pages open inside of iframe_B.

All good.... but, unfortunately... I haven't been unable to get the content pages for the subsite's iframe_B to open at the top the same way as they do in iframe_A.

To better illustrate the issue I am having, I have included an extremely stripped down model (6 pages, including the 'Index Page') of the site, to represent the layout I am using.

INDEX PAGE:

```<code><!DOCTYPE html>
<html>
<head>
<style>
body{margin:0;}
.header{width:100%; height:60px; background-color:blue;}
.header a{padding-left:20px; vertical-align:middle; line-height:60px; font-family:Arial; font-size:12pt; color:#ffffff;}
#iframe_A{width:100%; height:1700px;}
.footer{width:100%; height:60px; background-color:blue; margin-bottom:20px;}
.footer a{padding-left:20px; vertical-align:middle; line-height:60px; font-family:Arial; font-size:12pt; color:#ffffff;}
</style>
</head>
<body>

<div class="header"><a>Index Header  </a>
<a href="Page1.html" target="iframe_A">Page 1</a>
<a href="Page2.html" target="iframe_A">Page 2</a>
<a href="Page3.html" target="iframe_A">Page 3</a>
</div>

<iframe id="iframe_A" name="iframe_A" src="Page1.html" scrolling="no" onload="scroll(0,0);"></iframe>

<div class="footer"><a>Index Footer  </a>
<a href="Page1.html" target="iframe_A">Page 1</a>
<a href="Page2.html" target="iframe_A">Page 2</a>
<a href="Page3.html" target="iframe_A">Page 3</a>
</div>

</body>
</html>
</code>```

PAGE 1

```<code><!DOCTYPE html>
<html>
<head>
<style>
body{margin:0px 0px 0px 20px;}
.font{font-family:Arial, Helvetica, sans-serif; font-size:12pt;}
.top{margin-top:10px;}
.bottom{margin-top:1640px;}
</style>
</head>
<body>
<div class="top font">This is Page 1 in iframe_A (Top).</div>
<div class="bottom font">This is Page 1 in iframe_A (Bottom).</div>
</body>
</html>
</code>```

PAGE 2

```<code><!DOCTYPE html>
<html>
<head>
<style>
body{margin:0px 0px 0px 20px;}
.font{font-family:Arial, Helvetica, sans-serif; font-size:12pt;}
.top{margin-top:10px;}
.bottom{margin-top:1640px;}
</style>
</head>
<body>
<div class="top font">This is Page 2 in iframe_A (Top).</div>
<div class="bottom font">This is Page 2 in iframe_A (Bottom).</div>
</body>
</html>
</code>```

PAGE 3

```<code><!DOCTYPE html>
<html>
<head>
<style>
body{margin:0px;}
.header{width:100%; height:60px; background-color:red;}
.header a{padding-left:20px; vertical-align:middle; line-height:60px; font-family:Arial; font-size:12pt; color:#ffffff;}
#iframe_B{width:100%; height:1580px; }
.footer{width:100%; height:60px; background-color:red;}
.footer a{padding-left:20px; vertical-align:middle; line-height:60px; font-family:Arial; font-size:12pt; color:#ffffff;}
</style>
</head>
<body>
<div class="header"><a>Page 3 (Subsite) Header</a>
<a href="Page4.html" target="iframe_B">Page 4</a>
<a href="Page5.html" target="iframe_B">Page 5</a>
</div>
<iframe id="iframe_B" name="iframe_B" src="Page4.html" scrolling="no">
</iframe>
<div class="footer"><a>Page 3 (Subsite) Footer  </a>
<a href="Page4.html" target="iframe_B">Page 4</a>
<a href="Page5.html" target="iframe_B">Page 5</a>
</div>
</body>
</html>
</code>```

PAGE 4

```<code><!DOCTYPE html>
<html>
<head>
<style>
body{margin:0px 0px 0px 20px;}
.font{font-family:Arial, Helvetica, sans-serif; font-size:12pt;}
.top{margin-top:10px;}
.bottom{margin-top:1520px;}
</style>
</head>
<body>
<div class="top font">This is Page 4, in iframe_B (Top).</div>
<div class="bottom font">This is Page 4, in iframe_B (Bottom).</div>
</body>
</html>
</code>```

PAGE 5

```<code><!DOCTYPE html>
<html>
<head>
<style>
body{margin:0px 0px 0px 20px;}
.font{font-family:Arial, Helvetica, sans-serif; font-size:12pt;}
.top{margin-top:10px;}
.bottom{margin-top:1520px;}
</style>
</head>
<body>
<div class="top font">This is Page 5, in iframe_B (Top).</div>
<div class="bottom font">This is Page 5, in iframe_B (Bottom).</div>
</body>
</html>
</code>```

In this model... Pages 1, 2 and 3 always open at the top of the page in iframe_A, no matter what page position you were at on the previous page... as they should.

I am attempting to get content pages 4 and 5 (which open in 'iframe_B' on Page 3), to ALSO open at the top each time.

答:
Try using one of below onload scripts inside your iframe_B html tag:

```<code><iframe id="iframe_B" name="iframe_B" src="Page4.html" scrolling="no" onload="window.top.scrollTo(0,0);">
</code>```

Out of below, mostly the first 2 should work in your case.

```<code>onload="window.top.scrollTo(0,0);" //Refers to the top main window (page)
onload="window.parent.scrollTo(0,0);" //Refers to the immediate parent window (page)
onload="window.parent.parent.scrollTo(0,0);" //Refers to the parent of parent window (page)
</code>```

I just tried it and both the first 2 onload event are working like a charm.

Body:
All of my website's 'content pages' open inside of an iframe on my index page.

I am using a onload="scroll(0,0);" code in that iframe which successfully forces all of my 'content pages' to start at the 'top'.

So far, so good.

However... within my website, I also have a 'subsite' (which also open's inside of iframe_A), yet has it's own iframe [iframe_B].

All of the subsite's content pages open inside of iframe_B.

All good.... but, unfortunately... I haven't been unable to get the content pages for the subsite's iframe_B to open at the top the same way as they do in iframe_A.

To better illustrate the issue I am having, I have included an extremely stripped down model (6 pages, including the 'Index Page') of the site, to represent the layout I am using.

INDEX PAGE:

<!DOCTYPE html>

Index Header
Page 1
Page 2
Page 3

Index Footer
Page 1
Page 2
Page 3

PAGE 1

<!DOCTYPE html>

This is Page 1 in iframe_A (Top).

This is Page 1 in iframe_A (Bottom).

PAGE 2

<!DOCTYPE html>

This is Page 2 in iframe_A (Top).

This is Page 2 in iframe_A (Bottom).

PAGE 3

<!DOCTYPE html>

Page 3 (Subsite) Header
Page 4
Page 5

Page 3 (Subsite) Footer
Page 4
Page 5

PAGE 4

<!DOCTYPE html>

This is Page 4, in iframe_B (Top).

This is Page 4, in iframe_B (Bottom).

PAGE 5

<!DOCTYPE html>

This is Page 5, in iframe_B (Top).

This is Page 5, in iframe_B (Bottom).

In this model... Pages 1, 2 and 3 always open at the top of the page in iframe_A, no matter what page position you were at on the previous page... as they should.

I am attempting to get content pages 4 and 5 (which open in 'iframe_B' on Page 3), to ALSO open at the top each time.

Body:
Try using one of below onload scripts inside your iframe_B html tag:

<iframe id="iframe_B" name="iframe_B" src="Page4.html" scrolling="no" onload="window.top.scrollTo(0,0);">

Out of below, mostly the first 2 should work in your case.

onload="window.top.scrollTo(0,0);" //Refers to the top main window (page)
onload="window.parent.scrollTo(0,0);" //Refers to the immediate parent window (page)
onload="window.parent.parent.scrollTo(0,0);" //Refers to the parent of parent window (page)

I just tried it and both the first 2 onload event are working like a charm.


问:
Cannot implicitly convert type 'double' to 'long'
In this code i got the above error in lines i commented.

```<code>public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter < i.Length; counter++)
    {
        nums[counter] = Convert.ToInt32(i[counter]);
    }

    u = nums[0];
    int firstdigits = Convert.ToInt32(Math.Floor(Math.Log10(u) + 1));
    v = nums[1];
    int seconddigits = Convert.ToInt32(Math.Floor(Math.Log10(v) + 1));
    if (firstdigits >= seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}
</code>```

Whats is the problem? Thanks!

答: You cant' cast implicitly double to long, use (long) cast or change type of variable declaration to double.</p>

ContentLicense: CC BY-SA 2.5

Body:
In this code i got the above error in lines i commented.

public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter = seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}

Whats is the problem? Thanks!


问:
2 jdk on the same machine. Set a specific java version to sonarqube-4.5.7
I have windows 7 OS, java 1.7 and 1.8. Sonar works with 1.8, but I do not want to change my JAVA_HOME environment variable  every time I compile the project with sonar. In a wrapper.conf I set wrapper.java.command=C:/Program Files/Java/jdk1.8.0_131/jre/bin/java but it still doesn't work. Also I changed the settings.xml in a .m2 folder putting

```<code> <profiles>
        <profile>
            <id>jdk8</id>
            <properties>
                <JAVA_HOME>C:\Program Files\Java\jdk1.8.0_131</JAVA_HOME>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
......
</code>```

but without success.

答:
I couldn't resolve this problem, and for that I've created a .bat file witch executes the commands I need.</p>

```<code>echo off
title Ejecuta Sonar

SET PROJECT_HOME=C:\Project\Smarthome

cd %PROJECT_HOME%\xxx\
call mvn clean install

setx -m JAVA_HOME "C:\Program Files\Java\jdk1.8"
setx -m JRE_HOME "C:\Program Files\Java\jre1.8"

cd %PROJECT_HOME%\xxx\
call mvn sonar:sonar

setx -m JAVA_HOME "C:\Program Files\Java\jdk1.7"
setx -m JRE_HOME "C:\Program Files\Java\jre7"

pause
</code>```

Body:
I have windows 7 OS, java 1.7 and 1.8. Sonar works with 1.8, but I do not want to change my JAVA_HOME environment variable  every time I compile the project with sonar. In a wrapper.conf I set wrapper.java.command=C:/Program Files/Java/jdk1.8.0_131/jre/bin/java but it still doesn't work. Also I changed the settings.xml in a .m2 folder putting

 <profiles>
        <profile>
            <id>jdk8</id>
            <properties>
                <JAVA_HOME>C:\Program Files\Java\jdk1.8.0_131</JAVA_HOME>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
......

but without success.

Body:
I couldn't resolve this problem, and for that I've created a .bat file witch executes the commands I need.

echo off
title Ejecuta Sonar

SET PROJECT_HOME=C:\Project\Smarthome

cd %PROJECT_HOME%\xxx\
call mvn clean install

setx -m JAVA_HOME "C:\Program Files\Java\jdk1.8"
setx -m JRE_HOME "C:\Program Files\Java\jre1.8"

cd %PROJECT_HOME%\xxx\
call mvn sonar:sonar

setx -m JAVA_HOME "C:\Program Files\Java\jdk1.7"
setx -m JRE_HOME "C:\Program Files\Java\jre7"

pause


问:
Php/laravel "link_to_route" to JQuery  tag
I have this in Laravel

```<code>  {{ link_to_route('users.publications.create', 'text of link', ['users' => $user->username]) }}
</code>```

What it does is create a "" HTML tag to a view in the site link this:

```<code><a href="http://kinbu.co/users/luis02lopez/publications/create >text of link</a>
</code>```

I want to have the same result in JQuery but it uses the "users" in the link route as other user:

```<code>            var action_call = $({{ link_to_route('users.publications.create', 'publica uno como intercambio',
            ['users' => $user->username], ['style' => 'color:blueviolet']) }}
            });
            body.append(action_call);
</code>```

With which I have the next error: http://imgur.com/a/Lrmbg

Do I need to create other var with the users name?

If any idea will be a great help. Thanks

答:
A solution for get the logged (and principal) user information is:

```<code>Auth::user()->username
</code>```

This bring the data of the logged in user.

Title: Php/laravel "link_to_route" to JQuery <a> tag

Body:
I have this in Laravel

  {{ link_to_route('users.publications.create', 'text of link', ['users' => $user->username]) }}

What it does is create a "" HTML tag to a view in the site link this:

text of link

I want to have the same result in JQuery but it uses the "users" in the link route as other user:

            var action_call = $({{ link_to_route('users.publications.create', 'publica uno como intercambio',
            ['users' => $user->username], ['style' => 'color:blueviolet']) }}
            });
            body.append(action_call);

With which I have the next error: http://imgur.com/a/Lrmbg

Do I need to create other var with the users name?

If any idea will be a great help. Thanks

Body:
A solution for get the logged (and principal) user information is:

Auth::user()->username

This bring the data of the logged in user.


问:
Encrypt / Decrypt Between iOS(swift3), Android and PHP
hello fellow programmers,

It's about ios(Swift3) encrypt/decrypt:
I'm an ios swift beginner. I followed a tutorial at https://www.funboxpower.com/php_android_ios_aes to complete encrypt/decrypt between Android and PHP.

Now I wanna to do the same on iOS(Swift3), the author mentioned ios(object-c) method as this Wanted Compatible AES code Encrypt/Decrypt for Iphone, Android, Windows/XP

so I find CryptoSwift and it help me to encrypt my string. but the result is not same as Android and PHP. How can I do that use iOS(Swift3) with CryptoSwift to encrypt/decrypt like the tutorial(Android/PHP) ?

Here is the code for encryption on Swift:

```<code>import CryptoSwift

class LoginViewController: UIViewController {
   @IBAction func loginAction(sender: AnyObject) {
        let account = self.accountTextField.text
        let password = self.passwordTextField.text

        let key = "itakeylengthtotalis32keykeykey00"
        let iv = "0000000000000000"
        let encryptedAccount = try! account?.aesEncrypt(key:key, iv: iv)
        let encryptedPassword = try! password?.aesEncrypt(key:key, iv: iv)

        //result here ------------------------------
        print( "encryptedAccount: " + encryptedAccount! )
        print( "encryptedPassword: " + encryptedPassword! )
   }
}

extension String {

    func aesEncrypt(key: String, iv: String) -> String? {
        var result: String?
        do {
          // 用UTF8的编碼方式將字串轉成Data / use Data func for a UT8 string
          let data: Data = self.data(using: String.Encoding.utf8, allowLossyConversion: true)!

          // 用AES的方式將Data加密 / use AES to encrypt Data
          let aecEnc: AES = try AES(key: key, iv: iv, blockMode: .CBC, padding:PKCS7())
          let enc = try aecEnc.encrypt(data.bytes)

          // 使用Base64編碼方式將Data轉回字串 / use Base64 to encode string
          let encData: Data = Data(bytes: enc, count: enc.count)
          result = encData.base64EncodedString()
       } catch {
        print("\(error.localizedDescription)")
       }

      return result
}
</code>```

答:
Use Java 8 on Android.

Install Java Cryptography Extension on Android machine.

Check your Base64 class.

Test it here: http://aesencryption.net.

Check what bit is compatible.

Check key size.

Testing tips: Use same (iv)intigrated vector & key on all three platform encrypt from one platform  and try decrypt  on other use harcdoded encrypted decrypted text.

Body:
hello fellow programmers,

It's about ios(Swift3) encrypt/decrypt:
I'm an ios swift beginner. I followed a tutorial at https://www.funboxpower.com/php_android_ios_aes to complete encrypt/decrypt between Android and PHP.

Now I wanna to do the same on iOS(Swift3), the author mentioned ios(object-c) method as this Wanted Compatible AES code Encrypt/Decrypt for Iphone, Android, Windows/XP

so I find CryptoSwift and it help me to encrypt my string. but the result is not same as Android and PHP. How can I do that use iOS(Swift3) with CryptoSwift to encrypt/decrypt like the tutorial(Android/PHP) ?

Here is the code for encryption on Swift:

import CryptoSwift

class LoginViewController: UIViewController {
   @IBAction func loginAction(sender: AnyObject) {
        let account = self.accountTextField.text
        let password = self.passwordTextField.text

        let key = "itakeylengthtotalis32keykeykey00"
        let iv = "0000000000000000"
        let encryptedAccount = try! account?.aesEncrypt(key:key, iv: iv)
        let encryptedPassword = try! password?.aesEncrypt(key:key, iv: iv)

        //result here ------------------------------
        print( "encryptedAccount: " + encryptedAccount! )
        print( "encryptedPassword: " + encryptedPassword! )
   }
}

extension String {

    func aesEncrypt(key: String, iv: String) -> String? {
        var result: String?
        do {
          // 用UTF8的编碼方式將字串轉成Data / use Data func for a UT8 string
          let data: Data = self.data(using: String.Encoding.utf8, allowLossyConversion: true)!

          // 用AES的方式將Data加密 / use AES to encrypt Data
          let aecEnc: AES = try AES(key: key, iv: iv, blockMode: .CBC, padding:PKCS7())
          let enc = try aecEnc.encrypt(data.bytes)

          // 使用Base64編碼方式將Data轉回字串 / use Base64 to encode string
          let encData: Data = Data(bytes: enc, count: enc.count)
          result = encData.base64EncodedString()
       } catch {
        print("\(error.localizedDescription)")
       }

      return result
}


问:
converting date format to yyyy-mm-dd sql server c#
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

```<code>SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID
</code>```

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

答:
Why should you convert the date in sql? You can return it as datetime and then format in your web page using toString

Then in c# you can use:

```<code>  YourDateVar.ToString("yyyy-MM-dd");
</code>```

Body:
I am creating a web app in which i want to convert the date format into yyyy-mm-dd

currently i am getting date in the following format Saturday, July 1, 2017

here is my full select query

SELECT
    ROW_NUMBER() OVER (ORDER BY D.D_ID ) AS SL,
    D.D_DATE, D.USER_TP, D_ITEM_TYPE,D_AUTH_REF,D.D_ID, D.SUR_REFNO, D.REF_NO_DT,
    M.PART_NO,
    S.D_NAME,
    PART_DESC, DENOM, QTY_DEM, STORE_TYPE, ITEM_TYPE, EQUIPMENT,D_NO
FROM SURVEY_HDR D, DEMAND_STATUS S, STORE_MASTER M
WHERE
    M.STORE_ID=D.PART_NO_ID
    AND S.D_ID=D.D_STATUS
    AND D_DATE >= CONVERT(VarChar, 'Saturday, July 1, 2017',1)
    AND D_DATE <= CONVERT(VarChar, 'Monday, July 31, 2017',1)
ORDER BY D.D_ID

but i am getting the following error

Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
  date and/or time from character string.

NOTE

D_DATE is in Date format and date is being stored as '2011-01-01'

how can i convert the date?

Body:
Why should you convert the date in sql? You can return it as datetime and then format in your web page using toString

Then in c# you can use:

  YourDateVar.ToString("yyyy-MM-dd");


问:
how to disable csrf in testing django?
I have a problem testing views with csrf tokens.

This code

```<code>class ViewTests(TestCase):
    def test_bets_view(self):
        login_page = self.client.get('/users/login/')
        print(login_page.content)
</code>```

returns HTML with CSRF hidden input.

And this thing, which I need to compare to the former HTML,

```<code>expected_html = render_to_response('login.html',
                                   dictionary={'form': LoginForm()})
</code>```

doesn't have hidden CSRF input. So the assertion fails.

Ho do I disable CSRF rendering in test client?

答:
First you get the page in your tests and extract the csrf token from it:

```<code>page = self.client.get("/users/login")
token = page.context.get("csrf_token")
</code>```

Then you use the same token to render the template and compare:

```<code>expected_html = TemplateResponse(
    page.wsgi_request,
    "login.html",
    context={"form": LoginForm(), "csrf_token": token}).render()

assert expected_html.content == page.content
</code>```

Title: how to disable csrf in testing django?

Body:
I have a problem testing views with csrf tokens.

This code

class ViewTests(TestCase):
    def test_bets_view(self):
        login_page = self.client.get('/users/login/')
        print(login_page.content)

returns HTML with CSRF hidden input.

And this thing, which I need to compare to the former HTML,

expected_html = render_to_response('login.html',
                                   dictionary={'form': LoginForm()})

doesn't have hidden CSRF input. So the assertion fails.

Ho do I disable CSRF rendering in test client?

Body:
First you get the page in your tests and extract the csrf token from it:

page = self.client.get("/users/login")
token = page.context.get("csrf_token")

Then you use the same token to render the template and compare:

expected_html = TemplateResponse(
    page.wsgi_request,
    "login.html",
    context={"form": LoginForm(), "csrf_token": token}).render()

assert expected_html.content == page.content


问:
Call Perl function in HTML using AJAX
im having a setback, im making an Html page with javascript, and im using AJAX to call Perl functions. The thing is when my Perl program doesn't need parameters the calling is trivial. But i have a function to open and read a file so i need to give the location of the file to the perl script, thus having to passe it trough a paramenter in the AJAX calling.
Ex working call:

```<code>function getOption(){
   var selectmenu=document.getElementById("Select1")
    selectmenu.onchange=function(){  //run some code when "onchange" event fires
    var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
    if (chosenoption.value!="nothing"){
     var s = chosenoption.text;
     openFile("C:\PerlTest\test.txt");
    }
   }
  }
</code>```

EX. not working trying to pass parameter:

```<code>function openFile(name){
 XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
 XMLHttp.onreadystatechange = function() {
 if (XMLHttp.readyState == 4) {
    document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
     }
     }
     XMLHttp.send(null);
   }
</code>```

Im attempting to pass the paremeter in that way because of this example:

http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201

Can anyone help??

Thanks a lot.

After the sugestion of Kinopiko, that makes sense, i have the following:

HTML-

```<code>function openFile(name){
            XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
            XMLHttp.onreadystatechange = function() {
            if (XMLHttp.readyState == 4) {
                var container = XMLHttp.responseText.split("\n");
                if (container.length>0){
                    for ( i=0; i< container.length-1;i++){
                        document.getElementById("TxtArea").innerHTML += container[i] + " ";
                    }
                }
            }
            else{
                document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
            }
            }
            XMLHttp.send(null);
        }
</code>```

Perl script:

```<code>#!c:/Perl/bin/perl

use strict;
use CGI qw/param/;
use URI::Escape;

print "Content-type: text/html\n\n";

my $file = param ('file');
$file = uri_unescape ($file);

open (MYFILE, $file);
    while (<MYFILE>) {
        chomp;
        print "$_\n";
}
close (MYFILE);
</code>```

Now i dont get error in javascript, but my XMLHttp.readyState is never 4, so i dont get the content of the file.

Maybe im using the encodeURI wrong??

Thanks.

答:
```<code>open (MYFILE, $file);
</code>```

<p>should be </p>

```<code>open (MYFILE, $file) or die "Cannot open file $file: $!\n";
</code>```

Title: Call Perl function in HTML using AJAX

Body:
im having a setback, im making an Html page with javascript, and im using AJAX to call Perl functions. The thing is when my Perl program doesn't need parameters the calling is trivial. But i have a function to open and read a file so i need to give the location of the file to the perl script, thus having to passe it trough a paramenter in the AJAX calling.
Ex working call:

function getOption(){
   var selectmenu=document.getElementById("Select1")
    selectmenu.onchange=function(){  //run some code when "onchange" event fires
    var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
    if (chosenoption.value!="nothing"){
     var s = chosenoption.text;
     openFile("C:\PerlTest\test.txt");
    }
   }
  }

EX. not working trying to pass parameter:

function openFile(name){
 XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true);
 XMLHttp.onreadystatechange = function() {
 if (XMLHttp.readyState == 4) {
    document.getElementById("TxtArea").innerHTML = XMLHttp.responseText;
     }
     }
     XMLHttp.send(null);
   }

Im attempting to pass the paremeter in that way because of this example:

http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201

Can anyone help??

Thanks a lot.

After the sugestion of Kinopiko, that makes sense, i have the following:

HTML-

function openFile(name){
            XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true);
            XMLHttp.onreadystatechange = function() {
            if (XMLHttp.readyState == 4) {
                var container = XMLHttp.responseText.split("\n");
                if (container.length>0){
                    for ( i=0; i< container.length-1;i++){
                        document.getElementById("TxtArea").innerHTML += container[i] + " ";
                    }
                }
            }
            else{
                document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText;
            }
            }
            XMLHttp.send(null);
        }

Perl script:

#!c:/Perl/bin/perl

use strict;
use CGI qw/param/;
use URI::Escape;

print "Content-type: text/html\n\n";

my $file = param ('file');
$file = uri_unescape ($file);

open (MYFILE, $file);
    while (<MYFILE>) {
        chomp;
        print "$_\n";
}
close (MYFILE);

Now i dont get error in javascript, but my XMLHttp.readyState is never 4, so i dont get the content of the file.

Maybe im using the encodeURI wrong??

Thanks.

Body:
open (MYFILE, $file);

should be

open (MYFILE, $file) or die "Cannot open file $file: $!\n";


问:
Cannot use the output of the inner (child ) template in the parent template in cloudformation
I am trying to use the output of a cloudformation stack in another. I looked at some examoles such as
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-crossstackref.html

but it is very confusing and I could not make it work in my example:

here is what I have: I have a beanstalk.json template and I output the sampleEnvironment I created in resource section:

```<code>{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
    "sampleApplication": {
        "Type": "AWS::ElasticBeanstalk::Application",
        "Properties": {
            "Description": "AWS Elastic Beanstalk Sample Application",
            "ApplicationName": "app-name-test"
        }
    },
    "sampleApplicationVersion": {
        "Type": "AWS::ElasticBeanstalk::ApplicationVersion",
        "Properties": {
            "ApplicationName": {
                "Ref": "sampleApplication"
            },
            "Description": "AWS ElasticBeanstalk Sample Application Version",
            "SourceBundle": {
                "S3Bucket": "test-war",
                "S3Key": "deployment.war"
            }
        }
    },
    "sampleConfigurationTemplate": {
        "Type": "AWS::ElasticBeanstalk::ConfigurationTemplate",
        "Properties": {
            "ApplicationName": {
                "Ref": "sampleApplication"
            },
            "Description": "AWS ElasticBeanstalk Sample Configuration Template",
            "OptionSettings": [{
                    "Namespace": "aws:autoscaling:asg",
                    "OptionName": "MinSize",
                    "Value": "2"
                },
                {
                    "Namespace": "aws:autoscaling:asg",
                    "OptionName": "MaxSize",
                    "Value": "3"
                },
                {
                    "Namespace": "aws:elasticbeanstalk:environment",
                    "OptionName": "EnvironmentType",
                    "Value": "LoadBalanced"
                }
            ],
            "SolutionStackName": "64bit Amazon Linux 2017.03 v2.6.1 running Tomcat 8 Java 8"
        }
    },
    "sampleEnvironment": {
        "Type": "AWS::ElasticBeanstalk::Environment",
        "Properties": {
            "ApplicationName": {
                "Ref": "sampleApplication"
            },
            "Description": "AWS ElasticBeanstalk Sample Environment",
            "TemplateName": {
                "Ref": "sampleConfigurationTemplate"
            },
            "VersionLabel": {
                "Ref": "sampleApplicationVersion"
            },
            "EnvironmentName": "test-dep-env-name"
        }
    }
},
 "Outputs": {
    "applicationName11": {
       "Description": "The application chosen by user is :",
       "Value": {
        "Ref": "sampleEnvironment"
      },
   "Export" : {
    "Name" : {"Ref": "sampleEnvironment"}
    }
 }
}
</code>```

Now my problem starts. I need to refer to the name of the sampleEnvironment created in beanstalk.json  and assign it to the name of the s3 in resource section in the main template which uses beanstalk.json template. Here is my main tempalte code:

```<code>{
"Parameters": {
    "appName1": {
        "Description": "enter the app name",
        "Type": "String",
        "Default": "bn-test-jun"
    },
    "appEnv1": {
        "Description": "enter the app name",
        "Type": "String",
        "Default": "bn-test-jun"
    }
},
"Resources": {
    "CodeDeployEC2InstancesStack": {
        "Type": "AWS::CloudFormation::Stack",
        "Properties": {
            "TemplateURL": "https://s3.amazonaws.com/url...../beanstalk.json",
            "TimeoutInMinutes": "60"
        }
    },
    "myS3": {
        "Type": "AWS::S3::Bucket",
        "Properties": {
            "AccessControl": "PublicRead",
            "BucketName": "name of the environment returned as an output sth like Outputs.EnvironmentName"
        }
    }
}
 ,
 "Outputs":{
  "app":{
  "Description": "The application chosen by user is :",
     "Value": {
             "Fn::ImportValue" : "sampleEnvironment"
     }
   }
 }
  }
</code>```

Now you see that in the bucketName section I am stuck. I need to assign the name of the environment created in beanstalk.json to the name of the s3 bucket which is going to be created. How can I do that?

答:
I've replied on the CFN course forums

https://acloud.guru/forums/aws-advanced-cloudformation/discussion/-KoAxjlT_ZtSAdrlg1lp/cannot_use_the_output_of_the_i

You dont need to use Export/Import value because you are using nested stacks.

Body:
I am trying to use the output of a cloudformation stack in another. I looked at some examoles such as
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-crossstackref.html

but it is very confusing and I could not make it work in my example:

here is what I have: I have a beanstalk.json template and I output the sampleEnvironment I created in resource section:

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
    "sampleApplication": {
        "Type": "AWS::ElasticBeanstalk::Application",
        "Properties": {
            "Description": "AWS Elastic Beanstalk Sample Application",
            "ApplicationName": "app-name-test"
        }
    },
    "sampleApplicationVersion": {
        "Type": "AWS::ElasticBeanstalk::ApplicationVersion",
        "Properties": {
            "ApplicationName": {
                "Ref": "sampleApplication"
            },
            "Description": "AWS ElasticBeanstalk Sample Application Version",
            "SourceBundle": {
                "S3Bucket": "test-war",
                "S3Key": "deployment.war"
            }
        }
    },
    "sampleConfigurationTemplate": {
        "Type": "AWS::ElasticBeanstalk::ConfigurationTemplate",
        "Properties": {
            "ApplicationName": {
                "Ref": "sampleApplication"
            },
            "Description": "AWS ElasticBeanstalk Sample Configuration Template",
            "OptionSettings": [{
                    "Namespace": "aws:autoscaling:asg",
                    "OptionName": "MinSize",
                    "Value": "2"
                },
                {
                    "Namespace": "aws:autoscaling:asg",
                    "OptionName": "MaxSize",
                    "Value": "3"
                },
                {
                    "Namespace": "aws:elasticbeanstalk:environment",
                    "OptionName": "EnvironmentType",
                    "Value": "LoadBalanced"
                }
            ],
            "SolutionStackName": "64bit Amazon Linux 2017.03 v2.6.1 running Tomcat 8 Java 8"
        }
    },
    "sampleEnvironment": {
        "Type": "AWS::ElasticBeanstalk::Environment",
        "Properties": {
            "ApplicationName": {
                "Ref": "sampleApplication"
            },
            "Description": "AWS ElasticBeanstalk Sample Environment",
            "TemplateName": {
                "Ref": "sampleConfigurationTemplate"
            },
            "VersionLabel": {
                "Ref": "sampleApplicationVersion"
            },
            "EnvironmentName": "test-dep-env-name"
        }
    }
},
 "Outputs": {
    "applicationName11": {
       "Description": "The application chosen by user is :",
       "Value": {
        "Ref": "sampleEnvironment"
      },
   "Export" : {
    "Name" : {"Ref": "sampleEnvironment"}
    }
 }
}

Now my problem starts. I need to refer to the name of the sampleEnvironment created in beanstalk.json  and assign it to the name of the s3 in resource section in the main template which uses beanstalk.json template. Here is my main tempalte code:

{
"Parameters": {
    "appName1": {
        "Description": "enter the app name",
        "Type": "String",
        "Default": "bn-test-jun"
    },
    "appEnv1": {
        "Description": "enter the app name",
        "Type": "String",
        "Default": "bn-test-jun"
    }
},
"Resources": {
    "CodeDeployEC2InstancesStack": {
        "Type": "AWS::CloudFormation::Stack",
        "Properties": {
            "TemplateURL": "https://s3.amazonaws.com/url...../beanstalk.json",
            "TimeoutInMinutes": "60"
        }
    },
    "myS3": {
        "Type": "AWS::S3::Bucket",
        "Properties": {
            "AccessControl": "PublicRead",
            "BucketName": "name of the environment returned as an output sth like Outputs.EnvironmentName"
        }
    }
}
 ,
 "Outputs":{
  "app":{
  "Description": "The application chosen by user is :",
     "Value": {
             "Fn::ImportValue" : "sampleEnvironment"
     }
   }
 }
  }

Now you see that in the bucketName section I am stuck. I need to assign the name of the environment created in beanstalk.json to the name of the s3 bucket which is going to be created. How can I do that?


问:
Antonym filtering in Elasticsearch
If I search for with a query string that contains "extrahepatisch" i do not want to find documents with the word "intrahepatisch" which is a antonym.

I have a list with such antonym pairs. What is the best way to make elasticsearch use the antonym list?

答: I believe what you're looking for is to use a Stop Token Filter.</p>

Title: Antonym filtering in Elasticsearch


问:
Density Value for each Return
I have a dataframe "foo" looking like this

```<code>Date       Return
1998-01-01  0.02
1998-01-02  0.04
1998-01-03 -0.02
1998-01-04 -0.01
1998-01-05  0.02
...
1998-02-01  0.1
1998-02-02 -0.2
1998-02-03 -0.1
etc.
</code>```

I would like to add to this dataframe a new column showing me the density value of the corresponding return. I tried:

```<code>foo$density <- for(i in 1:length(foo$Return)) density(foo$Return,
from = foo$Return[i], to = foo$Return[i], n = 1)$y
</code>```

But it didn't work. I really have difficulty applying a "function" to each row. But maybe there is also another way to do it, not using density()?

What I essentially would like to do is to extract the fitted density values from density() to the returns in foo. If I just do plot(density(foo$Return)) it gives me the curve, however I would like to have the density values attached to the returns.

@Joris:

```<code>foo$density <- density(foo$Return, n=nrow(foo$Return))$y
</code>```

calculates something, however seems to return wrong density values.

Thank you for helping me out!
Dani

答:
If we ignore the density issue, which @Joris expertly answers, you don't seem to have grasped how to set up a loop. What you are returning from the loop is the value NULL. This is the value that is being inserted in foo$density and that won't not work because it is the NULL, which means it is an empty component, i.e. it doesn't exists as far as R is concerned. See ?'for' for further details.

```<code>> bar <- for(i in 1:10) {
+     i + 1
+ }
> bar
NULL

> foo <- data.frame(A = 1:10, B = LETTERS[1:10])
> foo$density <- for(i in seq_len(nrow(foo))) {
+     i + 1
+ }
> head(foo) ## No `density`
  A B
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
6 6 F
</code>```

If you want to insert the return value for each iteration of the loop, you must do the assignment inside the loop, and that means you should pre-allocate the storage space before you enter the loop, e.g. the above loop if we wanted to have i + 1 for i in 1,...,10, we could do this:

```<code>> bar <- numeric(length = 10)
> for(i in seq_along(bar)) {
+     bar[i] <- i + 1
+ }
> bar
 [1]  2  3  4  5  6  7  8  9 10 11
</code>```

Of course, you would not do such a calculation as this via a loop, because R is vectorized and will work with vectors of numbers rather than you having to code each computation element by element as you might in C or other programming languages.

```<code>> bar <- 1:10 + 1
> bar
 [1]  2  3  4  5  6  7  8  9 10 11
</code>```

Notice that R has turned 1 into a vector of 1s of sufficient length to allow the computation to proceed, something known as recycling in R-speak.

Sometimes, you might need to iterate over an object with a loop or using one of the s|l|t|apply() family, but most often you will find a function that works for an entire vector of data in one go. This is one of the advantages of R over other programming languages, but does require you to get your head into vectorized mode.

Title: Density Value for each Return

Body:
I have a dataframe "foo" looking like this

Date       Return
1998-01-01  0.02
1998-01-02  0.04
1998-01-03 -0.02
1998-01-04 -0.01
1998-01-05  0.02
...
1998-02-01  0.1
1998-02-02 -0.2
1998-02-03 -0.1
etc.

I would like to add to this dataframe a new column showing me the density value of the corresponding return. I tried:

foo$density <- for(i in 1:length(foo$Return)) density(foo$Return,
from = foo$Return[i], to = foo$Return[i], n = 1)$y

But it didn't work. I really have difficulty applying a "function" to each row. But maybe there is also another way to do it, not using density()?

What I essentially would like to do is to extract the fitted density values from density() to the returns in foo. If I just do plot(density(foo$Return)) it gives me the curve, however I would like to have the density values attached to the returns.

@Joris:

foo$density <- density(foo$Return, n=nrow(foo$Return))$y

calculates something, however seems to return wrong density values.

Thank you for helping me out!
Dani

Body:
If we ignore the density issue, which @Joris expertly answers, you don't seem to have grasped how to set up a loop. What you are returning from the loop is the value NULL. This is the value that is being inserted in foo$density and that won't not work because it is the NULL, which means it is an empty component, i.e. it doesn't exists as far as R is concerned. See ?'for' for further details.

> bar <- for(i in 1:10) {
+     i + 1
+ }
> bar
NULL

> foo <- data.frame(A = 1:10, B = LETTERS[1:10])
> foo$density <- for(i in seq_len(nrow(foo))) {
+     i + 1
+ }
> head(foo) ## No `density`
  A B
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
6 6 F

If you want to insert the return value for each iteration of the loop, you must do the assignment inside the loop, and that means you should pre-allocate the storage space before you enter the loop, e.g. the above loop if we wanted to have i + 1 for i in 1,...,10, we could do this:

> bar <- numeric(length = 10)
> for(i in seq_along(bar)) {
+     bar[i] <- i + 1
+ }
> bar
 [1]  2  3  4  5  6  7  8  9 10 11

Of course, you would not do such a calculation as this via a loop, because R is vectorized and will work with vectors of numbers rather than you having to code each computation element by element as you might in C or other programming languages.

> bar <- 1:10 + 1
> bar
 [1]  2  3  4  5  6  7  8  9 10 11

Notice that R has turned 1 into a vector of 1s of sufficient length to allow the computation to proceed, something known as recycling in R-speak.

Sometimes, you might need to iterate over an object with a loop or using one of the s|l|t|apply() family, but most often you will find a function that works for an entire vector of data in one go. This is one of the advantages of R over other programming languages, but does require you to get your head into vectorized mode.


问:
Replicate Base64 decoding of Java in PL/SQL
I am trying to get the same result I am getting in Java when decoding a Base64 String (NVARCHAR2) in Oracle.

I do have the following String: N'AAECAwQFBgdNu+qx2ZcqsA==' which is basically a encrypted password packed into a Base64 encoding.

In Java I am doing this:

```<code>byte[] bytes = Base64.decodeBase64(testValue.getBytes());
for(byte b: bytes){
     System.out.print(String.valueOf(b & 0xFF) + " "); //Decimal (unsigned)
}
for(byte b: bytes){
     System.out.print(Integer.toHexString(b & 0xFF) + " "); //Hex
}
</code>```

which prints me following:

```<code>Unsigned: 0 1 2 3 4 5 6 7 77 187 234 177 217 151 42 176
Hex:      0 1 2 3 4 5 6 7 4d bb  ea  b1  d9  97  2a b0
</code>```

Now I want to replicate the Base64 decoding like it's made in Java. I am trying following in a PL/SQL-Function:

```<code>base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_I18N.STRING_TO_RAW(valueToDecrypt, charset));
DBMS_OUTPUT.PUT_LINE ( 'Base64 decoded is: ' || base64DecodedInput);
</code>```

The charset is: AL16UTF16
and valueToDecrypt is the test String I mentioned above as NVARCHAR2(200)

The DBMS_OUTPUT prints me:

```<code>Base64 decoded is: 0000004200300105A8308FDD02FE02B11B7901EA02C0
</code>```

Which is wrong!...

What did I miss. Is PL/SQL not using url safe decoding or whatever?

I am stuck.

The code is part of a PL/SQL-Function:

```<code>CREATE OR REPLACE FUNCTION decodeBase64
(valueToDecrypt IN NVARCHAR2)
RETURN NVARCHAR2
AS
   --Declaration area
   charset VARCHAR(100);
   base64DecodedInput RAW(2000);
   ...
</code>```

And Server/Database Settings are:

```<code>NLS_RDBMS_VERSION   12.1.0.2.0
NLS_NCHAR_CONV_EXCP FALSE
NLS_LENGTH_SEMANTICS    BYTE
NLS_COMP    BINARY
NLS_DUAL_CURRENCY   $
NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR
NLS_TIME_TZ_FORMAT  HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_FORMAT    DD-MON-RR HH.MI.SSXFF AM
NLS_TIME_FORMAT HH.MI.SSXFF AM
NLS_SORT    BINARY
NLS_DATE_LANGUAGE   AMERICAN
NLS_DATE_FORMAT DD-MON-RR
NLS_CALENDAR    GREGORIAN
NLS_NUMERIC_CHARACTERS  .,
NLS_NCHAR_CHARACTERSET  AL16UTF16
NLS_CHARACTERSET    WE8MSWIN1252
NLS_ISO_CURRENCY    AMERICA
NLS_CURRENCY    $
NLS_TERRITORY   AMERICA
NLS_LANGUAGE    AMERICAN
</code>```

答:
Have a look at CAST_TO_RAW Ddocumentation:

This function converts a VARCHAR2 value represented using some number of data bytes into a RAW value with that number of data bytes.

You should use this one:

```<code>base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_RAW.CAST_TO_RAW(TO_CHAR(valueToDecrypt)));
DBMS_OUTPUT.PUT_LINE ( 'Base64 decoded is: ' || base64DecodedInput);

00010203040506074DBBEAB1D9972AB0
</code>```

Which (formatted) should be equal to desired result:

```<code>00 01 02 03 04 05 06 07 4D BB EA B1 D9 97 2A B0
</code>```

It is quite useless to use NVARCHAR2 for a BASE64 string. The main purpose of BASE64 encoding is to represent arbitrary data only with ASCII characters, so NVARCHAR2 makes no sense. Since BASE64 contains only ASCII you don't have to worry about any character encoding at CAST(... AS VARCHAR2(200)).

Of course, for the decoded string data type NVARCHAR2 might be very useful.

Body:
I am trying to get the same result I am getting in Java when decoding a Base64 String (NVARCHAR2) in Oracle.

I do have the following String: N'AAECAwQFBgdNu+qx2ZcqsA==' which is basically a encrypted password packed into a Base64 encoding.

In Java I am doing this:

byte[] bytes = Base64.decodeBase64(testValue.getBytes());
for(byte b: bytes){
     System.out.print(String.valueOf(b & 0xFF) + " "); //Decimal (unsigned)
}
for(byte b: bytes){
     System.out.print(Integer.toHexString(b & 0xFF) + " "); //Hex
}

which prints me following:

Unsigned: 0 1 2 3 4 5 6 7 77 187 234 177 217 151 42 176
Hex:      0 1 2 3 4 5 6 7 4d bb  ea  b1  d9  97  2a b0

Now I want to replicate the Base64 decoding like it's made in Java. I am trying following in a PL/SQL-Function:

base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_I18N.STRING_TO_RAW(valueToDecrypt, charset));
DBMS_OUTPUT.PUT_LINE ( 'Base64 decoded is: ' || base64DecodedInput);

The charset is: AL16UTF16
and valueToDecrypt is the test String I mentioned above as NVARCHAR2(200)

The DBMS_OUTPUT prints me:

Base64 decoded is: 0000004200300105A8308FDD02FE02B11B7901EA02C0

Which is wrong!...

What did I miss. Is PL/SQL not using url safe decoding or whatever?

I am stuck.

The code is part of a PL/SQL-Function:

CREATE OR REPLACE FUNCTION decodeBase64
(valueToDecrypt IN NVARCHAR2)
RETURN NVARCHAR2
AS
   --Declaration area
   charset VARCHAR(100);
   base64DecodedInput RAW(2000);
   ...

And Server/Database Settings are:

NLS_RDBMS_VERSION   12.1.0.2.0
NLS_NCHAR_CONV_EXCP FALSE
NLS_LENGTH_SEMANTICS    BYTE
NLS_COMP    BINARY
NLS_DUAL_CURRENCY   $
NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR
NLS_TIME_TZ_FORMAT  HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_FORMAT    DD-MON-RR HH.MI.SSXFF AM
NLS_TIME_FORMAT HH.MI.SSXFF AM
NLS_SORT    BINARY
NLS_DATE_LANGUAGE   AMERICAN
NLS_DATE_FORMAT DD-MON-RR
NLS_CALENDAR    GREGORIAN
NLS_NUMERIC_CHARACTERS  .,
NLS_NCHAR_CHARACTERSET  AL16UTF16
NLS_CHARACTERSET    WE8MSWIN1252
NLS_ISO_CURRENCY    AMERICA
NLS_CURRENCY    $
NLS_TERRITORY   AMERICA
NLS_LANGUAGE    AMERICAN

Body:
Have a look at CAST_TO_RAW Ddocumentation:

This function converts a VARCHAR2 value represented using some number of data bytes into a RAW value with that number of data bytes.

You should use this one:

base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_RAW.CAST_TO_RAW(TO_CHAR(valueToDecrypt)));
DBMS_OUTPUT.PUT_LINE ( 'Base64 decoded is: ' || base64DecodedInput);

00010203040506074DBBEAB1D9972AB0

Which (formatted) should be equal to desired result:

00 01 02 03 04 05 06 07 4D BB EA B1 D9 97 2A B0

It is quite useless to use NVARCHAR2 for a BASE64 string. The main purpose of BASE64 encoding is to represent arbitrary data only with ASCII characters, so NVARCHAR2 makes no sense. Since BASE64 contains only ASCII you don't have to worry about any character encoding at CAST(... AS VARCHAR2(200)).

Of course, for the decoded string data type NVARCHAR2 might be very useful.


问:
Code crashes on Excel VBA
Every time I run this code, it crashes , I tried all that I can, but I just  don't know which part is crashing and it's not telling me why. I need  it to look through every cell until its respective amount and put into the current sheet.

Is there any advice or see anything that might help?

```<code>Sub bringbookstogether()

Dim currentsheet As Worksheet
Set currentsheet = Application.ActiveSheet

'assigns the number to start with
Dim a, b, c, d As Integer

a = 4
b = 6
c = 3
d = 1

Dim wsheet As Worksheet
Set wsheet = Application.ActiveWorkbook.Sheets(c)

Dim wbook As Workbook

'assigns workbook numbers
If (d = 1) Then
    Set wbook = Workbooks.Open("C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 1st.xlsm", UpdateLinks:=xlUpdateLinksAlways)
Else

    If (d = 2) Then
        Set wbook = Workbooks.Open("C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 2nd.xlsm", UpdateLinks:=xlUpdateLinksAlways)
    Else

        If (d = 3) Then
            Set wbook = Workbooks.Open("C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 3rd.xlsm", UpdateLinks:=xlUpdateLinksAlways)

        End If
    End If
End If

Application.ScreenUpdating = False
'End if it's done with all the workbooks

Do Until (d = 4)

    'Looks for the sheet that has the same name

    Do Until (c = 53)
        If (wsheet.Name = currentsheet.Name) Then

            'Ends in row 99
            Do Until (b = 99)

                'Ends in Column 52
                Do Until (a = 52)

                    currentsheet.Cells(b, a) = currentsheet.Cells(b, a) + Workbooks(d).Sheets(c).Cells(b, a)

                    a = a + 1
                Loop

                b = b + 1
            Loop

        End If
    Loop

    d = d + 1
Loop

Application.ScreenUpdating = True

End Sub
</code>```

答:
Ok, what your script does:

It sets a number for variable d. Based on this one it opens a workbook.

Next, it uses variable c to start looping at a specific worksheet until it finds the Sheet in the opened workbook that has the same name as the sheet that is active when the macro starts (Set currentsheet = Application.ActiveSheet)

It sets variable a to decide from which Column to 52 it must copy.

It sets variable b to decide from which Row to 99 it must copy.

Thus, based on this a,b,c,d you find 1 worksheet, in 1 workbook and you copy 1 range to the currentsheet. This basically means 1 operation, yet with your loops you make it a potential million operations. Hence the comment section and the incredibly slow performance.

This script does the exact same thing as yours without any loops:

```<code>Sub bringbookstogether()
Application.ScreenUpdating = False

Dim currentsheet As Worksheet
Dim wbook As Workbook
Dim wsheet As Worksheet

Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim d As Integer

Dim fName As String

a = 1 'Only for the starting column! Can't exceed 52
b = 1 'Only for the starting row! Cant' exceed 99
      'I got rid of c, we don't need it.
d = 4 'Not needed to loop. Your loop on d was obsolete.

Set currentsheet = Application.ActiveSheet

'Open the workbook:
Select Case d 'No need for a lot of nested If statements.
    Case 1:
        fName = "C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 1st.xlsm"
    Case 2:
        fName = "C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 2nd.xlsm"
    Case 3:
        fName = "C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 3rd.xlsm"
        'You might want to consider renaming the files "MaintPrep Sheet 1.xlsm", "MaintPrep Sheet 2.xlsm", etc.
        'In that case you could just do: fName = "C:Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet " & d & ".xlsm" and omit the whole Select.
    Case 4:
        fName = "C:\temp\test.xlsx"
End Select

Set wbook = Workbooks.Open(fName, UpdateLinks:=xlUpdateLinksAlways)

On Error Resume Next 'To avoid subscript out of range error if the same named sheet doesn't exist
    Set wsheet = wbook.Worksheets(currentsheet.Name)
On Error GoTo 0

If Not wsheet Is Nothing Then 'Check if we have the sheet with the same name
    With currentsheet 'Copy range row set in a, column set in a to row 99 and column 52 as per sample loop.
        wsheet.Range(wsheet.Cells(b, a), wsheet.Cells(99, 52)).Copy
        .Range(.Cells(b, a), .Cells(99, 52)).PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
    End With
End If

Application.ScreenUpdating = True
End Sub
</code>```

You'll see that this executes a few hundred (!!!) times faster than the posted script.

Edit:
To loop over each worksheet that is in the ActiveWorkbook and each corresponding sheet in the workbooks, I suggest changing the workbook names from "1st", "2nd", "3rd" etc. to simply 1, 2, 3, 4.

Then:
 - get rid of the d = 1 line
 - get rid of c altogether
 - get rid of the whole Select Case block above.
 - Replace the part from Set wbook = ... until the last end if with the code below:

```<code>For d = 1 to 4
    fName = "C:Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet " & d & ".xlsm"
    Set wbook = Workbooks.Open(fName, UpdateLinks:=xlUpdateLinksAlways)

    For Each currentSheet in ThisWorkbook.Worksheets
    On Error Resume Next 'To avoid subscript out of range error if the same named sheet doesn't exist
        Set wsheet = wbook.Worksheets(currentsheet.Name)
    On Error GoTo 0

    If Not wsheet Is Nothing Then 'Check if we have the sheet with the same name
        With currentsheet 'Copy range row set in a, column set in a to row 99 and column 52 as per sample loop.
            wsheet.Range(wsheet.Cells(b, a), wsheet.Cells(99, 52)).Copy
            .Range(.Cells(b, a), .Cells(99, 52)).PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
        End With
    End If
    Next currentSheet
Next d
</code>```

Title: Code crashes on Excel VBA

Body:
Every time I run this code, it crashes , I tried all that I can, but I just  don't know which part is crashing and it's not telling me why. I need  it to look through every cell until its respective amount and put into the current sheet.

Is there any advice or see anything that might help?

Sub bringbookstogether()

Dim currentsheet As Worksheet
Set currentsheet = Application.ActiveSheet

'assigns the number to start with
Dim a, b, c, d As Integer

a = 4
b = 6
c = 3
d = 1

Dim wsheet As Worksheet
Set wsheet = Application.ActiveWorkbook.Sheets(c)

Dim wbook As Workbook

'assigns workbook numbers
If (d = 1) Then
    Set wbook = Workbooks.Open("C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 1st.xlsm", UpdateLinks:=xlUpdateLinksAlways)
Else

    If (d = 2) Then
        Set wbook = Workbooks.Open("C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 2nd.xlsm", UpdateLinks:=xlUpdateLinksAlways)
    Else

        If (d = 3) Then
            Set wbook = Workbooks.Open("C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 3rd.xlsm", UpdateLinks:=xlUpdateLinksAlways)

        End If
    End If
End If

Application.ScreenUpdating = False
'End if it's done with all the workbooks

Do Until (d = 4)

    'Looks for the sheet that has the same name

    Do Until (c = 53)
        If (wsheet.Name = currentsheet.Name) Then

            'Ends in row 99
            Do Until (b = 99)

                'Ends in Column 52
                Do Until (a = 52)

                    currentsheet.Cells(b, a) = currentsheet.Cells(b, a) + Workbooks(d).Sheets(c).Cells(b, a)

                    a = a + 1
                Loop

                b = b + 1
            Loop

        End If
    Loop

    d = d + 1
Loop

Application.ScreenUpdating = True

End Sub

Body:
Ok, what your script does:

It sets a number for variable d. Based on this one it opens a workbook.

Next, it uses variable c to start looping at a specific worksheet until it finds the Sheet in the opened workbook that has the same name as the sheet that is active when the macro starts (Set currentsheet = Application.ActiveSheet)

It sets variable a to decide from which Column to 52 it must copy.

It sets variable b to decide from which Row to 99 it must copy.

Thus, based on this a,b,c,d you find 1 worksheet, in 1 workbook and you copy 1 range to the currentsheet. This basically means 1 operation, yet with your loops you make it a potential million operations. Hence the comment section and the incredibly slow performance.

This script does the exact same thing as yours without any loops:

Sub bringbookstogether()
Application.ScreenUpdating = False

Dim currentsheet As Worksheet
Dim wbook As Workbook
Dim wsheet As Worksheet

Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim d As Integer

Dim fName As String

a = 1 'Only for the starting column! Can't exceed 52
b = 1 'Only for the starting row! Cant' exceed 99
      'I got rid of c, we don't need it.
d = 4 'Not needed to loop. Your loop on d was obsolete.

Set currentsheet = Application.ActiveSheet

'Open the workbook:
Select Case d 'No need for a lot of nested If statements.
    Case 1:
        fName = "C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 1st.xlsm"
    Case 2:
        fName = "C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 2nd.xlsm"
    Case 3:
        fName = "C:\Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet 3rd.xlsm"
        'You might want to consider renaming the files "MaintPrep Sheet 1.xlsm", "MaintPrep Sheet 2.xlsm", etc.
        'In that case you could just do: fName = "C:Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet " & d & ".xlsm" and omit the whole Select.
    Case 4:
        fName = "C:\temp\test.xlsx"
End Select

Set wbook = Workbooks.Open(fName, UpdateLinks:=xlUpdateLinksAlways)

On Error Resume Next 'To avoid subscript out of range error if the same named sheet doesn't exist
    Set wsheet = wbook.Worksheets(currentsheet.Name)
On Error GoTo 0

If Not wsheet Is Nothing Then 'Check if we have the sheet with the same name
    With currentsheet 'Copy range row set in a, column set in a to row 99 and column 52 as per sample loop.
        wsheet.Range(wsheet.Cells(b, a), wsheet.Cells(99, 52)).Copy
        .Range(.Cells(b, a), .Cells(99, 52)).PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
    End With
End If

Application.ScreenUpdating = True
End Sub

You'll see that this executes a few hundred (!!!) times faster than the posted script.

Edit:
To loop over each worksheet that is in the ActiveWorkbook and each corresponding sheet in the workbooks, I suggest changing the workbook names from "1st", "2nd", "3rd" etc. to simply 1, 2, 3, 4.

Then:
 - get rid of the d = 1 line
 - get rid of c altogether
 - get rid of the whole Select Case block above.
 - Replace the part from Set wbook = ... until the last end if with the code below:

For d = 1 to 4
    fName = "C:Users\mminchuk\Documents\Updated MaintPrep Sheets\MaintPrep Sheet " & d & ".xlsm"
    Set wbook = Workbooks.Open(fName, UpdateLinks:=xlUpdateLinksAlways)

    For Each currentSheet in ThisWorkbook.Worksheets
    On Error Resume Next 'To avoid subscript out of range error if the same named sheet doesn't exist
        Set wsheet = wbook.Worksheets(currentsheet.Name)
    On Error GoTo 0

    If Not wsheet Is Nothing Then 'Check if we have the sheet with the same name
        With currentsheet 'Copy range row set in a, column set in a to row 99 and column 52 as per sample loop.
            wsheet.Range(wsheet.Cells(b, a), wsheet.Cells(99, 52)).Copy
            .Range(.Cells(b, a), .Cells(99, 52)).PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
        End With
    End If
    Next currentSheet
Next d


问:
How to Change previous button color when pressed the next button?
I have a number of buttons in a horizontal UIScrollView added programmatically. I have to change the color of the user selected button. But if user select another button the previous button color must be change to default color.
how can I do this? Please help me...

```<code>func createHorizontalScroll()
{
    let scrollView = UIScrollView(frame: CGRect(x: CGFloat(0), y: CGFloat(410), width: CGFloat(view.frame.size.width), height: CGFloat(40)))

    var buttonX: CGFloat = 0

    for index in 0..<btnNames.count
    {
        //add an element and the previous element together
        let sum = btnNames[index]

        button = UIButton(frame: CGRect(x: CGFloat(buttonX), y: CGFloat(0), width: CGFloat(100), height: CGFloat(40)))

        print("btnNames:\(sum)")

        button.setTitle("\(sum)",for:.normal)
        button.layer.borderWidth = 2.5
        button.layer.borderWidth = 2.5
        button.layer.borderColor = UIColor.white.cgColor
        button.layer.backgroundColor = UIColor.black.cgColor
        button.tag = index
        scrollView.addSubview(button)
        buttonX = button.frame.size.width + buttonX

        button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
    }

    scrollView.contentSize = CGSize(width: CGFloat(buttonX), height: CGFloat(scrollView.frame.size.height))
    scrollView.backgroundColor = UIColor.clear
    view.addSubview(scrollView)
}

func changeView(_ sender: UIButton)
{
   print("I Clicked a button \(Int(sender.tag))")
}
</code>```

答:
Simple solution without tags.

Declare a property currentButton

```<code>weak var currentButton : UIButton?
</code>```

In changeView reset the color of the currentButton, set the color of the sender and assign the sender to currentButton.

```<code>func changeView(_ sender: UIButton)
{
    currentButton?.backgroundColor = .black
    currentButton = sender
    sender.backgroundColor = .red
}
</code>```

Due to optional chaining the color of currentButton will not be set if currentButton is nil.

Body:
I have a number of buttons in a horizontal UIScrollView added programmatically. I have to change the color of the user selected button. But if user select another button the previous button color must be change to default color.
how can I do this? Please help me...

func createHorizontalScroll()
{
    let scrollView = UIScrollView(frame: CGRect(x: CGFloat(0), y: CGFloat(410), width: CGFloat(view.frame.size.width), height: CGFloat(40)))

    var buttonX: CGFloat = 0

    for index in 0..<btnNames.count
    {
        //add an element and the previous element together
        let sum = btnNames[index]

        button = UIButton(frame: CGRect(x: CGFloat(buttonX), y: CGFloat(0), width: CGFloat(100), height: CGFloat(40)))

        print("btnNames:\(sum)")

        button.setTitle("\(sum)",for:.normal)
        button.layer.borderWidth = 2.5
        button.layer.borderWidth = 2.5
        button.layer.borderColor = UIColor.white.cgColor
        button.layer.backgroundColor = UIColor.black.cgColor
        button.tag = index
        scrollView.addSubview(button)
        buttonX = button.frame.size.width + buttonX

        button.addTarget(self, action: #selector(changeView), for: .touchUpInside)
    }

    scrollView.contentSize = CGSize(width: CGFloat(buttonX), height: CGFloat(scrollView.frame.size.height))
    scrollView.backgroundColor = UIColor.clear
    view.addSubview(scrollView)
}

func changeView(_ sender: UIButton)
{
   print("I Clicked a button \(Int(sender.tag))")
}

Body:
Simple solution without tags.

Declare a property currentButton

weak var currentButton : UIButton?

In changeView reset the color of the currentButton, set the color of the sender and assign the sender to currentButton.

func changeView(_ sender: UIButton)
{
    currentButton?.backgroundColor = .black
    currentButton = sender
    sender.backgroundColor = .red
}

Due to optional chaining the color of currentButton will not be set if currentButton is nil.


问:
What tools to choose for developing a simple GUI application?
I'd like to implement a very simple application, which would:

Get a number from bar code reader

Fetch some data from MySQL based on the number

Based on the data, draw max 10 selection boxes on the screen of a touchscreen display

User points at the boxes she wants to select

Application updates database according to user's selection

The selection screen should be aesthetically pleasing and "fill" the whole display.

Application can implemented for either Windows or Linux, but the development environment and other tools should be either free or low cost.

The software will not be made available for download, but it will only be installed in a couple of computers.

My experience is mostly from server side applications, so I welcome suggestions for the technology which would enable fast development of such an application.

答: Two interesting development suites for simple (and possibly advanced) crossplatform GUI applications are RealStudio and LiveCode (previously called Runtime Revolution). </p>


答:
Keep a week property of type UIButton to temporally save the selected button.

```<code>weak var selectedButton: UIButton?
</code>```

In the selector for your buttons make the color of the selectedButton to default, then change the color of the newly selected button and reset the selectedButton

```<code>@IBAction func actionTouchUpInside(sender: UIButton) {
    if let selectedButton = self.selectedButton {
        selectedButton.backgroundColor = UIColor.clear
    }

    sender.backgroundColor = UIColor.blue
    selectedButton = sender
}
</code>```

Title: How to Change previous button color when pressed the next button?

Body:
Keep a week property of type UIButton to temporally save the selected button.

weak var selectedButton: UIButton?

In the selector for your buttons make the color of the selectedButton to default, then change the color of the newly selected button and reset the selectedButton

@IBAction func actionTouchUpInside(sender: UIButton) {
    if let selectedButton = self.selectedButton {
        selectedButton.backgroundColor = UIColor.clear
    }

    sender.backgroundColor = UIColor.blue
    selectedButton = sender
}


问:
Correct way to compile Settings.apk in android
I have Mini Cyanogenmod sources on my laptop.
So I did make Settings to compile Settings.apk from source. (I don't wanna compile the whole ROM)

And compilation finished nicely and I got Settings.apk compiled.

So I pushed Settings.apk to /system/app by the following commands :

```<code>adb root
adb push Settings.apk /system/app
</code>```

The file successfully copies. But now the Settings app is itself removed from the app drawer. I tried setting the permissions of apk but it didn't work either. And when I push the original apk to /system/app the Settings app reappears in the app drawer.

What could be the problem of my compiled apk is not working.

答:
The problem is that push Settings.apk to /system/app. You should push Settings.apk to "/system/priv-app/Settings/" by the following command:

adb push Settings.apk /system/priv-app/Settings/

Steps are described as follows：

root and romount the filesystem.

push Settings.apk to the right directory.

reboot.

The corresponding commands are:

```<code>adb root
adb remount
adb push Settings.apk /system/priv-app/Settings/
adb reboot
</code>```

Body:
I have Mini Cyanogenmod sources on my laptop.
So I did make Settings to compile Settings.apk from source. (I don't wanna compile the whole ROM)

And compilation finished nicely and I got Settings.apk compiled.

So I pushed Settings.apk to /system/app by the following commands :

adb root
adb push Settings.apk /system/app

The file successfully copies. But now the Settings app is itself removed from the app drawer. I tried setting the permissions of apk but it didn't work either. And when I push the original apk to /system/app the Settings app reappears in the app drawer.

What could be the problem of my compiled apk is not working.

Body:
The problem is that push Settings.apk to /system/app. You should push Settings.apk to "/system/priv-app/Settings/" by the following command:

adb push Settings.apk /system/priv-app/Settings/

Steps are described as follows：

root and romount the filesystem.

push Settings.apk to the right directory.

reboot.

The corresponding commands are:

adb root
adb remount
adb push Settings.apk /system/priv-app/Settings/
adb reboot


问:
What are DDL and DML?
I have heard the terms DDL and DML in reference to databases, but I don't understand what they are.

What are they and how do they relate to SQL?

答:
In layman terms suppose you want to build a house, what do you do.

DDL i.e Data Definition Language

Build from scratch

Rennovate it

Destroy the older one and recreate it from scratch

that is

CREATE

ALTER

DROP & CREATE

DML i.e. Data Manipulation Language

People come/go inside/from your house

SELECT

DELETE

UPDATE

TRUNCATE

DCL i.e. Data Control Language

You want to control the people what part of the house they are allowed to access and kind of access.

GRANT PERMISSION

ContentLicense: CC BY-SA 4.0

Title: What are DDL and DML?


问:
Combining the values of an array with the values of hash
I have an attributes array which is defined by me and  I get an hash  both of them which I need to combine into an output array. Please let me know the simplest way to do this.

attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]

entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017", "Time (Hours)"=>"1", "Comment"=>"yes"}

When it is combined I want a hash like

Output = {"user_id"=>1, "project_id"=>8, "task_id"=>87,
         "date"=>6/22/2017,"time_spent"=>1,"comment"=>"yes"}

Thanks for the help!

答:
Try this</p>

```<code>attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]
# puts attributes.inspect
entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017", "Time (Hours)"=>"1", "Comment"=>"yes"}
# puts entry_hash.inspect

output = {}
a = 0
entry_hash.each do |key,value|
    if value.class == Array
        output[attributes[a]] = value.first.to_s
        #output[attributes[a]] = value.first.to_i   //also you can convert them into int
    else
        output[attributes[a]] = value
    end
    a += 1

end
#puts output.inspect
#{:user_id=>1, :project_id=>"8", :task_id=>"87", :date=>"05/22/2017", :time_spent=>"1", :comment=>"yes"}
</code>```

Body:
Try this

attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]
# puts attributes.inspect
entry_hash = {"User"=>1, "Project"=>[8], "Task"=>[87], "Date"=>"05/22/2017", "Time (Hours)"=>"1", "Comment"=>"yes"}
# puts entry_hash.inspect

output = {}
a = 0
entry_hash.each do |key,value|
    if value.class == Array
        output[attributes[a]] = value.first.to_s
        #output[attributes[a]] = value.first.to_i   //also you can convert them into int
    else
        output[attributes[a]] = value
    end
    a += 1

end
#puts output.inspect
#{:user_id=>1, :project_id=>"8", :task_id=>"87", :date=>"05/22/2017", :time_spent=>"1", :comment=>"yes"}


问:
If else statement with string JavaScript
I am designing a page where can display score when the users make their choices.

However, this code seems not working and does not show any result in the 'score' field.
My Html code:

```<code><tr>
  <td>
    <div>
      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>
    </div>
  </td>

  <td><input type="text" id="score" name="score" autocomplete="off"></td>
</tr>
</code>```

My Script is below:

```<code>var type = document.getElementById("type");
var score = document.getElementById("score");

if (type === 0) {
  score.value = 0;
} else if (type === 'basketball') {
  score.value = 1;
} else if (type === 'soccer') {
  score.value = 2;
} else if (type === 'table tenis') {
  score.value = 3;
}
</code>```

答:
```<code>// you forgot to attach the value property of the type element
var typeValue = document.getElementById("type").value;
// the result for typeValue is allways a string or undefined

var scoreElement = document.getElementById("score");

// a swtich case is more efficient here
swtich(typeValue){
  case 'basketball':
    scoreElement.value = 1;
    break;
  case 'soccer':
    scoreElement.value = 2:
    break;
  case 'table tenis'
    scoreElement.value = 3;
    break;
  default:
    sourceElement.value = 0;
}
</code>```

Body:
I am designing a page where can display score when the users make their choices.

However, this code seems not working and does not show any result in the 'score' field.
My Html code:

      <input list="typeList" name="type" id="type">
      <datalist id="typeList">
        <option value="basketball">
        <option value="soccer">
        <option value="table tenis">
      </datalist>

  <input type="text" id="score" name="score" autocomplete="off">

My Script is below:

var type = document.getElementById("type");
var score = document.getElementById("score");

if (type === 0) {
  score.value = 0;
} else if (type === 'basketball') {
  score.value = 1;
} else if (type === 'soccer') {
  score.value = 2;
} else if (type === 'table tenis') {
  score.value = 3;
}


问:
Create shared_ptr to stack object
In my method a Player object is created like:

```<code>Player player(fullName,age);
</code>```

My teacher gave us a piece of code with a constructor that takes a shared_ptr to a player object.

```<code>//constructor of the class
SomeClass(const std::shared_ptr<Socket> client, std::shared_ptr<Player> player)
</code>```

Lets say we want to call the constructor of SomeClass and pass the player object we created on stack.

Is it ever safe/possible/good to create a shared_ptr from a stack object?

To make the question more understandable lets say we have two big code projects and we want to merge them so a method from one project is called from another one, should we rewrite all the files to use shared_ptr or stack objects exclusivly (for the methods that needs to be connected) or should we just create a shared_ptr to the stack object.

Why im not sure of the result:

What if the scope where the stackobject is created ends but the shared_ptr is still used and vise versa.

The stackobject gets deleted when out of scope or does it stay alive because there is still a reference to the object (in another class though)?

The shared_ptr goes out of scope and tries to delete the object, can it even though the stackobject is refering to it?

Note: I know I could just use the following and pass player

```<code>shared_ptr<Player> player{ new Player {fullName,age} };
</code>```

答:
Safe is a strong word.
However, You can make the code safer by defining a StackObjectSharedPtr, forcing the shared_ptr instanciated type to include a "special" StackObjectDeleter

```<code>using PlayerStackSP = std::shared_ptr <Player, StackObjectDeleter> ;

class StackObjectDeleter {
public:
    void operator () (void*) const {}
};

Player player(fullName,age);
std::shared_ptr<PlayerStackSP, StackObjectDeleter> player(&player, StackObjectDeleter());
</code>```

The StackObjectDeleter replaces the default_delete as the deleter object. default_delete simply calls delete (or delete []). In case of StackObjectDeleter, nothing will happen.

This is a step further of @Nicol Bolas's answer.

Title: Create shared_ptr to stack object

Body:
In my method a Player object is created like:

Player player(fullName,age);

My teacher gave us a piece of code with a constructor that takes a shared_ptr to a player object.

//constructor of the class
SomeClass(const std::shared_ptr<Socket> client, std::shared_ptr<Player> player)

Lets say we want to call the constructor of SomeClass and pass the player object we created on stack.

Is it ever safe/possible/good to create a shared_ptr from a stack object?

To make the question more understandable lets say we have two big code projects and we want to merge them so a method from one project is called from another one, should we rewrite all the files to use shared_ptr or stack objects exclusivly (for the methods that needs to be connected) or should we just create a shared_ptr to the stack object.

Why im not sure of the result:

What if the scope where the stackobject is created ends but the shared_ptr is still used and vise versa.

The stackobject gets deleted when out of scope or does it stay alive because there is still a reference to the object (in another class though)?

The shared_ptr goes out of scope and tries to delete the object, can it even though the stackobject is refering to it?

Note: I know I could just use the following and pass player

shared_ptr<Player> player{ new Player {fullName,age} };

Body:
Safe is a strong word.
However, You can make the code safer by defining a StackObjectSharedPtr, forcing the shared_ptr instanciated type to include a "special" StackObjectDeleter

using PlayerStackSP = std::shared_ptr <Player, StackObjectDeleter> ;

class StackObjectDeleter {
public:
    void operator () (void*) const {}
};

Player player(fullName,age);
std::shared_ptr<PlayerStackSP, StackObjectDeleter> player(&player, StackObjectDeleter());

The StackObjectDeleter replaces the default_delete as the deleter object. default_delete simply calls delete (or delete []). In case of StackObjectDeleter, nothing will happen.

This is a step further of @Nicol Bolas's answer.


问:
UITextfield validation
I am trying to validate my text fields. I have two textfields Username and Password. I want to check that if the username textfield is kept empty then do not allow the user to move to the password textfield until he enters the username. Any sample code to do this will be much appreciated.

Thanks in advance.

答:
disable your password textField in viewDidLoad

```<code>yourPassWordTextField.enabled=NO;
</code>```

and add a notification on textField by using

```<code>NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

    [notificationCenter addObserver:self
                           selector:@selector (handle_TextFieldTextChanged:)
                               name:UITextFieldTextDidChangeNotification
                             object:self.yourUserIdTextField];

- (void) handle_TextFieldTextChanged:(id)notification {

    if(![yourUserIdTextField.text isEqualToString:@""])
    {
          yourPassWordTextField.enabled=YES;
    }
       else
      yourPassWordTextField.enabled=NO;
}
</code>```

in .h file

```<code>-(void)registerForTextFieldNotifications;
</code>```

declair this also.

Title: UITextfield validation

Body:
disable your password textField in viewDidLoad

yourPassWordTextField.enabled=NO;

and add a notification on textField by using

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

    [notificationCenter addObserver:self
                           selector:@selector (handle_TextFieldTextChanged:)
                               name:UITextFieldTextDidChangeNotification
                             object:self.yourUserIdTextField];

- (void) handle_TextFieldTextChanged:(id)notification {

    if(![yourUserIdTextField.text isEqualToString:@""])
    {
          yourPassWordTextField.enabled=YES;
    }
       else
      yourPassWordTextField.enabled=NO;
}

in .h file

-(void)registerForTextFieldNotifications;

declair this also.


问:
Location of public class method 'new' of 'Class'
Ruby's Class class lists two methods named 'new':

Class::new is a public class method

Class#new is a public instance method

But when I do:

```<code>Class.methods(false)
#=> []
</code>```

which is supposed to list singleton methods (which I am assuming what class methods are), I get an empty array. Why is this so? Where is Class::new defined?

答:
new is defined as a instance method of Class class, rather than a singleton method:

```<code>Class.instance_method :new     # => #<UnboundMethod: Class#new>
</code>```

Tricky to note: Class (object) itself is also an instance of Class (class).

```<code>Class.instance_of? Class       # => true
</code>```

Body:
Ruby's Class class lists two methods named 'new':

Class::new is a public class method

Class#new is a public instance method

But when I do:

Class.methods(false)
#=> []

which is supposed to list singleton methods (which I am assuming what class methods are), I get an empty array. Why is this so? Where is Class::new defined?

Body:
new is defined as a instance method of Class class, rather than a singleton method:

Class.instance_method :new     # => #<UnboundMethod: Class#new>

Tricky to note: Class (object) itself is also an instance of Class (class).

Class.instance_of? Class       # => true


答:
Here you go with pure JavaScript along with jsfiddle https://jsfiddle.net/4oyrw61w/</p>

```<code>document.getElementById('type').addEventListener('input', function () {
    var type = document.getElementById("type").value;
    var score = document.getElementById("score");

    if (type === '0') {
        score.value = 0;
    } else if (type === 'basketball') {
      score.value = 1;
    } else if (type === 'soccer') {
      score.value = 2;
    } else if (type === 'table tenis') {
      score.value = 3;
    }
 });
</code>```

Title: If else statement with string JavaScript

Body:
Here you go with pure JavaScript along with jsfiddle https://jsfiddle.net/4oyrw61w/

document.getElementById('type').addEventListener('input', function () {
    var type = document.getElementById("type").value;
    var score = document.getElementById("score");

    if (type === '0') {
        score.value = 0;
    } else if (type === 'basketball') {
      score.value = 1;
    } else if (type === 'soccer') {
      score.value = 2;
    } else if (type === 'table tenis') {
      score.value = 3;
    }
 });


问:
retrieving data in Indian language from MySql database using php shows unusual character set
I am retrieving data in Indian language and I am getting output as ??????????????????????????

NOTE : - I used this 2 line in my php script

```<code>header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');
</code>```

and also I used utf8_general_ci encoding in databse and table.

my php script is

```<code><?php

require 'init.php';

header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');

$table = $_GET['table_name'];

$sql = "SELECT * FROM ".$table;

$response = array();

$result = mysqli_query($conn,$sql);

if(mysqli_num_rows($result)>0) {
        while($row = mysqli_fetch_array($result)) {
        array_push($response, array('id'=>$row['id'],'text'=>$row['text']));
    }
    echo json_encode($response);
} else {
    echo "error";
}

mysqli_close($conn);

?>
</code>```

You can check the link http://www.sharefb.com/statusApp/readStatus.php?table_name=gujrati_attitude

答: Use mysqli_set_charset( $db, 'utf8');</p>

Body:
I am retrieving data in Indian language and I am getting output as ??????????????????????????

NOTE : - I used this 2 line in my php script

header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');

and also I used utf8_general_ci encoding in databse and table.

my php script is

<?php

require 'init.php';

header('Content-type: text/plain; charset=utf-8');
mysqli_set_charset($conn,'utf-8');

$table = $_GET['table_name'];

$sql = "SELECT * FROM ".$table;

$response = array();

$result = mysqli_query($conn,$sql);

if(mysqli_num_rows($result)>0) {
        while($row = mysqli_fetch_array($result)) {
        array_push($response, array('id'=>$row['id'],'text'=>$row['text']));
    }
    echo json_encode($response);
} else {
    echo "error";
}

mysqli_close($conn);

?>

You can check the link http://www.sharefb.com/statusApp/readStatus.php?table_name=gujrati_attitude

Body: Use mysqli_set_charset( $db, 'utf8');