问:
rspec giving incorrect error messages
Following the RailsTutorial, I keep getting this error message (one of four actually) when it should be working:

```<code>UsersController authentication of edit/update pages for signed-in
users should require matching users for 'edit'
Failure/Error: @users = [@user, second, third] undefined local variable
or method 'second' for
#<RSpec::Core::ExampleGroup::Nested_3::Nested_7::Nested_2:0x000001040dcb68> #
./spec/controllers/users_controller_spec.rb:275:in 'block
(4 levels) in <top (required)>'
</code>```

I have tried to fix it by looking at other questions on stack overflow but to no avail. My gemfile now looks like this:

```<code>gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.0.1'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec-rails', '2.0.1'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.8.4'
  gem 'factory_girl_rails', '1.0'
end
</code>```

Any suggestions would be greatly appreciated!

答:
The backtrace is coming from the users_controller_spec.  Without the source, it's hard to say, but I'm guessing it's something like this:

```<code>describe UsersController
  before do
    @user = Factory(:user)
    sign_in(@user)
  end

  context "GET to edit for another user" do
    before do
      @other_user = Factory(:user)
      get :edit, :id => @other_user
    end

    it "should disallow editing of other users" do
      # ... expectations here of HTTP 401 or a user-friendly message
    end
  end
end
</code>```

Note that the variables shared between #before blocks and the examples are instance variables - local variables wouldn't be shared across them.  I'm guessing your code might be trying to share a local between examples, or between a #before block and its examples.

Title: rspec giving incorrect error messages

Body:
Following the RailsTutorial, I keep getting this error message (one of four actually) when it should be working:

UsersController authentication of edit/update pages for signed-in
users should require matching users for 'edit'
Failure/Error: @users = [@user, second, third] undefined local variable
or method 'second' for
#<RSpec::Core::ExampleGroup::Nested_3::Nested_7::Nested_2:0x000001040dcb68> #
./spec/controllers/users_controller_spec.rb:275:in 'block
(4 levels) in <top (required)>'

I have tried to fix it by looking at other questions on stack overflow but to no avail. My gemfile now looks like this:

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'
gem 'gravatar_image_tag', '0.1.0'
gem 'will_paginate', '3.0.pre2'

group :development do
  gem 'rspec-rails', '2.0.1'
  gem 'annotate-models', '1.0.4'
  gem 'faker', '0.3.1'
end

group :test do
  gem 'rspec-rails', '2.0.1'
  gem 'webrat', '0.7.1'
  gem 'spork', '0.8.4'
  gem 'factory_girl_rails', '1.0'
end

Any suggestions would be greatly appreciated!

Body:
The backtrace is coming from the users_controller_spec.  Without the source, it's hard to say, but I'm guessing it's something like this:

describe UsersController
  before do
    @user = Factory(:user)
    sign_in(@user)
  end

  context "GET to edit for another user" do
    before do
      @other_user = Factory(:user)
      get :edit, :id => @other_user
    end

    it "should disallow editing of other users" do
      # ... expectations here of HTTP 401 or a user-friendly message
    end
  end
end

Note that the variables shared between #before blocks and the examples are instance variables - local variables wouldn't be shared across them.  I'm guessing your code might be trying to share a local between examples, or between a #before block and its examples.


来源: stackexchange

问:
download sitecore support patch 451366
In Sitecore 8.1 update 1 there is a fix : Sitecore 8.1 Update 1 (An image’s URL became broken after changing its size in Rich Text Editor field. This has been fixed. (451366)) .
Is there a place from where I can download Sitecore.Support.451366 patch?

Dora

答:
Fixes are found on the Sitecore kb site

Unfortunately there is not an individual patch for this particular issue. This was a bug that was found in the 8.1 version and fixed in 8.1 Update 1.

