text:
Q: FEventTypeValue running before FEventTypeChildAdded I'm looking at the Firechat demo project, and they use a technique whereas they're using FEventTypeChildAdded as well as FEventTypeValue as the latter will fire just after FEventTypeChildAdded. This is done in order to prevent a "spam" of FEventTypeChildAdded callbacks to avoid a UI lockup. However, I implemented the same technique in my app, but FEventTypeValue is actually called before FEventTypeChildAdded, resulting in the BOOL changing to NO and locking the UI.
From the demo project:
// This allows us to check if these were messages already stored on the server
// when we booted up (YES) or if they are new messages since we've started the app.
// This is so that we can batch together the initial messages' reloadData for a perf gain.
__block BOOL initialAdds = YES;

[self.firebase observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
    // Add the chat message to the array.
    if (newMessagesOnTop) {
        [self.chat insertObject:snapshot.value atIndex:0];
    } else {
        [self.chat addObject:snapshot.value];
    }

    // Reload the table view so the new message will show up.
    if (!initialAdds) {
        [self.tableView reloadData];
    }
}];

// Value event fires right after we get the events already stored in the Firebase repo.
// We've gotten the initial messages stored on the server, and we want to run reloadData on the batch.
// Also set initialAdds=NO so that we'll reload after each additional childAdded event.
[self.firebase observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
    // Reload the table view so that the intial messages show up
    [self.tableView reloadData];
    initialAdds = NO;
}];


