问:
jQuery add or remove class based on menu item clicked
I tried this, searched on StackOverflow.

```<code>$(".sub>li>a").click(function(e) {
    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});
</code>```

But it does not work.

Here is my fiddle. https://jsfiddle.net/v2oLfcnf/

答:
Maker sure jQuery is included.

var study1= 0;
$("#info").click(function(){
 study1++;
  if(study1%2==1){
   $(".one").fadeIn('fast');

  }else{
   $(".one").fadeOut();
   $(".two").fadeOut();
   $(".three").fadeOut();
   $(".four").fadeOut();
  }
 });

  var study= 0;
$("#study").click(function(){
 study++;
  if(study%2==1){
   $(".two").fadeIn('fast');

  }else{
   $(".one").fadeOut();
   $(".two").fadeOut();
   $(".three").fadeOut();
   $(".four").fadeOut();
  }
 });

  $(".sub>li>a").click(function(e) {

    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code> a{
   text-decoration: none;
   color: white;
  }
  a:hover{
   color: #D8B490;
  }

  li{
   text-decoration: none;
   list-style: none;

  }
    .sub{
 position: relative;

 top: 20%;
}
#info,#study,#edu,#sup{
   display: inline-block;z-index: 5;
   position: relative;

   margin: 2%;

  }
  #top{
  z-index: 80;
  background:#D8B490;
  width: 100%;}
.menu{
  position: absolute;
  top:5%;
   background: /*#69341C;*/ #302F42;
   color: white;
   height: 100px;
   z-index:55;
  width: 100%;
   }
.sub{
 display: inline-block;

}

/*hide menu, if clicked .sub>li>a , fadeIn() below*/
  .one{

   width: 50%;
   height: 20%;
   display: block;
   background: white;
   position: absolute;
   left: 40%;
   top: 88%;
   color: red;
   display: none;
  }

  .two{
  display: none;
    color: red;
   width: 50%;
   height: 20%;

   background: white;
   position: absolute;
   left: 40%;
   top: 88%;

  }

  .three{
   display: none;
    color: red;
   width: 50%;
   height: 20%;

   background: white;
   position: absolute;
   left: 40%;
   top: 88%;
  }
  .four{
   display: none;

   width: 50%;
   height: 20%;
    color: red;
   background: white;
   position: absolute;
   left: 40%;
   top: 88%;
  }</code>```

      infomation

a

b

      study

c

d

     edu

e

f

     support

g

h

```

Body:
I tried this, searched on StackOverflow.

$(".sub>li>a").click(function(e) {
    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});

But it does not work.

Here is my fiddle. https://jsfiddle.net/v2oLfcnf/

Body:
Maker sure jQuery is included.

var study1= 0;
$("#info").click(function(){
 study1++;
  if(study1%2==1){
   $(".one").fadeIn('fast');

  }else{
   $(".one").fadeOut();
   $(".two").fadeOut();
   $(".three").fadeOut();
   $(".four").fadeOut();
  }
 });

  var study= 0;
$("#study").click(function(){
 study++;
  if(study%2==1){
   $(".two").fadeIn('fast');

  }else{
   $(".one").fadeOut();
   $(".two").fadeOut();
   $(".three").fadeOut();
   $(".four").fadeOut();
  }
 });

  $(".sub>li>a").click(function(e) {

    if( $(this).hasClass("open") ) {
        $(this).removeClass("open").addClass("closed");
    } else {
        // if other menus are open remove open class and add closed
        $(this).siblings().removeClass("open").addClass("closed");
        $(this).removeClass("closed").addClass("open");
    }
});

 a{
   text-decoration: none;
   color: white;
  }
  a:hover{
   color: #D8B490;
  }

  li{
   text-decoration: none;
   list-style: none;

  }
    .sub{
 position: relative;

 top: 20%;
}
#info,#study,#edu,#sup{
   display: inline-block;z-index: 5;
   position: relative;

   margin: 2%;

  }
  #top{
  z-index: 80;
  background:#D8B490;
  width: 100%;}
.menu{
  position: absolute;
  top:5%;
   background: /*#69341C;*/ #302F42;
   color: white;
   height: 100px;
   z-index:55;
  width: 100%;
   }
.sub{
 display: inline-block;

}

/*hide menu, if clicked .sub>li>a , fadeIn() below*/
  .one{

   width: 50%;
   height: 20%;
   display: block;
   background: white;
   position: absolute;
   left: 40%;
   top: 88%;
   color: red;
   display: none;
  }

  .two{
  display: none;
    color: red;
   width: 50%;
   height: 20%;

   background: white;
   position: absolute;
   left: 40%;
   top: 88%;

  }

  .three{
   display: none;
    color: red;
   width: 50%;
   height: 20%;

   background: white;
   position: absolute;
   left: 40%;
   top: 88%;
  }
  .four{
   display: none;

   width: 50%;
   height: 20%;
    color: red;
   background: white;
   position: absolute;
   left: 40%;
   top: 88%;
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="menu">
   <ul class="sub">
    <li>
     <a href="#" id="info"> infomation</a>
    </li>

   </ul>

   <ul class="one">
      <li>a</li>
      <li>b</li>
     </ul>

   <ul class="sub">
    <li>
     <a href="#" id="study"> study</a>

    </li>

   </ul>
   <ul class="two">
      <li>c</li>
      <li>d</li>
     </ul>

   <ul class="sub">
    <li>
     <a href="#" id="edu">edu</a>

    </li>

   </ul>
   <ul class="three">
      <li>e</li>
      <li>f</li>
     </ul>

   <ul class="sub">
    <li>
     <a href="#" id="sup">support</a>

    </li>

   </ul>

   <ul class="four">
      <li>g</li>
      <li>h</li>
     </ul>
  </div>


来源: stackexchange

问:
in Java is variable memory space allocated dynamically or statically?
If we run this line of code

```<code>long num = 5;
</code>```

Does this variable have 64 bits of space? Or is the size determined by the value put in side? Logically it should be 64 bits as primitive datatypes are mutable. But is my conclusion true?

Furthermore, if we have an immutable object such as a string

```<code>String str = "Hello World";
</code>```

Giving this String the maximum memory by default seems counter intuitive. If you were to set a String and then change it you would just change the pointer into the memory address of the second String, the newly created one.

Could someone please answer this question or point me in the right direction?

答:
long is a 64-bit primitive value, regardless of what actual value you keep inside.

String is a class that wraps a char[]. The internal array has different sizes depending on the amount of characters inside. 16-bits¹ per char.

¹ It's a bit more complicated than that, but generally speaking it's 16-bits per char.

ContentLicense: CC BY-SA 3.0

Body:
If we run this line of code

long num = 5;

Does this variable have 64 bits of space? Or is the size determined by the value put in side? Logically it should be 64 bits as primitive datatypes are mutable. But is my conclusion true?

Furthermore, if we have an immutable object such as a string

String str = "Hello World";

Giving this String the maximum memory by default seems counter intuitive. If you were to set a String and then change it you would just change the pointer into the memory address of the second String, the newly created one.

Could someone please answer this question or point me in the right direction?


问:
AVA: setup different timeout for each test case
I writing asynchronous tests using AVA, and need to setup custom timeout for each test cases. I've not found out any information about this possibility and my tests seems like this:

import test from 'ava';

test.cb('super test', t => {
    setTimeout(() => {
        t.is(1, 1);
        t.end();
    }, 10000);

    setTimeout(() => {
        t.fail("Timeout error!");
        t.end();
    }, 100);
});```

Does anybody know another way to implement this in AVA?

答:
There's an open issue to support this in AVA itself: https://github.com/avajs/ava/issues/1565

Until that lands you'll have to manage a timer yourself. Don't forget to clear it once your normal test completes.

Body:
I writing asynchronous tests using AVA, and need to setup custom timeout for each test cases. I've not found out any information about this possibility and my tests seems like this:

import test from 'ava';

test.cb('super test', t => {
    setTimeout(() => {
        t.is(1, 1);
        t.end();
    }, 10000);

    setTimeout(() => {
        t.fail("Timeout error!");
        t.end();
    }, 100);
});

Does anybody know another way to implement this in AVA?


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
You need something that you need/want to accomplish.

Sit down and create it.

While you are creating it you will have to figure out the things you don't know.  It's probably the best way to identify what those things are.

When you are done and have something working you look back on it and think about what you could have done differently to organize it better.

Do some research about those specific things and possible ways to approach it.

Create something else and reflect on that.

Repeat until you have an a-ha moment.

For me my first a-ha moment was being taught Honeywell assembler during my 3rd week of training and finally realizing how the computer really worked.

My OOP a-ha moment was during a Real Time Relay Ladder Logic course and I decided to make a library to simulate the Texas Instrument hardware that we had to write our programs against.  It let me write/test my programs for the class without having to go to the school and use the real hardware.  It opened my eyes to OOP.  I believe the a-ha moment happened because I was able to model (with code) something that was real.

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: bruceatk


问:
How to get different values from 2 object arrays using underscore js
How to get different values from 2 object arrays using underscore js.
I have 2 object arrays like this

```<code>var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];
</code>```

My result should be like this

```<code>[{
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}]
</code>```

Is there any inbuilt functions to this in underscorejs

答:
You could achieve it using _.reject and _.findWhere.

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

var newArr = _.reject(a, function(obj) {
  return _.findWhere(b, obj)
})

console.log(newArr)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script></code>```

Body:
How to get different values from 2 object arrays using underscore js.
I have 2 object arrays like this

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

My result should be like this

[{
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}]

Is there any inbuilt functions to this in underscorejs

Body:
You could achieve it using _.reject and _.findWhere.

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

var newArr = _.reject(a, function(obj) {
  return _.findWhere(b, obj)
})

