问:
What does alloca(0) do and return on various platforms?
Does alloca() returns  NULL if the size given is 0?

A quick search reveals that  alloca(0) force garbage collection in some cases! but I am mostly interested by return value.

thanks

答:
On Windows, _alloca(0); returns the stack pointer (with some fixed offset.) This may be necessary in some exceptional situations when C code needs to know the RSP CPU register from within an x64 process (since inline assembly is not supported for 64-bit builds in Visual Studio.)

Keep in mind though, that calling _alloca(0); will allocate some memory on the stack, so make sure not to call it repeatedly in the same local scope, as otherwise that may deplete your stack and cause the stack overflow exception.

As a much better alternative, consider calling _AddressOfReturnAddress() intrinsic instead.


来源: stackexchange

问:
Convert Object To Byte Array without Serialization nor Padding
It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct

```<code>[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}
</code>```

Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added

```<code>int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
</code>```

Also Remark: I can't use Binary format serialization as there's a metadata added.  All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as

```<code>    arr {byte[12]}  byte[]
    [0]  1  byte
    [1]  0  byte
    [2]  2  byte
    [3]  0  byte
    [4]  0  byte
    [5]  0  byte
    [6]  3  byte
    [7]  0  byte
    [8]  0  byte
    [9]  0  byte
    [10] 4  byte
    [11] 0  byte
</code>```

Any help?

答:
Edit: I may have misunderstood the question; if your point is that you want the specific layout - then see the FieldOffset hints that Tim Rutter notes in their answer.

unsafe might be the easiest option:

```<code>using System;
using System.Runtime.InteropServices;

static class P
{
    private static unsafe void Main()
    {
        MyStruct orig = new MyStruct { a = 1, b = 2, c = 3, d = 4 };

        byte[] raw = new byte[sizeof(MyStruct)];
        // write the empty array to prove it is empty
        Console.WriteLine(BitConverter.ToString(raw));

        // serialize
        fixed (byte* p = raw)
        {
            var typed = (MyStruct*)p;
            *typed = orig;
        }

        // write the serialized data
        Console.WriteLine(BitConverter.ToString(raw));

        // deserialize
        MyStruct clone;
        fixed (byte* p = raw)
        {
            var typed = (MyStruct*)p;
            clone = *typed;
        }

        Console.WriteLine($"a = {clone.a}, b = {clone.b}, c = {clone.c}, d = {clone.d}");
    }
}
</code>```

with:

```<code>[StructLayout(LayoutKind.Sequential)] // see Tim's answer for explicit layout
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}
</code>```

However, it isn't very generic. If you need more generic code: the Unsafe type has many utility methods for this kind of thing.

ContentLicense: CC BY-SA 3.0

Body:
It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}

Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added

int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);

Also Remark: I can't use Binary format serialization as there's a metadata added.  All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as

    arr {byte[12]}  byte[]
    [0]  1  byte
    [1]  0  byte
    [2]  2  byte
    [3]  0  byte
    [4]  0  byte
    [5]  0  byte
    [6]  3  byte
    [7]  0  byte
    [8]  0  byte
    [9]  0  byte
    [10] 4  byte
    [11] 0  byte

Any help?

Body:
Edit: I may have misunderstood the question; if your point is that you want the specific layout - then see the FieldOffset hints that Tim Rutter notes in their answer.

unsafe might be the easiest option:

using System;
using System.Runtime.InteropServices;

static class P
{
    private static unsafe void Main()
    {
        MyStruct orig = new MyStruct { a = 1, b = 2, c = 3, d = 4 };

        byte[] raw = new byte[sizeof(MyStruct)];
        // write the empty array to prove it is empty
        Console.WriteLine(BitConverter.ToString(raw));

        // serialize
        fixed (byte* p = raw)
        {
            var typed = (MyStruct*)p;
            *typed = orig;
        }

        // write the serialized data
        Console.WriteLine(BitConverter.ToString(raw));

        // deserialize
        MyStruct clone;
        fixed (byte* p = raw)
        {
            var typed = (MyStruct*)p;
            clone = *typed;
        }

        Console.WriteLine($"a = {clone.a}, b = {clone.b}, c = {clone.c}, d = {clone.d}");
    }
}

with:

[StructLayout(LayoutKind.Sequential)] // see Tim's answer for explicit layout
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}

However, it isn't very generic. If you need more generic code: the Unsafe type has many utility methods for this kind of thing.


问:
hovering over a tag, but not showing the menu
im trying to make a very simple menu here
basically i want to hover over the link and a menu show up.
but its not showing up!
i nested 2 tags inside of each other and gave em ids.
u can see the rest in code.

.navbar {
  width: 100%;
  height: 30px;
  overflow: no-display;
}

#headermenu {
  display: none;
}

#amenu:hover #headermenu {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar">
  <ul id="Header">
    <li>
      aaaa
        <div id="headermenu">
          <ul>
            <li><a>menue yek</li>
          </ul>
        </div>
      </a>
    </li>
  </ul>
</nav></code>```

答:
You have to remove the submenu from the a tag, and put the "amenu" id on the li item, like so:

.navbar{
   width:100%;
   height:30px;
   overflow: no-display;
}
#headermenu{
   display:none;
}

#amenu:hover #headermenu{
   display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar">
  <ul id="Header">
    <li id="amenu">
      <a>aaaa</a>
      <div id="headermenu">
        <ul>
          <li><a>menue yek</a></li>
        </ul>
      </div>
    </li>
  </ul>
</nav></code>```

Body:
im trying to make a very simple menu here
basically i want to hover over the link and a menu show up.
but its not showing up!
i nested 2 tags inside of each other and gave em ids.
u can see the rest in code.

.navbar {
  width: 100%;
  height: 30px;
  overflow: no-display;
}

#headermenu {
  display: none;
}

#amenu:hover #headermenu {
  display: block;
}

      aaaa

menue yek

Body:
You have to remove the submenu from the a tag, and put the "amenu" id on the li item, like so:

.navbar{
   width:100%;
   height:30px;
   overflow: no-display;
}
#headermenu{
   display:none;
}

#amenu:hover #headermenu{
   display:block;
}

<nav class="navbar">
  <ul id="Header">
    <li id="amenu">
      <a>aaaa</a>
      <div id="headermenu">
        <ul>
          <li><a>menue yek</a></li>
        </ul>
      </div>
    </li>
  </ul>
</nav>


问:
Sorting POST data to update MySQL table rows via id in the POST name
I have made a form application in PHP and now I'm trying to implement updating the fields. I have made it so the POST contains data like this:

```<code>Array (
    '17-label' => "select label 0 ",
    '17-placeholder' => "select placeholder 0 ",
    '17-answer' => Array (
        "Answer 1",
        "Answer 2",
        "Answer 3"
    ),
    '18-label' => "textfield label 1",
    '18-placeholder' => "textfield placeholder 1",
    '19-label' => "textfield label 2",
    '19-placeholder' => "textfield placeholder 2"
)
</code>```

Now as you can see I use the id of the row I want to update as the start, and then a - to identify the break and the actual column name I want to update in the column.

But how do I do this?

I know how to update, it is just, how to make sure everything goes to the right column. The first number is the id, and after the - sign it is the actual column name. But how do I do this?

答:
I'm not entirely sure I have understood but if it is breaking apart and working with the constituent pieces of the array keys then perhaps this might be of use

```<code>foreach( $arr as $key => $str ){
    list( $id,$dash,$param )=explode( '-', $key );
    /* How do you wish to handle sub-arrays? */
    if( is_array( $param ) && !empty( $param ) )$param=implode(',',$param);

    /* do stuff with ID and PARAM */
}
</code>```

or, probably more like:

```<code>foreach( $arr as $key => $value ){

    list( $id, $dash, $param )=explode( '-', $key );
    if( is_array( $value ) && !empty( $value ) )$value=implode(',',$value);

    /* do stuff with ID and PARAM and value */
}
</code>```

Body:
I have made a form application in PHP and now I'm trying to implement updating the fields. I have made it so the POST contains data like this:

Array (
    '17-label' => "select label 0 ",
    '17-placeholder' => "select placeholder 0 ",
    '17-answer' => Array (
        "Answer 1",
        "Answer 2",
        "Answer 3"
    ),
    '18-label' => "textfield label 1",
    '18-placeholder' => "textfield placeholder 1",
    '19-label' => "textfield label 2",
    '19-placeholder' => "textfield placeholder 2"
)