text:
Q: Quick sort not working as intended with linked list Preface:
I do not care about the viability of my particular quick sort algorithm. That is not what the question is about. I am curious as to why the program I have already written behaves the way it does, not about why I should use the STL or whatever. This is for learning purposes. (for instance, I'm aware picking pivot as the head is not the best case -- that's not what I'm asking though)
Question:
I have a linked list composed of Node*s. I've written a quick sort algorithm for it specifically. It works by taking a given linked list, and recursively splitting it into sublists based on a chosen pivot. The pivot is always the head (front) of the list, and the sublists left and right are lists that contain values less than and greater than/equal to the pivot, respectively. I've almost gotten it down, but I don't know how to properly add_link the pivots. In a previous iteration, I would just add_link the pivot to the right sublist always, but that caused an infinite loop, so I ended up skipping the pivots entirely when comparing values against it. The resulting list is sorted, but it is missing every value that was used for a pivot. How should I fix this?
Here is a minimal reproducible example:
#include <iostream>
struct Link {
    Link(int d=int(), Link* n=nullptr) {
        data = d;
        next = n;
    }
    int         data;
    Link* next;
};

struct LinkList {
  Link* sentinel;
  size_t      size;

 LinkList(Link* h=new Link, size_t s=0) {
    size = s;
    sentinel = h;
  }

  ~LinkList() {
    Link* current = sentinel;
    while (current != 0) {
      Link* next = current->next;
      delete current;
      current = next;
    }
    sentinel = 0;
  }
};

// Prototypes

Link* sort_q(Link* sentinel);
void  divide(Link* sentinel, Link* cmp, Link*& lower, Link*& greater);
Link* concatenate(Link* lower, Link* greater);

// helpful function calls quick sort
void sort(LinkList& l) {
    l.sentinel = sort_q(l.sentinel);
}

// returns false if there sentinel = null; true if add_link was successful
bool add_link(Link* sentinel, Link* add_link, Link*& end) {
    if (sentinel == nullptr) {
        return false;
    }
    Link* curr = sentinel;
    for (; curr->next; curr = curr->next) {}
    curr->next = add_link;
    end = curr->next;
    return true;
}

Link* sort_q(Link* sentinel) {

    Link* lower = nullptr;
    Link* greater = nullptr;
    Link* cmp = sentinel;

  // base case LinkList = null or sentinel->null
    if (sentinel == nullptr || sentinel->next == nullptr) {
        return sentinel;
    }

    divide(sentinel, cmp, lower, greater);

    lower = sort_q(lower);

    greater = sort_q(greater);

    return concatenate(lower, greater);
}

void divide(Link* sentinel, Link* cmp, Link*& lower, Link*& greater) {
    lower = new Link, greater = new Link;
  // lend is pointer to end of lower subLinkList
  // rend is pointer to end of greater subLinkList
    Link* lend = nullptr, * rend = nullptr;

  // loop through LinkList until end
    while (sentinel != nullptr) {
        if (sentinel == cmp) {
            sentinel = sentinel->next; continue;
        }
        if (sentinel->data < cmp->data) {
            // break current link
            Link* tmp = sentinel;
            sentinel = sentinel->next;
            tmp->next = nullptr;
      // if subLinkList is not empty, add_link current Link to subLinkList and update end pointer
            if (add_link(lend, tmp, lend))
                continue;
        // otherwise, "add_link" current Link to empty subLinkList and update end pointer manually
            lower->next = tmp;
            lend = lower->next;
        }
        else {
            // break current link
            Link* tmp = sentinel;
            sentinel = sentinel->next;
            tmp->next = nullptr;
            // if subLinkList is not empty, add_link current Link to subLinkList and update end pointer
            if (add_link(rend, tmp, rend))
                continue;
            // otherwise, "add_link" current Link to empty subLinkList and update end pointer manually
            greater->next = tmp;
            rend = greater->next;
        }
    }
    // remove dummy Link(s)
    if (lower->next)
        lower = lower->next;
    else
        lower = cmp;
    if (greater->next)
        greater = greater->next;
    else
        greater = cmp;
    // unlink cmp
    cmp->next = nullptr;
}

// connected subLinkLists
Link* concatenate(Link* lower, Link* greater) {
    Link* sentinel;

    sentinel = lower;

    while (lower->next != nullptr) {
        lower = lower->next;
    }

    lower->next = greater;

    return sentinel;
}

void print(LinkList &l) {
  for (Link* n = l.sentinel; n != NULL; n = n->next) {
    std::cout << n->data << '\n';
  }
}

int main() {
  // set up linked LinkList 8->4->5->11->7->5->3->9->null
  Link* sentinel = new Link(8 , new Link(4, new Link(5, new Link(11, new Link(7, new Link(5, new Link(3, new Link(9))))))));
  LinkList l(sentinel,5);

  sort(l);
  print(l);

  return 0;
}

The output I want to have is
3
4 // pivot missing from output
5
5
7
8 // pivot missing from output
9
11

but it outputs
3
5
5
7
9
11

Edit #1:
I have tried adding the pivot between concatenations, but that does not work either. It produces different results, but not quite the same. Modifying sort_q() and partition() like so:
Link* qsort(Link* sentinel) {
   // ... other stuff before modification
   return concatenate(lower, cmp); // changed greater argument to pass cmp which is now cmp->next = greater once finishing partition()
}

void partition(Link* sentinel, Link*& cmp, Link*& lower, Link*& greater) {
    // .. other stuff before modifications

    // remove dummy Link
    if (lower->next)
        lower = lower->next;

    if (greater->next)
        greater = greater->next;

    cmp->next = greater; // cmp points to greater (greater) sublist
}

The output becomes
3
4
5
7
0
8
11
0

A: You have assumptions that you can get both a lower and a greater list, and you already make sure you have at least 2 items in the list before you call divide, so that is good.
You just need to handle all the cases at the end of divide. Make sure cmp ends up in one of the two lists. Almost like you had before, but you need to handle the case where both lower and greater lists are non-empty.
// remove dummy node(s)
    cmp->next = nullPtr;
    if (lower->next && greater->next) {
        // we have two lists. put cmp on greater
        lower = lower->next;
        cmp->next = greater->next;
        greater = cmp;
    }
    else if (lower->next) {
        // only a lower list, use cmp on greater
        lower = lower->next;
        greater = cmp;
    }
    else if (greater->next) {
        // only a greater list, use cmp as lower.
        greater = greater->next;
        lower = cmp;
    }

seeing the above, handling all 3 cases, it can be simplified to this:
// remove dummy node(s)
    if (lower->next) {
        // we have lower node, so put cmp on greater
        lower = lower->next;
        cmp->next = greater->next;
        greater = cmp;
    }
    else if (greater->next) {
        // only a greater list, use cmp as lower.
        greater = greater->next;
        lower = cmp;
        cmp->next = nullPtr;
    }

then use concatenate(lower,greater) afterwards. Although it could be optimized to have divide concatenate the lists and just return the sentinel, but that's a bit more of a rewrite.
EDIT: putting it all together to eliminate your memory leak, it should be like this (note, I have not compiled or tested)
void divide(Node* sentinel, Node* cmp, Node*& lower, Node*& greater) {
    lower = nullptr, greater = nullptr;
  // lend is pointer to end of lower sublist
  // rend is pointer to end of greater sublist
    Node* lend = nullptr, * rend = nullptr;

  // loop through list until end
    while (sentinel != nullptr) {
        if (sentinel == cmp) {
            sentinel = sentinel->next; continue;
        }
        if (sentinel->data < cmp->data) {
            // break current link
            Node* tmp = sentinel;
            sentinel = sentinel->next;
            tmp->next = nullptr;
      // if sublist is not empty, append current node to sublist and update end pointer
            if (append(lend, tmp, lend))
                continue;
        // otherwise, "append" current node to empty sublist and update end pointer manually
            lend = lower = tmp;
        }
        else {
            // break current link
            Node* tmp = sentinel;
            sentinel = sentinel->next;
            tmp->next = nullptr;
            // if sublist is not empty, append current node to sublist and update end pointer
            if (append(rend, tmp, rend))
                continue;
            // otherwise, "append" current node to empty sublist and update end pointer manually
            rend = greater = tmp;
        }
    }
    // insert cmp node
    if (lower) {
        // we have lower node, so put cmp on greater
        cmp->next = greater;
        greater = cmp;
    }
    else if (greater) {
        // only a greater list, use cmp as lower.
        lower = cmp;
        cmp->next = nullptr;
    }
}

A: The main problem I see is that you sometimes, but not always, add the pivot to the "left" or "right" list in partition(). This inconsistency likely violates the desired functionality of partition(). However, this functionality is not documented. So I'll revise my assessment to say the main problem is that you have not documented your functions. The bigger your project, the more likely you are to encounter problems because of the lack of documentation.
Document!
I would expect to see partition() documented to say that it partitions the list into three pieces: left, right, and pivot.
/// Partitions the list starting at `head` into three pieces. Data less than
/// the given partition's data is put in the `left` list, while the remaining
/// data (except `*partition` itself) is put in the `right` list. The third
/// piece consists of `*partition`, which is assumed to be in the given list.
void partition(Node* head, Node* pivot, Node*& left, Node*& right) {

Another option might be to immediately put the pivot in one of these lists. However, these lists are going to be sorted immediately after the call to partition(), and there is no need to include *partition in that sort. Sort left, sort right, then concatenate left, partition, and right. In addition to being faster because there are fewer nodes to sort in the next recursive call, keeping the partition node out of your lists will guarantee that your lists get shorter with each recursive call.
It's your call, though, since you are the designer. The important thing is to decide what functionality you want, document it, and follow that decision.
Enforce consistency!
Once you have specified functionality, it is easier to verify that your code respects whatever design decisions you have made. Your sort_q() function fails to account for the above specification in that it does not add the partition to the list. There is probably a simpler way to do this than the below, but the below serves the purpose with little re-writing of your code. (This is the end of sort_q().)
    // ** Return left -> pivot -> right, not just left -> right **
    return concatenate(left, concatenate(pivot, right));
}

In addition, your partition() function violates this specification by (sometimes) adding the partition node to one of your lists. Stop doing that. Set your links to null instead.
    // remove dummy node(s)
    if (left->next)
        left = left->next;
    else
        left = nullptr;   // <-- null, not pivot
    if (right->next)
        right = right->next;
    else
        right = nullptr;   // <-- null, not pivot

Hmm... I had avoided re-writing your code earlier, but this particular structure strikes me as needlessly complicated. If a certain pointer is not null, assign it to something. Otherwise (when that pointer is null), assign null instead of the pointer (which is null, so same thing). That is rather wordy. Just assign the pointer.
    // remove dummy node(s)
    left = left->next;
    right = right->next;
    // *** Memory leak, as we removed the nodes without deleting them ***

Oh that memory leak is a pain. Especially since you don't really need the dummy nodes. But that digresses into a separate question, so for now I'll just note that your code is very close to working if you had initialized left and right to nullptr. (Your hint is that if left is initialized to nullptr then, at the moment append() is called, lend is null if and only if left is null.)
One final piece: if you've followed all this so far, you probably ran into a segmentation fault at some point. You are missing a check in concatenate() (maybe the reason you started using dummy nodes?)
// connected sublists
Node* concatenate(Node* left, Node* right) {
    if ( left == nullptr )   // <-- Add this check
        return right;        // <-- It is very easy to concatenate to nothing.
    Node* head = left;

That should address the immediate question. There are other places to improve, though, so keep working at it. (There are other parts of your code that I would call "needlessly complicated", albeit less severely – and less obviously – than what that if statement became.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which .Net framework should my .Net Core library target? I am enjoying the "multi-target" feature of .xproj in Visual Studio 2015 which make it really easy to target multiple .Net frameworks with the same C# project. I am currently targeting .Net 4.5.2, 4.6, 4.6.1, 4.6.2, .Net Standard 1.3 and .Net Standard 1.6 and I am packaging all the DLLs in a nuget package.
Do you think this is overkill? Should I target fewer frameworks? More?
By the way, I know xproj is eventually going away in favor of .csproj, but that's what I'm using for the time being.

A: If you don't have any conditional compilation yet, then you should leave only .NET Framework 4.5.2 and .NET Standard 1.3.
The reason is simple. If the package works for .NET Framework 4.5.2, it works for all .NET Framework with a bigger version. No need to target them separately.
The same applies to .NET Standard. If the package targets .NET Standard 1.3, then it can work fine for .NET Standard 1.4/1.5/1.6/2.0.
You do have to target both because .NET Framework 4.5.2 does not implement .NET Standard 1.3. Probably you don't want to target .NET Standard 1.2, as it is too limited.


text:
Q: DataGridView not showing correct cultureinfo I have a fairly standard BindingSource / DataGridView combination. The bindingSource has a decimal type property that must be displayed in the DataGridView as a currency. For a test I want to see what it looks like if I use a culture info that uses € as currency format instead of £
My problem is, that although I programmatically change the CurrentUICulture of the current thread (My application has only one thread), my DataGridView still shows £.
The designer created for me the following code snippets:
this.columnPriceValue = new Forms.DataGridViewTextBoxColumn();
this.columnPriceValue.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
this.columnPriceValue.DataPropertyName = "Value";
dataGridViewCellStyle2.Format = "C4";
...

In the constructor of my main form I set the currentUICulture to the Dutch Culture according to a stackoverflow answer How to change CurrentCulture at runtime?
System.Threading.Thread.CurrentThread.CurrentUICulture =
    CultureInfo.GetCultureInfo(0x0013);

Because the GBP sign is still shown I checked the currencySymbol just before adding the data to the bindingsource:
public void ShowPrices(IEnumerable<Price> prices)
{
    string txt = System.Threading.Thread.CurrentThread.CurrentUICulture.NumberFormat.CurrencySymbol;
    Debug.WriteLine(txt);
    this.bindingSource1.DataSource = prices;
    ...

The debugger output window shows that € is still the Currency Symbol, , yet the DataGridview still shows £.
What to do to let it show the euro-sign?

A: Do set Thread.CurrentThread.CurrentCulture, not Thread.CurrentThread.CurrentUICulture.
Although the names do seem to imply something different, CurrentCulture is actually used to decide what formats to use to display values.
CurrentUICulture only has an effect when you use resource dlls and is then only used to decide which resource dll is loaded.
See also What is the difference between CurrentCulture and CurrentUICulture properties of CultureInfo in .NET?

A: Edit:
NineBerry beat me to it as I was editing, but as stated: Just use the following instead:
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(0x0013);

Previous Answer:
Try setting the CultureInfo for the specific column using the FormatProvider:
this.columnPriceValue.DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo(0x0013);

Or if dataGridViewCellStyle2 is the style for the Price column's cell template:
dataGridViewCellStyle2.FormatProvider = CultureInfo.GetCultureInfo(0x0013);

Or more generically, after setting the CurrentUICulture:
dataGridViewCellStyle2.FormatProvider = Thread.CurrentThread.CurrentUICulture;


text:
Q: PHPSpreadsheet & CodeIgniter -> Message: syntax error, unexpected 'use' (T_USE) I'm having trouble creating a test file using the PHPSpreadsheet library in CodeIgniter. When I run the code below I get the error message:

An uncaught Exception was encountered Type: ParseError
Message: syntax error, unexpected 'use' (T_USE)
Filename: C:\wamp64\www\din-din\application\controllers\home.php
Line Number: 17
Backtrace:
File: C:\wamp64\www\din-din\index.php Line: 315 Function: require_once

Could you explain what happens?
The test was performed with PHP 5.6.35 and 7.2.4, using WampServer64 3.1.3 and CodeIgniter in version 3.1.9! The PHPSpreadsheet library was installed via composer according to the documentation in https://phpspreadsheet.readthedocs.io/en/develop/
Thank you!
CODE:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
    }

    public function index()
    {

        require 'vendor/autoload.php';

        use PhpOffice\PhpSpreadsheet\Spreadsheet;
        use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'Hello World !');

        $writer = new Xlsx($spreadsheet);
        $writer->save('hello_world.xlsx');
    }

}

A: use, as a means to import or alias a namespace, cannot be made inside function scope. To quote the docs:

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.

The convention is to place use as the very first instructions in your file, before anything else: constant declaration, function definition, etc. Your code would be re-written as:
<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {
    // ...

You could put the use after the defined(), or after the class (ie at the bottom of the file), but that would be quite unusual.
Two notes:

*

*There is a use operator that imports variables into Closure, like so function () use ($var) { ... }. The same keyword, but in that lexical context it's not related to namespacing.

*If you're using a recent version of PHP, you can use namespace grouping to save yourself some typing: use PHPOffice\PhpSpreadsheet\{Spreadsheet, Writer\Xlsx}


text:
Q: How to handle large integers in Rails 3 and postgres Im using rails 3.2.3, ruby 1.9.3, and postgres 8.4.12 (on RHEL 6.3). I was hoping to store IP addresses as integers in a database, but get the following error when trying to save the record from the controller:
  def create
    @network = Network.new(params[:network])

    @network.address_int = IPAddr.new(@network.address_str).to_i
    @network.netmask_int = IPAddr.new(@network.netmask_str).to_i

    respond_to do |format|
      if @network.save
        format.html { redirect_to @network, notice: 'Network was successfully created.' }
        format.json { render json: @network, status: :created, location: @network }
      else
        format.html { render action: "new" }
        format.json { render json: @network.errors, status: :unprocessable_entity }
      end
    end
  end

I get the following error
PG::Error: ERROR:  value "4294967040" is out of range for type integer

My migration defines this column as a 8 byte integer:
class CreateNetworks < ActiveRecord::Migration
  def change
    create_table :networks do |t|
      t.integer :vlan
      t.integer :address_int, :limit => 8
      t.integer :netmask_int, :limit => 8
      t.string :address_str
      t.string :netmask_str
      t.string :desc

      t.timestamps
    end
  end
end

But I have been able to store this large integer at the rails console:
1.9.3p125 :001 > n=Network.new
 => #<Network id: nil, vlan: nil, address_int: nil, address_str: nil, netmask_int: nil, netmask_str: nil, desc: nil, created_at: nil, updated_at: nil>
1.9.3p125 :002 > n.address_int=4294967040
 => 4294967040
1.9.3p125 :003 > n
 => #<Network id: nil, vlan: nil, address_int: 4294967040, address_str: nil, netmask_int: nil, netmask_str: nil, desc: nil, created_at: nil, updated_at: nil>
1.9.3p125 :004 > n.save
(0.2ms)  BEGIN
  SQL (5.0ms)  INSERT INTO "networks" ("address_int", "address_str", "created_at", "desc", "netmask_int", "netmask_str", "updated_at", "vlan") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"  [["address_int", 4294967040], ["address_str", nil], ["created_at", Tue, 10 Jul 2012 15:09:37 UTC +00:00], ["desc", nil], ["netmask_int", nil], ["netmask_str", nil], ["updated_at", Tue, 10 Jul 2012 15:09:37 UTC +00:00], ["vlan", nil]]
(0.9ms)  COMMIT
 => true

So, should this bigint data type be defined somewhere else too? Thanks in advance.

A: If you upgrade to PG 9.1 you can use their native IP address/Subnet/MAC address types. You can even use them in your migrations with the postgres_ext gem. This should automatically handle IP address of any type without having to cast them as BIGINT or STRING and allow some awesome tricks such as "SELECT FROM * IN SAME SUBNET"


text:
Q: How to add page numbers to APA citations in ConTeXt? I have created a basic document with APA citations using the course code for creating bibliographies in MK IV in APA format, as found at the ConTeXt garden:
\setupbibtex[database={sample},sort=author]
\setuppublications[alternative=apa]
\starttext
    \placepublications[criterium=text]
\stoptext

To place citations on the page, I am using \cite[articleID]. As APA format is selected, this appears as (Author, Year) in the text, as expected. In some situations, as is explained in the APA Formatting and Style Guide, I need to include page number information. The resulting format should look like this example, also from the guide:
She stated, "Students often had difficulty using APA style" (Jones, 1998, p. 199), but she did not offer an explanation as to why.

How can I add this page number information to my APA citations in ConTeXt?

A: Use \cite[extras={, p.~199}][cite-key]


text:
Q: visualizar pdf de aplicacion Angular 10 en Internet Explorer 11 Hola amigos tengo desarrollada mi aplicacion en angular 10 donde tego un modulo para visualizar pdf.
el codigo es el siguiente:
<ngx-extended-pdf-viewer [base64Src]="pdfSrc" useBrowserLocale="true" height="500px"></ngx-extended-pdf-viewer>

la version de esta libreria es la 6, aunque eh intentado con la 5 y la 7 y con ninguna me funciona.
cabe recalcar que para chrome y Edge si mecarga de manera correcta el pdf pero internet explorer me carga asi:


text:
Q: Change Tabindex in JQGrid My jQGrid keeps a tabindex with 1 value! I wanna change it to -1 or remove it.
How can I do it?
thanks buddies.
Here is the source of my grid, when jQGrid renders it:

A: try this:
$('#list_allprices').attr('tabindex','-1');

A: Late but sure, here is my answer:
I couldn't find an option to specifically set the tabIndex through the jqgrid element but I was able to iterate over all the elements I was interested about to set them to ignore the tab (by setting the tabindex = -1).
I did the following:
function ignoreTabs(){
        $('.HeaderButton').each(function(i, obj) {
            obj.tabIndex = -1;
        });
}

In the example above I look for all the elments with class HeaderButton and set the value tabIndex = -1. For your example Amin Sh, you should replace '.HeaderButton' by '#list_allprices'.
Of course call the function ignoreTabs when your page is loading.
Hope it helps.


text:
Q: Twilio Video + Parse im building an App with Twilio-Video  (https://www.twilio.com/docs/api/video). I did  usermanagement-Database with parse but i have problem with access token.
When my user sign up in my app i want to assign twilio access token to their username - the question is how can i do that? or is it with parse not possible? do i need extra backend server for my app  ? Im little bit confused.
https://www.twilio.com/docs/api/video/guide/identity
Thanks!

A: Twilio developer evangelist here.
As you've mentioned you're using the Parse server on Heroku, I believe I can help!
You don't actually want to create an access token for Twilio Video when a users signs up to your application. Tokens are configurable and can last up to 24 hours. So you want to generate tokens when a user needs one.
Parse server is a Node.js based server and can be embedded within an Express server. Once you do that you can then install the latest Twilio npm module and use it to generate tokens for your users from an Express endpoint.
The code required to generate a token looks a bit like this:
var AccessToken = require('twilio').AccessToken;
var IpMessagingGrant = AccessToken.IpMessagingGrant;

// Used when generating any kind of tokens
var twilioAccountSid = 'ACxxxxxxxxxx';
var twilioApiKey = 'SKxxxxxxxxxx';
var twilioApiSecret = 'xxxxxxxxxxxx';

// Used specifically for creating IP Messaging tokens
var serviceSid = 'ISxxxxxxxxxxxxx';
var appName = 'HipFlowSlackDockRC';
var identity = 'user@example.com';
var deviceId = 'someiosdeviceid';
var endpointId = appName + ':' + identity + ':' + deviceId;

// Create a "grant" which enables a client to use IPM as a given user,
// on a given device
var ipmGrant = new IpMessagingGrant({
    serviceSid: serviceSid,
    endpointId: endpointId
});

// Create an access token which we will sign and return to the client,
// containing the grant we just created
var token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret);
token.addGrant(ipmGrant);
token.identity = identity;

// Serialize the token to a JWT string
console.log(token.toJwt());
// For your app you want to return the token to the front end somehow.

For more information, check out the Twilio API reference for creating access tokens.


text:
Q: A question about the Paley-Wiener-Zygmund stochastic integral I am reading a book titled "An Introduction to Stochastic Differential Equations" written by Evans.
In Chapter 4, it introduces the Paley-Wiener-Zygmund stochastic integral as follows

Definition. Suppose $g: [0,T] \to \mathbb{R}$ is continuously differentiable, with $g(0) = g(T) = 0"$. We define
$$ \int_0^T g\,dW := -\int_0^T g'W\,dt, $$

Also, a lemma and its proof follow,

Lemma. We have $E\big( \int_0^T g \,dW \big) = 0$.

Proof. $E\big( \int_0^T g \,dW\big) = -E\big( \int_0^T g'W \,dt\big) = -\int_0^T g'E(W(t)) \,dt = 0$

Here I don't understand why the second equality holds. It seems that he uses Fubini's theorem. However, in order to do that, $W(t,\omega)$, which presumably Wiener Process, should be measurable in $\mathbb{R} \times X$, where $X$ is the probability space in which $W(t,\cdot)$ is defined for every $t $.
How can I justify this? Any help would be appreciated!

A: (Good catch!  It's a little surprising that Evans doesn't comments on this point.)
The joint measurability follows because each map $\omega\mapsto W(t,\omega)$ is measurable and $t\mapsto W(t,\omega)$ is continuous for each $\omega$. Using the continuity you can approximate $W$ as follows:
$$
W(t,\omega) =\lim_{n\to\infty}\sum_{k=0}^\infty 1_{[k/n,(k+1)/n)}(t)\cdot W(k/n,\omega).
$$
(This sum, for a fixed $t$, has only finitely many non-zero terms, so convergence of the series is not an issue.) Each term in the sum is jointly measurable in $(t,\omega)$, hence so it the sum , hence so is the pointwise limit.


text:
Q: Calculating customer's trips based on transactions dates Basic T-SQL user here. I'm having problems trying to complete a task and would appreciate some guidance. Apologies in advance for any errors as English is not my mother tongue.
I have a table with a lot of transactions, for the sake of simplicity let's say that I only have two columns: CUSTOMER_ID, which is my customer  and DATE which is the date of the transaction.
My customers make a lot of transactions while they're in town but then they can spend weeks,  months or even years before coming back and start making transactions again. I would like to somehow identify each one of those "Trips" and group the transactions involved, then I'd like to do thins like calculate trip duration, number of transactions, etc.
I'd like to consider a Trip as any new transaction occurring after an IDLE period of 10 days.
Let me try to better explain my request by using some simple example:
This is my transactions table:
+-------------+------------+
| CUSTOMER_ID |    DATE    |
+-------------+------------+
| JHON        | 01-01-2016 |
| JHON        | 01-02-2016 |
| PEDRO       | 01-02-2016 |
| JHON        | 01-05-2016 |
| MIKE        | 01-05-2016 |
| MIKE        | 01-10-2016 |
| JHON        | 01-07-2016 |
| …           | …          |
| JHON        | 02-15-2016 |
| JHON        | 02-18-2016 |
| MIKE        | 02-19-2016 |
| MIKE        | 02-19-2016 |
+-------------+------------+

So far I've made this query to enumerate the customer's visits:
SELECT
    CUSTOMER_ID,
    DATE,
    ROW_NUMBER() OVER(PARTITION BY CUSTOMER_ID ORDER BY DATE) as VISIT_NUM

FROM
    TRANSACTIONS
WHERE
    CUSTOMER_ID IN ('JHON','MIKE','PEDRO')

Running that query would give a result similar to this:
+-------------+------------+-----------+
| CUSTOMER_ID |    DATE    | VISIT_NUM |
+-------------+------------+-----------+
| JHON        | 01-01-2016 |         1 |
| JHON        | 01-02-2016 |         2 |
| JHON        | 01-07-2016 |         3 |
| JHON        | 02-15-2016 |         4 |
| JHON        | 02-18-2016 |         5 |
| MIKE        | 01-05-2016 |         1 |
| MIKE        | 01-10-2016 |         2 |
| MIKE        | 02-19-2016 |         3 |
| MIKE        | 02-19-2016 |         4 |
| PEDRO       | 01-02-2016 |         1 |
+-------------+------------+-----------+

Now comes the tricky part: I need somehow to create a query that (maybe using the above query as a previous step) show me the customer with they trip info, continuing with the example the ideal result would be like this:
+-------------+----------+---------------+-------------+---------------+--------------+
| CUSTOMER_ID | TRIP_NUM | TRIP_START_DT | TRIP_END_DT | TRIP_DURATION | TRANSACTIONS |
+-------------+----------+---------------+-------------+---------------+--------------+
| JHON        |        1 | 01-01-2016    | 01-07-2016  |             7 |            3 |
| JHON        |        2 | 02-15-2016    | 02-18-2016  |             3 |            2 |
| MIKE        |        1 | 01-05-2016    | 01-10-2016  |             5 |            2 |
| MIKE        |        2 | 02-19-2016    | 02-19-2016  |             1 |            2 |
| PEDRO       |        1 | 01-02-2016    | 01-02-2016  |             1 |            1 |
+-------------+----------+---------------+-------------+---------------+--------------+

As you can see, Mr. Jhon came 3 times during the month of January and came back again in February. As more than 10 days passed from his last transaction in January, I'd like to consider his new set of transactions as a new "trip" for him. Mike also had some activity in January, and came back in February too, in his second trip he made two transactions in the same day, I'd like to account that too. If a customer only came a single day and had some activity (as the case of Mr. Pedro) I'd also like to consider that single-day, single-transaction record as a trip record.
I would greatly appreciate any light on this, I honestly have no idea on how to proceed (I've been reading about cursors but it seems like dark magic at this point, cant figure out a way to implement them on this).
Apologies again for any grammatical errors and any possible omissions on my part. I'd further clarify anything if necessary.

A: Calculating trip duration is not standard for all employees in your example,so i have tweaked it to follow first customer id for all
DEMO HERE
 ;with cte
 as
 (select cid,datee,datepart(month,datee) as monthh,
  dense_rank () over (partition by cid order by datepart(month,datee)) as samemonth,
 count(0) over (partition by cid,datepart(month,datee) ) as cnt
 from #temp
)
,cte1 as
 (
select cid,max(samemonth) as tripnumber,min(datee) as startdate,max(datee) as enddate,
max(cnt) as numberoftrips
from  cte
group by cid,samemonth
)
select *,datediff(day,startdate,dateadd(day,1,enddate))as duration
from  cte1

Output:
cid   tripnumber startdate      enddate    numberoftransactions duration
JHON    1        2016-01-01    2016-01-07   3                    7
JHON    2        2016-02-15    2016-02-18   2                    4
MIKE    1        2016-01-05    2016-01-10   2                    6
MIKE    2        2016-02-19    2016-02-19   2                    1
PEDRO   1        2016-01-02    2016-01-02   1                    1

A: I found the perfect answer elsewhere. All credit goes to to the Reddit user nvarscar for the amazing solution!
I'll just copy his/her answer below, in case someone else need it in the future:

You may use a window function feature, which helps you to aggregate
  rows between current row and all preceding ones. The code looks too
  long, but at least you will see the steps taken.

DECLARE @t TABLE
    ([CUSTOMER_ID] varchar(5), [DATE] datetime)
;

INSERT INTO @t
    ([CUSTOMER_ID], [DATE])
VALUES
    ('JHON', '2016-01-01 00:00:00'),
    ('JHON', '2016-01-02 00:00:00'),
    ('PEDRO', '2016-01-02 00:00:00'),
    ('JHON', '2016-01-05 00:00:00'),
    ('MIKE', '2016-01-05 00:00:00'),
    ('MIKE', '2016-01-10 00:00:00'),
    ('JHON', '2016-01-07 00:00:00'),
    ('JHON', '2016-02-15 00:00:00'),
    ('JHON', '2016-02-18 00:00:00'),
    ('MIKE', '2016-02-19 00:00:00'),
    ('MIKE', '2016-02-19 00:00:00'),
    ('JHON', '2016-02-01 00:00:00'),
    ('JHON', '2016-02-02 00:00:00'),
    ('PEDRO', '2016-03-02 00:00:00'),
    ('JHON', '2016-03-05 00:00:00'),
    ('MIKE', '2016-05-05 00:00:00'),
    ('MIKE', '2016-05-10 00:00:00'),
    ('JHON', '2016-03-07 00:00:00'),
    ('JHON', '2016-04-15 00:00:00'),
    ('JHON', '2016-04-18 00:00:00'),
    ('MIKE', '2016-06-19 00:00:00'),
    ('MIKE', '2016-06-19 00:00:00')
;

WITH CTE1 AS (
SELECT
  [CUSTOMER_ID]
, [DATE]
, COUNT(*) AS Transactions
FROM @t
GROUP BY
  [CUSTOMER_ID]
, [DATE]
)
, CTE2 AS (
SELECT
  [CUSTOMER_ID]
, [DATE]
, Transactions
, DATEDIFF(day,LAG([DATE]) OVER (PARTITION BY [CUSTOMER_ID] ORDER BY [DATE]),[DATE]) AS DaysSinceLastTransaction
FROM CTE1
)
, CTE3 AS (
SELECT
  [CUSTOMER_ID]
, [DATE]
, Transactions
, CASE WHEN DaysSinceLastTransaction > 10 THEN 1 ELSE 0 END AS TripTag --Here we set the idle tag
FROM CTE2
)
, CTE4 AS (
SELECT
  [CUSTOMER_ID]
, [DATE]
, Transactions
, SUM(TripTag) OVER (PARTITION BY [CUSTOMER_ID] ORDER BY [DATE] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS TripTag
FROM CTE3
)
SELECT
  [CUSTOMER_ID]
, TripTag+1 AS TripNumber
, MIN ([DATE]) AS TripStartDate
, MAX ([DATE]) AS TripEndDate
, DATEDIFF(day, MIN ([DATE]), MAX ([DATE])) AS TripDuration
, SUM(Transactions) AS Transactions
FROM CTE4
GROUP BY [CUSTOMER_ID], TripTag


text:
Q: Must declare the table variable @table I'm a beginner in C# and SQL, i have this SQL insert statement that i want to perform. It asks for the table name among the other variables that i want to insert.
But when i run this console app i get this error :

Must declare the table variable @table

This is a part of the code :
StreamReader my_reader =  getFile(args);
string CS = formCS();
try
{
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand com = new SqlCommand("insert into @table (time, date, pin) values (@time, @date, @pin)", con);
        con.Open();
        Console.WriteLine("Enter table name:");
        Console.Write(">> ");
        string tblname = Console.ReadLine();
        com.Parameters.AddWithValue("@table", tblname);

        string line = "";
        int count = 0;
        while ((line = my_reader.ReadLine()) != null)
        {
            Dictionary<string, string> result = extractData(line);
            com.Parameters.AddWithValue("@time", result["regTime"]);
            com.Parameters.AddWithValue("@date", result["regDate"]);
            com.Parameters.AddWithValue("@pin", result["regPin"]);
            count += com.ExecuteNonQuery();
            com.Parameters.Clear();

        }
        Console.WriteLine("Recoreds added : {0}", count.ToString());
        Console.WriteLine("Press Enter to exit.");
    }
    Console.ReadLine();
}
catch (SqlException ex)
{
    Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

A: The table name cannot be an input parameter in a sql query. However, you can always "prepare the sql string BEFORE passing it to the SqlCommand as follows:
var sqlString = string.Format("insert into {0} (time, date, pin) values (@time, @date, @pin)", tblname)

and then
SqlCommand com = new SqlCommand(sqlString);
...

A: You can't do this. You can't pass the table name as a parameter the way you did:
SqlCommand com = new SqlCommand("insert into @table ...");
...
com.Parameters.AddWithValue("@table", tblname);

You can do this instead:
Console.WriteLine("Enter table name:");
Console.Write(">> ");
string tblname = Console.ReadLine();

string sql = String.Format("insert into {0} (time, date, pin) values ... ", tblname);

SqlCommand com = new SqlCommand(sql, con);

...

A: Be aware that this could allow SQL Injection attacks like this...
string tblname = "; DROP TABLE users;";
var sqlString = string.Format("insert into {0} (time, date, pin) values (@time, @date, @pin)", tblname)

https://en.wikipedia.org/wiki/SQL_injection


text:
Q: How to restore broken Automatic cell grouping behavior? By default output cells are grouped with the input cell from which they are generated (note the nested cell brackets on the right):

Sometimes it is desirable to group manually input cell with previous "Text" cell containing some comments/description. We can do it manually by selecting both cells and then applying the "Group Cells" item from the right-click menu:

Now both cells are placed in one group:

And this is what happens when we evaluate the grouped input cell:

Now output cells aren't automatically grouped with the input cell anymore!
First question: Is it possible to keep automatic grouping for generated cells if the input cell was manually grouped with some previous cell?

But it is not the end of the story. Being in despair due to this behavior, I manually delete the output cells as well as the text cell, and then try to evaluate my input cell again. Here is what I get:

Surprisingly, output cells aren't grouped with the input cell again! Obviously, the FrontEnd somehow has "marked" this input cell to behave differently. Let us check its internal expression (I selected the cell and pressed Clrl+Shift+E):

Second question: What makes this cell "special" and how to make it an "ordinary" cell again?

Now I copy this cell and try to evaluate it in another place of the Notebook:

The copy obviously is also "special": the automatic grouping doesn't work for it as well! So with the cell some "flag" marking it as "special" was copied. What can it be and how can I remove such a "flag"?
If I copy not the cell, but only the code from it, and then paste as a new cell, normal grouping behavior is restored:

To summarize, my questions are:

*

*Is it possible to keep automatic grouping for generated cells if the input cell was manually grouped with some previous cell?

*How FrontEnd "marks" the cell as a "special" and how is it possible to remove such a "mark"?

A:
What makes this cell "special" and how to make it an "ordinary" cell again?

It is the CellGroupingRules -> {"GroupTogetherGrouping", 10000.} option. Removing this option from input cell restores the default grouping in the case described in the OP. Generally whenever one uses the menu item "Group Cells", this option is set for all cells which should be grouped together. Apparently this is all what this option do.
UPDATE: As John Fultz notes in the comment, for removing this option from selected cells one can use the menu item "Ungroup Cells".

Is it possible to keep automatic grouping for generated cells if the input cell was manually grouped with some previous cell?

One simple way is to apply "SectionGrouping" by adding the option CellGroupingRules->{"SectionGrouping",100} to the "Text" cell. According to this answer, only "SectionGrouping"  and "TitleGrouping" group "InputGrouping" (i.e. "Input" and "Code" cells). The disadvantage is that it will also group all further input cells what is undesirable. One solution suggested in that answer is to add a delimiter which will break up grouping for {"SectionGrouping",100} but not for {"SectionGrouping",50} (i.e. "Subsubsection" style). Here is how it can look like:

And here is a code which generates something like a template (I used the "Delimiter" style from the built-in Documentaion as a base for my delimiter):
NotebookPut@
 Notebook[{Cell[
    CellGroupData[{Cell["Ordinary \"Subsubsection\" cell", "Subsubsection"],
      Cell["\"Text\" cell with CellGroupingRules->{\"SectionGrouping\", 100}", "Text",
       CellGroupingRules -> {"SectionGrouping", 100}],
      Cell["Ordinary \"Input\" cell", "Input"],
      Cell["\t", "Delimiter", Editable -> False, CellMargins -> {{48, 14}, {0, -5}},
       CellFrameMargins -> 0, CellFrame -> {{0, 0}, {0, 0}}, Evaluatable -> False,
       TabFilling -> "\[LongDash]\[NegativeThickSpace]", TabSpacings -> {16},
       CellGroupingRules -> {"SectionGrouping", 58}, FontFamily -> "Verdana",
       FontSize -> 9, FontWeight -> "Plain", FontSlant -> "Plain",
       FontColor -> GrayLevel[.9], CellSize -> {Inherited, 1}],
      Cell["Ordinary \"Input\" cell", "Input"]}]]}]

It is possible to assign a keyboard shortcut (perhaps Ctrl+Space or Alt+Space) for inserting the delimiter. Refs: (1), (2).
Another approach to the problem is demonstrated by Carl Woll in this answer. It has a drawback: output of Echo can't be auto-grouped using this method because Echo isn't supported by "GeneratedCellStyles".


text:
Q: Why I am getting UnreachableBrowserException while executing my selenium test in Cucumber but in simple maven project it is working fine? In Cucumber project I have used Selenium 4.0 aplha and in Simple maven project I have used Selenium 3.14
Is that the reason. The chrome driver used is 85.0.4183.87 and Chrome browser is also 85.
While executing in IE I get Unsupported Command Exception in the cucumber project.
In simple maven project all steps are in one test method but in Cucumber project the steps are divided in Given When and Then. There are 14 steps(Given When and Then) and all are in one feature file.


text:
Q: Hide View Report button on Visualforce Component on Lightning Record Page I am looking to add a Report to my Case Lightning Record Page. I want to filter the report by the Case Account so I cannot use the standard Lightning component (this can only filter by the record).
I have created the Visualforce page below and added this to a Visualforce Component on my Lightning Record Page.  The Lightning component is also adding a "View Report" button which when clicked does not open the report with the applied filter - it returns results for all Accounts.
I was able to adjust the styling to make this "read-only" and disable the button action.
Is there a way to hide the button entirely?
<apex:page standardController="Case">

    <style>
        #dispnone{
        pointer-events: none;
        }
    </style>

    <div id="dispnone" >
        <analytics:reportChart reportId="00O74000000Nze8EAC"
            hideonerror="false"
            filter="{column:'KimbleOne__ResourcedActivity__c.KimbleOne__DeliveryGroup__c.KimbleOne__Account__c.Id',
               operator:'equals', value:'{!Case.Account.Id}'}"
            size="tiny"
            showRefreshButton="false">
        </analytics:reportChart>
    </div>

 </apex:page>


text:
Q: Mysql return value I have a small php page like below that I would like to return the "auto-incremented_id" from this insert.
Only requirement is that I can read the number from an android application. I'm sure I could look it up but is there a code SQL code I can check on success that will return it?
Here's the php:
<?php

//Make connection
$con = mysqli_connect('xxxxx', 'xxxxxxx', 'xxxxx');

//check connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//change db to andriodnfp db
mysqli_select_db($con, 'andriodnfp');

$table = 'USER';

$fbid   = htmlspecialchars($_GET["fbid"]);
$social = htmlspecialchars($_GET["social"]);

$name = htmlspecialchars($_GET["name"]);
$name = !empty($name) ? "'$name'" : "NULL";

$fname = htmlspecialchars($_GET["fname"]);
$fname = !empty($fname) ? "'$fname'" : "NULL";

$username = htmlspecialchars($_GET["username"]);
$username = !empty($username) ? "'$username'" : "NULL";

$email = htmlspecialchars($_GET["email"]);
$email = !empty($email) ? "'$email'" : "NULL";

$picture = htmlspecialchars($_GET["picture"]);
$picture = !empty($picture) ? "'$picture'" : "NULL";

$other = htmlspecialchars($_GET["other"]);
$other = !empty($other) ? "'$other'" : "NULL";

if (!$fbid == '') {

    if (!mysqli_query($con, 'INSERT INTO ' . $table . ' ( facebookID, social_outlet, Name, first_name, username, email, picture, significant_other) VALUES ("' . $fbid . '","' . $social . '","' . $name . '","' . $fname . '","' . $username . '","' . $email . '","' . $picture . '","' . $other . '")')) {
        printf("Errormessage: %s\n", mysqli_error($con));
    };
}

mysqli_close($con);

//$posts = array($json);
$posts = array(
    1
);
header('Content-type: application/json');
echo json_encode(array(
    'posts' => $posts
));

?>

A: Try this: mysqli_insert_id
if (mysqli_query($con, 'INSERT INTO '.$table.' ( facebookID, social_outlet, Name, first_name, username, email, picture, significant_other) VALUES ("'.$fbid.'","'.$social.'","'.$name.'","'.$fname.'","'.$username.'","'.$email.'","'.$picture.'","'.$other.'")') === false) {
    printf("Errormessage: %s\n", mysqli_error($con));
    die();
}
$id = mysqli_insert_id($con);

You should also probably die after an error.
Also, you should compare the query with datatype as well ===, this ensures that it truly failed, not returned a value which evaluates to false. -- but it's not likely it returned something for an insert right?
Suppose you have a table in the database that looks like this:
id, username, user_level
1, dave, 0
2, jcaruso, 1

Suppose user_level was an integer, (0 = user, 1 = administrator).
Doing a select such as SELECT user_level FROM table WHERE id=1 would return 0 and if you compare that with ==, it would be true. 0==false.

A: <?php
//Make connection
$con = mysqli_connect('xxxxx','xxxxxxx','xxxxx') ;

//check connection
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

//change db to andriodnfp db
mysqli_select_db($con, 'andriodnfp');

$table= 'USER';

$fbid = htmlspecialchars($_GET["fbid"]);
$social = htmlspecialchars($_GET["social"]);

$name = htmlspecialchars($_GET["name"]);
$name = !empty($name) ? "'$name'" : "NULL";

$fname = htmlspecialchars($_GET["fname"]);
$fname = !empty($fname) ? "'$fname'" : "NULL";

$username = htmlspecialchars($_GET["username"]);
$username = !empty($username) ? "'$username'" : "NULL";

$email = htmlspecialchars($_GET["email"]);
$email = !empty($email) ? "'$email'" : "NULL";

$picture = htmlspecialchars($_GET["picture"]);
$picture = !empty($picture) ? "'$picture'" : "NULL";

$other = htmlspecialchars($_GET["other"]);
$other = !empty($other) ? "'$other'" : "NULL";

//$posts = array($json);
$posts = array(1);

if (!$fbid == '') {

    if (!mysqli_query($con, 'INSERT INTO '.$table.' ( facebookID, social_outlet, Name, first_name, username, email, picture, significant_other) VALUES ("'.$fbid.'","'.$social.'","'.$name.'","'.$fname.'","'.$username.'","'.$email.'","'.$picture.'","'.$other.'")')) {
        printf("Errormessage: %s\n", mysqli_error($con));
    };

    $auto_id = 'autoincramented_id';

    //passyour primary key here
    $cql  = "SELECT MAX($auto_id) AS primary_id FROM {$table}";

    $result = mysqli_query($con, $cql);

    $id_result = mysql_fetch_assoc($result);

    //$posts = array($json);
    $posts = array('auto_increment_id'=>$id_result['primary_id']);

}

mysqli_close($con);

header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));

?>


text:
Q: Parse Promises, destroyAll(); not working? The second line in the code below is not executing during a Cloud Job, why might this be the case? The prior line runs fine.
Parse.Object.destroyAll(apples).then(function() {
  return Parse.Object.destroyAll(pears); //Destroy all pear objects.
}, function(error) {
  status.error("Failed to destroy all apples/pears.");
});

status.success("Successfully deleted " + results.length + " pears.");

A: your status.success is run synchronously before the destroyAll(pears) would even get a chance to run
try it this way
Parse.Object.destroyAll(apples).then(function() {
    return Parse.Object.destroyAll(pears); //Destroy all pear objects.
}).then(function() {
    status.success("Successfully deleted " + results.length + " pears.");
}, function(error) {
    status.error("Failed to destroy all apples/pears.");
});


text:
Q: woocommerce_free_price_html not working I used the following code to change the 0,00 to a text in Wordpress Woocommerce, but it doesn't work anymore:
add_filter('woocommerce_free_price_html', 'changeFreePriceNotice', 10, 2);

function changeFreePriceNotice($price, $product) {
    return 'Call for price';
}

Does anyone know how to solve this? Google can't help me unfortunately. Hope somebody can help me!

A: Since WooCommerce 3.0 woocommerce_free_price_html does not work any more
I could not find the information why it no longer works.
But I found one solution and adapted it, making it more universal:
add_filter( 'woocommerce_get_price_html','custom_free_price_text' );

function custom_free_price_text( $product ) {
    global $product;
    $price = $product->get_price();

    if($price == '0.00') {
        return 'Call for price';
    } else {
        return "$ ".$price;
    }
}


text:
Q: How do I force Visual Studio 2017 to downgrade to a previous .NET Core version How do I downgrade the Microsoft.NETCore.App package in Visual Studio 2017?
The package manager shows it as 'Blocked by project'

I need to do this as Azure web apps do not yet have the 1.1.2 .NET Core runtime installed.

A: A specific version of the package can be used by editing the csproj file and adding a package reference that specifies Update instead of Include

<ItemGroup>
    <PackageReference Update="Microsoft.NETCore.App" Version="1.1.1" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />


text:
Q: USB powering batteries without OS support? On a bare-metal project I have in mind, I would like to know if I can avoid to implement the multiple USB specs (O/E/xHCI) and still benefit from usb charging my battery. It will run on a almost broken/useless flashed smartphone with one mini usb port.
I literally don't want any usb port for media storage or hid or anything for that project. There will only be one app running.
I was thinking that the already existing hardware usb controller(s) would allow me that, but.. on the other hand, if it is not activated by software, it may be an issue.
Question:
Can I power up my batteries via a usb cable, without software usb implementation? Is there a shortcut avoiding the full usb implementation?
Thanks
Update, to make things clear:
My goal was to use one of my cables, without modification made on it, plug it into my phone, and let it charge. With that information, would you consider that it is still a "yes" to that question?

A: Answer: Yes.
Maxim Integrated Guide to smart battery devices. Or if you're a "dumb device" kinda person, the device being charged can tie their data lines (D+ and D-) and receive maximum power from an adapter. Vice Versa YOu can always charge a USB device 5V @ 500mA regardless of what is present on the data lines (tied up or down or floating or anything). Anything past that would require one of the chips similar to the link's that intelligently (and without programming, i.e. you just solder it in and it works) charges the device that follows USB charging spec.
On the off chance you're talking about using your phone to charge something (still not quite sure, but adding for completeness), that's called OTG and from what I know you'll only be able to provide around 8mA from your phone to the device.
Addendum: Apple doesn't follow USB Charging spec. Ask apple why that is.

A: Yes, if I understand your question correctly. Cut a cable or remove the d+ and D- pins. This data goes through the D- D+ pins. USB Pinout. Use a volt meter in ohms mode if your unsure which pins go to which wires. This may require soldering. I think I have seen USB cables that only have the power and ground on ebay before, but I can't remember what the name is.


text:
Q: How to disable a button after it is clicked a certain number of times? I'm making a game similar to 'who wants to be a millionaire?' and I have a 'Next' button which takes the player to the next question. However, since I am allowing up to four players to play, I want this 'Next' button to disable after a maximum of 3 clicks, (or less if there is one/two/three players playing).
Here is my code so far for the 'Next' button:
nextButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            StatusPage.setVisible(false);
            QuestionPage.setVisible(true);
            option1.setEnabled(true);
            option2.setEnabled(true);
            option3.setEnabled(true);
            option4.setEnabled(true);

            if (Player2JButton.isEnabled()){
                counter = 1;
            }
            else if (Player3JButton.isEnabled()){
                counter = 2;
            }
            else if (Player4JButton.isEnabled()){
                counter = 3;
            }
            else {
                System.out.println("Error getting next question.");
            }

            if (generalKnowledge.isEnabled()){

                currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "generalKnowledge");
            }
            else if (geography.isEnabled()){

                currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "geography");
            }
            else if (hipHopMusic.isEnabled()){

                currentQuest = quest.setQnA(option1, option2, option3, option4, question1, "hipHopMusic");
            }
            else {
                System.out.println("Error getting next question.");
            }
        }
    });

