text:
Q: CRON starts to skipping to the next minute I am setting up single minute crons to the crontab via a bash script for a load testing purpose. There is no issue with the script executing and the crons are added up and i can monitor crons are being executed via the /var/log/cron.
But the issue is when I informed the script the other day to 106 crons it added and they were executed nicely. But today I reset the crontab from scratch and I only able to set up 85 crons.Then it starts to say
crond[31243]: (root) INFO (Job execution of per-minute job scheduled for 08:32 delayed into subsequent minute 08:33. Skipping job run.)
and eventually all the crons will started to get skipped and nothing will get executed. But initial conclusion I had was 106 is the maximum value that can be st up on this server. But today it got reduced to 85. Server configurations weren't changed;same environmnet as it when it was 106
Is this because of the setting up crons too frequently or something else. I'm new to cron and its workings. Please help

A: It sounds like you're setting up a cron schedule with crontab with many entries with identical schedules in the expectation that cron will execute those in parallel for you.
* * * * * /path/to/task1
* * * * * /path/to/task2
* * * * * /path/to/task3
...

That is not exactly what happens:
In most cron implementations I know the tasks will be started in sequential order, not in parallel, in the order the tasks are listed in the crontab file. Cron will start them one after another...
Cron won't need to wait for task1 to complete before starting task2, but will only start task3 after task1 and task2 are started etc. Once started the tasks will run in parallel (for as long as it takes the tasks to complete.)
The tasks that need to be started and the load on the system at the time will limit how fast cron can start new tasks. When cron can't start all tasks in the allotted time interval and the next iteration of your schedule (a new minute) starts, it will forfeit the tasks that couldn't be started. That will result in the error:

Job execution of per-minute job scheduled for 08:32 delayed into subsequent minute 08:33. Skipping job run.

It sounds like you want to start many identical tasks in parallel:
* * * * * /path/to/task
* * * * * /path/to/task
* * * * * /path/to/task
...

simply use the parallel helper program to that that for you;
* * * * * parallel -j 50 /path/to/task

Please note that when your parallel tasks don't finish within a single minute, the next minute 50 additional runs of your task will start regardless, which, with the additional load of those tasks that are still running, will also be running longer that 1 minute. After some time your system will probably run out of resources and become completely unresponsive.


text:
Q: Creating an empty bitmap and drawing though canvas in Android I'd like to create an empty bitmap and set a canvas to that bitmap and then draw any shape on the bitmap.

A: This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's the official documentation on the topic: Custom Drawing

A: Do not use Bitmap.Config.ARGB_8888
Instead use
    int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps.
Or better yet, try avoiding usage of ARGB option itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What to do instead of nested fragments? I've read here: http://developer.android.com/about/versions/android-4.2.html#NestedFragments that "Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically."
Is there any other way to make UI elements hierarchical/reusable besides fragments? For example, I have a SelectLogFileFragment that has some checkboxes/textboxes that I want to be able to use to setup log files from multiple places. If one of those places happens to itself be a fragment, I run into the "can't inflate a layout into a fragment when the layout contains a ".
What are my other options here?

A: You should be using fragments. It is just saying don't put the fragment in the xml. In your FragmentActivity, simply add the fragment to the container in the xml. The xml in your case will be a bunch of containers. That way you can nest to your heart's content!

A: One solution you could use is a call back design where you would have pass the creation of the nested fragment off to the activity.  This woud allow more flexibilty in your design a help you avoid the nested fragments.  Here is an example of the design I'm referring to.


text:
Q: How Can I connect the emulated device on genymotion on windows with the adb on wsl? I'm trying to setting up an environment to develop in react native.
I've installed the sdk-android, the npm of react native on wsl and the genymotion on windows.
I want to use the vscode on windows and run the project on wsl and emulate on genymotion.


text:
Q: Changing BorderStyle inside OnCreateControl causes it to fire again I have an extended RichTextBox:
public class RichTextBoxEx : RichTextBox
{
    protected override void OnCreateControl()
    {
        Text = "Hello World";
        base.OnCreateControl();
    }
}

When I remove the border using BorderStyle = BorderStyle.None;, the method is called twice:
protected override void OnCreateControl()
{
    BorderStyle = BorderStyle.None;
    Text = "Hello World";
    base.OnCreateControl();
}

Why is this happening?

A: When setting BorderStyle, it checks if the new border style is different from the current value, it recreates the handle which result in a call to OnCreateControl at the end of method calls.
If you want to change the default value for BorderStyle property which has been set in TextBoxBase control, the correct location is in constructor of your control:
public class RichTextBoxEx : RichTextBox
{
    RichTextBoxEx ()
    {
        BorderStyle = BorderStyle.None;
    }
}

The Text property is different. I've described about it an answer to your other question.


text:
Q: Python Parsing JSON objects from logfile Currently I am looking to parse through a logfile where each line is represented as individual JSON objects
Example:
{"timestamp":"2021-09-15T14:56:28Z","event":{"agentId":"Foo/2.1.0 [foo.bar.java/3.207.3]","stage":"CLOSE","type":"TEST_RESULTS","testId":["uuid"],"threadId":16,"stackTrace":"com.Foo.logSessionResultsAndThrowException()","data":{"url":"foobar","status":"Unresolved"}},"level":"Notice"}
{"timestamp":"2021-09-15T14:58:28Z","event":{"agentId":"Foo/2.1.0 [foo.bar.java/3.207.3]","stage":"CLOSE","type":"TEST_RESULTS","testId":["uuid"],"threadId":16,"stackTrace":"com.Foo.logSessionResultsAndThrowException()","data":{"url":"foobar","status":"Passed"}},"level":"Notice"}
{"timestamp":"2021-09-15T14:58:28Z","event":{"agentId":"Foo/2.1.0 [foo.bar.java/3.207.3]","stage":"CLOSE","type":"TEST_RESULTS","testId":["uuid"],"threadId":16,"stackTrace":"com.Foo.logSessionResultsAndThrowException()","data":{"url":"foobar","status":"Passed"}},"level":"Notice"}

Based on how it's output, I'm unable to format it as a json file
Is there a way I can do the following:

*

*Read through the log file

*Find the objects that match specific criteria (i.e., "type":"TEST_RESULTS")