You can either upgrade to 8.1 Update 1 or contact sitecore support and ask that they create an individual patch for this fix. (You'll need a Sitecore account to log in to this site)

ContentLicense: CC BY-SA 3.0

Title: download sitecore support patch 451366


问:
How can I connect to my server without outside ip adress from another network?
I want to connect to my server from another network, my server hasn't got an outside ip adress. I want to reach the sql server from where I host my website. I host my website somewhere else (not in my network). </p>

答:
Your SQL Server will have to be visible to the server from which you host your website.

I'm assuming you want to access the data in SQL Server to generate some content for your website.

There are 2 simple ways to do this:

Static IP - Ask your ISP for a static IP address for your local
network, you can use this in the connection string. This is preferable & more stable, since it will always be in sync.

Dynamic DNS - If your ISP won't give you a static address or you don't want to pay for it. You sign up with a DDNS service provider, they give you a domain name, like ferrysqlserver.ddns.org, and your network is visible to the internet via that name. Some routers support DDNS, otherwise you may have to run a service application that keeps your external ip address in sync with your DDNS provider.

Once you have either of those working, your network is now available to the internet, but nothing is likely accessible.
What you have done so far is to create a path from an internet name to your local router.

To make SQL Server accessible, you need to find out which ports your SQL Server uses (default is 1433). It's possible you may need to open other ports as well if you connect to SQL in a different way.

On your router, find the port forwarding options, and enable port forwarding to the local network ip address of your SQL Server, for port 1433.

This step maps connections from the internet to port 1433 of your router, and forwards those connections to port 1433 of your SQL Server.

Good luck.


问:
Linq extract a count() value from a data object
I have divAssignments that has potential multiple rows by rNI, an official id, according to a compound key of Indictment and booking numbers.

```<code>rNI    Booking  Indictment
12345  954445   10 12345
12345  954445   10 12346
12345  954445   10 12347
</code>```

So ID has a count of 3 for a single booking number for this rni.

I get lost attempting to generate a count and a group by booking Number:

```<code>var moreThen = from dA in divAssignments
    select new { dA.rNI, IndictmentCount = dA.indictmentNumber.Count() };
</code>```

Most of the examples are dealing with static int[] and don't seem to work in my case.

How do I get a group and then a count?  If I could put in a having that would be fantastic.

from a t-sql POV I'd use this:

```<code>Select rni, bookingNumber, count(*) IndictmentCount
from divAssignments
group by rni, bookingNumber
having count(*) > 0
</code>```

TIA

答:
How about something like this:

```<code>var query = from item in divAssignments
group item by item.rNI into grouping
select new
{
  Id = grouping.Key,
  Count = grouping.Count()
}
</code>```

If you're interested in grouping by both the rNI and the booking number, I would change it to this:

```<code>var query = from item in divAssignements
   group item by new { item.rNI, a.Booking } into grouping
   select new
    {
      Id = grouping.Key,
      Count = grouping.Count
    };
</code>```

OR

```<code>var query = from item in divAssignments
    group item by item into grouping
    select new
    {
      Id = grouping.Key,
      Count = grouping.Count()
    }
</code>```

and implement IEquatable on the divAssignment object to support equality comparison.  The other option if you'd like is to write an IEqualityComparer instance to do the composite key comparison. Your query could then look like:

```<code>var query =
  divAssignments
      .GroupBy(i => i, new MyCustomEqualityComparer())
      .Select(i => new { Key = i.Key, Count = i.Count());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have divAssignments that has potential multiple rows by rNI, an official id, according to a compound key of Indictment and booking numbers.

rNI    Booking  Indictment
12345  954445   10 12345
12345  954445   10 12346
12345  954445   10 12347

So ID has a count of 3 for a single booking number for this rni.

I get lost attempting to generate a count and a group by booking Number:

var moreThen = from dA in divAssignments
    select new { dA.rNI, IndictmentCount = dA.indictmentNumber.Count() };

Most of the examples are dealing with static int[] and don't seem to work in my case.

How do I get a group and then a count?  If I could put in a having that would be fantastic.

from a t-sql POV I'd use this:

Select rni, bookingNumber, count(*) IndictmentCount
from divAssignments
group by rni, bookingNumber
having count(*) > 0

TIA

Body:
How about something like this:

var query = from item in divAssignments
group item by item.rNI into grouping
select new
{
  Id = grouping.Key,
  Count = grouping.Count()
}

If you're interested in grouping by both the rNI and the booking number, I would change it to this:

var query = from item in divAssignements
   group item by new { item.rNI, a.Booking } into grouping
   select new
    {
      Id = grouping.Key,
      Count = grouping.Count
    };

OR

var query = from item in divAssignments
    group item by item into grouping
    select new
    {
      Id = grouping.Key,
      Count = grouping.Count()
    }

and implement IEquatable on the divAssignment object to support equality comparison.  The other option if you'd like is to write an IEqualityComparer instance to do the composite key comparison. Your query could then look like:

var query =
  divAssignments
      .GroupBy(i => i, new MyCustomEqualityComparer())
      .Select(i => new { Key = i.Key, Count = i.Count());


问:
mysql get row number from table where a column value is equal to a specific value
I have a table where results of modeltest are given in a column in descending order. Now I want to get the row number of a specific row. Here is the example table:

So when i will search a with userid=44, it should return 3. Again when i will search with userid=11, it should return 4. How can I do this ? If anyone could kindly help me out.

答:
A simple where clause will achieve this.

```<code>SELECT id FROM table WHERE userid = 44
</code>```

Swap table and userid value to whatever is needed.

Hope this helps

Body:
A simple where clause will achieve this.

SELECT id FROM table WHERE userid = 44

Swap table and userid value to whatever is needed.

Hope this helps


问:
Arguments to function not getting passed in correctly MASM
I'm learning MASM and I can't get this simple code to work. I'm not getting the values I pass into invoke, I don't know what's happening. I've tried push 2, push 2, call pow. Same results. EAX and EDX look like garbage or maybe memory addresses.

The thread 0x1544 has exited with code -1073741510 (0xc000013a).
The thread 0xd8 has exited with code -1073741510 (0xc000013a).
The thread 0x898 has exited with code -1073741510 (0xc000013a).
The thread 0x21c4 has exited with code -1073741510 (0xc000013a).
The program '[2296] AssemblyTutorial.exe' has exited with code -1073741510 (0xc000013a).

This just means I closed the console window, but why are there 4 threads?

```<code>.386
.model flat,stdcall
option casemap:none

include windows.inc

include masm32.inc
includelib masm32.lib

include kernel32.inc
includelib kernel32.lib

include user32.inc
includelib user32.lib

.code

;requires power > 0 for correct answers
pow proc x:DWORD, power:DWORD

    ;THESE TWO MOVES RIGHT HERE ARE NOT WORKING AS EXPECTED
    ;I PUSH 2 ONTO STACK BUT WHEN I LOOK AT REGISTER VALUES
    ;IN DEBUG THEY ARE INCORRECT/GARBAGE
    mov eax, x      ;eax has x
    mov edx, power  ;edx has power
    mov ecx, eax    ;ecx will be my constant base

start_power:
    cmp edx, 1      ;is power 1?
    je end_power    ;then jump to end
    imul eax, ecx   ;else mul result/x with x
    dec edx         ;power--
    jmp start_power ;jump back to beginning of loop

end_power:
    ret             ;return answer eax

pow endp

start:

invoke pow, 2, 2 ;eax should hold 4 after this
invoke ExitProcess, eax ;program should exit with code eax, ez way to print result

end start
</code>```

答:
Yes, the difference between cdecl and stdcall is that the former is caller-clean and the latter is callee-clean. (See also Raymond Chen's series on calling conventions in Windows.

The problem is, your pow procedure was not following the stdcall convention because it was not cleaning the stack. You need to specify the number of bytes to pop as part of the ret instruction. In this case, that would be ret 8.

Or, you can make the function cdecl, in which case the caller becomes responsible for cleaning the stack, and MASM can automatically generate this code as part of the INVOKE directive.

why are there 4 threads?

Windows starts background threads for various reasons. These are nothing to worry about. If you investigate them further, you'll probably see that they're started by the thread-pool worker thread (TppWorkerThread in ntdll.dll).

For what it's worth, the pow function could be more efficiently written as:

```<code>pow PROC x:DWORD, power:DWORD
    ; Load parameters into registers
    mov  eax, x
    mov  edx, power
    mov  ecx, eax

    ; Decrement 'power' by 1 and bail out if we're done.
    dec  edx
    jz   Finished

    ; The main loop.
CalculatePow:
    imul eax, ecx
    dec  edx
    jnz  CalculatePow

Finished:
    ret  8        ; assuming this function is STDCALL
pow ENDP
</code>```

Body:
I'm learning MASM and I can't get this simple code to work. I'm not getting the values I pass into invoke, I don't know what's happening. I've tried push 2, push 2, call pow. Same results. EAX and EDX look like garbage or maybe memory addresses.

The thread 0x1544 has exited with code -1073741510 (0xc000013a).
The thread 0xd8 has exited with code -1073741510 (0xc000013a).
The thread 0x898 has exited with code -1073741510 (0xc000013a).
The thread 0x21c4 has exited with code -1073741510 (0xc000013a).
The program '[2296] AssemblyTutorial.exe' has exited with code -1073741510 (0xc000013a).

This just means I closed the console window, but why are there 4 threads?

.386
.model flat,stdcall
option casemap:none

include windows.inc

include masm32.inc
includelib masm32.lib

include kernel32.inc
includelib kernel32.lib

include user32.inc
includelib user32.lib

.code

;requires power > 0 for correct answers
pow proc x:DWORD, power:DWORD

    ;THESE TWO MOVES RIGHT HERE ARE NOT WORKING AS EXPECTED
    ;I PUSH 2 ONTO STACK BUT WHEN I LOOK AT REGISTER VALUES
    ;IN DEBUG THEY ARE INCORRECT/GARBAGE
    mov eax, x      ;eax has x
    mov edx, power  ;edx has power
    mov ecx, eax    ;ecx will be my constant base

start_power:
    cmp edx, 1      ;is power 1?
    je end_power    ;then jump to end
    imul eax, ecx   ;else mul result/x with x
    dec edx         ;power--
    jmp start_power ;jump back to beginning of loop

end_power:
    ret             ;return answer eax

pow endp

start:

invoke pow, 2, 2 ;eax should hold 4 after this
invoke ExitProcess, eax ;program should exit with code eax, ez way to print result

end start

Body:
Yes, the difference between cdecl and stdcall is that the former is caller-clean and the latter is callee-clean. (See also Raymond Chen's series on calling conventions in Windows.

The problem is, your pow procedure was not following the stdcall convention because it was not cleaning the stack. You need to specify the number of bytes to pop as part of the ret instruction. In this case, that would be ret 8.

Or, you can make the function cdecl, in which case the caller becomes responsible for cleaning the stack, and MASM can automatically generate this code as part of the INVOKE directive.

why are there 4 threads?

Windows starts background threads for various reasons. These are nothing to worry about. If you investigate them further, you'll probably see that they're started by the thread-pool worker thread (TppWorkerThread in ntdll.dll).

For what it's worth, the pow function could be more efficiently written as:

pow PROC x:DWORD, power:DWORD
    ; Load parameters into registers
    mov  eax, x
    mov  edx, power
    mov  ecx, eax

    ; Decrement 'power' by 1 and bail out if we're done.
    dec  edx
    jz   Finished

    ; The main loop.
CalculatePow:
    imul eax, ecx
    dec  edx
    jnz  CalculatePow

Finished:
    ret  8        ; assuming this function is STDCALL
pow ENDP


问:
c++ XOR between bitsets
```<code>std::bitset <1> a1;
std::bitset <1> a2;

a1 = std::bitset<1> (0);
a2 = std::bitset<1> (1);

std::bitset<1> b = (a1 ^= a2)
</code>```

This results in

```<code>b = 1
</code>```

which is fine but modifies also a1, which after the XOR operation becomes:

```<code>a1 = 1
</code>```

Why is this happening?
How can I avoid this without creating temp variables?

答:
```<code>#include <iostream>
#include <bitset>
using namespace std;
int main()
{
    std::bitset <1> a1;
    std::bitset <1> a2;

    a1 = std::bitset<1>(0);
    a2 = std::bitset<1>(1);

    std::bitset<1> b = (a1 ^ a2);
    std::cout << b << std::endl;
    std::cout << a1 << std::endl;
    std::cout << a2 << std::endl;
    return 0;

}
</code>```

Correct output:
1
0
1

```<code>#include <iostream>
#include <bitset>
using namespace std;
int main()
{
    std::bitset <1> a1;
    std::bitset <1> a2;

    a1 = std::bitset<1>(0);
    a2 = std::bitset<1>(1);

    std::bitset<1> b = (a1 ^= a2);
    std::cout << b << std::endl;
    std::cout << a1 << std::endl;
    std::cout << a2 << std::endl;
    return 0;

}
</code>```

Correct output:
1
1
1
because ^=, so you change a1.

XOR is operator ^

Operator ^= is XOR with assignment

Title: c++ XOR between bitsets

Body:
std::bitset <1> a1;
std::bitset <1> a2;

a1 = std::bitset<1> (0);
a2 = std::bitset<1> (1);

std::bitset<1> b = (a1 ^= a2)

This results in

b = 1

which is fine but modifies also a1, which after the XOR operation becomes:

a1 = 1

Why is this happening?
How can I avoid this without creating temp variables?

Body:
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
    std::bitset <1> a1;
    std::bitset <1> a2;

    a1 = std::bitset<1>(0);
    a2 = std::bitset<1>(1);

    std::bitset<1> b = (a1 ^ a2);
    std::cout << b << std::endl;
    std::cout << a1 << std::endl;
    std::cout << a2 << std::endl;
    return 0;

}

Correct output:
1
0
1

#include <iostream>
#include <bitset>
using namespace std;
int main()
{
    std::bitset <1> a1;
    std::bitset <1> a2;

    a1 = std::bitset<1>(0);
    a2 = std::bitset<1>(1);

    std::bitset<1> b = (a1 ^= a2);
    std::cout << b << std::endl;
    std::cout << a1 << std::endl;
    std::cout << a2 << std::endl;
    return 0;

}

Correct output:
1
1
1
because ^=, so you change a1.

XOR is operator ^

Operator ^= is XOR with assignment


问:
java.net.MalformedURLException: unknown protocol: f
I am trying to get histogram of an image using this code Displaying a histogram of image data. Normally it works fine when input image given by url. But while I give image from local directory

```<code>private BufferedImage getImage() {
    try {
        return ImageIO.read(new URL(
            "F:/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}
</code>```

it gives exception,

```<code> java.net.MalformedURLException: unknown protocol: f
</code>```

How to resolve this exception and get Histogram of an image

答:
While the other answers will technically solve your problem, you shouldn't be using a URL for this. There are other signatures for the read function, one which takes a File and one which takes an InputStream instead, so you can use either of the following:

```<code>return ImageIO.read(new File("F:/test.jpg"));
// or
return ImageIO.read(new FileInputStream("F:/test.jpg"));
</code>```

Body:
I am trying to get histogram of an image using this code Displaying a histogram of image data. Normally it works fine when input image given by url. But while I give image from local directory

private BufferedImage getImage() {
    try {
        return ImageIO.read(new URL(
            "F:/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

it gives exception,

 java.net.MalformedURLException: unknown protocol: f

How to resolve this exception and get Histogram of an image

Body:
While the other answers will technically solve your problem, you shouldn't be using a URL for this. There are other signatures for the read function, one which takes a File and one which takes an InputStream instead, so you can use either of the following:

return ImageIO.read(new File("F:/test.jpg"));
// or
return ImageIO.read(new FileInputStream("F:/test.jpg"));


问:
Docker to run new container - list of all mapped ports?
When running a new container, we specify a port RUN_PORT:EXPOSED_PORT to map with the host machine. This will fail if RUN_PORT is already used.

So my question is how to list all the mapped port - so that we can pick up the port number out of the list.

p.s.

I'm using Ubuntu 16.04

答:
Listing all tcp ports being used (for listening) can be seen with:

```<code>netstat -lnt
</code>```

Looking up what is using a single port can be done with a netstat and grep, or if you have lsof installed:

```<code>sudo lsof -i :80 # shows the process using port 80
</code>```

Starting a docker container on a random available port mapped to port 80 inside the container:

```<code>docker run -p 80 -n container_name your_container
</code>```

Looking up what random port docker used in the above command on the host (this includes what IP interfaces it's attached to, or 0.0.0.0 for all interfaces, which is the default):

```<code>docker port container_name 80
</code>```

Body:
Listing all tcp ports being used (for listening) can be seen with:

netstat -lnt

Looking up what is using a single port can be done with a netstat and grep, or if you have lsof installed:

sudo lsof -i :80 # shows the process using port 80

Starting a docker container on a random available port mapped to port 80 inside the container:

docker run -p 80 -n container_name your_container

Looking up what random port docker used in the above command on the host (this includes what IP interfaces it's attached to, or 0.0.0.0 for all interfaces, which is the default):

docker port container_name 80


问:
PHP parse error on hello world
(warning: beginner)
So i set up a web server with a apache, mysql, php for OS X tutorial online.

https://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/

Everything is working and i can get on localhost/user/sites/ to open .php scripts. When im doing the simplest things like :

```<code><?php
echo "Hi";
?>
</code>```

Parse error: parse error, expecting `"identifier (T_STRING)"' in
  /Users/xyz/Sites/test.php on line 11

But there is not even a line 11 to correct something?

I even tried it with html body and so on. not working either.

Apache is working and the mysql server too.
phpMyAdmin is working, i can edit lists on mysql and so on.
phpInfo tells me its version 5.5.38

What can i do to get a simple browser view of what i wrote in my .php doc?

答:
if short_open_tags are enabled, then you can't begin your PHP scripts with an XML declaration.
PHP will see the <? and reclaim it for itself. It won't understand what the stray php was meant for. It'll get interpreted as constant. But the echo will be seen as another literal/constant. And since the parser can't make sense of two subsequent literals/values without an expression operator in between, that'll be a parser failure.

EDIT : (solution approved by OP)

it's Invisible Unicode characters issue. Changing code editor solved the problem

Title: PHP parse error on hello world

Body:
(warning: beginner)
So i set up a web server with a apache, mysql, php for OS X tutorial online.

https://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/

Everything is working and i can get on localhost/user/sites/ to open .php scripts. When im doing the simplest things like :

<?php
echo "Hi";
?>

Parse error: parse error, expecting `"identifier (T_STRING)"' in
  /Users/xyz/Sites/test.php on line 11

But there is not even a line 11 to correct something?

I even tried it with html body and so on. not working either.

Apache is working and the mysql server too.
phpMyAdmin is working, i can edit lists on mysql and so on.
phpInfo tells me its version 5.5.38

What can i do to get a simple browser view of what i wrote in my .php doc?


问:
Scala return variable type after future is complete Add Comment Collapse
I've got a problem with returning a list after handling futures in scala. My code looks like this:

```<code>def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
    var elementArray: Seq[Element] = Seq()

    arrayOfIds.map {
      ids => ids.map(id => dto.getElementById(id).map {
                    case Some(element) => elementArray = elementArray :+ element
                    case None => println("Element not found")
                  })
    }
    arrayOfIds.onComplete(_ => elementArray)
  }
</code>```

I'd like to do something like .onComplete, however the return type is
 Unit and I'd like to return a Future[Seq[Whatever]]. Is there clean way to handle futures like this? Thanks!

答:
Please provide the type of function dto.getElementById. If it is Int => Future[Option[Element]], then:

```<code>def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
  val allElements: Future[Seq[Option[Element]]] = arrayOfIds.flatMap( ids =>
    Future.sequence(ids.map(dto.getElementById))
  )
  allElements.map(_.flatMap{
    case None => println();None
    case some => some
  })
}
</code>```

Without logging, it would be:

```<code>arrayOfIds.flatMap( ids => Future.traverse(ids.map(dto.getElementById))(_.flatten))
</code>```

Body:
I've got a problem with returning a list after handling futures in scala. My code looks like this:

def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
    var elementArray: Seq[Element] = Seq()

    arrayOfIds.map {
      ids => ids.map(id => dto.getElementById(id).map {
                    case Some(element) => elementArray = elementArray :+ element
                    case None => println("Element not found")
                  })
    }
    arrayOfIds.onComplete(_ => elementArray)
  }

I'd like to do something like .onComplete, however the return type is
 Unit and I'd like to return a Future[Seq[Whatever]]. Is there clean way to handle futures like this? Thanks!

Body:
Please provide the type of function dto.getElementById. If it is Int => Future[Option[Element]], then:

def getElements(arrayOfIds: Future[Seq[Int]]): Future[Seq[Element]] = {
  val allElements: Future[Seq[Option[Element]]] = arrayOfIds.flatMap( ids =>
    Future.sequence(ids.map(dto.getElementById))
  )
  allElements.map(_.flatMap{
    case None => println();None
    case some => some
  })
}

Without logging, it would be:

arrayOfIds.flatMap( ids => Future.traverse(ids.map(dto.getElementById))(_.flatten))


问:
SVN: Malformed XML error
I am trying to checkout a branch from a remote repository. A number of files are checked out, then the checkout fails with the following errors:

svn: E175009: The XML response contains invalid XML

svn: E130003: Malformed XML: not well-formed (invalid token)

What could have caused this issue and is there a way to repair the remote repository?

答:
You should contact the admin of the server for assistance with this problem. The root cause can be a malfunctioning antivirus on your workstation or on the server. Firewall or proxy could also cause such problems. Moreover, your server is outdated.

The remote is Apache Subversion version 1.7.22

I guess that 'remote' means the remote server that hosts your repositories. SVN version that it runs is outdated. You must plan an upgrade to the latest 1.9.x version.

Title: SVN: Malformed XML error


问:
variable button vb.net
i declared a global variable button:

Dim button1 As New Button()

Now, i dont know how to add a click event in this button since it is a variable. Do you have any idea how do i do it?

答:
```<code>AddHandler button1.Click, AddressOf MyEventHandler

Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs)
      '
      ' Code to be executed when the event is raised.
      '
      MsgBox("I caught the event!")
End Sub
</code>```

OwnerDisplayName: sef

LastEditorDisplayName: lc

Title: variable button vb.net

OwnerDisplayName: Michael Buen


问:
What is difference between session and cookie in php?
Hi I would like to know the difference between a php session and a cookie

答:
Cookie: A key/value pair that is stored by the user's browser and is available in the superglobal $_COOKIE array available in PHP. The cookie request is initiated with an explicitly defined expiration date. For example:

setcookie('cookieName', $some_value, time()+3600, "/", ".example.com")

On the next server request, $_COOKIE['cookieName'] will be available. If you use a browser tool to look at the cookie, it will have an expiration date.

Session Cookie: Identical to the above but defined without an expiration date. If you use the same browser tool it will say that the cookie expires at the end of the session; which is ultimately when you close your browser. For example:

setcookie('cookieName', $some_value);

PHP Session: a server side mechanism that will associate a bunch of data with a session id. Every time a session is invoked, it serializes/unserializes it. This could be more data than just a single key/value pair that a cookie supports, but the way of associating this data with a user is by creating a cookie (regular or session as described above) in their browser that contains the session id. This way, the right data can be retrieved for a given user based on the value of that cookie.


问:
Modify string representation of data in Python
O would like to modify my data. My function is:

```<code> print (str(freq[8:10])[2:-1])
</code>```

I have 2 results like this: 105.00000031 105.0000041

Can I modify the presentation of this to include newlines like this?:

```<code>105.00000031
105.00000041
</code>```

data to normalyze

答:
I'm not sure I understand your question, but if what you want is to take a string and replace all spaces with "\n", you can simply replace.

```<code>data = '105.00000031 105.0000041'
data.replace(' ', '\n')  # returns the data separed by newlines
data2 = data.replace(' ', '\n')  # saves the data separed by newlines in a new variable
data = data.replace(' ', '\n')  # replaces the original data with the "normalized" one
</code>```

If you might have more complicated patterns (multiple spaces, colons, anything) you should use the re module. Is this the case?

Body:
O would like to modify my data. My function is:

 print (str(freq[8:10])[2:-1])

I have 2 results like this: 105.00000031 105.0000041

Can I modify the presentation of this to include newlines like this?:

105.00000031
105.00000041

data to normalyze

Body:
I'm not sure I understand your question, but if what you want is to take a string and replace all spaces with "\n", you can simply replace.

data = '105.00000031 105.0000041'
data.replace(' ', '\n')  # returns the data separed by newlines
data2 = data.replace(' ', '\n')  # saves the data separed by newlines in a new variable
data = data.replace(' ', '\n')  # replaces the original data with the "normalized" one

If you might have more complicated patterns (multiple spaces, colons, anything) you should use the re module. Is this the case?


问:
CSS Text-overflow Ellipsis Not Displaying Correctly
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

```<code>.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}
</code>```

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

答:
.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: block;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="mw">
  TestingTestingTestingTestingTestingTesting
</p></code>```

use display: block for truncation.

NOTE: clamp css will not work on Firefox and IE

Ref: https://caniuse.com/#search=clamp

Body:
I have a
 tag to display some information but it should be restricted to 2 lines and if the text is greater then it should show "..." at end. I tried many solutions but i am not able to get exactly what i am looking for. i have tried below css.

.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}

