问:
True random numbers with C++11 and RDRAND
I have seen that Intel seems to have included a new assembly function to get real random numbers obtained from hardware. The name of the instruction is RdRand, but only a small amount of details seem accessible on it on Internet: http://en.wikipedia.org/wiki/RdRand

My questions concerning this new instruction and its use in C++11 are the following:

Are the random numbers generated with RdRand really random? (each bit generated from uncorrelated white noise or quantum processes? )

Is it a special feature of Ivy Bridge processors and will Intel continue to implement this function in the next generation of cpu?

How to use it through C++11? Maybe with std::random_device but do compilers already call RdRand if the instruction is available?

How to check whether RdRand is really called when I compile a program?

答:
1) No, the numbers from RdRand are not truly random, since they come from a cryptographically-secure pseudorandom number generator.  However, RdRand, RdSeed, and the Intel Secure Key technology are probably the closest to truly random you will find.

2)  Yes, the feature is available in all Intel processors that appear in laptops, desktops, and servers starting with the Ivy Bridge processors you mention.  These days, the features are also implemented in AMD chips.

3 and 4)  The Intel software development guide is the place to look for these answers.  There is an interesting discussion of how Intel Secure Key is applied to an astrophysical problem here (http://iopscience.iop.org/article/10.3847/1538-4357/aa7ede/meta;jsessionid=A9DA9DDB925E6522D058F3CEEC7D0B21.ip-10-40-2-120) and non-paywalled version here (https://arxiv.org/abs/1707.02212).  This paper describes how the technology works, how to implement it, and describes its performance (Sections 2.2.1 and 5).  Had to read it for a class.


来源: stackexchange

问:
View array with over 1000 items in VSCode debugger
I am working on a dotnet core project using VSCode and the C# Omnisharp extension.

My debug view looks like this:

...

Is is possible to expand the full array? I want to view some lines around location 2163 but cannot view past 999.

答:
This is a current limitation of Omnisharp, and I see you opened this issue to track this already.

As suggested, try using a linq query to filter down the data before inspecting it: cFile.Skip(1000)

ContentLicense: CC BY-SA 3.0


问:
pass a context to another class and change a TextView of an activity
I want to change a TextView from another, non-activity class. I see the answer here How to update a TextView of an activity from another class in the adapost's post, but I don't know how to properly pass a context to "ClassB".

In Main class, I tried ClassB obj = new ClassB(this); and ClassB obj = new ClassB(getApplicationContext());. But every time, TextView txtView = (TextView)findViewById(R.id.text); returns NullPointerException.

I am sure that I do it aftersetContentView, I can acheive this textView from Main class.

How to pass the context to make it work?

答:
Create an object of that activity inside the other class.
Pass the activity in the constructor and attach it to the object. This way, all public variables and methods from the activity will be retrieved in the other class.

```<code>class B {
final MyActivity activity;
public B(MyActivity activity) {
this.activity = activity;
}
// here you can access all public field variables and methods of MyActivity.
}
</code>```

But for activity to activity, you can make all those variables that will be used outside "static".

Body:
Create an object of that activity inside the other class.
Pass the activity in the constructor and attach it to the object. This way, all public variables and methods from the activity will be retrieved in the other class.

class B {
final MyActivity activity;
public B(MyActivity activity) {
this.activity = activity;
}
// here you can access all public field variables and methods of MyActivity.
}

But for activity to activity, you can make all those variables that will be used outside "static".


问:
Code generation in software development
First broader view : I got assignment for school project that states "Design and implement tool for rapid development of IS by code generation of core of business and data layer. (paraphrased). Its specific for .NET and C#, but anything is fine in this case.

I dont have that extensive knowledge of code generation or development of information systems. I was looking around some code generation framewroks and tools. More specificaly T4 and CodeSmith Generator. One thing that hit my eye is .netTiers set of templates, that have some interesting ones, that can be used in software development. But I dont know how much usefull in actual development they can be.

Well my question : Is there a way to develop an information system based mostly on code-generation? Or some way to make bigger use of code generation tools and templates in general? If I have this, I can work on more specific things.

I also tried to look at some questions here, that concert code-generation, but most of them are about if it is good or bad, or general experience with them. What I want is specific experience with specific tools and templates and how much profit in development they have.

Thanks a lot for answers.

答:
Yes it is.

I think that one of the Biggest things you could look at is Naked Objects.

Java: Naked Objects.org

.NET: Naked Objects MVC

These two basically generate an entire program just from the domain model. Very interesting. Scott Hanselman did a Hanselminutes on it here: Hanselminutes w/ Richard Pawson. Also has some links to some very interesting things on it.

If you watch Hanselmans talk from PDC PDC he does a lot of stuff using code generation.

My company Generates the entire DAL and BO layer (without out custom functions) from a data model, using the CSLA .NET templates and CodeSmith.

So yes you can do quite a bit using generation and I haven't even really touched the surface of what you could really do.

ContentLicense: CC BY-SA 2.5

Title: Code generation in software development


问:
Not able to receive tcp(mode is server) message on channel with undefined terminator
Currently we are using Spring Integration 2.1.0 Release(Due to legacy application can not switch on latest version ) in our application.
Application flow is as below:

All the configuration details are defined in a configuration file, like host name, port number, terminator etc

Get the message from TCP using tcp-inbound-channel-adapter via channel.

Pass it to splitter for further flow.

Here issue is if message has terminator other than, which is defined in configuration file,message does not come to class defined for splitter, if terminator is same, it is working fine.
Requirement is if terminator value is different it should show a error message on same channel using tcp-outbound-channel-adapter(inbound and outbound is used due asynchronous call).
 I have enabled the application and spring logging at Trace level but not able to understand why and where message is stuck.

Code for Configuration file is

```<code><Config>
<host>localhost</host>
<port>8888</port>
<mode>server</mode>
<terminator>10</terminator>
<msgLength>65535</msgLength>
<inChannel>telnetInboundCustomChannel</inChannel>
</Config>
</code>```

XML for connection details

```<code><beans:bean id="serverCustomSerializer"
class="com.core.serializer.CustomSerializer">
<beans:property name="terminatingChar" value="${server.terminator}"/>
<beans:property name="maxLength" value="${server.msgLength}"/>
</beans:bean>

<beans:bean id="serverFactoryTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<beans:property name="corePoolSize" value="5" />
<beans:property name="queueCapacity" value="0" />

</beans:bean
<int:channel id="telnetLandingChannel" />
<ip:tcp-connection-factory id="serverFactory" type="server"
host="${server.host}" port="${server.port}" single-use="false"
serializer="${server.serializer}" deserializer="${server.serializer}" task-
executor="serverFactoryTaskExecutor"/>

<ip:tcp-inbound-channel-adapter id="serverInboundAdpater"
channel="telnetLandingChannel" connection-factory="serverFactory"
error-channel="errorChannel" auto-startup="false"/>
<ip:tcp-outbound-channel-adapter id="serverOutboundAdapter"
channel="serverReplyChannel"
connection-factory="serverFactory"
auto-startup="true"/>
</code>```

XML for Channel details and flow are:

```<code><int:channel id="telnetInboundCustomChannel" />

<int:splitter id="messageSplitter"
input-channel="telnetInboundCustomChannel" ref="telnetCustomMessageSplitter"
method="splitCustomMessageStream"
outputchannel="base24CustomSplitterChannel" />

<int:filter id="messageFilter" input-
channel="base24CustomSplitterChannel"
output-channel="base24CustomCoreMessageChannel"
ref="telnetCustomMessageFilter"
method="customMessageFilter" />
<!--Other code to get data from filer and pass it to correct router -->
</code>```

If somehow message is visible in filter class, I can apply the logic to written error code on TCP connection.
I have applied the break points on run() of TcpNetConnection class as well. I am not able to understand Spring Integration internal flow. How message is coming even till splitter.
I have noticed one more thing if I send message with correct terminator, after sending with wrong terminator, Spring will append new message with old message.

Looks like without correct terminator spring is not able to cut the frame and it is stuck in telnetInboundCustomChannel.
Please guide how to fix this issue and reason of issue for better understanding.

答: The requirement is strictly meaningless. There is no such thing as a message in TCP, and no such thing as a message with an undefined terminator in any protocol.</p>

Body:
Currently we are using Spring Integration 2.1.0 Release(Due to legacy application can not switch on latest version ) in our application.
Application flow is as below:

All the configuration details are defined in a configuration file, like host name, port number, terminator etc

Get the message from TCP using tcp-inbound-channel-adapter via channel.

Pass it to splitter for further flow.

Here issue is if message has terminator other than, which is defined in configuration file,message does not come to class defined for splitter, if terminator is same, it is working fine.
Requirement is if terminator value is different it should show a error message on same channel using tcp-outbound-channel-adapter(inbound and outbound is used due asynchronous call).
 I have enabled the application and spring logging at Trace level but not able to understand why and where message is stuck.

Code for Configuration file is

<Config>
<host>localhost</host>
<port>8888</port>
<mode>server</mode>
<terminator>10</terminator>
<msgLength>65535</msgLength>
<inChannel>telnetInboundCustomChannel</inChannel>
</Config>

XML for connection details

<beans:bean id="serverCustomSerializer"
class="com.core.serializer.CustomSerializer">
<beans:property name="terminatingChar" value="${server.terminator}"/>
<beans:property name="maxLength" value="${server.msgLength}"/>
</beans:bean>

<beans:bean id="serverFactoryTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<beans:property name="corePoolSize" value="5" />
<beans:property name="queueCapacity" value="0" />

</beans:bean
<int:channel id="telnetLandingChannel" />
<ip:tcp-connection-factory id="serverFactory" type="server"
host="${server.host}" port="${server.port}" single-use="false"
serializer="${server.serializer}" deserializer="${server.serializer}" task-
executor="serverFactoryTaskExecutor"/>

<ip:tcp-inbound-channel-adapter id="serverInboundAdpater"
channel="telnetLandingChannel" connection-factory="serverFactory"
error-channel="errorChannel" auto-startup="false"/>
<ip:tcp-outbound-channel-adapter id="serverOutboundAdapter"
channel="serverReplyChannel"
connection-factory="serverFactory"
auto-startup="true"/>

XML for Channel details and flow are:

<int:channel id="telnetInboundCustomChannel" />

<int:splitter id="messageSplitter"
input-channel="telnetInboundCustomChannel" ref="telnetCustomMessageSplitter"
method="splitCustomMessageStream"
outputchannel="base24CustomSplitterChannel" />

<int:filter id="messageFilter" input-
channel="base24CustomSplitterChannel"
output-channel="base24CustomCoreMessageChannel"
ref="telnetCustomMessageFilter"
method="customMessageFilter" />

If somehow message is visible in filter class, I can apply the logic to written error code on TCP connection.
I have applied the break points on run() of TcpNetConnection class as well. I am not able to understand Spring Integration internal flow. How message is coming even till splitter.
I have noticed one more thing if I send message with correct terminator, after sending with wrong terminator, Spring will append new message with old message.

Looks like without correct terminator spring is not able to cut the frame and it is stuck in telnetInboundCustomChannel.
Please guide how to fix this issue and reason of issue for better understanding.


问:
HTML5 Changing paragraphs background color with button js
I got small troubles with this one:

```<code><style>
p:empty {height:20px};
p:nth-child(4n+3) {background:black};
</style>
</head>

<body>

<button onclick="f()">white</button>
<script>
function f() {
var x = document.getElementsByTagName("p");
x.style.backgroundColor = "white";
}
</script>

<p></p>
<p></p>
<p></p>
....
</code>```

(there are 20paragraphs)
So every 4th paragraph got black background, and it all works well.
I want this button to switch black back to the white after clicking on it, but it's just not working, what am I doing wrong?

答:
Actually document.getElementsByTagName() will return a HTMLCollection, you need to loop over it and apply the style:

```<code>function f() {
  var paragraphs = document.getElementsByTagName("p");
  Array.from(paragraphs).forEach(function(x){
       x.style.backgroundColor = "white";
  });
}
</code>```

Demo:

function f() {
  var paragraphs = document.getElementsByTagName("p");
  Array.from(paragraphs).forEach(function(x){
       x.style.backgroundColor = "white";
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p:empty {
  height: 20px;
}

p:nth-child(4n+3) {
  background: black;
}</code>```

<button onclick="f()">white</button>

A

B

C

A

B

C
```

Body:
I got small troubles with this one:

<button onclick="f()">white</button>

....

(there are 20paragraphs)
So every 4th paragraph got black background, and it all works well.
I want this button to switch black back to the white after clicking on it, but it's just not working, what am I doing wrong?

Body:
Actually document.getElementsByTagName() will return a HTMLCollection, you need to loop over it and apply the style:

function f() {
  var paragraphs = document.getElementsByTagName("p");
  Array.from(paragraphs).forEach(function(x){
       x.style.backgroundColor = "white";
  });
}

Demo:

function f() {
  var paragraphs = document.getElementsByTagName("p");
  Array.from(paragraphs).forEach(function(x){
       x.style.backgroundColor = "white";
  });
}

p:empty {
  height: 20px;
}

p:nth-child(4n+3) {
  background: black;
}

<button onclick="f()">white</button>

<p>A</p>
<p>B</p>
<p>C</p>
<p>A</p>
<p>B</p>
<p>C</p>


问:
Linking an existing repository to Visual Studio Team Services repository (Github to VSTS migration)
We are currently in the process of moving all of our repositories over to VSTS from Github which has been great and easy so far but are now running into the small problem of linking our old local repositories to the new ones in VSTS.

So technically they should be the exact same files except for the local ones that we weren't committing up to Github in the first place (Which we'd like to not have to manually copy back and forth). Is there a way to link these local repositories to the new ones in VSTS?

答:
Just treat GitHub as a source repo here</p>

```<code>git clone --mirror <repo on HitHub>
git push --mirror <remote on VSTS>
</code>```

Body:
Just treat GitHub as a source repo here

git clone --mirror <repo on HitHub>
git push --mirror <remote on VSTS>


问:
Dynamic items in viewholder on RecyclerView
If we have N categories (between 1 and 100 according to a REST API) and each with X items (between 1 and 50, depending on the category), what is the best way to do a category RecyclerView?

To add do this I am adding card views for each item item of a category in the method "onBindViewHolder" like this:

```<code>    @Override
public void onBindViewHolder(MoviesViewHolder holder, int i) {
    holder.title.setText(items.get(i).getTitle());

     // I add a CardView (item_category.xml) for each item in the list

    for (ObjectShort object: items.get(i).getObjects()) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_category, holder.linearCategories, false);
        ImageView img = (ImageView) view.findViewById(R.id.iv_wallpaper);
        imageLoader.load(img, object.getImg().getPoster().getThumbnail());
        holder.linearCategories.addView(view);
    }

}
</code>```

And when it is recycled I remove the ITEMS elements in "onViewRecycled" because if I do not do it when doing vertical scrolling and reloading a category, items are added again duplicating:

```<code>    @Override
public void onViewRecycled(MoviesViewHolder holder) {
    // delete all items
    holder.linearCategories.removeAllViews();
}
</code>```

Is there any better way to do it? This is not effective and the scroll is very slow

thanks to all

答:
To answer your question, I'm going to go back to the old days of ListView. Let's imagine that I had a simple list where each row was just a title and an image. A really naive implementation of getView() to support that list might look like this:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.itemview, parent, false);

    TextView title = view.findViewById(R.id.title);
    title.setText("hello world");

    ImageView image = view.findViewById(R.id.image);
    image.setImageResource(R.drawable.my_image);

    return view;
}
</code>```

There's two major sources of performance trouble in this implementation:

We're inflating a new view every time

We're calling findViewById() every time

Number 1 was solved by making use of the convertView parameter, and number 2 was solved by something called the "view holder pattern". When the Google dev team created the RecyclerView API to replace ListView, they made "view holders" a first-class citizen, and now everyone works with RecyclerView.ViewHolders by default.

It's important to remember that the performance gains of avoiding repeated view inflation and repeated view lookup were so valuable that Google baked them into the new system.

Now let's look at your code...

```<code>public void onBindViewHolder(MoviesViewHolder holder, int i) {
    ...
    for (ObjectShort object: items.get(i).getObjects()) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_category, holder.linearCategories, false);
        ImageView img = (ImageView) view.findViewById(R.id.iv_wallpaper);
        imageLoader.load(img, object.getImg().getPoster().getThumbnail());
        holder.linearCategories.addView(view);
    }
}
</code>```

This for loop inside your bind method has all the same problems that my naive getView() implementation above had. Inflating a new view for each item in the category, and invoking findViewById() to get ahold of its ImageView is going to be expensive, especially when the user flings the list.

To fix your performance problems, just apply the same logic to your "inner" list of content as you have to your "outer" content: use a RecyclerView for items (inside each ViewHolder for categories).

Here is a really simple sample app that illustrates my solution: https://gist.github.com/zizibaloob/2eb64f63ba8d1468100a69997d525a54

Body:
If we have N categories (between 1 and 100 according to a REST API) and each with X items (between 1 and 50, depending on the category), what is the best way to do a category RecyclerView?

To add do this I am adding card views for each item item of a category in the method "onBindViewHolder" like this:

    @Override
public void onBindViewHolder(MoviesViewHolder holder, int i) {
    holder.title.setText(items.get(i).getTitle());

     // I add a CardView (item_category.xml) for each item in the list

    for (ObjectShort object: items.get(i).getObjects()) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_category, holder.linearCategories, false);
        ImageView img = (ImageView) view.findViewById(R.id.iv_wallpaper);
        imageLoader.load(img, object.getImg().getPoster().getThumbnail());
        holder.linearCategories.addView(view);
    }

}

And when it is recycled I remove the ITEMS elements in "onViewRecycled" because if I do not do it when doing vertical scrolling and reloading a category, items are added again duplicating:

    @Override
public void onViewRecycled(MoviesViewHolder holder) {
    // delete all items
    holder.linearCategories.removeAllViews();
}

Is there any better way to do it? This is not effective and the scroll is very slow

thanks to all

Body:
To answer your question, I'm going to go back to the old days of ListView. Let's imagine that I had a simple list where each row was just a title and an image. A really naive implementation of getView() to support that list might look like this:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.itemview, parent, false);

    TextView title = view.findViewById(R.id.title);
    title.setText("hello world");

    ImageView image = view.findViewById(R.id.image);
    image.setImageResource(R.drawable.my_image);

    return view;
}

There's two major sources of performance trouble in this implementation:

We're inflating a new view every time

We're calling findViewById() every time

Number 1 was solved by making use of the convertView parameter, and number 2 was solved by something called the "view holder pattern". When the Google dev team created the RecyclerView API to replace ListView, they made "view holders" a first-class citizen, and now everyone works with RecyclerView.ViewHolders by default.

It's important to remember that the performance gains of avoiding repeated view inflation and repeated view lookup were so valuable that Google baked them into the new system.

Now let's look at your code...

public void onBindViewHolder(MoviesViewHolder holder, int i) {
    ...
    for (ObjectShort object: items.get(i).getObjects()) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_category, holder.linearCategories, false);
        ImageView img = (ImageView) view.findViewById(R.id.iv_wallpaper);
        imageLoader.load(img, object.getImg().getPoster().getThumbnail());
        holder.linearCategories.addView(view);
    }
}

This for loop inside your bind method has all the same problems that my naive getView() implementation above had. Inflating a new view for each item in the category, and invoking findViewById() to get ahold of its ImageView is going to be expensive, especially when the user flings the list.

To fix your performance problems, just apply the same logic to your "inner" list of content as you have to your "outer" content: use a RecyclerView for items (inside each ViewHolder for categories).

Here is a really simple sample app that illustrates my solution: https://gist.github.com/zizibaloob/2eb64f63ba8d1468100a69997d525a54


问:
Subqueries, Having and GroupBy in Slick
I am currently learning Slick. I was trying to translate this query from SQL into Scala:

```<code>SELECT name FROM Passenger
WHERE ID_psg in
(SELECT ID_psg FROM Pass_in_trip
GROUP BY place, ID_psg
HAVING count(*)>1)
</code>```

But I have only managed to write something like this, and it gives compile errors:

```<code>PassengerTable.table.filter(_.idPsg in (PassInTripTable.table.map(_.idPsgFk)))
  .filter(PassengerTable.table.count(_.name) > 1)
  .map(_.name)