console.log(newArr)

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
Incorrect wxpython version
I have installed wxPython 2.8.12.1 (unicode) for python 2.7. but when I check the version it shows as 4.0.0b2 msw (phoenix)

When check the version it shows as follows:

print wx.version()                                                                                4.0.0b2 msw (phoenix)

答:
There seem to be two possible explanations:

You have two python instances on your machine and the one where you typed print wx.version() is not the one where you installed wxPython classic

(more likely): You did at one point in time pip install wxPython which will currently install 4.0.0b2 msw (phoenix)

I do not know which version will be imported when you somehow manage to install classic and phoenix.

Recommendation: Uninstall from Windows setup 2.8.12.1 and continue with phoenix.

The only reason to use the completely outdated 2.8.12.1 (released somewhere in 2010/11) is if you have a huge app which cannot be ported to a newer wxPython.

Title: Incorrect wxpython version


问:
VSTO 2010 excel addins cannot be loaded on target xp machine
I published my excel addins with clickonce on vs2010.
It`s prerequisites contains .net framework 4 client,vsto 2010 and installer3.5.

Deploying it on win7 works well,when I deploy it on xp,installing no error occured,
but it(com) cannot loaded when run excel app.

I tried mang mehods,only when I manually installed .net framework 2.0 or 3.0 or 3.5
my addin will appear

I donot know why.

thanks

答: Here's a dumb question, when deploying are your users installing the .vsto or the setup.exe (aka bootstrap). If they are installing the just the .vsto file they aren't getting any of the pre-reqs. They live in the setup.exe. Also are you installing the PIAs (or are you using the embedded PIAs which is new to 2010)? Win7 machines tend to have the right pre-reqs but when you go back in time on XP they don't.</p>


问:
How to update some data in SQL server into null for Classic ASP
I want to make update function in a web based system using Classic ASP to enable the user to cancel their application. I'm not using delete function because some data should be maintained, and some data will be set into NULL. This function also allow the user to choose date range in a form to delete their application.

There is no error shown but the set of data is not updated when click on cancel button in the form.

This is the code :

```<code><%param="keyid=" & session("keyid")
idkehadiran=request("idkehadiran")
nokpl=request("nokpl")

set SimpanRS=server.CreateObject("adodb.recordset")
sql="select * from tms_kehadiran where nokpl='"&nokpl&"' and (tarikh >= '"&tarikh&"' and tarikh <= '"&hinggaTarikh&"')"
SimpanRS.open sql,connehr,3,3

while not SimpanRS.EOF
SimpanRS("alasan")=""
SimpanRS("nokpPenyelia")=""
SimpanRS("kelulusan")=null
if isnull(SimpanRS("datecreated")) then
SimpanRS("datecreated")=now
end if
SimpanRS("lastupdate")=now

SimpanRS.update
SimpanRS.movenext
wend
SimpanRS.close
set SimpanRS=nothing
%>
</code>```

I don't what are the error with this code. Can anyone help me ?

答:
Instead of looping the RS. You should use GetRows().

After that you can update the data in the SQL server while looping the array.

Body:
I want to make update function in a web based system using Classic ASP to enable the user to cancel their application. I'm not using delete function because some data should be maintained, and some data will be set into NULL. This function also allow the user to choose date range in a form to delete their application.

There is no error shown but the set of data is not updated when click on cancel button in the form.

This is the code :

<%param="keyid=" & session("keyid")
idkehadiran=request("idkehadiran")
nokpl=request("nokpl")

set SimpanRS=server.CreateObject("adodb.recordset")
sql="select * from tms_kehadiran where nokpl='"&nokpl&"' and (tarikh >= '"&tarikh&"' and tarikh <= '"&hinggaTarikh&"')"
SimpanRS.open sql,connehr,3,3

while not SimpanRS.EOF
SimpanRS("alasan")=""
SimpanRS("nokpPenyelia")=""
SimpanRS("kelulusan")=null
if isnull(SimpanRS("datecreated")) then
SimpanRS("datecreated")=now
end if
SimpanRS("lastupdate")=now

SimpanRS.update
SimpanRS.movenext
wend
SimpanRS.close
set SimpanRS=nothing
%>

I don't what are the error with this code. Can anyone help me ?


问:
How to size an Image of a button?
I have the following Layout

```<code>            <Button
                android:layout_width="fill_parent"
                android:layout_height="75dp"
                android:drawableLeft="@drawable/binocular"
                android:gravity="left|center_vertical"
                android:text="search" />
</code>```

and it looks like :

The picture is too large. I simply want to align the image to the left with the corredct size, so it fits with the height of the button.

I know I could adjust the bound of the image by code. But I would like to know, if there is a way to do with layout specification.

There is a solution mentoined : how to change a drawableLeft icon size on a button? (accepted answer)

I guess this is the correct one, but I do not understand , where to put the layer-list and how to reference it in the button.

Can someone help ?

答:
use ImageButton with these properties

```<code><ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
 />
</code>```

padding plays very important role in sizing the image after scaleType fails.

hope this will help you.

Title: How to size an Image of a button?

Body:
I have the following Layout

            <Button
                android:layout_width="fill_parent"
                android:layout_height="75dp"
                android:drawableLeft="@drawable/binocular"
                android:gravity="left|center_vertical"
                android:text="search" />

and it looks like :

The picture is too large. I simply want to align the image to the left with the corredct size, so it fits with the height of the button.

I know I could adjust the bound of the image by code. But I would like to know, if there is a way to do with layout specification.

There is a solution mentoined : how to change a drawableLeft icon size on a button? (accepted answer)

I guess this is the correct one, but I do not understand , where to put the layer-list and how to reference it in the button.

Can someone help ?

Body:
use ImageButton with these properties

<ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
 />

padding plays very important role in sizing the image after scaleType fails.

hope this will help you.


问:
How to execute multiple if statements optimally in swift ios
I have defined a function which executes multiple if-statements. although it executes only if-statements but not executing else statements in a flow in which it is defined. What I have to do to execute else statements just after the respective call of related if statements.</p>

```<code>  func levelTwo() {

    if firstText.text == "A"
    {
        hintLabel.text = "\(self.hintsTwo[1])"
        self.firstValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.firstValid.image = #imageLiteral(resourceName: "markQ")
    }

    if SecFirstText.text == "A" && secSecText.text == "C"
    {
        hintLabel.text = "\(self.hintsTwo[2])"
        self.secondValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.secondValid.image = #imageLiteral(resourceName: "markQ")
    }

    if thiFirstText.text == "C" && thiSecText.text == "A" && thiThirdText.text == "T"
    {
        hintLabel.text = "\(self.hintsTwo[3])"
        self.thirdValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.thirdValid.image = #imageLiteral(resourceName: "markQ")
    }

}
</code>```

答:
You can use switch with tuples:</p>

```<code>switch(firstText.text, thiSecText.text) {
    case ("A", _):
        //First text equal a, second text equal anything
        break
    case ("A", "C"):
        //First text A, second text B
        break
    case (_, "B"):
        //First text anything, second text B
        break
    default:
        break
}
</code>```

Body:
I have defined a function which executes multiple if-statements. although it executes only if-statements but not executing else statements in a flow in which it is defined. What I have to do to execute else statements just after the respective call of related if statements.

  func levelTwo() {

    if firstText.text == "A"
    {
        hintLabel.text = "\(self.hintsTwo[1])"
        self.firstValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.firstValid.image = #imageLiteral(resourceName: "markQ")
    }

    if SecFirstText.text == "A" && secSecText.text == "C"
    {
        hintLabel.text = "\(self.hintsTwo[2])"
        self.secondValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.secondValid.image = #imageLiteral(resourceName: "markQ")
    }

    if thiFirstText.text == "C" && thiSecText.text == "A" && thiThirdText.text == "T"
    {
        hintLabel.text = "\(self.hintsTwo[3])"
        self.thirdValid.image = #imageLiteral(resourceName: "check")
    }
    else {
        self.thirdValid.image = #imageLiteral(resourceName: "markQ")
    }

}

Body:
You can use switch with tuples:

switch(firstText.text, thiSecText.text) {
    case ("A", _):
        //First text equal a, second text equal anything
        break
    case ("A", "C"):
        //First text A, second text B
        break
    case (_, "B"):
        //First text anything, second text B
        break
    default:
        break
}


问:
Spring Boot: Make property non-configurable
In Spring Boot I have several options to externalize my configuration. However, how can I make such properties non-configurable, i.e. readonly.

Concretly, I want to set server.tomcat.max-threads to a fixed value and do not want somebody who is going to start the application to have the ability to change it. This could easily be done by passing it as a command line argument for instance.

It's probably not possible by default, maybe someone could suggest workarounds?

答:
I ended up implementing an ApplicationContextInitializer (Docu), which in its initialize() method simply sets the static value programatically:

```<code>@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    Map<String, Object> props = new HashMap<>();
    props.put(MAX_THREADS, MAX_THREADS_VAL);
    environment.getPropertySources().addFirst(new MapPropertySource("tomcatConfigProperties", props));

}
</code>```

Another possible solution was found here: Prevent overriding some property in application.properties - Spring Boot

Body:
I ended up implementing an ApplicationContextInitializer (Docu), which in its initialize() method simply sets the static value programatically:

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    Map<String, Object> props = new HashMap<>();
    props.put(MAX_THREADS, MAX_THREADS_VAL);
    environment.getPropertySources().addFirst(new MapPropertySource("tomcatConfigProperties", props));

}

Another possible solution was found here: Prevent overriding some property in application.properties - Spring Boot


答:
Why don't you try to have a generic status (closed), and on click, toggle class open which would be more specific ? I'm just assuming that the initial state is closed

```<code><style>
    .closed {
        /*code*/
    }
    div.open {
        /*status when open*/
    }