A: Have you thought about using a simple int variable that will count the number of times one of the players pressed that button?
What do you think about this:
    final int NUMBER_OF_PLAYERS=4;
    int count=0;

     nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                count++;
                if(count-1==NUMBER_OF_PLAYERS)
                  {
                  nextButton.setEnabled(false);  //disable the button
                  }

              ///Your code

            }
        });

A: I guess I'll add it as an answer. Here's a working sample, without some Android-yitter.
We'll use an int counter. Every time someone clicks you increment counter within the actionPerformed-block. If counter is greater than 2, it's been clicked 3 times. We'll disable nextButton with #setEnabled.
public class ButtonCycle extends JPanel implements ActionListener {
    private int counter = 0;
    private JButton btn;

    public ButtonCycle() {
        this.btn = new JButton("Next");
        this.btn.addActionListener(this);

        add(this.btn);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame f = new JFrame("Button cycling through animations");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setPreferredSize(new Dimension(250,250));
                f.setContentPane(new ButtonCycle());
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent a) {
        switch(this.counter) {
            case 0:
            case 1:
                this.counter++;
                break;
            case 2:
                ((JButton) a.getSource()).setEnabled(false);
                // or like this
                this.btn.setEnabled(false);
                break;
        }
    }
}

Should give you what you need.