but i am getting three different outputs for three different text in
.

TestingTestingTestingTestingTestingTesting

TestingTesting TestingTestingTestingTesting

TestingTesting TestingTesting TestingTesting

Body:
.mw {
   overflow: hidden;
   text-overflow: ellipsis;
   display: block;
   -webkit-box-orient: vertical;
   -webkit-line-clamp: 2;
   line-height: 20px;
   max-height: 40px;
   width:100px;
   border:1px solid #ccc;
}

<p class="mw">
  TestingTestingTestingTestingTestingTesting
</p>

use display: block for truncation.

NOTE: clamp css will not work on Firefox and IE

Ref: https://caniuse.com/#search=clamp


问:
common roles for all tenants in AspNetBoilerplate
I have a custom set of roles that is supposed to be used in a multi-tenant app.

AbpRoles table has a column titled "TenantId" (nullable).

Problem is that if I leave this field with a null value, a user per certain tenant cannot be recognized as being related to a certain role. But if an AbpRole record has tenant id value - all works pretty well.

The bottomline is:

my code has to be creating the same set of roles for each tenant, so I'm just wondering if it's possible to have common set of roles for all tenants.

If the TenantId value is null for AbpRole record and I wrap the code that checks if user belongs to a role

```<code>User.IsInRole("Employee")
</code>```

into this block

```<code>using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
</code>```

the problem is still not solved.

答:
Sorry for late answer. For the guys looking an answer for this question;
Roles should be created per tenant. If you are using single tenant then you have use the Default tenant's id. As a result you can not share a role. If you insist on sharing roles btw tenants you have to disable MayHaveTenant everytime you make operation on role.</p>

Body:
I have a custom set of roles that is supposed to be used in a multi-tenant app.