</style>
<script>
    $(.closed).on('click', function(){
        this.toggleClass('open');
    }
</script>
</code>```

I'm not an expert with jQuery syntax but this might work

edit :

jQuery might be pretty heavy just for this, don't hesitate to look at addEventListener which is implemented on every browser nowaday

Title: jQuery add or remove class based on menu item clicked

Body:
Why don't you try to have a generic status (closed), and on click, toggle class open which would be more specific ? I'm just assuming that the initial state is closed

<style>
    .closed {
        /*code*/
    }
    div.open {
        /*status when open*/
    }
</style>
<script>
    $(.closed).on('click', function(){
        this.toggleClass('open');
    }
</script>

I'm not an expert with jQuery syntax but this might work

edit :

jQuery might be pretty heavy just for this, don't hesitate to look at addEventListener which is implemented on every browser nowaday


答:
From JLS §4.2 and §4.2.1:

The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).

The floating-point types are float, whose values include the 32-bit IEEE 754 floating-point numbers, and double, whose values include the 64-bit IEEE 754 floating-point numbers.

Clearly for these primitives to be able to have minimum and maximum values, they need to be represented by a fixed amount of memory, so it cannot be variable.

Regarding String, each object is backed by a char[] (up until JDK 9), which has a fixed length.

Title: in Java is variable memory space allocated dynamically or statically?


问:
Improper Neutralization of Script-Related HTML Tags in a Web Page (XSS)
Can anyone please help me in understanding what's wrong.

```<code> @ResponseBody
 @RequestMapping(value = "/compare", method = RequestMethod.POST,
                                     produces = { "application/json" })
    public List<A> compareDocument(HttpServletRequest request,
            @RequestBody B b) {

        C c = new C();
        c.setSourceContactCode(b.getTargetContactID());
        c.setSourceProfileID(b.getTargetProfileID());
        B b= this.Service.getAllPortfolio(c);
        List<A> targetDocument = b.getDocuments();
        return this.Service.compareDocument(b, targetDocument);
            }
</code>```

The veracode is showing me error on :

```<code>         c.setSourceProfileID(b.getTargetProfileID());
</code>```

B and C are Value Objects (Vo's) of which instances are JSON properties. All getter and setter method returns / uses String.

答:
(B) b object comes from request (user input), so Veracode considers it as untrusted data. Someone can put there script code which can be executed. For example:

```
</div>
</div>
</p>

<p>When you log this data and view through some html tool or put this data on site page it can be executed on load and lead to attacks. Veracode wants you to escape special characters like '<' and '>'.
It can be done with ESAPI tool, for example:</p>

```String encodedForHtml = ESAPI.encoder().encodeForHTML(b.getTargetProfileID());
c.setSourceProfileID(encodedForHtml);
```

This will escape special characters and string will be printed as string but not as part of html page.

Body:
Can anyone please help me in understanding what's wrong.

 @ResponseBody
 @RequestMapping(value = "/compare", method = RequestMethod.POST,
                                     produces = { "application/json" })
    public List compareDocument(HttpServletRequest request,
            @RequestBody B b) {

        C c = new C();
        c.setSourceContactCode(b.getTargetContactID());
        c.setSourceProfileID(b.getTargetProfileID());
        B b= this.Service.getAllPortfolio(c);
        List targetDocument = b.getDocuments();
        return this.Service.compareDocument(b, targetDocument);
            }

The veracode is showing me error on :

         c.setSourceProfileID(b.getTargetProfileID());

B and C are Value Objects (Vo's) of which instances are JSON properties. All getter and setter method returns / uses String.

Body:
(B) b object comes from request (user input), so Veracode considers it as untrusted data. Someone can put there script code which can be executed. For example:

<script>alert('Collect data and send to my server or other actions');</script>

When you log this data and view through some html tool or put this data on site page it can be executed on load and lead to attacks. Veracode wants you to escape special characters like '<' and '>'.
It can be done with ESAPI tool, for example:

String encodedForHtml = ESAPI.encoder().encodeForHTML(b.getTargetProfileID());
c.setSourceProfileID(encodedForHtml);

This will escape special characters and string will be printed as string but not as part of html page.


答:
the $ syntax is not a built-in Javascript API. You must have jQuery in your project in order to use it.

Just add this line, which include jquery in your project:

```<code>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
 </script>
</code>```

I updated your fiddle with the code https://jsfiddle.net/v2oLfcnf/

Body:
the $ syntax is not a built-in Javascript API. You must have jQuery in your project in order to use it.

Just add this line, which include jquery in your project:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
 </script>

I updated your fiddle with the code https://jsfiddle.net/v2oLfcnf/


问:
Controlling row height in kableExtra()
Hi i made this awesome table with kableExtra, but my only problem is that the height of the rows is not always equal. Does any one know a remedy for this?

my table:

for example, as you can see, the line for item number 22 (6th row) has a larger height (spacing) than other lines.

my code:

```<code>my_column_names = c("Item number", "Item",
                "Emotion", "Social",
                "At Home", "Body", "Emotion",
                "Social 1", "Social 2",
                "At Home", "Body")

kable(df1,
      format = "latex", booktabs = TRUE,
      col.names = my_column_names,
      caption = "Factor loadings for the 4 and 5 Factor Model") %>%
      kable_styling(latex_options = c("striped", "hold_position"),
                    full_width = FALSE) %>%
      add_header_above(c(" " = 2,
                 "4 Factor Model " = 4, "5 Factor model" = 5)) %>%
      add_header_above(c(" " = 2,
                 "Model" = 9)) %>%
      kableExtra::landscape()
</code>```

答:
Usually, this is something that you can change via CSS in an HTML table. Not sure how to do this with kableExtra but you might want to consider tableHTML to do it. I am adding a small example below to demonstrate row height:

```<code>library(tableHTML)
tableHTML(mtcars[1:10, ],
          border = 1,
          rownames = TRUE,
          caption = 'This is a caption',
          footer = 'This is a footer',
          widths = c(140, rep(50, 11)),
          second_headers = list(c(2, 5, 6), c('', 'col2', 'col3')),
          theme = 'scientific') %>%
  add_css_row(list('height', '50px'), rows = 3:12)
</code>```

You don't need to use the scientific theme if you don't want to. The package gives you flexibility to add any css you like (like striped rows, etc.). You can check a tutorial here if interested.

P.S. It currently only supports one extra header. Apart from that your whole table can be replicated.

Title: Controlling row height in kableExtra()

Body:
Hi i made this awesome table with kableExtra, but my only problem is that the height of the rows is not always equal. Does any one know a remedy for this?

my table:

for example, as you can see, the line for item number 22 (6th row) has a larger height (spacing) than other lines.

my code:

my_column_names = c("Item number", "Item",
                "Emotion", "Social",
                "At Home", "Body", "Emotion",
                "Social 1", "Social 2",
                "At Home", "Body")

kable(df1,
      format = "latex", booktabs = TRUE,
      col.names = my_column_names,
      caption = "Factor loadings for the 4 and 5 Factor Model") %>%
      kable_styling(latex_options = c("striped", "hold_position"),
                    full_width = FALSE) %>%
      add_header_above(c(" " = 2,
                 "4 Factor Model " = 4, "5 Factor model" = 5)) %>%
      add_header_above(c(" " = 2,
                 "Model" = 9)) %>%
      kableExtra::landscape()

Body:
Usually, this is something that you can change via CSS in an HTML table. Not sure how to do this with kableExtra but you might want to consider tableHTML to do it. I am adding a small example below to demonstrate row height:

library(tableHTML)
tableHTML(mtcars[1:10, ],
          border = 1,
          rownames = TRUE,
          caption = 'This is a caption',
          footer = 'This is a footer',
          widths = c(140, rep(50, 11)),
          second_headers = list(c(2, 5, 6), c('', 'col2', 'col3')),
          theme = 'scientific') %>%
  add_css_row(list('height', '50px'), rows = 3:12)

You don't need to use the scientific theme if you don't want to. The package gives you flexibility to add any css you like (like striped rows, etc.). You can check a tutorial here if interested.

P.S. It currently only supports one extra header. Apart from that your whole table can be replicated.


问:
How to add a forgot password feature for the described system without compromising its security?
I created a security system that uses the users password to encrypt the users private key which is then stored on the database. So a user can only retrieve the private key if he enters the correct password which is then used to decrypt the private key stored on the database.

This system has some admirable security features but has the flaw that it is hard to do a 'forgotten password' option. The only way I could imagine is by storing a copy of all private keys somewhere else and encrypt them with a master server password and when a user forgets his password the server allows him to re encrypt his private key with the new password.

The problem with this method is that if the master server password where somehow compromised all account information would also be compromised with it. Is there a way of adding a reset password method without having to change the system to much or compromising its security?

答: If you escrow the private keys you need to have them on another server that is not directly connected to the Internet. Then rate limit and alarm all accesses to the escrowed keys. Also consider an HSM.</p>


问:
Moving a 'UITabBarController with UINavigationController' iPhone app to 'UITabBarController with UISplitView' on iPad
I have an app where the appDelegate has a UITabBarController.  Each of the tabs has a navigation controller which I currently use to push a single detail view onto the stack in each tab.  I am hoping to replace my navigation controller on each of the tabs with a splitViewController.  I use the Interface builder to provide the UINavigationController for each tab.  I am having trouble loading a nib for each tab that has a UISplitViewController in it.  I am getting an instance of the UITableViewController class displaying on the screen, but I am not getting the UISplitviewController or the Popover or the detail view etc.  These classes are all working in a standalone app, but I am not able to get them into each of the tabs in one app.  Although I am currently using the Interface Builder I am open to doing this programmatically. If someone has suggestions, or an example small project of a Tab based app with individual split views in the tabs I would appreciate it very much.  (As this is my first question I am not sure how much code or other pictures from IB would be helpful for me to post.  If you need further detail please let me know and I would gladly amend this post.)</p>

答: Not only shouldn't you -- if you do so, an error is thrown when you run. It's impossible.</p>


问:
CSS hover slide out flashes text too early
I have created a list of glyphicons, and when you hover over each glyphicon it displays expanding text.

The issue I am facing is that if the text is long it will flash over the glyphicon's container before the css transition has happened.

Here is a fiddle example (notice the second box on hover).

I have tried playing around with the transitions and getting the text to display after the transition has finished.

My HTML:

```<code><div class="myContainer">
  <div id="myNav">
    <ul class="subMenu">
      <li class="listItem"><a href="#">List Item 1</a></li>
      <li class="listItem"><a href="#">List Item 2 with long text</a></li>
    </ul>
  </div>
</div>
</code>```

My CSS:

```<code>.subMenu .listItem {
  clear:both;
  list-style: none;
  height:15px;
  width: 15px;
  color: transparent;
  cursor: pointer;
  float: right;
  background: #ededed url(https://static.tumblr.com/ftv85bp/MIXmud4tx/search-icon.png) no-repeat 10px center;
  border: solid 1px #ccc;
  padding: 9px 12px 9px 10px;
  -webkit-transition: all .5s;
  -moz-transition: all .5s;
  transition: all .5s;
}

.subMenu .listItem:hover {
  width: 100%;
  color: #000;
  cursor: auto;
  background: #fff
}

.subMenu .listItem a {
  color: transparent;
}

.subMenu .listItem:hover a{
  color: #000;
}
</code>```

答:
You could put overflow:hidden; in .listItem and force the line not break using white-space:nowrap; on the link.

new code fiddle

final code:

```<code>#myNav {
  width: 50%;
}

.subMenu .listItem {
  clear:both;
  list-style: none;
  height:15px;
  width: 15px;
  color: transparent;
  cursor: pointer;
  float: right;
  background: #ededed url(https://static.tumblr.com/ftv85bp/MIXmud4tx/search-icon.png) no-repeat 10px center;
  border: solid 1px #ccc;
  padding: 9px 12px 9px 10px;
  -webkit-transition: all .5s;
  -moz-transition: all .5s;
  transition: all .5s;
  overflow: hidden;
}

.subMenu .listItem:hover {
  width: 100%;
  color: #000;
  cursor: auto;
  background: #fff
}

.subMenu .listItem a {
  color: transparent;
  white-space:nowrap;
}

.subMenu .listItem:hover a{
  color: #000;
}
</code>```

hope this helps. =D

Body:
I have created a list of glyphicons, and when you hover over each glyphicon it displays expanding text.

The issue I am facing is that if the text is long it will flash over the glyphicon's container before the css transition has happened.

Here is a fiddle example (notice the second box on hover).

I have tried playing around with the transitions and getting the text to display after the transition has finished.

My HTML:

List Item 1

List Item 2 with long text

My CSS:

.subMenu .listItem {
  clear:both;
  list-style: none;
  height:15px;
  width: 15px;
  color: transparent;
  cursor: pointer;
  float: right;
  background: #ededed url(https://static.tumblr.com/ftv85bp/MIXmud4tx/search-icon.png) no-repeat 10px center;
  border: solid 1px #ccc;
  padding: 9px 12px 9px 10px;
  -webkit-transition: all .5s;
  -moz-transition: all .5s;
  transition: all .5s;
}

.subMenu .listItem:hover {
  width: 100%;
  color: #000;
  cursor: auto;
  background: #fff
}

.subMenu .listItem a {
  color: transparent;
}

.subMenu .listItem:hover a{
  color: #000;
}

Body:
You could put overflow:hidden; in .listItem and force the line not break using white-space:nowrap; on the link.

new code fiddle

final code:

#myNav {
  width: 50%;
}

.subMenu .listItem {
  clear:both;
  list-style: none;
  height:15px;
  width: 15px;
  color: transparent;
  cursor: pointer;
  float: right;
  background: #ededed url(https://static.tumblr.com/ftv85bp/MIXmud4tx/search-icon.png) no-repeat 10px center;
  border: solid 1px #ccc;
  padding: 9px 12px 9px 10px;
  -webkit-transition: all .5s;
  -moz-transition: all .5s;
  transition: all .5s;
  overflow: hidden;
}

.subMenu .listItem:hover {
  width: 100%;
  color: #000;
  cursor: auto;
  background: #fff
}

.subMenu .listItem a {
  color: transparent;
  white-space:nowrap;
}

.subMenu .listItem:hover a{
  color: #000;
}

hope this helps. =D


问:
React-Native react-navigation from another file
I have problem with navigation in RN, so I thought you could help me. I can't find any way to navigate from my "settings" tab to my "SignedOut", this is my repo, code is not complicated, all you have to look is in "navigation" and "screens" folder. Thing is my "settings" file is in one file "MainTabNavigator" and SignedOut is in "RootNavigation", and when i try something like this:

```<code>this.props.navigation.navigate("SignedOut");
</code>```

nothing happend, here is my function for this:

```<code>onSignOut()
.then(() => {
    console.log('Logout!');
    this.props.navigation.navigate("SignedOut");
})
.catch(e => {
    console.log(e);
})
</code>```

I do get this log printed out so it should call this navigation method successfully. Do you have any ideas why? I mean, I think that this is the reason maybe I am missing something here?

This is what my MainTabNavigator looks like:

```<code>import React from 'react';
import { Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { TabNavigator, TabBarBottom, DrawerNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import HomeScreen from '../screens/HomeScreen';
import ListScreen from '../screens/ListScreen';
import SettingsScreen from '../screens/SettingsScreen';
import WordDetails from '../screens/WordDetails';
import DrawerMenu from './drawerDesign/Drawer';

export default DrawerNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
    List: {
      screen: ListScreen,
    },
    Settings: {
      screen: SettingsScreen,
    },
    WordDetails: {
      screen: WordDetails,
    },
  }, {
    contentComponent: DrawerMenu,
    drawerWidth: 200,
    drawerPosition: "right",
    contentOptions: {
      activeTintColor: '#e91e63',
      itemsContainerStyle: {
        marginVertical: 0,
        opacity: 0.6

      },
      iconContainerStyle: {
        opacity: 0.6
      },
      style: {
        flex: 1,
        paddingTop: 35,
      },
    }
  }
);
</code>```

SingedOutNavigator:

```<code>import React from 'react';
import { Platform, StatusBar, Easing, Animated } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { StackNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import SignIn from '../screens/SignInScreen';
import Register from '../screens/RegisterScreen';

const headerStyle = {
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    backgroundColor: '#2b303b',
};

export default StackNavigator(
    {
        SignIn: {
            screen: SignIn,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        },
        Register: {
            screen: Register,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        }
    },
    {
        headerMode: "none",
        transitionConfig: () => ({
            transitionSpec: {
                duration: 1000,
                easing: Easing.step0,
                timing: Animated.timing,
            },
            screenInterpolator: sceneProps => {
                const { layout, position, scene } = sceneProps
                const { index } = scene

                const height = layout.initHeight
                const translateY = position.interpolate({
                    inputRange: [index - 1, index, index + 1],
                    outputRange: [height, 0, 0],
                })

                const opacity = position.interpolate({
                    inputRange: [index - 1, index - 0.99, index],
                    outputRange: [0, 1, 1],
                })

                return { opacity, transform: [{ translateY }] }
            },
        }),
    }
);
</code>```

And from this "Settings" Screen i want to go on this "SignIn" from "SignedOutNavigator"..

答:
From what I understand you are building an application that some of it's screens are only available when the user is singed in.

So when the user logout you should clear the history of the navigation, in order for the user to become unable to navigate back using the back hardware button.

You should do something like:

```<code>this.props.navigation.dispatch(NavigationActions.reset({
            index: 0, key: null, actions: [ NavigationActions.navigate({ routeName: "SignedOut" }) ]
}));
</code>```

Body:
I have problem with navigation in RN, so I thought you could help me. I can't find any way to navigate from my "settings" tab to my "SignedOut", this is my repo, code is not complicated, all you have to look is in "navigation" and "screens" folder. Thing is my "settings" file is in one file "MainTabNavigator" and SignedOut is in "RootNavigation", and when i try something like this:

this.props.navigation.navigate("SignedOut");

nothing happend, here is my function for this:

onSignOut()
.then(() => {
    console.log('Logout!');
    this.props.navigation.navigate("SignedOut");
})
.catch(e => {
    console.log(e);
})

I do get this log printed out so it should call this navigation method successfully. Do you have any ideas why? I mean, I think that this is the reason maybe I am missing something here?

This is what my MainTabNavigator looks like:

import React from 'react';
import { Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { TabNavigator, TabBarBottom, DrawerNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import HomeScreen from '../screens/HomeScreen';
import ListScreen from '../screens/ListScreen';
import SettingsScreen from '../screens/SettingsScreen';
import WordDetails from '../screens/WordDetails';
import DrawerMenu from './drawerDesign/Drawer';

export default DrawerNavigator(
  {
    Home: {
      screen: HomeScreen,
    },
    List: {
      screen: ListScreen,
    },
    Settings: {
      screen: SettingsScreen,
    },
    WordDetails: {
      screen: WordDetails,
    },
  }, {
    contentComponent: DrawerMenu,
    drawerWidth: 200,
    drawerPosition: "right",
    contentOptions: {
      activeTintColor: '#e91e63',
      itemsContainerStyle: {
        marginVertical: 0,
        opacity: 0.6

      },
      iconContainerStyle: {
        opacity: 0.6
      },
      style: {
        flex: 1,
        paddingTop: 35,
      },
    }
  }
);

SingedOutNavigator:

import React from 'react';
import { Platform, StatusBar, Easing, Animated } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { StackNavigator } from 'react-navigation';

import Colors from '../constants/Colors';

import SignIn from '../screens/SignInScreen';
import Register from '../screens/RegisterScreen';

const headerStyle = {
    marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    backgroundColor: '#2b303b',
};

export default StackNavigator(
    {
        SignIn: {
            screen: SignIn,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        },
        Register: {
            screen: Register,
            navigationOptions: {
                title: "Prijavi se",
                headerStyle,
                headerTitleStyle: {
                    color: '#f5f5f5'
                },
            },
        }
    },
    {
        headerMode: "none",
        transitionConfig: () => ({
            transitionSpec: {
                duration: 1000,
                easing: Easing.step0,
                timing: Animated.timing,
            },
            screenInterpolator: sceneProps => {
                const { layout, position, scene } = sceneProps
                const { index } = scene

                const height = layout.initHeight
                const translateY = position.interpolate({
                    inputRange: [index - 1, index, index + 1],
                    outputRange: [height, 0, 0],
                })

                const opacity = position.interpolate({
                    inputRange: [index - 1, index - 0.99, index],
                    outputRange: [0, 1, 1],
                })

                return { opacity, transform: [{ translateY }] }
            },
        }),
    }
);

And from this "Settings" Screen i want to go on this "SignIn" from "SignedOutNavigator"..

Body:
From what I understand you are building an application that some of it's screens are only available when the user is singed in.

So when the user logout you should clear the history of the navigation, in order for the user to become unable to navigate back using the back hardware button.

You should do something like:

this.props.navigation.dispatch(NavigationActions.reset({
            index: 0, key: null, actions: [ NavigationActions.navigate({ routeName: "SignedOut" }) ]
}));


问:
Reset random number stream
It appears that SAS/IML has the ability to reset it's random number stream (doc link) .

Is there a similar feature for random number routines in the SAS data step?

Based on this post, it seems that subsequent calls to streaminit are ignored within a single datastep.

For example, the below code produces different random numbers for each row:

```<code>data want;
  do i = 1 to 2;
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;
</code>```

Output:

```<code>i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.3878454913 ran2=0.3291709244 ran3=0.3615948586
</code>```

I would like the output to be:

```<code>i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
</code>```

答:
You cannot reset the streams for the RAND function in SAS 9.4M4.  However, you can rewind a stream in SAS 9.4M5 (which shipped in Sep 2017) by using the new STREAMREWIND routine.  The following program shows the syntax:

```<code>data want;
  call streaminit(123);
  do i = 1 to 2;
    call streamrewind;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;
</code>```

Title: Reset random number stream

Body:
It appears that SAS/IML has the ability to reset it's random number stream (doc link) .

Is there a similar feature for random number routines in the SAS data step?

Based on this post, it seems that subsequent calls to streaminit are ignored within a single datastep.

For example, the below code produces different random numbers for each row:

data want;
  do i = 1 to 2;
    call streaminit(123);  * <-- WANT THIS TO RESET THE STREAM;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;

Output:

i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.3878454913 ran2=0.3291709244 ran3=0.3615948586

I would like the output to be:

i=1 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207
i=2 ran1=0.5817000773 ran2=0.0356216603 ran3=0.0781806207

Body:
You cannot reset the streams for the RAND function in SAS 9.4M4.  However, you can rewind a stream in SAS 9.4M5 (which shipped in Sep 2017) by using the new STREAMREWIND routine.  The following program shows the syntax:

data want;
  call streaminit(123);
  do i = 1 to 2;
    call streamrewind;
    ran1 = rand('uniform');
    ran2 = rand('uniform');
    ran3 = rand('uniform');
    put _all_;
    output;
  end;
run;


问:
detect keyboard layout with javascript
Is there any way to detect the current keyboard layout using JavaScript? I found this,
 but it only detects if the visitor is on the english layout. I need to know the exact layout as a string, e.g.de-ch, fr or en.

答:
All what I know about this topic and already implemented a solution for it, is to detect non English layout keyboard, i.e Languages that uses any alphabet other than that used in English. The solution is depend on regular expression to match any word character \w, any digit character \d and a range of predefined English keyboard special characters, so any other characters, such as Arabic, Japanese, etc, will not match, all this uses keydown event and I am using this solution to restrict and notify usernames and passwords fields entry in login form.   I packaged it in a function like the following:

```<code>function checkKeyboard(ob,e){
        re = /\d|\w|[\.\$@\*\\\/\+\-\^\!\(\)\[\]\~\%\&\=\?\>\<\{\}\"\'\,\:\;\_]/g;
      a = e.key.match(re);
      if (a == null){
        alert('Error 2:\nNon English keyboard layout is detected!\nSet the keyboard layout to English and try to fill out the field again.');
        ob.val('');
        return false;
      }
      return true;
    }
</code>```

Then call the function from the event as the following:

```<code>$("#textFieldId").keydown(function(e){
        if (!checkKeyboard($(this),e)){
            return false;
        }
    });
</code>```

This is Working DEMO for unknown down voters!

Notice:

In the regex pattern, re you are able to add any missing special characters such as #,`,|, etc

Title: detect keyboard layout with javascript

Body:
All what I know about this topic and already implemented a solution for it, is to detect non English layout keyboard, i.e Languages that uses any alphabet other than that used in English. The solution is depend on regular expression to match any word character \w, any digit character \d and a range of predefined English keyboard special characters, so any other characters, such as Arabic, Japanese, etc, will not match, all this uses keydown event and I am using this solution to restrict and notify usernames and passwords fields entry in login form.   I packaged it in a function like the following:

function checkKeyboard(ob,e){
        re = /\d|\w|[\.\$@\*\\\/\+\-\^\!\(\)\[\]\~\%\&\=\?\>\<\{\}\"\'\,\:\;\_]/g;
      a = e.key.match(re);
      if (a == null){
        alert('Error 2:\nNon English keyboard layout is detected!\nSet the keyboard layout to English and try to fill out the field again.');
        ob.val('');
        return false;
      }
      return true;
    }

Then call the function from the event as the following:

$("#textFieldId").keydown(function(e){
        if (!checkKeyboard($(this),e)){
            return false;
        }
    });

This is Working DEMO for unknown down voters!

Notice:

In the regex pattern, re you are able to add any missing special characters such as #,`,|, etc

ContentLicense: CC BY-SA 4.0


问:
In PHP, why are my session variables persisted as references?
Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:

```<code>session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
    $_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}

if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    $_SESSION['security_error'] = true;
}
</code>```

If I insert var_dump($_SESSION) right after session_start() and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null) immediately after the session starts. What is going on?!

To reiterate, this is the output the first time:

```<code>array(0) {
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  string(11) "xx.xx.xxx.x"
}
</code>```

This is the output the second time:

```<code>array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
</code>```

And the third time and every time from then on:

```<code>array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &NULL
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
</code>```

答:
The only time your session variables are going to be references, is when you reference a session variable to another session variable (or if the original reference is still in scope).

Per example:

```<code>session_start();
$x = 'foo';
$_SESSION['x'] = &$x;
</code>```

This will give you:

```<code>array(1) {
  ["x"]=>
  string(3) "foo"
}
</code>```

While this:

```<code>$x = 'foo';
$_SESSION['x'] = $x;
$_SESSION['y'] = &$_SESSION['x']; // reference to another $_SESSION var
</code>```

Or this:

```<code>session_start();
$x = 'foo';
$_SESSION['x'] = $x;
$_SESSION['y'] = &$x;
var_dump($_SESSION); // reference still in scope
</code>```

Would give you:

```<code>array(2) {
  ["x"]=>
  string(3) "foo"
  ["y"]=>
  &string(3) "foo"
}
</code>```

Either way, doing this:

```<code>session_start();
$y = $_SESSION['y'];
$y = 'bar';
</code>```

Will not modify the y session variable. In order to do that, you'd have to do:

```<code>session_start();
$y = &$_SESSION['y'];
$y = 'bar';
</code>```

Body:
Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:

session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
    $_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}

if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    $_SESSION['security_error'] = true;
}

If I insert var_dump($_SESSION) right after session_start() and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null) immediately after the session starts. What is going on?!