text:
Q: My Spring app running on Docker for Windows crashes due to an UnknownHostException I'm trying to run a Spring app in a Docker container, but it keeps crashing due to an UnknownHostException caused by an image named "some-postgres". I had downloaded the official Postgres Docker image at https://hub.docker.com/_/postgres, and followed the setup instructions, and I created an image called "some-postgres". At some point, I set spring.datasource.url in my applications.properties to jdbc:postgresql://some-postgres:5432/docker_atm, and now, no matter what I use as my data source URL, and regardless of whether there's any usages of "some-postgres" in my project, I keep getting this error stacktrace:
2022-10-04T10:56:32.114821300Z  at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:331) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.114843600Z  at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.114847500Z  at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:247) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.114850500Z  at org.postgresql.Driver.makeConnection(Driver.java:434) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.114853100Z  at org.postgresql.Driver.connect(Driver.java:291) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.114855800Z  at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114858400Z  at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364) ~[HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114861100Z  at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114863800Z  at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) [HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114866500Z  at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) [HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114869200Z  at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114871900Z  at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-4.0.3.jar!/:na]
2022-10-04T10:56:32.114874600Z  at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114877400Z  at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:181) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114884400Z  at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:44) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114887400Z  at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:63) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114890300Z  at org.hibernate.tool.schema.extract.spi.ExtractionContext.getQueryResults(ExtractionContext.java:43) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114893000Z  at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:39) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114896100Z  at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.initializeSequences(DatabaseInformationImpl.java:66) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114898900Z  at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.<init>(DatabaseInformationImpl.java:60) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114904900Z  at org.hibernate.tool.schema.internal.Helper.buildDatabaseInformation(Helper.java:183) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114908000Z  at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:104) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114911100Z  at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:196) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114915000Z  at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114919000Z  at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114922700Z  at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114927000Z  at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) [hibernate-core-5.6.11.Final.jar!/:5.6.11.Final]
2022-10-04T10:56:32.114931700Z  at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) [spring-orm-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114936200Z  at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114940600Z  at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) [spring-orm-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114944800Z  at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) [spring-orm-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114949200Z  at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114953900Z  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114958200Z  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114962100Z  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114965500Z  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114968300Z  at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114975000Z  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114978400Z  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114982400Z  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) [spring-beans-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114985200Z  at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114988100Z  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114991100Z  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar!/:5.3.23]
2022-10-04T10:56:32.114993800Z  at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.4.jar!/:2.7.4]
2022-10-04T10:56:32.114996500Z  at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.4.jar!/:2.7.4]
2022-10-04T10:56:32.114999200Z  at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.4.jar!/:2.7.4]
2022-10-04T10:56:32.115001900Z  at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.4.jar!/:2.7.4]
2022-10-04T10:56:32.115004500Z  at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.4.jar!/:2.7.4]
2022-10-04T10:56:32.115007100Z  at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.4.jar!/:2.7.4]
2022-10-04T10:56:32.115009800Z  at xxxxxxxxxxxxxxxxxx.MyApplication.main(DockerAtmApplication.java:10) ~[classes!/:na]
2022-10-04T10:56:32.115012400Z  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_212]
2022-10-04T10:56:32.115015400Z  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_212]
2022-10-04T10:56:32.115019000Z  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_212]
2022-10-04T10:56:32.115022800Z  at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_212]
2022-10-04T10:56:32.115026200Z  at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) ~[app.jar:na]
2022-10-04T10:56:32.115030000Z  at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) ~[app.jar:na]
2022-10-04T10:56:32.115033800Z  at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) ~[app.jar:na]
2022-10-04T10:56:32.115037700Z  at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65) ~[app.jar:na]
2022-10-04T10:56:32.115040500Z Caused by: java.net.UnknownHostException: some-postgres
2022-10-04T10:56:32.115046600Z  at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184) ~[na:1.8.0_212]
2022-10-04T10:56:32.115053400Z  at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_212]
2022-10-04T10:56:32.115056900Z  at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_212]
2022-10-04T10:56:32.115059500Z  at org.postgresql.core.PGStream.createSocket(PGStream.java:241) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.115062000Z  at org.postgresql.core.PGStream.<init>(PGStream.java:98) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.115064800Z  at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:109) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.115067600Z  at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:235) ~[postgresql-42.5.0.jar!/:42.5.0]
2022-10-04T10:56:32.115070400Z  ... 57 common frames omitted