Now as you can see I use the id of the row I want to update as the start, and then a - to identify the break and the actual column name I want to update in the column.

But how do I do this?

I know how to update, it is just, how to make sure everything goes to the right column. The first number is the id, and after the - sign it is the actual column name. But how do I do this?

Body:
I'm not entirely sure I have understood but if it is breaking apart and working with the constituent pieces of the array keys then perhaps this might be of use

foreach( $arr as $key => $str ){
    list( $id,$dash,$param )=explode( '-', $key );
    /* How do you wish to handle sub-arrays? */
    if( is_array( $param ) && !empty( $param ) )$param=implode(',',$param);

    /* do stuff with ID and PARAM */
}

or, probably more like:

foreach( $arr as $key => $value ){

    list( $id, $dash, $param )=explode( '-', $key );
    if( is_array( $value ) && !empty( $value ) )$value=implode(',',$value);

    /* do stuff with ID and PARAM and value */
}


问:
C++ - Different concurrent behavious when using locals and globals
Given this program:

```<code>#include <thread>
#include <iostream>
#include <atomic>
template<typename T>
struct node
{
    T data;
    node* next;
    node(const T& data) : data(data), next(nullptr) {}
};

template<typename T>
class stack {
    std::atomic<node<T>*> head;
 public:
    void push(const T& data) {
      node<T>* new_node = new node<T>(data);
      new_node->next = head.load();
      while(!head.compare_exchange_weak(new_node->next, new_node));
    }
    node<T>* get_head() {
        return head;
    }
};

stack<int> x;
int main() {
    std::cout << "main() starts" << std::endl;
    const int MAKS_OP = 100;
    std::thread t1{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 1 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    std::thread t2{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 2 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    t1.join();
    t2.join();

    for (auto nod = x.get_head(); nod != nullptr; nod = nod->next) {
        std::cout << nod->data << "\n";
    }
    std::cout << "main() completes\n";
}
</code>```

The code is more or less appropriated from here.
In its current state it behaves exactly as expected, both threads push numbers to the stack in an unspecified order, and the stack is then printed in the correct order. It works whether or not I specify the default lambda capture for threads. However, when I move the declaration of stack x into main(), the program runs into a segfault when printing the contents of the stack. GDB tells me that it happens when accessing nod->data in the loop at the end, and running info locals crashes gdb. What is going on? Why does it even make a difference?

答:
I am not sure but, where in your code head member is initialized ?
When you create object as global variable (above main function) head will have 0 value, but when you create your stack object in main function as local variable, head will contain junk data - random value.

About default constructor from cppreference.com

1) The default constructor is trivial: no initialization takes place other than zero initialization of static and thread-local objects. std::atomic_init may be used to complete initialization.

Body:
Given this program:

#include <thread>
#include <iostream>
#include <atomic>
template<typename T>
struct node
{
    T data;
    node* next;
    node(const T& data) : data(data), next(nullptr) {}
};

template<typename T>
class stack {
    std::atomic<node<T>*> head;
 public:
    void push(const T& data) {
      node<T>* new_node = new node<T>(data);
      new_node->next = head.load();
      while(!head.compare_exchange_weak(new_node->next, new_node));
    }
    node<T>* get_head() {
        return head;
    }
};

stack<int> x;
int main() {
    std::cout << "main() starts" << std::endl;
    const int MAKS_OP = 100;
    std::thread t1{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 1 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    std::thread t2{[&]{
        for (int i = 0; i < MAKS_OP; ++i) {
            x.push(i);
            std::string s = "Thread 2 added ";
            s += std::to_string(i);
            s += " to the stack!\n";
            std::cout << s;
        }
    }};
    t1.join();
    t2.join();

    for (auto nod = x.get_head(); nod != nullptr; nod = nod->next) {
        std::cout << nod->data << "\n";
    }
    std::cout << "main() completes\n";
}

The code is more or less appropriated from here.
In its current state it behaves exactly as expected, both threads push numbers to the stack in an unspecified order, and the stack is then printed in the correct order. It works whether or not I specify the default lambda capture for threads. However, when I move the declaration of stack x into main(), the program runs into a segfault when printing the contents of the stack. GDB tells me that it happens when accessing nod->data in the loop at the end, and running info locals crashes gdb. What is going on? Why does it even make a difference?


问:
Are unit-test names important?
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

```<code>[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
</code>```

verse

```<code>[Test]
public void UserNameTestValidation1() {}
</code>```

答:
Yes, the names are totally important, specially when you are running the tests in console or continuous integration servers. Jay Fields wrote a post about it.

Moreover, put good test names with one assertion per test and your suite will give you great reports when a test fails.

OwnerDisplayName: Xian

ContentLicense: CC BY-SA 2.5

Title: Are unit-test names important?

Body:
If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?

ie

[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}

verse

[Test]
public void UserNameTestValidation1() {}

OwnerDisplayName: marcospereira


问:
Export a dynamic array from a React component to another component
I built a react component that imports a Json file into an array to map the result. I need that array in another component. I don't know if I must built this component inside the new component or if there's a method to export the needed array (data). The array source is updated every 4 seconds.

Thanks for your help.

My first component is:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class Ramas extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    componentDidMount() {
        const fetchData = () => {
            axios
            .get('http://localhost:8888/dp_8/fuente/procesos_arbol.json')
            .then(({ data })=> {
                this.setState({
                    data: data
                });
                console.log(data);
            })
            .catch(()=> {console.log('no recibido');});
        };
        fetchData();
        this.update = setInterval(fetchData, 4000);
    } //  final componentDidMount

    render() {
        const initialData = this.state.data.map((el) => {
            return (
        <p>id={ el.id } | name - { el.name } | padre - {el.parent}</p>
      );
        });

        return (<div className="datos_iniciales">
      { initialData }
      </div>);
    }

}

ReactDOM.render(
  <Ramas />,
  document.getElementById('container')
);
</code>```

答:
If you have parent component, you should pass function from it to this component as a prop.
That function will than set state and data will flow one way as it's imagined with ReactJS.

For example instead of this.setState, you could call
this.props.jsonToArray
and in jsonToArray you should call setState which will pass data to that seccond component.

Body:
I built a react component that imports a Json file into an array to map the result. I need that array in another component. I don't know if I must built this component inside the new component or if there's a method to export the needed array (data). The array source is updated every 4 seconds.

Thanks for your help.

My first component is:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class Ramas extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    componentDidMount() {
        const fetchData = () => {
            axios
            .get('http://localhost:8888/dp_8/fuente/procesos_arbol.json')
            .then(({ data })=> {
                this.setState({
                    data: data
                });
                console.log(data);
            })
            .catch(()=> {console.log('no recibido');});
        };
        fetchData();
        this.update = setInterval(fetchData, 4000);
    } //  final componentDidMount

    render() {
        const initialData = this.state.data.map((el) => {
            return (

id={ el.id } | name - { el.name } | padre - {el.parent}

      );
        });

        return (

      { initialData }

);
    }

}

ReactDOM.render(
  <Ramas />,
  document.getElementById('container')
);


问:
NSubstitute: Mock method is not returning expected result
I'm new to NSubstitute, mocking, and unit testing in general.

I'm trying to use NSubstitute to remove some dependencies I have in my class under test, but methods in the mock objects are not behaving as I expect based on how I configured them. Here is an example I created in Visual Studio:

Interface and concrete class to be substituted. Notice, MyConcreteClass.MyMethod() returns false:

```<code>public interface IMyInterface
{
    bool MyMethod(string arg);
}

public class MyConcreteClass : IMyInterface
{
    public bool MyMethod(string arg)
    {
        return false;
    }
}
</code>```

My class under test:

```<code>public class MyTestedClass
{
    private IMyInterface _concrete;

    public MyTestedClass()
    {
        _concrete = new MyConcreteClass();
    }

    public MyTestedClass(IMyInterface mock)
    {
        _concrete = mock;
    }

    public bool MyConcreteMethod(string arg)
    {
        return _concrete.MyMethod(arg);
    }
}
</code>```

My unit test class for MyTestedClass:

```<code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void Given_MyMethodIsUsingAMock_ShouldReturnTrue()
    {
        // Arrange
        var myMock = Substitute.For<IMyInterface>();
        myMock.MyMethod("blah").Returns(true);
        var myTestedObject = new MyTestedClass(myMock);

        // Act
        var result = myTestedObject.MyConcreteMethod("blah blah");

        // Assert
        Assert.AreEqual(result, true); // This assertion fails!
    }

    [TestMethod]
    public void Given_MyMethodIsNotMock_ShouldReturnFalse()
    {
        // Arrange
        var myTestedObject = new MyTestedClass();

        // Act
        var result = myTestedObject.MyConcreteMethod("blah blah");

        // Assert
        Assert.AreEqual(result, false); // This assertion passes.
    }
}
</code>```

Test results show that Given_MyMethodIsUsingAMock_ShouldReturnTrue() fails:

```<code>MyUnitTests (2 tests) [0:00.190] Failed: 1 test failed
 MyUnitTests (2 tests) [0:00.190] Failed: 1 test failed
  UnitTest1 (2 tests) [0:00.190] Failed: 1 test failed
   Given_MyMethodIsNotMock_ShouldReturnFalse [0:00.000] Success
   Given_MyMethodIsUsingAMock_ShouldReturnTrue [0:00.189] Failed