To reiterate, this is the output the first time:

array(0) {
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  string(11) "xx.xx.xxx.x"
}

This is the output the second time:

array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}

And the third time and every time from then on:

array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &NULL
}
array(1) {
  ["SESSION_IP_ADDRESS"]=>
  &string(11) "xx.xx.xxx.x"
}

Body:
The only time your session variables are going to be references, is when you reference a session variable to another session variable (or if the original reference is still in scope).

Per example:

session_start();
$x = 'foo';
$_SESSION['x'] = &$x;

This will give you:

array(1) {
  ["x"]=>
  string(3) "foo"
}

While this:

$x = 'foo';
$_SESSION['x'] = $x;
$_SESSION['y'] = &$_SESSION['x']; // reference to another $_SESSION var

Or this:

session_start();
$x = 'foo';
$_SESSION['x'] = $x;
$_SESSION['y'] = &$x;
var_dump($_SESSION); // reference still in scope

Would give you:

array(2) {
  ["x"]=>
  string(3) "foo"
  ["y"]=>
  &string(3) "foo"
}

Either way, doing this:

session_start();
$y = $_SESSION['y'];
$y = 'bar';

Will not modify the y session variable. In order to do that, you'd have to do:

session_start();
$y = &$_SESSION['y'];
$y = 'bar';