</code>```

I do not really know how to apply count and having on queries in Slick.
So I would be really grateful for some help.

答:
Try

```<code>  val subquery = PassInTripTable.table.groupBy(p => (p.place, p.idPsgFk))
    .map { case ((place, id), group) => (id, group.length) }
    .filter { case (id, count) => count > 1 }
    .map { case (id, count) => id }

  val query = PassengerTable.table.filter(_.idPsg in subquery).map(_.name)

  val action = query.result

  db.run(action)
</code>```

http://slick.lightbend.com/doc/3.0.0/sql-to-slick.html#groupby

http://slick.lightbend.com/doc/3.0.0/sql-to-slick.html#subquery

http://slick.lightbend.com/doc/3.0.0/sql-to-slick.html#having

Title: Subqueries, Having and GroupBy in Slick

Body:
I am currently learning Slick. I was trying to translate this query from SQL into Scala:

SELECT name FROM Passenger
WHERE ID_psg in
(SELECT ID_psg FROM Pass_in_trip
GROUP BY place, ID_psg
HAVING count(*)>1)

But I have only managed to write something like this, and it gives compile errors:

PassengerTable.table.filter(_.idPsg in (PassInTripTable.table.map(_.idPsgFk)))
  .filter(PassengerTable.table.count(_.name) > 1)
  .map(_.name)

I do not really know how to apply count and having on queries in Slick.
So I would be really grateful for some help.

Body:
Try

  val subquery = PassInTripTable.table.groupBy(p => (p.place, p.idPsgFk))
    .map { case ((place, id), group) => (id, group.length) }
    .filter { case (id, count) => count > 1 }
    .map { case (id, count) => id }

  val query = PassengerTable.table.filter(_.idPsg in subquery).map(_.name)

  val action = query.result

  db.run(action)

http://slick.lightbend.com/doc/3.0.0/sql-to-slick.html#groupby

http://slick.lightbend.com/doc/3.0.0/sql-to-slick.html#subquery

http://slick.lightbend.com/doc/3.0.0/sql-to-slick.html#having


问:
pytest.mark.paramterize doesnot accept new changed value of global variable
In the following code, the test script failed because of empty paramters in list1 even if it is changed in test_1 test function.

```<code>import pytest,csv
list1 = []