Assert.AreEqual failed. Expected:<False>. Actual:<True>.
   at MyUnitTests.UnitTest1.Given_MyMethodIsUsingAMock_ShouldReturnTrue() in "c:\MyWorkspace\projects\NSubstituteMocking\MyUnitTests\UnitTest1.cs":line 23
</code>```

It looks like I'm missing a trivial configuration, but it is eluding me.

答:
The MyMethod is arranged to return true when given "blah"

```<code>myMock.MyMethod("blah").Returns(true);
</code>```

but is then provide it with "blah blah" when being acted upon.

```<code>var result = myTestedObject.MyConcreteMethod("blah blah");
</code>```

As the expected/arranged parameter did not match, the mock did not behave as configured.

Provide the mock with what it expects to receive for it to behave as expected.

```<code>[TestMethod]
public void Given_Blah_MyConcreteMethod_ShouldReturnTrue() {
    // Arrange
    var myMock = Substitute.For<IMyInterface>();
    var arg = "blah";
    var expected = true;
    myMock.MyMethod(arg).Returns(expected);
    var myTestedObject = new MyTestedClass(myMock);

    // Act
    var actual = myTestedObject.MyConcreteMethod(arg);

    // Assert
    Assert.AreEqual(expected, actual); // This should pass
}
</code>```

Note the use of variables to store the provided and expected values so that mistakes can be reduced when exercising the test.

Body:
I'm new to NSubstitute, mocking, and unit testing in general.

I'm trying to use NSubstitute to remove some dependencies I have in my class under test, but methods in the mock objects are not behaving as I expect based on how I configured them. Here is an example I created in Visual Studio:

Interface and concrete class to be substituted. Notice, MyConcreteClass.MyMethod() returns false:

public interface IMyInterface
{
    bool MyMethod(string arg);
}

public class MyConcreteClass : IMyInterface
{
    public bool MyMethod(string arg)
    {
        return false;
    }
}

My class under test:

public class MyTestedClass
{
    private IMyInterface _concrete;

    public MyTestedClass()
    {
        _concrete = new MyConcreteClass();
    }

    public MyTestedClass(IMyInterface mock)
    {
        _concrete = mock;
    }

    public bool MyConcreteMethod(string arg)
    {
        return _concrete.MyMethod(arg);
    }
}

My unit test class for MyTestedClass:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void Given_MyMethodIsUsingAMock_ShouldReturnTrue()
    {
        // Arrange
        var myMock = Substitute.For<IMyInterface>();
        myMock.MyMethod("blah").Returns(true);
        var myTestedObject = new MyTestedClass(myMock);

        // Act
        var result = myTestedObject.MyConcreteMethod("blah blah");

        // Assert
        Assert.AreEqual(result, true); // This assertion fails!
    }

    [TestMethod]
    public void Given_MyMethodIsNotMock_ShouldReturnFalse()
    {
        // Arrange
        var myTestedObject = new MyTestedClass();

        // Act
        var result = myTestedObject.MyConcreteMethod("blah blah");

        // Assert
        Assert.AreEqual(result, false); // This assertion passes.
    }
}

Test results show that Given_MyMethodIsUsingAMock_ShouldReturnTrue() fails:

MyUnitTests (2 tests) [0:00.190] Failed: 1 test failed
 MyUnitTests (2 tests) [0:00.190] Failed: 1 test failed
  UnitTest1 (2 tests) [0:00.190] Failed: 1 test failed
   Given_MyMethodIsNotMock_ShouldReturnFalse [0:00.000] Success
   Given_MyMethodIsUsingAMock_ShouldReturnTrue [0:00.189] Failed
Assert.AreEqual failed. Expected:<False>. Actual:<True>.
   at MyUnitTests.UnitTest1.Given_MyMethodIsUsingAMock_ShouldReturnTrue() in "c:\MyWorkspace\projects\NSubstituteMocking\MyUnitTests\UnitTest1.cs":line 23

It looks like I'm missing a trivial configuration, but it is eluding me.

Body:
The MyMethod is arranged to return true when given "blah"

myMock.MyMethod("blah").Returns(true);

but is then provide it with "blah blah" when being acted upon.

var result = myTestedObject.MyConcreteMethod("blah blah");

As the expected/arranged parameter did not match, the mock did not behave as configured.

Provide the mock with what it expects to receive for it to behave as expected.

[TestMethod]
public void Given_Blah_MyConcreteMethod_ShouldReturnTrue() {
    // Arrange
    var myMock = Substitute.For<IMyInterface>();
    var arg = "blah";
    var expected = true;
    myMock.MyMethod(arg).Returns(expected);
    var myTestedObject = new MyTestedClass(myMock);

    // Act
    var actual = myTestedObject.MyConcreteMethod(arg);

    // Assert
    Assert.AreEqual(expected, actual); // This should pass
}

Note the use of variables to store the provided and expected values so that mistakes can be reduced when exercising the test.

ContentLicense: CC BY-SA 4.0


问:
Reading from InputStream and appending to String
I tried two difference approaches to read bytes from the InputStream and append the contents to a string/print the string:

1.)

```<code>buffer= new byte[32768];
   while((read= is.read(buffer))>0){
          System.out.println(new String(buffer));
    }
</code>```

2.)

```<code>     BufferedReader br = null;
     StringBuilder sb = new StringBuilder();
     String line;
     br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
               sb.append(line);
        }
      br.close();
</code>```

While the second approach works, the first approach gets only the first few bytes and stops.

Could someone please tell me what's wrong with approach 1?

Body:
I tried two difference approaches to read bytes from the InputStream and append the contents to a string/print the string:

1.)

buffer= new byte[32768];
   while((read= is.read(buffer))>0){
          System.out.println(new String(buffer));
    }

2.)

     BufferedReader br = null;
     StringBuilder sb = new StringBuilder();
     String line;
     br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
               sb.append(line);
        }
      br.close();

While the second approach works, the first approach gets only the first few bytes and stops.

Could someone please tell me what's wrong with approach 1?

Body: new BufferedReader(new InputStreamReader(is)).lines().collect(Collectors.joining("\n"));


问:
How can I add multiple TextViews inside a Button
I'm developing a calendar in which I need to show a big text inside of many cells
The button has a text that represents the number of the day how can I attach another textView inside of it?</p>

答:
You can surround the button with a FrameLayout and then add a textview within the FrameLayout. If the text doesn't show try using bringToFront()

layout:

```<code><FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:id="@+id/button_frame"
            >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_border"
            android:gravity="center"
            android:onClick="onClick"
            android:text="@string/get_more"
            android:id="@+id/get_more"
            android:stateListAnimator="@null"

        />

            <TextView
                android:id="@+id/linearTimer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_gravity="right"
                android:padding="10dp"
                android:text="123"
             >
    </FrameLayout>
</code>```

Activity:

```<code> countDownView = (TextView) findViewById(R.id.linearTimer);

 countDownView.bringToFront();
