问:
references undefined when linking against boost 1.63 static libs
I'm linking against boost statically.  When I do so, I get some undefined reference errors (below).

```<code>[100%] Linking CXX executable infiniteTests
/home/wdog/src/protos/infinite/libinfinite.a(ServiceDiscovery.cpp.o): In function `boost::date_time::month_formatter<boost::gregorian::greg_month, boost::date_time::simple_format<char>, char>::format_month(boost::gregorian::greg_month const&, std::ostream&)':
/home/wdog/src/3rdp/boost_1_63_0/boost/date_time/date_formatting.hpp:44: undefined reference to `boost::gregorian::greg_month::as_short_string() const'
/home/wdog/src/3rdp/boost_1_63_0/boost/date_time/date_formatting.hpp:49: undefined reference to `boost::gregorian::greg_month::as_long_string() const'
collect2: error: ld returned 1 exit status
</code>```

When I link dynamically, the references are presumably present, and the build links successfully.

I need to be able to build this statically; requirement of the project.

I'm building with cmake.  My link directories are ordered thus:

```<code>link_directories(
    $ENV{PROJECT_LIB_DIR}
    $ENV{BOOST_LIBRARY_DIR}
    $ENV{HIREDIS_LIB_DIR}
    $ENV{LIBEVENT_LIB_DIR}
    $ENV{PROJECT_ROOT}
    /usr/lib
    /usr/local/lib
)
</code>```

My target link libaries are defined as:

```<code>target_link_libraries(
    ${sThisProject}
    ${Boost_LIBRARIES}
    libhiredis.a
    libevent.a
    libevent_core.a
    libevent_pthreads.a
    libssl.so
    libcrypto.so
    libpthread.so.0
)
</code>```

Here's the CMakeLists.txt entry where I find boost:

```<code>find_package( Boost 1.63 EXACT REQUIRED COMPONENTS system chrono date_time filesystem program_options regex thread REQUIRED )
</code>```

I also set the following:

```<code>SET (Boost_NO_SYSTEM_PATHS ON)
SET (Boost_USE_STATIC_LIBS ON)
SET (Boost_USE_MULTITHREADED ON)
SET (Boost_USE_STATIC_RUNTIME ON)
</code>```

I've checked that my build of 1.63 has successfully built the appropriate static lib - libboost_date_time.a - and it's present in ${BOOST}/stage/lib/

It's my understanding that this can happen if the linker finds a boost static lib on the system install before the correct path.

Cmake appears to find the correct path for boost 1_63:

(output during build:)

```<code>-- Boost version: 1.63.0
-- Found the following Boost libraries:
--   system
--   chrono
--   date_time
--   filesystem
--   program_options
--   regex
--   thread
</code>```

I run fedora 25, so my system installed version of boost was 1_60, so to avoid the above problem, I uninstalled it completely:

```<code>sudo dnf remove boost boost-atomic boost-chrono boost-container boost-context boost-coroutine boost-date-time boost-devel boost-filesystem boost-graph boost-iostreams boost-locale boost-log boost-math boost-program-options boost-python boost-random boost-regex boost-serialization boost-signals boost-system boost-test boost-thread boost-timer boost-type_erasure boost-wave
</code>```

I built but do not install 1.63 in a 3rd party directory in my source tree.  It's built with the following commands:

```<code>./bootstrap.sh
./b2 -j8
</code>```

I set linker output with:

```<code>SET (CMAKE_EXE_LINKER_FLAGS -v)
</code>```

And determined via the following output that I'm linking against the correct static libary:

```<code>-o
...
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_system.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_chrono.a
**/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_date_time.a**
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_filesystem.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_program_options.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_regex.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_thread.a
...
</code>```

I've run out of ideas; is there something else I should check?

答: That libinfinite.a needs to precede the boost libraries in the command line.

Body:
I'm linking against boost statically.  When I do so, I get some undefined reference errors (below).

[100%] Linking CXX executable infiniteTests
/home/wdog/src/protos/infinite/libinfinite.a(ServiceDiscovery.cpp.o): In function `boost::date_time::month_formatter<boost::gregorian::greg_month, boost::date_time::simple_format<char>, char>::format_month(boost::gregorian::greg_month const&, std::ostream&)':
/home/wdog/src/3rdp/boost_1_63_0/boost/date_time/date_formatting.hpp:44: undefined reference to `boost::gregorian::greg_month::as_short_string() const'
/home/wdog/src/3rdp/boost_1_63_0/boost/date_time/date_formatting.hpp:49: undefined reference to `boost::gregorian::greg_month::as_long_string() const'
collect2: error: ld returned 1 exit status

When I link dynamically, the references are presumably present, and the build links successfully.

I need to be able to build this statically; requirement of the project.

I'm building with cmake.  My link directories are ordered thus:

link_directories(
    $ENV{PROJECT_LIB_DIR}
    $ENV{BOOST_LIBRARY_DIR}
    $ENV{HIREDIS_LIB_DIR}
    $ENV{LIBEVENT_LIB_DIR}
    $ENV{PROJECT_ROOT}
    /usr/lib
    /usr/local/lib
)

My target link libaries are defined as:

target_link_libraries(
    ${sThisProject}
    ${Boost_LIBRARIES}
    libhiredis.a
    libevent.a
    libevent_core.a
    libevent_pthreads.a
    libssl.so
    libcrypto.so
    libpthread.so.0
)

Here's the CMakeLists.txt entry where I find boost:

find_package( Boost 1.63 EXACT REQUIRED COMPONENTS system chrono date_time filesystem program_options regex thread REQUIRED )

I also set the following:

SET (Boost_NO_SYSTEM_PATHS ON)
SET (Boost_USE_STATIC_LIBS ON)
SET (Boost_USE_MULTITHREADED ON)
SET (Boost_USE_STATIC_RUNTIME ON)

I've checked that my build of 1.63 has successfully built the appropriate static lib - libboost_date_time.a - and it's present in ${BOOST}/stage/lib/

It's my understanding that this can happen if the linker finds a boost static lib on the system install before the correct path.

Cmake appears to find the correct path for boost 1_63:

(output during build:)

-- Boost version: 1.63.0
-- Found the following Boost libraries:
--   system
--   chrono
--   date_time
--   filesystem
--   program_options
--   regex
--   thread

I run fedora 25, so my system installed version of boost was 1_60, so to avoid the above problem, I uninstalled it completely:

sudo dnf remove boost boost-atomic boost-chrono boost-container boost-context boost-coroutine boost-date-time boost-devel boost-filesystem boost-graph boost-iostreams boost-locale boost-log boost-math boost-program-options boost-python boost-random boost-regex boost-serialization boost-signals boost-system boost-test boost-thread boost-timer boost-type_erasure boost-wave

I built but do not install 1.63 in a 3rd party directory in my source tree.  It's built with the following commands:

./bootstrap.sh
./b2 -j8

I set linker output with:

SET (CMAKE_EXE_LINKER_FLAGS -v)

And determined via the following output that I'm linking against the correct static libary:

-o
...
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_system.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_chrono.a
**/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_date_time.a**
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_filesystem.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_program_options.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_regex.a
/home/wdog/src/3rdp/boost_1_63_0/stage/lib/libboost_thread.a
...

I've run out of ideas; is there something else I should check?


来源: stackexchange

问:
How do I move sprites in random directions but with uniform speed python/pygame?
I try to move a set of balls in random movement, but with uniform speed. My code lets the balls move in random directions, but with different speeds. I think it is because the random.uniform function gives different values, some close to 0 which, multiplied with the speed and time, gives lower values than the ones closer to 1. But in the animation the speed doesn't seem to be tied with the direction the balls travel (which should be the case if the values of dx and dy are the cause). I know anout normalization, but I think random.uniform gives the same values as a normalized vector?

My questions are:

Is the random value of dx and dy the culprit of the difference in speed?

What is the way to make all the balls move in the same speed?

My code:

```<code>self.timer = pygame.time.Clock()
self.time_passed = self.timer.tick()
self.speed = 0.5
self.dx = random.uniform(-1, 1)
self.dy = random.uniform(-1, 1)
displacement = Vector2(
                       self.dx * (self.speed * self.time_passed),
                       self.dy * (self.speed * self.time_passed)
                       )

self.pos += displacement #both vector objects
</code>```

Thanks for any help!

答:
Use an angle to derive your x and y.</p>