def test_1():
    global list1
    print "IN TEST1"
    list1 = [['a','b','c'],['d','e','f'],['g','h','i']]

@pytest.mark.parametrize("test_input", list1)
def test_eval(test_input):
    print list1
    print "PARAMTERIZE FUNCTION"
    print (test_input)
</code>```

How do i access new value of list1 in pytest.parametrize ?

答:
Since you are not calling the function, so list1 is not updated. Either call the function test_1() before the test or a better way is given below:

```<code>def test_1():
    print "IN TEST1"
    list1 = [['a','b','c'],['d','e','f'],['g','h','i']]
    return list1

@pytest.mark.parametrize("test_input", test_1())
def test_eval(test_input):
    print "PARAMTERIZE FUNCTION"
    print (test_input)
</code>```

Body:
In the following code, the test script failed because of empty paramters in list1 even if it is changed in test_1 test function.

import pytest,csv
list1 = []

def test_1():
    global list1
    print "IN TEST1"
    list1 = [['a','b','c'],['d','e','f'],['g','h','i']]

@pytest.mark.parametrize("test_input", list1)
def test_eval(test_input):
    print list1
    print "PARAMTERIZE FUNCTION"
    print (test_input)

How do i access new value of list1 in pytest.parametrize ?

Body:
Since you are not calling the function, so list1 is not updated. Either call the function test_1() before the test or a better way is given below:

def test_1():
    print "IN TEST1"
    list1 = [['a','b','c'],['d','e','f'],['g','h','i']]
    return list1

@pytest.mark.parametrize("test_input", test_1())
def test_eval(test_input):
    print "PARAMTERIZE FUNCTION"
    print (test_input)


问:
How do I change colour of icon font inside active tab?
I'm trying to get the colour of my icon to stay a certain colour when it's the open active tab, but it's not working. I've been able to use p:active to get the icons to change colour when clicked, but that colour goes away after the click is done. I'd like it to stay when that tab is open.

The button.active is working only for background color and not font color. Can anyone help figure this out? I'm at a loss.

Here is all my coding:

```<code>/* Style the tab */
div.tab {
overflow: hidden;
border: 0px;
background-color: transparent;
text-align: center;
margin-left:auto;
margin-right:auto;
display:block;
}

/* Style the buttons inside the tab */
div.tab button {
background-color:transparent;
float: center;
border: none;
outline: none;
cursor: pointer;
min-width:100px;
transition: 0.3s;
font-size: 16px;
color:white;
text-transform: uppercase;
line-height:1;
margin: 2%;
height:31px;
font-weight:300;
}

/* Change background color of buttons on hover */
div.tab button > p:hover {
color:black;
}

/* Create an active/current tablink class */
div.tab button.active {
background-color:#F7941D;
color:white;
}

/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 0px;
border-top: none;
text-align:center;
}
</code>```

And my HTML:

```<code><div id="USA" class="tabcontent" style="display: block;">
<img class="diagram" src="http://dev.legendpower.com/wp-content/uploads/2017/11/Diagram_usa.png" style="margin-bottom:2%;">
</div>

<div id="Canada" class="tabcontent" style="display: none;">
<img class="diagram" src="http://dev.legendpower.com/wp-content/uploads/2017/11/Diagram_can.png"style="margin-bottom:2%;">
</div>

<div class="tab" style="width:50%; height:50px;">
  <button class="tablinks active" onclick="openToggle(event, 'USA')" id="defaultOpen"><p class="icon-usa-flag-icon" id="defaultOpen"></p></button>
  <button class="tablinks" onclick="openToggle(event, 'Canada')"><p class="icon-canada-flag-icon-1"></p></button>
</div>