</code>```

Body:
You can surround the button with a FrameLayout and then add a textview within the FrameLayout. If the text doesn't show try using bringToFront()

layout:

<FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:id="@+id/button_frame"
            >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/button_border"
            android:gravity="center"
            android:onClick="onClick"
            android:text="@string/get_more"
            android:id="@+id/get_more"
            android:stateListAnimator="@null"

        />

            <TextView
                android:id="@+id/linearTimer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_gravity="right"
                android:padding="10dp"
                android:text="123"
             >
    </FrameLayout>

Activity:

 countDownView = (TextView) findViewById(R.id.linearTimer);

 countDownView.bringToFront();


问:
The type or namespace name could not be found
I have a C# solution with several projects in Visual Studio 2010.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application project (I'll call it "PrjForm").  There is also a third project referenced by PrjForm, which it is able to reference and use successfully.

PrjForm references PrjTest, and PrjForm has a class with a using statement:

```<code>using PrjTest;
</code>```

Reference has been correctly added

using statement is correctly in place

Spelling is correct

PrjTest builds successfully

PrjForm almost builds, but breaks on the using PrjTest; line with the error:

The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)

I've tried the following to resolve this:

Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)

Removed and re-added the reference and using statement

Recreated PrjForm from scratch

PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder

Loaded the solution on a different computer with a fresh copy of VS 2010

I have done my homework and spent far too long looking for an answer online, none of the solutions has helped yet.

What else could I try?

答:
The using statement refers to a namespace, not a project.

Make sure that you have the appropriately named namespace in your referenced project:

```<code>namespace PrjTest
{
     public class Foo
     {
          // etc...
     }
}
</code>```

Read more about namespaces on MSDN:

Using Namespaces

Body:
I have a C# solution with several projects in Visual Studio 2010.
One is a test project (I'll call it "PrjTest"), the other is a Windows Forms Application project (I'll call it "PrjForm").  There is also a third project referenced by PrjForm, which it is able to reference and use successfully.

PrjForm references PrjTest, and PrjForm has a class with a using statement:

using PrjTest;

Reference has been correctly added

using statement is correctly in place

Spelling is correct

PrjTest builds successfully

PrjForm almost builds, but breaks on the using PrjTest; line with the error:

The type or namespace name 'PrjTest' could not be found (are you missing a using directive or an assembly reference?)

I've tried the following to resolve this:

Removed Resharper (since Resharper had no trouble recognizing the referenced project, I thought it might be worth a shot)

Removed and re-added the reference and using statement

Recreated PrjForm from scratch

PrjForm currently resides inside the PrjTest folder, I tried moving it to an outside folder

Loaded the solution on a different computer with a fresh copy of VS 2010

I have done my homework and spent far too long looking for an answer online, none of the solutions has helped yet.

What else could I try?

Body:
The using statement refers to a namespace, not a project.

Make sure that you have the appropriately named namespace in your referenced project:

namespace PrjTest
{
     public class Foo
     {
          // etc...
     }
}

Read more about namespaces on MSDN:

Using Namespaces


问:
React Rendering Dynamic Inner Components
This example illustrates what i`m tryng to do.

The goal is to have a dynamic component array and render it o the screen. I`m not being able to do the rendering part.

```<code>import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'

export default class KneatModalContent extends React.Component {

constructor() {
   super();
   this.components = [MyComponent1, MyComponent2];
}

render() {
  return (
  <div className='modal-contents'>
     {this.components.map(function (component, i) {
        return <{ component } key= { i } />
     })}
  </div>
)
}
}
</code>```

I have tryed to create the array as [<MyComponent1/>, <MyComponent2/>] as well, as tryed to render as React.createElement(component, {key:i}) but still couldnt find a solution =(

答:
There is a problem in this line:

```<code>return <{ component } key= { i } />
</code>```

Component is an instance and this is JSX, when you put component in {} braces, it means you are taking it as a JavaScript variable. Write this line as:

```<code>return <Component key={i} />
</code>```

Body:
This example illustrates what i`m tryng to do.

The goal is to have a dynamic component array and render it o the screen. I`m not being able to do the rendering part.

import PropTypes from 'prop-types';
import React from 'react';
import MyComponent1 from './MyComponent1.jsx'
import MyComponent2 from './MyComponent2.jsx'

export default class KneatModalContent extends React.Component {

constructor() {
   super();
   this.components = [MyComponent1, MyComponent2];
}

render() {
  return (

     {this.components.map(function (component, i) {
        return <{ component } key= { i } />
     })}

)
}
}

I have tryed to create the array as [<MyComponent1/>, <MyComponent2/>] as well, as tryed to render as React.createElement(component, {key:i}) but still couldnt find a solution =(

Body:
There is a problem in this line:

return <{ component } key= { i } />

Component is an instance and this is JSX, when you put component in {} braces, it means you are taking it as a JavaScript variable. Write this line as:

return <Component key={i} />


问:
How do I disable webrtc and javascript in Chrome
I want to disable webrtc and javascript in Chrome I've read a few posts and the consensus is this can't be done in python with chromedriver.  Though there is little on this topic.    Is there a way around this or is this still just not possible?

I'm needing these features because it is leaking proxy location.  You could I suppose do this manually through the profiles yourself and load it.  But depending on your number of profiles.. get ready for a lot of time to do this.

答:
You could use the chrome capabilities, and open the driver with the configuration you need. On this page, there are many useful properties like "--disable-rtc-smoothness-algorithm". This is an example with Python:</p>

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--disable-javascript")
driver = webdriver.Chrome(chrome_options=chrome_options)
</code>```

Body:
You could use the chrome capabilities, and open the driver with the configuration you need. On this page, there are many useful properties like "--disable-rtc-smoothness-algorithm". This is an example with Python:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--disable-javascript")
driver = webdriver.Chrome(chrome_options=chrome_options)


问:
ExecutorService.submit(Task) vs CompletableFuture.supplyAsync(Task, Executor)
To run some stuff in parallel or asynchronously I can use either an ExecutorService: <T> Future<T> submit(Runnable task, T result); or the CompletableFuture Api:static  CompletableFuture supplyAsync(Supplier supplier, Executor executor);
(Lets assume I use in both cases the same Executor)

Besides the return type Future vs. CompletableFuture are there any remarkable differences. Or When to use what?

And what are the differences if I use the CompletableFuture API with default Executor (the method without executor)?

答:
This clarified for me the difference between future an completable future a bit more: Difference between Future and Promise

CompletableFuture is more like a promise.


问:
Select 1 image from gallery and display on multiple ImageViews
```<code>ImageView imageView = (ImageView) findViewById(R.id.Gallery);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD);

        }
    });

}
   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // When an Image is picked
    if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri imageUri = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = getContentResolver().openInputStream(imageUri);
            ImageView imageView = (ImageView) findViewById(R.id.Gallery);
            imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
        } catch (FileNotFoundException e) {
            // Handle the error
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    // Ignore the exception
                }
            }
        }
    }

}
</code>```

<p>This code works fine for adding and image to one imageView. How can i get it to be displayed in multiple imageViews by just selecting an image once instead of repeating the process for every imageView </p>

答:
```<code>How can i get it to be displayed in multiple imageViews by just selecting an image
</code>```

Create a Bitmap from the stream.

Then assign the bitmap to as much image views you want.

Body:
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, RESULT_LOAD);

        }
    });

}
   @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // When an Image is picked
    if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri imageUri = data.getData();
        InputStream imageStream = null;
        try {
            imageStream = getContentResolver().openInputStream(imageUri);
            ImageView imageView = (ImageView) findViewById(R.id.Gallery);
            imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
        } catch (FileNotFoundException e) {
            // Handle the error
        } finally {
            if (imageStream != null) {
                try {
                    imageStream.close();
                } catch (IOException e) {
                    // Ignore the exception
                }
            }
        }
    }

}

This code works fine for adding and image to one imageView. How can i get it to be displayed in multiple imageViews by just selecting an image once instead of repeating the process for every imageView

Body:
How can i get it to be displayed in multiple imageViews by just selecting an image

Create a Bitmap from the stream.

Then assign the bitmap to as much image views you want.


问:
Selenium/testNG: How to run your test based on class priority and not on your method priorily from the XML file
If have the following:

Class A
{
  Method M(priority = 2)
}

Class B
{
  Method M(priority = 1)
}
```

<p>Then <code>Class B</code> is going to be executed before <code>Class A</code>. How can I execute <code>Class A</code> first?</p>

<p>The XML file that I am using is:</p>

<pre class="lang-xml prettyprint-override"><code><classes>
  <class name="com.Users.Admin_ManageUsers_AR"/>
  <class name="com.Users.Admin_ManageUsers_AR"/>
</classes>
</code>```

答:
Use preserver-order in testng.xml file, then all classes will be executed in order provided in testng.xml</p>

```<code><test name="Regression" preserve-order="true">
<classes>
</code>```

Body:
If have the following:

Class A
{
  Method M(priority = 2)
}

Class B
{
  Method M(priority = 1)
}

Then Class B is going to be executed before Class A. How can I execute Class A first?

The XML file that I am using is:

<classes>
  <class name="com.Users.Admin_ManageUsers_AR"/>
  <class name="com.Users.Admin_ManageUsers_AR"/>