```<code>self.angle = random.uniform(-1, 1)
self.dy = math.sin(self.angle * math.pi/2)
self.dx = math.cos(self.angle * math.pi/2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I try to move a set of balls in random movement, but with uniform speed. My code lets the balls move in random directions, but with different speeds. I think it is because the random.uniform function gives different values, some close to 0 which, multiplied with the speed and time, gives lower values than the ones closer to 1. But in the animation the speed doesn't seem to be tied with the direction the balls travel (which should be the case if the values of dx and dy are the cause). I know anout normalization, but I think random.uniform gives the same values as a normalized vector?

My questions are:

Is the random value of dx and dy the culprit of the difference in speed?

What is the way to make all the balls move in the same speed?

My code:

self.timer = pygame.time.Clock()
self.time_passed = self.timer.tick()
self.speed = 0.5
self.dx = random.uniform(-1, 1)
self.dy = random.uniform(-1, 1)
displacement = Vector2(
                       self.dx * (self.speed * self.time_passed),
                       self.dy * (self.speed * self.time_passed)
                       )

self.pos += displacement #both vector objects

Thanks for any help!

Body:
Use an angle to derive your x and y.

self.angle = random.uniform(-1, 1)
self.dy = math.sin(self.angle * math.pi/2)
self.dx = math.cos(self.angle * math.pi/2)


问:
Regex to extract first occurance of matching field
I want to extract first occurance of matching field. there are multiple occurrence present in same line.I have created a regex but its capturing the second occurence.

My Regex:Demo
.

Sample Data:

127776.635: [Full GC127776.636: [CMS: 12058623K->11149597K(12058624K), 28.5725635 secs] 12355879K->11149597K(12478080K), [CMS Perm : 75918K->75548K(262144K)], 28.5729197 secs] [Times: user=28.58 sys=0.01, real=28.57 secs]

In above example it should take 12058623K, not 12355879K.

答:
You don't need to match closing ] here just use this regex with lazy quantifier:

```<code>\[Full GC.*?\s(?P<before_full_gc>\d+)K
</code>```

Updated RegEx Demo

Body:
You don't need to match closing ] here just use this regex with lazy quantifier:

\[Full GC.*?\s(?P<before_full_gc>\d+)K

Updated RegEx Demo


问:
Referencing already opened word document in VBA
I am using Excel VBA to open a word Template and it populates the template with information from an excel spreadsheet. From there, I have a button on the spreadsheet that I want to then populate another line in the word document whenever it is clicked. The problem I am encountering is that when I run the button macro it just opens up another word document and pastes the button information instead of doing it on the already opened document. I will attach my code below and I believe it is an easy fix I just can't seem to find a way around it.</p>

```<code>Sub RepairCal()

Dim objWord As Object
Dim objDoc As Object

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Open("C:\Users\z003narc\Documents\Gage Lab Form Template.docm")

objWord.Activate

With Selection

   objWord.ActiveDocument.Selection.MoveDown count:=6
   objWord.ActiveDocument.Selection.MoveRight count:=5
   objWord.ActiveDocument.Selection.TypeText Text:="Repair and Calibration"

End With

End Sub
</code>```

答:
Try this:  </p>

```<code>With objWord

   .Selection.MoveDown count:=6
   .Selection.MoveRight count:=5
   .Selection.TypeText Text:="Repair and Calibration"

End With
</code>```

Body:
I am using Excel VBA to open a word Template and it populates the template with information from an excel spreadsheet. From there, I have a button on the spreadsheet that I want to then populate another line in the word document whenever it is clicked. The problem I am encountering is that when I run the button macro it just opens up another word document and pastes the button information instead of doing it on the already opened document. I will attach my code below and I believe it is an easy fix I just can't seem to find a way around it.

Sub RepairCal()

Dim objWord As Object
Dim objDoc As Object

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    Set objDoc = objWord.Documents.Open("C:\Users\z003narc\Documents\Gage Lab Form Template.docm")

objWord.Activate

With Selection

   objWord.ActiveDocument.Selection.MoveDown count:=6
   objWord.ActiveDocument.Selection.MoveRight count:=5
   objWord.ActiveDocument.Selection.TypeText Text:="Repair and Calibration"

End With

End Sub

Body:
Try this:

With objWord

   .Selection.MoveDown count:=6
   .Selection.MoveRight count:=5
   .Selection.TypeText Text:="Repair and Calibration"

End With


问:
Why do I get the error "the trait `Foo` is not implemented for `&mut T`" even though T implements the trait?
I have this source:

```<code>pub fn draw<G, C>(&self, font: &mut C, draw_state: &DrawState, transform: Matrix2d, g: &mut G)
where
    C: CharacterCache,
    G: Graphics<Texture = <C as CharacterCache>::Texture>,
{
    self.properties.draw(
        self.text.as_str(),
        &mut font,
        &draw_state,
        transform,
        g,
    );
}
</code>```

And the error

the trait bound `&mut C: graphics::character::CharacterCache` is not satisfied
(the trait `graphics::character::CharacterCache` is not implemented for `&mut C`)
```

<p>The only aspect of <code>C</code> that is defined is that it implements <code>CharacterCache</code>, yet the error says the opposite.</p>

<p><code>DrawState</code>, <code>Matrix2d</code>, <code>CharacterCache</code> and its implementations, <code>Texture</code>, and self.properties (<code>Text</code>) are provided by the Piston 2d graphics library. There must be something about traits in general that I'm misunderstanding.</p>

<p>The <code>Text::draw</code> function signature:</p>

```fn draw<C, G>(
    &self,
    text: &str,
    cache: &mut C,
    draw_state: &DrawState,
    transform: Matrix2d,
    g: &mut G,
) where
    C: CharacterCache,
    G: Graphics<Texture = C::Texture>,
```

答:
T, &T, and &mut T are all different types; and that means that &mut &mut T is likewise a different type. Traits are not automatically implemented for references to a type. If you wish to implement a trait for either of the references, you need to write it out explicitly.

As an example, this exhibits the same problem:

```<code>trait Foo {}

#[derive(Debug, Copy, Clone)]
struct S;
impl Foo for S {}

fn example<T>(_: T)
where
    T: Foo,
{}

fn main() {
    let mut s = S;

    example(s);
    example(&s);     // the trait bound `&S: Foo` is not satisfied
    example(&mut s); // the trait bound `&mut S: Foo` is not satisfied
}
</code>```

Explicit implementations of the trait for the references solve the problem:

```<code>impl<'a> Foo for &'a S {}
impl<'a> Foo for &'a mut S {}
</code>```

In many cases, you can delegate the function implementations to the non-reference implementation.

If this should always be true, you can make it so by applying it to all references to a type that implements a trait:

```<code>impl<'a, T> Foo for &'a T where T: Foo {}
impl<'a, T> Foo for &'a mut T where T: Foo {}
</code>```

If you don't have control over the traits, you may need to specify that you take a reference to a generic type that implements the trait:

```<code>fn example<T>(_: &mut T)
where
    for<'a> &'a mut T: Foo,
{}
</code>```

See also:

When should I not implement a trait for references to implementors of that trait?

Body:
I have this source:

pub fn draw<G, C>(&self, font: &mut C, draw_state: &DrawState, transform: Matrix2d, g: &mut G)
where
    C: CharacterCache,
    G: Graphics<Texture = <C as CharacterCache>::Texture>,
{
    self.properties.draw(
        self.text.as_str(),
        &mut font,
        &draw_state,
        transform,
        g,
    );
}

And the error

the trait bound `&mut C: graphics::character::CharacterCache` is not satisfied
(the trait `graphics::character::CharacterCache` is not implemented for `&mut C`)

The only aspect of C that is defined is that it implements CharacterCache, yet the error says the opposite.

DrawState, Matrix2d, CharacterCache and its implementations, Texture, and self.properties (Text) are provided by the Piston 2d graphics library. There must be something about traits in general that I'm misunderstanding.

The Text::draw function signature:

fn draw<C, G>(
    &self,
    text: &str,
    cache: &mut C,
    draw_state: &DrawState,
    transform: Matrix2d,
    g: &mut G,
) where
    C: CharacterCache,
    G: Graphics<Texture = C::Texture>,

Body:
T, &T, and &mut T are all different types; and that means that &mut &mut T is likewise a different type. Traits are not automatically implemented for references to a type. If you wish to implement a trait for either of the references, you need to write it out explicitly.

As an example, this exhibits the same problem:

trait Foo {}

#[derive(Debug, Copy, Clone)]
struct S;
impl Foo for S {}

fn example<T>(_: T)
where
    T: Foo,
{}

fn main() {
    let mut s = S;

    example(s);
    example(&s);     // the trait bound `&S: Foo` is not satisfied
    example(&mut s); // the trait bound `&mut S: Foo` is not satisfied
}

Explicit implementations of the trait for the references solve the problem:

impl<'a> Foo for &'a S {}
impl<'a> Foo for &'a mut S {}

In many cases, you can delegate the function implementations to the non-reference implementation.

If this should always be true, you can make it so by applying it to all references to a type that implements a trait:

impl<'a, T> Foo for &'a T where T: Foo {}
impl<'a, T> Foo for &'a mut T where T: Foo {}

If you don't have control over the traits, you may need to specify that you take a reference to a generic type that implements the trait:

fn example<T>(_: &mut T)
where
    for<'a> &'a mut T: Foo,
{}

See also:

When should I not implement a trait for references to implementors of that trait?


问:
VS C# Button with Mailto function - it needs to open Outlook's new mail window
What I am trying to do:

A user clicks a button on a ASP.net page and it opens a Outlook 'new mail' window.
That's all.

My Problem:

With this -->

```<code>     using Outlook = Outlook = Microsoft.Office.Interop.Outlook;

    OutlookApp outlookApp = new OutlookApp();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

    mailItem.Subject = "Test";
    mailItem.HTMLBody = "<html><body>This is the message body</body></html>";

    mailItem.Display(false);
</code>```

And several other code I've tried, I am getting security errors on my IIS web server - Access is denied. But on localhost Outlook opens fine.

I looked all over, and everyone suggests that NETWORKSERVICE should be the user that has full security rights. Did that. And after reading a bit more, People are suggesting to not try and open Outlook over a web server for several reasons. So I decided to leave Interops.Outlook.

Then I also tried the following, which again works on my localhost, but when published to the web server does not respond when the button is clicked. It literally does nothing.

```<code>    string subject = "Test subject";
    string emailTag = string.Format("mailto:someone@test.com?subject={0}", subject);
    System.Diagnostics.Process.Start(emailTag);
</code>```

Thanks

答: As vendettamit said you can use SenEmail to open Outlook or another default mail application on client side. Here you can find all stuff that ca be used within mailto:

Body:
What I am trying to do:

A user clicks a button on a ASP.net page and it opens a Outlook 'new mail' window.
That's all.

My Problem:

With this -->

     using Outlook = Outlook = Microsoft.Office.Interop.Outlook;

    OutlookApp outlookApp = new OutlookApp();
    MailItem mailItem = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);

    mailItem.Subject = "Test";
    mailItem.HTMLBody = "This is the message body";

    mailItem.Display(false);