Here's my Dockerfile:
FROM openjdk:8-jdk-alpine
ARG JAR_FILE=build/libs/*-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar
EXPOSE 8081
ENTRYPOINT ["java", "-jar", "/app.jar"]

And here's my docker-compose.yaml:
services:
  webapp:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8081:8081"

  postgres:
    container_name: postgres
    image: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password!
      PGDATA: /data/postgres
    volumes:
      - postgres:/data/postgres
    ports:
      - "5432:5432" #maps the host's port 5432 to the container's port 5432
    networks:
      - postgres
    restart: unless-stopped

  pgadmin: #access this on localhost:5050
    container_name: pgadmin_container
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
      PGADMIN_CONFIG_SERVER_MODE: 'False'
    volumes:
      - pgadmin:/var/lib/pgadmin

    ports:
      - "5050:80"
    networks:
      - postgres
    restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
  postgres:
  pgadmin:

I've tried a Gradle refresh, I've tried rebuilding the whole project, I've tried docker-compose build --no-cache, I've even tried the "nuclear option" of docker system prune, but no matter what, this one Docker image keeps haunting my code.
EDIT: Here's the application.properties file I'm using:
server.port=8081

spring.datasource.url=jdbc:postgresql://localhost:5432/docker_atm
spring.datasource.username=postgres
spring.datasource.password=password!

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

#Database initialisation - change to "validate" when in production
spring.jpa.hibernate.ddl-auto=update

A: In your docker-compose.yml under the following part
postgres:
    container_name: postgres
    image: postgres

you have named the database service as postgres. So by default docker will expose a host as ...postgres...
But from Spring-boot application it seems you try to connect to host some-postgres.
2022-10-04T10:56:32.115040500Z Caused by: java.net.UnknownHostException: some-postgres

The configuration that spring boot app has as you mention is jdbc:postgresql://some-postgres:5432/docker_atm
So to fix the situation you have 2 options:

*

*change the spring boot configuration into  jdbc:postgresql://postgres:5432/docker_atm

*keep the existing spring boot configuration url property jdbc:postgresql://some-postgres:5432/docker_atm and change the docker-compose.yml into
some-postgres:
     container_name: postgres
     image: postgres

so that the host available becomes the some-postgres.
Edit:
As to provide a clear specific solution please do the following.
Modify your compose.yml with the following
some-postgres: <---------------------
    container_name: postgres
    image: postgres
    environment:
      POSTGRES_DB: docker_atm  <-------------
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password!
      PGDATA: /data/postgres
    volumes:
      - postgres:/data/postgres
    ports:
      - "5432:5432" #maps the host's port 5432 to the container's port 5432
    networks:
      - postgres
    restart: unless-stopped

    .....

You have also forgot to declare in your docker the database name for your postgresql instance.
Then your spring boot application property should be
spring.datasource.url=jdbc:postgresql://some-postgres:5432/docker_atm

Rebuild the docker image and the jar for the application and repackage and redeploy and it shall work.


text:
Q: I need to create a simple module in drupal 7 to display "Hello world" I need to create a simple module in drupal 7 to display "Hello world" which can locate in various regions like content, header, footer, etc. and after reading a couple of tutorials, i can't seem to display anything appropriate.

A: You need to create a new block. You can do that with following hooks: hook_block_info and hook_block_view.
Create a new directory and call it hello_world. Create a hello_world.info and hello_world.module file.
You put following stuff in the hello_world.info file:
name = Hello World
description = Small module which just provides a block.
core = 7.x

And following into hello_world.module:
<?php

/**
 * @file
 * Main file of Hello World module.
 */