</classes>

Body:
Use preserver-order in testng.xml file, then all classes will be executed in order provided in testng.xml

<test name="Regression" preserve-order="true">
<classes>


问:
MS Visual Studio Project Dependencies disabled
I have a problem with MS Visual c++ 2002 (first .net = version 7).

When I go into 'Project Dependencies' (Build Order) all of the flags (no matter which project I select) are disabled - not greyed like 'is already dependent', but locked for changes.

This was working fine, for as long as I remember, but I need to add a DLL to my project and can't get the build order working because of this issue.

Has anyone had a similar problem? Or know where I can find a config file to write it manually?

Edit:

This problem occurs in ALL of my solutions, even older ones that haven't been changed in years.

答:
I'm not sure how to fix this in the program, but I found a way to set it up manually, if anyone else has this issue...

If you open the *.sln (solution) file into a text editor:
- At the top of the file you will see all of your projects in this format:

```<code>Microsoft Visual Studio Solution File, Format Version 7.00
Project("{XXXXXXXX-0000-XXXX-0000-SOLUTIONGUID}") = "SLN_NAME", "_path_\proj_name_1.vcproj", "{00000000-XXXX-0000-GUID-PROJECT_0001}"
EndProject
Project("{XXXXXXXX-0000-XXXX-0000-SOLUTIONGUID}") = "SLN_NAME", "_path_\proj_name_2.vcproj", "{00000000-XXXX-0000-GUID-PROJECT_0002}"
EndProject
Project("{XXXXXXXX-0000-XXXX-0000-SOLUTIONGUID}") = "SLN_NAME", "_path_\proj_name_3.vcproj", "{00000000-XXXX-0000-GUID-PROJECT_0003}"
EndProject
</code>```

Further down you will see:

```<code>GlobalSection(ProjectDependencies) = postSolution
    {00000000-XXXX-0000-GUID-PROJECT_0001}.0 = {00000000-XXXX-0000-GUID-PROJECT_0002}
    {00000000-XXXX-0000-GUID-PROJECT_0001}.1 = {00000000-XXXX-0000-GUID-PROJECT_0003}
EndGlobalSection
</code>```

Follow the Format and add the dependencies manually

Be sure to close the solution and back-up first

Body:
I'm not sure how to fix this in the program, but I found a way to set it up manually, if anyone else has this issue...

If you open the *.sln (solution) file into a text editor:
- At the top of the file you will see all of your projects in this format:

Microsoft Visual Studio Solution File, Format Version 7.00
Project("{XXXXXXXX-0000-XXXX-0000-SOLUTIONGUID}") = "SLN_NAME", "_path_\proj_name_1.vcproj", "{00000000-XXXX-0000-GUID-PROJECT_0001}"
EndProject
Project("{XXXXXXXX-0000-XXXX-0000-SOLUTIONGUID}") = "SLN_NAME", "_path_\proj_name_2.vcproj", "{00000000-XXXX-0000-GUID-PROJECT_0002}"
EndProject
Project("{XXXXXXXX-0000-XXXX-0000-SOLUTIONGUID}") = "SLN_NAME", "_path_\proj_name_3.vcproj", "{00000000-XXXX-0000-GUID-PROJECT_0003}"
EndProject

Further down you will see:

GlobalSection(ProjectDependencies) = postSolution
    {00000000-XXXX-0000-GUID-PROJECT_0001}.0 = {00000000-XXXX-0000-GUID-PROJECT_0002}
    {00000000-XXXX-0000-GUID-PROJECT_0001}.1 = {00000000-XXXX-0000-GUID-PROJECT_0003}
EndGlobalSection

Follow the Format and add the dependencies manually

Be sure to close the solution and back-up first


问:
Access Javascript Object Key with special symbol
```<code>var obj = {
a?: "abc"
}
</code>```

Want to access Key Which is Not in a valid format.

Giving me Error.

I'm accessing it like this obj.a.

and this is throwing an error.

const obj = { a?: 'aaa' }
console.log(obj.a)```

答:
This could work (not tested)</p>

```<code>obj['a?'];
</code>```

Body:
var obj = {
a?: "abc"
}

Want to access Key Which is Not in a valid format.

Giving me Error.

I'm accessing it like this obj.a.

and this is throwing an error.

const obj = { a?: 'aaa' }
console.log(obj.a)

Body:
This could work (not tested)

obj['a?'];


答:
Valid property names

Looking at the ECMAScript spec grammar, we can see that a property
name can be either an identifier name (i.e. identifiers + reserved
words), a string literal, or a numeric literal.

Identifier names are a superset of identifiers; any valid identifier
and any reserved word is a valid identifier name.

[...]

When can the quotes be omitted?

Unless an object key is a numeric literal or a valid identifier name,
you need to quote it to avoid a syntax error from being thrown. In
other words, quotes can only be omitted if the property name is a
numeric literal or a valid identifier name. Of course, if the property
name is a string literal, it’s already quoted by definition

source: https://mathiasbynens.be/notes/javascript-properties

To solve your specific issue you can use quotes:

```<code>var obj = {
'a?': "abc"
}

obj['aj']
</code>```

Full answer can be found at
https://stackoverflow.com/a/9571440/1211174

Title: Access Javascript Object Key with special symbol

Body:
Valid property names

Looking at the ECMAScript spec grammar, we can see that a property
name can be either an identifier name (i.e. identifiers + reserved
words), a string literal, or a numeric literal.

Identifier names are a superset of identifiers; any valid identifier
and any reserved word is a valid identifier name.

[...]

When can the quotes be omitted?

Unless an object key is a numeric literal or a valid identifier name,
you need to quote it to avoid a syntax error from being thrown. In
other words, quotes can only be omitted if the property name is a
numeric literal or a valid identifier name. Of course, if the property
name is a string literal, it’s already quoted by definition

source: https://mathiasbynens.be/notes/javascript-properties

To solve your specific issue you can use quotes:

var obj = {
'a?': "abc"
}

obj['aj']

Full answer can be found at
https://stackoverflow.com/a/9571440/1211174


问:
Laravel 5.5 : htmlspecialchars() expects parameter 1 to be string, array given
The below view throws the following error: htmlspecialchars() expects parameter 1 to be string, array given. Weirdly enough this code worked fine for a while before this error popped up.

(The error only comes when the following form is posted. There are no errors while the view is being loaded)

```<code>@extends($template)

@section('content')