And several other code I've tried, I am getting security errors on my IIS web server - Access is denied. But on localhost Outlook opens fine.

I looked all over, and everyone suggests that NETWORKSERVICE should be the user that has full security rights. Did that. And after reading a bit more, People are suggesting to not try and open Outlook over a web server for several reasons. So I decided to leave Interops.Outlook.

Then I also tried the following, which again works on my localhost, but when published to the web server does not respond when the button is clicked. It literally does nothing.

    string subject = "Test subject";
    string emailTag = string.Format("mailto:someone@test.com?subject={0}", subject);
    System.Diagnostics.Process.Start(emailTag);

Thanks


问:
Using int.TryParse with nullable int
How can I use int.TryParse with nullable int?

I am trying to do something like the following, which doesn't compile, obviously.

int? nr1 = int.TryParse(str1, out nr1) ? nr1 : null;

What is the correct way to achieve it?

答:
Because the out has to be int you need something like:

```<code>int temp;
int? nr1 = int.TryParse(str1, out temp) ? temp : default(int?);
</code>```

Note that I also use default(int?) instead of null because the conditional typing won't work otherwise. ? (int?)temp : null or ? temp : (int?)null would also solve that.

As of C#7 (VS Studio 2017) you can inline the declaration of temp

```<code>int? nr1 = int.TryParse(str1, out int temp) ? temp : default(int?);
</code>```

Title: Using int.TryParse with nullable int

Body:
Because the out has to be int you need something like:

int temp;
int? nr1 = int.TryParse(str1, out temp) ? temp : default(int?);

Note that I also use default(int?) instead of null because the conditional typing won't work otherwise. ? (int?)temp : null or ? temp : (int?)null would also solve that.

As of C#7 (VS Studio 2017) you can inline the declaration of temp

int? nr1 = int.TryParse(str1, out int temp) ? temp : default(int?);


问:
grep in IF statement
The following script portion read each line in $next. But when I try to grep particular pattern i.e. "MO" in $next, the error is shown on standard output as:

```<code>grep: 40922|OPR: No such file or directory
grep: MO: No such file or directory
grep: 12345|OPR: No such file or directory
grep: MO: No such file or directory
grep: 12345|12345|202|local|LMNO: No such file or directory

cat /home/scripts/$E1.out | while read next
do
i=`echo $next | awk -F"|" '{print($1)}'`
j=`echo $next | awk -F"|" '{print($2)}'`
k=`echo $next | awk -F"|" '{print($3)}'`
l=`echo $next | awk -F"|" '{print($4)}'`
m=`echo $next | awk -F"|" '{print($5)}'`
n=`echo $next | awk -F"|" '{print($6)}'`
o=`echo $next | awk -F"|" '{print($6)}'`
if grep -q "MO" $next
then echo "FOUND;" >> /home/scripts/sql.$E1.out
else echo "NOT FOUND;" >> /home/scripts/sql.$E1.out
fi
done
</code>```

$E1.out files looks like :

```<code>40922|OPR MO 12345|OPR MO 12345|12345|202|local|LMNO
</code>```

答:
```<code> if tmux ls | grep -q "ABC"; then echo "1";  else echo "2"; fi
</code>```

Title: grep in IF statement

Body:
The following script portion read each line in $next. But when I try to grep particular pattern i.e. "MO" in $next, the error is shown on standard output as:

grep: 40922|OPR: No such file or directory
grep: MO: No such file or directory
grep: 12345|OPR: No such file or directory
grep: MO: No such file or directory
grep: 12345|12345|202|local|LMNO: No such file or directory

cat /home/scripts/$E1.out | while read next
do
i=`echo $next | awk -F"|" '{print($1)}'`
j=`echo $next | awk -F"|" '{print($2)}'`
k=`echo $next | awk -F"|" '{print($3)}'`
l=`echo $next | awk -F"|" '{print($4)}'`
m=`echo $next | awk -F"|" '{print($5)}'`
n=`echo $next | awk -F"|" '{print($6)}'`
o=`echo $next | awk -F"|" '{print($6)}'`
if grep -q "MO" $next
then echo "FOUND;" >> /home/scripts/sql.$E1.out
else echo "NOT FOUND;" >> /home/scripts/sql.$E1.out
fi
done

$E1.out files looks like :

40922|OPR MO 12345|OPR MO 12345|12345|202|local|LMNO


问:
Two return statements for one method? Python
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

```<code>count = 80
a = 20
if a > count:
    return xyz
else:
    return abc
</code>```

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

```<code>            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }
</code>```

答:
Well, the code you provided is always going to print the report abc since what you are comparing always returns false (As everyone else had said).

If you do want to retrieve either of the two reports depending on the situation, (In the case of a compare) either one or both values should be mutable. So they need to be inputed by the user, a parameter for the function, or computer inputted (such as a variable provided by the computer. Like time)

Now if the snippet of code you provided represents a portion of your function and assuming the count variable is keeping track of an iteration, you would need to have the return statement after the iteration to make sure everything is accounted for.

```<code>for count in list:
    # Do something

if a > count:
    return xyz
else:
    return abc
</code>```

However, the a variable or list variable (don't use list as a name for a variable, this is just an example) must be mutable. Otherwise the function will always return the same thing.

As a note:
If you want more relevant answers, include more code that better represents what you are asking (Such as a function, class, or the areas where input is retrieved and then manipulated).  Don't just provide the code where there is the error but also what leads to it.

Body:
I have a method which should print reports. There are two reports that are printed using the same method but has different conditions. I have given the if-else condition but some reason the else part is not being executed!
Kindly help me with the issue

count = 80
a = 20
if a > count:
    return xyz
else:
    return abc

abc and xyz are two different types of reports that I have.

Edit:
This is my actual function. In each I'm fetching my records.

            for inv_no in each:
                if inv_no.invoice_date > '2017-06-30':
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'gst_invoice_print',
                            'datas': datas,
                            }
                else:
                    return {
                            'type': 'ir.actions.report.xml',
                            'report_name': 'invoice_print',
                            'datas': datas,
                            }

Body:
Well, the code you provided is always going to print the report abc since what you are comparing always returns false (As everyone else had said).

If you do want to retrieve either of the two reports depending on the situation, (In the case of a compare) either one or both values should be mutable. So they need to be inputed by the user, a parameter for the function, or computer inputted (such as a variable provided by the computer. Like time)

Now if the snippet of code you provided represents a portion of your function and assuming the count variable is keeping track of an iteration, you would need to have the return statement after the iteration to make sure everything is accounted for.

for count in list:
    # Do something

if a > count:
    return xyz
else:
    return abc

