text:
Q: Sacar datos de un observable (subscriber) en angular 6 primero lo que deseo hacer o intento hacer es utilizar una barra de menu con opciones y usar los valores para filtrar dependiendo de dicho valor, entonces como lo hago..
componente 1 aca esta la barra de menu, componente 2 listado que deseo filtrar, utilizo un service para la comunicacion entre los componentes y funciona bien, el problema radica en que el dato que intento obtener del componente 1 me sale undefine fuera de la funcion de subscribe y no la puedo usar para filtrar el listado.
    this.communicationService.communication$.subscribe( (data) => {
data === this.x;
console.log(data) // arroja los datos esperados.
});

asi es como obtengo los datos del componente 1, ahora bien cuando doy console log a los datos perfecto ahi comunicacion entre los componente y todo pero cuando quiero utilizar this.x para filtrar los datos this.x sale undefined.
cuando intento hacer esto no me tira ningun dato.
this.resultado = this.listadoAFiltrar.filter( (f) => {
  return f.opcion === this.x
});

e incluso he intentado hacer esto pero sin resultado
this.communicationService.communication$.subcribe( data => {
   this.resultado = this.listadoAFiltrar.filter( f => {
     return f.opcion === data;
   })
})

alguna ayuda con esto por favor, gracias por la ayuda que puedan darme para poder resolver este problema. bien, ahora el da

A: en el subscribe estas haciendo data === this.x;, debes escribir this.x = data;  this.x te da undefined porque nunca le asignas el valor de data.

A:  this.communicationService.communication$.subcribe( data => {
   this.resultado = this.listadoAFiltrar.filter( f => {
     return f.opcion === data;
   });
// Aquí debes trabajar con lo que se guarde en this.resultado
});

Si llamas a this.resultado afuera del subscribe todavía no tendrá valor porque subscribe es asíncrono.
Quiere decir que cuando subscribe es llamado empieza a procesar los datos en segundo plano y cuando los datos están listos ejecuta la función anónima que se le ha pasado al método y le pasa los datos en la variable data. A todo esto el código después del subscribe se sigue ejecutando y por esa razón this.resultado está vacio afuera del subscribe(), porque sus datos aún no están listos.


text:
Q: What is the Google Drive file parents limit I'm using Google Drive as a storage and decided to put one file into multiple folders (~500) in my case. I called Google Drive v2 API PUT files method to update file parents. It returns me error 400.
Does anybody know what is the addParents and removeParents limitation?

redpajama_set_name: RedPajamaStackExchange


text:
Q: record contents of packets dropped in iptables I'm trying to find a way to record the entire contents of packets (possibly with tcpdump) that have been dropped according to rules in iptables.
At present, I have a rule to log these packets (with a log prefix), then follow this with a rule to drop them.
Is there a way to record the contents of those packets for review afterwards?
So, I'm looking for this:

*

*A rule that logs the matching packet

*A rule that passes the packet to a new target that records its contents (maybe QUEUE target?)

*A rule that drops the packet

2 & 3 may even be combined.
My understanding is that tcpdump may not be able to do this as it examines packets before iptables and therefore will not record just the dropped packets.
Thanks.

A: The NFLOG target can be used for this purpose. Here is a very basic example:
# Drop traffic by default
iptables -P INPUT DROP

# add your whitelists here
# iptables -A INPUT ...

# Pass the packets to NFLOG (just like LOG, but instead of syslog,
# it uses netlink). You can add extra filters such as '-p tcp' as usual
iptables -A INPUT -j NFLOG
# packets that get here will now be dropped per INPUT policy

# Finally you can use tcpdump to capture from this interface (there
# can only be one active user of nflog AFAIK)
tcpdump -i nflog ...

Refer to the iptables-extensions manual page for a description of the NFLOG target.


text:
Q: Which way to go for reading public data using Graph API? I am currently developing an app that's going to show a Facebook page's events in one tab. Now I'm struggling with facebook's graph API and I think I just need some more explanation about how the whole thing is meant to be.
I registered an app and got my app id, app secret and an access token. Generally it works by using my app id and the access token. But from what I've read there are two drawbacks with that.

*

*The token expires.

*There seems to be only one token at a time.

If the token expires I need to re-authenticate my app whenever the session is not valid any more. But - what's the correct way to do that? Is it by sending the request method by adding my data to the params dictionary?
And if there can only be one app access token at a time, will it result in conflicts when multiple clients are going to connect?
I want my app to just read public data, so authenticating a user is a no-go, as its simply not needed (I hope). But the more I think about it the more I think that using an app's token is not the correct way either.
How is this generally achieved? Do I need a wrapper web app to implement reading public event data?
Thanks for your help

*

*Arne

A: I've never had a problem using one app token with multiple users.
As for expiring tokens, you can request a generic token, which should be sufficient for retrieving public data, by sending a GET request to:
https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials


text:
Q: Identifying when value in field changes from 0 to 1 in ArcGIS Desktop? I am trying to identify the start and stop of a particular incident- these are indicated by the unique values 0,1,2,3,4,5,6.
0 represents no incident- therefore in order to identify when an incident starts and stops and only retrieve these data records (i.e. incident 1) I would like to know how to query or determine when the value in the incident field changes from a 0 to a 1 (i.e. the start) and query when the value changes from a 1 to a 0 i.e. the finish. I only want to compare these changes between adjacent records i.e. those either side of a record.

A: Like pointed out by others, the data structure information is missing. I am not sure if you want to fire a custom action on the value change.
Assuming you have a database, you can think of writing a trigger for every update in that field. Check if the update changes the value to 1 or back to 0. Based on the final value, you can decide the course of action.
But I am not sure if you can launch external programs from within SQL environment.

A: You haven't described your data structure very clearly but to get started with you can perofrm a select by attribute.
It sounds like you may have some more sophisticated data structure and may want to time analize these data. For which tracking analyst would be a good solution for you.


text:
Q: Grep and regex on a file with bash in a file how could I select line where there is :
Value_1 and Name_species
I should get for instance:
Value_1:(O)_content_:Name_species

I tried
grep "Value_1:*:Name_species" file

but it does not work...

A: The simpliest way to combine two greps is by grepping the one after the other:
grep "Value_1" <filename> | grep "Name_species"

A: alternative
grep -E "Value_1:.*:Name_species" <filename>


text:
Q: Making a unique index non-unique I have an already created index on a table, but I need to remove the unique feature.
Is there a way to make a unique index non-unique without remaking the index in Transact-SQL?

A: There is no ALTER INDEX option available to change uniqueness. You can drop and recreate the index with unique setting removed in a single statement like given below:
CREATE NonClustered INDEX Index_Name
ON  <TableName> (Column Name/s)
WITH DROP_EXISTING = ON;


text:
Q: My laptop doesn't recognize its internal disk as bootable. How do I fix this? I bought a Toshiba Satellite and installed Ubuntu using a homemade liveusb, choosing to use the entire HDD and set up an encrypted LVM in the process. The installer finished with no errors, but the laptop's firmware didn't seem to recognize the HDD as bootable; powering it on without the flash drive gave me this error (capitalization not mine):
Reboot and select proper Boot device
or Insert Boot Media in selected Boot device and press a key

I booted back to the liveusb, zeroed out the first few mebibytes of the HDD for good measure, and ran the installer again the same way, with the same result. After this, I tried sudo grub-install /dev/sda and sudo update-grub from the installed system. Both completed successfully, but didn't fix the problem.
Someone from Freenode/#ubuntu was kind enough to write a pair of GRUB commands that I could use at the flash drive's GRUB shell to boot from the HDD:
search --set=root --file /grub/grub.cfg
configfile /grub/grub.cfg

And a handy menu entry:
menuentry "Load Installed Ubuntu's grub.cfg" {
    search --set --fs-uuid $sda2_uuid
    configfile /grub/grub.cfg
}

($sda2_uuid is the UUID of the partition that gets mapped to /dev/sda2 and mounted at /boot in the installed system. /dev/sda1 is mounted at /boot/efi.)
This works well enough as a temporary measure, though obviously it's impractical for the long term, as it requires me to keep the flash drive around.
What's going on here? How do I get this laptop to recognize its HDD as bootable?

Partition table (sudo parted /dev/sda print)
Model: ATA TOSHIBA MQ01ABF0 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:

Number  Start   End    Size   File system  Name                  Flags
 1      1049kB  538MB  537MB  fat32        EFI System Partition  boot, esp
 2      538MB   794MB  256MB  ext2
 3      794MB   500GB  499GB

Update
I remembered reading somewhere that the EFI partition (/dev/sda1 in my case) should be FAT16, so I made a disk image of it, formatted it as FAT16, and copied all the files back. After rebooting, the an error would flash up an error for a split second:
Failed to open \EFI\BOOT\grubx64.efi

There was a ./EFI/ubuntu/grubx64.efi (relative to the root of sda1), so I copied it to ./EFI/ubuntu/grubx64.efi and the laptop now boots on its own. It still doesn't give me a GRUB menu, and now it also gets stuck on a solid purple screen for a good half minute before it shows any indication of getting on with the boot process (despite me having replaced quiet splash in the kernel arguments with text), but it boots.
This seems like a rather crude solution, and I don't know why it worked in my case, so I won't post it as an answer. I'll keep messing with it, though; hopefully I'll find something better.

A: Great security comes with great responsibility.
Your BIOS itself simply cannot boot from an encrypted partition. What you should have done is: create a small (unencrypted) boot partition that loads the LVM and the encryption/decryption module and hands over the boot process to the encrypted encryption/decryption module which then completes the boot process.
TrueCrypt is software that completely automates this, and its sole developer is not maintaining the software any more, but it's still be best out there!
So what you have to do now is:

*

*Make an unencrypted backup of your date (if you have any)

*Read the manual of the encryption software you're going to use completely (hopefully TrueCrypt) and use the LVM manuals to create your LVs (if this is your first time using LVM).

*Re-install using the procedure above


text:
Q: Uncaught SyntaxError: Invalid or unexpected token while running this code
Hi im trying getting Uncaught SyntaxError: Invalid or unexpected token when i click on the edit or delete button could someone tell me whats the problem with this code! i looked for 3 hours starring at this code and everything looks fine to me! if you could point out the obvious it would just save my day thanks!