</div></div>
</code>```

And the JS I'm using:

```<code>function openToggle(evt, ToggleName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(ToggleName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</code>```

答: I solved the issue. My styling of the icons was overriding the styling I had for the button, which was causing the issue.</p>

Body:
I'm trying to get the colour of my icon to stay a certain colour when it's the open active tab, but it's not working. I've been able to use p:active to get the icons to change colour when clicked, but that colour goes away after the click is done. I'd like it to stay when that tab is open.

The button.active is working only for background color and not font color. Can anyone help figure this out? I'm at a loss.

Here is all my coding:

/* Style the tab */
div.tab {
overflow: hidden;
border: 0px;
background-color: transparent;
text-align: center;
margin-left:auto;
margin-right:auto;
display:block;
}

/* Style the buttons inside the tab */
div.tab button {
background-color:transparent;
float: center;
border: none;
outline: none;
cursor: pointer;
min-width:100px;
transition: 0.3s;
font-size: 16px;
color:white;
text-transform: uppercase;
line-height:1;
margin: 2%;
height:31px;
font-weight:300;
}

/* Change background color of buttons on hover */
div.tab button > p:hover {
color:black;
}

/* Create an active/current tablink class */
div.tab button.active {
background-color:#F7941D;
color:white;
}

/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 0px;
border-top: none;
text-align:center;
}

And my HTML:

  <button class="tablinks active" onclick="openToggle(event, 'USA')" id="defaultOpen">

</button>
  <button class="tablinks" onclick="openToggle(event, 'Canada')">

</button>

And the JS I'm using:

function openToggle(evt, ToggleName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(ToggleName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();


问:
Getting error $(...).modal is not a function in angularjs after upgraded bootstrap 3.3.6 to 4.0.0
After upgrading the bootstrap in my application from 3.3.6 to 4 I started getting error error $(...).modal is not a function, which(modal) was previously working fine. Error

```<code>angular.js:14700 TypeError: $(...).modal is not a function
at ReviewQueueController.js?V=1.2:122
at angular.js:20440
at completeOutstandingRequest (angular.js:6362)
at angular.js:6642
</code>```

I am using angular js. when there is a success, error or any info I use modal. I have tried to replicate the issue with fiddle.

I have just started working  on angular so i am not sure how to fix.

Fiddle Link

In many post i researched it was suggested to make changes to css

```<code>.fade.in {
  opacity: 1;
}

.modal.in .modal-dialog {
   -webkit-transform: translate(0, 0);
   -o-transform: translate(0, 0);
    transform: translate(0, 0);
 }

.modal-backdrop.in {
    filter: alpha(opacity=50);
    opacity: .5;
 }
</code>```

Also many link suggested to use noconflict like here. I am not sure how no conflict will work with angularjs

please suggest what i can do to fix the issue

答:
One solution mentioned in their GitHub repo us to put this in your html:

```<code><!-- Enable bootstrap 4 theme -->
<script>window.__theme = 'bs4';</script>
</code>```

Also you might need to disable ViewEncapsulation in app.component.ts.

See "Disable CSS Encapsulation" here for how to do it.

UPDATE:

It seems that in your fiddle you're missing the jQuery script file. I added that in yours and now it works:

here

Body:
After upgrading the bootstrap in my application from 3.3.6 to 4 I started getting error error $(...).modal is not a function, which(modal) was previously working fine. Error

angular.js:14700 TypeError: $(...).modal is not a function
at ReviewQueueController.js?V=1.2:122
at angular.js:20440
at completeOutstandingRequest (angular.js:6362)
at angular.js:6642

I am using angular js. when there is a success, error or any info I use modal. I have tried to replicate the issue with fiddle.

I have just started working  on angular so i am not sure how to fix.

Fiddle Link

In many post i researched it was suggested to make changes to css

.fade.in {
  opacity: 1;
}

.modal.in .modal-dialog {
   -webkit-transform: translate(0, 0);
   -o-transform: translate(0, 0);
    transform: translate(0, 0);
 }

.modal-backdrop.in {
    filter: alpha(opacity=50);
    opacity: .5;
 }

Also many link suggested to use noconflict like here. I am not sure how no conflict will work with angularjs

please suggest what i can do to fix the issue

Body:
One solution mentioned in their GitHub repo us to put this in your html:

<!-- Enable bootstrap 4 theme -->
<script>window.__theme = 'bs4';</script>

Also you might need to disable ViewEncapsulation in app.component.ts.

See "Disable CSS Encapsulation" here for how to do it.

UPDATE:

It seems that in your fiddle you're missing the jQuery script file. I added that in yours and now it works:

here


问:
How to retrieve source port with Puppeteer?
I've looked through the documentation and it doesn't look like there's support for lower level subjects such as sockets with Puppeteer. I'm trying to retrieve the source port of the request made with puppeteer, does someone have an idea of how that would be possible?

Here's obligatory current script:

```<code>const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch({headless: "False"});
  const page = await browser.newPage();
  page.on('request', request => {
    console.log(request.url);
    });

  await page.goto('https://facebook.com');
  await browser.close();
})();
</code>```

Any guidance would be greatly appreciated! Thank you.

答: I believe what you're looking for is the wsEndpoint found here. This returns the location + port of where Chrome is listening for inbound protocol requests.

Body:
I've looked through the documentation and it doesn't look like there's support for lower level subjects such as sockets with Puppeteer. I'm trying to retrieve the source port of the request made with puppeteer, does someone have an idea of how that would be possible?

Here's obligatory current script:

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch({headless: "False"});
  const page = await browser.newPage();
  page.on('request', request => {
    console.log(request.url);
    });

  await page.goto('https://facebook.com');
  await browser.close();
})();

Any guidance would be greatly appreciated! Thank you.


问:
Make a prediction using mxnet CNN model
Hi I'm a newbie to data science,
I followed this tutorial https://mxnet.incubator.apache.org/tutorials/nlp/cnn.html but I am confused over how to make a single prediction using the trained model generated by the above mentioned tutorial. Please guide me the right direction to fix this. Thanks.</p>

答:
One can load the model like this:

```<code>sym, arg_params, aux_params = mx.model.load_checkpoint('cnn', 3)
mod = mx.mod.Module(symbol=sym, context=mx.cpu(), label_names=None)
mod.bind(for_training=False, data_shapes=[('data', (50,56))],
         label_shapes=mod._label_shapes)
mod.set_params(arg_params, aux_params, allow_missing=True)
</code>```

But unfortunately, you cannot use this for making only one prediction. You would need a batch of 50.

Title: Make a prediction using mxnet CNN model

Body:
One can load the model like this:

sym, arg_params, aux_params = mx.model.load_checkpoint('cnn', 3)
mod = mx.mod.Module(symbol=sym, context=mx.cpu(), label_names=None)
mod.bind(for_training=False, data_shapes=[('data', (50,56))],
         label_shapes=mod._label_shapes)
mod.set_params(arg_params, aux_params, allow_missing=True)

But unfortunately, you cannot use this for making only one prediction. You would need a batch of 50.


问:
How to configure Jenkins dashboard from the console error?
I am planning to create a Jenkins dashboard by categorizing the jobs based on the build  errors.

I have the groovy script to parse the console error, but I don't see an option to insert into the dashboard.

Thanks in advance.

答:
Unfortunately there were no straight forward option to customize the dashboard view.

So I have written my own script and generated the HTML file and I used the HTML Publisher plugin to display as dashboard.

Thank everyone for your help.


问:
How get the result of a boolean method in one class into an if statement of another class in Java?
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have an issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total, same for subtraction. But if I need to write an if statement that checks if the subtraction is unsuccessful and if it is display an "error".

```<code> public class EmployeeInfo
 {
 //class constants

 //class variables
 private String firstName;
 private String lastName;
 private int itemsSold;
 private int employeeTotal;

public EmployeeInfo(String first, String last, int sold)
{

    //local constants

    //local variables

    /********************   Start Constructor  *****************/

    //Calls the first and last name, and the amount of items sold
    firstName = first;
    lastName = last;
    itemsSold = sold;

}//End constructor

 public void addition(int itemsSold)
   {
      //local constants

      //local variables

      /********************   Start main method  *****************/

      //Adds the items sold to the employee total
      employeeTotal = itemsSold + employeeTotal;

}//end addition

 public void subtraction(int itemsSold)
 {
       //local constants

       //local variables

       /********************   Start main method  *****************/

       //Subtracts the items not sold to the employee total
       employeeTotal = (employeeTotal - itemsSold);

}//end subtraction

public boolean booleanMethod(boolean result)
{
       //local constants

       //local variables

       /********************   Start main method  *****************/

       if(employeeTotal < 0)
       {
           result = false;
       }
       else
       {
           result = true;
       }

       return result;

 }//End booleanMethod

   public String toString()
    {
       //local constants

       //local variables

       /******************************************************/

       return String.format(Util.setLeft(45,"Eployee Name and Sales Figures") + "\n\n" + Util.setLeft(40, "First Name: ") + Util.setRight(30, firstName) +
       "\n" + Util.setLeft(40, "Last Name : ") + Util.setRight(30, lastName) + "\n" + Util.setLeft(40, "Items Sold: ") + Util.setRight(30, Integer.toString(employeeTotal)));

   }//end to string

}//end employeeInfo
</code>```

and this is a partial part of the class that uses the booleanMethod, method

```<code>while(soldItems != QUIT)
    {

        //Clear screen then prompt the user to add or subtract
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        System.out.print(Util.setLeft(35, "Add or Subtract: "));
        input = Keyboard.readString();
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        //if the user enters add the program will add to the employee total
        if(input.equals(ADD))
        {
            info.addition(soldItems);

        }

        //else the program will subtract from the employee total
        else
        {
            info.subtraction(soldItems);

            if (info.booleanMethod(false))
            {
                System.out.print("Error");
                System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }
        }
</code>```

the tool completes successfully but it doesn't display the error message it just displays my line asking for another sales figure, how do I get it to actually work?

答:
Start by placing the responsibility of the subtraction to perform the validation...

```<code>public boolean subtraction(int itemsSold)
{
    //local constants

    //local variables

    /********************   Start main method  *****************/

    //Subtracts the items not sold to the employee total
    employeeTotal = (employeeTotal - itemsSold);

    return employeeTotal < 0;
}//end subtraction
</code>```

Then simply use the return result to determine what should be done...

```<code>if (!info.subtraction(soldItems)) {
    //...
}
</code>```

IMHO, subtraction should actually stop before it reaches a possible invalid state, for example...

```<code>public boolean subtraction(int itemsSold)
{
    //local constants

    //local variables

    /********************   Start main method  *****************/

    if (employeeTotal - itemsSold >= 0) {
        //Subtracts the items not sold to the employee total
        employeeTotal = (employeeTotal - itemsSold);
        return true;
    }

    return false;
}//end subtraction
</code>```

Body:
I'm writing a program that gathers a first name, a last name, and the sales figure of an employee. I have all the basics working perfectly but I have an issue. In my while loop I have programmed it so if the user enters "add" then it will call a method I made in a different class and add whatever number they entered to the employees current sales total, same for subtraction. But if I need to write an if statement that checks if the subtraction is unsuccessful and if it is display an "error".

 public class EmployeeInfo
 {
 //class constants

 //class variables
 private String firstName;
 private String lastName;
 private int itemsSold;
 private int employeeTotal;

public EmployeeInfo(String first, String last, int sold)
{

    //local constants

    //local variables

    /********************   Start Constructor  *****************/

    //Calls the first and last name, and the amount of items sold
    firstName = first;
    lastName = last;
    itemsSold = sold;

}//End constructor

 public void addition(int itemsSold)
   {
      //local constants

      //local variables

      /********************   Start main method  *****************/

      //Adds the items sold to the employee total
      employeeTotal = itemsSold + employeeTotal;

}//end addition

 public void subtraction(int itemsSold)
 {
       //local constants

       //local variables

       /********************   Start main method  *****************/

       //Subtracts the items not sold to the employee total
       employeeTotal = (employeeTotal - itemsSold);

}//end subtraction

public boolean booleanMethod(boolean result)
{
       //local constants

       //local variables

       /********************   Start main method  *****************/

       if(employeeTotal < 0)
       {
           result = false;
       }
       else
       {
           result = true;
       }

       return result;

 }//End booleanMethod

   public String toString()
    {
       //local constants

       //local variables

       /******************************************************/

       return String.format(Util.setLeft(45,"Eployee Name and Sales Figures") + "\n\n" + Util.setLeft(40, "First Name: ") + Util.setRight(30, firstName) +
       "\n" + Util.setLeft(40, "Last Name : ") + Util.setRight(30, lastName) + "\n" + Util.setLeft(40, "Items Sold: ") + Util.setRight(30, Integer.toString(employeeTotal)));

   }//end to string

}//end employeeInfo

and this is a partial part of the class that uses the booleanMethod, method

while(soldItems != QUIT)
    {

        //Clear screen then prompt the user to add or subtract
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        System.out.print(Util.setLeft(35, "Add or Subtract: "));
        input = Keyboard.readString();
        System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

        //if the user enters add the program will add to the employee total
        if(input.equals(ADD))
        {
            info.addition(soldItems);

        }

        //else the program will subtract from the employee total
        else
        {
            info.subtraction(soldItems);

            if (info.booleanMethod(false))
            {
                System.out.print("Error");
                System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            }
        }

the tool completes successfully but it doesn't display the error message it just displays my line asking for another sales figure, how do I get it to actually work?

Body:
Start by placing the responsibility of the subtraction to perform the validation...

public boolean subtraction(int itemsSold)
{
    //local constants

    //local variables

    /********************   Start main method  *****************/

    //Subtracts the items not sold to the employee total
    employeeTotal = (employeeTotal - itemsSold);

    return employeeTotal < 0;
}//end subtraction

Then simply use the return result to determine what should be done...

if (!info.subtraction(soldItems)) {
    //...
}

IMHO, subtraction should actually stop before it reaches a possible invalid state, for example...

public boolean subtraction(int itemsSold)
{
    //local constants

    //local variables

    /********************   Start main method  *****************/

    if (employeeTotal - itemsSold >= 0) {
        //Subtracts the items not sold to the employee total
        employeeTotal = (employeeTotal - itemsSold);
        return true;
    }

    return false;
}//end subtraction


问:
Is intel's RdRand TRNG or PRNG?
I've searched the net for quite a while and couldn't find a definitive answer. I want to know the quality of random numbers generated by intel's rdrand instructions. How does it compare to IDQ's cards for example? Is it truly random or pseudo random?

Thanks

答:
Intel's RdRand is a high-quality, cryptographically-secure, psuedorandom number generator.  There is a detailed description of what it is, how to use it, how it has been used, and how fast it is to use given in a paper here (http://iopscience.iop.org/article/10.3847/1538-4357/aa7ede/meta;jsessionid=A9DA9DDB925E6522D058F3CEEC7D0B21.ip-10-40-2-120) or non-paywalled version here (https://arxiv.org/abs/1707.02212).

I think sections 2.2.1 and 5 have what you are looking for.

Title: Is intel's RdRand TRNG or PRNG?


问:
ContextMenu Fails To Remove Row From ListView With Custom Adapter
The Problem is: My ContextMenu Fails to Remove a Row from ListView with a Custom Adapter and
the app crashes with the error: UnsupportedOperationException, see Logcat output.

I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.

My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.

Java Code:

```<code>        public class TestActivity extends ListActivity {

        private String itemNameArray[];
        private String dateArray[];

        private ListView listview;
        CustomListViewAdapter customListViewAdapter;

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

                            setContentView(R.layout.activity_test);

                            registerForContextMenu(getListView());

                            root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
                            getDir(root);

            listview = getListView();

            name=itemNameArray;
            lastmod=dateArray;

            customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

            listview.setAdapter(customListViewAdapter);

      } // End of onCreate code.

        class CustomListViewAdapter extends ArrayAdapter<String> {
            Context context;
            String[] nameArray;
            String[] modifiedArray;

            CustomListViewAdapter(Context c, String[] name, String[] lastmod)
            {
                super(c, R.layout.layout_item_view, R.id.rowtext, name);
                this.context = c;
                this.nameArray = name;
                this.modifiedArray = lastmod;
            }

            public View getView(int position, View convertView, ViewGroup parent)
            {
                LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View row = inflater.inflate(R.layout.layout_item_view, parent, false);

                TextView myName;
                TextView myLastMod;

                myName=(TextView) row.findViewById(R.id.rowtext);
                myName.setText(nameArray[position]);

                myLastMod=(TextView) row.findViewById(R.id.textView6);
                myLastMod.setText(modifiedArray[position]);

                return row;
            }
        }

         @Override
         public void onCreateContextMenu(ContextMenu menu, View v,
                                         ContextMenu.ContextMenuInfo menuInfo) {
             super.onCreateContextMenu(menu, v, menuInfo);
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(R.menu.context_menu, menu);
         }

        @Override
        public boolean onContextItemSelected(MenuItem itemMenu) {

            final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();

            switch (itemMenu.getItemId()) {
                case R.id.context_menu_rename:
                    Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.context_menu_delete:
                    // NOTE TESTING the line of code below caused a runtime error: java.lang.UnsupportedOperationException
                    customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
                    customListViewAdapter.notifyDataSetChanged();

                    Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
                    Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                return true;

                return super.onContextItemSelected(itemMenu);
        }
    }
}
</code>```

Logcat output:

```<code>11-13 10:45:21.229  21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-13 10:45:21.246  21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 21432
    java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:638)
            at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
            at java.util.AbstractCollection.remove(AbstractCollection.java:229)
            at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