AbpRoles table has a column titled "TenantId" (nullable).

Problem is that if I leave this field with a null value, a user per certain tenant cannot be recognized as being related to a certain role. But if an AbpRole record has tenant id value - all works pretty well.

The bottomline is:

my code has to be creating the same set of roles for each tenant, so I'm just wondering if it's possible to have common set of roles for all tenants.

If the TenantId value is null for AbpRole record and I wrap the code that checks if user belongs to a role

User.IsInRole("Employee")

into this block

using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))

the problem is still not solved.


问:
Can I use winston logging functions in my all ".js" file in my nodejs server?
I am creating a nodjs server.
In this server I am going to use winston logging.
This server is haveing some .js file related to webpages so do I need to use winston in all the .js files in place of console.log.</p>

答:
This server is haveing some .js file related to webpages

If "having some .js file related to webpages" mean client-side JavaScript then you cannot use Winston on the client directly - what you could do is create a logging connection e.g. with WebSocket or Socket.io or even create a logging endpoint for your client-side code that would internally use Winston on the server side and use that for logging on the client side.

If "having some .js file related to webpages" mean having multiple .js files on the backend then you can easily share a Winston instance with shared configuration and export it from a shared module that would be imported by all of the code that needs logging on the backend.


问:
Core Data predicate to fetch based on two of relationship's properties
I have two simple Entities:

```<code>Part {
    @NSManaged var states: Set<PartState>
}

PartState {
    @NSManaged var date: Date
    @NSManaged var state: Int
}
</code>```

I want to fetch those entities from Part, that newest PartState has state == 1.

I've tried to create NSPredicate:

NSPredicate(format: "SUBQUERY(states, $s, $s.date == max($s.date) AND $s.state == 1).@count > 0")

It looks like max($.date) checks all existing PartState entities, not just those belonging to a given Part and always returns 1 or 0 results.

NSPredicate(format: "ANY (states.state == 1 AND states.date == states.@max.date)")

Fails with: Unable to parse the format string...

NSPredicate(format: "ANY states.state == 1 AND ANY states.date == states.@max.date")

Returns all entities that have ever had state == 1 (which is what I would expect).

The only other solution that comes to my mind, is to have newestState property in Part but I still looking for some NSPredicate-based way.

答:
You can fetch latest entry based on date using sort Descriptor
and apply predicate to fetch which has state == 1</p>

```<code>let fetchRequest = NSFetchRequest<Part>.init(entityName: "Part")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "states.date", ascending: false)]

 let predicate = NSPredicate.init(format: "states.state = %@","1")
</code>```

Body:
I have two simple Entities:

Part {
    @NSManaged var states: Set<PartState>
}

PartState {
    @NSManaged var date: Date
    @NSManaged var state: Int
}

I want to fetch those entities from Part, that newest PartState has state == 1.

I've tried to create NSPredicate:

NSPredicate(format: "SUBQUERY(states, $s, $s.date == max($s.date) AND $s.state == 1).@count > 0")

It looks like max($.date) checks all existing PartState entities, not just those belonging to a given Part and always returns 1 or 0 results.

NSPredicate(format: "ANY (states.state == 1 AND states.date == states.@max.date)")

Fails with: Unable to parse the format string...

NSPredicate(format: "ANY states.state == 1 AND ANY states.date == states.@max.date")

Returns all entities that have ever had state == 1 (which is what I would expect).

The only other solution that comes to my mind, is to have newestState property in Part but I still looking for some NSPredicate-based way.

Body:
You can fetch latest entry based on date using sort Descriptor
and apply predicate to fetch which has state == 1

let fetchRequest = NSFetchRequest<Part>.init(entityName: "Part")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "states.date", ascending: false)]

 let predicate = NSPredicate.init(format: "states.state = %@","1")


问:
Is it possible to extract contents of a *non* self-extracting .exe file?
Well.... the question sort of says it all. If possible I would like to be able to do so from a Linux or macOS environment, but I have virtualized Windows if need be.

Thanks in advance!

答:
There is no general answer for this because different installers/applications use different storage methods. You should first try to identify the author of the installer software by looking for clues in the version information and maybe with a hex editor.

My first suggestion is to try 7-zip, it can extract from NSIS based installers and some MSI based installers.

If the setup was created with Inno Setup then you can try this.

If all else fails, try Universal Extractor but even that will fail for obscure and custom .exe files.


答:
```<code>  std::bitset<1> b = (a1 ^= a2);
</code>```

You are modifying a1 here as

a1^=a2 is equivalent to a1=a1^a2.Also it will only modify a1 and not a2.

Use this

```<code>  std::bitset<1> b = (a1 ^ a2);
</code>```

Title: c++ XOR between bitsets

Body:
  std::bitset<1> b = (a1 ^= a2);

You are modifying a1 here as

a1^=a2 is equivalent to a1=a1^a2.Also it will only modify a1 and not a2.

Use this

  std::bitset<1> b = (a1 ^ a2);


问:
Datatables Using ssp.class.php gives up warning of syntax error
class.php of datatables and Getting a error as below

error
:

An SQL error occurred: SQLSTATE[42000]: Syntax error or access
  violation: 1064 You have an error in your SQL syntax; check the manual
  that corresponds to your MySQL server version for the right syntax to
  use near 'ORDER BY request_id ASC↵             LIMIT 0, 10' at line 4

My Server side code is as below named as request-list.php

```<code>    <?php
   $inc_files = array("ph_utils");
   require_once ('autoload.php');
   $db = new db();
   $table = 'wallet_load_request';
  $primaryKey = 'request_id';
  $columns = array(
   array('db' => 'request_id', 'dt' => 0),
   array('db' => 'request_date', 'dt' => 1),
   array('db' => 'trans_mode', 'dt' => 2),
   array('db' => 'trans_amt', 'dt' => 3),
   array('db' => 'request_status', 'dt' => 4),
   array('db' => 'org_id', 'dt' => 5)
  );
  $sql_details = array(
   'user' => PH_DB_USER,
   'pass' => PH_DB_PSWD,
   'db' => PH_DB,
   'host' => PH_DB_HOST
   );
require_once('ssp.class.php');
$filterByStaus = isset($_REQUEST['filter_by_status']) ?
$_REQUEST['filter_by_status'] : "PENDING";

switch ($filterByStaus) {
case 'REJECTED':
$fixedFilter .= " AND request_status = 'REJECTED'";
break;
case 'APPROVED':
$fixedFilter .= " AND request_status = 'APPROVED'";
break;
default:
break;
}
$output = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns,
$fixedFilter);
foreach ($output['data'] as $i => $d) {
$request_id = $output['data'][$i][0];
$trans_amt = $output['data'][$i][3];
$request_status = $output['data'][$i][4];
$org_id = $output['data'][$i][5];
$output['data'][$i][0] = '<div class="text-center"><h4><span class="label label-success"> #'. $request_id .'</span></h4></div>';

if ($request_status == 'APPROVED') {
$output['data'][$i][4] = '<div class="text-center"><span class="label label-success"> APPROVED </span></div>';
$output['data'][$i][5] = '<div class="text-center"><button id="accept" type="button" class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'><i class="fa fa-ban"></i> ACCEPT</button></div>';
$output['data'][$i][6] = '<div class="text-center"><button id="reject" type="button" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'><i class="fa fa-ban"></i> REJECT</button></div>';
} else if ($request_status == 'REJECTED') {
$output['data'][$i][4] = '<div class="text-center"><span class="label label-danger"> REJECTED </span></div>';
$output['data'][$i][5] = '<div class="text-center"><button type="button" id="accept"  class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'><i class="fa fa-ban"></i> ACCEPT</button></div>';
$output['data'][$i][6] = '<div class="text-center"><button type="button" id="reject" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'><i class="fa fa-ban"></i> REJECT</button></div>';
} else {
$output['data'][$i][4] = '<div class="text-center"><span class="label label-warning"> PENDING </span></div>';
$output['data'][$i][5] = '<div class="text-center"><button type="button" id="accept" class="text-center btn btn-success accept" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'><i class="fa fa-ban"></i> ACCEPT</button></div>';
$output['data'][$i][6] = '<div class="text-center"><button type="button" id="reject" class="text-center btn btn-danger reject" data-request_id=\'' . $request_id . '\'><i class="fa fa-ban"></i> REJECT</button></div>';
 }

}
SSP::sendJson($output);
</code>```

My jquery code is as below request-list.js

```<code>var requestList = {
  oTable: {},
  init: function () {

   requestList.oTable = $('#req_list').dataTable({
    "processing": true,
    "serverSide": true,
    "columnDefs": [{className: "data_middle ", "targets": [0, 1, 2, 3, 4, 5, 6]}],
    "columns": [null, null, null, {"orderable": false}, {"orderable": false}, {"orderable": false}, {"orderable": false}],
   "ajax": {
   "url": "web/request-list",
   "data": function (d) {
     return $.extend({}, d, {
     "filter_by_status": $('#status').val(),

     });
   }
 }
});
}
}
</code>```

My front end code is list.html

           Filter By :

            PENDING
            APPROVED
            REJECTED

```<code>    <br>

    <div class="row">
     <div class="col-md-10 col-md-offset-1">
      <table class="table table-bordered table-striped table-hover" id="req_list">
       <thead>
        <tr>
         <th>Request ID</th>
         <th>DATE</th>
         <th>Mode</th>
         <th class="text-center">AMOUNT</th>
         <th class="text-center">STATUS</th>
         <th class="text-center">ACCEPT</th>
         <th class="text-center">REJECT</th>
        </tr>
       </thead>
       <tbody>
       </tbody>
      </table>
     </div>
    </div>
</code>```

after running the code the page shows up warning as DataTables warning: table id=req_list - An SQL error occurred: SQLSTATE[42000]: Syntax error or acess violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server cersion for the right syntax to user near 'ORDER BY request_id ASC LIMIT 0, 10' at line 4

and in console i get the error as

jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined

The Custom ssp code is as below on below link

https://drive.google.com/open?id=0B-e2dOqifK3QOFFnRjhTYjhPQmM

答:
If you want to filtered data in this case you need to use complex() instead of simple() method.

Complex() Method

```<code>SSP::complex($request, $conn, $table, $primaryKey, $columns, $whereResult = null, $whereAll = null)
</code>```

Simple() Method

```<code>simple($request, $conn, $table, $primaryKey, $columns)
</code>```