问:
Antiword with UTF-8 in python
This is my code :

```<code>from subprocess import Popen, PIPE
cmd = ['antiword', 'tbhocbong151.doc']
p = Popen(cmd, stdout=PIPE)
stdout, stderr = p.communicate()
print(stdout.decode('utf-8', 'ignore'))
</code>```

I have content in file word like this : "Chào bạn"

but when I generated output is: "Ch?o b?n"

How can I fix it to output like input ?
Thanks for your help

答:
I believe that the problem is that the locale is not properly set when antiword is running. Try this:

```<code>import os
from subprocess import Popen, PIPE
myenv = dict(os.environ)
if 'LC_ALL' in myenv:
    del myenv['LC_ALL']
myenv['LANG'] = 'en_US.UTF-8'
cmd = ['antiword', 'tbhocbong151.doc']
p = Popen(cmd, stdout=PIPE, env=myenv)
stdout, stderr = p.communicate()
print(stdout.decode('utf-8', 'ignore'))
</code>```

If that doesn't work, try setting the LANG env variable in your shell before running your python program; e.g. by doing:

```<code>export LANG=en_US.UTF-8
</code>```

Title: Antiword with UTF-8 in python

Body:
This is my code :

from subprocess import Popen, PIPE
cmd = ['antiword', 'tbhocbong151.doc']
p = Popen(cmd, stdout=PIPE)
stdout, stderr = p.communicate()
print(stdout.decode('utf-8', 'ignore'))