However, the a variable or list variable (don't use list as a name for a variable, this is just an example) must be mutable. Otherwise the function will always return the same thing.

As a note:
If you want more relevant answers, include more code that better represents what you are asking (Such as a function, class, or the areas where input is retrieved and then manipulated).  Don't just provide the code where there is the error but also what leads to it.


问:
Online Shop - Create an order with multiple products MVC .net
So I am building an online shop using Code-First MVC

So I created this model classes for now (don't take the types of the attributes too serious for now):

Products (Produto):

```<code> public Produto()
        {
            ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
        }
        public int ProdutoID { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [Required]
        public double Preco { get; set; }

        [Required]
        public double Peso { get; set; }

        [Required]
        [StringLength(255)]
        public string Descricao { get; set; }

        [Required]
        public double IVA { get; set; }

        public string Imagem { get; set; }

        public DateTime UltimaAtualizacao { get; set; }

        public int Stock { get; set; }

        public int CategoriaID {get;set;}

        public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
    }
</code>```

Encomenda (Order):

```<code>public class Encomenda
{
    public Encomenda()
    {
        ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
    }
    [Key]
    public int IDEncomenda { get; set; }

    [Required]
    public DateTime DataSubmissao { get; set; }

    [Required]
    public DateTime DataEnvio { get; set; }

    [Required]
    public int EstadoEnvioID { get; set; }

    [StringLength(50)]
    public string NomeDestino { get; set; }

    [Required]
    public int TipoExpedicaoID { get; set; }

    [Required]
    public int RegiaoDestinoID { get; set; }

    [StringLength(50)]
    public string MoradaDestino { get; set; }

    [StringLength(50)]
    public string CodPostalDestino { get; set; }

    [Required]
    [StringLength(50)]
    public string MoradaFaturacao { get; set; }

    [Required]
    [StringLength(50)]
    public string CodPostalFaturacao { get; set; }

    public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }

}
</code>```

And the connection table between the produtos (Products) and Encomenda (Order)

```<code>   public class Produto_Encomenda
    {

        [Key]
        public int IDProduto_Encomenda { get; set; }

        [Required]
        public string NomeProduto { get; set; }

        [Required]
        public int Quantidade { get; set; }

        [Required]
        public float preco { get; set; }

        [Required]
        public float IVA { get; set; }

        public virtual Encomenda Encomenda { get; set; }

        public virtual Produto Produto { get; set; }

        [ForeignKey("Encomenda")]
        public int IDEncomendaFK { get; set; }

        [ForeignKey("Produto")]
        public int IDProdutoFK { get; set; }

    }
</code>```

So my question is..
Let's pretend that a costumer buys 2 or 3 products or more.
How can I store all this products in a single line of an order?
Cheers and thanks a lot in advance for the time spent reading.

答:
I'm not sure what you mean by "a single line of an order". Each product is a separate line item, and your entities already model this through the many-to-many relationship.

However, in general this setup is a very bad idea. Your order should not be directly related to products. Instead, your order should simply have an order item, and you'll create those order items based on the products that were sold. The reason for this is that products are very likely to change. If a product is removed because it's no longer available, for example, that doesn't negate the fact that it was previously sold in an order. However, in order for referential integrity to be maintained, any orders sold with that product would have to also have their relationship with that product removed. By having an entirely separate entity, i.e. order item, products can come and go, while the already created orders remain unaffected.

Body:
So I am building an online shop using Code-First MVC

So I created this model classes for now (don't take the types of the attributes too serious for now):

Products (Produto):

 public Produto()
        {
            ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
        }
        public int ProdutoID { get; set; }

        [Required]
        [StringLength(50)]
        public string Nome { get; set; }

        [Required]
        public double Preco { get; set; }

        [Required]
        public double Peso { get; set; }

        [Required]
        [StringLength(255)]
        public string Descricao { get; set; }

        [Required]
        public double IVA { get; set; }

        public string Imagem { get; set; }

        public DateTime UltimaAtualizacao { get; set; }

        public int Stock { get; set; }

        public int CategoriaID {get;set;}

        public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }
    }

Encomenda (Order):

public class Encomenda
{
    public Encomenda()
    {
        ListaProdutoEncomenda = new HashSet<Produto_Encomenda>();
    }
    [Key]
    public int IDEncomenda { get; set; }

    [Required]
    public DateTime DataSubmissao { get; set; }

    [Required]
    public DateTime DataEnvio { get; set; }

    [Required]
    public int EstadoEnvioID { get; set; }

    [StringLength(50)]
    public string NomeDestino { get; set; }

    [Required]
    public int TipoExpedicaoID { get; set; }

    [Required]
    public int RegiaoDestinoID { get; set; }

    [StringLength(50)]
    public string MoradaDestino { get; set; }

    [StringLength(50)]
    public string CodPostalDestino { get; set; }

    [Required]
    [StringLength(50)]
    public string MoradaFaturacao { get; set; }

    [Required]
    [StringLength(50)]
    public string CodPostalFaturacao { get; set; }

    public virtual ICollection<Produto_Encomenda> ListaProdutoEncomenda { get; set; }

}

And the connection table between the produtos (Products) and Encomenda (Order)

   public class Produto_Encomenda
    {

        [Key]
        public int IDProduto_Encomenda { get; set; }

        [Required]
        public string NomeProduto { get; set; }

        [Required]
        public int Quantidade { get; set; }

        [Required]
        public float preco { get; set; }

        [Required]
        public float IVA { get; set; }

        public virtual Encomenda Encomenda { get; set; }

        public virtual Produto Produto { get; set; }

        [ForeignKey("Encomenda")]
        public int IDEncomendaFK { get; set; }

        [ForeignKey("Produto")]
        public int IDProdutoFK { get; set; }

    }

So my question is..
Let's pretend that a costumer buys 2 or 3 products or more.
How can I store all this products in a single line of an order?
Cheers and thanks a lot in advance for the time spent reading.


问:
Creating two textfields with only bottom border swift
I'm trying to create two UITextFields that both only have the bottom border, I got some code from another StackOverflow and it worked. However, when I copy and pasted the code again for my second TextField it only shows one TextField with the bottom border.

Here is the code:

```<code> let border = CALayer()
 let width = CGFloat(2.0)
 border.borderColor = UIColor.gray.cgColor
 border.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

border.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

    border.borderWidth = width
    passwordText.layer.addSublayer(border)
    passwordText.layer.masksToBounds = true

    border.borderWidth = width
    emailText.layer.addSublayer(border)
    emailText.layer.masksToBounds = true
</code>```

Thanks for the help!

答:
You cant use the same view for both textfield. Use a copy of border for the second one. Easiest way to make this work is to refine a variable as border2 and set it up and sublayer it. Don't forget to remove your duplicate frame assign for boarder.</p>

```<code>let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.gray.cgColor
border.frame = CGRect(x: 0, y: emailText.frame.size.height -  width, width:  emailText.frame.size.width, height:  emailText.frame.size.height)

let border2 = CALayer() border2.borderColor = border.borderColor border2.frame = border.frame;

border.borderWidth = width
passwordText.layer.addSublayer(border)
passwordText.layer.masksToBounds = true

border.borderWidth = width
emailText.layer.addSublayer(border2)
emailText.layer.masksToBounds = true
</code>```

Body:
I'm trying to create two UITextFields that both only have the bottom border, I got some code from another StackOverflow and it worked. However, when I copy and pasted the code again for my second TextField it only shows one TextField with the bottom border.

Here is the code:

 let border = CALayer()
 let width = CGFloat(2.0)
 border.borderColor = UIColor.gray.cgColor
 border.frame = CGRect(x: 0, y: emailText.frame.size.height -
width, width:  emailText.frame.size.width, height:
emailText.frame.size.height)

border.frame = CGRect(x: 0, y: passwordText.frame.size.height
- width, width:  passwordText.frame.size.width, height:
passwordText.frame.size.height)

    border.borderWidth = width
    passwordText.layer.addSublayer(border)
    passwordText.layer.masksToBounds = true

    border.borderWidth = width
    emailText.layer.addSublayer(border)
    emailText.layer.masksToBounds = true

Thanks for the help!

Body:
You cant use the same view for both textfield. Use a copy of border for the second one. Easiest way to make this work is to refine a variable as border2 and set it up and sublayer it. Don't forget to remove your duplicate frame assign for boarder.

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.gray.cgColor
border.frame = CGRect(x: 0, y: emailText.frame.size.height -  width, width:  emailText.frame.size.width, height:  emailText.frame.size.height)

let border2 = CALayer() border2.borderColor = border.borderColor border2.frame = border.frame;

border.borderWidth = width
passwordText.layer.addSublayer(border)
passwordText.layer.masksToBounds = true

border.borderWidth = width
emailText.layer.addSublayer(border2)
emailText.layer.masksToBounds = true


问:
Run Debian Bash script with PHP
I'm having trouble to run a bash file using PHP.

PHP File :

```<code>chdir('/var/www/PATH/inc/bash/');
exec('./status.sh argument, $output);
</code>```

Bash File :

```<code>#!/bin/bash
echo 'test' >> /var/www/PATH/inc/bashOutput/test.txt
</code>```

PHP File (ls -al handler.func.php) :

```<code>-rw-r--r-- 1 root root 461 Jul  5 11:35 handler.func.php
</code>```

Bash File (ls -al status.sh) :

```<code>-rwxr-xr-x 1 root root 255 Jul  5 11:39 status.sh
</code>```

Script is working using through root with SSH.

I'm not a pro on Linux.
But I think it's a problem come with the file owner.

But I have already done some damages in the past with "chown" so If it is indead the problem I would prefer some guidance from more experienced people.

Thanks for you help,
Konorr.

答:
Thanks for you answer but unfortunatly it didn't worked for me.

I search a litle more about file owners.

I did few changes

I made in these change :

```<code>chown -R www-data:www-data /var/www/PATH
usermod -a -G www-data user
chgrp -R www-data /var/www/PATH
chmod 2750 /var/www/PATH
chmod 2750 /var/www/PATH/inc/bash
</code>```

It wasn't yet working till I removed the sudo from the EXEC function.
So I don't know from which point my problem was already fixed.

I followed this article : www-data permissions?

Thanks for you time and in the hope it can help someone else.

Title: Run Debian Bash script with PHP

Body:
I'm having trouble to run a bash file using PHP.

PHP File :

chdir('/var/www/PATH/inc/bash/');
exec('./status.sh argument, $output);

Bash File :

#!/bin/bash
echo 'test' >> /var/www/PATH/inc/bashOutput/test.txt

PHP File (ls -al handler.func.php) :

-rw-r--r-- 1 root root 461 Jul  5 11:35 handler.func.php

Bash File (ls -al status.sh) :

-rwxr-xr-x 1 root root 255 Jul  5 11:39 status.sh

Script is working using through root with SSH.

I'm not a pro on Linux.
But I think it's a problem come with the file owner.

But I have already done some damages in the past with "chown" so If it is indead the problem I would prefer some guidance from more experienced people.

Thanks for you help,
Konorr.

Body:
Thanks for you answer but unfortunatly it didn't worked for me.

I search a litle more about file owners.

I did few changes

I made in these change :

chown -R www-data:www-data /var/www/PATH
usermod -a -G www-data user
chgrp -R www-data /var/www/PATH
chmod 2750 /var/www/PATH
chmod 2750 /var/www/PATH/inc/bash

It wasn't yet working till I removed the sudo from the EXEC function.
So I don't know from which point my problem was already fixed.

I followed this article : www-data permissions?

Thanks for you time and in the hope it can help someone else.


答:
The error message says that "graphics::character::CharacterCache is not implemented for &mut C"; and indeed, all you have said in your where-clause is that C: CharacterCache, not &mut C: CharacterCache.

(In general, one cannot conclude &mut Type: Trait if all one knows is Type: Trait)

I'm assuming that the .draw method that you are invoking on self.properties: Text wants a &mut C for its argument, so you might be able to pass in either font or &mut *font, but I'm guessing that your extra level of indirection via &mut font is causing a problem there.

In other words:

```<code>self.properties.draw(
        self.text.as_str(),
        &mut font,
     // ~~~~~~~~~ is not the same as `font` or `&mut *font`
        &draw_state,
        transform,
        g,
    );
</code>```

Sidenote for Experienced Rustaceans:

This kind of coding "mistake" (putting in an extra level of indirection)  actually occurs more than you might think when programming in Rust.

However, one often does not notice it, because the compiler will often compare the expected type with the type that was provided, and will apply so-called deref coercions to turn in the given value into an appropriate argument.

So if you consider the following code:

```<code>fn gimme_ref_to_i32(x: &i32, amt: i32) -> i32 { *x + amt }
fn gimme_mutref_to_i32(x: &mut i32, amt: i32) { *x += amt; }

let mut concrete = 0;
gimme_mutref_to_i32(&mut concrete, 1);
gimme_mutref_to_i32(&mut &mut concrete, 20);
let i1 = gimme_ref_to_i32(&concrete, 300);
let i2 = gimme_ref_to_i32(& &concrete, 4000);

println!("concrete: {} i1: {} i2: {}", concrete, i1, i2);
</code>```

it will run without a problem; the compiler will automatically insert dereferences underneath the borrow, turning &mut &mut concrete into &mut *(&mut concrete), and & &concrete into & *(&concrete) (aka &mut concrete and &concrete respectively, in this case).

(You can read more about the history of Deref Coercions by reading the associated RFC.)

However, this magic does not save us when the function we are calling is expecting a reference to a type parameter, like so:

```<code>fn gimme_mutref_to_abs<T: AddAssign>(x: &mut T, amt: T) { *x += amt; }

let mut abstract_ = 0;
gimme_mutref_to_abs(&mut abstract_, 1);
gimme_mutref_to_abs(&mut &mut abstract_, 1);
//                  ^^^^ ^^^^^^^^^^^^^^
// compiler wants   &mut T               where T: AddAssign

println!("abstract: {}", abstract_);
</code>```

In this code, the Rust compiler starts off assuming that the input type (&mut &mut i32) will decompose into some type &mut T that satisfies T: AddAssign.

It checks the first case that can possibly match: peel off the first &mut, and then see if the remainder (&mut i32) could possibly be the T that we are searching for.

&mut i32 does not implement AddAssign, so that attempt to solve the trait constraints fails.

Here's the crucial thing: the compiler does not then decide to try applying any coercions here (including deref coercions); it just gives up. I have not managed to find a historical record of the basis for giving up here, but my memory from conversations (and from knowledge of the compiler) is that the trait resolution step is expensive, so we choose not to try to search for potential traits on each step of a coercion. Instead, the programmer is expected to figure out an appropriate conversion expression that will turn the given type T into some intermediate type U that the compiler can accept as the expected type.

Title: Why do I get the error "the trait `Foo` is not implemented for `&mut T`" even though T implements the trait?

Body:
The error message says that "graphics::character::CharacterCache is not implemented for &mut C"; and indeed, all you have said in your where-clause is that C: CharacterCache, not &mut C: CharacterCache.

(In general, one cannot conclude &mut Type: Trait if all one knows is Type: Trait)

I'm assuming that the .draw method that you are invoking on self.properties: Text wants a &mut C for its argument, so you might be able to pass in either font or &mut *font, but I'm guessing that your extra level of indirection via &mut font is causing a problem there.

In other words:

self.properties.draw(
        self.text.as_str(),
        &mut font,
     // ~~~~~~~~~ is not the same as `font` or `&mut *font`
        &draw_state,
        transform,
        g,
    );

Sidenote for Experienced Rustaceans:

This kind of coding "mistake" (putting in an extra level of indirection)  actually occurs more than you might think when programming in Rust.

However, one often does not notice it, because the compiler will often compare the expected type with the type that was provided, and will apply so-called deref coercions to turn in the given value into an appropriate argument.

So if you consider the following code:

fn gimme_ref_to_i32(x: &i32, amt: i32) -> i32 { *x + amt }
fn gimme_mutref_to_i32(x: &mut i32, amt: i32) { *x += amt; }

let mut concrete = 0;
gimme_mutref_to_i32(&mut concrete, 1);
gimme_mutref_to_i32(&mut &mut concrete, 20);
let i1 = gimme_ref_to_i32(&concrete, 300);
let i2 = gimme_ref_to_i32(& &concrete, 4000);

println!("concrete: {} i1: {} i2: {}", concrete, i1, i2);

it will run without a problem; the compiler will automatically insert dereferences underneath the borrow, turning &mut &mut concrete into &mut *(&mut concrete), and & &concrete into & *(&concrete) (aka &mut concrete and &concrete respectively, in this case).

(You can read more about the history of Deref Coercions by reading the associated RFC.)

However, this magic does not save us when the function we are calling is expecting a reference to a type parameter, like so:

fn gimme_mutref_to_abs<T: AddAssign>(x: &mut T, amt: T) { *x += amt; }

let mut abstract_ = 0;
gimme_mutref_to_abs(&mut abstract_, 1);
gimme_mutref_to_abs(&mut &mut abstract_, 1);
//                  ^^^^ ^^^^^^^^^^^^^^
// compiler wants   &mut T               where T: AddAssign

println!("abstract: {}", abstract_);

In this code, the Rust compiler starts off assuming that the input type (&mut &mut i32) will decompose into some type &mut T that satisfies T: AddAssign.

It checks the first case that can possibly match: peel off the first &mut, and then see if the remainder (&mut i32) could possibly be the T that we are searching for.

&mut i32 does not implement AddAssign, so that attempt to solve the trait constraints fails.

Here's the crucial thing: the compiler does not then decide to try applying any coercions here (including deref coercions); it just gives up. I have not managed to find a historical record of the basis for giving up here, but my memory from conversations (and from knowledge of the compiler) is that the trait resolution step is expensive, so we choose not to try to search for potential traits on each step of a coercion. Instead, the programmer is expected to figure out an appropriate conversion expression that will turn the given type T into some intermediate type U that the compiler can accept as the expected type.


问:
How i can optimize Xpath expression?
I need to concat first 5 symbols of string with 4 last and divide them with '_'.
I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)</p>

```<code>concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))
</code>```

答:
Here's an XPath 2.0 solution:

```<code>replace(//element1/element2, '^(.{5}).*(.{4})$', '$1_$2')
</code>```

Unlike your solution, it assumes the string is at least 9 characters long.

Title: How i can optimize Xpath expression?

Body:
I need to concat first 5 symbols of string with 4 last and divide them with '_'.
I came up with this, but it looks so ugly. Can it be rewritten better? I am new to Xpath, so maybe its ok(but i dont think so)

concat(substring(//element1/element2/text(),1,5),"_",substring(//element1/element2/text(),string-length(//element1/element2/text())-4))

Body:
Here's an XPath 2.0 solution:

replace(//element1/element2, '^(.{5}).*(.{4})$', '$1_$2')

Unlike your solution, it assumes the string is at least 9 characters long.


问:
app not installed error on android in kotlin gradle 3.0.0-alpha5
```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "//"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

and project level

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

actually before i'm using 2.3 gradle at that time there is no error now i changed to 3.0.0-alphs-5 app not installing error.  i do appreciate if u solve this error . is it  kotlin error or anything different i cant find the solution pls help me(this is happening only  while i'm sharing  not by debugging through studio)

答:
Try the following

```<code>./gradlew --stop
</code>```

and then go to

```<code>File > invalidate caches / restart > invalidate and restart
</code>```

Body:
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "//"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

and project level

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha5'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

actually before i'm using 2.3 gradle at that time there is no error now i changed to 3.0.0-alphs-5 app not installing error.  i do appreciate if u solve this error . is it  kotlin error or anything different i cant find the solution pls help me(this is happening only  while i'm sharing  not by debugging through studio)

Body:
Try the following

./gradlew --stop

and then go to

File > invalidate caches / restart > invalidate and restart


问:
Macro Code to Number Lines based on if there is Data
I am newish at VBA but I cannot figure out how to make this work. I am copying a ton of data from a another Excel sheet and then deleting the unneeded rows. The problem is that I need my data numbered in column A and when I delete the row it skips numbers. I want a macro that will number my data after I delete the unneeded lines. I do need it to stop when my data stops but the number of lines will be different each time. Any tips? Thank you.</p>

答:
Use union  method.  You collect range and at the last line,  delete them.</p>

```<code>Sub test()
    Dim rngU As Range
    Dim i As Integer

    For i = 1 To 100
        If Range("a" & i) = "" Then
            If rngU Is Nothing Then
                Set rngU = Range("a" & i)
            Else
                Set rngU = Union(rngU, Range("a" & i))
            End If
        End If
    Next i
    If rngU Is Nothing Then
    Else
        rngU.EntireRow.Delete 'rngu is collected ranges.
    End If
End Sub
</code>```

Body:
Use union  method.  You collect range and at the last line,  delete them.

Sub test()
    Dim rngU As Range
    Dim i As Integer

    For i = 1 To 100
        If Range("a" & i) = "" Then
            If rngU Is Nothing Then
                Set rngU = Range("a" & i)
            Else
                Set rngU = Union(rngU, Range("a" & i))
            End If
        End If
    Next i
    If rngU Is Nothing Then
    Else
        rngU.EntireRow.Delete 'rngu is collected ranges.
    End If
End Sub


问:
Odoo 8 override button with workflow
I want to override the button 'Validate' inside Accounting -> Customer Invoices -> Invoice. I just want to change the visibility group (just for customer refunds).

Here is how it looks like:

```<code><record id="invoice_form" model="ir.ui.view">
  <field name="name">account.invoice.form</field>
  <field name="model">account.invoice</field>
  <field name="inherit_id" ref="account.invoice_form"/>
  <field name="arch" type="xml">
    <xpath expr="/form/header/button[@name='invoice_open' and @states='draft']" position="replace">

      <!-- Show validate button inside invoice of type out_refund only, if in state draft + group_customer_refund_manager -->
      <button name="invoice_open" type="object" string="Validate" class="oe_highlight"
            attrs="{'invisible': ['|',('type', '!=', 'out_refund'), ('state','not in',('draft',))]}"
            groups="account.group_customer_refund_manager"/>
      <!-- Show validate button inside invoice of type !out_refund if state in draft -->
      <button name="invoice_open" type="object" string="Validate" class="oe_highlight"
            attrs="{'invisible': ['|',('type', '=', 'out_refund'), '&', ('type', '!=', 'out_refund'), ('state','not in',('draft',))]}"
            groups="base.group_user" />

    </xpath>

  </field>
</code>```

The button is replaced, however the workflow 'invoice_open' seems to be unknown now. When clicking on the Button I receive the error message AttributeError: 'account.invoice' object has no attribute 'invoice_open

Can you help me fix this for Odoo8. (I tried it for Odoo10 already and it worked ...the only difference there was, that the button name was 'action_invoice_open' and it triggers a method in python instead of a workflow - but I need it for Odoo8)

The workflow is still visible in the settings menu ...

答:
I just found my mistake :) - as I also tried for Odoo 10 I used the wrong button type for Odoo8.

As a workflow is called, the button type must be workflow instead of object.

Maybe this helps someone else too to find their errors when receiving a similar error. Thanks.

Title: Odoo 8 override button with workflow

Body:
I want to override the button 'Validate' inside Accounting -> Customer Invoices -> Invoice. I just want to change the visibility group (just for customer refunds).

Here is how it looks like:

<record id="invoice_form" model="ir.ui.view">
  <field name="name">account.invoice.form</field>
  <field name="model">account.invoice</field>
  <field name="inherit_id" ref="account.invoice_form"/>
  <field name="arch" type="xml">
    <xpath expr="/form/header/button[@name='invoice_open' and @states='draft']" position="replace">

      <button name="invoice_open" type="object" string="Validate" class="oe_highlight"
            attrs="{'invisible': ['|',('type', '!=', 'out_refund'), ('state','not in',('draft',))]}"
            groups="account.group_customer_refund_manager"/>

      <button name="invoice_open" type="object" string="Validate" class="oe_highlight"
            attrs="{'invisible': ['|',('type', '=', 'out_refund'), '&', ('type', '!=', 'out_refund'), ('state','not in',('draft',))]}"
            groups="base.group_user" />

    </xpath>

  </field>

The button is replaced, however the workflow 'invoice_open' seems to be unknown now. When clicking on the Button I receive the error message AttributeError: 'account.invoice' object has no attribute 'invoice_open

Can you help me fix this for Odoo8. (I tried it for Odoo10 already and it worked ...the only difference there was, that the button name was 'action_invoice_open' and it triggers a method in python instead of a workflow - but I need it for Odoo8)

The workflow is still visible in the settings menu ...


问:
Change letter case of column names
I have a large number of data sets each containing a long list of column names.  In some files the column names are all capital letters and in some files only the first letter of the column names is capitalized.  I need to append the data sets and thought the easiest way to match column names among data sets would be to convert the all-capital names into names with only the first letter capitalized.

I am hoping to find a general solution, maybe even a one-liner.

Here is my example data set.  The desired names are included in the names statements.

```<code>my.data2 <-  "
landuse units grade CLAY    LINCOLN  BASINANDRANGE  MCCARTNEY  MAPLE
apple   acres AAA     0         2          3             4         6
apple   acres AA   1000       900         NA            NA       700
pear    acres AA   10.0        20         NA          30.0        40
peach   acres AAA   500       400        350           300       200
"
my.data2 <- read.table(textConnection(my.data2), header=TRUE)

names(my.data2)[names(my.data2)=="CLAY"]            <- "Clay"
names(my.data2)[names(my.data2)=="BASINANDRANGE"]   <- "BasinandRange"
names(my.data2)[names(my.data2)=="LINCOLN"]         <- "Lincoln"
names(my.data2)[names(my.data2)=="MCCARTNEY"]       <- "McCartney"
names(my.data2)[names(my.data2)=="MAPLE"]           <- "Maple"

my.data2
</code>```

Note that I included the names McCartney and BasinandRange to make things more realistic and more difficult.  However, if I can find a one-liner to deal with 95% of the names and use the above names statements to deal with complications like McCartney and BasinandRange that would be great.

I have searched the internet, including the StackOverflow archives, without finding a solution.  Sorry if I overlooked one.  Thank you for any help.

答:
data.table syntax, I believe would save more time and efficient. its also a one line statement, even shorter.</p>

```<code>library(data.table)
setnames(my.data2, tolower(names(my.data2[4:8])))

#   landuse units grade clay lincoln basinandrange mccartney maple
#1:   apple acres   AAA    0       2             3         4     6
#2:   apple acres    AA 1000     900            NA        NA   700
#3:    pear acres    AA   10      20            NA        30    40
#4:   peach acres   AAA  500     400           350       300   200
</code>```

Title: Change letter case of column names

Body:
I have a large number of data sets each containing a long list of column names.  In some files the column names are all capital letters and in some files only the first letter of the column names is capitalized.  I need to append the data sets and thought the easiest way to match column names among data sets would be to convert the all-capital names into names with only the first letter capitalized.

I am hoping to find a general solution, maybe even a one-liner.

Here is my example data set.  The desired names are included in the names statements.

my.data2 <-  "
landuse units grade CLAY    LINCOLN  BASINANDRANGE  MCCARTNEY  MAPLE
apple   acres AAA     0         2          3             4         6
apple   acres AA   1000       900         NA            NA       700
pear    acres AA   10.0        20         NA          30.0        40
peach   acres AAA   500       400        350           300       200
"
my.data2 <- read.table(textConnection(my.data2), header=TRUE)

names(my.data2)[names(my.data2)=="CLAY"]            <- "Clay"
names(my.data2)[names(my.data2)=="BASINANDRANGE"]   <- "BasinandRange"
names(my.data2)[names(my.data2)=="LINCOLN"]         <- "Lincoln"
names(my.data2)[names(my.data2)=="MCCARTNEY"]       <- "McCartney"
names(my.data2)[names(my.data2)=="MAPLE"]           <- "Maple"

my.data2

Note that I included the names McCartney and BasinandRange to make things more realistic and more difficult.  However, if I can find a one-liner to deal with 95% of the names and use the above names statements to deal with complications like McCartney and BasinandRange that would be great.

I have searched the internet, including the StackOverflow archives, without finding a solution.  Sorry if I overlooked one.  Thank you for any help.

Body:
data.table syntax, I believe would save more time and efficient. its also a one line statement, even shorter.

library(data.table)
setnames(my.data2, tolower(names(my.data2[4:8])))

#   landuse units grade clay lincoln basinandrange mccartney maple
#1:   apple acres   AAA    0       2             3         4     6
#2:   apple acres    AA 1000     900            NA        NA   700
#3:    pear acres    AA   10      20            NA        30    40
#4:   peach acres   AAA  500     400           350       300   200

ContentLicense: CC BY-SA 4.0


问:
Move packaged_task into lambda
I want to move and call a boost::packaged_task inside a lambda.

However, I can't figure out an elegant solution.

e.g. This won't compile.

```<code>        template<typename Func>
        auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
        {
            typedef boost::packaged_task<decltype(func())> task_type;

            auto task = task_type(std::forward<Func>(func));
            auto future = task.get_future();

            execution_queue_.try_push([=]
            {
                try{task();}
                catch(boost::task_already_started&){}
            });

            return std::move(future);
        }

    int _tmain(int argc, _TCHAR* argv[])
    {
        executor ex;
        ex.begin_invoke([]{std::cout << "Hello world!";});
       //error C3848: expression having type 'const boost::packaged_task<R>' would lose some const-volatile qualifiers in order to call 'void boost::packaged_task<R>::operator ()(void)'
//          with
//          [
//              R=void
//          ]
        return 0;
    }
</code>```

My rather ugly solution:

```<code>    struct task_adaptor_t
    {
        // copy-constructor acts as move constructor
        task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
        task_adaptor_t(task_type&& task) : task(std::move(task)){}
        void operator()() const { task(); }
        mutable task_type task;
    } task_adaptor(std::move(task));

    execution_queue_.try_push([=]
    {
        try{task_adaptor();}
        catch(boost::task_already_started&){}
    });
</code>```

What is the "proper" way to move a packaged_task into a lambda which calls it?

答:
There's a similar question up that I posted about moving into lambdas. C++0x doesn't have any move capture syntax. The only solution I could come up with was some kind of proxy function object.

```<code>template<typename T, typename F> class move_capture_proxy {
    T t;
    F f;
public:
    move_capture_proxy(T&& a, F&& b)
        : t(std::move(a)), f(std::move(b)) {}
    auto operator()() -> decltype(f(std::move(b)) {
        return f(std::move(b));
    }
};
template<typename T, typename F> move_capture_proxy<T, F> make_move_proxy(T&& t, F&& f) {
    return move_capture_proxy<T, F>(std::move(t), std::move(f));
}

execution_queue.try_push(make_move_proxy(std::move(task), [](decltype(task)&& ref) {
    auto task = std::move(ref);
    // use task
});
</code>```

Note that I haven't actually tried this code, and it would become a lot nicer with variadic templates, but MSVC10 doesn't have them so I don't really know about them.

ContentLicense: CC BY-SA 2.5

Title: Move packaged_task into lambda

Body:
I want to move and call a boost::packaged_task inside a lambda.

However, I can't figure out an elegant solution.

e.g. This won't compile.

        template<typename Func>
        auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
        {
            typedef boost::packaged_task<decltype(func())> task_type;

            auto task = task_type(std::forward<Func>(func));
            auto future = task.get_future();

            execution_queue_.try_push([=]
            {
                try{task();}
                catch(boost::task_already_started&){}
            });

            return std::move(future);
        }

    int _tmain(int argc, _TCHAR* argv[])
    {
        executor ex;
        ex.begin_invoke([]{std::cout << "Hello world!";});
       //error C3848: expression having type 'const boost::packaged_task<R>' would lose some const-volatile qualifiers in order to call 'void boost::packaged_task<R>::operator ()(void)'
//          with
//          [
//              R=void
//          ]
        return 0;
    }

My rather ugly solution:

    struct task_adaptor_t
    {
        // copy-constructor acts as move constructor
        task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
        task_adaptor_t(task_type&& task) : task(std::move(task)){}
        void operator()() const { task(); }
        mutable task_type task;
    } task_adaptor(std::move(task));

    execution_queue_.try_push([=]
    {
        try{task_adaptor();}
        catch(boost::task_already_started&){}
    });

What is the "proper" way to move a packaged_task into a lambda which calls it?

Body:
There's a similar question up that I posted about moving into lambdas. C++0x doesn't have any move capture syntax. The only solution I could come up with was some kind of proxy function object.

template<typename T, typename F> class move_capture_proxy {
    T t;
    F f;
public:
    move_capture_proxy(T&& a, F&& b)
        : t(std::move(a)), f(std::move(b)) {}
    auto operator()() -> decltype(f(std::move(b)) {
        return f(std::move(b));
    }
};
template<typename T, typename F> move_capture_proxy<T, F> make_move_proxy(T&& t, F&& f) {
    return move_capture_proxy<T, F>(std::move(t), std::move(f));
}

execution_queue.try_push(make_move_proxy(std::move(task), [](decltype(task)&& ref) {
    auto task = std::move(ref);
    // use task
});

Note that I haven't actually tried this code, and it would become a lot nicer with variadic templates, but MSVC10 doesn't have them so I don't really know about them.


问:
Bind Combobox in WPF to Entity class
I have a data input form where i have textboxes,comboboxes and datepickers. I want to Bind comboboxes to the DB column so that users select the correct value for insertion. I have attached the viewmodel class and XAML code. In the viewmodel code "private void GetSW()" - this gets all the list of the entity class and "private void addSW()" this adds the record to the DB, Except the combobox binding everything works fine. in XAML i have binded combobox like this but this give blank combobox, please help what i am missing. I researched many topics on this forum but didn't find any solution

```<code><ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding newSW.PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
</code>```

Its a ViewModel Code

```<code>using BusinessEntities;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MUDB.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MUDB.Ui.Logic
{
    public class SoftwareVersionListViewModel:ViewModelBase
    {
        private bool enableRowDetails=false;
        public bool EnagleRowDetails
        {
            get { return enableRowDetails; }
            set {
                enableRowDetails = value;
                RaisePropertyChanged();
            }
        }

        public SoftwareVersionListViewModel()
        {
            SaveSW = new RelayCommand(addSW);
            //savecommand = new RelayCommand(addprod);
            GetSW();
            newSW = new SoftwareDefEntity();
            EditSW = new RelayCommand(() => {
                EnagleRowDetails = true;

                MessageBox.Show("Edit button clicked!!");});

            //SWList = new SoftwareDefEntity(); //Initializing the object of the Entity class
            }

        public List<SoftwareDefEntity> SWentities
        {
            get;
            set;
        }

        private SoftwareDefEntity _selectedsw;
        public SoftwareDefEntity Selectedsw
        {
            get { return _selectedsw; }
            set
            {
                _selectedsw = value; //This will get all the values of that particular Selected row that are defined in the entity class
                EnagleRowDetails = false; //Reset boolean value EnagleRowDetails, so that the selected rowdetails are disabled until Edit button is not clicked.
                //ShowView();
            }
        }

        public RelayCommand SaveSW { get; private set; }
        public RelayCommand EditSW { get; private set; }
        public SoftwareDefEntity newSW { get; private set; }

        private void ShowView()
        {
            //cUSTOM METHODS
        }

        private void GetSW() // Method that reads the data from the service layer
        {
            SWDefService obj = new SWDefService();
            SWentities = obj.getSW() ; //getSW is the method refered in Service layer

        }

        private void addSW()
        {
            SWDefService obj = new SWDefService();
            obj.addSW(newSW); //newproduct object will hold the value of the binded control, in XAML its binded like this "{Binding newproduct.ProductName(ProductName is the field name in the entityclass/DB table)}"
            newSW = new SoftwareDefEntity();

        }
    }

}
</code>```

This is the XAML Code

```<code><UserControl x:Class="MUDB.Ui.CreateSW"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:MUDB.Ui"
             xmlns:converter="clr-namespace:MUDB.Ui.Logic.Converters;assembly=MUDB.Ui.Logic"
             xmlns:enums="clr-namespace:MUDB.Ui.Logic.Enums;assembly=MUDB.Ui.Logic"
             mc:Ignorable="d" Height="Auto" Width="Auto"
            DataContext="{Binding SoftwareVersionList,Source={StaticResource Locator}}" >
    <UserControl.Resources>
        <converter:RadioButtonToBooleanConverter x:Key="RadioButtonToBooleanConverter" />
    </UserControl.Resources>
    <Grid>
        <Border Background="#90000000" Visibility="{Binding Visibility}">
            <Border BorderBrush="Black" BorderThickness="1" Background="White"
                    CornerRadius="10,0,10,0" VerticalAlignment="Center"
                    HorizontalAlignment="Center">
                <Border.BitmapEffect>
                    <DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" />
                </Border.BitmapEffect>
                <Grid Margin="10">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition Width="Auto"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="100"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>

        <Label Content="Create New Software Version" Grid.Column="0" Grid.Row="0" Foreground="White" Background="black"
               HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.ColumnSpan="3" />
        <Label Content="ECU" Grid.Column="0" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Software Name" Grid.Column="1" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Previous Software" Grid.Column="2" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Request Freeze Date" Grid.Column="0" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Request Freeze Status" Grid.Column="1" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Bottom" />
        <Label Content="Software Freeze Date" Grid.Column="0" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Center" />
        <Label Content="Software Freeze Status" Grid.Column="1" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Center" />
        <Label Content="Comments" Grid.Column="0" Grid.Row="7" Foreground="Black" HorizontalAlignment="Left"
               VerticalAlignment="Center" />
                    <ComboBox x:Name="ECU" Grid.Column="0" Grid.Row="2" Text="{Binding newSW.ECU}" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80" Height="Auto">
                        <ComboBoxItem Name="cbi1">ACM</ComboBoxItem>
                        <ComboBoxItem Name="cbi2">MCM</ComboBoxItem>
                    </ComboBox>
                    <TextBox x:Name="SW" Grid.Column="1" Grid.Row="2" Text="{Binding newSW.SoftwareName}" HorizontalAlignment="Left" VerticalAlignment="Top"  Height="Auto" Width="150"  />
                    <ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
                    <DatePicker Grid.Column="0" Grid.Row="4" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.Req_Freeze_Date}" Height="Auto" Width="Auto"/>
                    <DatePicker Grid.Column="0" Grid.Row="6" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.SW_Freeze_Date}" Height="Auto" Width="Auto"/>
                    <RadioButton Content="Yes" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4"  HorizontalAlignment="Left"  VerticalAlignment="Top" Height="14" Width="Auto"/>
                    <RadioButton Content="No" GroupName="ReQstat"  IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" Margin="60 0 0 0" HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <RadioButton Content="Yes" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}"   Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6"  HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <RadioButton Content="No" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}"  Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" Margin="60 0 0 0" HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <TextBox x:Name="CommenttextBox" Grid.Column="1" Grid.Row="7"  HorizontalAlignment="Left" Height="69" TextWrapping="WrapWithOverflow" VerticalAlignment="Center" Text="{Binding Comment}" Width="170" Margin="4.4,2.2,0,0" />
                    <UniformGrid Grid.Row="9" Margin="2" Columns="2" HorizontalAlignment="Stretch"
                                 VerticalAlignment="Center" Height="Auto">
                        <Button x:Name="SaveButton" Command="{Binding SaveSW}" Content="Save"  Height="27"   />
                        <Button x:Name="CloseButton" Click="CloseButton_Click" Content="Close" Height="26"  />
                    </UniformGrid>
                </Grid>
            </Border>
        </Border>
    </Grid>
</UserControl>
</code>```

答:
This is the code to bind the data to combobox. i did not add any of other controls since those are working fine at your place. Observable collection is easy way to bind combobox .

Here is your View Model..

```<code> public class SoftwareVersionListViewModel : ViewModelBase
    {
        public SoftwareVersionListViewModel()
        {
            GetSW();
        }

        //Define the observable collection
        private ObservableCollection<SoftwareDefEntity> _SWmappings2 = new ObservableCollection<SoftwareDefEntity>();

        //here is  your Entity list
        public List<SoftwareDefEntity> SWentities
        {
            get;
            set;
        }

        // Obeservable collection property for access
        public ObservableCollection<SoftwareDefEntity> SWmappings2
        {
            get { return _SWmappings2; }
            set
            {
                _SWmappings2 = value;
                OnPropertyChanged("appeventmappings2");
            }
        }

        /// <summary>
        ///  load the combobox
        /// </summary>
       private void GetSW() // Method that reads the data from the service layer
        {
        SWDefService obj = new SWDefService();
        SWentities = obj.getSW(); //getSW is the method refered in Service layer
        SWentities.ForEach(_SWmappings2.Add);
        }
    }
</code>```

and Xaml...

```<code> <ComboBox x:Name="ComboBox"   ItemsSource="{Binding SWmappings2, UpdateSourceTrigger=PropertyChanged}"  DisplayMemberPath="PreviousSW" SelectedItem="{Binding PreviousSW, Mode=TwoWay}"   Grid.Row="0"  >
 </ComboBox>
</code>```

Title: Bind Combobox in WPF to Entity class

Body:
I have a data input form where i have textboxes,comboboxes and datepickers. I want to Bind comboboxes to the DB column so that users select the correct value for insertion. I have attached the viewmodel class and XAML code. In the viewmodel code "private void GetSW()" - this gets all the list of the entity class and "private void addSW()" this adds the record to the DB, Except the combobox binding everything works fine. in XAML i have binded combobox like this but this give blank combobox, please help what i am missing. I researched many topics on this forum but didn't find any solution

<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding newSW.PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>

Its a ViewModel Code

using BusinessEntities;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MUDB.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MUDB.Ui.Logic
{
    public class SoftwareVersionListViewModel:ViewModelBase
    {
        private bool enableRowDetails=false;
        public bool EnagleRowDetails
        {
            get { return enableRowDetails; }
            set {
                enableRowDetails = value;
                RaisePropertyChanged();
            }
        }

        public SoftwareVersionListViewModel()
        {
            SaveSW = new RelayCommand(addSW);
            //savecommand = new RelayCommand(addprod);
            GetSW();
            newSW = new SoftwareDefEntity();
            EditSW = new RelayCommand(() => {
                EnagleRowDetails = true;

                MessageBox.Show("Edit button clicked!!");});

            //SWList = new SoftwareDefEntity(); //Initializing the object of the Entity class
            }

        public List<SoftwareDefEntity> SWentities
        {
            get;
            set;
        }

        private SoftwareDefEntity _selectedsw;
        public SoftwareDefEntity Selectedsw
        {
            get { return _selectedsw; }
            set
            {
                _selectedsw = value; //This will get all the values of that particular Selected row that are defined in the entity class
                EnagleRowDetails = false; //Reset boolean value EnagleRowDetails, so that the selected rowdetails are disabled until Edit button is not clicked.
                //ShowView();
            }
        }

        public RelayCommand SaveSW { get; private set; }
        public RelayCommand EditSW { get; private set; }
        public SoftwareDefEntity newSW { get; private set; }

        private void ShowView()
        {
            //cUSTOM METHODS
        }

        private void GetSW() // Method that reads the data from the service layer
        {
            SWDefService obj = new SWDefService();
            SWentities = obj.getSW() ; //getSW is the method refered in Service layer

        }

        private void addSW()
        {
            SWDefService obj = new SWDefService();
            obj.addSW(newSW); //newproduct object will hold the value of the binded control, in XAML its binded like this "{Binding newproduct.ProductName(ProductName is the field name in the entityclass/DB table)}"
            newSW = new SoftwareDefEntity();

        }
    }

}

This is the XAML Code

<UserControl x:Class="MUDB.Ui.CreateSW"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:MUDB.Ui"
             xmlns:converter="clr-namespace:MUDB.Ui.Logic.Converters;assembly=MUDB.Ui.Logic"
             xmlns:enums="clr-namespace:MUDB.Ui.Logic.Enums;assembly=MUDB.Ui.Logic"
             mc:Ignorable="d" Height="Auto" Width="Auto"
            DataContext="{Binding SoftwareVersionList,Source={StaticResource Locator}}" >
    <UserControl.Resources>
        <converter:RadioButtonToBooleanConverter x:Key="RadioButtonToBooleanConverter" />
    </UserControl.Resources>
    <Grid>
        <Border Background="#90000000" Visibility="{Binding Visibility}">
            <Border BorderBrush="Black" BorderThickness="1" Background="White"
                    CornerRadius="10,0,10,0" VerticalAlignment="Center"
                    HorizontalAlignment="Center">
                <Border.BitmapEffect>
                    <DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" />
                </Border.BitmapEffect>
                <Grid Margin="10">

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition Width="Auto"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="100"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>

                    <ComboBox x:Name="ECU" Grid.Column="0" Grid.Row="2" Text="{Binding newSW.ECU}" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80" Height="Auto">
                        <ComboBoxItem Name="cbi1">ACM</ComboBoxItem>
                        <ComboBoxItem Name="cbi2">MCM</ComboBoxItem>
                    </ComboBox>
                    <TextBox x:Name="SW" Grid.Column="1" Grid.Row="2" Text="{Binding newSW.SoftwareName}" HorizontalAlignment="Left" VerticalAlignment="Top"  Height="Auto" Width="150"  />
                    <ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
                    <DatePicker Grid.Column="0" Grid.Row="4" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.Req_Freeze_Date}" Height="Auto" Width="Auto"/>
                    <DatePicker Grid.Column="0" Grid.Row="6" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.SW_Freeze_Date}" Height="Auto" Width="Auto"/>
                    <RadioButton Content="Yes" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4"  HorizontalAlignment="Left"  VerticalAlignment="Top" Height="14" Width="Auto"/>
                    <RadioButton Content="No" GroupName="ReQstat"  IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" Margin="60 0 0 0" HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <RadioButton Content="Yes" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}"   Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6"  HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <RadioButton Content="No" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}"  Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" Margin="60 0 0 0" HorizontalAlignment="Left"  VerticalAlignment="Top" Height="Auto" Width="Auto"/>
                    <TextBox x:Name="CommenttextBox" Grid.Column="1" Grid.Row="7"  HorizontalAlignment="Left" Height="69" TextWrapping="WrapWithOverflow" VerticalAlignment="Center" Text="{Binding Comment}" Width="170" Margin="4.4,2.2,0,0" />
                    <UniformGrid Grid.Row="9" Margin="2" Columns="2" HorizontalAlignment="Stretch"
                                 VerticalAlignment="Center" Height="Auto">
                        <Button x:Name="SaveButton" Command="{Binding SaveSW}" Content="Save"  Height="27"   />
                        <Button x:Name="CloseButton" Click="CloseButton_Click" Content="Close" Height="26"  />
                    </UniformGrid>
                </Grid>
            </Border>
        </Border>
    </Grid>
</UserControl>

Body:
This is the code to bind the data to combobox. i did not add any of other controls since those are working fine at your place. Observable collection is easy way to bind combobox .

Here is your View Model..

 public class SoftwareVersionListViewModel : ViewModelBase
    {
        public SoftwareVersionListViewModel()
        {
            GetSW();
        }

        //Define the observable collection
        private ObservableCollection<SoftwareDefEntity> _SWmappings2 = new ObservableCollection<SoftwareDefEntity>();

        //here is  your Entity list
        public List<SoftwareDefEntity> SWentities
        {
            get;
            set;
        }

        // Obeservable collection property for access
        public ObservableCollection<SoftwareDefEntity> SWmappings2
        {
            get { return _SWmappings2; }
            set
            {
                _SWmappings2 = value;
                OnPropertyChanged("appeventmappings2");
            }
        }

        /// <summary>
        ///  load the combobox
        /// </summary>
       private void GetSW() // Method that reads the data from the service layer
        {
        SWDefService obj = new SWDefService();
        SWentities = obj.getSW(); //getSW is the method refered in Service layer
        SWentities.ForEach(_SWmappings2.Add);
        }
    }

and Xaml...

 <ComboBox x:Name="ComboBox"   ItemsSource="{Binding SWmappings2, UpdateSourceTrigger=PropertyChanged}"  DisplayMemberPath="PreviousSW" SelectedItem="{Binding PreviousSW, Mode=TwoWay}"   Grid.Row="0"  >
 </ComboBox>