Let us know if it not works for you.

Body:
class.php of datatables and Getting a error as below

error
:

An SQL error occurred: SQLSTATE[42000]: Syntax error or access
  violation: 1064 You have an error in your SQL syntax; check the manual
  that corresponds to your MySQL server version for the right syntax to
  use near 'ORDER BY request_id ASC↵             LIMIT 0, 10' at line 4

My Server side code is as below named as request-list.php

    <?php
   $inc_files = array("ph_utils");
   require_once ('autoload.php');
   $db = new db();
   $table = 'wallet_load_request';
  $primaryKey = 'request_id';
  $columns = array(
   array('db' => 'request_id', 'dt' => 0),
   array('db' => 'request_date', 'dt' => 1),
   array('db' => 'trans_mode', 'dt' => 2),
   array('db' => 'trans_amt', 'dt' => 3),
   array('db' => 'request_status', 'dt' => 4),
   array('db' => 'org_id', 'dt' => 5)
  );
  $sql_details = array(
   'user' => PH_DB_USER,
   'pass' => PH_DB_PSWD,
   'db' => PH_DB,
   'host' => PH_DB_HOST
   );
require_once('ssp.class.php');
$filterByStaus = isset($_REQUEST['filter_by_status']) ?
$_REQUEST['filter_by_status'] : "PENDING";

switch ($filterByStaus) {
case 'REJECTED':
$fixedFilter .= " AND request_status = 'REJECTED'";
break;
case 'APPROVED':
$fixedFilter .= " AND request_status = 'APPROVED'";
break;
default:
break;
}
$output = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns,
$fixedFilter);
foreach ($output['data'] as $i => $d) {
$request_id = $output['data'][$i][0];
$trans_amt = $output['data'][$i][3];
$request_status = $output['data'][$i][4];
$org_id = $output['data'][$i][5];
$output['data'][$i][0] = '

 #'. $request_id .'

';

if ($request_status == 'APPROVED') {
$output['data'][$i][4] = '
 APPROVED
';
$output['data'][$i][5] = '
<button id="accept" type="button" class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'> ACCEPT</button>
';
$output['data'][$i][6] = '
<button id="reject" type="button" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'> REJECT</button>
';
} else if ($request_status == 'REJECTED') {
$output['data'][$i][4] = '
 REJECTED
';
$output['data'][$i][5] = '
<button type="button" id="accept"  class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'> ACCEPT</button>
';
$output['data'][$i][6] = '
<button type="button" id="reject" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'> REJECT</button>
';
} else {
$output['data'][$i][4] = '
 PENDING
';
$output['data'][$i][5] = '
<button type="button" id="accept" class="text-center btn btn-success accept" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'> ACCEPT</button>
';
$output['data'][$i][6] = '
<button type="button" id="reject" class="text-center btn btn-danger reject" data-request_id=\'' . $request_id . '\'> REJECT</button>
';
 }

}
SSP::sendJson($output);

My jquery code is as below request-list.js

var requestList = {
  oTable: {},
  init: function () {

   requestList.oTable = $('#req_list').dataTable({
    "processing": true,
    "serverSide": true,
    "columnDefs": [{className: "data_middle ", "targets": [0, 1, 2, 3, 4, 5, 6]}],
    "columns": [null, null, null, {"orderable": false}, {"orderable": false}, {"orderable": false}, {"orderable": false}],
   "ajax": {
   "url": "web/request-list",
   "data": function (d) {
     return $.extend({}, d, {
     "filter_by_status": $('#status').val(),

     });
   }
 }
});
}
}

My front end code is list.html

           Filter By :

            PENDING
            APPROVED
            REJECTED

         Request ID
         DATE
         Mode
         AMOUNT
         STATUS
         ACCEPT
         REJECT

after running the code the page shows up warning as DataTables warning: table id=req_list - An SQL error occurred: SQLSTATE[42000]: Syntax error or acess violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server cersion for the right syntax to user near 'ORDER BY request_id ASC LIMIT 0, 10' at line 4

and in console i get the error as

jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined

The Custom ssp code is as below on below link

https://drive.google.com/open?id=0B-e2dOqifK3QOFFnRjhTYjhPQmM

Body:
If you want to filtered data in this case you need to use complex() instead of simple() method.

Complex() Method

SSP::complex($request, $conn, $table, $primaryKey, $columns, $whereResult = null, $whereAll = null)

Simple() Method

simple($request, $conn, $table, $primaryKey, $columns)

Let us know if it not works for you.


问:
Globalize Version 1.2.3 - root/fallback Culture
i'm using the current release version 1.2.3 and would like to use the functionality described here:
https://github.com/globalizejs/globalize/blob/6d3a5a57c56fd0afb93e20340905a435d1650341/doc/api/message/load-translation.md#example

I need to inherit translations to have a fallback culture for the case that a browser culture is not defined / initialized in my loadMessages method. For example:

Globalize.loadMessages({
 root: { hello: "Hi!" },
 de: { hello: "Moin!" }
});

This is what i expect:

Globalize( "de-DE" ).formatMessage( "hello" );

"Moin!"

Globalize( "fr" ).formatMessage( "hello" );

"Hi!" (fallback)

How can i realize this?

答:
Short answer

It's missing Globalize.loadMessages({fr: {}});. The empty message tells globalize fr is a valid bundle.

Longer answer

The documentation example works just fine. Note: Use v1.2.3 documentation here: https://github.com/globalizejs/globalize/blob/1.2.3/doc/api/message/load-messages.md

In order to test I did:

```<code>npm install globalize cldr-data
</code>```

Then:

```<code>var Globalize = require( "globalize" );
Globalize.load( require( "cldr-data" ).entireSupplemental() );

Globalize.loadMessages({
  root: {
    amen: "Amen"
  },
  de: {},
  en: {},
  "en-GB": {},
  fr: {},
  pt: {
    amen: "Amém"
  },
  "pt-PT": {}
});

Globalize( "de" ).formatMessage( "amen" );
// > "Amen"

Globalize( "en" ).formatMessage( "amen" );
// > "Amen"

Globalize( "en-GB" ).formatMessage( "amen" );
// > "Amen"

Globalize( "fr" ).formatMessage( "amen" );
// > "Amen"

Globalize( "pt-PT" ).formatMessage( "amen" );
// > "Amém"
</code>```

Body:
Short answer

It's missing Globalize.loadMessages({fr: {}});. The empty message tells globalize fr is a valid bundle.

Longer answer

The documentation example works just fine. Note: Use v1.2.3 documentation here: https://github.com/globalizejs/globalize/blob/1.2.3/doc/api/message/load-messages.md

In order to test I did:

npm install globalize cldr-data

Then:

var Globalize = require( "globalize" );
Globalize.load( require( "cldr-data" ).entireSupplemental() );

Globalize.loadMessages({
  root: {
    amen: "Amen"
  },
  de: {},
  en: {},
  "en-GB": {},
  fr: {},
  pt: {
    amen: "Amém"
  },
  "pt-PT": {}
});

Globalize( "de" ).formatMessage( "amen" );
// > "Amen"

Globalize( "en" ).formatMessage( "amen" );
// > "Amen"

Globalize( "en-GB" ).formatMessage( "amen" );
// > "Amen"

Globalize( "fr" ).formatMessage( "amen" );
// > "Amen"

Globalize( "pt-PT" ).formatMessage( "amen" );
// > "Amém"


问:
Android Blank screen on PDF
In My App, I have given all permissions like storage, contact etc to app (Given run time permission for marshmallow and above version), but still app shows black screen for some mobile phone.

Permission Denial: opening provider

android.support.v4.content.FileProvider from ProcessRecord{bd58bf1
  15489:com.google.android.apps.pdfviewer/u0a213} (pid=15489, uid=10213)

That is not exported from uid 10227.

//Code

```<code>    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider",
pdfFile);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        List<ResolveInfo> resolvedIntentActivities = context.getPackageManager().queryIntentActivities(objIntent,
PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
            String packageName = resolvedIntentInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        objIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        objIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        objIntent.setDataAndType(photoURI, "application/pdf");
        context.startActivity(objIntent);
    }else{
        Uri path = Uri.fromFile(pdfFile);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        objIntent.setDataAndType(path, "application/pdf");
        objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(objIntent);
    }`
</code>```

[Screen]

答:
Hi actually there might be some issue with accessing the FILE URI as it doesnt have the write read uri permission while raising the intent.

check the following thread.. Android - file provider - permission denial
hope you will get some idea.

Also post the code here to understand more.

Title: Android Blank screen on PDF

Body:
In My App, I have given all permissions like storage, contact etc to app (Given run time permission for marshmallow and above version), but still app shows black screen for some mobile phone.

Permission Denial: opening provider

android.support.v4.content.FileProvider from ProcessRecord{bd58bf1
  15489:com.google.android.apps.pdfviewer/u0a213} (pid=15489, uid=10213)

That is not exported from uid 10227.

//Code

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider",
pdfFile);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        List<ResolveInfo> resolvedIntentActivities = context.getPackageManager().queryIntentActivities(objIntent,
PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
            String packageName = resolvedIntentInfo.activityInfo.packageName;
            context.grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        objIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        objIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        objIntent.setDataAndType(photoURI, "application/pdf");
        context.startActivity(objIntent);
    }else{
        Uri path = Uri.fromFile(pdfFile);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        objIntent.setDataAndType(path, "application/pdf");
        objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(objIntent);
    }`

[Screen]


问:
What are the AVFoundation AVCaptureDevice settings for the camera app on iphone?
I was wondering what the AVCaptureDevice settings are for the camera app on iPhone. Specifically the AVCaptureExposureMode, AVCaptureFocusMode, and AVCaptureWhiteBalanceMode. I am trying to make a custom camera and for some reason I can't get the lighting of the photo to change correctly on focusing. I set the ExposurePointOfInterest and the FocusPointOfInterest for my camera, but for some reason it seems as though the camera focuses correctly but the lighting doesn't focus where I tap. When I tap on a dark area it doesn't lighten up like in the camera app. Is there some setting that I'm forgetting to set? Here is my code for focusing the camera.</p>

