text:
Q: Layering images with Bootstrap I'm attempting to create the following (mockup) with Bootstrap
https://i.stack.imgur.com/vkgBu.jpg
The idea is that each of those squares is an image and I'll have Javascript control when they appear/disappear when the background image is clicked. What I'm having trouble with is getting the little squares to stack on top like I have it. I've done research here, tried a bunch of things on my own, but get close but no cigar.
This is the closest I've come (testing with 1 row first).
https://i.stack.imgur.com/mqTc1.jpg
The squares line up next to eachother pretty well however they aren't showing within the same grid column/row correctly.
Relevant HTML:

CSS:
.character-img{
    position: relative;
    z-index: 10;
}

.stock-img{
    position: relative;
    z-index: 20;
}

EDIT:
Updated version yields slightly better results? Included adding the blue boxes to the second row.
HTML

CSS
.character-img{
position: relative;
z-index: 10;
}

.stock-img{
position: relative;
z-index: 20;
}

Result: https://imgur.com/vd3IZsP

A: Based on the images you've shown us to depict your desired outcome, I think Bootstrap is a smart choice. Much of what you want to do in your layout can be achieved using native classes.  But it's also pretty apparent that you lack a fundamental understanding of the Bootstrap Framework, and I would strongly encourage you to revisit their documentation.
A full example of the structure you're trying to achieve can be viewed at: https://www.bootply.com/SwuSKmlKWe
But let's look at the HTML of a single 'box' item:

The first
 element is a column wrapper that supplies information on the breakpoints that will affect the display.  From left to right it is written with the smallest breakpoint (col-*) to the largest.  If we were to translate this to something readable it might read:

At the smallest breakpoint use 6/12 columns. At the medium breakpoint
  begin using 4/12 columns, and at the large breakpoint use 3/12
  columns.