*Output the lines that matched the criteria (in this case, only output the object:

{"timestamp":"2021-09-15T14:56:28Z","event":{"agentId":"Foo/2.1.0 [foo.bar.java/3.207.3]","stage":"CLOSE","type":"TEST_RESULTS","testId":["uuid"],"threadId":16,"stackTrace":"com.Foo.logSessionResultsAndThrowException()","data":{"url":"foobar","status":"Unresolved"}},"level":"Notice"}

Thanks in advance; I'm not the greatest with how Python does things


text:
Q: Can I use Android PreferenceActivity / PerferenceManager to store a user managed list of strings? My application requires a list of strings that is editable by the user.
There is a default list of strings but the user must be able to add or delete any number of strings. These changes need to be stored for use in multiple activities.
Is this something that the PreferenceActivity / PreferenceManager is able to do out of the box? Or does it require custom code? Or am I thinking in the wrong space entirely?
Thanks for your help

A: SharedPreferences are meant for small data like key-value pairs.
It can also be used to store Sets.
If the data is very big, better go for Database.


text:
Q: How to block incoming ports using group policy in active directory windows server 2012 We have a domain, and there are some computers in this domain. we applied some many policies like password policy and etc to this domain which makes it easier for us to control the use PC in our organization. Now I wonder if it is possible to stipulate a certain configuration for every PC's firewall in our domain or to force every PC in domain at least block some certain Ports and maybe IPs. Can any one help me? Is it possible?

A: You can create GPOs for the firewall here:
Computer Configuration -> Administrative Templates -> Network -> Network Connections -> Windows Firewall
Then apply them to your computer group(s) as desired.


text:
Q: Pandas change cell color I am trying to change the cell colour if the cell contains a string from a list of strings:
This allows me to change the colour if there is a match but it doesn't appear to go through every item in the list it only does the first match (i think this is because of the ==)
def color_negative_red(val):
    for technique in techniques:
        color = 'green' if val == technique else 'black'
        return 'color: %s' % color

I am trying the following but that doesn't appear to be changing any colours:
def color_negative_blue(val):
    for technique in techniques:
        color = 'blue' if technique in val else 'black'
        return 'color: %s' % color

I call these functions as followed:
s = df1.style.applymap(color_negative_blue)

I want to be able to go over a list of items and if the item from the list exists then change the colour of that text in the cell.
DataFrame:
Column1                Column2              Column3          Column4

Acquire               Infrastructure        Botnet      Drive-by Compromise
DNS Server                                               Exploit Public-Facing Application
Domains                                                 External Remote Services
Server                                                  Hardware Additions
Virtual Private Server                    Phishing      Spearphishing Attachment
Web Services                              Spearphishing Link
Compromise Accounts Email Accounts                      Spearphishing via Service
Social Media Accounts                                   Replication Through Removable Media

techniques = ['Server','Web Services', 'Phishing']

A: Replace any cell when its content matches techniques:
def my_func_blue(val):
   if val in techniques:
      return "color: blue"
   else:
      return "color: black"

df.style.applymap(my_func_blue).render()

A: def my_func_blue(val):
    if val in techniques:
        color = 'green'
        return f'background-color: {color}'
    else:
        color = 'red'
        return f'background-color: {color}'

the above code allows me to carry out the searches and change the color of the cell that it has matched on


text:
Q: Jquery Body change event? How to capture the body change event in the attached image source?
Basically i want to set max characters to ajaxcontrol html editor without using any other third party control.

I have tried the following script, but no luck.
$('body', $('iframe#MainContent_VWIContent_AdminContent_ManageLoginPageMsgControl_txtHtmlMessage_ctl02_ctl00').contents()).on('keyup', function (e) {
    alert('testing');
});


text:
Q: cannot convert void to "classname" im trying to create a class that is a thread that can be stored in an array, which will make it easier for me to handle user inputs from clients to the server.
here is my PongPlayerThread
package Pong;

import java.net.*;
import java.io.*;

public class PongPlayerThread extends Thread
{
private Socket socket = null;
private String pongData = "";

public PongPlayerThread()
{
    //clear
}

public PongPlayerThread(Socket socket, int id, String data)
{
    //super("PongPlayerThread");
    pongData = data;
    this.socket = socket;
}

public void passData(String data)
{
    pongData = data;
}

public void run()
{
    try
    {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        while(true)
        {
            out.println(pongData);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

}

now in this line on my server where a client can connect
players[0] = new PongPlayerThread(serverSocket.accept(), 0, rtnInfo()).start();

I get this error
"cannot convert from void to PongPlayerThread" why is that? I have searched but it is quite hard when you get the error with your classname.
I now have this code
        players[idPlayer] = new PongPlayerThread(serverSocket.accept(), idPlayer, rtnInfo());
        players[idPlayer].start();

but when a client connects i get this error
Pong
400.0:301.0:60.0:300.0:740.0:300.0
Server started
Server was setup and will try to create a socket
Exception in thread "main" java.lang.NullPointerException
    at Pong.PongServer.main(PongServer.java:82)
the line it is pointing at is
    players[idPlayer] = new PongPlayerThread(serverSocket.accept(), idPlayer, rtnInfo());
???

A: players[0] = new PongPlayerThread(serverSocket.accept(), 0, rtnInfo());
players[0].start();

A: The problem is that Thread.start() returns void, and you are trying to assign the result of new PPT(...).start() to players[0].
new PPT(...).start() returns void, and so the compiler is complaining that it can't convert this void into an object of type PongPlayerThread.


text:
Q: Finding path name to use as a slug for custom built cms with PHP I'm building a website with a custom content management system, and I want to build a slug area like wordpress. I want to retrieve the path name from my front-end depending on the page they're on, and echo that out in my backend in the slug area.
I'm using php and my front-end is dynamic, which means I have one page, and depending on what the user clicks on, I will include that file.
What I want the code to look like for the slug in the backend:
<?php
//front end path/ echo $slug;
?>

My front-end path looks something like this: blahblah/index.php/slug-name
I have a slug stored in the database that I will echo out, but my problem is I don't know how to retrieve the front end path and echo it out in the backend. I realize I can type the front-end path manually, but I think doing it dynamically would be better incase I move my website to a different location in the future.
I've tried using pathinfo or $_SERVER but that echos out my backend path rather than my front end.
Hopefully I was clear, if not, ask me to clarify something. Thanks again.

A: You need the rewrite module for apache or nginx.
That allows you to do like this:

PrettyPath(This will be seen to all visitors): http://blah.com/blah/bl/ah/test
=> RealPath(This can be used for develop): http://blah.com/blah/index.php?slug=bl/ah/test

You can do beautiful job like this for using rewrite module. (Rewrite Example)

A: $front_end_path = 'your/site/path';
$full_url = $front_end_path . $slug;


text:
Q: Prove that $v(t,x) = xu_x(x,t) + 2tu_t(x,t)$ satisfies the heat equation using the fact that $u^{\lambda} = u(\lambda x, \lambda^2t)$ satisfies it Let $\lambda \in \mathbb{R}$ and denote $u_x(x,t) = \frac{d}{dx}u(x,t).$
Let $u$ satisfy the heat equation $u_t - u_{xx} = 0$ on $\mathbb{R}\times(0,\infty).$ Prove that $v(t,x) = xu_x(x,t) + 2tu_t(x,t)$ satisfies the heat equation using the fact that $u^{\lambda} = u(\lambda x, \lambda^2t)$ satisfies the heat equation.
My attempt:
I've proved that $u^\lambda$ satisfies the heat equation, and I can prove that $v$ satisfies it by just taking the proper derivatives. I'm just really not sure what I can do to use $u^{\lambda}$ in the proof, since the problem is asking that I use it, specifically, I suppose I should! Any hints would be appreciated!

A: Hint: $$v=\left.\frac{d u^{\lambda}}{d\lambda}\right|_{\lambda=1}$$


text:
Q: How to fix this deprecated use of std::allocator? Here are the key points:
1: This project uses the open-source repository NanoRT as a raytracer in a project.
2: This project is compiled under Visual Studio 2019 (C++17)
3: This project is compiled with warnings treated as errors (and this cannot be changed). Adding the define to suppress these warnings did not help.
However, it looks like part of this code does not work in C++17, as it uses something that has become deprecated: (line 133 and 134 in the link I provided)
  typedef typename std::allocator<T>::pointer pointer;
  typedef typename std::allocator<T>::size_type size_type;

I need to figure out how to approach fixing this. The error suggests using std::allocator_traits but I am really unfamiliar with this use of std::allocator or allocator_traits.
Looking at the source, is this a few-line fix, or is this much more complicated than that and would require restructuring large portions of the code?
It looks like pointer is used as the return for allocate() and the first argument to deallocate(), with size_type being used in the same way.
  // Actually do the allocation. Use the stack buffer if nobody has used it yet
  // and the size requested fits. Otherwise, fall through to the standard
  // allocator.
  pointer allocate(size_type n, void *hint = 0) {
    if (source_ != NULL && !source_->used_stack_buffer_ &&
        n <= stack_capacity) {
      source_->used_stack_buffer_ = true;
      return source_->stack_buffer();
    } else {
      return std::allocator<T>::allocate(n, hint);
    }
  }

  // Free: when trying to free the stack buffer, just mark it as free. For
  // non-stack-buffer pointers, just fall though to the standard allocator.
  void deallocate(pointer p, size_type n) {
    if (source_ != NULL && p == source_->stack_buffer())
      source_->used_stack_buffer_ = false;
    else
      std::allocator<T>::deallocate(p, n);
  }

A: There's a couple of ways to address this, and one size doesn't fit all.
The simplest path:
For std::allocator<T>, the type std::size_t is always the same as size_type, and the type T* is always the same as pointer.  So the easiest thing is to just sub in those types.
The std::allocator_traits path:
These types also exist as nested types of the type std::allocator_traits<std::allocator<T>>.  So you can access them like this:
std::allocator_traits<std::allocator<T>>::pointer

It is common to create type aliases to cut down on the verbosity:
using pointer = std::allocator_traits<std::allocator<T>>::pointer;

Irony:  allocator<T>::size_type is "de-deprecated" in C++20.

A: Replace std::allocator<T>::pointer with T* and std::allocator<T>::size_type with std::size_t. That is what those deprecated member type aliases are defined as.

is this a few-line fix, or is this much more complicated than that and would require restructuring large portions of the code?

This seems like a trivial change.

The error suggests using std::allocator_traits

std::allocator_traits should be used if the allocator type is templated. That appears to not be the case here, and so using std::allocator_traits would be unnecessary.
But if we were to fix the problem in a case where the allocator is templated: Let's say the template argument is Alloc. Then you should replace Alloc::pointer with std::allocator_traits<Alloc>::pointer and Alloc::size_type with std::allocator_traits<Alloc>::size_type.

However, it looks like part of this code does not work in C++17, as it uses something that has become deprecated

Actually, use of deprecated features still works. It should still be fixed though since it will stop working in C++20. std::allocator<T>::pointer has been removed in C++20.


text:
Q: Golang struct to Json schema Hi I need to infer a json schema (github.com/go-openapi/spec.Schema) from a struct :
type Testcase struct {
    Id           string    `json:"id,omitempty"`            // id of this test case
    Name         string    `json:"name,omitempty"`          // name of this test case
    CreationDate time.Time `json:"creation_date,omitempty"` // timestamp when the scenario was first created
    UpdateDate   time.Time `json:"update_date,omitempty"`   // last update timestamp
    Steps        []Step    `json:"steps,omitempty"`         // list of steps  type:"[]StepCcs"
}

I can't find a simple way to do so.
I guess that this is a prerequisite for many REST frameworks out there that generate open api spec from the code.
Can someone point me out to a package that contains such helper : ie
func toSchema(obj interface{}) (spec.Schema, error)

A: https://github.com/invopop/jsonschema
is what you are looking for.
type TestUser struct {
  ID            int                    `json:"id"`
  Name          string                 `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"`
  Friends       []int                  `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"`
  Tags          map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"`
  BirthDate     time.Time              `json:"birth_date,omitempty" jsonschema:"oneof_required=date"`
  YearOfBirth   string                 `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"`
  Metadata      interface{}            `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"`
  FavColor      string                 `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"`
}

Results in following JSON Schema:
jsonschema.Reflect(&TestUser{})

A: Huma's schema package can do this. Be sure to check out all the validation tags that are available. Example:
import "github.com/danielgtaylor/huma/schema"

// First define some structs:
type Child struct {
    Name string `json:"name" doc:"Child name"`
}

type Hello struct {
    Greeting string    `json:"greeting" maxLength:"80" doc:"A greeting message"`
    Optional uint      `json:"optional,omitempty" doc:"Optional integer example"`
    Child    *Child    `json:"child,omitempty" doc:"Child struct example"`
    Labels   []string  `json:"labels" maxItems:"10" doc:"Array example"`
    Created  time.Time `json:"created" doc:"Created time for this greeting"`
}

// Then later you can do:
s, err := schema.Generate(reflect.TypeOf(Hello{}))

https://go.dev/play/p/4F8NpcgZ4Yh
This will output:
{
  "type": "object",
  "properties": {
    "child": {
      "type": "object",
      "description": "Child struct example",
      "properties": {
        "name": {
          "type": "string",
          "description": "Child name"
        }
      },
      "additionalProperties": false,
      "required": [
        "name"
      ]
    },
    "created": {
      "type": "string",
      "description": "Created time for this greeting",
      "format": "date-time"
    },
    "greeting": {
      "type": "string",
      "description": "A greeting message",
      "maxLength": 80
    },
    "labels": {
      "type": "array",
      "description": "Array example",
      "items": {
        "type": "string"
      },
      "maxItems": 10
    },
    "optional": {
      "type": "integer",
      "description": "Optional integer example",
      "format": "int32",
      "minimum": 0
    }
  },
  "additionalProperties": false,
  "required": [
    "greeting",
    "labels",
    "created"
  ]
}


text:
Q: When does Go allocate a new backing array to slice? When reading up on Go slices, I came across this behaviour in the context of the append method

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.
Source - Golang Tour

To understand this I wrote the following piece of code:
Try on the Go Playground
func makeSlices() {
    var a []int;

    a = append(a, 0)

    b := append(a, 1)
    printSlice("b", b)

    c := append(a, 2)
    printSlice("b", b)
    printSlice("c", c)

}

func printSlice(name string, s []int) {
    fmt.Printf("var=%v len=%d cap=%d first_address=%v %v\n", name, len(s), cap(s), &s[0], s)
}

Output:
var=b len=2 cap=2 first_address=0x414020 [0 1]
var=b len=2 cap=2 first_address=0x414020 [0 2]
var=c len=2 cap=2 first_address=0x414020 [0 2]

I would expect b and c to point to the same underlying array as they both are slices of the same length

But if I were to vary the same code for another length of slice:
Try on the Go Playground
func makeSlices() {
    var a []int;

    a = append(a, 0, 9)

    d := append(a, 1, 2)
    printSlice("d", d)

    e := append(a, 3, 4)
    printSlice("d", d)
    printSlice("e", e)
}

Output:
var=d len=5 cap=8 first_address=0x450020 [0 0 9 1 2]
var=d len=5 cap=8 first_address=0x450020 [0 0 9 1 2]
var=e len=5 cap=8 first_address=0x450040 [0 0 9 3 4]

In this scenario, d and e should point to the same backing array as they are again slices of the same length but they do not.

Why this anomaly in behaviour? When exactly does Go decide to allocate a new backing array to a slice?

A: The answer is simple: append() allocates a new backing array (and copies current content over) if the elements to be appended do not fit into the current capacity. Formally:
if len(s) + len(newElements) > cap(s) {
    // Allocate new backing array
    // copy content (s) over to new array
} else {
    // Just resize existing slice
}
// append (copy) newElements

So for example if len=2, cap=4, you can append 2 elements, no allocation.
If len=2, cap=4, and you append 3 elements, then len+3 > cap, so a new backing array will be allocated (whose capacity will be greater than len+3, thinking of future growth, but its length will be 2+3=5).
Explaining your first example
In your first example you declare a slice variable that will have 0 length and capacity.
var a []int
fmt.Println(len(a), cap(a)) // Prints 0 0

When you do the first append, a new array will be allocated:
a = append(a, 0)
fmt.Println(len(a), cap(a)) // Prints 1 2

When you do another append, it fits into the capacity, so no allocation:
fmt.Println(len(a), cap(a)) // Prints 1 2
b := append(a, 1)
fmt.Println(len(b), cap(b)) // Prints 2 2

But this time you store the result slice in b, not in a. So if you do your 3rd append to a, that still has length=1 and cap=2, so appending another element to a won't require allocation:
fmt.Println(len(a), cap(a)) // Prints 1 2
c := append(a, 2)
fmt.Println(len(c), cap(c)) // Prints 2 2

So excluding the first append, all other append don't require allocation, hence the first allocated backing array is used for all a, b and c slices, hence addresses of their first elements will be the same. This is what you see.
Explaining your second example
Again you create an empty slice (len=0, cap=0).
Then you do the first append: 2 elements:
a = append(a, 0, 9)
fmt.Println(len(a), cap(a)) // Prints 2 2

This allocates a new array with length = 2, so both length and capacity of the slice will be 2.
Then you do your 2nd append:
d := append(a, 1, 2)
fmt.Println(len(d), cap(d)) // Prints 4 4

Since there is no room for more elements, a new array is allocated. But you store the slice pointing to this new array in d, not in a. a still points to the old array.
Then you do your 3rd append, but to a (which points to the old array):
fmt.Println(len(a), cap(a)) // Prints 2 2
e := append(a, 3, 4)
fmt.Println(len(e), cap(e)) // Prints 4 4

Again, array of a can't accommodate more elements, so a new array is allocated, which you store in e.
So d and e have different backing arrays, and appending to any slice that shares a backing array with "another" slice doesn't (can't) change this "another" slice. So the result is that you see the same address for d twice, and a different address for e.

A: I added another few lines to your example, have a look here.
Look at the first printSlice("a", a). The length is 1, capacity is 2. When you add an item there is no need to allocated a larger underlying array, so the same array is used for b and c.
Once the length goes beyond 2, (d := append(c, 3)), a new backing array is allocated for d. c remains unchanged. So when e is created the same process occurs with another new backing array created.


text:
Q: How to find the second element in a stream satisfying some condition? I want to display the second element of the stream for which the name starts with 's'.
I tried:
employees.stream()
         .filter(e -> e.getName().charAt(0) == 's')
         .findAny()
         .ifPresent(e -> System.out.println("Employee : " + e));

However, when I use findAny(), it returns the first element in the stream (same as findFirst()) and I want the second one.

A: You can skip the first match by adding skip(1) after the filter:
employees.stream()
         .filter(e -> e.getName().charAt(0) == 's')
         .skip(1)
         .findAny()
         .ifPresent(e -> System.out.println("Employee : " + e));


text:
Q: How to store big variables in a redstone RAM memory? I've just made a simple RAM memory in Minecraft (with redstone), with 4 bits for the address and 4 bits stored in each cell. Our next goal is to store different kinds of variables in it and to process them differently.
We are not engineers, so we don't really know nothing, but we have made already some quite complex things and we think we can do this. The problem is that we can't figure out how to store variables that of more bits that can be stored in a single cell. I'll give an example.
Think of a 16 bit variable. We thought that there's no sense in creating so big cells so we decided to store that data storing 4 bits in each cell. But that's not enough, we had to relate that 4 cells. So we thought that we had to create 8 bit cells, with 4 bits of content and 4 bits to store the address where the next 4 bits of the variable are stored. However, 4 bits of address is nothing for a RAM memory, we can't store anything there. So we would need at least 8 bits for the address. 4 bits of content also seems quite low, and we also need at least other 4 bits to store the type of the variable.
Well, finally we thought that that technique was absurd and that it couldn't be done like that in real life. And we don't know how to do it now. I've searched on the web about how the RAM memory works and the few that I've find was too complex for our needs. Could someone please explain us how this is done in real life and how we can apply it to redstone?

A: While going over how memory works in real life is pretty out of scope for Arqade, rather than chaining memory cells together, you could use a set number of cells for the address and the rest for the data.
So let's say you have 16 8-bit memory cells, and you want to store 16-bit values. Your current solution would be something like this:
# Value NextAdr
0 0000  0001
1 1111  0010
2 0100  0011
3 1111  0000

And so on, meaning for every 16 bits of data you want to store, you have to allocate 32 bits of cells. Instead, use the first cell to specify the two parts of the 16 bit value:
# Addr1 Addr2
0 0001  0010

# Value
1 11110010
2 01000011

Which would only require 24 bits of allocation per 16 bits of data.
You could further improve the efficiency by allocating one static 8-bit cell as a pointer. So, given 16 8-bit memory cells, you could hold 14 16-bit values, with an extra 8-bit cell left over.
Value 1:
Cell 0: 11110000 Cell 1: 01010101

Value 2:
Cell 2: 11110000 Cell 3: 01010101

# Access Value 1
Pointer cell: 0000 0001

# Access Value 2
Pointer cell: 0010 0011

Doing it this way is also scalable. If you need 32-bit values or 32 8-bit cells, assign two 8-bit cells as a pointer; 64-bit values or 64 8-bit cells, assign three cells as a pointer; and so on.
You could save even more space by making assumptions about where the parts of the value are stored. If, for example, the first part of the value is always proceeded by the second half, you don't need to keep track of the second half's address, cutting the pointer size in half:
Value 1:
Cell 0: 11110000 Cell 1: 01010101

Value 2:
Cell 2: 11110000 Cell 3: 01010101

# Access Value 1
Pointer cell: 0000

# Access Value 2
Pointer cell: 0010

Real world memory is a little more complicated than this, but it follows the same principles, and it should give you a good idea of how to improve your memory storage.

A: sounds like you need to store more than you can hold, try a 16 bit CPU (16 per cell) with 4 bits allocated as op code (16 functions decoded), 1 bit for a # (data / address storage multiplexer), and the remaining 11 bits as possable data entry, giving either a storage value up to 121, OR a value to controll one of 121 data cells or (bytes)

A: In a real computer, values larger than one addressable memory cell are stored in adjacent memory cells. That is, if you have a 16-bit value to store in your 4-bits-per-cell memory, you store it in 4 cells, perhaps with addresses 0100, 0101, 0110, 0111.
This means that you do not need to store any extra pointers (addresses); the memory is used efficiently. All you need to do to fetch the entire value is to fetch one cell and increment the address, four times.
Also note that "value followed by address of the next part" is a common data structure known as a linked list. It's quite useful for some purposes, but in this case is a waste.


text:
Q: how to display class data members stored in multimap here is the code
class student
{
int num;
string name;
float marks;
public:
void add()
{
    cout << "Enter the num name and marks:" << endl;
    cin >> num >> name >> marks;
}
void display()
{
    cout << num << endl;
    cout << name << endl;
    cout << marks << endl;
}
};
void main()
{
student ss;
multimap<int,student> st;
multimap<int,student>::iterator itr;
    ss.add();
    st.insert(make_pair(1000, ss));

for (itr = st.begin(); itr != st.end(); itr++)
{
    cout << itr->second; // its showing ERROR
}
}

the error is
Error   C2679   binary '<<': no operator found which takes a right-hand operand of type 'student' (or there is no acceptable conversion)    firstmultimap
how to fix this

A: To display the student object you need to overload << operator.
I have made the operator overloading function friend of student class so it could be called without creating an object.
Also, check this example on MSDN.
Example:

#include<iostream>
#include<map>
#include<string>
using namespace std;
class student
{
private:
    int num;
    string name;
    float marks;
public:
    void add()
    {
        cout << "Enter the num name and marks:" << endl;
        cin >> num >> name >> marks;
    }
    void display()
    {
        cout << num << endl;
        cout << name << endl;
        cout << marks << endl;
    }
    friend ostream &operator << (ostream &output, const student &s)
    {
        output << "Num: " << s.num << "\nName: " << s.name << "\nMarks: " << s.marks << endl;
        return output;
    }
};

int main()
{
    student ss;
    multimap<int, student> st;
    multimap<int, student>::iterator itr;
    ss.add();
    st.insert(make_pair(1000, ss));
    for (itr = st.begin(); itr != st.end(); itr++)
    {
        cout << itr->second;
    }
    // Using Range based for loop
    // for(const auto &i : st)
    //     cout << i.second;
    return 0;
}


text:
Q: Mongoid: return embedded_in class How can I get name of the class of the object which embeds my instance:
class Person
  include Mongoid::Document
  embeds_many :addresses
end

class Address
  include Mongoid::Document
  embedded_in :person
end

my_instance = Person.first.adresses.first
my_instance.embedded?
#=> true
my_instance.embedded_class????? # <=== I need to get this
#=> Person

A: You have two options:
my_instance.metadata.inverse_class_name.constantize
# or use the undocumented _parent method
my_instance._parent.class


text:
Q: Passar e declarar parâmetro (matriz) em Polymer eu preciso passar o seguinte prametro pra um elemento polymer:
[
  ["id", "nome",     "idade"],
  [1,    "matheus",  16],
  [2,    "cristian", 16],
  [3,    "pedro",    10],
  [4,    "henrique", 10]
]

como eu declaro essa variável (uma matrix) no campo propertie?

A: Porque não utiliza um Array de objetos?
Ex:
Polymer({

  is: 'hello',

  properties: {
    users: Array
  },

  ready: function() {

    this.users = [
       {id: 1, nome: 'Mateus', idade: 16},
       {id: 2, nome: 'Cristian', idade: 16},
       {id: 3, nome: 'Pedro', idade: 16}
    ];

  }

});

Para acessar cada um dos usuários você pode iterar o this.users.
Ex:
this.users.forEach(function(user){
  console.log(user.id, user.nome, user.idade);
});

Espero ter ajudado.


text:
Q: How to evaluate Area of $B:= \{(x,y,z) \in A | z \le 1 \}$ with $A:=\{(x,y,z) \in \mathbb{R}^3 | x^2 + y^2 = z\} = \frac{\pi}{6}(5 \sqrt{5}-1) $? I have following problem:
Let $$A:=\{(x,y,z) \in \mathbb{R}^3 | x^2 + y^2 = z\} \\
B:= \{(x,y,z) \in A | z \le 1 \}. $$
Compute the area $\mu_2(B) $.
First, I thought $\mu_2(B) $ would just be the area of the unit circle, $\pi$. However, that's not right. The solution says that $\mu_2(B) = \frac{\pi}{6}(5 \sqrt{5}-1)$.   I tried to use polar coordinates, but I still just get $\pi$ with $\int_C r d\theta dr $ and $C:=\{(x,y,z) \in \mathbb{R}^3 | x^2 + y^2 \le 1\}$.
Can anybody explain me how to get to $\frac{\pi}{6}(5 \sqrt{5}-1)$ and what must be defined differently so that $\mu_2(B) = \pi$?

A: Hint for the first question: You are looking at a "cap" (sliced off portion) of a paraboloid of revolution that is caused by rotating the graph of the curve $z=x^2$ for $0\le x\le 1$ around the $z$ axis. So use the method to find the area of a solid of revolution.
Hint for the second question: The "cap" is the unit circle in the $xy$ plane, curved up to make a paraboloid. The flat unit circle has the area $\pi$. Curving it up can only increase the area, so your desired area must be greater than $\pi$. Some ways to get an area of $\pi$ are to leave the circle flat (so it is no longer a paraboloid) and reducing the limit on $z$ to something less than one to reduce the area to what you want. I suppose you could also change the equation to $x^2+y^2=cz$ for some constant $c>1$ and leave $z\le 1$ to reduce the area to what you want. You would need to figure out the desired constants in the last two methods.


text:
Q: Using stack to store objects I'm doing a program where I need to store objects in stack. I define the stack as a template class like this:
template < class T >
class stackType
{
private:
    int maxStackSize;
    int stackTop;
    T *list;           // pointer to the array that holds the stack elements
public:
    stackType( int stackSize );  // constructor
    ~stackType();                // destructor
    void initializeStack();
    bool isEmptyStack();
    bool isFullStack();
    void push( T newItem );
    T top();
    void pop();
};

And this is my class:
class Matrix_AR
{
public:
    float **Matrix;        // Matrix as a pointer to pointer
    int rows, columns;     // number of rows and columns of the matrix

// class function
    Matrix_AR();
    Matrix_AR( int m, int n ); // initialize the matrix of size m x n
    void inputData( string fileName ); // read data from text file
    void display(); // print matrix
};

However, when I declare a function like this
void myfunction( stackType<Matrix_AR>& stack )
{
    Matrix_AR item1, item2, item3;

    stack.push( item1 );
    stack.push( item2 );
    stack.push( item3 );
}

I kept getting the error. I tried to fix it for five hours and still cannot figure it out. Could anyone help, please !!!
Undefined symbols for architecture x86_64:
      "Matrix_AR::Matrix_AR()", referenced from:
      myfunction(stackType<Matrix_AR>&, char&, bool&)in main.o
ld: symbol(s) not found for architecture x86_64

A: It seems like you are not defining your default constructor. If you want a quick solution just declare it like this:
// class function
Matrix_AR() {}
Matrix_AR( int m, int n ); // initialize the matrix of size m x n
void inputData( string fileName ); // read data from text file
void display(); //...

The error posted is for the default constructor, but if you are not defining the other functions, you are going to get similar errors for those too. You should have a separate .cpp file with the definitions of all your member functions.
Matrix_AR::Matrix_AR()
{
...
}

Matrix_AR::Matrix_AR( int m, int n )
{
...
}

void Matrix_AR::inputData( string fileName )
{
...
}

etc.......


text:
Q: How do I get HDFS bytes read and write for Spark applications? I want to collect different metrics for the spark application, if some one have any idea about how do i get HDFS bytes read and write please tell me?

A: I'm looking for the same information and I can't find the information anywhere: neither Spark documentation or the Spark users mailing list (even if some poeple are asking the question) is giving me the information.
But, I found some clues over the internet that suggest that it is provided by Spark in the metrics.
I'm working on some application logs (the ones that are provided by the history server) and it seems that the Input Metrics and Output Metrics that are presents in Task Metrics in each SparkListenerTaskEnd events is giving the amount of data that is read and written for each tasks.
{
  "Event": "SparkListenerTaskEnd",
  ...
  "Task Metrics": {
      ...
      "Input Metrics": {
        "Bytes Read": 268566528,
        "Records Read": 2796202
      },
      "Output Metrics": {
        "Bytes Written": 0,
        "Records Written": 0
      },
      ...
  },
  ...
}

Note that I'm not a 100% sure on that but the log I got seems to be consistent with this assumption :)
Also, If you are reading from local filesystem I think this will be mixed in the same metric.


text:
Q: Is there a problem with filtering questions after selecting them for the site homepage? I occasionally open an incognito window on my favourite Stack just to check if there are any interesting questions on tags I have ignored.
Today a large number of negatively-scored posts have been edited, and when I visited the homepage I saw only 3 posts, instead of the expected 15 (see image below).  Checking against the most recently active questions page, these 3 are the only non-negatively rated questions in the most recently active 15 questions.
Does it make sense to filter out the negative questions after picking the set of 15?  It seems counter-intuitive to me, and I would instead expect to see the most recently active 15 questions that are not negative.
(It also doesn't look great to show a potential new user just 3 questions; the site looks a bit abandoned.)


text:
Q: MySQL logic issue: Which is the best way to give permission to users to different rows from different tables? We have a few tables: users, units, classes, schedules and marks (can be more)

*

*users ( id_user, email, password )

*units ( id_unit, name )

*classes ( id_class, id_unit, name )

*schedule ( id_schedule, id_class, start_dt, end_dt )

*marks ( id_mark, id_user, id_schedule, value )

I want to give permission to one user or another to view / update / delete one row from one table.
I can't use roles, because I don't have a particular rule for this.
My solution for this is: create a table named: permissions ( id, table, id_table, id_user, view, update, delete ) and passing users with rows tables, but when this table will have 70k rows, the next statement will take a while ( I tested with a db seeder ):
SELECT *
FROM marks
WHERE id_mark IN (SELECT id_table FROM permissions WHERE table = 'marks' AND id_user = '1')

Which is the best way to give permission to users to different rows from different tables?

A: You could try to create updatable views that reference the permissions table with a join and use WITH CHECK OPTION to "to constrain inserts or updates to rows in tables referenced by the view." (source) The permissions will be granted to the views and not to the tables themselves.
You can check if a view is updatable:

MySQL sets a flag, called the view updatability flag, at CREATE VIEW
  time. The flag is set to YES (true) if UPDATE and DELETE (and similar
  operations) are legal for the view. Otherwise, the flag is set to NO
  (false). The IS_UPDATABLE column in the INFORMATION_SCHEMA.VIEWS table
  displays the status of this flag.


text:
Q: Should you use application services, domain services, or domain events for business processes? Let's say we have a business rule that states that once a product is purchased, you should update the inventory and generate an invoice. Which of the following should you use?
Should you use application services where you call something like UpdateInventory() followed by GenerateInvoice()? Should you call the same methods but put them in a domain service instead? Or should you just call UpdateInventory() which raises a domain event to generate the invoice?
What are the pros and cons of each?


text:
Q: Android Bottom Navigation bar 4 Items not showing properly on some devices I got a little problem, as I'm trying to add 4 Icons to a Bottom Navigation Bar in Android.
On some devices it looks like this
But I want it to be looking like this
How to achieve that ? Thanks in advance
Don't know which code you need. Just added everything used by the viewpager for the Bottom navigation Bar
    bottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_stdplan:
                            viewPager.setCurrentItem(0);
                            break;
                        case R.id.action_klausur:
                            viewPager.setCurrentItem(1);
                            break;
                        case R.id.action_hausaufgaben:
                            viewPager.setCurrentItem(2);
                            break;
                        case R.id.action_fehlzeiten:
                            viewPager.setCurrentItem(3);
                            break;
                    }
                    return false;
                }
            });

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (prevMenuItem != null) {
                prevMenuItem.setChecked(false);
            }
            else
            {
                bottomNavigationView.getMenu().getItem(0).setChecked(false);
            }
            Log.d("page", "onPageSelected: "+position);
            bottomNavigationView.getMenu().getItem(position).setChecked(true);
            prevMenuItem = bottomNavigationView.getMenu().getItem(position);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    stdplanFragment =new StdplanFragment();
    klausurenFragment =new KlausurenFragment();
    hausaufgabenFragment =new HausaufgabenFragment();
    fehlzeitenFragment =new FehlzeitenFragment();
    adapter.addFragment(stdplanFragment);
    adapter.addFragment(klausurenFragment);
    adapter.addFragment(hausaufgabenFragment);
    adapter.addFragment(fehlzeitenFragment);
    viewPager.setAdapter(adapter);
}

}
bottom_navigation.xml:
    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_stdplan"
        android:checked="true"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/tab1"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_klausur"
        android:checked="false"
        android:icon="@android:drawable/ic_menu_agenda"
        android:title="@string/tab2"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_hausaufgaben"
        android:checked="false"
        android:icon="@android:drawable/ic_menu_manage"
        android:title="Hausaufgaben"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_fehlzeiten"
        android:checked="false"
        android:icon="@android:drawable/ic_menu_recent_history"
        android:title="@string/tab3"
        app:showAsAction="never" />