<div class="container" style="margin-top: 50px; margin-bottom: 50px;">

    <div class="row">

        <!-- Blog Entries Column -->
        <div class="col-md-12">

            <h1 class="my-4">Report Incident
            </h1>

            <form action="{{ route('add_post') }}" method="POST" enctype="multipart/form-data">
                {{ csrf_field() }}
                <div class="form-group">
                    <label for="title">Title</label>
                    <input type="text" class="form-control {{ $errors->has('title') ? ' is-invalid' : '' }}" id="title" name="title" placeholder="Title" value="{{ old('title') }}" required>
                    <div class="invalid-feedback">
                        {{ $errors->first('title') }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="date">Date of incident</label>
                    <input type="date" class="form-control {{ $errors->has('date') ? ' is-invalid' : '' }}" id="date" name="date" required value="{{ old('date') }}">
                    <div class="invalid-feedback">
                        {{ $errors->first('date') }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="type">Incident Type</label>
                    <select class="form-control {{ $errors->has('type') ? ' is-invalid' : '' }}" id="type" name="type">
                        @foreach($types as $type => $icon)
                            @if($type == old('type'))
                                <option value="{{ $type }}" selected>{{ $type }}</option>
                            @else
                                <option value="{{ $type }}">{{ $type }}</option>
                            @endif
                        @endforeach
                    </select>
                    <div class="invalid-feedback">
                            {{ $errors->first('type') }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control {{ $errors->has('description') ? ' is-invalid' : '' }}" id="description" name="description" rows="5" required>{{ old('description') }}</textarea>
                    <div class="invalid-feedback">
                        {{ $errors->first('description') }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="images">Upload images (if any)</label>
                    <input type="file" class="form-control-file {{ $errors->has('images') ? ' is-invalid' : '' }}" id="images" name="images[]" value="{{ old('images') }}" accept=".jpg, .png" multiple>
                    <div class="invalid-feedback">
                        {{ $errors->first('images') }}
                    </div>
                </div>

                <div class="form-group">
                    <label for="province">Select Province</label>
                    <select class="form-control {{ $errors->has('province') ? ' is-invalid' : '' }}" id="province" name="province">
                        @foreach($provinces as $province)
                            @if($province == old('$province'))
                                <option value="{{ $province }}" selected>{{ $province }}</option>
                            @else
                                <option value="{{ $province }}">{{ $province }}</option>
                            @endif
                        @endforeach
                    </select>
                    <div class="invalid-feedback">
                        {{ $errors->first('province') }}
                    </div>
                </div>
                <div class="form-group">
                    <label for="pac-input">Please type in a location</label>
                    <input type="text" class="form-control {{ $errors->has('pac-input') ? ' is-invalid' : '' }}" id="pac-input" name="pac-input" placeholder="Location" value="{{ old('pac-input') }}" required>
                    <div class="invalid-feedback">
                        {{ $errors->first('pac-input') }}
                    </div>
                </div>
                <div class="form-group">
                    <label>Please select an approximate location from the map</label>
                    <div id="map" style="height: 500px; width: 100%;"></div>
                </div>
                <div class="d-inline-block">
                    <label for="lat">Latitude</label>
                    <input type="text" name="lat" id="lat" class="form-control" value="{{ old('lat') }}" readonly>
                </div>
                <div class="d-inline-block">
                    <label for="lng" style="margin-top: 10px;">Longitude</label>
                    <input type="text" name="lng" id="lng" class="form-control" value="{{ old('lng') }}" readonly>
                </div>
                <div class="form-group col-6 col-md-4">

                </div>
                <div class="form-group">
                    <br><br><input type="submit" class="btn btn-lg btn-block btn-success" value="Submit">
                </div>
            </form>

        </div>

    </div>
    <!-- /.row -->

</div>

<script>
    var map;
    function initAutocomplete(){
        console.log(document.getElementById('map'));
        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 6.870066, lng: 79.879710},
            zoom: 15
        });
        var marker = new google.maps.Marker({
            position: {
                lat: 16.870066,
                lng: 80.879710
            },
            map: map,
            draggable: true
        });

//            document.getElementById('lat').value = marker.getPosition().lat();
//            document.getElementById('lng').value = marker.getPosition().lng();

        var input = document.getElementById('pac-input');

        var searchBox = new google.maps.places.SearchBox(input);

        google.maps.event.addListener(searchBox, 'places_changed',function(){
            var places = searchBox.getPlaces();
            var bounds = new google.maps.LatLngBounds();
            var i, place;

            for (i=0; place=places[i]; i++) {
                bounds.extend(place.geometry.location);
                marker.setPosition(place.geometry.location);
            }

            map.fitBounds(bounds);
            map.setZoom(15);
        });

        google.maps.event.addListener(marker, 'position_changed', function(){
            var lat = marker.getPosition().lat();
            var lng = marker.getPosition().lng();

            document.getElementById('lat').value = lat;
            document.getElementById('lng').value = lng;
        });
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY_WAS_HERE&libraries=places&callback=initAutocomplete"
        async defer></script>

@endsection
</code>```

I think it has something to do with my declaration of my file uploads input:

```<code><div class="form-group">
                    <label for="images">Upload images (if any)</label>
                    <input type="file" class="form-control-file {{ $errors->has('images') ? ' is-invalid' : '' }}" id="images" name="images[]" value="{{ old('images') }}" accept=".jpg, .png" multiple>
                    <div class="invalid-feedback">
                        {{ $errors->first('images') }}
                    </div>
</div>
</code>```

The name I have given the following input is images[] since I want multiple images to be uploaded. When I change the name from images[] to images, the error seems to go away but no images are uploaded/saved (if needed the code to handle the backend image uploading can be posted as well).

答:
How do you expect PHP to echo an array? It can't.

Your inputs are using array naming. So on the server side images in the request is an array. So the "old" data for images is an array, not a single value. You are trying to echo an array  {{ old('images') }}.

First you can't set a value on a file input. That would be a security concern.

Second you have potentially multiple files not one, so what value are you trying to set it to? What do you think old('images') will be besides an array?

Body:
The below view throws the following error: htmlspecialchars() expects parameter 1 to be string, array given. Weirdly enough this code worked fine for a while before this error popped up.

(The error only comes when the following form is posted. There are no errors while the view is being loaded)

@extends($template)

@section('content')

Report Incident

            <form action="{{ route('add_post') }}" method="POST" enctype="multipart/form-data">
                {{ csrf_field() }}

                    Title
                    <input type="text" class="form-control {{ $errors->has('title') ? ' is-invalid' : '' }}" id="title" name="title" placeholder="Title" value="{{ old('title') }}" required>

                        {{ $errors->first('title') }}

                    Date of incident
                    <input type="date" class="form-control {{ $errors->has('date') ? ' is-invalid' : '' }}" id="date" name="date" required value="{{ old('date') }}">

                        {{ $errors->first('date') }}

                    Incident Type
                    <select class="form-control {{ $errors->has('type') ? ' is-invalid' : '' }}" id="type" name="type">
                        @foreach($types as $type => $icon)
                            @if($type == old('type'))
                                <option value="{{ $type }}" selected>{{ $type }}</option>
                            @else
                                <option value="{{ $type }}">{{ $type }}</option>
                            @endif
                        @endforeach
                    </select>

                            {{ $errors->first('type') }}

                    Description
                    <textarea class="form-control {{ $errors->has('description') ? ' is-invalid' : '' }}" id="description" name="description" rows="5" required>{{ old('description') }}</textarea>

                        {{ $errors->first('description') }}

                    Upload images (if any)
                    <input type="file" class="form-control-file {{ $errors->has('images') ? ' is-invalid' : '' }}" id="images" name="images[]" value="{{ old('images') }}" accept=".jpg, .png" multiple>

                        {{ $errors->first('images') }}

                    Select Province
                    <select class="form-control {{ $errors->has('province') ? ' is-invalid' : '' }}" id="province" name="province">
                        @foreach($provinces as $province)
                            @if($province == old('$province'))
                                <option value="{{ $province }}" selected>{{ $province }}</option>
                            @else
                                <option value="{{ $province }}">{{ $province }}</option>
                            @endif
                        @endforeach
                    </select>

                        {{ $errors->first('province') }}

                    Please type in a location
                    <input type="text" class="form-control {{ $errors->has('pac-input') ? ' is-invalid' : '' }}" id="pac-input" name="pac-input" placeholder="Location" value="{{ old('pac-input') }}" required>

                        {{ $errors->first('pac-input') }}

                    Please select an approximate location from the map

                    Latitude
                    <input type="text" name="lat" id="lat" class="form-control" value="{{ old('lat') }}" readonly>

                    Longitude
                    <input type="text" name="lng" id="lng" class="form-control" value="{{ old('lng') }}" readonly>

<input type="submit" class="btn btn-lg btn-block btn-success" value="Submit">

            </form>

@endsection

I think it has something to do with my declaration of my file uploads input:

                    Upload images (if any)
                    <input type="file" class="form-control-file {{ $errors->has('images') ? ' is-invalid' : '' }}" id="images" name="images[]" value="{{ old('images') }}" accept=".jpg, .png" multiple>

                        {{ $errors->first('images') }}

The name I have given the following input is images[] since I want multiple images to be uploaded. When I change the name from images[] to images, the error seems to go away but no images are uploaded/saved (if needed the code to handle the backend image uploading can be posted as well).


问:
Get max score and the fields in the max score row in MySQL 5.7
```<code>| id | uid  | score   | date    |
————————————————————————————————
| 1  | aaa  | 10      | 2017.7.7|

| 2  | bbb  | 5       | 2017.7.7|

| 3  | aaa  | 15      | 2017.7.7|

| 4  | bbb  | 20      | 2017.7.8|
</code>```

I want to get everyone’s max score and every row should include all fields like id and date.

```<code>| id | uid | score | date    |
—————————————————————————————
| 4  | bbb | 20    | 2017.7.8|

| 3  | aaa | 15    | 2017.7.7|
</code>```

Select max(score) as score, id, date, uid from data group by uid order by score desc

I can use this sql to get what I want in MySQL before v5.7 but you know after MySQL 5.7 there is a sql_mode ONLY_FULL_GROUP_BY. So I can’t get the result as before. I see there are some answers tell me to disable the mode. But I want to know if there are any sql can do this as well as I don’t disable the mode.

答:
i suggest you to change this property for only this query by using</p>

```<code>SET sql_mode = 'ONLY_FULL_GROUP_BY';
</code>```

Body:
| id | uid  | score   | date    |
————————————————————————————————
| 1  | aaa  | 10      | 2017.7.7|

| 2  | bbb  | 5       | 2017.7.7|

| 3  | aaa  | 15      | 2017.7.7|

| 4  | bbb  | 20      | 2017.7.8|

I want to get everyone’s max score and every row should include all fields like id and date.

| id | uid | score | date    |
—————————————————————————————
| 4  | bbb | 20    | 2017.7.8|

| 3  | aaa | 15    | 2017.7.7|

Select max(score) as score, id, date, uid from data group by uid order by score desc

I can use this sql to get what I want in MySQL before v5.7 but you know after MySQL 5.7 there is a sql_mode ONLY_FULL_GROUP_BY. So I can’t get the result as before. I see there are some answers tell me to disable the mode. But I want to know if there are any sql can do this as well as I don’t disable the mode.

Body:
i suggest you to change this property for only this query by using

SET sql_mode = 'ONLY_FULL_GROUP_BY';


问:
VTK: rotate a 3D model and capture its depth map
Currently, based on the VTK ZBuffer example, I iteratively rotate the 3D model and capture each time the depth map. The issue is that although the model rotates the output images contain all the first depth map.

```<code>int main(int argc, char *argv[]){

...variable declaration/initialization

//read off file
offReader->SetFileName(argv[1]);
offReader->Update();

int step = 30; std::string out;
for (int i = 0; i < 3; i++) {
    mapper->NewInstance();
    actor->NewInstance();
    renWin->NewInstance();
    renderer->NewInstance();

    mapper->SetInputData(polyData);
    actor->SetMapper(mapper);

    out = std::to_string(i);

    actor->RotateZ(step*i);

    renWin->AddRenderer(renderer);

    renderer->AddActor(actor);
    renderer->SetBackground(1, 1, 1);
    renWin->Render();

    // Create Depth Map
    filter->NewInstance();
    scale->NewInstance();
    imageWriter->NewInstance();

    filter->SetInput(renWin);
    filter->SetMagnification(3);
    filter->SetInputBufferTypeToZBuffer();        //Extract z buffer value
    filter->Update();

    scale->SetOutputScalarTypeToUnsignedChar();
    scale->SetInputConnection(filter->GetOutputPort());
    scale->SetShift(0);
    scale->SetScale(-255);
    scale->Update();

    std::string out1 = out + "_depth.bmp";
    std::cout << " " << out1 << std::endl;

    // Write surface map as a .bmp image
    imageWriter->SetFileName(out1.c_str());
    imageWriter->SetInputConnection(scale->GetOutputPort());
    imageWriter->Update();
    imageWriter->Write();

    filter->RemoveAllInputs();
    scale->RemoveAllInputs();
    imageWriter->RemoveAllInputs();
    renderer->RemoveActor(actor);
    renWin->RemoveRenderer(renderer);

    .... remaining script

}
</code>```

The output depth maps are all identical. 0_depth.bmp, 1_depth.bmp & 2_depth.bmp

Has anyone encountered the same issue? If yes, what could be a potential solution.

答: Problem solved by introducing a function within the rotation took place. Apparently it was a matter of a variable content update issue, that could be solved in a more straight forward way. </p>

Body:
Currently, based on the VTK ZBuffer example, I iteratively rotate the 3D model and capture each time the depth map. The issue is that although the model rotates the output images contain all the first depth map.

int main(int argc, char *argv[]){

...variable declaration/initialization

//read off file
offReader->SetFileName(argv[1]);
offReader->Update();

int step = 30; std::string out;
for (int i = 0; i < 3; i++) {
    mapper->NewInstance();
    actor->NewInstance();
    renWin->NewInstance();
    renderer->NewInstance();

    mapper->SetInputData(polyData);
    actor->SetMapper(mapper);

    out = std::to_string(i);

    actor->RotateZ(step*i);

    renWin->AddRenderer(renderer);

    renderer->AddActor(actor);
    renderer->SetBackground(1, 1, 1);
    renWin->Render();

    // Create Depth Map
    filter->NewInstance();
    scale->NewInstance();
    imageWriter->NewInstance();

    filter->SetInput(renWin);
    filter->SetMagnification(3);
    filter->SetInputBufferTypeToZBuffer();        //Extract z buffer value
    filter->Update();

    scale->SetOutputScalarTypeToUnsignedChar();
    scale->SetInputConnection(filter->GetOutputPort());
    scale->SetShift(0);
    scale->SetScale(-255);
    scale->Update();

    std::string out1 = out + "_depth.bmp";
    std::cout << " " << out1 << std::endl;

    // Write surface map as a .bmp image
    imageWriter->SetFileName(out1.c_str());
    imageWriter->SetInputConnection(scale->GetOutputPort());
    imageWriter->Update();
    imageWriter->Write();

    filter->RemoveAllInputs();
    scale->RemoveAllInputs();
    imageWriter->RemoveAllInputs();
    renderer->RemoveActor(actor);
    renWin->RemoveRenderer(renderer);

    .... remaining script

}

The output depth maps are all identical. 0_depth.bmp, 1_depth.bmp & 2_depth.bmp

Has anyone encountered the same issue? If yes, what could be a potential solution.


问:
Xcode throws an exception in Main() in iOS 8 with 'all exceptions' breakpoint
I am using Xcode 6 (GM, I didn't download betas), and I am developing apps for iOS 7+. For all my projects, I just opened the same projects I used to work on in Xcode 5.

In the Breakpoint navigator, I have the All Exceptions breakpoint on. It is set to Break: On Throw. Now, each time I run my app (whether on a device or in simulator), it stops execution on the line return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); in the main() function.

If I press Play to continue program execution twice, the program runs fine. So this doesn't prevent me from working, but it is annoying to have to manually play the execution each time and reset my editors.

I like the behaviors I have set up in Xcode (taking the current editor to where the execution has paused), and having that All Exceptions breakpoint is important IMO. (So I don't want to change those)

By running the same code, with the same environnements, for an iOS 7 target (again, device or simulator), the exception is not thrown.

Any clue what could cause this strange behavior?

答:
Xcode 9, sometimes there are exceptions that are thrown but iOS is catching it gracefully. This will help

source

for my case, it was a user-defined attribute in nib


问:
Place IF ELSE statement inside Woocommerce product loop - Wordpress
I've got the following custom shortcode to display a range of products

```<code>add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

while ( $products->have_posts() ) : $products->the_post();

wc_get_template_part( 'content', 'product' );

endwhile;

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '<div class="on-sale">' . ob_get_clean() . '</div>';
}
</code>```

I am trying to add a text message inside the loop that will say "No products to display" if there no products to show.

I'm struggling to correctly place the statement without getting a syntax error.

I've been fiddling around with the code like this:

```<code>add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

if ( $products->have_posts() ) : $products->the_post() {

   wc_get_template_part( 'content', 'product' );

} else {

   echo '<div class="no-products">There are no products to display</div>';
}

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '<div class="on-sale">' . ob_get_clean() . '</div>';
}
</code>```

But that's not correct.

Could you please point me to the right direction?

答:
Try this example,

```<code>function newsItems( $atts ) {
$news_query= null;
$args = array(
  'post_type'      => 'news',
  'post_status'    => 'publish',
  'posts_per_page' => 10,
);

$news_query = new WP_Query( $args );
$output = '';
if ( $news_query->have_posts() ) {
  $output .= '<div class="news-shortcode-posts">';
  while ( $news_query->have_posts() ) : $news_query->the_post();
      ob_start();
      get_template_part( 'inc/news-item' );
      $output .= ob_get_clean();
  endwhile;
  if( $show_archive == 'true' ) {
      $output .= '<div class="full-width align-right">';
      $output .= 'See All Archives';
      $output .= '</div>';
  }
  $output .= '</div>';
  }
  return $output;
}
add_shortcode('teamsters-news', 'newsItems');
</code>```

Hope this will helps you. for more information.

Using WordPress get_template_part in Shortcode Loop

get_template_part from inside a shortcode function

Body:
I've got the following custom shortcode to display a range of products

add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

while ( $products->have_posts() ) : $products->the_post();

wc_get_template_part( 'content', 'product' );

endwhile;

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '
' . ob_get_clean() . '
';
}

I am trying to add a text message inside the loop that will say "No products to display" if there no products to show.

I'm struggling to correctly place the statement without getting a syntax error.

I've been fiddling around with the code like this:

add_shortcode( 'my_shortcode_name', 'on_sale_products' );

function on_sale_products() {
global $product, $woocommerce, $woocommerce_loop;

$args = apply_filters('woocommerce_related_products_args', array(
       // this is working array, just empty for this example
       )
);
$products = new WP_Query( $args );

ob_start();

woocommerce_product_loop_start();

if ( $products->have_posts() ) : $products->the_post() {

   wc_get_template_part( 'content', 'product' );

} else {

   echo '
There are no products to display
';
}

woocommerce_product_loop_end();

woocommerce_reset_loop();
wp_reset_postdata();

return '
' . ob_get_clean() . '
';
}

But that's not correct.

Could you please point me to the right direction?

Body:
Try this example,

function newsItems( $atts ) {
$news_query= null;
$args = array(
  'post_type'      => 'news',
  'post_status'    => 'publish',
  'posts_per_page' => 10,
);

$news_query = new WP_Query( $args );
$output = '';
if ( $news_query->have_posts() ) {
  $output .= '<div class="news-shortcode-posts">';
  while ( $news_query->have_posts() ) : $news_query->the_post();
      ob_start();
      get_template_part( 'inc/news-item' );
      $output .= ob_get_clean();
  endwhile;
  if( $show_archive == 'true' ) {
      $output .= '<div class="full-width align-right">';
      $output .= 'See All Archives';
      $output .= '</div>';
  }
  $output .= '</div>';
  }
  return $output;
}
add_shortcode('teamsters-news', 'newsItems');

Hope this will helps you. for more information.

Using WordPress get_template_part in Shortcode Loop

get_template_part from inside a shortcode function


问:
How to put a background image in a 2nd Frame?
I need help. I need to bring out the image background to my new created frame in genkeymenu function. But the problem is, once the frame is created, the image background only seems to change in the first created frame. I tried to search for solutions but nothing works. Can I ask what's the problem?</p>

```<code>import Tkinter as tk
from Tkinter import *
from PIL import Image, ImageTk

def genkeymenu():
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = Label(image=bg1)
    background_label.place(x=0, y=0)
    background_label.image = bg1

    keynamelabel = Label(generatemenu, text="Enter your key name")

    keynameEntry = Entry(generatemenu)

    keynameButton = Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    tk.background_label.grid(row=0)

    keynamelabel.grid(row=0)
    keynameEntry.grid(row=1)
    keynameButton.grid(row=2)

    check1024.grid(row=3, column=0)
    check2048.grid(row=3, column=1)
    check4096.grid(row=3, column=2)

    generatemenu.title("Generate Key")
    generatemenu.mainloop()

mainmenu = tk.Tk()

bg = ImageTk.PhotoImage(file="key.jpg")
background_label = Label(image=bg)
background_label.place(x=0, y=0)

genkeybutton = Button(mainmenu, text= "Generate Key Pair", fg="black", command=genkeymenu)
encryptbutton = Button(mainmenu, text= "Encrypt your message", fg="black")
decryptbutton = Button(mainmenu, text= "Decrypt your message", fg="black")

background_label.grid(row=0)

genkeybutton.grid(row=0, column=0, sticky = N, rowspan=2)

encryptbutton.grid(row=0, column=0)

decryptbutton.grid(row=0, column=0, sticky=S)

mainmenu.title("RSA ENCRYPTION")
mainmenu.mainloop()
</code>```

答:
You specify all the widget to appear in the toplevel window but didn't do that for the background. background_label = Label(generatemenu, image=bg1)

```<code>import Tkinter as tk
from Tkinter import *
PIL import Image, ImageTk

def genkeymenu():
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = Label(generatemenu, image=bg1)# specify the window you it to appear.
    background_label.place(x=0, y=0)
    background_label.image = bg1

    keynamelabel = Label(generatemenu, text="Enter your key name")

    keynameEntry = Entry(generatemenu)

    keynameButton = Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    tk.background_label.grid(row=0)

    keynamelabel.grid(row=0)
    keynameEntry.grid(row=1)
    keynameButton.grid(row=2)

    check1024.grid(row=3, column=0)
    check2048.grid(row=3, column=1)
    check4096.grid(row=3, column=2)

    generatemenu.title("Generate Key")
    generatemenu.mainloop()

mainmenu = tk.Tk()

bg = ImageTk.PhotoImage(file="key.jpg")
background_label = Label(image=bg)
background_label.place(x=0, y=0)

genkeybutton = Button(mainmenu, text= "Generate Key Pair", fg="black",
command=genkeymenu)
encryptbutton = Button(mainmenu, text= "Encrypt your message", fg="black")
decryptbutton = Button(mainmenu, text= "Decrypt your message", fg="black")

background_label.grid(row=0)

genkeybutton.grid(row=0, column=0, sticky = N, rowspan=2)

encryptbutton.grid(row=0, column=0)

decryptbutton.grid(row=0, column=0, sticky=S)

mainmenu.title("RSA ENCRYPTION")
mainmenu.mainloop()
</code>```

Body:
I need help. I need to bring out the image background to my new created frame in genkeymenu function. But the problem is, once the frame is created, the image background only seems to change in the first created frame. I tried to search for solutions but nothing works. Can I ask what's the problem?

import Tkinter as tk
from Tkinter import *
from PIL import Image, ImageTk

def genkeymenu():
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = Label(image=bg1)
    background_label.place(x=0, y=0)
    background_label.image = bg1

    keynamelabel = Label(generatemenu, text="Enter your key name")

    keynameEntry = Entry(generatemenu)

    keynameButton = Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    tk.background_label.grid(row=0)

    keynamelabel.grid(row=0)
    keynameEntry.grid(row=1)
    keynameButton.grid(row=2)

    check1024.grid(row=3, column=0)
    check2048.grid(row=3, column=1)
    check4096.grid(row=3, column=2)

    generatemenu.title("Generate Key")
    generatemenu.mainloop()

mainmenu = tk.Tk()

bg = ImageTk.PhotoImage(file="key.jpg")
background_label = Label(image=bg)
background_label.place(x=0, y=0)

genkeybutton = Button(mainmenu, text= "Generate Key Pair", fg="black", command=genkeymenu)
encryptbutton = Button(mainmenu, text= "Encrypt your message", fg="black")
decryptbutton = Button(mainmenu, text= "Decrypt your message", fg="black")

background_label.grid(row=0)

genkeybutton.grid(row=0, column=0, sticky = N, rowspan=2)

encryptbutton.grid(row=0, column=0)

decryptbutton.grid(row=0, column=0, sticky=S)

mainmenu.title("RSA ENCRYPTION")
mainmenu.mainloop()

Body:
You specify all the widget to appear in the toplevel window but didn't do that for the background. background_label = Label(generatemenu, image=bg1)

import Tkinter as tk
from Tkinter import *
PIL import Image, ImageTk

def genkeymenu():
    generatemenu = tk.Toplevel(mainmenu)

    bg1 = ImageTk.PhotoImage(file="key2.jpg")
    background_label = Label(generatemenu, image=bg1)# specify the window you it to appear.
    background_label.place(x=0, y=0)
    background_label.image = bg1

    keynamelabel = Label(generatemenu, text="Enter your key name")

    keynameEntry = Entry(generatemenu)

    keynameButton = Button(generatemenu, text="Enter")

    check1024= Checkbutton(generatemenu, text="1024 bit")
    check2048= Checkbutton(generatemenu, text="2048 bit")
    check4096= Checkbutton(generatemenu, text="4096 bit")

    tk.background_label.grid(row=0)

    keynamelabel.grid(row=0)
    keynameEntry.grid(row=1)
    keynameButton.grid(row=2)

    check1024.grid(row=3, column=0)
    check2048.grid(row=3, column=1)
    check4096.grid(row=3, column=2)

    generatemenu.title("Generate Key")
    generatemenu.mainloop()

mainmenu = tk.Tk()

bg = ImageTk.PhotoImage(file="key.jpg")
background_label = Label(image=bg)
background_label.place(x=0, y=0)

genkeybutton = Button(mainmenu, text= "Generate Key Pair", fg="black",
command=genkeymenu)
encryptbutton = Button(mainmenu, text= "Encrypt your message", fg="black")
decryptbutton = Button(mainmenu, text= "Decrypt your message", fg="black")

background_label.grid(row=0)

genkeybutton.grid(row=0, column=0, sticky = N, rowspan=2)

encryptbutton.grid(row=0, column=0)

decryptbutton.grid(row=0, column=0, sticky=S)

mainmenu.title("RSA ENCRYPTION")
mainmenu.mainloop()