I have content in file word like this : "Chào bạn"

but when I generated output is: "Ch?o b?n"

How can I fix it to output like input ?
Thanks for your help

Body:
I believe that the problem is that the locale is not properly set when antiword is running. Try this:

import os
from subprocess import Popen, PIPE
myenv = dict(os.environ)
if 'LC_ALL' in myenv:
    del myenv['LC_ALL']
myenv['LANG'] = 'en_US.UTF-8'
cmd = ['antiword', 'tbhocbong151.doc']
p = Popen(cmd, stdout=PIPE, env=myenv)
stdout, stderr = p.communicate()
print(stdout.decode('utf-8', 'ignore'))

If that doesn't work, try setting the LANG env variable in your shell before running your python program; e.g. by doing:

export LANG=en_US.UTF-8


问:
Select a row from rows with similar data
I hope someone will be able to solve my issue with knex.js

There is a table-"task_history" and it has following columns:
id, task_id, duration, date, start_time, finish_time

Let's say I have three rows inside task_history table:

```<code>row 1 - id(1) task_id(3333), duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time("2017-12-05 00:59:18.943+11")

row 2 - id(2) task_id(3333),  duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()

row 3 - id(3) task_id(4444), duration(100), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()
</code>```

As you can see, row 1 and row 2 are almost same except id, finish_time.
row 2 has "null" value for the finish_time column.

When I try the following query it returns me the row2 and row3.

```<code>select * from task_history where date=20171204 and finish_time is null
</code>```

But, that's not what I want. I don't want to get any row if its task_id exists in another row, but also it has value for the finish_time column.

The query should return row 3 only.
But row 1 and 2, because row 1 has finish_time value and the same task_id with the row2.

Thank you in advance!

答:
But, that's not what I want. I don't want to get any row if its
  task_id exists in another row, but also it has value for the
  finish_time column.

I understand this like

Select all task rows  exluding rows with
  task_id that exists in a row that has finished != null

This would be SQLized like

```<code>SELECT * FROM task t
WHERE NOT EXISTS (
   SELECT id FROM task -- note the 'id' is not important here, could be '*' also
   WHERE task_id=t.task_id AND finish_time IS NOT NULL
);
</code>```

Body:
I hope someone will be able to solve my issue with knex.js

There is a table-"task_history" and it has following columns:
id, task_id, duration, date, start_time, finish_time

Let's say I have three rows inside task_history table:

row 1 - id(1) task_id(3333), duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time("2017-12-05 00:59:18.943+11")

row 2 - id(2) task_id(3333),  duration(200), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()

row 3 - id(3) task_id(4444), duration(100), date(20171204)
        ,start_time("2017-10-19 21:00:00+11"), finish_time()

As you can see, row 1 and row 2 are almost same except id, finish_time.
row 2 has "null" value for the finish_time column.

When I try the following query it returns me the row2 and row3.

select * from task_history where date=20171204 and finish_time is null

But, that's not what I want. I don't want to get any row if its task_id exists in another row, but also it has value for the finish_time column.

The query should return row 3 only.
But row 1 and 2, because row 1 has finish_time value and the same task_id with the row2.

Thank you in advance!

Body:
But, that's not what I want. I don't want to get any row if its
  task_id exists in another row, but also it has value for the
  finish_time column.

I understand this like

Select all task rows  exluding rows with
  task_id that exists in a row that has finished != null

This would be SQLized like

SELECT * FROM task t
WHERE NOT EXISTS (
   SELECT id FROM task -- note the 'id' is not important here, could be '*' also
   WHERE task_id=t.task_id AND finish_time IS NOT NULL
);


问:
Python Created Object Attribute
I would like to create attributes of an object based on a dictionary passed in as an argument. Here is the code. But it does not work as

```<code>class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for k in di.keys():
            name = 'k' + '_' + 'series'
            self.name = None

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series
</code>```

I get the following error: 'Obj' object has no attribute 'c'

The code read "name" as a literal, and not as the variable defined.

答:
This is what will work :</p>

```<code>class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for key, value in di.items():
            key += '_series'
            setattr(self, key, value)

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series
</code>```

Title: Python Created Object Attribute

Body:
I would like to create attributes of an object based on a dictionary passed in as an argument. Here is the code. But it does not work as

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for k in di.keys():
            name = 'k' + '_' + 'series'
            self.name = None

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series

I get the following error: 'Obj' object has no attribute 'c'

The code read "name" as a literal, and not as the variable defined.

Body:
This is what will work :

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for key, value in di.items():
            key += '_series'
            setattr(self, key, value)

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series


问:
Angular.io (SystemJS) THREE is not defined ReferenceError: THREE is not defined
I started to use three.js in angular.io and have this error:

```<code>(index):18 Error: (SystemJS) THREE is not defined
ReferenceError: THREE is not defined
    at Object.eval (http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js:16:1)
    at eval (http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js:1044:4)
    at eval (http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js:1045:3)
    at eval (<anonymous>)
Evaluating http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js
Evaluating http://localhost:3000/app/three-basis/three-camera-orbit-control.component.js
</code>```

My imports and component:

```<code>import {Component} from '@angular/core';
import {CameraProvider} from './camera-provider.service';
import 'threejs/controls/OrbitControls';
import {OrbitControls} from 'three';

@Component({selector: 'three-camera-orbit-control', template: ''})
export class ThreeCameraOrbitControlComponent {

    constructor(private cameraProvider: CameraProvider) {
        let camera = this.cameraProvider.getCamera();
        let controls = new OrbitControls(camera);
        controls.addEventListener('change', () => {});
    }

}
</code>```

If I add this var THREE = require("three"); in OrbitControls.js in my node_modules/three, error gones and all is ok. I'm not good in js yet, can please some one help me, how to do it wright way? Thanks.

答:
See working example of using Angular + Three.js including OrbitControls and ColladaLoader: https://github.com/makimenko/angular-three-examples

Currently, Three.js examples are not included into a module and use them in Angular typescript code could be a little bit tricky. One of solution/workaround could be:

Firstly, include dependencies:

```<code>three
@types/three
</code>```

Secondly, import in component:

```<code>import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";
</code>```

Then use it in code:

```<code>this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);
</code>```

Hope this could help you to start

Body:
I started to use three.js in angular.io and have this error:

(index):18 Error: (SystemJS) THREE is not defined
ReferenceError: THREE is not defined
    at Object.eval (http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js:16:1)
    at eval (http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js:1044:4)
    at eval (http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js:1045:3)
    at eval (<anonymous>)
Evaluating http://localhost:3000/node_modules/three/examples/js/controls/OrbitControls.js
Evaluating http://localhost:3000/app/three-basis/three-camera-orbit-control.component.js

My imports and component:

import {Component} from '@angular/core';
import {CameraProvider} from './camera-provider.service';
import 'threejs/controls/OrbitControls';
import {OrbitControls} from 'three';

@Component({selector: 'three-camera-orbit-control', template: ''})
export class ThreeCameraOrbitControlComponent {

    constructor(private cameraProvider: CameraProvider) {
        let camera = this.cameraProvider.getCamera();
        let controls = new OrbitControls(camera);
        controls.addEventListener('change', () => {});
    }

}

If I add this var THREE = require("three"); in OrbitControls.js in my node_modules/three, error gones and all is ok. I'm not good in js yet, can please some one help me, how to do it wright way? Thanks.

Body:
See working example of using Angular + Three.js including OrbitControls and ColladaLoader: https://github.com/makimenko/angular-three-examples

Currently, Three.js examples are not included into a module and use them in Angular typescript code could be a little bit tricky. One of solution/workaround could be:

Firstly, include dependencies:

three
@types/three

Secondly, import in component:

import * as THREE from 'three';
import "./js/EnableThreeExamples";
import "three/examples/js/controls/OrbitControls";
import "three/examples/js/loaders/ColladaLoader";

Then use it in code:

this.controls = new THREE.OrbitControls(this.camera);
this.controls.rotateSpeed = 1.0;
this.controls.zoomSpeed = 1.2;
this.controls.addEventListener('change', this.render);

Hope this could help you to start


问:
Update React Component after render
I am using react-native-sortable-listview to change order of list-item by drag and drop. Only drag item is again rendered so its position is updated but other have their previous position. When This component is re-rendered by other cause like some increment button, all position are being correct.
 So my question is when my react-native-sortable-list is rendered how can I re-render this again.
 Both ways to render by forceUpdate() and this.setState() , I could not follow as I can not update state in render function.
 What can be a possible way for doing this.