</menu>

A: I fixed it myself by changing the font size of the titles
Everyone else struggling with this: Just add these two lines to your dimens.xml
  <dimen name="design_bottom_navigation_text_size" tools:override="true">10sp</dimen>
  <dimen name="design_bottom_navigation_active_text_size" tools:override="true">10sp</dimen>

A: It could be a problem from a smallest thing possible. Not sure if it has anything to do with the image icons you have used, but can you please see if the image icons happen to have any paddings i.e. in the image itself?
Also for debugging purposes please remove the titles or keep them empty and see if it aligns the image icons properly.
Can you please change the following,
app:showAsAction="never"

to
app:showAsAction="ifRoom"

I would try following this link just in case.


text:
Q: Proving a lemma related to composition of maps $A\xrightarrow{\phi} B\xrightarrow{\psi} C$ are linear maps, $\psi$ surjective, then prove $\psi \circ \phi$ is surjective $\iff$ $B = Im(\phi) + Ker(\psi)$.
I know $B/Ker(\psi)$ is isomorphic to $C$ since $\psi$ is surjective. Is $A$ isomorphic to $B/Ker(\psi)$ when $\psi \circ \phi$ is surjective? Also, how would that lead to $B = Im(\phi) + Ker(\psi)$? Thanks and appreciate a hint.