答:
Just remove items from nameArray and modifiedArray at that particular position, then notify adapter of dataset changes.

I see. One big mistake is using fixed size array in a place that requires dynamic size array.

Change your

```<code>String nameArray[];
String modifiedArray[];
</code>```

to

```<code>ArrayList<String> nameArray;
 ArrayList<String> modifiedArray;
</code>```

Body:
The Problem is: My ContextMenu Fails to Remove a Row from ListView with a Custom Adapter and
the app crashes with the error: UnsupportedOperationException, see Logcat output.

I have done Google searches and searched stackoverflow. None of the information I have found solves this problem.

My Question is: What is wrong with my code?
Please provide the correct code to solve this problem.

Java Code:

        public class TestActivity extends ListActivity {

        private String itemNameArray[];
        private String dateArray[];

        private ListView listview;
        CustomListViewAdapter customListViewAdapter;

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

                            setContentView(R.layout.activity_test);

                            registerForContextMenu(getListView());

                            root = Environment.getExternalStorageDirectory() + File.separator + "/ListTestFiles";
                            getDir(root);

            listview = getListView();

            name=itemNameArray;
            lastmod=dateArray;

            customListViewAdapter = new CustomListViewAdapter(this, name, lastmod);

            listview.setAdapter(customListViewAdapter);

      } // End of onCreate code.

        class CustomListViewAdapter extends ArrayAdapter<String> {
            Context context;
            String[] nameArray;
            String[] modifiedArray;

            CustomListViewAdapter(Context c, String[] name, String[] lastmod)
            {
                super(c, R.layout.layout_item_view, R.id.rowtext, name);
                this.context = c;
                this.nameArray = name;
                this.modifiedArray = lastmod;
            }

            public View getView(int position, View convertView, ViewGroup parent)
            {
                LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View row = inflater.inflate(R.layout.layout_item_view, parent, false);

                TextView myName;
                TextView myLastMod;

                myName=(TextView) row.findViewById(R.id.rowtext);
                myName.setText(nameArray[position]);

                myLastMod=(TextView) row.findViewById(R.id.textView6);
                myLastMod.setText(modifiedArray[position]);

                return row;
            }
        }

         @Override
         public void onCreateContextMenu(ContextMenu menu, View v,
                                         ContextMenu.ContextMenuInfo menuInfo) {
             super.onCreateContextMenu(menu, v, menuInfo);
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(R.menu.context_menu, menu);
         }

        @Override
        public boolean onContextItemSelected(MenuItem itemMenu) {

            final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)itemMenu.getMenuInfo();

            switch (itemMenu.getItemId()) {
                case R.id.context_menu_rename:
                    Toast.makeText(this, "Rename", Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.context_menu_delete:
                    // NOTE TESTING the line of code below caused a runtime error: java.lang.UnsupportedOperationException
                    customListViewAdapter.remove(customListViewAdapter.getItem(info.position));
                    customListViewAdapter.notifyDataSetChanged();

                    Toast.makeText(getApplicationContext(), "position = " + info.position, Toast.LENGTH_SHORT).show();
                    Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();

                return true;

                return super.onContextItemSelected(itemMenu);
        }
    }
}

Logcat output:

11-13 10:45:21.229  21432-21432/com.testing.listapp D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
11-13 10:45:21.246  21432-21432/com.testing.listapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.testing.listapp, PID: 21432
    java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:638)
            at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
            at java.util.AbstractCollection.remove(AbstractCollection.java:229)
            at android.widget.ArrayAdapter.remove(ArrayAdapter.java:244)
            at com.testing.listapp.TestActivity.onContextItemSelected(TestActivity.java:5468)
            at android.app.Activity.onMenuItemSelected(Activity.java:2905)
            at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
            at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
            at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
            at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
            at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
            at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
            at android.widget.AdapterView.performItemClick(AdapterView.java:305)
            at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
            at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
            at android.widget.AbsListView$3.run(AbsListView.java:3860)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Body:
Just remove items from nameArray and modifiedArray at that particular position, then notify adapter of dataset changes.

I see. One big mistake is using fixed size array in a place that requires dynamic size array.

Change your

String nameArray[];
String modifiedArray[];

to

ArrayList<String> nameArray;
 ArrayList<String> modifiedArray;


问:
Mysql Query Slow on large table
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

```<code>SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25
</code>```

Here is the explain:

答:
The problem here is that the LIMIT is applied at the end of the query, after all the costly table scans are complete. The cost is not from returning lots of rows, but instead from scanning lots of rows.