for (i = 0; i < response.data.length; i++) {
                $("#table").append("
  " + response.data[i].user_email + " 	  " + response.data[i].booking_number + " 	  " + response.data[i].booking_address + " 	  " + response.data[i].booking_date + " 	  " + response.data[i].booking_message + " 	  " + response.data[i].request_date + " 	  " + response.data[i].chosen_emails_1 + " 	  " + response.data[i].chosen_emails_2 + " 	  " + response.data[i].chosen_emails_3 + " 	  <button onclick='edit(" + response.data[i].user_email + ");'> Edit </button>
    <button onclick='delete_(" + response.data[i].user_email + ");'> Delete </button>
");
              }

                    //to delete

delete_ = function(user_email) {
  alert("inside delete");
};

  //to edit

edit = function(user_email) {
  alert("inside edit");
};

A: the problem is that when you generate your html the result is
<button onclick='edit(test@gmail.com);'>

and the text inside the function should be inside quotes like this
<button onclick='edit("test@gmail.com");'>

to solve this use
"<button onclick=delete_('" + response.data[i].user_email + "');>"

instead of
"<button onclick='delete_(" + response.data[i].user_email + ");'>

in both buttons when you concatenate the strings

A: Since you're adding html elements dynamically and they aren't accessible in the dom when the page is first loaded, I think you could attach your events like this;
//to delete
$(document).on("click", ".delete-btn", function() {
  alert($(this).val());
});

//to edit
$(document).on("click", ".edit-btn", function() {
  alert($(this).val());
});

Here's a working sample. I added the appropriate classes to their respective buttons and placed the data inside the value attribute. Do run the snippet;

$(document).ready(function() {
  var response = {
    data: [{
      booking_number: "test A",
      user_email: "test A",
      booking_address: "test A"
    }]
  };

  for (i = 0; i < response.data.length; i++) {
    $("#table tbody").append("
" +
      "" + response.data[i].user_email + "	" +
      "" + response.data[i].booking_number + "	" +
      " " + response.data[i].booking_address + " 	" +
      " " + response.data[i].booking_date + " 	" +
      " " + response.data[i].booking_message + " 	" +
      " " + response.data[i].request_date + " 	" +
      " " + response.data[i].chosen_emails_1 + " 	" +
      " " + response.data[i].chosen_emails_2 + " 	" +
      " " + response.data[i].chosen_emails_3 + " 	" +
      " <button class='edit-btn' value='" + response.data[i].user_email + "'>Edit</button><button class='delete-btn' value='" + response.data[i].user_email + "'> Delete </button>	" +
      "
");
  }

  //to delete
  $(document).on("click", ".delete-btn", function() {
    alert($(this).val());
  });

  //to edit
  $(document).on("click", ".edit-btn", function() {
    alert($(this).val());
  });
})
#table {
  border-collapse: collapse;
}

#table tr td {
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 0px 4px 0px 4px;
}

#table tr td button {
  display: inline-block;
  margin-right: 4px;
}


text:
Q: Inconsistent module location in python and jupyter notebook Because of the incompatibility between the Apple's new M1 chip and TensorFlow in Python, I followed some online guides to create an environment under Miniforge3 (so that we can run the python in the arm64 instead of the x86_64 one? I don't fully understand the tricks here.).
Following the tutorial (at https://medium.com/codex/installing-tensorflow-on-m1-macs-958767a7a4b3), I created an environment named tf and successfully installed tensorflow. I checked that the modules are installed inside the miniforge3 folder:
(tf) pokfung@pn-204-145 ~ % which python
/Users/pokfung/miniforge3/envs/tf/bin/python
(tf) pokfung@pn-204-145 ~ % python
Python 3.8.10 | packaged by conda-forge | (default, May 11 2021, 06:27:18)
[Clang 11.1.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy, tensorflow
>>> print(numpy.__file__)
/Users/pokfung/miniforge3/envs/tf/lib/python3.8/site-packages/numpy/__init__.py
>>> print(tensorflow.__file__)
/Users/pokfung/miniforge3/envs/tf/lib/python3.8/site-packages/tensorflow/__init__.py

However, when I initiate the Jupyter notebook by (tf) pokfung@pn-204-145 ~ % jupyter notebook, I found that the notebook was not loading modules from the above directories:
import numpy
print(numpy.__file__)
# Output of the print statement is:
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/__init__.py

I wonder how I shall configure the Jupyter notebook so that it can correctly run in the tf conda environment.

A: Jupyter runs a kernel in the background that in your case supports Python, but it chooses the kernel from your main installation not the virtual environment you just installed. You can tell Jupyter which kernel to use - Have you tried that?


text:
Q: Understand canvas PaperJS path JSON export When I export the path drawn on PaperJS, I got this:
["Path",
  {"applyMatrix":true,
  "segments":
    [
      [
        [255, 451.51563],
        [0, 0],
        [0, -2.09596]
      ],
      [
        [255, 439.51563],
        [-1.22916, 1.22916],
        [0.23839, -0.23839]
      ],
      [
        [269, 441.51563],
        [0, -0.70695],
        [0, 0]
      ]
    ],
    "strokeColor":[0, 0, 1]
  }
]

In segments object, there are segments composed of 3 arrays. I understand that the first arrays are the coordinates of successives points drawn. What are the last two arrays?

A: These are the different points used to draw the path.  In your example that may be hard to illustrate due to the path being drawn.  In an easier example you can see point one is at x,y of 20,20  then the third point is moved 120 on the x axis and at 140,20.

The additional are used for handle in and handle out for example:

segments: [
    [[offset, y], null, vector.rotate(-90)],
    [[width / 2, y], vector.rotate(-180), vector],
    [[width - offset, y], vector.rotate(90), null]

http://paperjs.org/reference/path/#path-object


text:
Q: convert '18/10/2016 10:31:22PM' format into '18/10/2016 22:31:22' time format in javascript

var now = new Date('18/10/2016 10:31:22PM');
var time = now.toLocaleTimeString();

alert(time);

this function give an output invalid date. I want to convert this "18/10/2016 22:31:22" format. give me an appropriate example as a solution.

A: this function should work for your date format

function convertDate(date_string){
var d = date_string.trim();
d = d.split(" ");
v = d[1].split(":")[0];
v = d[1].indexOf("PM")>-1 ? +v+12 : v;
d[1] = d[1].replace(d[1].split(":")[0],v);
d = d.join(" ").replace("PM","").replace("AM","");
return d;
}

console.log(convertDate("18/10/2016 10:31:22PM"));
console.log(convertDate("01/10/2016 09:31:22PM"));
console.log(convertDate("06/10/2016 2:31:22AM"));
console.log(convertDate("07/10/2016 7:31:22AM"));

A: Without using a library, you will need to extract all the date tokens and send them into a new date object in the correct order. From there, you can create your own date formatting function.

var DATE_FORMAT = /(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}):(\d{2})([AP]M)/;
var dateStr = '18/10/2016 10:31:22PM';
var now = parseDateString(dateStr, DATE_FORMAT, function(tokens) {
  return [
    parseInt(tokens[3], 10),                  // year
    parseInt(tokens[2], 10) - 1,              // month
    parseInt(tokens[1], 10),                  // date
    to24(parseInt(tokens[4], 10), tokens[7]), // hours, meridiem
    parseInt(tokens[5], 10),                  // minutes
    parseInt(tokens[6], 10),                  // seconds
    0                                         // milliseconds
  ];
});
document.body.innerHTML = formateDate(now);

function parseDateString(dateStr, dateFormat, func) {
  var tokens = dateStr.match(dateFormat);
  var args = Array.prototype.concat.apply([null], func(tokens));
  return new (Function.prototype.bind.apply(Date, args));
}
function formateDate(date, dateSeparator) {
  return [
    pad2(date.getDate()),
    pad2(date.getMonth() + 1),
    date.getFullYear()
  ].join(dateSeparator || '/') + ' ' + [
    pad2(date.getHours()),
    pad2(date.getMinutes()),
    pad2(date.getSeconds())
  ].join(':');
}
function pad2(str) { return ('00' + str).substr(-2); }
function to24(hours, meridiem) {
  switch (meridiem) {
    case 'PM': if (hours < 12) return hours + 12;
    case 'AM': if (hours === 12) return hours - 12;
    default: return hours;
  }
}

Of course, this can be done in moment with one line.

var dateStr = '18/10/2016 10:31:22PM';
var time = moment(dateStr, 'DD/MM/YYYY hh:mm:ssA').format('DD/MM/YYYY HH:mm:ss');
document.body.innerHTML = time;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>


text:
Q: free allocated char* multiple times in C i have this code in C:
 char* func(char* str, int a) {
        str = malloc(a * sizeof(char));
        return str;
    }
    int main() {
        char* s1 = NULL;
        s1 = func(s1,4);
        s1 = "123";
        free(s1);
        s1 = func(s1, 5);
        s1 = "1234";
        free(s1);
        ...
    }

i keep getting run time error(as if it were an infinte loop)
is this using of s1 in main() legal?
would it produce memory leakage?

A: s1 = "123"; here you make s1 to point to a string literal and you should never call free for a string literal. My guess is that you meant to copy these characters to the memory allocated for s1. If that is the case, make use of strcpy. For instance:
char* func(char* str, int a) {
    str = malloc(a * sizeof(char));
    return str;
}
int main() {
    char* s1 = NULL;
    s1 = func(s1,4);
    strcpy(s1, "123");
    free(s1);
    s1 = func(s1, 5);
    strcpy(s1, "1234");
    free(s1);
    ...
}

As for your second question - you have a memory leak in your code but precisely because of the reason I already mentioned - s1 = "123"; does not copy the bytes but points s1 at the literal. The code I suggest should be safe of memory leaks.

A: You are freeing a string literal, and you loose the address s1 points to when you do s1 = "123"; and now you can never free it.

is this using of s1 in main() legal? would it produce memory leakage? \

it will compile but it is not an issue of ilegal use but incorrect use, and yes it is an evident memory leak.


text:
Q: Minimal http service test without resetting up routes? Say I have a very simple Web service.
func main() {
    http.HandleFunc("/", sanityTest)
    log.Fatal(http.ListenAndServe(":8000", nil))
}

If I want to test it, I could minimally just have:
func ExampleTest() {
        server := httptest.NewServer(http.DefaultServeMux)
        defer server.Close()

        resp, err := http.Get(server.URL)
        if err != nil {
                log.Fatal(err)
        }
        body, _ := ioutil.ReadAll(resp.Body)

        fmt.Println(resp.StatusCode)
        fmt.Println(resp.Header.Get("Content-Type"))
        fmt.Println(string(body))

        // Output:
        // 200
        // text/plain; charset=utf-8
        // OK

}

But that will result in a 404, since it doesn't know about the routes. So what I've seen main_test.go code do, is re-setup the handles in the test file's init, like so:
func init() {
    http.HandleFunc("/", sanityTest)
}

Which leads to duplication, and inevitably I have to create a function in main.go like:
func setupRoutes() {
        http.HandleFunc("/", sanityTest)
}

Which I find a little ugly. Am I missing a trick to instantiate the routes from main.go and avoid the init?

A: You can re-use routes between tests and main.go file, also it's helpful if you want to mock something in your handlers (add a new argument to router() func below)
main.go:
func sanityTest(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s", "sanity test")
}

func router() *http.ServeMux {
    h := http.NewServeMux()
    h.HandleFunc("/", sanityTest)
    return h
}

func main() {
    http.ListenAndServe(":8080", router())
}

main_test.go:
func TestSanity(t *testing.T) {
    tests := []struct {
        name string
        uri  string
        want string
    }{
        {"1", "/", "sanity test"},
    }

    ts := httptest.NewServer(router())
    defer ts.Close()

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            url := ts.URL + tt.uri
            resp, _ := http.Get(url)
            respBody, _ := ioutil.ReadAll(resp.Body)
            resp.Body.Close()

            got := string(respBody)
            if got != tt.want {
                t.Errorf("got %s, Want %s", got, tt.want)
            }
        })
    }
}