A: Just do it from definitions. Let $B=Im(\phi)+ker(\psi)$ and take any $c \in C$. We can write $c$ as $\psi (b)$ for some $b \in B$. We can write $b$ as $x+y$ with $ x \in Im(\phi), y \in ker(\psi)$. We can write $x=\phi(z)$ for some $z \in A$. We get $c=\psi (\phi(z)+y)=\psi (\phi(z))+\psi (x)=\psi (\phi(z))$ proving that $\psi \circ \phi $ is surjective.
Converse: suppose $\psi \circ \phi $ is surjective. Clearly $Im(\phi)+ker(\psi) \subset B$. Now take any $b \in B$. Then $\psi (b) \in C$, so we can write $\psi (b)=\psi (\phi (a))$ for some $a \in A$. Since $\psi (b-\phi (a))=0$ it follows that $b-\phi (a) \in ker (\psi)$. Since $b =(b-\phi (a))+ \phi (a)$ the proof is complete.


text:
Q: Difference between creating a class in javascript to create an object and creating an class and object in Java Statement:

Javascript can create an Object without creating a class.

Is that statement valid? Maybe I didn't get the concept here right...
For example if I create an object in Javascript:
var mercedes = new Object();
mercedes.speed = "260";
mercedes.model = "SLS";
mercedes.year = 1969;