The easiest way to speed up queries like this is with a covering index.   This will allow you to scan through the rows you want, but require fewer bytes of I/O per row (since you're only scanning a portion of each row's data, not the entire row). Furthermore, if your index is sorted in the same way that your query is, you can avoid the cost of a sort and can scan vastly fewer rows.

Your index should have these columns below. The first three columns must be in the same order as your GROUP BY-- this allows your GROUP BY and WHERE to be vastly cheaper to execute. The second line allows the index to "cover" the query, which means that MySQL will be able to satisfy the entire listing_track part of the query from the index alone:

```<code>CREATE INDEX ix_listing_track_covering ON listing_track (
    commid, listingid, trackip,
    listing_impression, listing_view, listing_phone, listing_forward, listing_coupon, listing_email);
</code>```

With this index in place, you should be able to run the exact same query but see vastly better performance.

Title: Mysql Query Slow on large table

Body:
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25

Here is the explain:

Body:
The problem here is that the LIMIT is applied at the end of the query, after all the costly table scans are complete. The cost is not from returning lots of rows, but instead from scanning lots of rows.

The easiest way to speed up queries like this is with a covering index.   This will allow you to scan through the rows you want, but require fewer bytes of I/O per row (since you're only scanning a portion of each row's data, not the entire row). Furthermore, if your index is sorted in the same way that your query is, you can avoid the cost of a sort and can scan vastly fewer rows.

Your index should have these columns below. The first three columns must be in the same order as your GROUP BY-- this allows your GROUP BY and WHERE to be vastly cheaper to execute. The second line allows the index to "cover" the query, which means that MySQL will be able to satisfy the entire listing_track part of the query from the index alone:

CREATE INDEX ix_listing_track_covering ON listing_track (
    commid, listingid, trackip,
    listing_impression, listing_view, listing_phone, listing_forward, listing_coupon, listing_email);

With this index in place, you should be able to run the exact same query but see vastly better performance.


问:
Simple Injector decorator and covariance
I have an application where I have multiple connection strings for my DbContext implementations. To support this in the consuming classes, I've created an IDbContextProvider interface with a Get method that can provide me with the DbContext instances I need.

I've also got an ICommandHandler thing going, and I'm trying to create a decorator that will call DbContext.SaveChangesAsync() on successful command execution. I'm registering my decorator like this:

```<code>container.RegisterDecorator(typeof(ICommandHandler<>),
    typeof(SaveChangesCommandHandlerDecorator<>));
</code>```

Now, because I don't want to add a type parameter for the DbContext implementaiton, and I know all classes derived from DbContext have a SaveChangesAsync() method, I figured I could use covariance. So my interface looks like this:

```<code>public public interface IDbContextProvider<out TDbContext> where TDbContext : DbContext
{
    TDbContext Get(DbPrivileges privileges);
}
</code>```

And the relevant part of my decorator:

```<code>public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
    where TCommand : ICommand
{
    private readonly ICommandHandler<TCommand> _handler;
    private readonly IDbContextProvider<DbContext> _dbContextProvider;

    public SaveChangesCommandHandlerDecorator(
        ICommandHandler<TCommand> handler, IDbContextProvider<DbContext> dbContextProvider)
    {
        _handler = handler;
        _dbContextProvider = dbContextProvider;
    }

    ...
</code>```

However, when I call Verify() on my container, it complains that the IDbContextProvider is invalid, as it's looking for the "base" IDbContextProvider<DbContext> instead of one of the ones registered in my app.

The constructor of type SaveChangesCommandHandlerDecorator<CreateUserCommand> contains the parameter with name 'dbContextProvider' and type IDbContextProvider<DbContext> that is not registered.Please ensure IDbContextProvider<DbContext> is registered, or change the constructor of SaveChangesCommandHandlerDecorator<CreateUserCommand>. Note that there exists a registration for a different type (Redacted).IDbContextProvider<TDbContext> while the requested type is (Redacted).IDbContextProvider<Microsoft.EntityFrameworkCore.DbContext>.

This actually makes sense, since Simple Injector has no way of knowing what concrete type to inject into the dbContextProvider parameter.

Is there any way of customizing the way my decorator is created, so that it can peek at the dependencies of the underlying ICommandHandler implementation's dependencies, and pick the IDbContextProvider signature from there on creation? So if my command handler has a IDbContextProvider<AwesomeDbContext>, I want that to be resolved for my decorator as well.

答:
So let me get this straight: your application contains multiple DbContext implemtantations, such as:

AwesomeDbContext

EventBetterDbContext

BrilliantDbContext

Now each command handler will typically depend on one particular DbContext implementation, by getting an IDbContextProvider<TDbContext> where the TDbContext is the specific DbContext implementation.

Now depending on what the decorator command handler depends upon, you wish to inject that exact same IDbContextProvider<TDbContext> implementation in the decorator as well, so you can save the changes for that particular instance.

If I summarize your question correctly, the short answer to your question is: no, you can't do that.

The longer answer is, yes this is actually possible by adding an extra generic type argument for TDbContext to your SaveChangesCommandHandlerDecorator<TCommand, TDbContext> decorator, and use the RegisterDecorator overload that accepts the Func<DecoratorPredicateContext, Type>. Using the supplied DecoratorPredicateContext to the factory delegate, you can analyze its Expression property to find out which IDbContextProvider<TDbContext> is injected, and based on that information you build a partially-closed version of SaveChangesCommandHandlerDecorator<TCommand, TDbContext> where you fill in TDbContext but leave TCommand open for Simple Injector to fill in.

But to be honest, I wouldn't take this route. It takes a lot of work, leads to hard to understand code, and your coworkers will hate you for this.

Instead, try injecting a list of IDbContextProvider<TDbContext> instances into the decorator instead. You can do that by making the IDbContextProvider<out TDbContext> registrations both separately, and as part of a collection using RegisterCollection.

When you inject the collection, the decorator can simply call save changes on all the DbContext instances. SaveChanges will be really fast when there are no changes, so from a performance perspective, I don't think there is anything to worry about.

Body:
I have an application where I have multiple connection strings for my DbContext implementations. To support this in the consuming classes, I've created an IDbContextProvider interface with a Get method that can provide me with the DbContext instances I need.

I've also got an ICommandHandler thing going, and I'm trying to create a decorator that will call DbContext.SaveChangesAsync() on successful command execution. I'm registering my decorator like this:

container.RegisterDecorator(typeof(ICommandHandler<>),
    typeof(SaveChangesCommandHandlerDecorator<>));

Now, because I don't want to add a type parameter for the DbContext implementaiton, and I know all classes derived from DbContext have a SaveChangesAsync() method, I figured I could use covariance. So my interface looks like this:

public public interface IDbContextProvider<out TDbContext> where TDbContext : DbContext
{
    TDbContext Get(DbPrivileges privileges);
}

And the relevant part of my decorator:

public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
    where TCommand : ICommand
{
    private readonly ICommandHandler<TCommand> _handler;
    private readonly IDbContextProvider<DbContext> _dbContextProvider;

    public SaveChangesCommandHandlerDecorator(
        ICommandHandler<TCommand> handler, IDbContextProvider<DbContext> dbContextProvider)
    {
        _handler = handler;
        _dbContextProvider = dbContextProvider;
    }

    ...

However, when I call Verify() on my container, it complains that the IDbContextProvider is invalid, as it's looking for the "base" IDbContextProvider<DbContext> instead of one of the ones registered in my app.

The constructor of type SaveChangesCommandHandlerDecorator<CreateUserCommand> contains the parameter with name 'dbContextProvider' and type IDbContextProvider<DbContext> that is not registered.Please ensure IDbContextProvider<DbContext> is registered, or change the constructor of SaveChangesCommandHandlerDecorator<CreateUserCommand>. Note that there exists a registration for a different type (Redacted).IDbContextProvider<TDbContext> while the requested type is (Redacted).IDbContextProvider<Microsoft.EntityFrameworkCore.DbContext>.

This actually makes sense, since Simple Injector has no way of knowing what concrete type to inject into the dbContextProvider parameter.

Is there any way of customizing the way my decorator is created, so that it can peek at the dependencies of the underlying ICommandHandler implementation's dependencies, and pick the IDbContextProvider signature from there on creation? So if my command handler has a IDbContextProvider<AwesomeDbContext>, I want that to be resolved for my decorator as well.


问:
R: Unexpected behaviour with error comparison in testthat
I am implementing a helper function that checks the length of the provided parameter against a template and throws an error when the lengths are different. Here is the function:

```<code>assert_character_vec_length <- function(x, ...) {
  name   <- as.character(substitute(x))
  lens   <- unlist(list(...))
  lnames <- as.character(substitute(list(...)))[-1]
  lnames <- paste(lnames, collapse=' or ')
  if(!(length(x) %in% lens) | !is.character(x))
    stop(paste0('"', name, '"', ' must be a character vector with length ', lnames))
}
</code>```

Below is an example of it's usage:

```<code>grp <- LETTERS[1:4]
assert_character_vec_length(grp, 3)
</code>```

Error in assert_character_vec_length(grp, 3) :
    "grp" must be a character vector with length 3

I am using this inside another function to check if the passed parameters are correct. And I am also writing tests for the function using the testthat library.

When I am comparing the length with a simple number everything works and the test passes:

```<code>x <- matrix(1:100, ncol=10)
grp <- LETTERS[1:4]

err1 <- '"grp" must be a character vector with length 10'
expect_error(assert_character_vec_length(grp, 10), err1)
</code>```

But to my surprise the error message doesn't match when I am using an expression to compare the lengths:

```<code>err2 <- '"grp" must be a character vector with length ncol(x)'
expect_error(assert_character_vec_length(grp, ncol(x)), err2)
</code>```

Error: error$message does not match "\"grp\" must be a character vector with length ncol(x)".
  Actual value: ""grp" must be a character vector with length ncol(x)"

What did I miss and what is going on here?

答:
Take a look at ?expect_output:

```<code>expect_output(object, regexp = NULL, ..., info = NULL, label = NULL)
</code>```

The second parameter is named "regexp",
and indeed,
it's used as a regular expression to test against.

The ( and ) have special meaning in regular expressions,
called capturing groups.
As written, these ( and ) will not match the literal "(" and ")" characters in the error message.

To make them match literal parentheses, you need to escape them:

```<code>err2 <- '"grp" must be a character vector with length ncol\\(x\\)'
expect_error(assert_character_vec_length(grp, ncol(x)), err2)
</code>```

(Actually, escaping the opening ( will be enough here.
But I find it's less confusing to read when the closing parenthesis is escaped too.)

Body:
I am implementing a helper function that checks the length of the provided parameter against a template and throws an error when the lengths are different. Here is the function:

assert_character_vec_length <- function(x, ...) {
  name   <- as.character(substitute(x))
  lens   <- unlist(list(...))
  lnames <- as.character(substitute(list(...)))[-1]
  lnames <- paste(lnames, collapse=' or ')
  if(!(length(x) %in% lens) | !is.character(x))
    stop(paste0('"', name, '"', ' must be a character vector with length ', lnames))
}

Below is an example of it's usage:

grp <- LETTERS[1:4]
assert_character_vec_length(grp, 3)

Error in assert_character_vec_length(grp, 3) :
    "grp" must be a character vector with length 3

I am using this inside another function to check if the passed parameters are correct. And I am also writing tests for the function using the testthat library.

When I am comparing the length with a simple number everything works and the test passes:

x <- matrix(1:100, ncol=10)
grp <- LETTERS[1:4]

err1 <- '"grp" must be a character vector with length 10'
expect_error(assert_character_vec_length(grp, 10), err1)

But to my surprise the error message doesn't match when I am using an expression to compare the lengths:

err2 <- '"grp" must be a character vector with length ncol(x)'
expect_error(assert_character_vec_length(grp, ncol(x)), err2)

Error: error$message does not match "\"grp\" must be a character vector with length ncol(x)".
  Actual value: ""grp" must be a character vector with length ncol(x)"

What did I miss and what is going on here?

Body:
Take a look at ?expect_output:

expect_output(object, regexp = NULL, ..., info = NULL, label = NULL)

The second parameter is named "regexp",
and indeed,
it's used as a regular expression to test against.

The ( and ) have special meaning in regular expressions,
called capturing groups.
As written, these ( and ) will not match the literal "(" and ")" characters in the error message.

To make them match literal parentheses, you need to escape them:

err2 <- '"grp" must be a character vector with length ncol\\(x\\)'
expect_error(assert_character_vec_length(grp, ncol(x)), err2)

(Actually, escaping the opening ( will be enough here.
But I find it's less confusing to read when the closing parenthesis is escaped too.)


问:
(How) can I count the items in an enum?
This question came to my mind, when I had something like

```<code>enum Folders {FA, FB, FC};
</code>```

and wanted to create an array of containers for each folder:

```<code>ContainerClass*m_containers[3];
....
m_containers[FA] = ...; // etc.
</code>```

(Using maps it's much more elegant to use: std::map<Folders, ContainerClass*> m_containers;)

But to come back to my original question: What if I do not want to hard-code the array size, is there a way to figure out how many items are in Folders? (Without relying on e.g. FC being the last item in the list which would allow something like ContainerClass*m_containers[FC+1] if I'm not mistaken.)

答:
I like to use enums as arguments to my functions.  It's an easy means to provide a fixed list of "options". The trouble with the top voted answer here is that using that, a client can specify an "invalid option".  As a spin off, I recommend doing essentially the same thing, but use a constant int outside of the enum to define the count of them.

```<code>enum foobar { foo, bar, baz, quz };
const int FOOBAR_NR_ITEMS=4;
</code>```

It's not pleasant, but it's a clean solution if you don't change the enum without updating the constant.

Title: (How) can I count the items in an enum?

Body:
This question came to my mind, when I had something like

enum Folders {FA, FB, FC};

and wanted to create an array of containers for each folder:

ContainerClass*m_containers[3];
....
m_containers[FA] = ...; // etc.

(Using maps it's much more elegant to use: std::map<Folders, ContainerClass*> m_containers;)

But to come back to my original question: What if I do not want to hard-code the array size, is there a way to figure out how many items are in Folders? (Without relying on e.g. FC being the last item in the list which would allow something like ContainerClass*m_containers[FC+1] if I'm not mistaken.)

Body:
I like to use enums as arguments to my functions.  It's an easy means to provide a fixed list of "options". The trouble with the top voted answer here is that using that, a client can specify an "invalid option".  As a spin off, I recommend doing essentially the same thing, but use a constant int outside of the enum to define the count of them.

enum foobar { foo, bar, baz, quz };
const int FOOBAR_NR_ITEMS=4;

It's not pleasant, but it's a clean solution if you don't change the enum without updating the constant.


问:
Disable screenshot
I am  using below code to view image with the help of default gallery,

```<code>        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoURI, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
</code>```

But at the same time  i want to disable screenshot when users view image using gallery. I can disable screenshot directly for my app screen but can't do when image is viewed from gallery.

Please help me.

答: You can't.  If you need that functionality, don't use gallery and write your own display code.  Although that's 99% useless-  if a user really wants to screenshot his own phone, he can.  Worst case he can grab a second phone and take a picture.</p>

Title: Disable screenshot

Body:
I am  using below code to view image with the help of default gallery,

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(photoURI, "image/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);

But at the same time  i want to disable screenshot when users view image using gallery. I can disable screenshot directly for my app screen but can't do when image is viewed from gallery.

Please help me.


问:
PowerBuilder unit testing framework
Is there any ability of PowerBuilder to write and run unit tests? I'm talking about PowerBuilder 12 classic.

Alternatively is there any third party framework or library for unit testing of powerbuilder code?

I'm pretty new to PowerBuilder, so I appreciate any advice or experience on testing PB applications.

答: I recommend PowerUnit. It has many enhancements compared to PbUnit.</p>

Title: PowerBuilder unit testing framework


问:
Python print result to variable with correct formatting
I have a script that uses raw_input to enter a IPv4 IP address in CIDR format.

```<code>#<--BEGIN IPv4 CIDR FORMATTING -->
# Get address string and CIDR string from command line
sys.argv = raw_input("Type IPv4 address in CIDR format ")
(addrString, cidrString) = sys.argv.split('/')
</code>```

The functions defined in the script converts the user inputted CIDR (1.1.1.1/16) to normal IPv4 format.

Print result with code: print addrString, ".".join(map(str, mask)) outputs to screen as 1.1.1.1 255.255.0.0 which is correct.
But when I assign addrString, ".".join(map(str, mask)) to a variable, like var2 = addrString, ".".join(map(str, mask)) it's shown as ('1.1.1.1', '255.255.0.0')

How can i strip the unneeded signs like

(

and

'

and

,

when assigning to a variable?

答:
You're printing a tuple. That's what tuples look like when printed. It sounds like you just want the two values together as a string, so you could do something like;</p>

```<code>display_value = " ".join(var2)
print var2
</code>```

Body:
I have a script that uses raw_input to enter a IPv4 IP address in CIDR format.

#<--BEGIN IPv4 CIDR FORMATTING -->
# Get address string and CIDR string from command line
sys.argv = raw_input("Type IPv4 address in CIDR format ")
(addrString, cidrString) = sys.argv.split('/')

The functions defined in the script converts the user inputted CIDR (1.1.1.1/16) to normal IPv4 format.

Print result with code: print addrString, ".".join(map(str, mask)) outputs to screen as 1.1.1.1 255.255.0.0 which is correct.
But when I assign addrString, ".".join(map(str, mask)) to a variable, like var2 = addrString, ".".join(map(str, mask)) it's shown as ('1.1.1.1', '255.255.0.0')

How can i strip the unneeded signs like

(

and

'

and

,

when assigning to a variable?

Body:
You're printing a tuple. That's what tuples look like when printed. It sounds like you just want the two values together as a string, so you could do something like;

display_value = " ".join(var2)
print var2


问:
Actions inside Areas
I have a masterpage inside a Area and a Controller outside the area. The controller's called "SecurityController" and i'm calling <%= Url.Action("LogOut", "Security", new {area=""}) %> as i saw in some posts but that doens't map to my "root" controllers.
The link is generated for /AREANAME/SecurityController/ witch's wrong.

What i'm doing wrong?

Thank U all.

答:
I was unable to reproduce the behavior you are describing. Here are the steps I did:

Create a new ASP.NET MVC 2 project using the default template

Add a new area called AREANAME using the Visual Studio Wizard

Add a FooController inside ~/Areas/AREANAME/Controller/FooController.cs:

```<code>public class FooController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}
</code>```

Copy-Paste the master page from ~/Views/Shared/Site.Master to ~/Areas/AREANAME/Views/Shared/Site.Master

Add a new Index view corresponding to the Index action of the FooController using the master page. Leave it as default.

Somewhere inside the master page of the area add the following (or inside the Index view of the FooController, it doesn't really matter):

```<code><%= Url.Action("Index", "Home", new { area = "" }) %>
</code>```

Run the site and navigate to /AREANAME/foo/index.

The correct url is generated: /

If you remove the area="" part of the helper the following url is generated: /AREANAME/Home.

So?

Title: Actions inside Areas

Body:
I was unable to reproduce the behavior you are describing. Here are the steps I did:

Create a new ASP.NET MVC 2 project using the default template

Add a new area called AREANAME using the Visual Studio Wizard

Add a FooController inside ~/Areas/AREANAME/Controller/FooController.cs:

public class FooController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Copy-Paste the master page from ~/Views/Shared/Site.Master to ~/Areas/AREANAME/Views/Shared/Site.Master

Add a new Index view corresponding to the Index action of the FooController using the master page. Leave it as default.

Somewhere inside the master page of the area add the following (or inside the Index view of the FooController, it doesn't really matter):

<%= Url.Action("Index", "Home", new { area = "" }) %>

Run the site and navigate to /AREANAME/foo/index.

The correct url is generated: /

If you remove the area="" part of the helper the following url is generated: /AREANAME/Home.

So?


问:
DOM not Populating in PhantomJS when Accessing Through Selenium
I've been searching for a solution to this problem for a good many days now, but have not been having much luck.

The versions I am using are as follows:

-Java 8

-Selenium 3.4.0

-PhantomJS 1.9.8 (Have had the same results with PhantomJS 2.1.1)

-JUnit 4.12 (The code is getting called through JUnit.)

Everything is happening on Windows 10 for this run, but I have had similar issues on CentOS 7.

I am attempting to run Selenium with PhantomJS and am running into issues getting a page to become fully available.

Below is a code snippet (with a ton of System.outs for testing purposes) in which I run into problems:

```<code>   methodDriver.manage().window().maximize();

   System.out.println(methodDriver.getPageSource());

   WebElement trackingInbox = methodDriver.findElement(By.id("inbox-widget-container-id"));

  WebElement inboxBody = trackingInbox.findElement(By.xpath("div[1]/div[2]/table/tbody"));

 >  List<WebElement> rows = inboxBody.findElements(By.tagName("tr"));
</code>```

I get

"errorMessage":"Unable to find element with id 'inbox-widget-container-id'"
   at the line:
  WebElement trackingInbox = methodDriver.findElement(By.id("inbox-widget-container-id"));

This makes some since because when I print the page source at the second line, these are the DOM contents:

Tracking Inbox

     <select id="inbox_group" name="inbox_group"></select>

     <select id="inboxes" name="inboxes"></select>

  <input type="hidden" id="inbox_content_totalRecords" value="">

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

<p>If, however, I use either chrome or firefox (headed) I get the following:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><body id="inboxBody" style="border: none; width: 957px;"><div id="inbox-widget-container-id" class="ui-resizable" style="width: 958px; margin-left: 1px; height: 500px;"><div class="grid-widget" style="width: 955px;"><div class="heading" style="background: linear-gradient(rgb(66, 139, 202), rgb(7, 105, 173)); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom: 0px; width: 955px;"><table class="heading" style="width: 938px; table-layout: fixed;"><tbody><tr><td style="text-align: center; height: 35px; width: 90px;"><div class="btn-group no-border condensed"><span class="btn btn-primary btn-sm thin-padding no-border hover-effect sortable" data-sortable-event="click">Case�#�<i class="fa fa-sort-amount-asc fa-fw fa-opaque"> . . .
     <div id="inboxContent" style="display: none;">
    <div class="mui-panel mui-panel-header">
     <p class="mui--text-subhead">Tracking Inbox</p>
    </div>
    <div id="inboxes_div">
          <div id="inboxes_control_section">
      <div id="inboxes_control_inboxGroup" style="float: left; padding-right: 10px;padding-left: 5px;">
       <select id="inbox_group" name="inbox_group"><option value="inbox.group.case">Case</option><option value="group.InvestiagtionItems">Investigation Items</option></select>
      </div>
      <div id="inboxes_control_inbox" style="float: left; padding-right: 10px;">
       <select id="inboxes" name="inboxes"><option value="inbox.cases">Assigned</option></select>
      </div>
     </div>
     <p></p>
     <div id="inbox_content_div" style="padding-top: 5px;"></div>
         </div>
    <input type="hidden" id="inbox_content_totalRecords" value="" />
   </div>
    <br />

</body></code>```

Notice that the first line goes on for a very long time (I deliberately cut it short here). That line contains the elements I want to work with, but are not showing up in PhantomJS.

Above the “” element, there is a large “” element with a jquery script. I have heard suggestions that this script is not running in phantomjs and that it would populate the DOM if it did. So, maybe I need to find out how to get it to run in phantom, though I am having some trouble figuring out how to do that.

答:
It looks like you need to wait for an element. Otherwise, the website doesn’t allow PhantomJS. Let’s try the wait first, see the example below.</p>

```<code>WebDriverWait wait = new WebDriverWait(methodDriver, 10);
WebElement trackingInbox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("inbox-widget-container-id")));
</code>```

Body:
I've been searching for a solution to this problem for a good many days now, but have not been having much luck.

The versions I am using are as follows:

-Java 8

-Selenium 3.4.0

-PhantomJS 1.9.8 (Have had the same results with PhantomJS 2.1.1)

-JUnit 4.12 (The code is getting called through JUnit.)

Everything is happening on Windows 10 for this run, but I have had similar issues on CentOS 7.

I am attempting to run Selenium with PhantomJS and am running into issues getting a page to become fully available.

Below is a code snippet (with a ton of System.outs for testing purposes) in which I run into problems:

   methodDriver.manage().window().maximize();

   System.out.println(methodDriver.getPageSource());

   WebElement trackingInbox = methodDriver.findElement(By.id("inbox-widget-container-id"));

  WebElement inboxBody = trackingInbox.findElement(By.xpath("div[1]/div[2]/table/tbody"));

 >  List<WebElement> rows = inboxBody.findElements(By.tagName("tr"));

I get

"errorMessage":"Unable to find element with id 'inbox-widget-container-id'"
   at the line:
  WebElement trackingInbox = methodDriver.findElement(By.id("inbox-widget-container-id"));

This makes some since because when I print the page source at the second line, these are the DOM contents:

Tracking Inbox

     <select id="inbox_group" name="inbox_group"></select>

     <select id="inboxes" name="inboxes"></select>

  <input type="hidden" id="inbox_content_totalRecords" value="">

If, however, I use either chrome or firefox (headed) I get the following:

Case�#� . . .

Tracking Inbox

       <select id="inbox_group" name="inbox_group"><option value="inbox.group.case">Case</option><option value="group.InvestiagtionItems">Investigation Items</option></select>

       <select id="inboxes" name="inboxes"><option value="inbox.cases">Assigned</option></select>

    <input type="hidden" id="inbox_content_totalRecords" value="" />

Notice that the first line goes on for a very long time (I deliberately cut it short here). That line contains the elements I want to work with, but are not showing up in PhantomJS.

Above the “” element, there is a large “” element with a jquery script. I have heard suggestions that this script is not running in phantomjs and that it would populate the DOM if it did. So, maybe I need to find out how to get it to run in phantom, though I am having some trouble figuring out how to do that.

Body:
It looks like you need to wait for an element. Otherwise, the website doesn’t allow PhantomJS. Let’s try the wait first, see the example below.

WebDriverWait wait = new WebDriverWait(methodDriver, 10);
WebElement trackingInbox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("inbox-widget-container-id")));


问:
How can I split a string at the first occurrence of "-" (minus sign) into two $vars with PHP?
How can I split a string at the first occurrence of - (minus sign) into two $vars with PHP?

I have found how to split on every "-" but, not only on the first occurrence.

example:

```<code>this - is - line - of whatever - is - relevant
$var1 = this
$var2 = is - line - of whatever - is - relevant
</code>```

Note, also stripped the first "-" .

答:
You can use strtok function:</p>

```<code>$first = strtok($string, '-');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I split a string at the first occurrence of - (minus sign) into two $vars with PHP?

I have found how to split on every "-" but, not only on the first occurrence.

example:

this - is - line - of whatever - is - relevant
$var1 = this
$var2 = is - line - of whatever - is - relevant

Note, also stripped the first "-" .

Body:
You can use strtok function:

$first = strtok($string, '-');


问:
How to fix: Host name 'repo1.maven.org' does not match the certificate subject provided
My builds are starting to fail today. Looks like we're still pointing to a deprecated maven repository? How do I update my gradle build without having to override every mavenCentral?!

If I do the follow, then my build works again. But I have so many projects that need to build in Jenkins.

```<code>repositories{
    mavenCentral(url:'https://repo.maven.apache.org/maven2')
}
</code>```

Here's the errors we're seeing:

```<code>> Could not resolve commons-lang:commons-lang:2.6.
  Required by:
      project : > [ snip ]:1.0-SNAPSHOT > net.sf.ezmorph:ezmorph:1.0.6
   > Could not resolve commons-lang:commons-lang:2.6.
      > Could not get resource 'https://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.pom'.
         > Could not GET 'https://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.pom'.
            > Host name 'repo1.maven.org' does not match the certificate subject provided by the peer (CN=repo.maven.apache.org, O="Sonatype, Inc", L=Fulton, ST=MD, C=US)
</code>```

TIA!

Piko

答: This is an issue started today, use https://issues.sonatype.org/browse/MVNCENTRAL-2870 for tracking the status.</p>

Body:
My builds are starting to fail today. Looks like we're still pointing to a deprecated maven repository? How do I update my gradle build without having to override every mavenCentral?!

If I do the follow, then my build works again. But I have so many projects that need to build in Jenkins.

repositories{
    mavenCentral(url:'https://repo.maven.apache.org/maven2')
}

Here's the errors we're seeing:

> Could not resolve commons-lang:commons-lang:2.6.
  Required by:
      project : > [ snip ]:1.0-SNAPSHOT > net.sf.ezmorph:ezmorph:1.0.6
   > Could not resolve commons-lang:commons-lang:2.6.
      > Could not get resource 'https://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.pom'.
         > Could not GET 'https://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.pom'.
            > Host name 'repo1.maven.org' does not match the certificate subject provided by the peer (CN=repo.maven.apache.org, O="Sonatype, Inc", L=Fulton, ST=MD, C=US)

TIA!

Piko