text:
Q: CW-filtration in K-Theory I'm just reading Atiyah's paper "Characters and cohomology of finite groups". In §2 he's defining a filtration on $K^*(X)$ by putting $K_p^*(X) = ker \{K^*(X) \rightarrow K^*{(X^{p-1}}) \}$, where $X$ is a finite CW-complex and the map is induced by the inclusion of the $(p-1)$-skeleton. Now he states that
$$K^0_{2k-1}(X) = K^0_{2k}(X), \ \ \ \ \ K^1_{2k}(X) = K^1_{2k+1}(X)$$
Why do these equalities hold? As I'm completely lost right now, any help is much appreciated.


text:
Q: Finding cheapest combination of items with conditions on the selection Lets say that I have 3 sellers of a particular item. Each seller has different amounts of this items stored. The also have a different price for the item.

Name            Price      Units in storage
Supplier #1     17$        1 Unit
Supplier #2     18$        3 Units
Supplier #3     23$        5 Units

If I do not order enough items from the same supplier, I have to pay some extra costs per unit. Let's say, for example, that if I do not order at least 4 units, I do have to pay extra 5$ for each unit ordered.
Some examples:
If I wanted to buy 4 units, the best price would come from getting them from Supplier #1 and Supplier #2, rather than getting it all from Supplier #3
(17+5)*1 + (18+5)*3 = 91                 <--- Cheaper
            23   *4 = 92

But if I were to buy 5 units, getting them all from Supplier 3 gives me a better price, than getting first the cheaper ones and the rest from more expensive suppliers
(17+5)*1 + (18+5)*3 + (23+5)*1 = 119
                       23   *5 = 115$    <--- Cheaper

The question
Keeping all this in mind... If I knew beforehand how many items I want to order, what would be an algorithm to find out what is the best combination I can chose?

A: As noted in comments, you can use a graph search algorithm for this, like Dijkstra's algorithm. It might also be possible to use A*, but in order to do so, you need a good heuristic function. Using the minimum price might work, but for now, let's stick with Dijkstra's.
One node in the graph is represented as a tuple of (cost, num, counts), where cost is the cost, obviously, num the total number of items purchased, and counts a breakdown of the number of items per seller. With cost being the first element in the tuple, the item with the lowest cost will always be at the front of the heap. We can handle the "extra fee" by adding the fee if the current count for that seller is lower than the minimum, and subtracting it again once we reach that minimum.
Here's a simple implementation in Python.
import heapq

def find_best(goal, num_cheap, pay_extra, price, items):
    # state is tuple (cost, num, state)
    heap = [(0, 0, tuple((seller, 0) for seller in price))]
    visited = set()

    while heap:
        cost, num, counts = heapq.heappop(heap)
        if (cost, num, counts) in visited:
            continue  # already seen this combination
        visited.add((cost, num, counts))

        if num == goal:  # found one!
            yield (cost, num, counts)

        for seller, count in counts:
            if count < items[seller]:
                new_cost = cost + price[seller]  # increase cost
                if count + 1 < num_cheap: new_cost += pay_extra  # pay extra :(
                if count + 1 == num_cheap: new_cost -= (num_cheap - 1) * pay_extra  # discount! :)
                new_counts = tuple((s, c + 1 if s == seller else c) for s, c in counts)
                heapq.heappush(heap, (new_cost, num+1, new_counts))  # push to heap

The above is a generator function, i.e. you can either use next(find_best(...)) to find just the best combination, or iterate over all the combinations:
price = {1: 17, 2: 18, 3: 23}
items = {1: 1, 2: 3, 3: 5}
for best in find_best(5, 4, 5, price, items):
    print(best)

And as we can see, there's an even cheaper solution for buying five items:
(114, 5, ((1, 1), (2, 0), (3, 4)))
(115, 5, ((1, 0), (2, 0), (3, 5)))
(115, 5, ((1, 0), (2, 1), (3, 4)))
(119, 5, ((1, 1), (2, 3), (3, 1)))
(124, 5, ((1, 1), (2, 2), (3, 2)))
(125, 5, ((1, 0), (2, 3), (3, 2)))
(129, 5, ((1, 1), (2, 1), (3, 3)))
(130, 5, ((1, 0), (2, 2), (3, 3)))

Update 1: While the above works fine for the example, there can be cases where it fails, since subtracting the extra cost once we reach the minimum number means that we could have edges with negative cost, which can be a problem in Dijkstra's. Alternatively, we can add all four elements at once in a single "action". For this, replace the inner part of the algorithm with this:
            if count < items[seller]:
                def buy(n, extra):  # inner function to avoid code duplication
                    new_cost = cost + (price[seller] + extra) * n
                    new_counts = tuple((s, c + n if s == seller else c) for s, c in counts)
                    heapq.heappush(heap, (new_cost, num + n, new_counts))

                if count == 0 and items[seller] >= num_cheap:
                    buy(num_cheap, 0)     # buy num_cheap in bulk
                if count < num_cheap - 1: # do not buy single item \
                    buy(1, pay_extra)     #   when just 1 lower than num_cheap!
                if count >= num_cheap:
                    buy(1, 0)             # buy with no extra cost

Update 2: Also, since the order in which the items are added to the "path" does not matter, we can restrict the sellers to those that are not before the current seller. We can add the for seller, count in counts: loop to his:
        used_sellers = [i for i, (_, c) in enumerate(counts) if c > 0]
        min_sellers = used_sellers[0] if used_sellers else 0
        for i in range(min_sellers, len(counts)):
            seller, count = counts[i]

With those two improvements, the states in the explored graph looks for next(find_best(5, 4, 5, price, items)) like this (click to enlarge):

Note that there are many states "below" the goal state, with costs much worse. This is because those are all the states that have been added to the queue, and for each of those states, the predecessor state was still better than out best state, thus they were expanded and added to, but never actually popped from the queue. Many of those could probably be trimmed away by using A* with a heuristic function like items_left * min_price.

A: This is a Bounded Knapsack problem. Where you want to optimize(minimize) the cost with the constraints of price and quantity.
Read about 0-1 KnapSack problem here. Where you have only 1 quantity for given supplier.
Read how to extend the 0-1 KnapSack problem for given quantity ( called Bounded Knapsack ) here
A more detailed discussion of Bounded KnapSack is here
These all will be sufficient to come up with an algorithm which requires a bit of tweaking ( i.g. adding 5$ when the quantity is below some given quantity )


text:
Q: Scheduler in Java I need some assistance in implementing a scheduler which runs parallel with the other processing. I found quartz scheduler for many of my searches on the web. But, I need something which is inbuilt and can run concurrently with other processes and not any external libraries
I checked with scheduleAtFixedRate. But, this has not option for parallel execution.
Can anyone please suggest in this regard?? My requirement is that, a java function has to run at every fixed intervals soon after the server starts. This will be known by the servlet start and I will have to initiate the scheduler in the init().

A:
My requirement is that, a java function has to run at every fixed
  intervals soon after the server starts

*

*To begin with, you can start using java.util.Timer. Here is a good link on usage of Timer class.

*Using quartz scheduler is always a better option, but Timer can be a quick way to start off with. You can find some help to start using Quartz Scheduler in Java

*Alternatively, you can also opt for ScheduledExecutorService in java. I would prefer this option over java.util.Timer

A: I suggest you to define a ServletContextListener, and to start a Quartz scheduler from its contextInitialized method.
contextInitialized is called on application deployment/reload on your application server, thus your scheduler can be initialized soon after the server starts.


text:
Q: Non-empty closures and the question mark: only first element is put into the AST? I'm haunted by a strange phenomenon:
Only the first in x in z: x | '<'! y? '>', where y: x (','! x)*, occurs in the resulting AST. But only if I compile the code using Antlr3 as deployed in the maven repositories. With AntlrWorks I see a correct Tree.
Is b: a a*; c: d b? d; semantically wrong? What am I doing wrong? Or is there simply an error in Antlr?
If you need a more complete example (my problem occurs in the $v2 of try_):
variables
    : annotatedVariable
        -> ^(VARIABLES annotatedVariable)
    | v='<' annotatedVariableList? '>'
        -> ^(VARIABLES[$v] annotatedVariableList?)
    ;

annotatedVariableList
    : annotatedVariable (','! annotatedVariable)*
    ;

try_
    : v='try' e1=expression 'of' v1=variables '->' e2=expression
      'catch' v2=variables '->' e3=expression
        -> ^(TRY[$v] $e1 $v1 $e2 $v2 $e3)
    ;