```<code>CGPoint touchPoint = [gesture locationInView:collectView];
float focus_x = touchPoint.x / collectView.frame.size.width;
float focus_y = touchPoint.y / collectView.frame.size.height;
NSError *tError = nil;
NSLog(@"previous: %.2f, %.2f", backCamera.focusPointOfInterest.x, backCamera.focusPointOfInterest.y);
if (isFrontCamera) {
    focus_x = collectView.frame.size.width - focus_x; //the view is mirrored for the front camera
    if ([frontCamera lockForConfiguration:&tError]) {
        if ([frontCamera isExposurePointOfInterestSupported]) {
            [frontCamera setExposurePointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([frontCamera isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
                [frontCamera setExposureMode:AVCaptureExposureModeAutoExpose];
            }
        }
        if ([frontCamera isFocusPointOfInterestSupported]) {
            [frontCamera setFocusPointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([frontCamera isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
                [frontCamera setExposureMode:AVCaptureExposureModeAutoExpose];
            }
        }
        if ([frontCamera isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [frontCamera setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [frontCamera unlockForConfiguration];
    }
    else {
        NSLog(@"Couldn't change focus point:%@",tError);
    }
}
else {
    if ([backCamera lockForConfiguration:&tError]) {
        if ([backCamera isExposurePointOfInterestSupported]) {
            [backCamera setExposurePointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([backCamera isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
                [backCamera setExposureMode:AVCaptureExposureModeAutoExpose];
            }
        }
        if ([backCamera isFocusPointOfInterestSupported]) {
            [backCamera setFocusPointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([backCamera isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
                [backCamera setFocusMode:AVCaptureFocusModeAutoFocus];
            }
        }
        if ([backCamera isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [backCamera setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [backCamera unlockForConfiguration];
    }
    else {
        NSLog(@"Couldn't change focus point:%@",tError);
    }
}
</code>```

答:
This document has many things in it and will partially answer your question.

Hope this helps a bit as we can not tell every properties' value for the Camera app.

Body:
I was wondering what the AVCaptureDevice settings are for the camera app on iPhone. Specifically the AVCaptureExposureMode, AVCaptureFocusMode, and AVCaptureWhiteBalanceMode. I am trying to make a custom camera and for some reason I can't get the lighting of the photo to change correctly on focusing. I set the ExposurePointOfInterest and the FocusPointOfInterest for my camera, but for some reason it seems as though the camera focuses correctly but the lighting doesn't focus where I tap. When I tap on a dark area it doesn't lighten up like in the camera app. Is there some setting that I'm forgetting to set? Here is my code for focusing the camera.