答:
Ok I have find a way to re-render as follow.

```<code>  <SortableListView
      key={this.state.count}
      data={this.state.allObj}
      order={this.state.order}
      activeOpacity={0.5}
      onRowMoved={e => {
        this.setState({ count: this.state.count + 1 });
        this.props.arrangedMilestoneList(e);
        console.log('onRowMoved is called');
      }}
      onMoveEnd={() => console.log('onMoveEnd is fired')}
      renderRow={(row, s1, i) => this.renderOneDraggableMilestone(row, s1, i)}
    />
</code>```

What I am doing is I added a key attribute to SortableListView and update this key on each onRowMoved action. And because of this it causes re-render.

Title: Update React Component after render

Body:
Ok I have find a way to re-render as follow.

  <SortableListView
      key={this.state.count}
      data={this.state.allObj}
      order={this.state.order}
      activeOpacity={0.5}
      onRowMoved={e => {
        this.setState({ count: this.state.count + 1 });
        this.props.arrangedMilestoneList(e);
        console.log('onRowMoved is called');
      }}
      onMoveEnd={() => console.log('onMoveEnd is fired')}
      renderRow={(row, s1, i) => this.renderOneDraggableMilestone(row, s1, i)}
    />

What I am doing is I added a key attribute to SortableListView and update this key on each onRowMoved action. And because of this it causes re-render.


问:
Transposing query results
I have select statement that returns two values (one column, two rows). I'd like to change them so that I have two columns and one row. I know there is something like pivot but I'm not sure how to used that, as it requires aggregation values and I do not aggregate here anything. What would be the most performant way to accomplish this task? Thank you!</p>

答:
Use the ROWNUM pseudo-column to generate a unique identifier for each column and then you can use any aggregation function (as it will only be aggregating a single value):

```<code>SELECT value1, value2  /*, value3 ... */
FROM   ( SELECT your_column, ROWNUM AS rn FROM your_table_or_query )
PIVOT  ( MAX( your_column )
         FOR rn IN ( 1 AS value1, 2 As value2 /*, 3 AS value3 ... */ )
       );
</code>```

Title: Transposing query results

Body:
Use the ROWNUM pseudo-column to generate a unique identifier for each column and then you can use any aggregation function (as it will only be aggregating a single value):

SELECT value1, value2  /*, value3 ... */
FROM   ( SELECT your_column, ROWNUM AS rn FROM your_table_or_query )
PIVOT  ( MAX( your_column )
         FOR rn IN ( 1 AS value1, 2 As value2 /*, 3 AS value3 ... */ )
       );


问:
bash: using find with multiple file types, provided as an array
In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:

```<code>getMatchingFiles() {
  output=$1
  directory=$2
  shift 2
  _types_=("$@")

  file_array=find $directory -type f where-name-matches-item-in-_types_

  # do other stuff with $file_array, such as trimming file names to
  # just the basename with no extension

  eval $output="${file_array[@]}"
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"
</code>```

For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.

```<code>getMatchingFiles() {
  local _output=$1
  local _dir=$2
  shift 2
  local _type=("$@")
  local _files=($_dir/$_type/*)
  local -i ii=${#_files[@]}
  local -a _filetypes
  local _file _regex

  case $_type in
    audio )
      _filetypes=(ogg mp3)
      ;;
    images )
      _filetypes=(jpg png)
      ;;
  esac

  _regex="^.*\.("
  for _filetype in "${_filetypes[@]}"
  do
     _regex+=$_filetype"|"
  done

  _regex=${_regex:0:-1}
  _regex+=")$"

  for (( ; ii-- ; ))
  do
    _file=${_files[$ii]}
    if ! [[ $_file =~ $_regex ]];then
      unset _files[ii]
    fi
  done

  echo "${_files[@]}"

  # eval $_output="${_files[@]}" # tries to execute the files
}

dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"
</code>```

答:
Supporting the original, unmodified calling convention, and correctly handling extensions with whitespace or glob characters:</p>

```<code>#!/usr/bin/env bash

getMatchingFiles() {
  declare -g -a "$1=()"
  declare -n gMF_result="$1"  # variables are namespaced to avoid conflicts w/ targets
  declare -n gMF_dir="$2"
  declare -n gMF_types="$3"
  local gMF_args=( -false )   # empty type list not a special case
  local gMF_type gMF_item

  for gMF_type in "${gMF_types[@]}"; do
    gMF_args+=( -o -name "*.$gMF_type" )
  done

  while IFS= read -r -d '' gMF_item; do
    gMF_result+=( "$gMF_item" )
  done < <(find "$gMF_dir" '(' "${gMF_args[@]}" ')' -print0)
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
</code>```

Body:
In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:

getMatchingFiles() {
  output=$1
  directory=$2
  shift 2
  _types_=("$@")

  file_array=find $directory -type f where-name-matches-item-in-_types_

  # do other stuff with $file_array, such as trimming file names to
  # just the basename with no extension

  eval $output="${file_array[@]}"
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"

For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.

getMatchingFiles() {
  local _output=$1
  local _dir=$2
  shift 2
  local _type=("$@")
  local _files=($_dir/$_type/*)
  local -i ii=${#_files[@]}
  local -a _filetypes
  local _file _regex

  case $_type in
    audio )
      _filetypes=(ogg mp3)
      ;;
    images )
      _filetypes=(jpg png)
      ;;
  esac

  _regex="^.*\.("
  for _filetype in "${_filetypes[@]}"
  do
     _regex+=$_filetype"|"
  done

  _regex=${_regex:0:-1}
  _regex+=")$"

  for (( ; ii-- ; ))
  do
    _file=${_files[$ii]}
    if ! [[ $_file =~ $_regex ]];then
      unset _files[ii]
    fi
  done

  echo "${_files[@]}"

  # eval $_output="${_files[@]}" # tries to execute the files
}

dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"

Body:
Supporting the original, unmodified calling convention, and correctly handling extensions with whitespace or glob characters:

#!/usr/bin/env bash

getMatchingFiles() {
  declare -g -a "$1=()"
  declare -n gMF_result="$1"  # variables are namespaced to avoid conflicts w/ targets
  declare -n gMF_dir="$2"
  declare -n gMF_types="$3"
  local gMF_args=( -false )   # empty type list not a special case
  local gMF_type gMF_item

  for gMF_type in "${gMF_types[@]}"; do
    gMF_args+=( -o -name "*.$gMF_type" )
  done

  while IFS= read -r -d '' gMF_item; do
    gMF_result+=( "$gMF_item" )
  done < <(find "$gMF_dir" '(' "${gMF_args[@]}" ')' -print0)
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types


问:
How to get all records from one table between dates of column in another table
I'm using sql server, I have a queues table has a column called process_date, and a users table has a column called process_date, there is no relation between the two tables. I want to get all users that has been processed with one queue depending on process_date (I have the queue_id and I want to return all users that have been processed with that queue)
How can I write a query to do so?

update: the process_date is date time so it's not a match for the queue and the users, that's why I needed to get the process date for the previous queue and then the current queue and then get the users that were processed in that date range

答: The process_date field is date time so it won't be a match that's why I'm not joining, What I did is selecting the previous process_date from the queue, and the process_date for the current queue, and then selecting the users with process_date between these two dates</p>


问:
Question regarding C loops
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

```<code>for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}
</code>```

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

```<code>#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}
</code>```

Thanks!
Amit

答:
Are you sure you are starting 'k' at zero?

In the sample you posted you are using l not 1 - is this just a typo?

Title: Question regarding C loops

Body:
I'm not exactly sure why this isn't returning what it should be, perhaps one of you could help me out. I have the following for loop in C:

for (i=0; i<nrow; i++) {
    dat[k]=l.0;
    k++;
}

Now, you would think that this would set all values of dat (of which there are nrow values) to 1.0; Instead, it is being set to 0. The program compiles fine and everything goes smoothly. The memory is properly allocated and dat is defined as a double.

Is there a reason this is yielding 0? I'm guessing the 0 is coming from the initialization of the dat variable (since I used calloc for memory allocation, which supposedly initializes variables to 0 (but not always)).

EDIT: Please note that there is a specific reason (this is important) that I'm not defining it as dat[i]. Additionally. k was defined as an integer and was initialized to 0.

EDIT 2: Below is the entire code:

#include "stdio.h"
#include "stdlib.h"
#define NCH 81

// Generate swap-mode data for bonds for input.conf file

int main()
{
    int i,j,k;
    int **dat2;
    double *dat;

    int ns = 500;

    int nrow = NCH*(ns-1);

    dat = (double*) calloc(nrow, sizeof(double));
    dat2 = (int**) calloc(nrow,sizeof(int*));

    /*for (i=0; i<nrow; i++) {
        dat2[i] = (int*) calloc(2, sizeof(int));
        for (j=0; j<2; j++)
            dat2[i][j] = 0;
    }*/

    k=0;

    printf("\nBreakpoint\n");

    /*for (i=0; i<81; i++) {
        for (j=0; j<250; j++) {
            dat[k] = j+1;
            k++;
        }

        for (j=251; j>1; j++) {
            dat[k] = j-1;
            k++;
        }
    }*/

    FILE *inp;
    inp = fopen("input.out", "w");

    for (i=0; i<nrow; i++) {
        dat[k]=1.0;
        k++;
    }

    //fprintf(inp, "%lf\n", dat[i]);

    printf("%d", dat[nrow]);
    printf("\nDone\n");
    fclose(inp);

    return 0;
}

Thanks!
Amit


问:
Use lapply for a recursion (so without a foor loop)
I'd like to solve a recursion function in R, which is defined as

```<code>p(t) = 0.5p(t-1) + 0.2p(t-2)
</code>```

for t = 3,...,100, where the initial values p(1), p(2) are given.

I know that this would be possible to solve using a for loop just like this one here: Using R to solve a recursion function

I'm wondering whether this is also possible using  the lapply() function in R? I think it should somehow be possible, but I don't know where to start. I'd appreciate any hint.

答:
Sure you can use recursive function with lapply.

```<code>p <- function(t){
  if(t == 1){ return(1) } # arbitrary number
  if(t == 2){ return(2) } # arbitrary number

  return( 0.5*p(t-1) + 0.2*p(t-2) )
}

lapply(3:100, p)
</code>```

Note that it is a bad idea to use a recursive function for this problem without some sort of memoization, because it will be of exponential complexity.

The following code works in linear time instead:

```<code>p_tab <- c(1, 2, rep(-1, 98)) # 1 and 2 arbitrary numbers
p <- function(t){
  if(p_tab[t] != -1) return(p_tab[t])

  p_tab[t] <<- 0.5*p_tab[t-1] + 0.2*p_tab[t-2]
}

p_tab <- unlist(lapply( 1:100, p))
</code>```

p_tab will be filled with the numbers you need. p_tab[100] will be p(100) for instance, if that's the one you need.

Body:
I'd like to solve a recursion function in R, which is defined as

p(t) = 0.5p(t-1) + 0.2p(t-2)

for t = 3,...,100, where the initial values p(1), p(2) are given.

I know that this would be possible to solve using a for loop just like this one here: Using R to solve a recursion function

I'm wondering whether this is also possible using  the lapply() function in R? I think it should somehow be possible, but I don't know where to start. I'd appreciate any hint.

Body:
Sure you can use recursive function with lapply.

p <- function(t){
  if(t == 1){ return(1) } # arbitrary number
  if(t == 2){ return(2) } # arbitrary number

  return( 0.5*p(t-1) + 0.2*p(t-2) )
}

lapply(3:100, p)

Note that it is a bad idea to use a recursive function for this problem without some sort of memoization, because it will be of exponential complexity.

The following code works in linear time instead:

p_tab <- c(1, 2, rep(-1, 98)) # 1 and 2 arbitrary numbers
p <- function(t){
  if(p_tab[t] != -1) return(p_tab[t])

  p_tab[t] <<- 0.5*p_tab[t-1] + 0.2*p_tab[t-2]
}

p_tab <- unlist(lapply( 1:100, p))

p_tab will be filled with the numbers you need. p_tab[100] will be p(100) for instance, if that's the one you need.


问:
How can I mock ZipFile constructor?
I'm trying to test this code:

```<code>def read_classes(file):
    if CLASSES in file:
        classes = open(file, "rb").read()
    else:
        with ZipFile(file, "r") as archive:
            classes = archive.read(CLASSES)
    return classes
</code>```

What is important for me is, when the provided file contains CLASSES in its name, open will be called, otherwise, ZipFile will be used. The first part I was able to test already, however, I cannot mock ZipFile in order to return a mocked object (archive) - which I then can assert that had the read method called. This is what I've been trying so far:

```<code>@patch('zipfile.ZipFile')
def test_givenFile_whenReadClasses_expectArchiveCalled(self, mock_zipfile):
    file = 'sample.file'
    archive = Mock()
    mock_zipfile.return_value = archive

    read_classes(file)

    archive.read.assert_called_once_with("classes.file")
</code>```

When I do that, it continues to execute the original ZipFile constructor, giving me:
IOError: [Errno 2] No such file or directory: 'sample.file'

答:
Straight to the point:</p>

```<code>@patch('zipfile.ZipFile')
def test_givenFile_whenReadClasses_expectArchiveCalled(self, mocked_zip_file):
    file = 'file'
    archive = Mock()
    mocked_read = Mock()
    archive.return_value.read = mocked_read
    mocked_zip_file.return_value.__enter__ = archive

    read_classes(dex_file)

    mocked_read.assert_called_once_with('another_file')
</code>```

Title: How can I mock ZipFile constructor?

Body:
I'm trying to test this code:

def read_classes(file):
    if CLASSES in file:
        classes = open(file, "rb").read()
    else:
        with ZipFile(file, "r") as archive:
            classes = archive.read(CLASSES)
    return classes

What is important for me is, when the provided file contains CLASSES in its name, open will be called, otherwise, ZipFile will be used. The first part I was able to test already, however, I cannot mock ZipFile in order to return a mocked object (archive) - which I then can assert that had the read method called. This is what I've been trying so far:

@patch('zipfile.ZipFile')
def test_givenFile_whenReadClasses_expectArchiveCalled(self, mock_zipfile):
    file = 'sample.file'
    archive = Mock()
    mock_zipfile.return_value = archive

    read_classes(file)

    archive.read.assert_called_once_with("classes.file")

When I do that, it continues to execute the original ZipFile constructor, giving me:
IOError: [Errno 2] No such file or directory: 'sample.file'

Body:
Straight to the point:

@patch('zipfile.ZipFile')
def test_givenFile_whenReadClasses_expectArchiveCalled(self, mocked_zip_file):
    file = 'file'
    archive = Mock()
    mocked_read = Mock()
    archive.return_value.read = mocked_read
    mocked_zip_file.return_value.__enter__ = archive

    read_classes(dex_file)

    mocked_read.assert_called_once_with('another_file')


问:
Best Scheduler for .NET Application?
I'm trying to determine what would be a good Process Scheduler for .NET applications, so far I have only looked into Quartz.NET. Are there any viable alternatives and what are the tradeoffs when using them?</p>

答: Honestly, Quartz.NET is pretty much the best one out there.  One of Quartz.NET's biggest strengths lies in the fact that you schedule tasks using CRON expressions.  This gives you are succinct format that can easily be configured and stored in a variety of places.</p>

Title: Best Scheduler for .NET Application?


问:
Parsing time stamps - AM/PM not recognized
I'm trying to convert some timestamps (character) to a POSIXct object:

```<code>> u <- "December 05, 2017 1:00 PM"
</code>```

I'm using as.POSIXct as below:

```<code>> as.POSIXct(u, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 01:00:00 UTC"
</code>```

I would expect the output to show 13 for the hour instead of 01:

```<code>"2017-12-05 13:00:00 UTC"
</code>```

I've seen the question posted here: Parse timestamp with a.m./p.m but I seem to have the correct input and format string (with %p).

as.POSIXct appears to completely ignore the AM/PM part of the string and therefore the AM timestamps work fine but the PM stamps lag by 12 hours. Here's some more data to illustrate this:

```<code>> sample_tstamps
 [1] "December 05, 2017 8:00 AM"  "December 05, 2017 9:00 AM"  "December 05, 2017 10:00 AM" "December 05, 2017 11:00 AM"
 [5] "December 05, 2017 12:00 PM" "December 05, 2017 1:00 PM"  "December 05, 2017 2:00 PM"  "December 05, 2017 3:00 PM"
 [9] "December 05, 2017 4:00 PM"  "December 05, 2017 5:00 PM"
> as.POSIXct(sample_tstamps, format = "%B %d, %Y %H:%M %p", tz = "UTC")
 [1] "2017-12-05 08:00:00 UTC" "2017-12-05 09:00:00 UTC" "2017-12-05 10:00:00 UTC" "2017-12-05 11:00:00 UTC"
 [5] "2017-12-05 12:00:00 UTC" "2017-12-05 01:00:00 UTC" "2017-12-05 02:00:00 UTC" "2017-12-05 03:00:00 UTC"
 [9] "2017-12-05 04:00:00 UTC" "2017-12-05 05:00:00 UTC"
</code>```

Body:
I'm trying to convert some timestamps (character) to a POSIXct object:

> u <- "December 05, 2017 1:00 PM"

I'm using as.POSIXct as below:

> as.POSIXct(u, format = "%B %d, %Y %H:%M %p", tz = "UTC")
[1] "2017-12-05 01:00:00 UTC"

I would expect the output to show 13 for the hour instead of 01:

"2017-12-05 13:00:00 UTC"

I've seen the question posted here: Parse timestamp with a.m./p.m but I seem to have the correct input and format string (with %p).

as.POSIXct appears to completely ignore the AM/PM part of the string and therefore the AM timestamps work fine but the PM stamps lag by 12 hours. Here's some more data to illustrate this:

> sample_tstamps
 [1] "December 05, 2017 8:00 AM"  "December 05, 2017 9:00 AM"  "December 05, 2017 10:00 AM" "December 05, 2017 11:00 AM"
 [5] "December 05, 2017 12:00 PM" "December 05, 2017 1:00 PM"  "December 05, 2017 2:00 PM"  "December 05, 2017 3:00 PM"
 [9] "December 05, 2017 4:00 PM"  "December 05, 2017 5:00 PM"
> as.POSIXct(sample_tstamps, format = "%B %d, %Y %H:%M %p", tz = "UTC")
 [1] "2017-12-05 08:00:00 UTC" "2017-12-05 09:00:00 UTC" "2017-12-05 10:00:00 UTC" "2017-12-05 11:00:00 UTC"
 [5] "2017-12-05 12:00:00 UTC" "2017-12-05 01:00:00 UTC" "2017-12-05 02:00:00 UTC" "2017-12-05 03:00:00 UTC"
 [9] "2017-12-05 04:00:00 UTC" "2017-12-05 05:00:00 UTC"

Body:
We need %I instead of %H

as.POSIXct(u, format = "%B %d, %Y %I:%M %p", tz = "UTC")
#[1] "2017-12-05 13:00:00 UTC"