Here I have no class but I already have an instance. Does that mean I don't need to define classes in Javascript?
Also one more question what is the difference in Javascript between creating a object as described above and creating an object in the following method:
myCar["speed"] = "260";
myCar["model"] = "SLS";
myCar["year"] = 1969;

A: In javascript there are no classes. That being said you can simulate classes using few different ways.
Using a function and defining methods to its prototype
var Person = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
};

// you can define Person.fullname = function() {} straight to the function
// drawback to this is fullname function will be created everytimg you create a new Person
// instead you can create fullname in the prototype of the Person so it only gets created once

Person.prototype.fullname = function() {
    return this.firstName + ' ' + this.lastName;
};

var person = new Person('John', 'Doe');
person.fullname(); // John Doe

Using object literals
var Person = {
    firstName: 'John',
  lastName: 'Doe',
  fullname: function() {
    return this.firstName + ' ' + this.lastName;
  }
};

Person.fullname(); // John Doe

Person.firstName = 'Jane';
Person.fullname(); // Jane Doe

Using Singleton
var person = new function() {
    this.firstName = 'John';
    this.lastName = 'Doe';
    this.fullname = function() {
      return this.firstName + ' ' + this.lastName;
    };
};

person.fullname(); // John Doe

person.firstName = 'Jane';
person.fullname(); // Jane Doe

If you are planning to get more closer to how java classes work, apply inheritance, etc then I suggest you to go with the first method. Below is example of a simple inheritance using prototype.
var Person = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
};

Person.prototype.fullname = function() {
  return this.firstName + ' ' + this.lastName;
};

Person.prototype.getFirstName = function() {
    return this.firstName;
};

Person.prototype.getLastName = function() {
    return this.lastName;
};

Person.prototype.setLastName = function(lastName) {
    return this.lastName = lastName;
};

Person.prototype.setFirstName = function(firstName) {
    return this.firstName = firstName;
};

var Student = function(firstName, lastName, grade) {
    this.grade = grade;
  Person.call(this, firstName, lastName);
};

Student.prototype = Object.create(Person.prototype);

Student.prototype.getGrade = function() {
    return this.grade;
};

var student = new Student('John', 'Doe', '5th');
student.fullname(); // John Doe
student.getFirstName(); // John
student.setFirstName('Jane');
student.getFirstName(); // Jane
student.getGrade(); // 5th

That should explain how you can use classes in javascript similar to you are used to in java.
What is difference between using dot notation and brackets to access object properties?
Long answer short, both behave exactly the same. But there would be instances where dot notation will not always work. For example:
var person = {
    "first name": "john",
    "last name": "doe",
    "fullname": "john doe"
};

person.fullname; // john doe

// to access first name property of person
person.first name; // will not work
person["first name"]; // john

A: There are classes in javascript. But you can also inherit an object properties using the .prototype property. This W3School's article can explain it better.
For your second question there's no real difference when you use brackets or dot properties. Accesing properties using brackets can be useful when you use a variable to access an object property. Example:
 var obj = {}:
 var val = 'value';
 obj[val] = 'new value';
 console.log(obj[val]); // Output: new value

The above can also work with:
var obj = { 'value' = 'new value'};
var val = 'value';
console.log(obj[val]); // Output: new value

A: This has been answered several times on SO already, so I'll just link a very good answer I often referred to when learning javascript:
https://stackoverflow.com/a/387733/3299157
A quick answer though, yes you can create an object in Javscript without creating a traditional Object-Oriented class.
And to your second question, there's no discernible difference when using the "brackets style".

A: JavaScript has no concept of class. Instead of defining classes from the beginning, with JavaScript you can just write code.
With bracket notation you can dynamically decide which property to access, and you can use special characters in property name.
var prop = "speed";
myCar = {};  // create a object
myCar[prop] = "260"; // using dynamically property
myCar["speed.a"] = "265"; // using special characters

reference: The Principles of Object-Oriented JavaScript, Nicholas C. Zakas


text:
Q: Cannot instantiate interface Lcobucci\\JWT\\Parser in laravel 9 {
"message": "Cannot instantiate interface Lcobucci\JWT\Parser",
"exception": "Error",
"file": "/var/www/app/Http/Middleware/Authenticate.php",
"line": 95,
"trace": [
{
"file": "/var/www/app/Http/Middleware/Authenticate.php",
"line": 54,
"function": "validateToken",
"class": "App\Http\Middleware\Authenticate",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "App\Http\Middleware\Authenticate",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 116,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 726,
"function": "then",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 703,
"function": "runRouteWithinStack",
"class": "Illuminate\Routing\Router",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 667,
"function": "runRoute",
"class": "Illuminate\Routing\Router",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"line": 656,
"function": "dispatchToRoute",
"class": "Illuminate\Routing\Router",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
"line": 167,
"function": "dispatch",
"class": "Illuminate\Routing\Router",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 141,
"function": "Illuminate\Foundation\Http\{closure}",
"class": "Illuminate\Foundation\Http\Kernel",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
"line": 21,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php",
"line": 31,
"function": "handle",
"class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php",
"line": 21,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php",
"line": 40,
"function": "handle",
"class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "Illuminate\Foundation\Http\Middleware\TrimStrings",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php",
"line": 27,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php",
"line": 86,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Http/Middleware/HandleCors.php",
"line": 62,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "Illuminate\Http\Middleware\HandleCors",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php",
"line": 39,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 180,
"function": "handle",
"class": "Illuminate\Http\Middleware\TrustProxies",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php",
"line": 116,
"function": "Illuminate\Pipeline\{closure}",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
"line": 142,
"function": "then",
"class": "Illuminate\Pipeline\Pipeline",
"type": "->"
},
{
"file": "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php",
"line": 111,
"function": "sendRequestThroughRouter",
"class": "Illuminate\Foundation\Http\Kernel",
"type": "->"
},
{
"file": "/var/www/public/index.php",
"line": 52,
"function": "handle",
"class": "Illuminate\Foundation\Http\Kernel",
"type": "->"
}
]
}

A: use Lcobucci\JWT\Parser as JwtParser;
$token = app(Parser::class)->parse($token)->claims()->get('jti');


text:
Q: VBA Automation - How To Access Date Picker Elements I am working on some VBA Automation where it is taking data from an Excel Spreadsheet, and inputting that data into an Intranet Site.
On the Intranet Site there is a little datepicker tool (with a start date and end date) that allows you to pick the date (please see html excerpt of the datepicker html code):
<input type="text" id="startdate" name="startdate" value="" class="form-control" size="30">
<button class="pika-button pika-day" type="button" data-pika-year="2019" data-pika-month="8" data-pika-day="2">2</button>
<button class="pika-prev" type="button">Previous Month</button>

<input type="text" id="enddate" name="enddate" value="" class="form-control" size="30">
<button class="pika-button pika-day" type="button" data-pika-year="2019" data-pika-month="8" data-pika-day="2">2</button>
<button class="pika-prev" type="button">Previous Month</button>

Please also see the JavaScript code below for the datepicker function:
<script>
    var startDate,
    endDate,
    updateStartDate = function() {
        startPicker.setStartRange(startDate);
        endPicker.setStartRange(startDate);
        endPicker.setMinDate(startDate);
    },
    updateEndDate = function() {
        startPicker.setEndRange(endDate);
        startPicker.setMaxDate(endDate);
        endPicker.setEndRange(endDate);
    },
    startPicker = new Pikaday({
        field: document.getElementById('startdate'),
        minDate: new Date(2016, 1, 1),
        maxDate: new Date(2050, 12, 31),
        onSelect: function() {
            startDate = this.getDate();
            updateStartDate();
        }
    }),
    endPicker = new Pikaday({
        field: document.getElementById('enddate'),
        minDate: new Date(2016, 1, 1),
        maxDate: new Date(2050, 12, 31),
        onSelect: function() {
            endDate = this.getDate();
            updateEndDate();
        }
    });
    _startDate = startPicker.getDate();
    _endDate = endPicker.getDate();
    if (_startDate) {
        startDate = _startDate;
        updateStartDate();
    };
    if (_endDate) {
        endDate = _endDate;
        updateEndDate();
    };
</script>

I originally had this code which pushes the correct date string to the form, but the datepicker elements inside the datepicker don't get selected (they default to today's date) after running the automation (see code below:).
IE.document.all("startdate").Value = Format$(ThisWorkbook.Sheets("Legends").Range("b7").Value, "yyyy-mm-dd")
IE.document.all("enddate").Value = Format$(ThisWorkbook.Sheets("Legends").Range("b8").Value, "yyyy-mm-dd")