CGPoint touchPoint = [gesture locationInView:collectView];
float focus_x = touchPoint.x / collectView.frame.size.width;
float focus_y = touchPoint.y / collectView.frame.size.height;
NSError *tError = nil;
NSLog(@"previous: %.2f, %.2f", backCamera.focusPointOfInterest.x, backCamera.focusPointOfInterest.y);
if (isFrontCamera) {
    focus_x = collectView.frame.size.width - focus_x; //the view is mirrored for the front camera
    if ([frontCamera lockForConfiguration:&tError]) {
        if ([frontCamera isExposurePointOfInterestSupported]) {
            [frontCamera setExposurePointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([frontCamera isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
                [frontCamera setExposureMode:AVCaptureExposureModeAutoExpose];
            }
        }
        if ([frontCamera isFocusPointOfInterestSupported]) {
            [frontCamera setFocusPointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([frontCamera isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
                [frontCamera setExposureMode:AVCaptureExposureModeAutoExpose];
            }
        }
        if ([frontCamera isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [frontCamera setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [frontCamera unlockForConfiguration];
    }
    else {
        NSLog(@"Couldn't change focus point:%@",tError);
    }
}
else {
    if ([backCamera lockForConfiguration:&tError]) {
        if ([backCamera isExposurePointOfInterestSupported]) {
            [backCamera setExposurePointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([backCamera isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
                [backCamera setExposureMode:AVCaptureExposureModeAutoExpose];
            }
        }
        if ([backCamera isFocusPointOfInterestSupported]) {
            [backCamera setFocusPointOfInterest:CGPointMake(focus_x, focus_y)];
            if ([backCamera isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
                [backCamera setFocusMode:AVCaptureFocusModeAutoFocus];
            }
        }
        if ([backCamera isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [backCamera setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [backCamera unlockForConfiguration];
    }
    else {
        NSLog(@"Couldn't change focus point:%@",tError);
    }
}


问:
How to use resources file in Asp.net MVC layout
I implemented a multi-language website by using resources files in Asp.net MVC.
All works fine, but my problem is in the layout. How I can use dynamic resources in my layout using view-bag?

I need to write something like this somewhere in my layout but I dont know what is the correct way to do this:

```<code>@{ var langu = ViewBag.lang;}
@Resources.langu.App_Name;
</code>```

it has Error of course.

here is my layout page if needed:

```<code><!DOCTYPE html>
<html>
<head>
    .....
</head>

<body>
    <div class="preloader">
        <div class="spinner">
            <div class="double-bounce1"></div>
            <div class="double-bounce2"></div>
        </div>
    </div>

    <!-- Header
    ============================================ -->
    <div class="header">

        <div class="container  relativesaz">
            <div class="row">
                <div class="col-sm-12">
                    <!-- Navbar Header -->
                    <div class="navbar-header">
                        <!-- Menu Toggle -->
                        <button class="menu-toggle"><i class="fa fa-navicon"></i></button>
                        <!-- Logo -->
                        <a class="iconvrf logo navbar-brand relativesaz" href="" target="_blank">

                            <img src="" alt="" />
                            <span class="fontsmall">

                            </span>
                        </a>
                    </div>
                    <!-- Menu -->
                    <div class="menu">
                        <nav>
                            <ul>
                                <li class="active"><a href="#hero-area">Home</a></li>
                                <li><a href="#about-area">About</a></li>
                                <li><a href="#feature-area">Feature</a></li>
                                <li><a href="#pricing-area">Description</a></li>
                                <li><a href="#screenshot-area">Screenshot</a></li>
                                <li><a href="#team-area">AW </a></li>
                                <li>
                                    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
                                        @ViewBag.ActiveMenu

                                        <span class="caret"></span>
                                    </button>
                                        <ul class="dropdown-menu">
                                            <li>
                                                <ul>
                                                    <li><a class="colorblack" href="@Url.Action("ru", "Home")">Russian</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("cn", "Home")">Chinese</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("jp", "Home")">Japanese</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("nl", "Home")">Dutch</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("dk", "Home")">Danish</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("de", "Home")">German</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("fr", "Home")">French</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("en", "Home")">English </a></li>
                                                </ul>
                                            </li>
                                            <li>
                                                <ul>
                                                    <li><a class="colorblack" href="@Url.Action("tr", "Home")">Turkish</a></li>

                                                    <li><a class="colorblack" href="@Url.Action("th", "Home")">Tahi</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("sv", "Home")">Swedish</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("pt", "Home")">Portuguese</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("no", "Home")">Norwegian</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("kr", "Home")">Korean</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("es", "Home")">Spanish</a></li>
                                                    <li><a class="colorblack" href="@Url.Action("it", "Home")">Italian </a></li>
                                                </ul>
                                            </li>
                                        </ul>
                                </li>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @RenderBody()
    <script src="~/Scripts/plugins.js"></script>
    <script src="~/Scripts/main.js"></script>
</body>
</html>
</code>```

答:
You can directly use resx without viewbag like this:

Solution

A layout and two resx.

_Layout.cshtml

```<code><header>
  <div class="content-wrapper">
    <div class="float-left">
      <p class="site-title">
        @if (System.Globalization.CultureInfo.CurrentCulture.ToString() == "fa-IR")
            {
                <a href="~/Home/">@Resource_fa_IR.App_Name</a>
            }
            else
            {
                <a href="~/Home/">@Resource.App_Name</a>
            }
      </p>
    </div>
  </div>
</header>
</code>```

Resource.Designer.cs and Resource.fa.IR.Designer.cs

```<code>public static string App_Name {
            get {
                return ResourceManager.GetString("App_Name", resourceCulture);
            }
        }
</code>```

You should change internal to public in there classes.

Body:
I implemented a multi-language website by using resources files in Asp.net MVC.
All works fine, but my problem is in the layout. How I can use dynamic resources in my layout using view-bag?

I need to write something like this somewhere in my layout but I dont know what is the correct way to do this:

@{ var langu = ViewBag.lang;}
@Resources.langu.App_Name;

it has Error of course.

here is my layout page if needed:

<!DOCTYPE html>

    .....

                        <button class="menu-toggle"></button>

Home

About

Feature

Description

Screenshot

AW

                                    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
                                        @ViewBag.ActiveMenu

                                    </button>

Russian

Chinese

Japanese

Dutch

Danish

German

French

English

Turkish

Tahi

Swedish

Portuguese

Norwegian

Korean

Spanish

Italian

    @RenderBody()

Body:
You can directly use resx without viewbag like this:

Solution

A layout and two resx.

_Layout.cshtml

<header>
  <div class="content-wrapper">
    <div class="float-left">
      <p class="site-title">
        @if (System.Globalization.CultureInfo.CurrentCulture.ToString() == "fa-IR")
            {
                <a href="~/Home/">@Resource_fa_IR.App_Name</a>
            }
            else
            {
                <a href="~/Home/">@Resource.App_Name</a>
            }
      </p>
    </div>
  </div>
</header>

Resource.Designer.cs and Resource.fa.IR.Designer.cs

public static string App_Name {
            get {
                return ResourceManager.GetString("App_Name", resourceCulture);
            }
        }

You should change internal to public in there classes.


问:
Delphi 2007 DBX Access Violation in dbxmys30.dll
I'm trying to use the dbexpress components in Delphi 2007 to connect to a MySQL database but getting an error the reads "Access violation at address 0B86E258 in module 'dbxmys30.dll'. Read of address 00000000".

I have a TSQLConnection using the MySQL drivers and setup to connect to a MySQL 5.1 database. I can set it to active without a problem.

The problem arises when I try to get data from the database using any number of components. To be more specific, I have a TSQLTable object. I set the SQLConnection parameter to the TSQLConnection I created and set table name to a table in my database. When I try to set Active to true I get the error. This happens in design mode as well as at runtime. It will also happen with any other dbx component that try to get data from the database.

I'm running Windows 7 64 bit with a MySQL 5.1 client and server. I can run queries on the database using MySQL Query Browser without any issues.

Any Help would be much appreciated. Thanks!

答: Access Violation ... read of address 00000000 means that something is trying to dereference a nil pointer.  Do you have the source to dbxmys30.dll?  If so, this will be very easy to debug.  If not, there's not much you can do except file a bug report (who created dbxmys30.dll, BTW?) and hope it gets fixed quickly.


问:
No output in second RenderTarget when blend state is set
I have a strange issue when using two RenderTargets in SharpDX, using DX11.
I am rendering a set of objects that can be layered, and am using blend modes to achieve partial transparency. Rendering is done to two render targets in a single pass, with the second render target being used as a colour picker - I simply render the object ID (integer) to this second target and retrieve the object ID from the texture under the mouse after rendering.

The issue I am getting is frustrating, as it does not happen on all computers. In fact, it doesn't happen on any of our development machines but has been reported in the wild - typically on machines with integrated Intel (HD) graphics. On these computers, no output is generated in the second render target. We have been able to reproduce the problem on a laptop here, and if we don't set the blend state, then the issue is resolved. Obviously this isn't a fix, since we need the blending.

The texture descriptions for the main render target (0) and the colour picking target look like this:

```<code>var desc = new Texture2DDescription
        {
            BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
            Format = Format.B8G8R8A8_UNorm,
            Width = width,
            Height = height,
            MipLevels = 1,
            SampleDescription = sampleDesc,
            Usage = ResourceUsage.Default,
            OptionFlags = RenderTargetOptionFlags,
            CpuAccessFlags = CpuAccessFlags.None,
            ArraySize = 1
        };

var colourPickerDesc = new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget,
                Format = Format.R32_SInt,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1,
            };
</code>```

The blend state is set like this:

```<code>var blendStateDescription = new BlendStateDescription { AlphaToCoverageEnable = false };

        blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
        blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
        blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
        blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
        blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha;
        blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
        blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
        blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

        _blendState = new BlendState(_device, blendStateDescription);
</code>```

and is applied at the start of rendering. I have tried explicitly setting IsBlendEnabled to false for RenderTarget[1] but it makes no difference.

Any help on this would be most welcome - ultimately, we may have to resort to making two render passes but that would be annoying.

答: I have now resolved this issue, although exactly how or why the "fix" works in not entirely clear. Hat-tip to VTT for pointing me to the IndependentBlendEnable flag in the BlendStateDescription. Setting that flag on its own (to true), along with RenderTarget[1].IsBlendEnabled = false, was not enough. What worked in the end was filling a complete set of values for RenderTarget[1], along with the aforementioned flags. Presumably all other values in the second RenderTarget would be ignored, as blend is disabled, but for some reason they need to be populated. As mentioned before, this problem only appears on certain graphics cards so I have no idea if this is the correct behaviour or just a quirk of those cards.

Body:
I have a strange issue when using two RenderTargets in SharpDX, using DX11.
I am rendering a set of objects that can be layered, and am using blend modes to achieve partial transparency. Rendering is done to two render targets in a single pass, with the second render target being used as a colour picker - I simply render the object ID (integer) to this second target and retrieve the object ID from the texture under the mouse after rendering.

The issue I am getting is frustrating, as it does not happen on all computers. In fact, it doesn't happen on any of our development machines but has been reported in the wild - typically on machines with integrated Intel (HD) graphics. On these computers, no output is generated in the second render target. We have been able to reproduce the problem on a laptop here, and if we don't set the blend state, then the issue is resolved. Obviously this isn't a fix, since we need the blending.

The texture descriptions for the main render target (0) and the colour picking target look like this:

var desc = new Texture2DDescription
        {
            BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
            Format = Format.B8G8R8A8_UNorm,
            Width = width,
            Height = height,
            MipLevels = 1,
            SampleDescription = sampleDesc,
            Usage = ResourceUsage.Default,
            OptionFlags = RenderTargetOptionFlags,
            CpuAccessFlags = CpuAccessFlags.None,
            ArraySize = 1
        };

var colourPickerDesc = new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget,
                Format = Format.R32_SInt,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.None,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1,
            };

The blend state is set like this:

var blendStateDescription = new BlendStateDescription { AlphaToCoverageEnable = false };

        blendStateDescription.RenderTarget[0].IsBlendEnabled = true;
        blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
        blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
        blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add;
        blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.SourceAlpha;
        blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha;
        blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
        blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

        _blendState = new BlendState(_device, blendStateDescription);

and is applied at the start of rendering. I have tried explicitly setting IsBlendEnabled to false for RenderTarget[1] but it makes no difference.

Any help on this would be most welcome - ultimately, we may have to resort to making two render passes but that would be annoying.


问:
Why is my output Undefined or NaN?
For some reason, when I enter value, all of the output is
undefined and NaN and I have no idea why.I think the
error is really simple..so simple I would facepalm. Sorry
for my code, I'm still new to javascript. And also, nevermind about the Credit Card.

```<code>function processAmount(){
    var numOfLiters= parseInt(document.estore.noOfLiters.value);
    var result;
    var perLiterAmount;
    var gasType;

    switch(gasType){
    case "Premium":

            perLiterAmount= 50;
            result= 50*numOfLiters;
            break;
    case "Diesel":
           perLiterAmount= 38;
          result= 38*numOfLiters;
            break;

    case "Unleaded":
           perLiterAmount= 44;
            result= 44*numOfLiters;
            break;
    }

    var vat= result*0.12;

    document.write("<p>Fuel Type: " + gasType + "</p>");
    document.write("<p>Price per Liter amount: " + perLiterAmount + "</p>");
    document.write("<p>Purchase Amount: " + result + "</p>");
    document.write("<p>VAT: " + vat + "</p>");
    document.write("<p>TOTAL AMOUNT: " + (result+vat) + "</p>");
    document.write("<p>Credit Card : " + creditCard + "</p>");`
</code>```

and here is the form:

```<code> <form name='estore' id='estore'>
   <fieldset>
            <legend>Gasoline eStore</legend>
                <p>Enter gasoline type:
                    <select name='gastype' id='gastype'>
                        <option value="Premium"> Premium</option>
                        <option value="Unleaded"> Unleaded</option>
                        <option value="Diesel"> Diesel</option>
                        </select></p>

                <p> Enter number of Liters:
                    <input type='number' name='noOfLiters' id='noOfLiters'/>
                </p>

                <p> Enter Credit Card Number:
                    <input type="number" name='creditCardNumber' id='creditCardNumber'/>
                </p>

                <p>
                    <input type='button' value='Submit'
                        onclick="processAmount()"/>
                    <input type='reset'/>
                </p>
</code>```

答:
You could replace

```<code>var gasType;
</code>```

with

```<code>var gasType = document.getElementById('gastype').value;
</code>```

That way your method processAmount() should work as intended.
As some other replies here already suggested, you didn't initialize your variable  gasType, so it was undefined.

Using the line above, you initialize it with the value from the select field.

Title: Why is my output Undefined or NaN?

Body:
For some reason, when I enter value, all of the output is
undefined and NaN and I have no idea why.I think the
error is really simple..so simple I would facepalm. Sorry
for my code, I'm still new to javascript. And also, nevermind about the Credit Card.

function processAmount(){
    var numOfLiters= parseInt(document.estore.noOfLiters.value);
    var result;
    var perLiterAmount;
    var gasType;

    switch(gasType){
    case "Premium":

            perLiterAmount= 50;
            result= 50*numOfLiters;
            break;
    case "Diesel":
           perLiterAmount= 38;
          result= 38*numOfLiters;
            break;

    case "Unleaded":
           perLiterAmount= 44;
            result= 44*numOfLiters;
            break;
    }

    var vat= result*0.12;

    document.write("
Fuel Type: " + gasType + "
");
    document.write("
Price per Liter amount: " + perLiterAmount + "
");
    document.write("
Purchase Amount: " + result + "
");
    document.write("
VAT: " + vat + "
");
    document.write("
TOTAL AMOUNT: " + (result+vat) + "
");
    document.write("
Credit Card : " + creditCard + "
");`

and here is the form:

 <form name='estore' id='estore'>
   <fieldset>
            <legend>Gasoline eStore</legend>

Enter gasoline type:
                    <select name='gastype' id='gastype'>
                        <option value="Premium"> Premium</option>
                        <option value="Unleaded"> Unleaded</option>
                        <option value="Diesel"> Diesel</option>
                        </select>

 Enter number of Liters:
                    <input type='number' name='noOfLiters' id='noOfLiters'/>

 Enter Credit Card Number:
                    <input type="number" name='creditCardNumber' id='creditCardNumber'/>

                    <input type='button' value='Submit'
                        onclick="processAmount()"/>
                    <input type='reset'/>

Body:
You could replace

var gasType;

with

var gasType = document.getElementById('gastype').value;

That way your method processAmount() should work as intended.
As some other replies here already suggested, you didn't initialize your variable  gasType, so it was undefined.

Using the line above, you initialize it with the value from the select field.


问:
Different Prometheus scrape URL for every target
Every instance of my application has a different URL.
How can I configure prometheus.yml so that it takes path of a target along with the host name?</p>

```<code>scrape_configs:
- job_name:       'example-random'

# Override the global default and scrape targets from this job every 5 seconds.
scrape_interval: 5s

static_configs:
  - targets: ['localhost:8090','localhost:8080']
    labels:
      group: 'dummy'
</code>```

答:
You currently can't configure the metrics_path per target within a job but you can create separate jobs for each of your targets so you can define metrics_path per target.

Your config file would look something like this:

```<code>scrape_configs:
- job_name:       'example-target-1'
  scrape_interval: 5s
  metrics_path: /target-1-path-to-metrics
  static_configs:
    - targets: ['localhost:8090']
      labels:
        group: 'dummy'

- job_name:       'example-target-2'
  scrape_interval: 5s
  metrics_path: /totally-different-path-for-target-2
  static_configs:
    - targets: ['localhost:8080']
      labels:
        group: 'dummy-2'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Every instance of my application has a different URL.
How can I configure prometheus.yml so that it takes path of a target along with the host name?

scrape_configs:
- job_name:       'example-random'

# Override the global default and scrape targets from this job every 5 seconds.
scrape_interval: 5s

static_configs:
  - targets: ['localhost:8090','localhost:8080']
    labels:
      group: 'dummy'

Body:
You currently can't configure the metrics_path per target within a job but you can create separate jobs for each of your targets so you can define metrics_path per target.

Your config file would look something like this:

scrape_configs:
- job_name:       'example-target-1'
  scrape_interval: 5s
  metrics_path: /target-1-path-to-metrics
  static_configs:
    - targets: ['localhost:8090']
      labels:
        group: 'dummy'

- job_name:       'example-target-2'
  scrape_interval: 5s
  metrics_path: /totally-different-path-for-target-2
  static_configs:
    - targets: ['localhost:8080']
      labels:
        group: 'dummy-2'


问:
MySQL index for only maximum and minimum values
I have a huge table with millions of rows which stores the values obtained from some weather stations. Every row contains the station that gathered the value, the metric (for example, temperature, humidity, noise level, etc.), the date and the value itself.

This is its structure:

station: int(8)

metric: int(8)

date: datetime

value: float

And these are the indices I've defined:

PRIMARY KEY: station+metric+date

KEY: metrica (for the foreign key)

Sometimes, I'm interested in retrieving the last time every station has sent some value. Then I use this query:

```<code> SELECT station, MAX(date)
 FROM MyTable
 GROUP BY station
</code>```

This query is very slow, as it has to read the entire table. If I add an index for station+date, the query now can use it and it becomes very fast. But the table storage also increases a lot, and for me indexing all date values is not useful, given I'm only interested on the max value.

So my question is if it's possible to create an index that indexes some range, ideally to only keep track of the maximum value.

答:
Not that I know. But you have alternative solutions.

In other databases I'd suggest a materialized view, but MySQL does not support materialized views (SO#3991912) so you have to create and manage your own aggregate table your self.

If your source table is not updated too frequently a CREATE TABLE last_observation AS SELECT station, MAX(date) AS date FROM observations GROUP BY station will do the work. Simply issue the statement before any relevant request.

If your server has enough resources, you can leave the table in MEMORY, to get superfast responses. In that case you need to name explicitly the columns CREATE TABLE last_observation (station VARCHAR(x), lastDate DATE) ENGINE=MEMORY AS SELECT station, MAX(date) AS lastDate FROM observations GROUP BY station. Of course this statement should issued routinely each time you open mysql.

If your table is updated frequently, you can manage the content with triggers on the source table (Full tutorial here).

An other solution, on a totally different path, is to use a column oriented database. We used Infobright a few years ago, which has an free community edition, and is totally transparent for you (just install it and use mysql as before).

Body:
I have a huge table with millions of rows which stores the values obtained from some weather stations. Every row contains the station that gathered the value, the metric (for example, temperature, humidity, noise level, etc.), the date and the value itself.

This is its structure:

station: int(8)

metric: int(8)

date: datetime

value: float

And these are the indices I've defined:

PRIMARY KEY: station+metric+date

KEY: metrica (for the foreign key)

Sometimes, I'm interested in retrieving the last time every station has sent some value. Then I use this query:

 SELECT station, MAX(date)
 FROM MyTable
 GROUP BY station

This query is very slow, as it has to read the entire table. If I add an index for station+date, the query now can use it and it becomes very fast. But the table storage also increases a lot, and for me indexing all date values is not useful, given I'm only interested on the max value.

So my question is if it's possible to create an index that indexes some range, ideally to only keep track of the maximum value.


问:
Instapaper-like algorithm
Does anyone of an algorithm that extracts contents from a webpage? like instapaper?</p>

答:
there is an open source application that parses the text of an article out from any webpage

https://github.com/jiminoc/goose/wiki

should do the trick

Title: Instapaper-like algorithm


问:
JS - How to add a button into a div with appendChid
I want to create a sidebar using only JavaScript, but I can't add the close button to the div.
I tried this:

```<code>var sideb = document.createElement("Div");
    sideb.style.height = "100%";
    sideb.style.width = "0px";
    sideb.style.backgroundColor = "rgb(30,30,30)";
    sideb.style.top = "0px";
    sideb.style.right = "0px";
    sideb.style.margin = "0px";
    sideb.style.padding = "0px";
    sideb.style.position = "fixed"

    document.body.appendChild(sideb);

var close = document.createElement("Button");
    close.innerText = "close";
    close.onclick = close;

    document.body.sideb.appendChild(close)
</code>```

But it's not working.

答:
You have a couple of bugs in your code.  Did you make a function called close?  I ask this because you're assigning close to the onclick handler of the button, but after you defined close to be the button element in the local scope.  If not, you have to write a function to actually "close" the div.  Also, as another person pointed out, sideb is not a property of document.body.  You can just call sideb's appendChild method to add the button.

```<code>var sideb = document.createElement("Div");
sideb.style.height = "100%";
sideb.style.width = "0px";
sideb.style.backgroundColor = "rgb(30,30,30)";
sideb.style.top = "0px";
sideb.style.right = "0px";
sideb.style.margin = "0px";
sideb.style.padding = "0px";
sideb.style.position = "fixed";

document.body.appendChild(sideb);

var close = document.createElement("Button");
close.innerText = "close";
close.onclick = function() {
    sideB.parentNode.removeChild(sideB);
};

sideb.appendChild(close);
</code>```

Also, if you want to remove some code duplication, you can use Object.assign to remove all the extra references to sideb.style.

```<code>Object.assign(sideb.style, {
    height: "100%",
    width: "0px",
    backgroundColor: "rgb(30,30,30)",
    top: "0px",
    right: "0px",
    margin: "0px",
    padding: "0px",
    position: "fixed"
});
</code>```

Body:
I want to create a sidebar using only JavaScript, but I can't add the close button to the div.
I tried this:

var sideb = document.createElement("Div");
    sideb.style.height = "100%";
    sideb.style.width = "0px";
    sideb.style.backgroundColor = "rgb(30,30,30)";
    sideb.style.top = "0px";
    sideb.style.right = "0px";
    sideb.style.margin = "0px";
    sideb.style.padding = "0px";
    sideb.style.position = "fixed"

    document.body.appendChild(sideb);

var close = document.createElement("Button");
    close.innerText = "close";
    close.onclick = close;

    document.body.sideb.appendChild(close)

But it's not working.

Body:
You have a couple of bugs in your code.  Did you make a function called close?  I ask this because you're assigning close to the onclick handler of the button, but after you defined close to be the button element in the local scope.  If not, you have to write a function to actually "close" the div.  Also, as another person pointed out, sideb is not a property of document.body.  You can just call sideb's appendChild method to add the button.

var sideb = document.createElement("Div");
sideb.style.height = "100%";
sideb.style.width = "0px";
sideb.style.backgroundColor = "rgb(30,30,30)";
sideb.style.top = "0px";
sideb.style.right = "0px";
sideb.style.margin = "0px";
sideb.style.padding = "0px";
sideb.style.position = "fixed";

document.body.appendChild(sideb);

var close = document.createElement("Button");
close.innerText = "close";
close.onclick = function() {
    sideB.parentNode.removeChild(sideB);
};

sideb.appendChild(close);

Also, if you want to remove some code duplication, you can use Object.assign to remove all the extra references to sideb.style.

Object.assign(sideb.style, {
    height: "100%",
    width: "0px",
    backgroundColor: "rgb(30,30,30)",
    top: "0px",
    right: "0px",
    margin: "0px",
    padding: "0px",
    position: "fixed"
});


问:
How do you update an environment variable using Ruby and Chef?
I know how to set the variables for both user and machine.
The problem arises when I try to add to the PATH. Currently my code will overwrite what is in the PATH.

```<code>execute 'set java_home2' do
command "setx -m PATH2 \"D:\\Home"
*only_if {"PATH2" == " "}*
end
</code>```

This currently ensures that the PATH will only run if there is no PATH. When the only_if is removed the problem of overwriting arises.

EDIT:
I am now able to modify the system variable but cannot work out how to do the same with the user variables

```<code>env 'path addition' do
key_name "PATH"
value (ENV["PATH"] + ";D:\\Home\\Apps\\variable")
:modify
end
</code>```

答:
I found the answer:

```<code>   #Append notepad to user PATH variable
registry_key "HKEY_CURRENT_USER\\Environment" do
  $path_name = ""
  subkey_array = registry_get_values("HKEY_CURRENT_USER\\Environment", :x86_64)
  subkey_array.each{ |val|
    case val[:name].include?("PATH")
    when true
        $path_name = val[:data]
        print "\n The User PATH is: #{$path_name}"
        break
    when false
      print ':'
    end
  }
    values [{
      :name => "PATH",
      :type => :string,
      :data => "#{$path_name};D:\\Home\\Apps\\Notepad++\\Notepad++"
      }]
  action :create
  #add a guard to prevent duplicates
  not_if {
      $path_name.include?("D:\\Home\\Apps\\Notepad++\\Notepad++")
  }
end
</code>```

This code when ran from the CMD line will print the current User PATH variables, then it will append D:/Home/Apps/Notepad++/Notepad++ IF it is not currently in the PATH. If it already exists then this will be skipped.

Body:
I know how to set the variables for both user and machine.
The problem arises when I try to add to the PATH. Currently my code will overwrite what is in the PATH.

execute 'set java_home2' do
command "setx -m PATH2 \"D:\\Home"
*only_if {"PATH2" == " "}*
end

This currently ensures that the PATH will only run if there is no PATH. When the only_if is removed the problem of overwriting arises.

EDIT:
I am now able to modify the system variable but cannot work out how to do the same with the user variables

env 'path addition' do
key_name "PATH"
value (ENV["PATH"] + ";D:\\Home\\Apps\\variable")
:modify
end

Body:
I found the answer:

   #Append notepad to user PATH variable
registry_key "HKEY_CURRENT_USER\\Environment" do
  $path_name = ""
  subkey_array = registry_get_values("HKEY_CURRENT_USER\\Environment", :x86_64)
  subkey_array.each{ |val|
    case val[:name].include?("PATH")
    when true
        $path_name = val[:data]
        print "\n The User PATH is: #{$path_name}"
        break
    when false
      print ':'
    end
  }
    values [{
      :name => "PATH",
      :type => :string,
      :data => "#{$path_name};D:\\Home\\Apps\\Notepad++\\Notepad++"
      }]
  action :create
  #add a guard to prevent duplicates
  not_if {
      $path_name.include?("D:\\Home\\Apps\\Notepad++\\Notepad++")
  }
end

This code when ran from the CMD line will print the current User PATH variables, then it will append D:/Home/Apps/Notepad++/Notepad++ IF it is not currently in the PATH. If it already exists then this will be skipped.