/**
 * Implements hook_block_info().
 */
function hello_world_block_info() {
  $blocks = array();

  $blocks['hello_world'] = array(
    'info' => t('Hello world'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function hello_world_block_view($delta = '') {
  $block = array();

  if ($delta == 'hello_world') {
    $block['subject'] = t('Hello world');
    $block['content'] = t('This is the block content.');
  }

  return $block;
}

Then put the hello_world directory into sites/all/modules/custom and enable the module on /admin/modules. You will see a new block called "Hello world" in the block overview (/admin/structure/block). Drag it into the right region and the block will show up there.


text:
Q: Is there a way to specify Build Action=None with nuspec? My company has an assembly versioning package that I've written in powershell and is distributed amongst my colleagues via our internal nuget feed.
There are a couple of template files which can be user-modified after the package in installed. These files are being included in the package which we generate via
nuget pack xxxx.csproj

We've done a little investigation and there files are not packaged when we change the Build Action to None.
Is there a way to tell nuspec to add the files to the project with Build Action set to None*?
Alternatively is there a way to tell nuget pack to not include certain files in the package in generates?

A: *

*NuGet pack has an Exclude parameter that can be used to filter out files that you don't want in your package.

*If you want to include files that are auto excluded from your project then you need to add a nuspec to your project and add a  element that includes that file.

More information here:
http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package#From_a_project
http://docs.nuget.org/docs/reference/command-line-reference#Pack_Command

A: nuget pack will ignore any files or folders that start with period/full stop. So one easy way would be to rename your template files or the folder they are located in to start with a period/full stop if possible.


text:
Q: How to average time commands? I am timeing some of my commands. Now to average the measures, I'd like to run and time my commands a specified number of times, and get the results with a calculated mean and standard deviation. The result would be like:
avgtime -n 100 my_command

real    0m5.388s stdev 0m0.068s
user    0m5.380s stdev 0m0.067s
sys     0m0.004s stdev 0m0.000s

Is there a UNIX tool for this?
Does GNU/Linux have one?

A: Hyperfine is another option.
Sample usage:
hyperfine --warmup 3 'my_command'

See related question.

A: It's not exactly a UNIX or GNU/Linux tool, but you could quite comfortably use the R software environment for statistical computing for this. (I cannot find anything more specific for your task, though.)
Edit How could I doubt it, there of course is a benchmark package for R: rbenchmark.  It apparently wraps system.time() which you could also just use directly.  Or have a look at this, a simple stopwatch function pair.  Also see "Executing a system command" @Rosetta Code (or don't, it's system("command").)
Edit2 I just saw this question, "Measuring time within a script" in the right "Related" column, this could be used, too, i.e. take time, do for-loop (N times), take time again, calculate timespan, divide by N.  (Even easier, try time ( for-loop ), parse its output, divide by N).

A: You can use R to quickly compute the mean, standard-deviation and other interesting values.
For example, you can use GNU time to write several runtime measurements into a CSV file:
function measure
{
  f=$1; shift
  n=$2; shift
  echo wall,user,sys,rss > "$f"
  for i in $(seq $n); do
    /usr/bin/time --output "$f" --append --format '%e,%U,%S,%M' "$@" >/dev/null
  done
}

Then you can generate the values with R like this:
Rscript --vanilla -e "b=read.csv(file='$f');summary(b);sapply(b, sd);"

I've created a small benchmark script that also does some pretty printing of the R output, e.g.:
$ benchmark.sh 100 ./some_prog arg1 arg2
n=100 | min    | Q1     | med    | mean   | Q3     | max    | std
wall  | 0.0400 | 0.0400 | 0.0500 | 0.0471 | 0.0500 | 0.0800 | 0.00624
user  | 0.0400 | 0.0400 | 0.0400 | 0.0426 | 0.0400 | 0.0700 | 0.00562
sys   | 0      | 0      | 0      | 0      | 0      | 0      | 0.00000
rss   | 2608   | 2657   | 2704   | 2728   | 2764   | 2920   | 95.06524

A: Two more options (both now available in debian et al.):

*

*multitime (on
github), as in multitime -q -n 10 sleep 1 (from
https://superuser.com/a/1301756/129608)

*linux-perf (wiki), as in perf stat -r 10 -B sleep 1 (from https://superuser.com/a/1279724/129608)

A: You can to try use the timeit module, available in any system with Python:
$ python -m timeit "__import__('os').system('my command here')"
10 loops, best of 3: 591 msec per loop

A: Option 1 - sqlite:
create simple table with command and time columns, and view with proper aggregation calculations. After timing, add a row to the table.
Advantages: simpler to define a table compared to solution 2.
Disadvantages: you need (do you?) care about data retention.
Option 2 - rrdtool:
Define rrd data base file, data definition and aggregation functions.
After timing, feed the database with rrdtool update ....
Advantages: you can easily generate graphs with rrdtool graph .... No data retention issue (round robin database).
Disadvantages: bit harder to define rrd database compared to simple SQL table/view


text:
Q: Trying to make an infinite scroll with a list of div already in the html I'm trying to write a function in jQuery that could create an infinite scroll with divs that are already in my page. I would like to make them appear and load randomly when you reached the end of the original content. The thing is that I'm just starting to use jQuery and I don't really know who to do it!
All my divs have a class of item and are inside a .content div. For the moment I have 11 of them.
I tried to .append(specific div) and it worked, but I don't know how to do it with a list of div.
Does anyone have an idea of what I should do?
    $(document).ready(function() {
      var collection = $("div.content .item").get();
      collection.sort(function() {
        return Math.random() * 10 > 5 ? 1 : -1;
      });

      $.each(collection, function(i, el) {
        $(el).appendTo($(el).parent());
      });
    });

    $(window).scroll(function() {
      if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        $(".content").append('Here is where I dont know what I should write')
      });
    });
  }
});