(Complete source and an example input file: https://gist.github.com/1004329. Only the T of  in catch  is present in the tree, but I see both T and R in AntlrWorks.)

A:
Kay wrote:
Only the first in x in z: x | '<'! y? '>', where y: x (','! x)*, occurs in the resulting AST. But only if I compile the code using Antlr3 as deployed in the maven repositories. With AntlrWorks I see a correct Tree.

ANTLRWorks produces a parse tree, not the AST your parser rules produce (assuming you're talking about ANTLRWorks' interpreter).
A simple test shows everything works just fine (tested with ANTLR v3):
grammar T;

options {
  output=AST;
}

z : x
  | '<'! y? '>'!
  ;

y : x (','! x)*
    ;

x : X
  ;

X : 'A'..'Z'
  ;

will parse the input:
<X,Y,Z>

into the following AST:

as you can test yourself:
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;

public class Main {
  public static void main(String[] args) throws Exception {
    TLexer lexer = new TLexer(new ANTLRStringStream("<X,Y,Z>"));
    TParser parser = new TParser(new CommonTokenStream(lexer));
    CommonTree tree = (CommonTree)parser.z().getTree();
    DOTTreeGenerator gen = new DOTTreeGenerator();
    StringTemplate st = gen.toDOT(tree);
    System.out.println(st);
  }
}

Kay wrote:
Is b: a a*; c: d b? d; semantically wrong?

No. But is this question related to your z: x | '<'! y? '>' rule? Sorry to say, but you're a bit vague.

Kay wrote:
What am I doing wrong?

I don't know. You'll have to post a short, self contained example here on SO, just like I posted. I'm not keen on following an external link and wading through hundreds of lines of code, sorry.


text:
Q: Fuel Level Sensor Safety I'm looking up fuel level sensor manufacturers (Omnicomm, Technoton etc) and noticed that a lot of them offer capacitive fuel sensors for all types of fuel. However, based on my understanding, capacitive fuel sensing involves electronics and fuel is highly flammable, the tiniest spark could cause an explosion. I tried to look up explanations for this but couldn't find something satisfactory (is galvanic isolation enough?).
I was hoping someone here could point me in the right direction, and if capacitive sensing really is safe for fuel tank level sensing, which sensors do you suggest for sensing petrol level at a filling station (not vehicles).
Please direct me to some industry standards/safety or regulations document for reference, thank you so much for your help!
If you require any more information, I'm ready to provide it.

A: Yes, there are Ex standards. The sensor itself has to be Ex version approved. The main point is to use such power supply and signal evaluation that does not produce spark in case of short circuit or malfunction - so this is so called Ex barrier. This is a device that separates non-ex zone and ex zone. All signals in ex zone are fed through this barrier, also the wiring has to be ex version, usually the cables are blue coloured.


text:
Q: How to get access token in AWS Cognito if using Browser based Javascript SDK? I currently use this (roundabout) way to find access token. What is the correct way to get it in browser JS ?
var cognitoUser = userPool.getCurrentUser();
var tempKey = "CognitoIdentityServiceProvider."+_config.cognito.userPoolClientId;
var LastAuthUserTemp = cognitoUser["storage"][tempKey+".LastAuthUser"];
var AccessToken = cognitoUser["storage"][tempKey+"."+LastAuthUserTemp+".accessToken"];

A: Once you get the session (call getSession() method), you can get the json web token via session.getIdToken().getJwtToken()
Here I am assuming your Cognito User Pool is configured to use jwt.


text:
Q: Efficient algorithm for calculating determinants Are there efficient algorithms for calculating determinants of matrices?

A: Suppose I have a square matrix $A \in \mathbb{C}^{n \times n} $
now
$$A = LU $$
in general the determinant takes $ \mathcal{O}(n!)$
instead
$$det(A) = det(LU) = det(L)det(U) $$
to calculate this
$$ det(A) = \prod_{i=1}^{n} l_{ii} \prod_{i=1}^{n} u_{ii} $$
however if the numerical stability is in question you could use the QR decomp
$$ A = QR$$
$$ det(A) = det(QR) = det(Q)det(R) $$
the determinant of $Q$ is 1 as it is orthogonal
$$ det(A) = \prod_{i=1}^{n} r_{ii}$$
now if the matrix is positive definite hermitian we can use the cholesky decomp
$$ A = R^{*}R$$
$$ det(A) = det(R^{*}R) = det(R^{*})det(R)$$
$$ det(A) = \prod_{i=1}^{n} r_{ii}^{*} \prod_{i=1}^{n} r_{ii}$$
There is also an algorithm called the Bareiss algorithm which has $\mathcal{O}(n^{2})$ time complexity for Toeplitz matrices.

A: You can perform a slight variation of Gauss elimination on the determinant to bring it into row echelon form.

*

*adding a scalar multiple of a row to another row will not change the value of the determinant, because the determinant is linear in its arguments (here: row vectors) and because it is alternating: two equal arguments will make it vanish (here: the addition)

*switching rows will flip the sign of the value of the determinant, because it is an alternating form

Laplace expansion along colums then has only contributions at the diagonal positions.
This lowers the complexity for a $n\times n$ matrix from $O(n!)$ for the Leibniz formula or Laplace expansion to $O(n^3)$ for Gauss elimination.


text:
Q: How best to deal with "None of the above" in Image Classification? This seems to be a fundamental question which some of you out there must have an opinion on.  I have an image classifier implemented in CNTK with 48 classes.  If the image does not match any of the 48 classes very well, then I'd like to be able to conclude that it was not among these 48 image types.  My original idea was simply that if the highest output of the final Softmax layer was low, I would be able to conclude that the test image matched none well.  While I occasionally see this occur, in most testing, Softmax still produces a very high (and mistaken) result when handed an 'unknown image type'.  But maybe my network is 'over fit' and if it wasn't, my original idea would work fine.  What do you think?  Any way to define a 49-th class called 'none-of-the-above'?

A: You really have these two options indeed--thresholding the posterior probabilities (softmax values), and adding a garbage class.
In my area (speech), both approaches are their place:
If "none of the above" inputs are of the same nature as the "above" (e.g. non-grammatical inputs), thresholding works fine. Note that the posterior probability for a class is equal to one minus an estimate of the error rate for choosing this class. Rejecting anything with posterior < 50% would be rejecting all cases where you are more likely wrong than right. As long as your none-of-the-above classes are of similar nature, the estimate may be accurate enough to make this correct for them as well.
If "none of the above" inputs are of similar nature but your number of classes is very small (e.g. 10 digits), or if the inputs are of a totally different nature (e.g. a sound of a door slam or someone coughing), thresholding typically fails. Then, one would train a "garbage model." In our experience, it is OK to include the training data for the correct classes. Now the none-of-the-above class may match a correct class as well. But that's OK as long as the none-of-the-above class is not overtrained--its distribution will be much flatter, and thus even if it matches a known class, it will match it with a lower score and thus not win against the actual known class' softmax output.
In the end, I would use both. Definitely use a threshold (to catch the cases that the system can rule out) and use a garbage model, which I would just train it on whatever you have. I would expect that including the correct examples in training will not harm, even if it is the only data you have (please check the paper Anton posted for whether that applies to image as well). It may also make sense to try to synthesize data, e.g. by randomly combining patches from different images.

A: I agree with you that this is a key question, but I am not aware of much work in that area either.
There's one recent paper by Zhang and LeCun, that addresses the question for image classification in particular. They use large quantities of unlabelled data to create an additional "none of the above" class. The catch though is that, in some cases, their unlabelled data is not completely unlabelled, and they have means of removing "unlabelled" images that are actually in one of their labelled classes. Having said that, the authors report that apart from solving the "none of the above" problem, they even see performance gains even on their test sets.
As for fitting something post-hoc, just by looking at the outputs of the softmax, I can't provide any pointers.


text:
Q: Get value with the lowest key value from Map[Int, String] Say I have a map: Map[Int, String]. How would I get the value [String] with the lowest key [Int]. I've been trying to implement this functionally, but just can't figure out how to do this.

A: The following code will get you a value with a lowest key (ignoring some corner cases).
def lowestKeyMember[A](m: Map[Int,A]): A = m(m.keys.min)

This will break ties arbitrarily and throw on an empty map. If you need to do this operation frequently and/or on large maps, you should look into SortedMap.

A: Maps are not normally sorted. You could however use a SortedMap, then the map will be sorted and the first value will be the head. All you need to do is retrieve the head.
map.head()

A: Come on, people!  "Functionally" is code word for "folding".
scala> val m = Map(1->"eins",2->"zwei",3->"drei")
m: scala.collection.immutable.Map[Int,String] = Map(1 -> eins, 2 -> zwei, 3 -> drei)

scala> m.foldLeft(Int.MaxValue -> "") { case (min,p) => if (min._1 <= p._1) min else p }
res0: (Int, String) = (1,eins)

But an 8-char operator?
Let's see, is that enough parens?  Don't tell me -> is like - and /: is like /.
scala> (Int.MaxValue -> "" /: m) { case (min,p) => if (min._1 <= p._1) min else p }
<console>:9: error: missing arguments for method /: in trait TraversableOnce;
follow this method with `_' if you want to treat it as a partially applied function
              (Int.MaxValue -> "" /: m) { case (min,p) => if (min._1 <= p._1) min else p }
                                  ^

Oh, well, OK.
scala> ((Int.MaxValue -> "") /: m) { case (min,p) => if (min._1 <= p._1) min else p }
res2: (Int, String) = (1,eins)

Or,
scala> import math.Ordering.Implicits._
import math.Ordering.Implicits._

scala> ((Int.MaxValue -> "") /: m) { case (min,p) if min <= p => min case (_, p) => p }
res5: (Int, String) = (1,eins)

A: A variant of the _.keys.min solution that works with Options (i.e. will not throw on an empty map):
scala> val a : Map[Int, String]=Map(1 -> "1", 2 -> "2")
a: Map[Int,String] = Map(1 -> 1, 2 -> 2)

scala> val b : Map[Int, String]=Map()
b: Map[Int,String] = Map()

scala> def valueForMinKey[K,V](a : Map[K,V])(implicit cmp : Ordering[K]) = a.keys.reduceOption(cmp.min(_, _)).map(a(_))
valueForMinKey: [K, V](a: Map[K,V])(implicit cmp: Ordering[K])Option[V]

scala> valueForMinKey(a)
res27: Option[String] = Some(1)

scala> valueForMinKey(b)
res28: Option[String] = None

In this example, the implicit parameter cmp will be satisfied by Ordering.Int. The example will work with any Map where the keys can be ordered (and a matching implict can be found by the compiler).


text:
Q: Small Technicality in simple Mayer Vietoris Example
In this example from Hatcher's book, he is trying to show how to use Mayer-Vietoris to calculate the homology groups of $S^n$.
However, I think we need $X=int(A)\cup int(B)$, which doesn't seem to hold in this example?
$int(A)\cup int(B)$ seems to be $X$ minus the "equator".
Thanks for any help.


text:
Q: How do I set a Svelte Component's event listener and inner HTML for slot dynamically via JavaScript? JavaScript:
    const dispatchEvent = createEventDispatcher();
    let dialog: Dialog;

HTML
<Dialog bind:this={dialog} on:close={() => {dispatchEvent("deletedPost", postIndex)}} modal={true} open={false}>
    ... Here I want to insert some HTML to be used in the slot of the "Dialog" component.
</Dialog>

My question is, how do I set the on:close and the inner HTML dynamically via JS?
I have this demand because this Dialog component should be reused for multiple purposes by its parent component. Sometimes it displays info about a post has been created, sometimes deleted, sometimes edited and so on.
And each of the cases requires different content in the component as well as a different handler for the close event emitted by the Dialog.
Should I use something like
dialog.$on = handlerFunction;
// I didn't find a possible property for setting HTML though

Thanks!

A: There currently is no way to programmatically interact with the slots (unless you want to investigate the Svelte internals and rely on implementation details which may change).
Either pass in a full component via the props (which can be rendered using <svelte:component>), insert only text or use {@html} to render HTML content (which is not recommended for security reasons).
(The syntax for the events is dialog.$on('close', event => ...) as detailed in the client-side API section.)

Example for all mentioned property types:

Dialog

    {#if component}
        <svelte:component this={component} />
    {/if}
    {#if text}
        {text}
    {/if}
    {#if html}
        {@html html}
    {/if}

<button on:click={() => open = false}>Close</button>

Usage:
// ...
import Content from './Content.svelte';
const d = new Dialog({
    // ...
    props: { text: 'Hello world' },
});
// or
const d = new Dialog({
    // ...
    props: { html: '<input placeholder="Text here"/>' },
});
// or
const d = new Dialog({
    // ...
    props: { component: Content },
});

d.$on('close', () => d.$destroy());

REPL
As noted, @html is dangerous and ideally should only be used with XSS sanitization in place.


text:
Q: Can Balloons used defensively damage your own structures? If I put balloons in my clan castle and they are triggered by an attacker. Do the bombs they drop do any damage to my own base or are my own structures immune to those bombs?

A: Your units cannot deal damage to your own base, and that includes units you received in your clan castle.
And that includes Balloons, even if they usually deal damage to their surroundings should they crash down.
The same applies for Valkyries, Wizards, Dragons, Golems, Wall Breakers (if somehow you received those as cc troops) which do splash damage one way or another.
The damage they deal will only affect enemy troops.


text:
Q: itext 7 text extraction from PDF file outputs unreadable text itext generates unreadable text when I try to extract the text from the attached PDF.
The font used in the PDF is True type (cid) with Identity-H encoding
{<< / BaseFont / GCMURL + SegoeUI / DescendantFonts [13 0 R] / Encoding / Identity-H / Subtype / Type0 / Type / Font >>}
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas.Parser.Listener;
using iText.Kernel.Pdf.Canvas.Parser;
using System.Diagnostics;
using iText.Kernel.Font;

            PdfReader pdfReader = new PdfReader(@"C:\Users\Myfile-_.pdf");
            PdfDocument pdfDoc = new PdfDocument(pdfReader);

            for (int page = 1; page <= pdfDoc.GetNumberOfPages(); page++)
            {
                PdfPage pagina = pdfDoc.GetPage(page);
                PdfDictionary fontResources = pagina.GetResources().GetResource(PdfName.Font);

                foreach (PdfObject font in fontResources.Values(true))
                {

                    if (font is PdfDictionary)
                        fontResources.Put(PdfName.Encoding, PdfName.IdentityH);
                }

                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string pageContent = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(page), strategy);

                Debug.WriteLine("pageContent : " + pageContent);
            }
            pdfDoc.Close();
            pdfReader.Close();

Any suggestions as to what I might have missed?
PDF is available here: https://files.fm/u/r4ejybyp8


text:
Q: How can I turn on the map mode for the scroll bar in Visual Studio 2019? I wish to get an overview of my code next to the scroll bar in Visual Studio 2019, something similar to the VS Code's Minimap.
How can I turn it on?

A: Open scroll bar options under Tools > Options > Text Editor > All Languages > Scroll Bars
and enable "Use map mode for vertical scroll bar"


text:
Q: Removing Elements From A LinkedList In A For Loop; Alternatives? I am working on a program that automatically downloads videos from websites. Each link has one video link so I am grabbing that link, then going through the re-directs to actually get the direct download link. Anyway, I am having trouble removing the element from the LinkedList; I am trying to make it so after the video is downloaded, the element is removed and it moves onto the next element (website URL). Currently, it gives me a warning saying to replace it with iterator().remove() but when I did that it gave me another error: "IllegalStateException". I am also going to have to know which episode is about to download to determine if it needs to be skipped later on in the program if it's already downloaded. I have attempted this by setting a field variable but haven't had much luck with that either as I am using a for loop and for loops use local variables. I am not sure what else to try, so any help would be appreciated! Thanks!
package com.trentmenard;
import org.jsoup.*;
import org.jsoup.nodes.*;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.LinkedList;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

class WebsiteScraper {
    private Document websiteConnection;
    private String episodeName;
    private String iFrameLink;
    private String URLDownloadLink;
    private String URL;
    private static DecimalFormat decimalFormat = new DecimalFormat("#.##");

    private LinkedList<String> episodeURLs = new LinkedList<>();
    private int currentEpisodeDownloading;

    WebsiteScraper(String URL) {
        for(int i = 1; i < 25; i++){
            episodeURLs.add("https://swordartonlineepisode.com/sword-art-online-season-3-episode-" + i + "-english-dubbed-watch-online/");
        }
        for(int x = 1; x < 25; x++){
            connectToURL("https://swordartonlineepisode.com/sword-art-online-season-3-episode-" + x + "-english-dubbed-watch-online/");
            episodeURLs.remove(x);
            currentEpisodeDownloading = x;
            getEpisodeName();
        }
    }

    private void connectToURL(String URL) {
        try{
            websiteConnection = Jsoup.connect(URL).get();
            System.out.println("Connection Successfully Established to: " + URL);
        }catch (IOException e)
        {e.printStackTrace();}

        if(URL.equals(iFrameLink)){
            getDownloadLink();
        }
        else if(URL.equals(URLDownloadLink)) {
            getDirectDownloadLink();
        }
    }

    private void getEpisodeName(){
        Element h2 = websiteConnection.selectFirst("h2");
        episodeName = h2.text();
        System.out.println("Found Episode Name: " + episodeName);
        getIFrameLink();
    }

    private void getIFrameLink(){
        Element iFrame = websiteConnection.selectFirst("iframe");
        iFrameLink = iFrame.attr("src");
        System.out.println("Found iFrame Link: " + iFrameLink + " for: " + episodeName);
        connectToURL(iFrameLink);
    }

    private void getDownloadLink() {
        Element hiddenID = websiteConnection.getElementById("id");
        String hiddenIDValue = hiddenID.attr("value");
        URLDownloadLink = "https://www.vidstreaming.io/download?id=" + hiddenIDValue;
        System.out.println("Found Download Link Using ID Value (" + hiddenIDValue + "): " + URLDownloadLink);
        connectToURL(URLDownloadLink);
    }

    private void getDirectDownloadLink(){
        Element downloadClass = websiteConnection.getElementsContainingOwnText("Download (orginalP - mp4)").first();
        String directDownloadLink = downloadClass.attr("href");
        System.out.println("Found Direct Download Link: " + directDownloadLink);
        downloadEpisode(directDownloadLink, episodeName);
    }

    private void downloadEpisode(String URL, String episodeName) {
        this.URL = URL;

        float Percent = 0;
        String downloadProgress = "0.00";

        JFrame progressFrame = new JFrame();
        JProgressBar progressBar = new JProgressBar(0, 100);

        progressBar.setSize(100, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        progressFrame.setTitle("Downloading: " + episodeName + " - " + Percent + "%");
        progressFrame.add(progressBar);
        progressFrame.setVisible(true);
        progressFrame.setLayout(new FlowLayout());
        progressFrame.setSize(575, 100);
        progressFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);

        JLabel percentComplete = new JLabel(downloadProgress + "% complete.");
        progressFrame.add(percentComplete);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        File createFile = new File(episodeName + ".mp4");
        if (createFile.exists() && !createFile.isDirectory()) {
            System.out.println("File: " + episodeName + " Already Exists! Moving Onto Next URL.");
            // TODO: 1/26/2020 FOR STATEMENT FOR MOVING ONTO NEXT URL.
        }
        try {
            java.net.URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            System.out.println("Connection Successfully Established!");
            System.out.println("Downloading File: " + episodeName);

            int filesize = connection.getContentLength();
            float totalDataRead = 0;
            byte[] data = new byte[1024];
            int i = 0;

            java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
            java.io.FileOutputStream fos = new java.io.FileOutputStream(episodeName + ".mp4");
            java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

            while ((i = in.read(data, 0, 1024)) >= 0) {
                totalDataRead = totalDataRead + i;
                bout.write(data, 0, i);
                Percent = (totalDataRead * 100) / filesize;
                decimalFormat.setRoundingMode(RoundingMode.CEILING);
                downloadProgress = decimalFormat.format(Percent);

                progressFrame.setTitle("Downloading: " + episodeName);
                progressBar.setValue((int) Percent);
                percentComplete.setText(downloadProgress);
            }
            bout.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Connection Failed!");
        }
    }
}

A: The Collection interface defines a method removeIf(Predicate<? super T> predicate) that, as the name suggests, removes all elements that satisfy the Predicate. You can use this to avoid your IllegalStateException (although you do not show your stack trace, I imagine the root cause is a ConcurrentModificationException).
For example:
List<String> list = Arrays.asList("hello", "world", "abc");
list.removeIf(str -> str.length() == 5);

// list = {"abc"}

However, in your case, you are calling list.remove(x), where x is an int on a List<String>. Since you iterate over x, I expect this code, even if you fix the IllegalStateException will throw another exception as you try to access an index out of range.

A: iterator().remove() doesn't work because the iterator initially doesn't point to a thing to remove.
If you want to use an Iterator:
Iterator<?> it = iterator();
it.next(); // Advance the iterator.
it.remove(); // Remove the previously-returned element.

But then, if it's a LinkedList, list.remove(0); or list.removeFirst(); would be far easier.


text:
Q: Put Append Block operation with Blob Service Rest API - 403 Authentication failure I'm investigating an error that has only happened with the Put Append operation in my application which communicates with Azure Blob Service thanks to the Rest API.
The creation of the file has succeeded but since it's an append blob, I had to add content with Append Block operation and I'm getting a 403 Forbidden WebException when I try to do so :
<?xml version="1.0" encoding="utf-8"?><Error>AuthenticationFailed<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:00dc0116-0001-00c2-066b-cbafe8000000
Time:2017-05-12T22:01:16.1689598Z</Message><AuthenticationErrorDetail>The MAC signature found in the HTTP request 'N7UVKFwftf2YnAFdnciRneu7LsAkWHKXUpwhFRxlQqI=' is not the same as any computed signature. Server used following string to sign: 'PUT

800

x-ms-date:Fri, 12 May 2017 22:01:15 GMT
x-ms-version:2016-05-31
/<myaccount>/write/FixedRecord10r.txt
comp:appendblock'.</AuthenticationErrorDetail></Error>

However, in the method where I construct the signature I displayed the stringToSign and it's exactly the same as the server used !
PUT

800

x-ms-date:Fri, 12 May 2017 22:01:15 GMT
x-ms-version:2016-05-31
/<myaccount>/write/FixedRecord10r.txt
comp:appendblock

Here is the header I parametrized :
public void AppendFile(MemoryStream stream)
{
 string dateFormatted = string.Format(CultureInfo.InvariantCulture, "{0:R}", DateTime.UtcNow);
 string signature = GetSignature("PUT", "xxxxxxx", afsAccount, dateFormatted, null, null, stream.Length, null);

 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://" + afsAccount + ".blob.core.windows.net" + path + "?comp=appendblock");
 request.Headers.Add("x-ms-version", "2016-05-31");
 request.Headers.Add("x-ms-date", dateFormatted);
 request.Headers.Add(HttpRequestHeader.Authorization, "SharedKey " + afsAccount + ":" + signature);
 request.Method = "PUT";
 request.ContentLength = stream.Length;

 using (var requestStream = request.GetRequestStream())
 {
      stream.Position = 0;
      stream.CopyTo(requestStream);
 }

 try
 {
  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){
...
}

    private String GetSignature(string verb, string azureAccessKey, string afsAccount, string date, string byteRange, string containerName, long contentLength, string blobType)
    {
        if(byteRange != null)
        {
            byteRange = "x-ms-range:" + byteRange + "\n";
        }

        string path = "/" + afsAccount + Dfs.Path;
        if (containerName != null)
        {
            path = "/" + afsAccount + "/" + containerName + "\nrestype:container";
        }else if (contentLength > 0)
        {
            path += " \ncomp:appendblock";
        }

        string length = "\n";
        if (contentLength != 0)
        {
            length = contentLength.ToString() + "\n";
        }

        if (blobType != null)
        {
            blobType = "x-ms-blob-type:" + blobType + "\n";
        }

        // construct input value
        string inputValue = verb + "\n" +
          "\n" + /*Content-Encoding*/
          "\n" + /*Content-Language*/
          length + /*Content-Length*/
          "\n" + /*Content-MD5*/
          "\n" + /*Content-Type*/
          "\n" + /*Date*/
          "\n" + /*If-Modified-Since*/
          "\n" + /*If-Match*/
          "\n" + /*If-None-Match*/
          "\n" + /*If-Unmodified-Since*/
          "\n" + /*Range*/
          blobType +
          "x-ms-date:" + date + "\n" +
          byteRange +
          "x-ms-version:2016-05-31\n" +
          path;

        Console.WriteLine(inputValue);

        // create base64 encoded signature
        var hmac = new HMACSHA256();
        hmac.Key = Convert.FromBase64String(azureAccessKey);
        byte[] sigbyte = hmac.ComputeHash(Encoding.UTF8.GetBytes(inputValue));
        var signature = Convert.ToBase64String(sigbyte);

        return signature;
    }

I'm now wondering if I missed something or if there is a problem with this specific operation as I've never had the problem with other operations.

A: I noticed that there's an extra space here (between " and \n):
{
    path += " \ncomp:appendblock";
}

Please remove this space and try your request again.


text:
Q: How do I keep my C# Windows Form Responsive while it churns loops? I have this massive nested loop scenario that is calling the DB and making HTTP requests to Basecamp API. At first it was a web app but it took much time to run the app so the user (billing department) would often quit out early or complain because it would take so long with no feedback and no way to cancel it. I wanted to make it more responsive and give it a Cancel button as well as a real time log, I also wanted to make it more controllable. I put it in forms so they could have control of every instance of it and have a cancel button and a real time log.
However when I hooked it all up with form buttons, multi-line text box to replace the response and error log, I cannot get anything to work! I added checks in the loop to break out if Cancel becomes pressed. However I can't even click cancel and the multiline TextBox will not live update when I .Text.Insert and then .Update() it. The whole app just sits there and spins... How do I get it to be responsive, accept button clicks during looping, and live update the multi-line TextBox?
NOTE: The thing compiles fine and I can step through it and it writes to a log file just fine so I can tell it's working after the fact that my form freezes up by looking at that log file.
Here is the code I am trying to update the multi-line TextBox with:
TimeSyncLog.Text.Insert(TimeSyncLog.Text.Length, "(((" + clientCode + ")))\n");

And here is the code for my loop breakout:
if(CancelPressed)
{
    TimeSyncLog.Text.Insert(TimeSyncLog.Text.Length,"\n\nSYNC STOPPED BY USER.");
    break;
}

But I can never click the Cancel button to toggle that boolean because the window says 'Not Responding'...

A: You shouldn't do any time consuming business logic on the UI thread.
you can use the BackgroundWorker class for those kind of things. it also support cancellation and progress report.
You can read about it here.

A: The UI thread should have only UI related changes in it.  Semi-irrelevant to your question, there's an awesome threading tutorial here.
BackgroundWorker is a great class that uses the thread pool, though there are many options and things to consider when threading.  If you want to cancel the thread, maybe nest an event in the GUI class so that the worker can subscribe to it, to handle the event of the 'Cancel' button being pressed.  Perhaps that isn't the most efficient way, but I'm sure someone else around here can recommend a few more alternative routes. Hope this helps.


text:
Q: Append npy file to another npy file with same number of columns in both files npy files size are around 5 gb and RAM is around 5gb so cannot load both numpy arrays. How to load one npy file and append its rows to other npy file without loading it

A: An npy file is a header containing the data type (metadata) and shape, followed by the data itself.
The header ends with a '\n' (newline) character.  So, open your first file in append mode, then open the second file in read mode, skip the header by readline(), then copy chunks (using read(size)) from the second file to the first.
There is only one thing left: to update the shape (length) field in the header.  And here it gets a bit tricky, because if the two files had for example the shapes (700,) and (400,), the new shape needs to be (1300,) but you may not have space in the header for it.  This depends on how many pad characters were in the original header--sometimes you will have space and sometimes you won't.  If there is no space, you will need to write a new header into a new file and then copy the data from both source files.  Still, this won't take much memory or time, just a bit of extra disk space.
You can see the code which reads and writes npy files here: https://github.com/numpy/numpy/blob/master/numpy/lib/format.py - there are some undocumented functions you may find useful in your quest.


text:
Q: Align text and use indent  I want to align my text and also use indent at each paragraph.But it seems i can use only one of them (either alignment or indent).
\usepackage{indentfirst}

\begin{flushleft}

\section {Heading}

\indent Here is text.....

\par\indent Another text,....

\end{flushleft}

A: Are you sure you want this?  flushleft uses \raggedright which sets \parindent to 0 if you \setlength\parindent{2em} after starting the environment you will get a visible indent again.


text:
Q: Повторяющиеся слова в `.txt` Как найти все слова, которые повторяются в .txt файле, и вывести их на экран ?

A: Можно например вот таким образом:
string[] input = "1 1 1 2 3 4".Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
//string[] input = File.ReadAllText("file.txt").Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

string[] output = (from word in input where Array.IndexOf(input, word) != Array.LastIndexOf(input, word) select word).Distinct().ToArray();

A: var hash = new HashSet<string>();
var strings = File.ReadAllText("file.txt")
        .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Where(x => !hash.Add(x)).Distinct().ToArray();
foreach (var s in strings)
{
    Console.WriteLine(s);
}

Метод HashSet<>.Add() возвращает false, если элемент уже есть в коллекции.

A: File.ReadAllText("file.txt")
    .Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
    .GroupBy(w => w)
    .Where(w => w.Count() > 1)
    .Select(w => w.Key)
    .ToList()
    .ForEach(Console.WriteLine);


text:
Q: Tails installer packages missing? I asked this question on stackoverflow already, but someone pointed me to this community (that I didn't know about before) - so here it is again:
I want to install Linux Tails. I already added ppa:tails-team/tails-installer to my sources, but when my Ubuntu Software Center tries to download the repository information, I get this error:
W:Failed to fetch
http://ppa.launchpad.net/tails-team/tails-installer/ubuntu/dists/trusty/main/binary-amd64/Packages
404 Not Found , W:Failed to fetch
http://ppa.launchpad.net/tails-team/tails-installer/ubuntu/dists/trusty/main/binary-i386/Packages
404 Not Found , E:Some index files failed to download. They have been
ignored, or old ones used instead.

I am using ubuntu 14.04 LTS. If you follow the link up to tails-installer/ubuntu/dists/ you can see that "trusty" is missing.
Any idea on what to do? Should I just wait?

A: You can't install the tails installer on Ubuntu 14.04 :/

In this step, you will install Tails Installer, a program designed
  specifically for installing Tails. Tails Installer is available in:

*

*Debian 8 (Jessie) or later in the backports repository

*Ubuntu 15.10
  (Wily) or later in a PPA (Personal Package Archive)

from tails installation doc
You'll need to install Tails using GNOME Disks


text:
Q: Remove "?"-button from Qt dialog I want to remove the "?"-button from a Qt dialog like explained here, but somehow it doesn't work.
This is my code:
Qt::WindowFlags flags;
flags = (Qt::Dialog | Qt::WindowStaysOnTopHint) &
          ~Qt::WindowContextHelpButtonHint;
setWindowFlags( flags );

I think that there is something wrong with the bitwise operators, but I don't know what..

A: This works fine for me:
QDialog *dialog = new QDialog;
Qt::WindowFlags flags(Qt::WindowTitleHint);
dialog->setWindowFlags(flags);

The most common way, however, is to pass the flags in the constructor:
QDialog *dialog = new QDialog(0, Qt::WindowTitleHint);

EDIT: I think there is a misunderstanding about the QFlags operators (see comments below). This example might clear it up:
Qt::WindowFlags flags(Qt::Dialog | Qt::WindowStaysOnTopHint);
qDebug() << flags.testFlag(Qt::WindowContextHelpButtonHint); // false because the flag hasn't been added
flags = flags | Qt::WindowContextHelpButtonHint;
qDebug() << flags.testFlag(Qt::WindowContextHelpButtonHint); // true because it has been added
flags = flags & ~Qt::WindowContextHelpButtonHint;
qDebug() << flags.testFlag(Qt::WindowContextHelpButtonHint); // false because it has been removed

The penultimate line of code removes Qt::WindowContextHelpButtonHint from flags. It does not add a "negative" flag.
At least that is my understanding.


text:
Q: Is there a standard way to organize methods within a class? There seem to be many different ways of organizing methods in a class. I could group methods by access, and order them alphabetically. I could group related methods together. I could use a mix of the two, or something else entirely. Is there a standard way to approach this? If not, how do you approach it?

A: Whatever you do, put it in your standards and be consistent. We use a custom Regionerate configuration to order our methods. Everyone on the team uses the same configuration.
EDIT: We're now using ReSharper's Code Cleanup with a custom Type Members Layout.

A: StyleCop enforces some things here:

Within a class, struct, or interface, elements must be positioned in the following order:

*

*Fields

*Constructors

*Finalizers (Destructors)

*Delegates

*Events

*Enums

*Interfaces

*Properties

*Indexers

*Methods

*Structs

*Classes

Furthermore, elements are ordered by access:

*

*public

*internal

*protected internal

*protected

*private

As well as a few other rules:

*

*Contants have to appear before fields

*static elements have to appear before instance elements.

This might be a good baseline to start. As for additional ordering rules, I usually group related methods together.

A: I use NArrange which does most of the things I want: Group fields, methods... alphabetically and by access modifiers. It also enforces some Style Cop rules (e.g. order of element types, location of using statements). NArrange is configurable to quite some degree, you do not have to live with the default configuration if you do not like it.
Update: Now I use Resharper since NArrange does not work correctly with newer C# syntax.

A: I do not order them by access modifier, nor do I order them alphabetically.  (I think this is quite a burden when you add or rename a method in that class ... ).
If necessary, I group them by functionality.  I mean: I put related methods toghether.
But, if you follow the SRP (Single Responsability Principle), then I think that ordering methods is in most of the circumstances a non-issue; since, when you follow SRP, your classes wouldn't have very much methods.

A:
I group my methods by their access modifier
and in the following sequence:

*

*public

*internal

*protected internal

*protected

*private

A: Since Visual Studio has tools for navigating quickly to methods by name, I prefer to put private member variables and constructors close to the top and group methods by functionality (ie, helper methods are close by to the methods that call them).  I also group properties together.  If a class becomes substantial, I make use of #region directives to show the organization.

A: I tend to find grouping of related methods far more useful when reading someone else's source code, than some arbitrary pseudo-order such as alphabetical.
Although the book is specifically about Java, Uncle Bob's Clean Code contains some excellent general principles for readability in OO classes. In particular, he uses the metaphor of a well-written newspaper article, with a headline at the top followed by a synopsis paragraph and then increasing detail as you read further down the article. By aiming for a similar top-down structure in your classes, it makes the task of reading or understanding your code much easier for others.

A: No, most people just group methods by logical similarity, or not at all.  It doesn't really matter - classes shouldn't get too big, and with a decent IDE you can just ctrl+click to goto to any method definition anyways.

A: I suggest first grouping by interface they come thru, with a nice comment saying the interface name - because these are non-obvious.
Then, by relation, and only then sorting alphabetically.
Use a lot of blank lines to reduce the reader's cognitive load.

A: I group my method by functionality, ranging from most generic to most concrete, all that inside a region, so I can hide unnecessary details.

A: Microsoft's StyleCop tool does a nice job of defining element order within a class.  You can also write extensions to the tool to conform to your company's coding standards.  That being said, StyleCop is a good starting point.

A: I'm not sure there's a consistently standard way... but I group related methods together, perhaps sub-grouped by accessor.  Makes it the easiest for finding related things later down the track.


text:
Q: Want to update mutiple records with update trigger Let me explain my scenario.
Let say I have 10 records in my "Activities" Table with "EstimatedDate" column. Each record is unique and have a different "EstimatedDate". These all 10 records belongs to one project, with same "ProjectId".
If I change the "EstimatedDate" of one row it should automatically change the below rows in the table which has the same "ProjectId".

A: CREATE TRIGGER dbo.Activities_Update
ON dbo.Activities
AFTER UPDATE
AS
BEGIN
  SET NOCOUNT ON;
  UPDATE a
    SET EstimatedDate = i.EstimatedDate
    FROM dbo.Activities AS a
    INNER JOIN inserted AS i
    ON a.ProjectId = i.ProjectId
    WHERE a.EstimatedDate <> i.EstimatedDate;
END
GO

While it's unlikely that your UPDATE statement looks like this:
UPDATE Activities SET EstimatedDate = CASE
  WHEN ActivityID = 1 THEN GETDATE()
  WHEN ActivityID = 2 THEN DATEADD(DAY, 1, GETDATE()) END
WHERE ProjectID = 1;

If you want to use the MAX date from inserted, you could say:
CREATE TRIGGER dbo.Activities_Update
ON dbo.Activities
AFTER UPDATE
AS
BEGIN
  SET NOCOUNT ON;

  ;WITH i AS (SELECT ProjectId, d = MAX(EstimatedDate)
    FROM inserted GROUP BY ProjectId)
  UPDATE a
    SET EstimatedDate = i.d
    FROM dbo.Activities AS a
    INNER JOIN i
    ON a.ProjectId = i.ProjectId
    WHERE a.EstimatedDate <> i.d;
END
GO

Latter is untested.


text:
Q: How to go from long to wide with stated preference data in R I hope this is not a cross-posting. I have been trying to understand from the available links on stackoverflow how to perform a change in the data from long to wide. I think I am almost there but there is still a lot missing.

I have stated prefence data on the choice between an electric and a gasoline car. Some variables are related to cars in general, such as PREZZO, whilst some other are specific to electric cars, such as AUTONOMIA_EV and others to internal combustion engine cars, such as AUTONOMIA ICEV.
Each respondent is identified by a number in the column INTERTOT. The first respondent has number 111. There are 20 rows corresponding to this individual because he faces 10 choices amongst two cars, one electric and one gasoline. In the column SCELTAEFF2 a value equal to 1 indicates the choice performed by the individual. Such a value has to be compared to correspoding one reported in column EV, where a value of 1 indicates that the option in that line is an electric vehicle.
Therefore, for example, if you look at line 4, which concerns the second choice confronted by the first individual, the column SCELTAEFF2 takes a value of 1 and the corresponding row on the column EV is 1 as well. This means that the respondent, for the second proposed alternatives, choose the electric vehicle. If you look, insted, at line 8, which concerns the fourth choice, the individual choose a gasoline car. This is the case because the column SCELTAEFF2 takes a value of 1, but the corresponding row on the column EV is zero.
Now, I would like to have for each respondent, INTERTOT, only one line, contaning all information that are now spread on 20 rows.
The file that I have is very big and that's why I am showing you only a part.
I would like to estimate a hybrid choice model and perform the calculation of the willingness-to-pay trough the delta method, but the very first issue is related to have the data in the right format.
The code I am trying is the following:
prova_reshape.wide = reshape(data = "prova_reshape", idvar = "INTERTOT", direction = "wide" )

but, of course, I get the following error message:

Error in data[, timevar] : numero di dimensioni errato

because I did not specified timevar. Well I did not, because I did not know what to put in it. Moreover, I am not sure that specifying idvar = "INTERTOT" is enough.
I had a look at different sources on the web, such as the following and this.
I think I could be close, but I am not sure on how to proceed.
I would be very helpful if anyone could help me.
Marco
Here an excerpt of my dataset:
structure(list(QI = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), CSET = c(10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L), INTERTOT = c(111L, 111L, 111L, 111L, 111L,
111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L,
111L, 111L, 111L, 111L), NSCELTA = c(1L, 1L, 2L, 2L, 3L, 3L,
4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L), SCELTAEFF2 = c(0L,
1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L,
1L, 1L, 0L), MARCA = c(4L, 1L, 1L, 2L, 1L, 4L, 4L, 2L, 2L, 3L,
1L, 2L, 3L, 1L, 2L, 3L, 2L, 4L, 3L, 1L), EV = c(1L, 0L, 1L, 0L,
1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L
), PREZZO = c(25000L, 30000L, 25000L, 20000L, 30000L, 25000L,
20000L, 15000L, 25000L, 15000L, 30000L, 20000L, 20000L, 25000L,
35000L, 30000L, 20000L, 15000L, 35000L, 20000L), AUTONOMIA = c(150L,
1200L, 150L, 800L, 150L, 400L, 350L, 400L, 250L, 400L, 350L,
1200L, 150L, 800L, 350L, 800L, 250L, 1200L, 250L, 400L), AUTONOMIA_EV = c(150L,
0L, 150L, 0L, 150L, 0L, 350L, 0L, 250L, 0L, 350L, 0L, 150L, 0L,
350L, 0L, 250L, 0L, 250L, 0L), AUTONOMIA_ICEV = c(0L, 1200L,
0L, 800L, 0L, 400L, 0L, 400L, 0L, 400L, 0L, 1200L, 0L, 800L,
0L, 800L, 0L, 1200L, 0L, 400L)), row.names = c(NA, 20L), class = "data.frame")

A: I can't see the data as example you posted but, if I've understood well, here what you need, all in base R. In case, it can be modified:
# add the timevar you need for reshape:
dats$timev <- with(dats, ave(rep(1, nrow(dats)),  CHOICE_SET, FUN = seq_along))

# now you can reshape it:
dats_w <- reshape(dats, idvar = " CHOICE_SET", timevar = "timev", direction = "wide")

# choose the column you need
dats_w <- dats_w[,c(2,1,3,4,10,6,12,7,13)]

# last add the correct column names
   colnames(dats_w) <- c('INTERVIEW','CHOICE_SET','CHOICE','BRAND_EV','BRAND_ICEV','PRICE_EV','PRICE_ICEV','RANGE_EV',' RANGE_ICEV')

dats_w
   INTERVIEW CHOICE_SET CHOICE BRAND_EV BRAND_ICEV PRICE_EV PRICE_ICEV RANGE_EV  RANGE_ICEV
1        111          1      0        4          1    25000      30000      150        1200
3        111          2      1        1          2    25000      20000      150         800
5        111          3      1        1          4    30000      25000      150         400
7        111          4      0        4          2    20000      15000      350         400
9        111          5      1        2          3    25000      15000      250         400
11       111          6      1        1          2    30000      20000      350        1200
13       111          7      0        3          1    20000      25000      150         800
15       111          8      1        2          3    35000      30000      350         800
17       111          9      0        2          4    20000      15000      250        1200
19       111         10      1        3          1    35000      20000      250         400

With data:
dats <- structure(list(INTERVIEW = c(111L, 111L, 111L, 111L, 111L, 111L,
111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L, 111L,
111L, 111L, 111L), CHOICE_SET = c(1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L), CHOICE = c(0L,
1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L,
1L, 1L, 0L), BRAND = c(4L, 1L, 1L, 2L, 1L, 4L, 4L, 2L, 2L, 3L,
1L, 2L, 3L, 1L, 2L, 3L, 2L, 4L, 3L, 1L), EV_DUMMY = c(1L, 0L,
1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L,
1L, 0L), PRICE = c(25000L, 30000L, 25000L, 20000L, 30000L, 25000L,
20000L, 15000L, 25000L, 15000L, 30000L, 20000L, 20000L, 25000L,
35000L, 30000L, 20000L, 15000L, 35000L, 20000L), RANGE = c(150L,
1200L, 150L, 800L, 150L, 400L, 350L, 400L, 250L, 400L, 350L,
1200L, 150L, 800L, 350L, 800L, 250L, 1200L, 250L, 400L), timev = c(1,
2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2)), row.names = c(NA,
20L), class = "data.frame")


text:
Q: python sort over list by value Json sctructure I'm trying to get an output of a json file sorted by the following value "created_at"
there a bit mass regarding all my tries in the code, I wasn't able to sort it.
If there is better solutions to resolve this task you more then welcome to share.
Your help and patience is much appreciated
import json
from datetime import datetime
import operator
from collections import OrderedDict
from operator import itemgetter

null = None
true = True
false = False

text = {

    "Recipes":
    [
        {
            "id": 2090210,
            "user_id": 198555,
            "parent_id": null,
            "folder_id": 792876,
            "version_no": 17,
            "last_run_at": "2022-01-13T03:52:31.559455-08:00",
            "created_at": "2022-01-13T00:53:48.433452-08:00",
            "updated_at": "2022-01-13T03:52:27.798961-08:00",
            "job_succeeded_count": 7,
            "job_failed_count": 0,
            "lifetime_task_count": 209,
            "active": true
        },
        {
            "id": 2072031,
            "user_id": 198555,
            "parent_id": null,
            "folder_id": 283206,
            "version_no": 98,
            "last_run_at": "2022-01-04T05:14:41.485273-08:00",
            "created_at": "2022-01-14T05:12:56.677338-08:00",
            "updated_at": "2022-01-12T10:08:49.199488-08:00",
            "job_succeeded_count": 1,
            "job_failed_count": 0,
            "lifetime_task_count": 227,
            "active": false
        },
    ]
}

#info = json.dump(text, sort_keys=False)
sorted_values = sorted(text.values())
#text.sort(key=lambda s: s['created_at'])
sorted_d = {r: text[r] for r in sorted(text, key=text.get('created_at'), reverse=True)}
#print(sorted_d)
ss = sorted(text.values()) #no recips
#print(ss)
newlist = sorted(ss, key=itemgetter(1))
print(newlist)

A: No need to write extra lines just write this one line and it will sort you data
sorted_text = { "Recipes" :  sorted(text['Recipes'], key=itemgetter('created_at'))}
print(sorted_text)


text:
Q: difference between vector and vector Question about threads in C++
What are the advantages and disadvantages of using  one or the other ?
vector<thread> tvec;
...

or
vector<thread*> tvec; // or vector<shared_ptr<thread>> tvec;
...

A: std::thread is a tiny class containing mostly just the thread ID or handle. It is also movable, and so is a good candidate to be stored in a vector by-value.
So it's easiest and most readable to store them by-value, as it vector<thread> tvec;.
In addition, the form vector<T*> carries non-owning semantics, and so is probably something different from what you meant to have.

A: Let's call them value and pointer versions:

*

*The value version will have better cache locality for sequential access. If thread is std::thread it would be moveable, otherwise copy constructing is more expensive.

*The pointer version implies that you always chase a pointer to access it. Page faults are expensive. You can set an entry to a nullptr if an element is optional/missing.  If you use a straight pointer like this you might need to manage resources manually.  This is error prune and leads to resource leaks (in this case threads and memory).

A:
difference between vector<thread> and vector<thread *>

I assume that by vector, you mean std::vector and by thread, you mean std::thread. Correct me if I assumed wrongly.
First is a vector that contain thread objects. The other is a vector that contains thread* objects which are pointers to thread.

What are the advantages and disadvantages of using one or the other ?

Advantage of vector<thread> is that you get thread objects.
Disadvantage of vector<thread> is that you don't get thread* objects.
Advantage of vector<thread *> is that you get thread* objects.
Disadvantage of vector<thread *> is that you don't get thread objects.

vector<thread> is useful when you want to start multiple threads for some parallel programming.
I haven't yet encountered a use case where vector<thread *> would be useful.


text:
Q: Complex Analysis analytic function problem Suppose that $f$ ang $g$ are two analytic functions on the set $\Bbb C$ of all complex numbers with $f(1/n) = g(1/n)$ for $n= 1,2,3,\ldots$, then show that $f(z) = g(z)$ for all $z\in\Bbb C$.

A: Hint: $f(z)-g(z)=0$ on a set of points with a limit point.


text:
Q: SteamedResponse not working in lumen on other server I am using Lumen for a set of APIs.
using streamedresponse built in library of symphony.
use Symfony\Component\HttpFoundation\StreamedResponse;

    protected function getFileResponseHeaders($filename)
{
    return [
        'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0',
        'Content-type'        => 'text/csv; =utf-8',
        'charset'        => 'utf-8',
        'Content-Disposition' => 'attachment; filename='.$filename,
        'Expires'             => '0',
        'Pragma'              => 'public'
    ];
}
//'Content-Type: '
protected function streamFile($callback, $headers)
{
    $response = new StreamedResponse($callback, 200, $headers);
    $response->send();
}

I am using this approach in a scenario where I want to stream data in command line with chunks of 2000. I have bulk of data upto 7 millions rows to stream.
This whole thing is working completly fine on a server with following specs.

*

*php 7.3.27

*centos fedora 7

*apache 2.4.41

*mysql8

But I have other servers where this stream only list down first batch. Specs of other servers are identical as following:

*

*php 7.4

*centos 8

*apache 2.4.47

*mysql8

I want guidance to run this stream on all the servers. I have compared php.ini and every other thing that I can think of.
Thanks in advance.

A: PHP ZTS was missing from all the servers except the one where the streamed response was working.
Adding php zts on the server fixed the problem for me finally.


text:
Q: Get the last file name in a S3 folder? I have a lot of files in the s3 bucket. The folder/file names are in the following format.
s3://bucket/folder/year=1990/1990-01-01.csv
......
s3://bucket/folder/year=2020/2021-01-23.csv

How to use Python to get the last file name? In the above example, it is 2021-01-23.csv.

A: You can check this alternative which uses filter:
import boto3

s3r = boto3.resource('s3')

all_files = list(s3r.Bucket('bucket').objects.filter(Prefix='folder/').all())

print(all_files[-1])

It does not do semantic check based on the dates in your files to find the last one. But the example could be extended to do it as well.

A: import glob
import os

# get all csv files recursively inside the folder s3://bucket/folder/
files = glob.glob('s3://bucket/folder/' + '/**/*.csv', recursive=True)
files.sort() # sort them by name
last_file = files[-1] # get the last element
last_file_name = os.path.basename(last_file) # extract filename from filepath


text:
Q: Find only current jQueryUI dialog's contents in dialog open handler I have an application that can have multiple jQueryUI dialogs open at the same time.
My problem is that I can't figure out how to find only the current dialogs elements in the open handler of the dialog.
I have tried $(this), ui, ui.dialog and a few other things but without result.
$("

" + text + "

")
    .dialog({
        closeOnEscape: false,
        open: function (event, ui) {
            /*
               What can I use to filter the two selectors below
               so that they only affect the current dialogs contents?
            */
            $(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
            $('.ui-dialog-buttonpane', ui.dialog | ui).find('button').each(function (id, el) {
                /* This cycles through all buttons on all dialogs */
                debugger;
            });
        },
        buttons: {
            "Button 1": function () { doStuff; },
            "Button 2": function () { doStuff; },
            "Button 3": function () { doStuff; }
        }
    });

A: The solution for me was to refer to the event targets parent element.
e.g.  event.target.parentElement

$("

" + text + "

")
    .dialog({
        closeOnEscape: false,
        open: function (event, ui) {
            /* Hide the close button of the dialog your are loading */
            $(".ui-dialog-titlebar-close", event.target.parentElement).hide();

            /* Cycle through only the buttons belonging to the current dialog */
            $('.ui-dialog-buttonpane', event.target.parentElement).find('button').each(function (id, el) {
                debugger;
            });
        },
        buttons: {
            "Button 1": function () { doStuff; },
            "Button 2": function () { doStuff; },
            "Button 3": function () { doStuff; }
        }
    });


text:
Q: Change from baseline mixed effects models I am trying to analyze a study that has three treatment groups and the measurements are conducted on the same subjects over time.  The first time point is a baseline measurement and then there are 7 additional time points.  I have taken the primary data and have fit a mixed effects model: resp ~ baseline + treat * time + (time|subject) using the syntax for lmer.  Once I have the model fit I used the package lsmeans to obtain model estimates with confidence limits at the different time points.
The question here is whether with this model I am able to obtain estimates for changes from baseline.  Alternatively, I could subtract the baseline values for each subject and refit the model on the change from baseline data, rather than the original data.  What is more appropriate?
Related to the previous question, if the data fitted are the primary data rather than the change from baseline, is there a way to get from lsmeans the estimates for change from baseline values with the corresponding 95% confidence limits?
Please advise.

A: If you fit the model with offset(baseline) instead of just baseline, then the lsmeans will indeed be in terms of changes from baseline. This is due to the fact that offset in essence puts in a covariate with its regression coefficient constrained to be 1 -- hence it is equivalent to subtracting it from the response.
But with baseline as an ordinary covariate, I am having trouble understanding what you would even mean by "change from baseline" in such a model. You could test the hypothesis $H_0: \beta_1=1$ versus $H_1: \beta_1\ne1$, where $\beta_1$ is the coefficient for baseline; and if rejected, it would suggest that change from baseline is not all that meaningful when explaining the factor effects.
I suppose another approach would be to add the argument
lsmeans( ..., cov.reduce = baseline ~ treat)

which would put in separate baseline predictions for each treatment; the results would then be predictions using predicted baseline values as a moderating variable. The LS means will be (means of) predictions from the model at those baseline values. However if you subtract 1 from $\hat\beta_1$, you obtain changes from those baseline values, because
$$ \beta_0 + (\beta_1 - 1)x + \mbox{factor effects} = (\beta_0 + \beta_1 x + \mbox{factor effects}) - x $$
where $x$ is the baseline value. You can implement this by devilish hacking, something like this:
lsm = lsmeans(...)   # with or without that cov.reduce thing
lsm@bhat[2] = lsm@bhat[2] - 1
summary(lsm)

This assumes that baseline is the first term in the model (second to the intercept). The statistical output is still valid because the variance of $\hat\beta_1-1$ is the same as the variance of $\hat\beta_1$, as is also true of the covariances of this with other regression coefficients.
But, as I said, this may or may not be what you mean by change from baseline when baseline is used as a covariate.