This is what happens after I run the automation, please see image with the date pushed: Intranet site with date
This is how it looks when I click on the datepicker element: Datepicker defaulting to today's date
After reading some some stuff online, it seems like you have to click on the "startdate" element, and then click on the other elements inside the datepicker (which I have successfully done below:).
IE.document.querySelector("startdate").Click

However I am unable to figure out how to click on the other elements (previous month, and the day) to complete this part of the automation.
Any help would be much appreciated!

A: You could try to use the SendKeys method to enter the date, please refer to the following code:
Sub Test()
    Dim IE As Object

    Dim startDateText As Object, endDateText As Object

    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Visible = True
        .Navigate "<the website url>"

        While IE.ReadyState <> 4
            DoEvents
        Wend

        'find the startdate textbox and focus
        Set startDateText = IE.document.all("startdate")
        startDateText.Focus
        'using sendkeys method to enter the date.
        SendKeys Format$(ThisWorkbook.Sheets("Legends").Range("b7").Value, "yyyy-mm-dd")
        'Waiting the date value enters (1 second)
        Application.Wait (Now + TimeValue("0:00:1"))

        Set endDateText = IE.document.all("enddate")
        endDateText.Focus
        SendKeys Format$(ThisWorkbook.Sheets("Legends").Range("b8").Value, "yyyy-mm-dd")

        Application.Wait (Now + TimeValue("0:00:1"))
        IE.document.all("startdate").Click

    End With
    Set IE = Nothing
End Sub


text:
Q: Problems installing Ubuntu 18.04, NVidia card, Windows 10 Pro I have been struggling to install Ubuntu 18.04 alongside my Windows 10, for a really long time. I recently bought Dell Vostro 3500, which comes with Windows 10 Pro. It has an Nvidia MX330 graphics card. I have been facing multiple issues trying to install Ubuntu 18.04 on the system.
I have installed Ubuntu 16-20 multiple times on my old systems and do know my way around the installation quite well, as I primarily use Ubuntu as my main OS. I installed Ubuntu 20.04 on this machine and that works fine, I had no trouble. However it just refuses to install 18.04, and I need to install Ubuntu 18.04 for my needs. I suspect it has got something to do with installing Nvidia graphics drivers, however, once I am done with my installation, it stops at the blank screen saying 'clean ..., files ... blocks'. I have tried multiple solutions such as purging and reinstalling nvidia-drivers, setting nomodeset, and reinstalling xserver, disabling Wayland, and multiple other solutions. solution, another solutoin etc.
I am able to somehow install remove nvidia, install the default graphics xservers, and I can get it to work, however once I install my Nvidia drivers and restart my system, I'm back to square one. I do need NVidia graphics card support for my applications. I've tried multiple drivers from 350 to 470 and that does not help as well.
I'd like to reiterate that I was able to get Ubuntu 20.04 working with NVidia support without any issues. However, Ubuntu 18.04 (I tried 18.04.1 to 18.04.6), and none of them seem to work.
I'm not sure what the error is and would need some help.
More details about my machine (that I think may be relevant):
Model : Dell Vostro 3500
Graphics card : Nvidia MX330 2GB
TPM 2.0
The machine is no longer available in the US, so here is the model from another country, but same specs : enter link description here


text:
Q: I am having issues while decryption using RNCryptor Library While decrypting I get the error : The operation couldnot be performed RNCryptorError 1
I dont understand what I am doing wrong. Here is my block of code

A: For anyone who might search here: this is a duplicate of RNCryptor#174, and you may want to read there as well.
Please just post code into the question rather than a screenshot. I can't compile a screenshot, and they're very hard to read.
Error 1 is an HMAC error. Either your data is corrupted or your password is incorrect.
Note that NSException never makes sense in Swift. Switch can't catch them. They only make sense in ObjC if you're going to crash the program shortly after. They're not memory-safe in ObjC. You meant to use Swift's throw and ErrorType, which are unrelated to raise or NSException.


text:
Q: 8051 I/O programming logic/ how it works I'm new to microprocessors and trying to figure out how they work. I am quite confused about using the ports as inputs and outputs. It says that we should send '1' to the pin if we want to use it as input and '0' for output. What happens when a '0' comes to an input port as data? Will that port still remain as an input port? Will the output pin remain an output when '1' comes in?
I know that I'm missing something quite obvious but I couldn't figure it out, even though I have checked many different sources. I wonder how the pin circuit works and how it is affected by commands.