A: Hi :3 The jquery clone() function may be of help, in your case:
let triggerDistance = $(document).height() - $(window).height() - 50;
let OriginalItems = $(".item").length;

$(window).scroll(function() {
    let scrolledDistance = $(window).scrollTop();
    if ( scrolledDistance > triggerDistance) {
        var randomItem = Math.floor(Math.random() * OriginalItems);
        var clonedItem = $("#item_"+randomItem).clone();
        clonedItem.removeAttr('id');
        clonedItem.appendTo("html");
    }
});

You select a random item from the original ones, you create a new copy of said item using clone, you append the clone to the document :)
Here's a fiddle: https://jsfiddle.net/collederfomento/d98a15cu/4/
A few things could be improved:

*

*preventing the function from firing too often

*preventing the function from cloning the same item twice in a row


text:
Q: Scala sorting Options If I have a case class like this
case class Foo(bar: Option[String])

why does this work
scala> val l = List(Foo(Some("b")), Foo(Some("a")), Foo(Some("c")))
l: List[Foo] = List(Foo(Some(b)), Foo(Some(a)), Foo(Some(c)))
scala> l.sortBy(_.bar)
res1: List[Foo] = List(Foo(Some(a)), Foo(Some(b)), Foo(Some(c)))

but not this
scala> l.sortWith((x,y) => x.bar > y.bar)
<console>:11: error: value > is not a member of Option[String]
          l.sortWith((x,y) => x.bar > y.bar)

If I want to sort a List of Option[String] in descending order, is it just simpler to use sortBy and then reverse the list?

A: It's because sorted but not sortWith takes an implicit parameter of type Ordering, and Ordering knows about options.  With sortWith, you're on your own.  And with < you're also on your own.
You can access the same machinery in a clunky fashion:
l.sortWith((a,b) => Ordering[Option[String]].gt(a.bar,b.bar))