Note: col-sm-* exists but was not used here. Because a 'small' breakpoint was not used Bootstrap will default to the next smallest (in this case col-6
Inside the column wrapper we have another wrapper with several classes:

*

*.h-100 helps us create equal-height items regardless of whether the
content dictates a smaller height.

*.bg-secondary is a utility class that provides the dark background color

*.p-4 is a utility class that provides padding on both the X and Y margins (4 indicates the 'level' of padding and can be as low as 0 and as high as 5)

At this point we start seeing the actual content.  Your primary image has several classes that affect its shape and its position:

*

*.rounded-circle is an image thumbnail class that forces a circular border radius.

*.img-fluid is a responsive class that helps the image size up and down proportional to the element in which it resides.

*.d-block transforms the img into a block-level element

*.mx-auto sets the X margins to 'auto' which, in combination with d-block, centers the image.

From here we reach the 8 button/images referenced in your original post. The Bootstrap Grid is the perfect solution for this sort of organization, but since we're already working with content inside a Grid Element we need to create a new .row.
Inside the new .row we have a single breakpoint column (.col-3) with a couple of utility classes: text-center centers the content and mb-2 sets the bottom margin in a similar way that the p-* utility class alters padding.


text:
Q: 'getaddrinfo' makes pointer from integer without a cast [enabled by default] My program has the following warning because of which I think there is a core dump segmentation fault error showing up:
warning: passing argument 2 of 'getaddrinfo' makes pointer from integer without a cast [enabled by default]

rc = getaddrinfo(svrHost, svrPort, &hints, &res);
                           ^
In file included from client6_main.c:16:0:
/usr/include/netdb.h:662:12: note: expected 'const char * restrict' but argument is of type 'short unsigned int'
extern int getaddrinfo (const char *__restrict __name,

The code segment is:
rc = getaddrinfo(svrHost, svrPort, &hints, &res);

if(rc != 0){
    printf("Host not found --> %s\n", gai_strerror(rc));
    if (rc == EAI_SYSTEM)
        perror("getaddrinfo() failed");
}

Please guide

A: You need to put the service name or the port number as a decimal string as second parameter of the getaddrinfo call.
For that, just change the type of the variable svrPort from unsigned short to  char* or char const*, and make it point to a valid string.
For example, "http" or "80" instead of 80.

A: The first two function arguments are expected to be pointers to strings.
int getaddrinfo(const char *node,
                const char *service,
                const struct addrinfo *hints,
                struct addrinfo **res);

I assume from the warning you got that svrPort is of type int.
The compiler will treat this in as a pointer. If svrPort is initialized to 1234 then the function will lookup a string starting at address 1234 which may or may not be a valid address.
You should probably pass NULL or 0 to tell getaddrinfo to ignore this argument.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql 5.7 equivalent to Mongos $elemMatch Is there a way of querying an array of objects in MySQL 5.7 JSON datatype that is the equivalent of Mongos $elemMatch?
For example, if I had the following document saved in a MySQL JSON column
{
  fields: [
    {
      key: 'age',
      value: 20
    },
    {
      key: 'years_employed',
      value: 10
    }
  ]
}

In Mongo, I could use
.find({fields: {$elemMatch: {key:'age', value:20}}})

This would return any documents that contain a fields array containing an object having parameters that match both key and value. The above would return the example document, however the following would return nothing:
.find({fields: {$elemMatch: {key:'age', value:10}}})

I'm looking to find the same functionality in MySQL 5.7.

A: Given the following JSON snippet in a JSON column named data in a table named data_table,
{
  fields: [
    {
      key: 'age',
      value: 20
    },
    {
      key: 'years_employed',
      value: 10
    }
  ]
}

you would use the JSON_CONTAINS function, like in the following SQL statement, to select rows that match a specific 'age'
SELECT * FROM `data_table` WHERE JSON_CONTAINS(`data`, '{"key":"age","value":20}', "$.fields")

I tested this on MySQL 5.7.17


text:
Q: Marshaling a message table resource I need to read a Message Table resource in C#.
I'm basically trying to port to C# the code in the answer to this question: Listing message IDs and symbolic names stored in a resource-only library (DLL) using Win32 API
My problem is that I cannot correctly marshal the MESSAGE_RESOURCE_DATA and MESSAGE_RESOURCE_BLOCK structures, which are defined like this (in <winnt.h>):
typedef struct _MESSAGE_RESOURCE_BLOCK {
    DWORD LowId;
    DWORD HighId;
    DWORD OffsetToEntries;
} MESSAGE_RESOURCE_BLOCK, *PMESSAGE_RESOURCE_BLOCK;

typedef struct _MESSAGE_RESOURCE_DATA {
    DWORD NumberOfBlocks;
    MESSAGE_RESOURCE_BLOCK Blocks[ 1 ];
} MESSAGE_RESOURCE_DATA, *PMESSAGE_RESOURCE_DATA;

In MESSAGE_RESOURCE_DATA, NumberOfBlocks is the number of MESSAGE_RESOURCE_BLOCK entries in the Blocks array (even if it is declared as an array with a single element).
Since I do not know at compile time the array size, I tried to marshal the struct declaring Blocks as a pointer, and then using Marshal.PtrToStructure like this:
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
struct MESSAGE_RESOURCE_BLOCK {
    public IntPtr LowId;
    public IntPtr HighId;
    public IntPtr OffsetToEntries;
}

[StructLayout(LayoutKind.Sequential)]
struct MESSAGE_RESOURCE_DATA {
    public IntPtr NumberOfBlocks;
    public IntPtr Blocks;
}

class Program {

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr LoadLibrary(string fileName);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr FindResource(IntPtr hModule, int lpID, int lpType);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);

    [DllImport("kernel32.dll")]
    public static extern IntPtr LockResource(IntPtr hResData);

    static void Main(string[] args) {
        const int RT_MESSAGETABLE = 11;
        IntPtr hModule = LoadLibrary(@"C:\WINDOWS\system32\msobjs.dll");
        IntPtr msgTableInfo = FindResource(hModule, 1, RT_MESSAGETABLE);
        IntPtr msgTable = LoadResource(hModule, msgTableInfo);
        var data = Marshal.PtrToStructure<MESSAGE_RESOURCE_DATA>(LockResource(msgTable));
        int blockSize = Marshal.SizeOf<MESSAGE_RESOURCE_BLOCK>();
        for (int i = 0; i < data.NumberOfBlocks.ToInt32(); i++) {
            IntPtr blockPtr = IntPtr.Add(data.Blocks, blockSize * i);
            // the following line causes an access violation
            var block = Marshal.PtrToStructure<MESSAGE_RESOURCE_BLOCK>(blockPtr);
        }
    }
}

This does not work, however, and I'm getting an access violation error.
How can I marshal a structure like this?

A: You are not close, these structures do not contain IntPtr.  DWORD is a 32-bit integer.  The variable-length structures used in resource formats are very awkward in C#, there is no decent way to declare them.  Best thing to do is to use Marshal.ReadXxx() to read the fields.
The only struct declaration that's still useful is:
[StructLayout(LayoutKind.Sequential)]
struct MESSAGE_RESOURCE_BLOCK {
    public int LowId;
    public int HighId;
    public int OffsetToEntries;
}

And then you slug it out like this:
static void Main(string[] args) {
    const int RT_MESSAGETABLE = 11;
    IntPtr hModule = LoadLibrary(@"C:\WINDOWS\system32\msobjs.dll");
    IntPtr msgTableInfo = FindResource(hModule, 1, RT_MESSAGETABLE);
    IntPtr msgTable = LoadResource(hModule, msgTableInfo);
    IntPtr memTable = LockResource(msgTable);

    int numberOfBlocks = Marshal.ReadInt32(memTable);
    IntPtr blockPtr = IntPtr.Add(memTable, 4);
    int blockSize = Marshal.SizeOf<MESSAGE_RESOURCE_BLOCK>();

    for (int i = 0; i < numberOfBlocks; i++) {
        var block = Marshal.PtrToStructure<MESSAGE_RESOURCE_BLOCK>(blockPtr);
        IntPtr entryPtr = IntPtr.Add(memTable, block.OffsetToEntries);

        for (int id = block.LowId; id <= block.HighId; id++) {
            var length = Marshal.ReadInt16(entryPtr);
            var flags = Marshal.ReadInt16(entryPtr, 2);
            var textPtr = IntPtr.Add(entryPtr, 4);
            var text = "Bad flags??";
            if (flags == 0) {
                text = Marshal.PtrToStringAnsi(textPtr);
            }
            else if (flags == 1) {
                text = Marshal.PtrToStringUni(textPtr);
            }
            text = text.Replace("\r\n", "");
            Console.WriteLine("{0} : {1}", id, text);
            entryPtr = IntPtr.Add(entryPtr, length);
        }
        blockPtr = IntPtr.Add(blockPtr, blockSize);
    }
}

Output in both 32-bit and 64-bit mode:
279 : Undefined Access (no effect) Bit 7
1536 : Unused message ID
1537 : DELETE
1538 : READ_CONTROL
1539 : WRITE_DAC
1540 : WRITE_OWNER
1541 : SYNCHRONIZE
1542 : ACCESS_SYS_SEC
1543 : MAX_ALLOWED
1552 : Unknown specific access (bit 0)
1553 : Unknown specific access (bit 1)
1554 : Unknown specific access (bit 2)
1555 : Unknown specific access (bit 3)
1556 : Unknown specific access (bit 4)
1557 : Unknown specific access (bit 5)
...etc...

Do keep in mind that you will not be reading the file you think you are when you use the jitter forcing to run the program in 32-bit mode.  The file system redirector will get you to read C:\WINDOWS\SysWow64\msobjs.dll instead.


text:
Q: how to create dynamic fields on the basis of user select dropdown value What I am trying to do is in my below code when I am select the dropdown list value then the dynamic field is open like text filed select field etc. And when I change the dropdown list value then the new field is open like upload file field text field etc. but in my below code is not working.
How can we do that using HTML CSS JavaScript jQuery?

function addElement() {
    var element = document.createElement("input");
    element.setAttribute("value", "");
    element.setAttribute("name", "newInput");
    var foo = document.getElementById("newAdd");
    foo.appendChild(element);
}
function addInput(){
    document.getElementById("newAdd").innerHTML="";
     var noInp=parseInt(document.getElementById("formName9").value);
        while(noInp>0)
        {
        addElement();
            noInp--;
        }
    }
<select id="formName9" name="blockUnits" onchange="return addInput()">

 <option value="">select field</option>
 <option value="4">apple four field</option>
 <option value="2">banana two filed</option>
 <option value="6">grapes six field</option>
 <option value="1">apple 1 field</option>
 <option value="4">guava four field</option>
 <option value="8">lichi eight field</option>
</select>
<form>
<div id="newAdd"> </div>.
</form>

A: document.getElementById("formName9").value is not a number. you should add .length to return the number of characters in a string.
  var noInp=parseInt(document.getElementById("formName9").value.length);


text:
Q: How to exit from a submenu back to a main menu? I have the following simple main menu without any methods called in it, and I'm lost at how to make the sub-menu exit back to the main menu when the exit option is chosen in each?
I'm quite the beginner and this project is quite important as if I fail I won't be able to do my exam despite having paid for it already :(
The menu code (so far) is the following:
*//The menu will consist of 6 listings being: Books, Members, Employees, Loans, Statistics, Exit.
//These listings from 1 to 4 will open a submenu consisting of: Insert, Search, Delete, Edit, List All, Exit.
//Listing 5 will consist of: Top 5 Books, Top 5 Members, Employee of the Month, List Overdues, Exit.
    import java.util.*;
    import java.io.*;
    public class Menu
      {
    public static void main(String args[]) throws IOException
      {
    Scanner sc = new Scanner(System.in);
    int option;

    do
    {
    System.out.println("Main Menu:");
    System.out.println("1. Books");
    System.out.println("2. Members");
    System.out.println("3. Employees");
    System.out.println("4. Loans");
    System.out.println("5. Statistics");
    System.out.println("6. Exit");
    System.out.println("Enter your option [1,2,3,4,5,6]:");
    option = sc.nextInt();

    switch (option) {
        case 1: System.out.println("Books Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                option = sc.nextInt();

                switch (option){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    option = sc.nextInt();
                    break;
                }
        break;

        case 2: System.out.println("Members Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                option = sc.nextInt();

                 switch (option){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    option = sc.nextInt();
                    break;
                }
        break;

        case 3: System.out.println("Employees Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                option = sc.nextInt();

                 switch (option){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    option = sc.nextInt();
                    break;
                }
        break;

        case 4: System.out.println("Loans Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                option = sc.nextInt();

                 switch (option){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    option = sc.nextInt();
                    break;
                }
        break;

        case 5: System.out.println("Statistics Sub-Menu:");
                System.out.println("1. Top 5 Books");
                System.out.println("2. Top 5 Members");
                System.out.println("3. Emplyee of the Month");
                System.out.println("4. List Overdue");
                System.out.println("5. Exit");
                System.out.println("Enter your option [1,2,3,4,5]:");
                option = sc.nextInt();

                 switch (option){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    option = sc.nextInt();
                    break;
                }
        break;

        case 6: System.out.println("You selected to Exit");
                System.exit(0);
                break;
    }

   }  while (option!=6);

    }
    }*

A: Avoid single variable to control two different switch. Here you used option variable to control both inner and outer switch. When  option is 6 then controls breaks from both switches.
Use another variable to control inner loop. I used subOption in the following code.
Also submenu functionality should work until user wants to exit. So better to add do while inside inner switch also.
    public class Menu {
    public static void main(String args[]) throws IOException {
    Scanner sc = new Scanner(System.in);
    int option, subOption;

    do {
        System.out.println("Main Menu:");
        System.out.println("1. Books");
        System.out.println("2. Members");
        System.out.println("3. Employees");
        System.out.println("4. Loans");
        System.out.println("5. Statistics");
        System.out.println("6. Exit");
        System.out.println("Enter your option [1,2,3,4,5,6]:");
        option = sc.nextInt();

        switch (option) {
        case 1: {

            do {
                System.out.println("Books Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                subOption = sc.nextInt();

                switch (subOption) {
                case 1: {
                    System.out.println("in Insert");
                    break;
                }
                case 2: {
                    System.out.println("in Search");
                    break;
                }
                case 3: {
                    System.out.println("in Delete");
                    break;
                }
                case 4: {
                    System.out.println("in Edit");
                    break;
                }
                case 5: {
                    System.out.println("in List All");
                    break;
                }
                case 6: {
                    System.out.println("in Exit");
                    break;
                }
                // option = sc.nextInt();
                }
            } while (subOption != 6);
            break;
        }

        case 2:

        {

            do {
                System.out.println("Members Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                subOption = sc.nextInt();

                switch (subOption) {
                case 1: {
                    System.out.println("in Insert");
                    break;
                }
                case 2: {
                    System.out.println("in Search");
                    break;
                }
                case 3: {
                    System.out.println("in Delete");
                    break;
                }
                case 4: {
                    System.out.println("in Edit");
                    break;
                }
                case 5: {
                    System.out.println("in List All");
                    break;
                }
                case 6: {
                    System.out.println("in Exit");
                    break;
                }
                // option = sc.nextInt();
                }
            } while (subOption != 6);
            break;
        }

        case 3:

        {

            do {
                System.out.println("Employees Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                subOption = sc.nextInt();

                switch (subOption) {
                case 1: {
                    System.out.println("in Insert");
                    break;
                }
                case 2: {
                    System.out.println("in Search");
                    break;
                }
                case 3: {
                    System.out.println("in Delete");
                    break;
                }
                case 4: {
                    System.out.println("in Edit");
                    break;
                }
                case 5: {
                    System.out.println("in List All");
                    break;
                }
                case 6: {
                    System.out.println("in Exit");
                    break;
                }
                // option = sc.nextInt();
                }
            } while (subOption != 6);
            break;
        }

        case 4:

        {

            do {
                System.out.println("Loans Sub-Menu:");
                System.out.println("1. Insert");
                System.out.println("2. Search");
                System.out.println("3. Delete");
                System.out.println("4. Edit");
                System.out.println("5. List All");
                System.out.println("6. Exit");
                System.out.println("Enter your option [1,2,3,4,5,6]:");
                subOption = sc.nextInt();

                switch (subOption) {
                case 1: {
                    System.out.println("in Insert");
                    break;
                }
                case 2: {
                    System.out.println("in Search");
                    break;
                }
                case 3: {
                    System.out.println("in Delete");
                    break;
                }
                case 4: {
                    System.out.println("in Edit");
                    break;
                }
                case 5: {
                    System.out.println("in List All");
                    break;
                }
                case 6: {
                    System.out.println("in Exit");
                    break;
                }
                // option = sc.nextInt();
                }
            } while (subOption != 6);
            break;

        }

        case 5: {

            do {
                System.out.println("Statistics Sub-Menu:");
                System.out.println("1. Top 5 Books");
                System.out.println("2. Top 5 Members");
                System.out.println("3. Emplyee of the Month");
                System.out.println("4. List Overdue");
                System.out.println("5. Exit");
                System.out.println("Enter your option [1,2,3,4,5]:");
                subOption = sc.nextInt();

                switch (subOption) {
                case 1: {
                    System.out.println("in Top 5 Books");
                    break;
                }
                case 2: {
                    System.out.println("in Top 5 Members");
                    break;
                }
                case 3: {
                    System.out.println("in Emplyee of the Month");
                    break;
                }
                case 4: {
                    System.out.println("in List Overdue");
                    break;
                }

                case 5: {
                    System.out.println("in Exit");
                    break;
                }
                // option = sc.nextInt();
                }
            } while (subOption != 6);
            break;

        }

        case 6:
            System.out.println("You selected to Exit");
            System.exit(0);
            break;
        }

    } while (option != 6);

  }
}


text:
Q: jquery append var If i alert x i can see the value. But from the below code, i can't seem to append the value to #result. What am i doing wrong.

<button id="more">more</button>

A: Edit: Oops, your code works. I should've tested it, my bad. +1 to SLaks

You need to put your code inside $(document).ready(function() { });. Read here to find out why.
More

W/o document ready - http://jsfiddle.net/Z2EjD/ -
More

That might be able to be improved. If anyone notices something, please comment.

A: If we are to go on this code sample alone then the answer is "You don't have an element with the id 'more' to click on".
That said, you've probably got an overly reduced test case that doesn't show that said element appears after the


text:
Q: EventBus with Kotlin not working I am new to Android, and trying to send message from a Fragment to its container Activity using EventBus.
However, I am getting error:
D/EventBus: No subscribers registered for event class com.app.todo.controllers.task.TaskListFragment$TaskCreateSelectEvent

Following is the code in Activity class related to EventBus:
public class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTaskCreateSelectEvent(event: TaskListFragment.TaskCreateSelectEvent) {
        Log.d("TAG", "On Main Activity")
    }

    fun addFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit)
        transaction.add(R.id.task_fragment_container, fragment)
        transaction.addToBackStack(fragment.javaClass.simpleName)
        transaction.commit()
    }

    public override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    public override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

}

Following is in Fragment class
public class TaskListFragment : Fragment() {
    private var fab: FloatingActionButton? = null

    public class TaskCreateSelectEvent {
        var fab: FloatingActionButton? = null
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view = inflater!!.inflate(R.layout.task_list_fragment, container, false)
        fab = view.findViewById<FloatingActionButton>(R.id.fab)
        fab!!.setOnClickListener {
            val selectEvent = TaskCreateSelectEvent()
            EventBus.getDefault().post(selectEvent)
        }
        return view
    }
}

This is how library is added in build.gradle file.
apply plugin: 'kotlin-kapt'

dependencies {
    compile 'org.greenrobot:eventbus:3.0.0'
    kapt 'org.greenrobot:eventbus-annotation-processor:3.0.1' }

kapt {
    arguments {
        arg('eventBusIndex', 'com.app.todo.controllers.MyEventBusIndex')
    }
}

Any idea what I am doing wrong?

A:
I am new to Android ...

then you should better get familiar with dagger and rx instead.
Event busses are a bad thing on android and often make things more complicated than necessary.
https://www.google.de/search?q=android+rxjava+instead+of+eventbus

A: try to change your subscribed method name to:
    onMessageEvent(event: TaskListFragment.TaskCreateSelectEvent)

but as the @Lord Flash suggested - use rxjava instead of eventbus. Take a look at PublishSubject/PublishProcessor (rx 2.0) classes


text:
Q: How to copy files & directories as a Sudo User I login to linux using my Id eg "A". then i'll sudo to the user 'B' without entering the password, after that i'll copy some files from X folder to Y Folder using the SUdo user 'B'.
I am trying to do this activity with a shell script to put it in the cronjob... so far no luck.
Any help on this will be really appreicate...
this is what i am trying...
#!/bin/sh
sudo /usr/local/sbin/deploy
cp -r /tmp/test /tmp/deploy

A: You must run the cp with sudo as well. Otherwise, deploy creates the files with owner B and then, the cp can't read them (since the shell returns you to the original user when the sudo in your script completes).
Alternatively, run chmod with sudo to make the files readable for A and then make a copy.

A: sudo only runs the command on the commandline, then returns you back to the invoker's account. if you want to run multiple commands as another user, it would be better to create a script and run that script via sudo.

A: sudo is an interactive command. Using it in cron jobs does not make sense. Either you create a super user script to copy all the files and then change the ownership, or run the script by the required user itself.

A: Try this: for example if your username is "james", add the following entry to the /etc/sudoers or into a separate /etc/sudoers.d/ file. After this, you can copy files from source to target without entering password.
# visudo
james  ALL=(ALL) NOPASSWD: /bin/cp


text:
Q: How do I connect the Sonicmaster subwoofer that came with the ASUS Q550L? No instructions are provided to describe the process of connecting the wireless subwoofer to the laptop.

A: The compact subwoofer plugs into an audio out port that's on the right-hand side of each (Asus) notebook (in your case it could be left side as well). Anyway - find an audio out port and plug it in.


text:
Q: I want to fetch data from Mysql database through retrofit2 api Actually I want to fetch data from Mysql database through retrofit2 api. I am fetching data on the basis of some category like category 1 or 2 but I am getting error @Field parameters can only be used with form encoding. (parameter #1)for method APIService.savePost
Here is my Interface code:
public interface APIService {

    @GET("fetchtext.php")
    Call<List<DataStored>> savePost(@Field("catId") String catId);
    @GET("testing.php")
    Call<List<DataStored>> searchcategory(@Field("catId") String catId,
            @Field("SubCatego") String SubCatego);
}

Here is my ApiUtils Class:
    public class ApiUtils {

  private ApiUtils() {}

    public static final String BASE_URL = "http://192.168.9.10/";

    public static APIService getAPIService() {

        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

RetrofitClient Class:
public class RetrofitClient {
    private static Retrofit retrofit = null;
    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }}

Code In Fragment where I am creating calling RetroApi:
 mAPIService = ApiUtils.getAPIService();
     mAPIService.savePost(category).enqueue(new Callback<List<DataStored>>() {
            @Override
            public void onResponse(Call<List<DataStored>> call, Response<List<DataStored>> response) {
                dataStored=  response.body();
                myRecyclerAdapter.addItems(dataStored);
            }

            @Override
            public void onFailure(Call<List<DataStored>> call, Throwable t) {

            }
        });

Please tell me how can I send category to database to compare if that
   category data available in database then data convert into Json and send  back in android to show on RecyclerView in android.

A: @GET("fetchtext.php")
Call<List<DataStored>> savePost(@Field("catId") String catId);

@Field is used to send POST data. To fetch data you should use @Query
@GET("fetchtext.php")
Call<List<DataStored>> savePost(@Query("catId") String catId);


text:
Q: Raspberry pi - run a python script through apache server I am trying to come up with a way to run a python file on my raspberry pi through apache.
To run the program in ssh i type sudo python testfile.py
I have tried through php using exec('sudo python /home/pi/python/testfile.py')
but no joy, i get an error in my /var/log/apache2/error.log
PHP Warning:  Unknown: failed to open stream: Permission denied in Unknown on line 0
 PHP Warning:  Unknown: failed to open stream: Permission denied in Unknown on line 0
PHP Fatal error:  Unknown: Failed opening required '/var/www/index2.php' (include_path='.:/usr/share/php:/usr/$

I have tried using cgi also. but get this error :
(13)Permission denied: exec of '/usr/lib/cgi-bin/runpython.cgi' failed
Premature end of script headers: runpython.cgi

I have googled as much as I can, and checked here to see if I could find anything.
Can anyone offer some help/advice ? Thanks

A: Take a look at mod_wsgi: https://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide
Also, are you sure your script needs to run as root?


text:
Q: Draw a triangle on a MapControl (UWP) 3d view I need to draw a triangle on an Aerial3d view on a UWP MapControl to have some visual information for the user like to see if certain vector crosses mountains or tall buildings, ...
I have the origin Geopoint, the azimuth and the elevation from the horizontal plane. From this data, I can have also the final Geopoint and, I think, "the altitude" for the upper point of the triangle.
Azimuth and elevation can be changed anytime, so the triangle should be drawn as many times as needed.
MapPolygon, MapPolyline and such don't work in this case because lines should be drawn above and across the map and not stuck to it.
New MapControl MapElements such MapModel3D and MapElement3D are static objects so they don't work as well.
This is the idea:

A: You should be able to use a MapPolyline - it will correctly be drawn in 3D space if you specify an altitude reference system and have an altitude value set for each vertex. MapPolygon will always be drawn to the terrain.
You should also be able to use a MapElement3D to show a filled polygon as shown on your picture. Just create a model that's a simple triangle and position at the origin/heading. If the origin or heading change, the model can be updated quickly. If the elevation angle changes, you'll need to re-create the model, but for a simple triangle, this should be reasonably fast. I've seen examples of someone animating a bird model with the wings flapping and getting 2-3FPS, so while it won't necessarily be interactively tracking, it should be a pretty quick update.


text:
Q: How to know the number of users for a particular wordpress plugin By checking the WordPress stats we get the idea that how many times a WordPress plugin is downloaded. But this is not the number of how many users for that plugin, right. Same user will download the plugin when a new version releases.
So do we have any tools or stats to get the total number of unique users for a WordPress plugin??

A: The only way I can think of that you could track something like this is by having the plugin phone-home with some stats to your own server.
Just make sure users can select to opt-out of tracking.

A: I did a research on the matter. And the answer is no.

Quotes from Otto comments in this 2010
article
about the stats charts in every plugin's page.

[...] the download count includes direct downloads as well
There is no "raw count" anywhere on that version number chart. The raw count is not data that will be made available.

For your own plugin, you can use tracking as @PeterVanDerDoes points out.
Curiously, the plugin I used as example in the research, WordPress SEO by Yoast, is the same that does this kind of tracking. And here's a nice discussion about it.
I'll reproduce the relevant part of the plugin development official guidelines:

7. No "phoning home" without user's informed consent. This seemingly simple rule actually covers several different aspects:

*

*No unauthorized collection of user data. For example, sending the admin's email address back to your own servers without permission of the user is not allowed; but asking the user for an email address and collecting if they choose to submit it is fine. All actions taken in this respect MUST be of the user's doing, not automatically done by the plugin.

*All images and scripts shown should be part of the plugin. These should be loaded locally. If the plugin does require that data is loaded from an external site (such as blocklists) this should be made clear in the plugin's admin screens or description. The point is that the user must be informed of what information is being sent where.

*In general, things like banner or text link advertising should not be anywhere in a plugin, including on its settings screen. Advertising on settings screens is generally ineffective anyway, as ideally users rarely visit these screens, and the advertising is low quality because the advertising systems cannot see the page content to determine good ads. So they're best just left off entirely. Putting links back to your own site or to your social-network of choice is fine. If the plugin does include advertising from a third party service, then it must default to completely disabled, in order to prevent tracking information from being collected from the user without their consent. This is the method commonly known as "opt-in".

*Note that if you do include what we consider to be "advertising spam", or attempt to game somebody else's advertising system, then we will not only remove your plugin, but also report your code to the advertising system's abuse mechanism as well. We do not react kindly to spam. Don't try it.


text:
Q: Browsing and playing videos in HTML5 To watch videos in an HTML5 web player requires us to add the source of the video in the HTML code like this:
 <video id="example" class="video" controls preload="none" width="500" height="300"
  poster="abc.jpg" data-setup="{}">
        <source src="../87D645D1d01.ogv" type='video/ogg' />
 </video>

So is there any way with which we can browse a media file in our local file system irrespective of the OS and then add the pah to the SRC: part of video element like we do it in any desktop based video players and then play it?
Regards.
Anuj.


text:
Q: Laravel website doesn't run on browser anymore after downloading older Github commit I'm learning how to build a blog using Laravel and following along on these youtube tutorials: https://www.youtube.com/watch?v=R8B4og-BeCk
I made a mistake in tutorial part 13 locally which I didn't know how to fix, but I had the project up on Github so I decided to use an older version which I knew had worked perfectly after finishing tutorial number 12. I then purposely deleted the entire broken project locally, and downloaded the zip from Github and simply copy pasted the entire older Github blog commit into the local folder (as suggested here by Sivan: How to get certain commit from GitHub project)
But when I went to test the site on my browser by running "php artisan serve" in the terminal as normal (I'm using Ubuntu as my os) it came back with the same error as here Laravel 5 Failed opening required bootstrap/../vendor/autoload.php .
I followed the advice of Shubhamoy Chakrabarty and ran "composer update --no-scripts", and it then seemed to be working.
So I ran "php artisan serve" once again in the terminal and the response in the terminal appears positive as it comes back with the usual:
Laravel development server started on http://localhost:8000/
[Sun Jul 10 13:55:19 2016] 127.0.0.1:58276 [200]: /favicon.ico
But when I go to test the site in the browser, it comes back with the error "Whoops, looks like something went wrong." and the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)".
And this is the point I'm at now and wondering if you could help me with. Please feel free to tell me if I went about it wrong at any point and what I should do now as I'm still figuring out the best way to go about this.
Thanks very much in advance!

A: I am glad you are enjoying the Laravel Series.
There are a few things on here that might help you. First of all, make sure you have ran all of the migrations which might be causing problems if your Database is not in sync with the code. You can do this in the terminal by typing php artisan migrate and running the command.
Also it sounds like your project is not running in development mode. In development mode, Laravel will publish more detailed errors about what is happening, instead of simply a 500 error. This will help us debug the problem.
Remember that on GitHub there are always a few files that do not get sent to the repo that you might need. One of these files is the .env file that contains important information about your project to Laravel. In this file it will tell Laravel to run the project in development mode, which in turn will reveal the detailed error messages.
The default .env file should look like this:
APP_ENV=local
APP_DEBUG=true
APP_KEY=11mw9hJML4VDO3PGrtIFnUaE8hCrXads

DB_HOST=127.0.0.1
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379

Of course your app key might be different. It is autogenerated when you build a new app or you can generate it yourself. You can use the one above if you don't have one. Also note that the APP_DEBUG is set to true which will give you those better error messages.
Note also the DB settings. Make sure your database settings work. Check the DB_DATABASE to the name of your database, the DB_USERNAME and DB_PASSWORD also should match the settings of your database.
Try this and see if this works. Also once the database settings are in your .env file then you will want to run php artisan migrate as well.
Let me know if that helps.


text:
Q: Split (explode) pandas dataframe string entry to separate rows. Multiple columns I have a dataframe that looks like this:

I need to replace "European Union" and split (explode) into the countries that are member of it like the following example:

I have tried to replace "European Union" for a dictionary containing its members, and then spliting it with the following line of code:
test_disc['countryname'] = test_disc['countryname'].replace({'European Union': 'Austria, Belgium, Bulgaria, Croatia, Cyprus, Czechia, Denmark, Estonia, Finland, France, Germany, Greece, Hungary, Ireland,Italy, Latvia, Lithuania, Luxembourg, Malta, Netherlands,Poland, Portugal, Romania, Slovakia, Slovenia, Spain, Sweden'})

test_disc[['iso_2', 'iso_3', 'countryname', 'país afetado','year',
       'SPS emergenciais', 'SPS regulares']].astype(str).apply(lambda x:
       x.str.split(',').explode()).reset_index()

However, I have been getting the following error:
"ValueError: cannot reindex from a duplicate axis"

A: when you use explode, you should only convert the target column to list content, not all columns.

demo data
data = [{'iso_2': 0, 'iso_3': 'NaN', 'countryname': 'JP', 'país afetado': 'US', 'year': 2015, 'SPS emergenciais': 0, 'SPS regulares': 0}, {'iso_2': 1, 'iso_3': 'NaN', 'countryname': 'European Union', 'país afetado': 'China', 'year': 2015, 'SPS emergenciais': 0, 'SPS regulares': 0}, {'iso_2': 2, 'iso_3': 'NaN', 'countryname': 'US', 'país afetado': 'European Union', 'year': 2015, 'SPS emergenciais': 0, 'SPS regulares': 0}, {'iso_2': 3, 'iso_3': 'NaN', 'countryname': 'European Union', 'país afetado': 'European Union', 'year': 2015, 'SPS emergenciais': 0, 'SPS regulares': 0}]
df = pd.DataFrame(data)
df

       iso_2 iso_3     countryname    país afetado  year  SPS emergenciais  \
    0      0   NaN              JP              US  2015                 0
    1      1   NaN  European Union           China  2015                 0
    2      2   NaN              US  European Union  2015                 0
    3      3   NaN  European Union  European Union  2015                 0

       SPS regulares
    0              0
    1              0
    2              0
    3              0

process:
for col in ['país afetado', 'countryname']:
    df[col] = df[col].replace({'European Union': 'Austria, Belgium, Netherlands,Poland'})
    df[col] = df[col].str.split(',\s*')

df_result = df.explode('countryname').explode('país afetado')

result:
   iso_2 iso_3  countryname país afetado  year  SPS emergenciais
0      0   NaN           JP           US  2015                 0
1      1   NaN      Austria        China  2015                 0
1      1   NaN      Belgium        China  2015                 0
1      1   NaN  Netherlands        China  2015                 0
1      1   NaN       Poland        China  2015                 0
2      2   NaN           US      Austria  2015                 0
2      2   NaN           US      Belgium  2015                 0
2      2   NaN           US  Netherlands  2015                 0
2      2   NaN           US       Poland  2015                 0
3      3   NaN      Austria      Austria  2015                 0
3      3   NaN      Austria      Belgium  2015                 0
3      3   NaN      Austria  Netherlands  2015                 0
3      3   NaN      Austria       Poland  2015                 0
3      3   NaN      Belgium      Austria  2015                 0
3      3   NaN      Belgium      Belgium  2015                 0
3      3   NaN      Belgium  Netherlands  2015                 0
3      3   NaN      Belgium       Poland  2015                 0
3      3   NaN  Netherlands      Austria  2015                 0
3      3   NaN  Netherlands      Belgium  2015                 0
3      3   NaN  Netherlands  Netherlands  2015                 0
3      3   NaN  Netherlands       Poland  2015                 0
3      3   NaN       Poland      Austria  2015                 0
3      3   NaN       Poland      Belgium  2015                 0
3      3   NaN       Poland  Netherlands  2015                 0
3      3   NaN       Poland       Poland  2015                 0


text:
Q: want to confirm popup with "Yes" and "No" button when user click on add to cart I am new in Wordpress so need help...
I want to show confirm popup with the button "Yes" and "No" when user clicks on Add to Cart. after selecting "Yes" on confirm Popup, add a product to cart. If user select "No" the close confirm popup and do nothing.
Also, I want to show product data filed value on confirm popup body section.
Update:
i already try with hook(woocommerce_add_to_cart_validation) and some javascript but not able to get it.
Thanks in Advanced...


text:
Q: Installation failed SteerMouse To be able to fully use my Logitech AnyWhere Mouse, I looked to install third party softwares
I'm currently running Yosemite 10.10.2 and unable to install SteerMouse 4.2.2.
After many rebooting or fixed permissions under DiskUtility app, I get the same result.
Here's an example of the Console log message after a try:
10/04/15 13:54:40,765 Installer[867]:
  The Installer encountered an error that caused the installation to fail.
  Contact the software manufacturer for assistance.

It's exactly the same problem with USB-Overdrive-31.
What I'm supposed to do?

A: Ok I saw that some directory was missing, something in /private/tmp...
which prevented an object creation, leading to a null variable.
I went to the /private/tmp directory a saw file named .keystone_install_lock
 which I suppressed and relaunch an installation. It was just fine after.


text:
Q: How to Display 4week per month with condition in sql I have this logic but I cant figure out what to do to come up with the results. I want to achieve the results below, the idea is (Ex. month of October 2014), normally it has 5 weeks. If there is a 5th week and days is greater than 3 then consider whole week in  the next month else add it to 4th week.
  Input:
     date range

     from: 10-01-2014
     to:   11-30-2014

  Sample Output:

     Date       Customer        week#          Dates covered
   10-01-2014     Cust01          1           Oct 01 - Oct 11, 2014
   10-08-2014     Cust02          1           Oct 01 - Oct 11, 2014
   10-17-2014     Cust02          2           Oct 12 - Oct 18, 2014
   10-25-2014     Cust03          3           Oct 19 - Oct 25, 2014
   10-31-2014     Cust01          4           Oct 26 - Oct 31, 2014
   11-01-2014     Cust01          1           Nov 01 - Nov 08, 2014
   11-28-2014     Cust02          4           Nov 23 - Nov 30, 2014
   11-30-2014     Cust05          4           Nov 23 - Nov 30, 2014

 Thanks

A: Use datepart(ww,[date]) to get week number in a year, then compare the week number by the begin date of a month.
Below is the detail approach to calculate for one date:
declare @dt date, @month_begin date, @month_end date, @week_of_month int
set @dt='20141031'
set @month_begin = convert(date,(convert(char(6),@dt,112)+'01'))
set @month_end = dateadd(day, -1, dateadd(month,1,@month_begin))
set @week_of_month = datepart(ww,@dt) - datepart(ww,convert(date,(convert(char(6),@dt,112)+'01'))) + 1
select
    case when @week_of_month > 4 and datepart(dw,@month_end)>3
         then 1
         else  @week_of_month
    end as week,
    case when @week_of_month > 4 and datepart(dw,@month_end)>3
         then datepart(month,dateadd(month,1,@dt))
         else datepart(month,@dt)
    end as month


text:
Q: Get value from control in the same control as the button is located I have a StackPanel, some Expanders, some textboxes and some buttons.
For example I have the following structure:
StackPanel
  Expander 1
    TextBox 1
    Button 1
  Expander 2
    TextBox 2
    Button 2
  Expander 3
    TextBox 3
    Button 3

How can i get the textbox.Text from the Expander where the Button is clicked?
For example i click Button 2 and I want to get TextBox 2 in Expander 2.
All the controls are added programmatically instead of the StackPanel.
Is there something like a event? I don't know the way to get the textbox when a button is clicked in the same expander.
I want 2 Methods to save my Expander Header and its content (a textbox value for example).
the 1st method is by right clicking the Expander's Header which will transform the Header into a TextBox so i can edit the text. By clicking ENTER it will save the TextBox.Text into TextBlock. Which works fine. But i can't use the same code for a Button.
Expander editable_expander;  // Expander sender  from Expander_MouseRightButtonDown

    private void Expander_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        var ex = sender as Expander;
        TextBox tb = new TextBox();
        tb.Text = ex.Header.ToString();
        tb.KeyUp += TextBox_KeyUp;
        ex.Header = tb;
        editable_expander = ex;
    }

    private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        // Edit Columnname of selected Column when Enter pressed
        if (e.Key != Key.Enter) return;

        var tb = sender as TextBox;
        e.Handled = true;

        string old_expander_name = editable_expander.Name.ToString();
        string old_column_name = old_expander_name.Split('_')[0];

        int length = 0;
        string type = "";

        if(OpenConnection() == true)
        {
            try
            {
                Grid grid = editable_expander.Content as Grid;
                List<StackPanel> stackpanel = grid.Children.OfType<StackPanel>().ToList();
                for(int i = 1; i < 2; i++)
                {
                    StackPanel sp = stackpanel[i];
                    List<TextBox> textbox = sp.Children.OfType<TextBox>().ToList();
                    for(int j = 0; j < textbox.Count; j++)
                    {
                        TextBox tb1 = textbox[j];
                        length = Convert.ToInt32(tb1.Text);
                    }
                    List<ComboBox> combobox = sp.Children.OfType<ComboBox>().ToList();
                    for(int k = 0; k < combobox.Count; k++)
                    {
                        ComboBox cb = combobox[k];
                        type = cb.Text;
                    }
                }

                string query = "ALTER TABLE " + editable_expander.Tag + " CHANGE " + old_column_name + " " +  tb.Text + " " + type + "(" + length + ")";
                MySqlCommand cmd = new MySqlCommand(query, connection);
                cmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        editable_expander.Header = tb.Text;
    }

A: The way to do this in MVVM:
Xaml style:
 <ItemsControl ItemsSource="{Binding List}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Expander Header="{Binding SomeText}" MinWidth="100">
                <StackPanel Orientation="Horizontal">
                    <TextBox Text="{Binding SomeText}" MinWidth="100"/>
                    <Button MaxWidth="150" Content="ClickMeToGetYourText" Command="{Binding DataContext.ButtonClickedCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}" CommandParameter="{Binding}"/>
                </StackPanel>
            </Expander>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

What you've got here is: List of controls: controls are placed in StackPanel, each control have: Expander with SomeText as header, then in it, there is also  TextBox with same text, and button which you can click. Button have command, in which you would get you'r text.
Now some code in C#:
ViewModel:
public class ViewModel
{
    public ObservableCollection<ExpanderData> List { set; get; } = new ObservableCollection<ExpanderData>();
    private ICommand _buttonClickedCommand;
    public ICommand ButtonClickedCommand
    {
        get
        {
            if (_buttonClickedCommand == null)
            {
                _buttonClickedCommand = new RelayCommand(p => ButtonClicked(p));
            }
            return _buttonClickedCommand;
        }
    }

    public void ButtonClicked(Object o)
    {
        var expanderData = (ExpanderData)o;
        var textThatYouWantedToHaveOnButtonClicked = expanderData.SomeText;
    }
}

You have here list, from which you will create your expanders. Command which will allow you to do something on ButtonClicked, and method that will fire on ButtonClicked event.
Now, how looks the ExpanderData class:
public class ExpanderData : INotifyPropertyChanged
{
    private string _someText;

    public string SomeText
    {
        set
        {
            _someText = value;
            OnPropertyChanged();
        }
        get
        {
            return _someText;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName]string name = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}
Here you have your Text that is assign to each of your Expander/TextBox, and event that will fire if you want to update your text from code behind.

And RelayCommand implementation, which allows you to binding Commands
public class RelayCommand : ICommand
{
    private Predicate<object> _canExecute;
    private Action<object> _execute;

    public RelayCommand(Action<object> execute)
    {
        this._canExecute = p => true;
        this._execute = execute;
    }
    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        this._canExecute = canExecute;
        this._execute = execute;
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

And this is how you can add VM to your view:
var vm = new ViewModel();
vm.List.Add(new ExpanderData() { SomeText = "Text1" });
vm.List.Add(new ExpanderData() { SomeText = "Text2" });
vm.List.Add(new ExpanderData() { SomeText = "Text3" });
vm.List.Add(new ExpanderData() { SomeText = "Text4" });

this.DataContext = vm;

Or, if you still want some dirty way:
private void ButtonClicked(Object sender, ...)
{
    var yourTextBox = ((Panel)((Button)sender).Parent).Children.OfType<TextBox>().First();
    var yourText = yourTextBox.Text;
}


text:
Q: Global environment variable not available to bash command executed inside PHP I'm trying to return the value of a global environment variable inside a bash script which is executed from inside PHP (run as sudo).
Running the command printenv from the bash script reveals that the global variable is not set. I understand sudo resets the environment.
Please consider the following setup;
Define global environment var
root@test:/# export HEY=hello

Test existence of var
root@test:/# printenv | grep HEY
HEY=hello

Please consider this PHP function
PHP function
function testAction() {

    define('TEST_CMD', '/usr/bin/sudo /usr/local/test/bin/');
    $command = 'bash_script';
    $query = TEST_CMD.$command;

    exec ($query, $output, $return_var);

    var_dump( $output );
    var_dump( $return_var );
    echo exec('whoami');

}

Contents of /etc/sudoers.d/admin
admin   ALL=(ALL)       ALL
admin   ALL=NOPASSWD:/usr/local/test/bin/*

Contents of /usr/local/test/bin/bash_script
#!/bin/bash
printenv
echo $HEY
exit

I have tried putting Defaults   env_keep +="HEY" inside /etc/sudoers.d/admin too but that doesn't appear to work either.
OS is ubuntu 14.04
Any ideas?


text:
Q: Dealing with Dual TypeScript installs I'm trying to do some TypeScript tutorials but I'm hitting a weird problem.  A while back I installed TypeScript 1.0.3.0 through Visual Studio here:
C:\Program Files (x86)\Microsoft SDKs\TypeScript
On the command line, when I check the TypeScript version it references that.  I wanted to do some Angular (Angular version 2/4) so I loaded Node Package Manager and installed TypeScript through NPM.  NPM loaded a newer version of TypeScript in another place on my computer.  When I create Angular projects using Angular's CLI tool it somehow uses the NPM install.  When I want to do simple, bare-bones TypeScript tutorials it uses the older version 1.0.3.0.
I lost my MSDN license so I can't run Visual Studio anymore.  How do I update TypeScript that is in the Microsoft SDKs folder?  Every Web site I check on installing or updating TypeScript tells me to use NPM.

A: If you don't plan to use it uninstall it, if you check Window uninstall software console panel page, you should find an item relating to that install.
If it's not there the simplest way would be to remove the old Typescript folder from your path variable (see here how to edit if you are not familiar). Look for the C:\Program Files (x86)\Microsoft SDKs\TypeScript folder and just remove it.
Then install the latest Typescript from npm.


text:
Q: Sort an array of associative arrays by multiple columns using a combination of ascending, descending, regular, numeric, and natural sorting Is it possible to sort a multidimensional array by multiple columns using natural sort in PHP? Here is an example. Suppose I have a 2D array of data, e.g.,
$array[1]['Name'] = 'John';
$array[1]['Age'] = '20';
$array[1]['Code'] = 'ABC 12';

$array[2]['Name'] = 'John';
$array[2]['Age'] = '21';
$array[2]['Code'] = 'ABC 1';

$array[3]['Name'] = 'Mary';
$array[3]['Age'] = '20';
$array[3]['Code'] = 'ABC 10';

I want to sort this array by name (ASC), then by age (DESC), and by code (ASC), all will be sorted naturally. Basically that will be array_multisort with natural sort.
I found many solutions about this topic on the web. Unfortunately, they only support sorting by one column, not multiple column.

A: I think you have to implement a custom comparison function for this behavior:
function myCmp($a, $b) {
 $nameCmp = strnatcasecmp($a['Name'], $b['Name']);
 $ageCmp = strnatcasecmp($a['Age'], $b['Age']);
 $codeCmp = strnatcasecmp($a['Code'], $b['Code']);

 if ($nameCmp != 0) // Names are not equal
   return($nameCmp);

 // Names are equal, let's compare age

 if ($ageCmp != 0) // Age is not equal
   return($ageCmp * -1); // Invert it since you want DESC

 // Ages are equal, we don't need to compare code, just return the comparison result
   return($codeCmp);
}

Then you can call usort($array, 'myCmp'); and should get the desired sorting

A: If you're using PHP 5.4 or newer, you can use array_multisort with the SORT_NATURAL flag.

A: Only one of the three sorting rules actually requires natural sorting.  In fact, if you use PHP's 3-way comparison operator (<=>), then it will automatically compare numeric strings as numeric values.  Only the third rule needs natural sorting to be explicitly declared because it demands the comparison of alphanumeric strings.
Code: (Demo)
$array = [
    1 => ['Name' => 'John', 'Age' => '20', 'Code' => 'ABC 12'],
    2 => ['Name' => 'John', 'Age' => '21', 'Code' => 'ABC 1'],
    3 => ['Name' => 'Mary', 'Age' => '20', 'Code' => 'ABC 10'],
    4 => ['Name' => 'John', 'Age' => '20', 'Code' => 'ABC 1'],
    5 => ['Name' => 'John', 'Age' => '20', 'Code' => 'ABC 100'],
    6 => ['Name' => 'John', 'Age' => '20', 'Code' => 'ABC 2'],

];

uasort(
    $array,
    fn($a, $b) =>
        [$a['Name'], $b['Age']] <=> [$b['Name'], $a['Age']] // name (ASC) then by age (DESC)
        ?: strnatcasecmp($a['Code'], $b['Code']) // then by code (ASC / naturally)
);
var_export($array);

Output:
array (
  2 =>
  array (
    'Name' => 'John',
    'Age' => '21',
    'Code' => 'ABC 1',
  ),
  4 =>
  array (
    'Name' => 'John',
    'Age' => '20',
    'Code' => 'ABC 1',
  ),
  6 =>
  array (
    'Name' => 'John',
    'Age' => '20',
    'Code' => 'ABC 2',
  ),
  1 =>
  array (
    'Name' => 'John',
    'Age' => '20',
    'Code' => 'ABC 12',
  ),
  5 =>
  array (
    'Name' => 'John',
    'Age' => '20',
    'Code' => 'ABC 100',
  ),
  3 =>
  array (
    'Name' => 'Mary',
    'Age' => '20',
    'Code' => 'ABC 10',
  ),
)

Note the the first level keys are preserved in the output because uasort() is used.  Because the input array is not indexed, I am assuming that the keys are ids or something otherwise important.

If you are comfortable with reindexing the parent level keys, then array_multisort() can be used after generating arrays of columnar data. (Demo)
foreach ($array as ['Name' => $names[], 'Age' => $ages[], 'Code' => $codes[]]);

array_multisort(
    $names,        // ASC, REGULAR
    $ages,         // DESC, NUMERIC
    SORT_DESC,
    SORT_NUMERIC,
    $codes,        // ASC, NATURAL
    SORT_ASC,
    SORT_NATURAL,
    $array         // the array to be affected
);
var_export($array);


text:
Q: 500 Internal Server Error - handler, asp.net MVC I am using a simple handler to display an image on MVC view, it works great on my localhost but when I publish it to our hosting server I get this error (using Fiddler):
GET ImageHandler.ashx?img=b...w=255&level=128&slice=0  500 Internal Server Error

Here is the view script:
<img id="Image1" alt="image"  src="ImageHandler.ashx?img=bmptest.bmp&window=255&level=128&slice=0" height="512" width="512" />

Here is the handler's script:
   public class ImageHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string sImageFileName = "";
            int slice = 0;
            int window = 0;
            int level = 0;
            sImageFileName = context.Request.QueryString["img"].ToLower().Trim();
           .....
            System.Drawing.Image objImage = null;
            Image bmp = Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("content/" + sImageFileName));
            MemoryStream objMemoryStream = new MemoryStream();
            bmp.Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] imageContent = new byte[objMemoryStream.Length];
            objMemoryStream.Position = 0;
            objMemoryStream.Read(imageContent, 0, (int)objMemoryStream.Length);
            context.Response.ContentType = "image/jpeg";
            context.Response.BinaryWrite(imageContent);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

I modified web.cong by adding:
<system.web>
......
    <httpHandlers>
      <add verb="*" path="*.ashx" type="DirectshowTest.ImageHandler,DirectshowTest"/>
    </httpHandlers>
   </system.web>

Would appreciate your suggestions.

A: I added the following to Global.asax:
 routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");

It is working now.


text:
Q: Attempted to use an object that has ceased to exist. (Exception from HRESULT: 0x80030102 (STG_E_REVERTED)) Well I'm trying to programmatically add a new ListItem to an already existing List in my SharePoint 2010 website.
I've created a new webpart , added a single button to it with the following event handler
    protected void Unnamed1_Click(object sender, EventArgs e)
    {
        using (SPSite currentSiteCollection = new SPSite(SPContext.Current.Site.ID))
        {
            using (SPWeb currentWebsite = currentSiteCollection.OpenWeb(SPContext.Current.Web.ID))
            {
                SPListItem myNewItem = currentWebsite.Lists["myList"].AddItem();
                myNewItem["Title"] = "newItem1";
                myNewItem.Update();
            }
        }

    }

Added my webpart to the default page of the sharepoint 2010 site ... by unfortunately when I click the button I get this error
    Attempted to use an object that has ceased to exist. (Exception from HRESULT: 0x80030102 (STG_E_REVERTED))
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: Attempted to use an object that has ceased to exist. (Exception from HRESULT: 0x80030102 (STG_E_REVERTED))

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[COMException (0x80030102): Attempted to use an object that has ceased to exist. (Exception from HRESULT: 0x80030102 (STG_E_REVERTED))]
   Microsoft.SharePoint.Library.SPRequestInternalClass.SetDisableAfterEvents(Boolean bNewDisableAfterEvents) +0
   Microsoft.SharePoint.Library.SPRequest.SetDisableAfterEvents(Boolean bNewDisableAfterEvents) +124

[SPException: Attempted to use an object that has ceased to exist. (Exception from HRESULT: 0x80030102 (STG_E_REVERTED))]
   Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx) +27677298
   Microsoft.SharePoint.Library.SPRequest.SetDisableAfterEvents(Boolean bNewDisableAfterEvents) +207
   Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32& ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents, String filename) +26793884
   Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents, String filename) +26793214
   Microsoft.SharePoint.SPListItem.Update() +161
   SLBWOA.Web.UCNewChecklist.UCNewChecklistUserControl.Unnamed1_Click(Object sender, EventArgs e) +259
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +115
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +140
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981

I've tried several solutions available on the forum and through google but with no luck.

A: I ran into this problem when my list definition contained, of all things, a <Field Type="Choice"> with a <Default> element inside.
Update:
The problem occurs if I have a <Field Type="Choice"> that doesn't allow an empty value, and I don't set this field to one of the valid values when creating the list item.

A: I had this error on every list view in one of sub-sites in SharePoint 2010, on default views also. It turned out that a user changed a time zone in site's regional settings to another time zone (+8), after I changed it back all started to work again )

A: Did you try :
    protected void Unnamed1_Click(object sender, EventArgs e)
{
    SPSite currentSiteCollection = SPContext.Current.Site;
    using (SPWeb currentWebsite = currentSiteCollection.OpenWeb(SPContext.Current.Web.ID))
    {
        SPListItem myNewItem = currentWebsite.Lists["myList"].AddItem();
        myNewItem["Title"] = "newItem1";
        myNewItem.Update();
    }
}


text:
Q: Vim-style keys to navigate up and down in Omnicomplete box One of the reasons that I moved from emacs to vim was to avoid awkward keybindings such as Ctrl+N and Ctrl+P for up and down. I would prefer more ergonomic keys like hjkl. However, I didn't find a way to navigate in Omnicomplete box without using arrow keys or Ctrl+N/P.
Does vim provide other keys for up and down?

A: In the insert mode completion popup, any printable character is used to further restrict the list of matches, so there are only the <C-N> / <C-P> keys to choose different menu items.
If you can live with losing some completion keys, you can define the following mappings:
:inoremap <expr> j pumvisible() ? '<C-n>' : 'j'
:inoremap <expr> k pumvisible() ? '<C-p>' : 'k'

A: I have the following mappings, which I'm very happy with:
" Move up and down in autocomplete with <c-j> and <c-k>
inoremap <expr> <c-j> ("\<C-n>")
inoremap <expr> <c-k> ("\<C-p>")

This is especially useful if you're using a plugin (such as Neocomplete, its older sibling Neocomplcache, or YouCompleteMe) that pops up autocomplete dialogues as soon as there might be something to complete to.


text:
Q: Proof of Sequential Continuity The theorem of sequential continuity states that:

f: $\mathbb{R} \rightarrow \mathbb{R}$ is continuous at $a \in \mathbb{R}$ $\Longleftrightarrow$ $f(x_n) \rightarrow f(a)$ $\forall$ sequences $x_n \rightarrow a$.

In the proof of the converse statement, i.e. suppose we know $f(x_n) \rightarrow f(a)$ and we want to prove $f$ is continuous, it is written that

(1) Suppose for a contradiction $f$ is not continuous, and suppose $f(x_n) \rightarrow f(a)$ for all sequences $x_n \rightarrow a$.
(2) Then $\exists \epsilon > 0$ s.t. $\forall \delta>0, \exists x \in
 (a-\delta, a+\delta)$ s.t. $|f(x)-f(a)| \geq \epsilon$.
(3) Choose $\delta = \dfrac{1}{n}$. Then $\exists x_n ∈ (a - \dfrac{1}{n}, a + \dfrac{1}{n})$ such that $|f(x_n) − f(a)| \geq \epsilon$. So $|x_n - a|<\dfrac{1}{n}$ $\forall n$ and therefore $x_n \rightarrow a$. But $f(x_n) \not\rightarrow f(a)$.

I can understand that from (2) is the negation of the definition of continuity which we assumed for a contradiction but I cannot understand how we get to $x_n \rightarrow a$ from $|x_n - a|<\dfrac{1}{n}$ $\forall n$.

A: The definition of $x_n \to a$ is
$$\forall \varepsilon >0: \exists N \in \mathbb{N}: \forall n \ge N: |x_n -a| < \varepsilon $$
So pick $\varepsilon>0$ and note that there is some $N \in \mathbb{N}$ such that $\frac{1}{N}< \varepsilon$. This is a consequence of the Archimedean property of the real numbers, if you want to be precise, or a consequence of the fact that $\frac{1}{n} \to 0$ in $\Bbb R$, if you covered that. I claim that this $N$ is as required, because for all $n \ge N$ we have $\frac{1}{n} \le \frac{1}{N}$ so
$$|x_n -a| < \frac{1}{n} \le \frac{1}{N} < \varepsilon$$
So the fact that $x_n \to a$ is an almost immediate consequence of $\frac{1}{n} \to 0$, really.

A: Let $\epsilon>0.$ By definition, $x_n \to a$ if there exists $N$ such that for all $n\geq N,$ we have $|x_n-a|<\epsilon.$ By the Archimedean property of real numbers, there exists $N$ such that $\frac{1}{N}<\epsilon.$ But then $\frac{1}{n}<\epsilon$ for all $n\geq N.$ Therefore,
$$
|x_n-a|<\frac{1}{n}<\epsilon.
$$
for all $n\geq N.$

A: Sequential continuity is in general a weaker statement than continuity, but is equivalent to continuity in first-countable spaces, that is, a space $X$ in which for every point $x\in X$, there exists a sequence $\{U_n\}$ of neighborhoods of $x$ such that for any neighborhood $U$ of $x$, there exists a positive integer $i$ with $U_i\subset U$.
For if $f$ is not continuous at $x\in X$, there is a neighborhood $V$ of $f(x)$ such that for any neighborhood $U$ of $x$, we have $f(U)\not\subset V$. Since $X$ is first-countable, there is a sequence $\{U_n\}$ of $x$ such that there exists a positive integer $i$ with $U_i\subset U$. But since $f(U_1)\not\subset V$, we may choose $x_1\in U_1$ such that $f(x_1)\notin V$. This yields a sequence $\{x_i\}$ which satisfies $x_i\to x$ but $f(x_i)\notin V$ for all $i$, so in particular $f(x_i)\not\to f(x)$.
Clearly $\mathbb R$ is a first-countable space, in particular being a metric space, so sequential continuity and continuity are equivalent.


text:
Q: Suddenly not working on Ubuntu Digital Ocean: requests error for only Google It was working fine a week ago, but all of a sudden it stopped working.
Steps to reproduce:
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> requests.get('http://yahoo.com')
<Response [200]>
>>> requests.get('http://google.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 67, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 480, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 609, in send
    history = [resp for resp in gen] if allow_redirects else []
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 211, in resolve_redirects
    **adapter_kwargs
  File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 588, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 437, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.google.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fc5076e7950>: Failed to establish a new connection: [Errno -5] No address associated with hostname',))

Expected output:
<Response [200]>

What is weird is that it works for other websites, but not Google


text:
Q: How to edit a textbox within a group in fabricjs My fabric application requires a feature that allows the user edit textboxes within groups. I almost have it working. As it stands, this is how my application works:

*

*Click on a group

*Checks to see if you are clicking on a textbox. If yes...

*Ungroups the group

*Sets the focus on the textbox so that the user can make edits.

*On "editing:exited," re-groups the objects

Here is a fiddle with my code:
https://jsfiddle.net/1dr8jn26/4/
Do the following to replicate my issue:

*

*Add 2 input boxes using the button at the top

*Group the input boxes using the button at the top

*Click once on one of the input boxes in the group you created

*Click on the canvas outside of the group

*Click back on the same input box

*Click on the canvas outside of the group again

*Repeat 5 & 6

You will notice that the group creates duplicates of itself off to the side of the page. What I have discovered on my own:

*

*"object.on('editing:exited... is what keeps getting run over and over.

*The "duplication counter" resets if you click on one input box vs another.

*When the duplicates appear, if you click on some of them, they disappear.

I am still relatively new to programming, so i'm sure this is something obvious to the experienced coders here. Any help would be appreciated!
canvas.on('mouse:down', function(options) {
if (options.target) {
    var thisTarget = options.target;
    var mousePos = canvas.getPointer(options.e);
    if (thisTarget.isType('group')) {
       var groupPos = {
            x: thisTarget.left,
            y: thisTarget.top
        }
var currentGroup = [];
var groupItems = []
groupItems = thisTarget._objects;
thisTarget.forEachObject(function(object,i) {
currentGroup[i] = object;
currentGroup.push(object);
})
        thisTarget.forEachObject(function(object,i) {
         if(object.type == "textbox"){
 console.log("Start for statement that finds the x and y for each
object")
var matrix = thisTarget.calcTransformMatrix()
var newPoint = fabric.util.transformPoint({y: object.top, x:
object.left}, matrix)
            var objectPos = {
                xStart: newPoint.x,
                xEnd: newPoint.x + object.width,
                yStart: newPoint.y,
                yEnd: newPoint.y + object.height
            }
            if (mousePos.x >= objectPos.xStart && mousePos.x <=
(objectPos.xEnd)) {
                if (mousePos.y >= objectPos.yStart && mousePos.y <=
objectPos.yEnd) {
function ungroup (group) {
groupItems = group._objects;
group._restoreObjectsState();
canvas.remove(group);
for (var i = 0; i < groupItems.length; i++) {
    canvas.add(groupItems[i]);
}
canvas.renderAll();
};
ungroup(thisTarget)
canvas.setActiveObject(object);
object.enterEditing();
object.selectAll();
object.on('editing:exited', function (options) {
var items = [];
groupItems.forEach(function (obj) {
    items.push(obj);
    canvas.remove(obj);
});
console.log(JSON.stringify(groupItems))
var grp = new fabric.Group(items, {});
canvas.add(grp);
                  });
                }
            }
        }
        });
      }
   }
});

-Chris

A: Have been looking at the code and I think I found a solution. The group is added two times in the group groupItems. Once at the start and a second time when ungrouping the items.
Used the code below in your fiddle and that works...
canvas.on('mouse:down', function(options) {
var groupItems;
if (options.target) {
    var thisTarget = options.target;
    var mousePos = canvas.getPointer(options.e);
    var editTextbox = false;
    var editObject;

    if (thisTarget.isType('group')) {
        var groupPos = {
            x: thisTarget.left,
            y: thisTarget.top
        }

        thisTarget.forEachObject(function(object,i) {
            if(object.type == "textbox"){
                var matrix = thisTarget.calcTransformMatrix();
                var newPoint = fabric.util.transformPoint({y: object.top, x: object.left}, matrix);
                var objectPos = {
                    xStart: newPoint.x - (object.width * object.scaleX) / 2,//When OriginX and OriginY are centered, otherwise xStart: newpoint.x - object.width * object.scaleX etc...
                    xEnd: newPoint.x + (object.width * object.scaleX) / 2,
                    yStart: newPoint.y - (object.height * object.scaleY) / 2,
                    yEnd: newPoint.y + (object.height * object.scaleY) / 2
                }

                if ((mousePos.x >= objectPos.xStart && mousePos.x <= objectPos.xEnd) && (mousePos.y >= objectPos.yStart && mousePos.y <= objectPos.yEnd)) {
                    function ungroup (group) {
                        groupItems = group._objects;
                        group._restoreObjectsState();
                        canvas.remove(group);
                        for (var i = 0; i < groupItems.length; i++) {
                            if(groupItems[i] != "textbox"){
                                groupItems[i].selectable = false;
                            }
                            canvas.add(groupItems[i]);
                        }
                        canvas.renderAll();
                    };

                    ungroup(thisTarget);
                    canvas.setActiveObject(object);

                    object.enterEditing();
                    object.selectAll();

                    editObject = object;
                    var exitEditing = true;

                    editObject.on('editing:exited', function (options) {
                        if(exitEditing){
                            var items = [];
                            groupItems.forEach(function (obj) {
                                items.push(obj);
                                canvas.remove(obj);
                            });

                            var grp
                            grp = new fabric.Group(items, {});
                            canvas.add(grp);
                            exitEditing = false;
                        }
                    });
                }
            }
        });
    }
}
});

Here is the fiddle: https://jsfiddle.net/u3Lfnja2/1/


text:
Q: MSAL idToken does not have upn, profile or email data? need it in idToken for passport-azure-ad authorization I have an angular8 app using the official msal package (not the one for angular, the main one) on the backend I'm authorizing using passport-azure-ad (official microsoft package)
I need to have the user's email address in the IdToken as I can't validate with bearer strategy against access token. I need some way to get that email address either through the UPN or directly.
I have tried 4 different accounts under different AD groups and so far only for 1 AD group it has actually showed an 'email' OR 'upn' field in the idToken.
Permissions configured in the app screenshot.
The options of the login request:
  private loginRequest: Msal.AuthenticationParameters = {
    scopes: ['user.read', 'email', 'profile', 'openid'],
    extraScopesToConsent: ['email']
  };

I have tried any variation I can think of, I tried having them starting with capital leters (Email, User.Read) like in the screenshot, I've tried swapping them around scopes & extraScopesToConsent, I've tried putting 'upn' anywhere but no luck.
Would it be possible to either:
A: Get that data somehow in the token
B: Get another token I can validate as 'bearer token' with my backend that has that data?

A: I ended up sending the email in the req body from frontend, then updated my passport strategy to use the request object.


text:
Q: Alternative to .trimmingCharacters to get my solution accepted by Coderbytes On my Xcode playground the following snippet trims the whitespaces from any String (as I want).
let trimmed = "   hello   ".trimmingCharacters(in: .whitespaces)

When I try to submit a solution using this syntax to Coderbytes it throws:

/tmp/005424279/main.swift:5:17: error: value of type 'String' has no
  member 'trimmingCharacters' let trimmed = "     hello      ".trimmingCharacters(in: .whitespaces)

The same thing happens when I try the Swift2 version of
 let trimmed = "   hello   ".stringByTrimmingCharactersInSet(in: .whitespaces)

There is no Intelligence on Coderbytes - and I'm really stumped for what would work to get my solution accepted. (I know I should just be happy I've solved the puzzle and not worry about Coderbyte accepting it - but, you know, you get competitive about building up a ranking!

A: It depends on the Swift version they are using.
For Swift 4 I used this:
import Foundation

let trimmed = "        hellloo     ".trimmingCharacters(in: CharacterSet.whitespaces)
print(trimmed)


text:
Q: I2C scanner freeze on "scanning ..." when using different addresses for MPR121 so i'm using an MPR121 sensor and an Arduino. the ADD pin of the MPR121 is connected to GND so it means that it's address is 0x5A and the I2C scanner works just fine but the problem is that when i connect ADD pin to change MPR121 address the I2C scanner program freezes on "scanning ...".
here's where i got my I2C  scanner code from
https://playground.arduino.cc/Main/I2cScanner/
schema :
SCL → A5
SDA→ A4
ADD → GND, 3.3v, SCL, SDA
IRQ → pin 4

A: [SOLVED] it was because of hard wiring, the solder bridges on the back of the MPR121 were badly welded.


text:
Q: Minted in listing: break code across pages? I'm using minted to highlight code. And I put that into a listing environment in order to get those numbered. By it self minted breaks code across pages. But when I put it into a listing, I get code on a separate page. Here's an MWE:
\documentclass{article}

\usepackage{minted}

\usepackage{lipsum}

\begin{document}

\lipsum[1-3]

\begin{listing}[H]
\begin{minted}{python}
# defs:
def fitfunc(p, coords):
    x0, y0, z0, R = p
    x, y, z = coords.T
    return sqrt((x-x0)**2 + (y-y0)**2 + (z-z0)**2)

# initial fit values:
BeadsCenter = (Beads.coordinates().max(axis=0)
              + Beads.coordinates().min(axis=0)) / 2
BeadsInSwell = Beads.selectAtoms("point {0} {1} {2} {3}".format(
               BeadsCenter[0], BeadsCenter[1], BeadsCenter[2],
               args.radius))

MaxZ = (BeadsInSwell.coordinates().max(axis=0)[2])
MinZ = (BeadsInSwell.coordinates().min(axis=0)[2])
b = MaxZ - MinZ

MaxY = (BeadsInSwell.coordinates().max(axis=0)[1])
MinY = (BeadsInSwell.coordinates().min(axis=0)[1])
a = MaxY - MinY

R0 = (a**2 / 4 + b**2) / (2 * b)

x0, y0, z0 = (BeadsInSwell.coordinates().max(axis=0)
             + BeadsInSwell.coordinates().min(axis=0)) / 2.
z0 = MaxZ - R0

# data:
coords = BeadsInSwell.coordinates()

# initial fit paramters:
p0 = [x0, y0, z0, R0]

# fit:
errfunc = lambda p, x: fitfunc(p, x) - p[3]
p1, flag = leastsq(errfunc, p0, args=coords)
\end{minted}
  \caption{Fit code (crucial part).\label{lst:fit}}
\end{listing}

\end{document}

I tried to put the listing environment in minipage, but it doesn't work.


text:
Q: Почему laravel из коробки медленно работает? Создал проект ларавель:
composer create-project laravel/laravel fresh

Запускаю сервер
php artisan serve

Постменом захожу на локалхост, время отклика 600мс
Переношу весь проект на рабочий сервер, получаю 550мс. При этом на нем же другие сайты работают с откликом 2-5 мс
Что может быть, ведь пустой проект, даже оптимизировать нечего
Локальный комп с ссд, как и сервер
Подскажите, что может быть не так настроено?


text:
Q: Sequential Backbone model.set overwrites model.changed attribute I'm sure I'm misunderstanding something about the purpose of the backbone models' changed, changedAttributes and set attribute/methods.  When I call set twice on a model, only the second attributes are included in the changed attribute. e.g:
model.set('field1', 'some diff value', {silent: true});
model.changed;   // => {'field1': 'some diff value'}

model.set('field2', 'some other value', {silent: true});
model.changed;   // => {'field2': 'some other value'}

What I'm expecting from the second access of changed is {'field1': 'some diff value', 'field2': 'some other value'}
I want the full list of changed values so I can optimise a sync to the server that would otherwise potentially drag in many other, large, unmodified fields.  I'm doing it currently with my own version of changed that is only equal to {} once the model has been saved to the server.
What am I missing / misunderstanding about Backbone?

A:
I want the full list of changed values so I can optimise a sync to the server that would otherwise potentially drag in many other, large, unmodified fields

Assuming you're using version 0.9.9+, you could pass in the patch option to your save call which will only send the changed attributes to the server. See Model save docs
model.set('field1', 'some diff value', {silent: true});
model.set('field2', 'some other value', {silent: true});
model.save({patch: true}); // field1 and field2 are only attributes saved to server

A: from the docs:

The changed property is the internal hash containing all the attributes that have changed since the last set. Please do not update changed directly since its state is internally maintained by set. A copy of changed can be acquired from changedAttributes.

Looking at the annotated source it looks like the only way to do what your after is to call save on the model passing in all the changed fields and the option patch: true
model.save({'field1': 'some diff value', 'field2': 'some other value'}, {patch: true})
another option could be to listen to all change events on the model and mange an internal change map; be sure to flush this map when you update server side.


text:
Q: Netplan doesn't create default route OVH cloud host allows an easy way to route multiple blocks of their IPs to virtual MACs on one interface. For example, eth0 has an address on the 40.30.20.0/24 network with a gateway of 40.30.20.254, but their router is setup to also route traffic for 45.35.25.15/32 to that same interface. My VM's are macvtap'd off the host interface, with this virtual MAC assigned. When I try to setup netplan, I use this config:
network:
  version: 2
  renderer: networkd
  ethernets:
    ens3:
      addresses:
        - 45.35.25.15/32
      gateway4: 40.30.20.254
    nameservers:
      addresses: [213.186.33.99]

Normally, that gateway4 piece should give me a default route, but since it's outside the subnet, it barfs. I can't find a specific error in the logs. After applying netplan, and even rebooting, my route command is blank (no routes at all). ifconfig shows the interface is up and configured, just no routes. It's the only interface on the VM (besides lo), and all it takes to fix it is sudo ip route add default dev ens3, so why can't netplan just add such an obvious route to the only interface?? This bug seems related, but never got addressed.
How do I use netplan to get a default route in this scenario?


text:
Q: What's the difference between return; and return undef; in Perl Is there a difference between a subroutine that does
return;

and one that does?
return undef;

A: return; will return an empty list in list context but undef in scalar context.  return undef; will always return a single value undef even in list context.
In general, it's usually not a good idea to return undef; from a subroutine normally used in list context:
sub foo { return undef }
if ( my @x = foo() ) {
    print "oops, we think we got a result";
}

In general, it's usually not a good idea to return; from a subroutine normally used in scalar context, because it won't behave as the user expects in list context:
sub foo { return }
%x = ( 'foo' => foo(), 'bar' => 'baz' );
if ( ! exists $x{'bar'} ) {
    print "oops, bar became a value, not a key";
}

Both of these errors happen quite a bit in practice, the latter more so, perhaps because subs that are expected to return a scalar are more common.  And if it's expected to return a scalar, it had better return a scalar.

A: Given
sub foo { return; }
sub bar { return undef; }

In scalar context, they behave the same.
my $foo = foo();   # $foo is undef
my $bar = bar();   # $bar is undef

In list context, they behave differently
my @foo = foo();   # @foo is ()  (an empty list)
my @bar = bar();   # @bar is ( undef )  (a one-element list)

Note that a one-element list is a true value in boolean context, even though the only element is undef.
In general, it's usually not a good idea to return undef; from a subroutine, because of how it behaves in context.

A: I think I still agree with PBP though.
1) You should avoid nesting function calls:
my $result = bar();
foo(1, $result, 2);

2) You should always be explicit (when doing "complicated" things):
foo(1, scalar bar(), 2);

A: The book "Perl Best Practices" recommends the use of return; instead of return undef; because the latter would return a one-element list in list context (the other answers already mention this). This would be a "nasty bug" according to the book.
However, I think returning nothing can actually cause serious bugs (probably difficult to find), whereas calling a boolean function in list context seems rather simple to debug.
So I always return something (that evaluates to) false in my boolean functions (usually 0 for false and 1 for true).
(Yes, this would also return a one-element list in list context - so the comment in the book is technically right -, but then the actual error would be calling the boolean function in list context.)
To be clear, I still recommend the book. It offers a lot of good advice.
And I am referring to Chapter 9 (Subroutines), page 199/200 ("Use a bare return to return failure.") in the book "Perl Best Practices" by Damian Conway (O'Reilly Media, Inc.), ISBN 978-0-596-00173-5. Not sure if there's another/newer edition.
Side note:
Perl seems to return an empty string when negating something. my $foo = 5; return !$foo; returns q().


text:
Q: Is it possible to use the id from taggable friends api for the see friendship feature? This is going off this thread retrieve full list of friends using facebook API. The answer said that "So, in v2.0 you'll only be able to get all friends via the /me/taggable_friends (https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends) endpoint, which only contains the fileds id, name, picture, and only can be used after a review of your app by Facebook" and one of the comments said that "You should be aware the even after a review and permission to use taggable_friends, the IDs you get back can only be used to tag friends - you can't use those IDs to get any other information about a user." Does that mean that I would not be able to use see friendship with the id from taggable friends? Usually for see friendship, you go to it by going to this url https://www.facebook.com/profile.php?id=person1Id&and=person2Id
Would the ids from taggable friends work as parameter vales and and?
Would that be a case of using that id to get information about a user?

A: Taggable_friends can only be used to tag people. You can not use it for anything else.


text:
Q: When should you start studying proofs when taking subjects like Calculus? For example, say I plan on studying Calculus. Calculus itself has many theorems and, as such, it has many proofs one should learn during his/her math career. But when is it recommended go and learn this proofs? I see three options:

*

*Go through the proof as soon you stumble upon a theorem/rule and learn how to apply it to some problems.

*Learn how to apply everything you learn from a subject such as Calculus I and then, after that, you go and learn every proof in Calculus I. And repeat the same for II and III.

*Like 2, but instead you learn Calculus I, II and III in a row and then you learn the proofs.

It seems option 1 would be the most rigorous, I wonder if it carries more benefits other than actually understanding why things work as soon as you see them working.

A: My recommendation . . .

While learning Calc 1,2,3, learn the concepts well, including the heart of the reasons why things are true, but go light on the proofs, else you'll take away the "joy of Calculus".

If you're heading towards Math Major, definitely start doing easy, fun proofs from other areas of Math, with independent study.

High School level contest exams provide a wealth of challenging problems, and working on them can promote the development of both problem solving skills and proof skills.

Also, echoing imranfat's comment, master precalculus. It's the base.