A: The 8051 I/O port is different from most other microcontrollers.
The I/O ports (except P0) effectively have open collector outputs with internal pull-up resistors (P0 doesn't have pull-ups).
If you write a Zero to a port pin, the pin will be pulled to ground, and is definitely an output.
If you write a One to a port pin, the transistor driving the port will be turned off, so the pull-up resistor will pull the pin High.  In this state, the pin can be considered as a High output, or it can be used as an input, as an external device can pull the pin Low, when it will be read as a Zero.  If the external device does not pull the pin Low, it will be read as a High input.
Many other microcontrollers have Data Direction Registers that determine whether the pins can be used as inputs or outputs, and may have other registers to determine whether outputs are open collector or not, and whether pull-up or pull-down resistors are active when the pin is set as an input.


text:
Q: Structuring a Database That Counts Similar Entries I'm new to databases. I'm organizing music using mysqlite3. I have ArtistName, SongTitle, and AlbumTitle fields in the Music table. The primary purpose of the database is to query it and return all of the artists who have less than 3 songs.
To achieve this, I think I will need some kind of "song count" entry that increments every time I add a song from the same artist. However, I'm not sure how to create a dynamic entry. I know of the AUTO_INCREMENT keyword, which has the dynamic properties I'm looking for, but not the conditional incrementing.
Thoughts?

A: Unless I am missing something in your request you do not need a songCount column, you can easily get the artists that have less than 3 songs but using the following query:
select artistname
from music
group by artistname
having count(SongTitle) <3

This will return the artistname for every artist that has count of songs less than three total songs.
Then if you want to expand on this, you can use the following which will return all of the columns from the music table where the artist has less than 3 songs:
select m1.*
from music m1
where exists (select artistname
              from music m2
              where m1.artistname = m2.artistname
              group by artistname
              having count(SongTitle) <3)

A: You don't need a "count" field. Try this...
SELECT ArtistName
FROM Music
GROUP BY ArtistName
HAVING Count(ArtistName) < 3

This is assuming there is only one entry for each song.


text:
Q: How is it possible to write event based single threaded programs? My knowledge of threads is very limited. I happen to be the guy who can write multi-threaded programs but just by copy-pasting and finding answers to my questions on the internet. But I've finally decided to learn a bit about concurrency and bought the book "Java Concurrency in Practice". After reading a couple of pages, I'm confident that I'll learn a great deal from this book.
Maybe I'm being a little impatient but I cannot resist the temptation of asking this question. It made me create an account on Stack Overflow. I'm not sure I'll be able to correctly phrase the question so I'll try to explain my question using an example.
If I had to write a (extremely unprofessionally coded) peer-to-peer chat client in, say, Java, I'll initiate a socket connection between the clients and keep it alive because messages can arrive at any time. The solution I can imagine would open a socket connection in a new thread and run a while loop continuously to keep the thread alive, as the thread dies as soon as run returns. For some reason, I cannot imagine a similar chat client in a single threaded program. How can you keep "waiting" until a message arrives if all you have is a single thread. Won't that block the execution of entire program?
To solve such a problem, what's the alternative to a continuous while loop?

A:
How can you keep "waiting" until a message arrives if all you have is a single thread.

One possibility is to have the "parallelism" to happen "outside" of your application. Imagine a waiter in a restaurant. Just one guy. He walks from one customer to the next, and writes up the orders. From time to time, he walks over to the counter, puts in the orders, and picks up whatever stuff the chef left for him. Just one guy, walking around, doing "single task" work. But in the end, the overall system still has multiple actors (the guests, the waiter, the chef, the guy beyond the bar preparing the beverages). So, the waiter could be seen as "single threaded", but in the end, the overall system "restaurant" isn't.
Some IT architectures "mimic" that, for example around the idea of "non blocking" IO. That is how node.js works. It is single threaded by nature, but does async IO (see here for details). And you can do similar things with Java, too.
On the other hand, when you learn about concurrency, you still want to learn about the "real" multi threading, what it means, and how you would write code to "use" that concept.


text:
Q: Property doesn't exist on type "object" error after checking if the property exists on the object Issue:
I am trying to create a type guard, which should check if some values exist on a property of type unknown.
interface TestProps {
    count: number;
}

const getIsTestShown = (test: unknown): test is TestProps => {
    if (test && typeof test === "object") {
        if ("count" in test) {
            if (typeof test.count === "number") {  // ERROR: Property 'count' does not exist on type 'object'.ts(2339)

                return true;
            }
        }
    }

    return false;
};

The above example is simplified, but represents exactly my problem. Typescript doesn't seem to understand that if  "count" in test is true, count should be accessible on test.
What am I missing?

A: You could try this:
interface TestProps {
    count: number;
}

const getIsTestShown = (test: any): test is TestProps => {
    return typeof test?.count === "number" ?? false;
};

console.log(getIsTestShown({})) // false
console.log(getIsTestShown({ count: 1 })) // true
console.log(getIsTestShown({ count: "1" })); // false
console.log(getIsTestShown({ someOtherProp: "1" })); // false

If linters tell you not to use any, I would suggest to disable them for this particular function, since you're already checking the existence of the property and the type.
Edit: Here is a more detailed example of how you could use unknown and why it doesn't work just like any.


text:
Q: How to use data.table to efficiently calculate allele frequencies (proportions) by group across multiple columns (loci) I have a data.table of allele identities (rows are individuals, columns are loci), grouped by a separate column. I want to calculate allele frequencies (proportions) for each locus efficiently, by group. An example data table:
    DT = data.table(Loc1=rep(c("G","T"),each=5),
      Loc2=c("C","A"), Loc3=c("C","G","G","G",
      "C","G","G","G","G","G"),
    Group=c(rep("G1",3),rep("G2",4),rep("G3",3)))
    for(i in 1:3)
        set(DT, sample(10,2), i, NA)
    > DT
        Loc1 Loc2 Loc3 Group
     1:    G   NA    C    G1
     2:    G    A    G    G1
     3:    G    C    G    G1
     4:   NA   NA   NA    G2
     5:    G    C   NA    G2
     6:    T    A    G    G2
     7:    T    C    G    G2
     8:    T    A    G    G3
     9:    T    C    G    G3
    10:   NA    A    G    G3

The problem I have is that when I try to do calculations by group, only the allele i.d.s present in the group are recognized, so I'm struggling to find code that can tell me e.g. the proportion of G's for locus 1 in all 3 groups. Simple example, calculating a sum (not proportion) for the first allele at each locus:
    > fun1<- function(x){sum(na.omit(x==unique(na.omit(x))[1]))}
    > DT[,lapply(.SD,fun1),by=Group,.SDcols=1:3]
       Group Loc1 Loc2 Loc3
    1:    G1    3    1    1
    2:    G2    1    2    2
    3:    G3    2    2    3

For G1 the result is that Loc1 has 3 G's, but for G3 it shows Loc1 has 2 T's, not the number of G's. I want the number of G's for both in this case. So the key problem is that the allele identities are determined by group, not over the whole column. I tried making a separate table with the allele identities I want to use in calculations, but can't figure out how to include it in fun1 so that the correct cells are referenced in lapply above. Allele identities table:
    > fun2<- function(x){sort(na.omit(unique(x)))}
    > allele.id<-data.table(DT[,lapply(.SD,fun2),.SDcols=1:3])
    > allele.id
       Loc1 Loc2 Loc3
    1:    G    A    C
    2:    T    C    G

A: It's probably wise to transform your data.table into long format first. This will make it easier to use for further calculations (or making visualisations with ggplot2 for example). With the melt function of data.table (which works the same as the melt function of the reshape2 package) you can transform from wide to long format:
DT2 <- melt(DT, id = "Group", variable.name = "loci")

When you want to remove the NA-values during the melt-operation, you can add na.rm = TRUE in the above call (na.rm = FALSE is the default behaviour).
Then you can make count and proportion variables as follows:
DT2 <- DT2[, .N, by = .(Group, loci, value)][, prop := N/sum(N), by = .(Group, loci)]

which gives the following result:
> DT2
    Group loci value N      prop
 1:    G1 Loc1     G 3 1.0000000
 2:    G2 Loc1    NA 1 0.2500000
 3:    G2 Loc1     G 1 0.2500000
 4:    G2 Loc1     T 2 0.5000000
 5:    G3 Loc1     T 2 0.6666667
 6:    G3 Loc1    NA 1 0.3333333
 7:    G1 Loc2    NA 1 0.3333333
 8:    G1 Loc2     A 1 0.3333333
 9:    G1 Loc2     C 1 0.3333333
10:    G2 Loc2    NA 1 0.2500000
11:    G2 Loc2     C 2 0.5000000
12:    G2 Loc2     A 1 0.2500000
13:    G3 Loc2     A 2 0.6666667
14:    G3 Loc2     C 1 0.3333333
15:    G1 Loc3     C 1 0.3333333
16:    G1 Loc3     G 2 0.6666667
17:    G2 Loc3    NA 2 0.5000000
18:    G2 Loc3     G 2 0.5000000
19:    G3 Loc3     G 3 1.0000000

I you want it back in wide format, you can use dcast on multiple variables:
DT3 <- dcast(DT2, Group + loci ~ value, value.var = c("N", "prop"), fill = 0)

which results in:
> DT3
   Group loci N_A N_C N_G N_T N_NA    prop_A    prop_C    prop_G    prop_T   prop_NA
1:    G1 Loc1   0   0   3   0    0 0.0000000 0.0000000 1.0000000 0.0000000 0.0000000
2:    G1 Loc2   1   1   0   0    1 0.3333333 0.3333333 0.0000000 0.0000000 0.3333333
3:    G1 Loc3   0   1   2   0    0 0.0000000 0.3333333 0.6666667 0.0000000 0.0000000
4:    G2 Loc1   0   0   1   2    1 0.0000000 0.0000000 0.2500000 0.5000000 0.2500000
5:    G2 Loc2   1   2   0   0    1 0.2500000 0.5000000 0.0000000 0.0000000 0.2500000
6:    G2 Loc3   0   0   2   0    2 0.0000000 0.0000000 0.5000000 0.0000000 0.5000000
7:    G3 Loc1   0   0   0   2    1 0.0000000 0.0000000 0.0000000 0.6666667 0.3333333
8:    G3 Loc2   2   1   0   0    0 0.6666667 0.3333333 0.0000000 0.0000000 0.0000000
9:    G3 Loc3   0   0   3   0    0 0.0000000 0.0000000 1.0000000 0.0000000 0.0000000

Another and straightforward approach is using melt and dcast in one call (which is a simplified version of the first part of @Frank's answer):
DT2 <- dcast(melt(DT, id="Group"), Group + variable ~ value)

which gives:
> DT2
   Group variable A C G T NA
1:    G1     Loc1 0 0 3 0  0
2:    G1     Loc2 1 1 0 0  1
3:    G1     Loc3 0 1 2 0  0
4:    G2     Loc1 0 0 1 2  1
5:    G2     Loc2 1 2 0 0  1
6:    G2     Loc3 0 0 2 0  2
7:    G3     Loc1 0 0 0 2  1
8:    G3     Loc2 2 1 0 0  0
9:    G3     Loc3 0 0 3 0  0

Because the default aggregation function in dcast is length, you will automatically get the counts for each of the values.

Used data:
DT <- structure(list(Loc1 = c("G", "G", "G", NA, "G", "T", "T", "T", "T", NA),
                     Loc2 = c(NA, "A", "C", NA, "C", "A", "C", "A", "C", "A"),
                     Loc3 = c("C", "G", "G", NA, NA, "G", "G", "G", "G", "G"),
                     Group = c("G1", "G1", "G1", "G2", "G2", "G2", "G2", "G3", "G3", "G3")),
                .Names = c("Loc1", "Loc2", "Loc3", "Group"), row.names = c(NA, -10L), class = c("data.table", "data.frame"))

A: Here is another option using table. (I am not sure about the format of the expected output.  Also, it is not clear whether we need to include the NA elements in calculation of proportion.  If we don't need it, we can remove the useNA=....)
We loop through the 'Loc' columns, create a table of that column with the 'Group', get the proportion using prop.table (specifying the margin) and store the results in a list ('lst').
nm1 <- paste0('Loc', 1:3)
lst <- vector('list' , length(nm1))

 for(i in seq_along(nm1)){
   temp <- table(DT$Group, DT[[i]], useNA= 'ifany')
   lst[[i]] <- list(temp, prop.table(temp, 1))
}

lst[[1]]
#[[1]]
#
#     G T <NA>
#  G1 3 0    0
#  G2 1 2    1
#  G3 0 2    1

#[[2]]
#
#             G         T      <NA>
#  G1 1.0000000 0.0000000 0.0000000
#  G2 0.2500000 0.5000000 0.2500000
#  G3 0.0000000 0.6666667 0.3333333


text:
Q: Computation of the marginal likelihood from MCMC samples This is a recurring question (see this post, this post and this post), but I have a different spin.
Suppose I have a bunch of samples from a generic MCMC sampler. For each sample $\theta$, I know the value of the log likelihood $\log f(\textbf{x} | \theta)$ and of the log prior $\log f(\theta)$. If it helps, I also know the value of the log likelihood per data point, $\log f(x_i | \theta)$ (this information helps with certain methods, such as WAIC and PSIS-LOO).
I want to obtain a (crude) estimate of the marginal likelihood, just with the samples that I have, and possibly a few other function evaluations (but without rerunning an ad hoc MCMC).
First of all, let's clear the table. We all know that the harmonic estimator is the worst estimator ever. Let's move on.
If you are doing Gibbs sampling with priors and posteriors in closed form, you can use Chib's method; but I am not sure how to generalize outside of those cases. There are also methods that require you to modify the sampling procedure (such as via tempered posteriors), but I am not interested in that here.
The approach I am thinking of consists of approximating the underlying distribution with a parametric (or nonparametric) shape $g(\theta)$, and then figuring out the normalization constant $Z$ as a 1-D optimization problem (i.e., the $Z$ that minimizes some error between $Z g(\theta)$ and $f(\textbf{x}|\theta) f(\theta)$, evaluated on the samples). In the simplest case, suppose that the posterior is roughly multivariate normal, I can fit $g(\theta)$ as a multivariate normal and get something similar to a Laplace approximation (I might want to use a few additional function evaluations to refine the position of the mode). However, I could use as $g(\theta)$ a more flexible family such as a variational mixture of multivariate $t$ distributions.
I appreciate that this method works only if $Z g(\theta)$ is a reasonable approximation to $f(\textbf{x}|\theta) f(\theta)$, but any reason or cautionary tale of why it would be very unwise to do it? Any reading that you would recommend?
The fully nonparametric approach uses some nonparametric family, such as a Gaussian process (GP), to approximate $\log f(\textbf{x}|\theta) + \log f(\theta)$ (or some other nonlinear transformation thereof, such as the square root), and Bayesian quadrature to implicitly integrate over the underlying target (see here and here). This seems to be an interesting alternative approach, but analogous in spirit (also, note that GPs would be unwieldy in my case).

A: The extension by Chib and Jeliazkov (2001) unfortunately gets quickly costly or highly variable, which is a reason why it is not much used outside Gibbs sampling cases.
While there are many ways and approaches to the normalisation constant $\mathfrak{Z}$ estimation problem (as illustrated by the quite diverse talks in the Estimating Constant workshop we ran last week at the University of Warwick, slides available there), some solutions do exploit directly the MCMC output.

*

*As you mentioned, the harmonic mean estimator of Newton and Raftery (1994) is almost invariably poor for having an infinite variance. However, there are ways to avoid the infinite variance curse by using instead a finite support target in the harmonic mean identity
$$\int \dfrac{\alpha(\theta)}{\pi(\theta)f(x|\theta)}\text{d}\pi(\theta|x)=\frac{1}{\mathfrak{Z}}$$
by picking $\alpha$ as the indicator of an HPD region for the posterior. This ensures finite variance by removing the tails in the harmonic mean. (Details are to be found in a paper I wrote with Darren Wraith and in a chapter about normalising constants written with Jean-Michel Marin.) In short, the method recycles the MCMC output $\theta_1,\ldots,\theta_M$ by identifying the $\beta$ (20% say) largest values of the target $\pi(\theta)f(x|\theta)$ and creating $\alpha$ as a uniform over the union of the balls centred at those largest density (HPD) simulations $\theta^0_i$ and with radius $\rho$, meaning the estimate of the normalising constant $\mathfrak{Z}$ is given by
$$\hat{\mathfrak{Z}}^{-1}=\underbrace{\frac{1}{\beta M^2}\sum_{m=1}^M}_{\text{double sum over}\\\beta M\text{ ball centres }\theta_i^0\\\text{and $M$ simulations } \theta_m}
\underbrace{\mathbb{I}_{(0,\rho)}(\min_i||\theta_m-\theta^0_i||)\{\pi(\theta_m)f(x|\theta_m)\}^{-1}\big/\overbrace{\pi^{d/2}\rho^d\Gamma(d/2+1)^{-1}}^{\text{volume of ball with radius $\rho$}}}_{\dfrac{\beta M\alpha(\theta_m)}{\pi(\theta_m)f(x|\theta_m)}}$$
if $d$ is the dimension of $\theta$ (corrections apply for intersecting balls) and if $\rho$ is small enough for the balls to never intersect (meaning that at best only one indicator on the balls is different from zero). The explanation for the $\alpha M^2$ denominator is that this is a double sum of $\beta M^2$ terms:
$$
\frac{1}{\beta M}\sum_{i=1}^{\beta M} \underbrace{\frac{1}{M}\sum_{m=1}^M {\cal U}(\theta_i^0,\rho)(\theta_m)}_{\text{same as with $\min$}} \times \frac{1}{\pi(\theta_m)f(x|\theta_m)}
$$
with each term in $\theta_m$ integrating to ${\mathfrak{Z}}^{-1}$.

*Another approach is to turn the normalising constant $\mathfrak{Z}$ into a parameter. This sounds like a statistical heresy but the paper by Guttmann and Hyvärinen (2012) convinced me of the opposite.
Without getting too much into details, the neat idea therein is to turn the observed log-likelihood
$$
\sum_{i=1}^n f(x_i|\theta) - n \log \int \exp f(x|\theta) \text{d}x
$$
into a joint log-likelihood
$$
\sum_{i=1}^n[f(x_i|\theta)+\nu]-n\int\exp[f(x|\theta)+\nu]\text{d}x
$$
which is the log-likelihood of a Poisson point process with intensity function
$$
\exp\{ f(x|\theta) + \nu +\log n\}
$$
This is an alternative model in that the original likelihood does not appear as a marginal of the above. Only the modes coincide, with the conditional mode in ν providing the normalising constant. In practice, the above Poisson process likelihood is unavailable and Guttmann and Hyvärinen (2012) offer an approximation by means of a logistic regression. To connect even better with your question, Geyer's estimate is a MLE, hence solution to a maximisation problem.

*A connected approach is Charlie Geyer's logistic regression approach. The fundamental notion is to add to the MCMC sample from $\pi(\theta|x)$ another sample from a known target, e.g., your best guess at $\pi(\theta|x)$, $g(\theta)$, and to run logistic regression on the index of the distribution behind the data (1 for $\pi(\theta|x)$ and 0 for $g(\theta)$). With the regressors being the values of both densities, normalised or not. This happens to be directly linked with Gelman and Meng (1997) bridge sampling, which also recycles samples from different targets. And later versions, like Meng's MLE.

*A different approach that forces one to run a specific MCMC sampler is Skilling's nested sampling. While I [and others] have some reservations on the efficiency of the method, it is quite popular in astrostatistics and cosmology, with software available like MultiNest, PolyChord and UltraNest.

*A last [potential if not always possible] solution is to exploit the Savage-Dickey representation of the Bayes factor in the case of an embedded null hypothesis. If the null writes as $H_0: \theta=\theta_0$ about a parameter of interest and if $\xi$ is the remaining [nuisance] part of the parameter of the model, assuming a prior of the form $\pi_1(\theta)\pi_2(\xi)$, the Bayes factor of $H_0$ against the alternative writes as
$$\mathfrak{B}_{01}(x)=\dfrac{\pi^\theta(\theta_0|x)}{\pi_1(\theta_0)}$$
where $\pi^\theta(\theta_0|x)$ denotes the marginal posterior density of $\theta$ at the specific value $\theta_0$. In case the marginal density under the null $H_0: \theta=\theta_0$
$$m_0(x)=\int_\Xi f(x|\theta_0,\xi)\pi_2(\xi)\text{d}\xi$$
is available in closed form, one can derive the marginal density for the unconstrained model
$$m_a(x)=\int_{\Theta\times\Xi} f(x|\theta,\xi)\pi_1(\theta)\pi_2(\xi)\text{d}\theta\text{d}\xi$$
from the Bayes factor. (This Savage-Dickey representation relies on specific versions of three different densities and so is fraught with danger, not even mentioning the computational challenge of producing the marginal posterior.)

[Here is a set of slides I wrote about estimating normalising
constants for a NIPS workshop last December.]


text:
Q: FAILED: tests/plugin/libinsn.so when building QEMU on Ubuntu 16.04.3 I'm trying to build QEMU on a Ubuntu 16.04.3 VirtualMachine following these instructions.
The problematic part is executing command make -j4, after some trials I found the correct configuration command to be ran before make -j4 is:
./configure --python=/usr/bin/python3.7 --cc="gcc-7" --extra-ldflags="-pie -fPIC" --extra-cflags="-fPIC" --extra-cxxflags="-fPIC" --target-list="arm-softmmu" --enable-fdt --disable-kvm --disable-xen

With this configuration make -j4 runs and builds [2290/2594] elements, but it fails when Linking target tests/plugin/libinsn.so with the following error:
FAILED: tests/plugin/libinsn.so
gcc-7 -m64 -mcx16  -o tests/plugin/libinsn.so tests/plugin/libinsn.so.p/insn.c.o -Wl,--as-needed -Wl,--allow-shlib-undefined -shared -fPIC -Wl,--start-group -Wl,-soname,libinsn.so -Wl,--warn-common -Wl,-z,relro -Wl,-z,now -fstack-protector-strong -Wl,--copy-dt-needed-entries -fPIC -pie -fPIC -pthread -lgmodule-2.0 -lglib-2.0 -Wl,--end-group
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
tests/plugin/libinsn.so.p/insn.c.o: In function `plugin_exit':
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:82: undefined reference to `qemu_plugin_outs'
tests/plugin/libinsn.so.p/insn.c.o: In function `vcpu_tb_trans':
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:39: undefined reference to `qemu_plugin_tb_n_insns'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:46: undefined reference to `qemu_plugin_register_vcpu_insn_exec_inline'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:43: undefined reference to `qemu_plugin_tb_get_insn'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:49: undefined reference to `qemu_plugin_insn_vaddr'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:50: undefined reference to `qemu_plugin_register_vcpu_insn_exec_cb'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:56: undefined reference to `qemu_plugin_insn_size'
tests/plugin/libinsn.so.p/insn.c.o: In function `vcpu_insn_exec_before':
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:31: undefined reference to `qemu_plugin_outs'
tests/plugin/libinsn.so.p/insn.c.o: In function `qemu_plugin_install':
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:93: undefined reference to `qemu_plugin_bool_parse'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:98: undefined reference to `qemu_plugin_bool_parse'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:112: undefined reference to `qemu_plugin_register_vcpu_tb_trans_cb'
/home/MY_PATH/qemu/build/../tests/plugin/insn.c:113: undefined reference to `qemu_plugin_register_atexit_cb'
collect2: error: ld returned 1 exit status

How to fix it?
If more info is needed ask and I'll provide it.
Thanks!


text:
Q: Rust lifetimes with async/await The following code works without an async keyword on the function. After changing it to async what should I do to make it work.
use cgmath::Vector2;
use winit::window::Window;

struct A<'a> {
    a: Option<&'a Vector2<f32>>,
}

impl A<'_> {
    async fn new(b: &Window) -> A<'_> {
        Self {
            a: None
        }
    }
}

Compile errors
error: lifetime may not live long enough
 --> src/lib.rs:7:9
9  |       async fn new(b: &Window) -> A<'_> {
   |                       -           ----- return type `impl std::future::Future<Output = lang::A<'_>>` contains a lifetime `'1`
   |                       |
   |                       let's call the lifetime of this reference `'2`
10 | /         Self {
11 | |             a: None
12 | |         }
   | |_________^ associated function was supposed to return data with lifetime `'2` but it is returning data with lifetime `'1`

I tried to change it to
struct A<'a> {
    a: Option<&'a Vector2<f32>>,
}

impl<'a> A<'a> {
    async fn new(b: &'a Window) -> A<'a> {
        Self {
            a: None
        }
    }
}

But it borrows the window for too long, and can not move the window after the call. Before I added a lifetime parameter 'a to struct A, it worked.
46 |       let mut a = A::new(&window).await;
   |                          ------- borrow of `window` occurs here
47 |       //player.init();
48 |       event_loop.run(move |event, _, control_flow| {
   |       -              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move out of `window` occurs here
   |  _____|
   | |
49 | |         match event {
50 | |             Event::WindowEvent {
51 | |                 ref event,
52 | |                 window_id,
53 | |             } if window_id == window.id() => if !player.input(event) { // UPDATED!
   | |                               ------ move occurs due to use in closure
...  |
92 | |         }
93 | |     });
   | |______- argument requires that `window` is borrowed for `'static`

A: When you say Self, you say "A in the impl header". It contains a lifetime. Let's call it 'b:
impl<'b> A<'b> {
    async fn new<'a>(b: &'a Window) -> A<'a> {
        A::<'b> {
            a: None
        }
    }
}

See the mismatch? You were supposed to return A<'a>, but you return A<'b>!
The fix is simple: either use Self for the return type too, or just use A for the return expression:
impl A<'_> {
    async fn new(b: &Window) -> A<'_> {
        A {
            a: None
        }
    }
}

A: This is the way to go, b: &Window doesn't need the same lifetime as A.a.
struct A<'a> {
    a: Option<&'a Vector2<f32>>,
}

impl<'a> A<'a> {
    async fn new(b: &Window) -> A<'a> {
        Self {
            a: None
        }
    }
}


text:
Q: How do I bind a key to a command on the lock screen? I want to bind a key when the lock screen is up (or the screensaver is on). My machine is often locked and I want to be able to hit a shortcut to run a script in my home directory.
I've used System Settings -> Keyboard -> Shortcuts to bind keys to trigger the lock screen, but when the screensaver is on or the lock screen is up, my custom shortcut is disabled. Is there a way to flag my custom shortcut so that it is available from the lock screen, or to set it in gnome-screensaver?

A: The scope of lock screen is to lock any user to do something. This mean that you can't run a script in lock screen only if you schedule it to run from before.
Consequently, your shortcut key or any other shortcut will never work when your computer is in lock screen.