or get the nicer version with an import (but now you'll be able to compare Options anywhere based on their contents; hopefully that is what you want):
import scala.math.Ordered._
l.sortWith((a,b) => a.bar > b.bar)

The first is such a mouthful that unless you're really pressed for performance, it's easier to just .sorted.reverse..  (And if you are really pressed for performance, you'd probably be better off handling the option logic manually, e.g. a.bar.isEmpty || !b.bar.isEmpty || a.bar.get < b.bar.get.)
If you're going to do multiple sorts, it's hard to beat the second for clarity.  For just one test, I'd still probably favor .sorted.reverse.


text:
Q: How to get array of key from amazon s3 object I am using amazon s3 v3 php sdk and i am trying to get key of all object for that i am using
s3->listObjects([ 'Bucket' => $somebucketName]);

this function is working fine and i am getting all object under $somebucketName bucket and its in below form
Aws\Result Object
(
    [data:Aws\Result:private] => Array
        (
            [IsTruncated] =>
            [Marker] =>
            [Contents] => Array
                (
                    [0] => Array
                        (
                            [Key] => 1.PNG
                            [LastModified] => Aws\Api\DateTimeResult Object
                                (
                                    [date] => 2015-07-14 07:22:25.000000
                                    [timezone_type] => 2
                                    [timezone] => Z
                                )

                            [ETag] => "23f423234v23v42424d23"
                            [Size] => 19980
                            [StorageClass] => STANDARD
                            [Owner] => Array
                                (
                                    [DisplayName] => sfsfssfsdf
                                    [ID] => 242f2342242342252g42f42vt34
                                )

                        )

                    [1] => Array
                        (
                            [Key] => 58.jpg
                            [LastModified] => Aws\Api\DateTimeResult Object
                                (
                                    [date] => 2015-07-14 07:20:26.000000
                                    [timezone_type] => 2
                                    [timezone] => Z
                                )

                            [ETag] => "vrtet4v4t54tvt4gvtgv45"
                            [Size] => 1226694
                            [StorageClass] => STANDARD
                            [Owner] => Array
                                (
                                    [DisplayName] => sfsfssfsdf
                                    [ID] => 34t3t3t3y43y4yg5yy4vg6u676
                                )

                        )

                    [2] => Array
                        (
                            [Key] => HDFHDFHDFHDFHFHFH
                            [LastModified] => Aws\Api\DateTimeResult Object
                                (
                                    [date] => 2015-07-30 12:07:42.000000
                                    [timezone_type] => 2
                                    [timezone] => Z
                                )

                            [ETag] => "3453345343rcf3f3r3r3f"

                )

            [Name] => SFSSD
            [Prefix] =>
            [MaxKeys] => 1000
            [@metadata] => Array
                (
                    [statusCode] => 200
                    [effectiveUri] => https://s3-us-west-2.amazonaws.com/SFSSD
                    [headers] => Array
                        (
                            [x-amz-id-2] =>  sdfsfs234sfs
                            [x-amz-request-id] => HSJFSD899
                            [date] => Mon, 03 Aug 2015 06:46:48 GMT
                            [x-amz-bucket-region] => us-west-2
                            [content-type] => application/xml
                            [transfer-encoding] => chunked
                            [server] => AmazonS3
                        )

                )

        )

)

now my question is that how to get array of key like below from above object
array("1.png","58.jpg","HDDHDFHDHDGH);

A: Aws\Result implements ArrayAccess. You can access the contents like so:
$result = $s3->listObjects(['Bucket' => $somebucketName])
$contents = $result['Contents'];

A: From comment: Please note that v1 of the SDK is deprecated. If you're still using it you can use the following snippet:
$ObjectsListResponse = s3->list_objects([ 'Bucket' => $somebucketName]);
$Objects = $ObjectsListResponse->body->Contents;
foreach ($Objects as $Object) {
        $keyArray[] = $Object->Key;
}

PHP S3 Examples


text:
Q: Determine if a series of discrete distributions are expected *I apologize for the length of this post and I have almost no statistics experience, please keep that in mind :)
In competitive diving, a diver will perform 5 different dives and will receive scores from a panel of judges.
I have a theory that a diver is more likely to either perform the dive well and get a good score or mess up and receive a bad score, leading to a bit of a bi-modal distribution of scores.
However, when I compared all divers at once, there was simply a normal(ish) distribution because the good divers' bad scores "cancel" with the bad divers' good scores(over simplification).
This lead me to separate all the data for a single person. But now I realize that because a diver's score changes with time/experience/age and also by event, this would lead to a "muddying" of the distributions.
So to avoid eclipsing, what I believe will be a kind of bimodal distribution, I extracted data for a single person for each event type/round.
I have a distribution of dive scores from each dive for many different meets and rounds. (One person's data)
City  Round  Total_score  Dive_1   Dive_2  ...   Dive_5
NYC   Finals    237       60.4     59.5
NYC   Semis     199       62.7     60.1
LDN   Prelim    356       65.1     57.35

From these, for each event(NYC Finals != NYC SemiFinals), I created a histogram to determine the frequency of different dive scores.
Just by eyeing some of the histograms, it seems you are more likely to do well or badly than "okay".
 Note: Each graph corresponds to one event.
But I now need to use statistics to prove that I am not deluded.
I was thinking of doing this by comparing the individual diver's yearly score's standard deviation to the individual event's deviation. From this I could derive an "expected" distribution and see if the individual event distributions are unlikely. However, I don't know if this is possible, or even makes sense to do.
Are there any other ways of determining if a distribution is unlikely?
Once I have that(or something like it), I would need to repeat this analysis for every diver and then finally come to a conclusion of whether my hypothesis is correct.
*Edit: I am using SAS to analyze my data. Are there any built in procedures that could aid me?


text:
Q: Resizing windows with keyboard shortcuts I have seen some people resizing their windows very efficiently with shortcuts..
For example window is on full screen then you press some key and it becomes the left side of the screen then another window you press a button and it takes the right side of the screen.
I'm not sure if this is achieved with any application or it's built in, does anyone know how to achieve that?

A: In Ubuntu, some keyboard shortcuts are set up by default:

*

*Maximize window: Super+Up

*Restore window: Super+Down

*Tile to left half of the screen:  Super+Left

*Tile to right half of the screen:  Super+Right
In addition, keys are setup to move and resize using the keyboard:

*

*Begin move:  Alt+F7. After hitting this key, arrow keys will move the window, Shift+Arrow keys will quickly move the window toward the side of the screen or the edge of another window. Press Enter or another key when done

*Begin resize: Alt+F8 will initiate a resize. arrow keys will resize the window, Shift+Arrow keys will resize towards the edge or another window.

Using hidden configuration settings, more custom shortcuts for window manipulation can be defined. Following configuration commands will set up shortcut keys for:
• centering a window or moving it quickly to the side of the screen
gsettings set org.gnome.desktop.wm.keybindings move-to-center "['<Control><Super>c']"
gsettings set org.gnome.desktop.wm.keybindings move-to-side-e "['<Control><Super>Right']"
gsettings set org.gnome.desktop.wm.keybindings move-to-side-n "['<Control><Super>Up']"
gsettings set org.gnome.desktop.wm.keybindings move-to-side-s "['<Control><Super>Down']"
gsettings set org.gnome.desktop.wm.keybindings move-to-side-w "['<Control><Super>Left']"

These are keybindings I defined. You can choose to use different keybindings by editing the commands first.
• positioning a window in one of the corners of the screen
gsettings set org.gnome.desktop.wm.keybindings move-to-corner-ne "['<Control><Super>2']"
gsettings set org.gnome.desktop.wm.keybindings move-to-corner-nw "['<Control><Super>1']"
gsettings set org.gnome.desktop.wm.keybindings move-to-corner-se "['<Control><Super>4']"
gsettings set org.gnome.desktop.wm.keybindings move-to-corner-sw ['<Control><Super>3']"

• maximizing horizontally and vertically
gsettings set org.gnome.desktop.wm.keybindings maximize-horizontally "['<Control><Super>equal']"
gsettings set org.gnome.desktop.wm.keybindings maximize-vertically "['<Control><Super>backslash']"

These settings can also be set using the utility dconf-editor.


text:
Q: CURL PHP handshake failure SSL I have the following code :
<?php
$cookie_file_path = "cookie.txt"; //
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'theurl');
curl_setopt($ch, CURLOPT_POSTFIELDS,'blocPnr_textField_labelNom='.urlencode('www').'&blocPnr_textField_labelPnr='.urlencode('xxx').'&blocPnr_valider=Submit');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_REFERER, "theurl");
$page = curl_exec($ch);
var_dump($page);
echo 'error:' . curl_error($ch);
?>

It gives me the following error:

bool(false) error:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

I can't figure out where the pb comes from. I looked for similar error message on Google and S/O but haven't found any solution.

A: You're trying to use version 3 of the SSL protocol which is either refused or unsupported by the server. The POODLE attack pushed a lot of system administrators to drop support for SSLv3 and its usage is not so widespread anymore (and definitely not recommended).
When you have SSL handshake errors, try different versions of SSL/TLS until one works (preferably the most secure). If you have a doubt, using CURL_SSLVERSION_DEFAULT works in most cases.
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);

It seems that formulaire.sncf.com supports TLSv1.0. You could also force use that protocol version:
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0);


text:
Q: Bash Script Quits After Exiting SSH I'm trying to write a Bash script that logs into 2 different linux based power-strips (Ubiquiti Mpower Pros) and turns 2 different lights off (one on each strip). To do this I login to the 1st strip, change the appropriate file to 0 (thus turning off the light), and exit, repeating the same process on the next power-strip. However, after I exit the first SSH connection, the script stops working. Could someone please suggest a fix? My only idea would be to encase this script in a python program. Here's my code:
#!/bin/bash
ssh User@192.168.0.100
echo "0" > /proc/power/relay1
exit
# hits the enter key
cat <(echo "") | <command>

ssh User@192.168.0.103
echo "logged in"
echo "0" > /proc/power/relay1
exit
cat <(echo "") | <command>

A: ssh as an app BLOCKS while it's running,  the echo and exit are executed by the local shell, not by the remote machine. so you are doing:

*

*ssh to remote machine

*exit remote shell

*echo locally

*exit locally

and boom, your script is dead. If that echo/exit is supposed to be run on the remote system, then you should be doing:
ssh user@host command
               ^^^^^---executed on the remote machine

e.g.
ssh foo@bar 'echo ... ; exit'

A: The commands you're apparently trying to run through ssh are actually being executed locally.  You can just pass the command you want to run to ssh and it will do it (without needing an explicit exit)
ssh User@192.168.0.110 'echo "0" > /proc/power/relay1'

will do that, and similar for the other ssh command