text:
Q: Why deletion of elements of hash table using doubly-linked list is O(1)? On CLRS's textbook "Introduction to Algorithm", there's such paragraph on pg. 258.
We can delete an element in O(1) time if the lists are doubly linked. (Note that CHAINED-HASH-DELETE takes as input an element x and not its key k, so that we don't have to search for x first. If the hash table supports deletion, then its linked list should be doubly linked so that we can delete an item quickly. If the lists were only singly linked, then to delete element x, we would first have to find x in the list so that we could update the next attribute of x's predecessor. With singly linked lists, both deletion and searching would have the same asymptotic running times).
What puzzle me is this big parenthses, I failed to understand its logic. With doubly linked list, one still have to find x in order to delete it, how is this different from singly linked list? Please help me to understand it!

A: The problem presented here is : consider you have are looking at a particular element of a  hashtable. How costly is it to delete it?
Suppose you have a simple linked list :
v ----> w ----> x ----> y ----> z
                |
            you're here

Now if you remove x, you need  to connect w to y to keep your list linked. You need to access w and tell it to point to y (you want to have w ----> y). But you can't access w from x because it's simply linked! Thus you have to go through all your list to find w in O(n) operations, and then tell it to link to y. That's bad.
Then, suppose you're doubly-linked :
v <---> w <---> x <---> y <---> z
                |
            you're here

Cool, you can access w and y from here, so you can connect the two (w <---> y) in O(1) operation!

A: It seems to me that the hash table part of this is mostly a red herring. The real question is: "can we delete the current element from a linked list in constant time, and if so how?"
The answer is: it's a little tricky, but in effect yes, we can -- at least usually. We do not (normally) have to traverse the entire linked list to find the previous element.  Instead, we can swap the data between the current element and the next element, then delete the next element.
The one exception to this is when/if we need/want to delete the last item in the list. In this case, there is no next element to swap with. If you really have to do that, there's no real way to avoid finding the previous element. There are, however, ways that will generally work to avoid that -- one is to terminate the list with a sentinel instead of a null pointer. In this case, since we never delete the node with the sentinel value, we never have to deal with deleting the last item in the list. That leaves us with relatively simple code, something like this:
template <class key, class data>
struct node {
    key k;
    data d;
    node *next;
};

void delete_node(node *item) {
    node *temp = item->next;
    swap(item->key, temp->key);
    swap(item->data, temp->data);
    item ->next = temp->next;
    delete temp;
}

A: In general you are correct - the algorithm you posted takes an element itself as input though and not just its key:

Note that CHAINED-HASH-DELETE takes as input an element x and not its
  key k, so that we don't have to search for x first.

You have the element x - since it is a double linked list you have pointers to predecessor and successor, so you can fix those elements in O(1) - with a single linked list only the successor would be available, so you would have to search for the predecessor in O(n).

A: suppose you want to delete an element x , by using doubly link list you can easily connect the previous element of x to next element of x. so no need to go through all the list and it will be in O(1).

A: Find(x) is, in general, O(1) for a chained hash table -- it is immaterial whether or not you use singly linked lists or doubly linked lists.  They are identical in performance.
If, after having run Find(x), you decide that you'd like to delete the object returned, you will find that, internally, a hash table might have to search for your object again.  It's still usually going to be O(1) and not a big deal, but you find that you delete an awful lot, you can do a little better.  Instead of returning a user's element directly, return a pointer to the underlying hash node.  You can then take advantage of some internal structures.  So if in this case, you chose a doubly linked list as the way to express your chaining, then during the delete process, there is no need to recompute the hash and search the collection again -- you can omit this step. You have enough information to perform a delete right from where you are sitting.  Additional care must be taken if the node you are submitting is the head node, so an integer might be used to mark the location of your node in the original array if it is the head of a linked list.
The trade-off is the guaranteed space taken by the extra pointer versus a possible faster delete (and slightly more complicated code).  With modern desktops, space is usually very cheap, so this might be a reasonable trade-off.

A: Coding point of view:
one can use unordered_map in c++ to implement this.
unordered_map<value,node*>mp;

Where node* is a pointer to a structure storing the key, left and right pointers!
How to use:
If you have a value v and you want to delete that node just do:

*

*Access that nodes value like mp[v].

*Now just make its left pointer point to the node on its right.
And voila, you are done.
(Just to remind, in C++ unordered_map takes an average O(1) to access a specific value stored.)

A: While going through the textbook, I also got confused on the same topic(whether "x" is a pointer to an element or the element itself) and then eventually landed upon this question. But after going through the above discussion and referring textbook again, I think in the book "x" is implicitly assumed to be a "node" and its possible attributes are "key", "next".
Some lines form the textbook..
1)CHAINED-HASH-INSERT(T,x)
 insert x at the head of list T[h(x.key)]
2)If the lists were only singly linked, then to
delete element x, we would first have to find x in the list T[h(x.key)] so that we
could update the next attribute of x's predecessor.
Hence we can assume that the pointer to the element is given and I think Fezvez has given a good explanation for the asked question.

A: The textbook is wrong. The first member of a list has no usable "previous" pointer, so additional code is needed to find and unlink the element if it happens to be the first in the chain (typically 30 % of the elements are the head of their chain, if N=M, (when mapping N items into M slots; each slot having a separate chain.))
EDIT:
A better way then using a backlink, is to use a pointer to the link that points to us (typically the ->next link of the previous node in the list)
struct node {
   struct node **pppar;
   struct node *nxt;
   ...
   }

deletion then becomes:
*(p->pppar) = p->nxt;

And a nice feature of this method is that it works equally well for the first node on the chain (whose pppar pointer points to some pointer that is not part of a node.
UPDATE 2011-11-11
Because people fail to see my point, I'll try to illustrate. As an example there is a hashtable table (basically an array of pointers)
and a buch of nodes one, two, three one of which has to be deleted.
    struct node *table[123];
    struct node *one, *two,*three;
    /* Initial situation: the chain {one,two,three}
    ** is located at slot#31 of the array */
    table[31] = one, one->next = two , two-next = three, three->next = NULL;
                one->prev = NULL, two->prev = one, three->prev = two;

    /* How to delete element one :*/
    if (one->prev == NULL) {
            table[31] = one->next;
            }
    else    {
            one->prev->next = one->next
            }
    if (one->next) {
            one->next->prev = one->prev;
            }

Now it is obvious that the obove code is O(1), but there is something nasty: it still needs array, and the index 31, so in most cases a node is "self contained", and a pointer to a node is sufficient to delete it from its chain, except when it happens to be the first node in its chain; additional information will then be needed to find table and 31.
Next, consider the equivalent structure with a pointer-to-pointer as a backlink.
    struct node {
            struct node *next;
            struct node **ppp;
            char payload[43];
            };

    struct node *table[123];
    struct node *one, *two,*three;
    /* Initial situation: the chain {one,two,three}
    ** is located at slot#31 of the array */
    table[31] = one, one-next = two , two-next = three, three->next = NULL;
                one->ppp = &table[31], two->ppp = &one->next, three->ppp = &two-next;

    /* How to delete element one */
    *(one->ppp) = one->next;
    if (one->next) one->next->ppp = one->ppp;

Note: no special cases, and no need to know the parent table. (consider the case where there is more than one hashtable, but with the same nodetypes: the delete operation would still need to know from which table the node should be removed).
Often, in the {prev,next} scenario, the special cases are avoided by adding a dummy node at the start of the double linked list; But that needs to be allocated and initialised, too.


text:
Q: Payment method nonces expire after 24 hours in Brain Tree We are making a bidding app in which highest bid will commit but after the completion of auction time (suppose 2 days).
As user may have provided me Payment method nonce 48 hours ago, than I have to save nonce and commit after 48 hours. Is there any solution to handle it?

A: Finally with help of Braintree Support I find a way to handle this. Payment method nonce actually expires after 24 hours but there is an alternate way to use payment method token instead of payment method nonce to commit transaction after desired time. I'm working on Rails.
First, create a customer with given payment method nonce from client
result = Braintree::Customer.create(
            :first_name => "Faisal",
            :last_name => "Iqbal",
            :payment_method_nonce => 'fake-valid-nonce' )

It will create a customer on vault of your Braintree account and generate a payment_method_token, you can get it as
token_generated=result.customer.payment_methods[0].token

then use it to commit transaction at any time using
transation = Braintree::Transaction.sale(
            :amount => "5000.00",
            :payment_method_token => token_generated)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Marquee plugin - setting start position I am using this jq plugin: http://plugins.jquery.com/marquee/, (github). The API options are pretty limited, and there is no mention of a start position. I want it to start with the first element of the marquee aligned to the left of the container, not to the right which is default.
Here's what I have put together so far, but as you can see from the fiddle it is far from perfect:
Fiddle
HTML:

1

2

3

4

5

6

7

8

CSS:
body {
    margin: 10px;
    font-family:'Lato', sans-serif;
}
.marquee {
    width: 100%;
    overflow: hidden;
    border:1px solid #ccc;
    background: black;
    color: rgb(202, 255, 195);
}
.ablock {
    width:50px;
    height:50px;
    background:red;
    margin-left:10px;
    display:inline-block;
}
.ablock:first-child {
    margin-left:0;
}

.wrapper{
    width:50%;
}

jQuery:
var offset_is_set = false;

$(function () {
    $('.marquee').bind('beforeStarting', function () {
        if (!offset_is_set) {
            $('.marquee > div > .js-marquee > .ablock:first-child').css('margin-left', '-' + $('.wrapper').width() + 'px');
            offset_is_set = true;
        }
    });

      $('.marquee').marquee({
        duration: 10000,
        duplicated: true,
        pauseOnHover: true,
        gap: 15
    });
});


text:
Q: dijit/InlineEditBox: How to set max characters per line In Dojo's text editor (dijit/InlineEditBox) I need to set dynamically the maximum number of characters per line.
I suspect that "editorparams" could be used for that, but I can't find documentation or good examples about it.
Is it possible to set a maximum number of characters per line? If so, how?

A: Yes, it is possible. editorParams should contain object with properties of editor, you're using in InlineTextBox.
See snippet below.
In this case editor is dijit/form/TextBox and its property maxlength is set to 10.

require(["dojo/parser",
         "dijit/InlineEditBox",
         "dijit/form/TextBox" ],
function(parser){
parser.parse();

});

123456789


text:
Q: How to maintain context when implementing a new TensorFlow Op? When implementing a new TensorFlow Op, if I want to maintain some intermediate data (not necessary a tensor) that is produced and consumed by both the forward and backward functions, how can I do this?
Let's say I need to implement a new layer which requires the storage of an intermediate hashtable for the layer, is there some way to store it in the context of TensorFlow? I don't want to serialize the hashtable as a tensor and need to spend O(n) time to reconstruct the hashtable every time I load it from the TensorFlow context.
Thank you.


text:
Q: MySQL Query join I'm trying to build a website which controls a portfolio of rental properties. The site owner can create a listing for a property. The property has a default price per night but also includes the ability to set a special price, for example, for August.
The sites users can then go onto the site and input a date range and search for listings which are available over that time period. I also need at that stage to see if there's a special price involved to replace the default price.
So the tables I have are:
listings
    id
    default_price
    etc...

bookings
   id
   listing_id
   checkin
   checkout

special_prices
   id
   listing_id
   from
   to
   price

But I'm useless at sql queries and I can't figure out what the query would look like to listings which had no bookings during the time period entered and which gets the special_price if it exists.
I'm using cakephp if that makes the query easier to build. Can anyone help me out?
EDIT
Hey guys, I'm still trying to figure this out at the minute I'm just concentrating on getting listings which don't have bookings which clash with the requested dates, and I'll sort out the special prices stuff after that
At the minute I have:
$conditions = array(
    "AND" => array(
        "OR" => array(
                    "Listing.address_one LIKE" => "%".$area."%",
                    "Listing.address_two LIKE" => "%".$area."%",
                    "Listing.city LIKE" => "%".$area."%",
                    "Listing.postcode LIKE" => "%".$area."%",
                    "Listing.title LIKE" => "%".$area."%",
                    ),
                    )
                );

$this->Listing->bindModel(array('hasMany' => array('Booking' => array('conditions' =>array('Booking.checkin BETWEEN ? AND ?' => array($to, $from))))));
$data = $this->paginate('Listing', $conditions);
$this->set('data', $data);

This gets all results which match the $area keyword in the Listing cols, but seems to completely ignore the Bookings table. I've tried putting in NOT BETWEEN to see if it made a difference and it still just returns whatever matches $area and seemingly ignores the Bookings between the requested dates.
Anyone any ideas?

A: There are several ways of doing this but LEFT JOINing the bookings table and searching for null results is one way of going about it. Assuming checkin = a booking date...
SELECT
*
FROM listings l
LEFT JOIN bookings b ON b.listing_id = l.id AND b.checkin BETWEEN YOUR START DATE AND YOUR_END_DATE
WHERE b.id IS NULL

A: This is done using correlated sub-query.
SELECT li.id FROM listings li WHERE
 0=(SELECT COUNT(*) FROM bookings bo WHERE bo.listing_id=li.id
 AND bo.checkin="START DATE" AND bo.checkout="END DATE");


text:
Q: Simple example with window.requestFileSystem() function I have next problem: I try to use window.requestFileSystem() function in Chrome, but it failed. Look for my steps:
1)I added 'allow file access from file' flag to Chrome(see img bellow):
2)I restarted the system.
3)Then I ran the Chrome with 'allow file access file' flag.
4) After all I try to launch this sample code:
function onInitFs(fs) {
  console.log('Opened file system: ' + fs.name);
}

    function errorHandler(e)
{
    console.log("Error");
}
    window.requestFileSystem(window.TEMPORARY, 5*1024*1024 /*5MB*/, onInitFs, errorHandler);

but It failed:

What's wrong in my actions?

A: That's because this functionality is currently only availble prefixed, ie window.webkitRequestFileSystem
You may find this turorial interesting: http://www.html5rocks.com/en/tutorials/file/filesystem/

A: You should change
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

to
window.RequestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

(The R should have been capitalized.)

A: open chrome from command  line using below command
chrome --allow-file-access-from-files

A: This code works for me in chrome. I actually used it for phonegap, but I tested it first on chrome on my notebook and a yellow bar appeared on the top of the browser, asking me to allow the web app permanent storage on my local drive.
    navigator.webkitPersistentStorage.requestQuota(1024*1024,
        function(grantedBytes) {
            window.requestFileSystem(window.PERSISTENT, grantedBytes, onInitFs, errorHandler);
        },
        function(errorCode) {
            alert("Storage not granted.");
        }
    );


text:
Q: Non-Renewal subscription in-app purchase clarification needed I have a requirement to implement monthly subscription plans to radio channels in the iPhone app. These radio channels are creating by the admin through web backend. Channels have its own unlock price. And also, the admin can add channels dynamically.
So, my first question is

*

*How do I implement Non-Renewal subscription in-app purchase for this kind of products set?
Do I need to manually add a product in iTunesConnect, each time the system admin add a new channel? If I do like that, I have to submit an app update also with the new in-app products?

My second question is,

*Can I implement this subscription plans without using iTunesConnect in-app purchases? Will Apple reject the app if I use a third party mechanism to implement subscriptions?

Other issue, I am facing is this app going to be a on Android platform also, In that case, if the user subscribe to a channel, he/she should able to use that subscription on any platform he/she uses.
Your thoughts and suggestions highly appreciated.

A: *

*Yes. Products need to be added to iTunes Connect. You don't need to submit an app update when you add new products - you are able to download the products using StoreKit from within your app. You'd then display them and allow the user to choose which product they would like to purchase and go from there.

*Yes. Apple only allow in-app purchases using their in-app purchase API.
You're going to have to work around this and come up with a solution for Android that works best for you.

A: IMHO your best option is to sell token packages (50 tokens, 100 tokens, etc) in-app purchase as non-renewal items. Then your users can use these tokens to add radio channels or whatever product you have. This way you can add new products easily and switching between android and ios is not a problem. We submitted an app using this in-app purchase model and it is approved.

A: *

*You don't need to upload a new application on Apple Store every time. You can fetch the product dynamically using store kit api. Then you can manage your view accordingly.

*Yes, Apple will reject your application. For more info refer In App Purchase Policy Section

*For the Android, You can store the expiration date in the backend database, which you can use to check on other platform. Android do have alternative to In App purchase called In App Billing, You can use that in Android.


text:
Q: Парсинг картинок на C# Есть небольшая проблема. При парсинге картинок, долго подгружаются изображения в PictureBox(разрешение 140х215, было бы чему грузится). Иногда быстро грузит, от чего зависит не знаю. Есть ли возможность подгружать их быстрее? Или же сохранять в кэш и после распределять по PictureBox'ам.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace ivi
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            GetHtmlAsync();
        }

        private async void GetHtmlAsync()
        {
            //Boxes
            PictureBox[] boxes = {
  pictureBox1, pictureBox2, pictureBox3, pictureBox4, pictureBox5, pictureBox6, pictureBox7, pictureBox8, pictureBox9, pictureBox10};
            Label[] labels = {
                label1, label2, label3, label4, label5, label6, label7, label8, label9, label10};

            //Parse
            var url = "https://www.ivi.ru/movies/horror";

            var httpClient = new HttpClient();
            var html = await httpClient.GetStringAsync(url);

            var htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);

            var ProductHtml = htmlDocument.DocumentNode.Descendants("ul")
                .Where(node => node.GetAttributeValue("class", "")
                .Equals("gallery posters-small mobile-has-titles js-criteo-gallery")).ToList();

            var ProductlistItems = ProductHtml[0].Descendants("li")
                .Where(node => node.GetAttributeValue("class", "")
                .Contains("poster")).ToList();
            int i = 0;

            //Список
            foreach (var ProducListItem in ProductlistItems)
            {
                //Название фильма
                var namefilm = ProducListItem.Descendants("span")
                    .Where(node => node.GetAttributeValue("class", "")
                    .Equals("name")).FirstOrDefault().InnerText.Trim();

                //Картинка фильма
                var picturefilm = ProducListItem.Descendants("img").FirstOrDefault().GetAttributeValue("src", "");

                //Logs
                LogText.Text += namefilm + '\r' + '\n';
                LogText.Text += picturefilm + '\r' + '\n';

                boxes[i].SizeMode = PictureBoxSizeMode.StretchImage;
                boxes[i].ImageLocation = picturefilm;
                labels[i].Text = namefilm;
                i++;
                if (i == 9)
                    break;
            }
        }

    }
}

A:
Не факт. Картинка весит в среднем по 12 КБ..подгружаю максимум 10 картинок. Не думаю, что сервак 120 Кбайт долго подгрузит.

Вопрос не в весе картинки, а в пинге сервера. Если по какой-то причине задержка на запрос увеличивается, то и 12 КБ будет долго качатся. Точнее качатся будет достаточно быстро, а вот начинать скачивание - долго.
Тебе нужно делать не последовательно запросы а в паралели. Это решит проблему скорости подгрузки. Открой для себя многопоточность и будет тебе счастье :)


text:
Q: Rows On Bootstrap modal-body have no gap? On my bootstrap modal, I have two rows but they are all bunched up with no spacing, between the rows.
Question: Why is the rows on the bootstrap modal-body have no gap between them and what would be the best solution to solve it?
Code Preview Click Here
Full Preview Click Here

HTML

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Click To Open Modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

    Parent Folder
    Refresh Page
    <button type="button" id="button-upload" class="btn btn-primary">Upload</button>
    <button type="button" id="button-folder" class="btn btn-default">Create Folder</button>
    <button type="button" id="button-delete" class="btn btn-danger">Delete</button>

    <input type="text" name="search" value="" placeholder="" class="form-control">

    <button type="button" data-toggle="tooltip" title="<?php echo $button_search; ?>" id="button-search" class="btn btn-primary"></button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

A: Whenever you use form-elements in bootstrap, its recommended that, you put that specific element inside a form-group class - this way, there is a margin-bottom of 15px below every element.

As per Bootstrap's form example: Wrap labels and controls in .form-group for optimum spacing.

.inline-group {
  display: inline-block;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Click To Open Modal
  </button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×
        </button>

Modal title

              Parent Folder

              Refresh Page

              <button type="button" id="button-upload" class="btn btn-primary">Upload</button>

              <button type="button" id="button-folder" class="btn btn-default">Create Folder</button>

              <button type="button" id="button-delete" class="btn btn-danger">Delete</button>

              <input type="text" name="search" value="" placeholder="" class="form-control">

    <button type="button" data-toggle="tooltip" title="<?php echo $button_search; ?>" id="button-search" class="btn btn-primary"></button>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

but, form-group is a block property, so, its gonna drop every form-element in new line, So either you can add another class like .inline-group and make it display:inline-block as shown

A: This is due to your use of .row in the modal. .row's has no padding or margin. If you not want to change your markup, then a little "hack" could be
.modal-body .row {
   padding-bottom: 16px;
}

the above and your code in a fiddle -> http://jsfiddle.net/zfLsmogx/


text:
Q: Desktop app with local and online database I want to create a Desktop App(Software), preferably in Java, which connects to a central MySQL DB on a local network whenever available.
I also want it to store and use a copy of the same DB when the central DB is not available, and sync whenever the central DB is available.
How can I store data locally, I mean which kind of database should I use for local database?
Also, are there any tools which speed up the Desktop App development?

A: Let's suppose that you will implement your solution in Java. You will need some classes (i.e. Data Access Obejcts, DAOs) in charge of interacting with the  database on the network and on a file based database embedded in the application (the "local" database).
What you need:

*

*A local database that you can ship with your application like H2 www.h2database.com, HSQLDB http://hsqldb.org/ or Derby db.apache.org/derby/.

*To develop your DAOs (using JDBC or Hibernate) in such a way that you can instantiate them with different drivers, URLs, login/pwd and use only SQL standard / functions supported both by MySql and by the local DBMS. In practice you must avoid using DB specific functions.

A: You can use Hibernate or JPA for example, they have quite a nice and easy integration with your application.


text:
Q: Set default order comments based on cart total in WooCommerce I want to add a default order comment (or pre populate the order_comments field) if the cart total is over 25 euros.
I already found this post about it: Add a custom order note programmatically in Woocommerce admin order edit pages

I almost got it working:
add_filter( 'woocommerce_checkout_fields' , 'set_default_order_comment' );
function set_default_order_comment( $order, $fields ) {
    // Targeting My account section
    if ( $order->get_total() > 25 ) {
        $fields['order']['order_comments']['default'] = 'Custom note!!';
    }
    return $fields;
}

At least, I think this should be it, but not quite right yet. I got this error:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function

How can create a simple function that checks the total amount in cart and if it is over 25 euro automaticly add an default order comment to the order?

A: It can be done like this.
/**
 * Add a custom note when the order total is above 25.
 *
 * @param int      $order_id Order ID.
 * @param WC_Order $order    Order object.
 */
function vkh_woocommerce_new_order_action( $order_id, $order ) {
    if ( $order->get_total() > 25 ) {
        $note = __( 'Write your note here!' );

        // Add the note
        $order->add_order_note( $note );
    }
}
add_action( 'woocommerce_new_order', 'vkh_woocommerce_new_order_action', 10, 2 );

A: The error is there because $order is not an argument of the woocommerce_checkout_fields filter hook, you should use get_cart_contents_total() instead
So you get:
function filter_woocommerce_checkout_fields( $fields ) {
    // Get cart total
    $cart_total = WC()->cart->get_cart_contents_total();

    // Greater than
    if ( $cart_total > 25 ) {
        $fields['order']['order_comments']['default'] = __( 'Custom note!', 'woocommerce' );
    }

    return $fields;
}
add_filter( 'woocommerce_checkout_fields' , 'filter_woocommerce_checkout_fields', 10, 1 );


text:
Q: Use sed to remove matching patterns I have a .txt file I need to clean, both a set of strings with a consistent pattern, as well as a set of matching strings. What I mean is as follows:
I want to delete everything contained within brackets and followed by a colon, such as [example]:
And then I also want to delete all instances of the word, example
To accomplish the first part, I am using the following:
sed -i new 's/\[.*]://g' rp.txt

Any ideas what I need to add to achieve the second part, which would also delete any strings which match *?
Example input:
[John]: Hello Mary.
[Mary]: Hello John.

Desired output:
Hello .
Hello .

Using terminal in Mac.

A: An answer to the revised question
As noted in a comment, the revised scenario requires two passes over the data.  The first pass determines what needs to be edited.  The second pass applies the edits.  The solution includes sort -u to eliminate duplicate entries for a given word in square brackets, so 'the first' pass actually involves two sed scripts.
Script
sed -e '/\[/!d' \
    -e 's/]:[^][]*$/]:/' \
    -e 's/^[^[]*//' \
    -e 's/[^][]*\(\[[^]]*]\):/\1/g' \
    -e 's/\[//g' \
    -e 's/]/\n/g' data |
sort -u |
sed -e '/^[    ]*$/d' \
    -e h \
    -e 's%.*%s/\\[&]://%p' \
    -e g \
    -e 's%.*%s/\\<&\\>//%' |
sed -f - data

Note that this supplies the sed script as the standard input with the -f - option.  Not all versions of sed necessarily support this.
If yours doesn't, you'll have to capture the generated sed script in a temporary file, feed that file to sed, and then remove it.  Or use process substitution.
Generated script
s/\[John]://
s/\<John\>//
s/\[Mary]://
s/\<Mary\>//
s/\[Name]://
s/\<Name\>//
s/\[like]://
s/\<like\>//
s/\[one]://
s/\<one\>//
s/\[something]://
s/\<something\>//

Note that this is using GNU sed, which supports both \b…\b and \<…\> to surround words (at least with -r; the \<…\> notation works without the -r option).  Mac OS X (BSD) sed does not support either, even under the -E option.
Sample data
[John]: Hello Mary.
[Mary]: Hello John.
[John]: Frank Johnson has a Name that is familiar.
[Mary]: A line [like]: this [one]: or [something]: similar should
be munged too.
[John]: A longer conversation with Mary that extends over several
lines which means that not all lines start with [Name]: but it
may actually be that when it occurs, [Name]: only actually
appears at the start of a line.
[Mary]: But it doesn't matter; we don't like this one, but
something similar should be OK, and should likely pacify the
Nameless ones, or someone acting all lonely on their behalf.

Sample output
 Hello .
 Hello .
 Frank Johnson has a  that is familiar.
 A line  this  or  similar should
be munged too.
 A longer conversation with  that extends over several
lines which means that not all lines start with  but it
may actually be that when it occurs,  only actually
appears at the start of a line.
 But it doesn't matter; we don't  this , but
 similar should be OK, and should likely pacify the
Nameless ones, or someone acting all lonely on their behalf.

It would be easy to add code to remove leading and trailing blanks and replace multiple blanks by singles.  A slightly more complex operation could remove blanks before punctuation such as comma or full stop (period).
Original answer

I want to delete everything contained within brackets and followed by a colon, such as [example]:
And then I also want to delete all instances of the word, example.

Deleting what's contained within square brackets that are followed by a colon is tricky because the open square bracket is a metacharacter.  Should the output include the empty []:?  That's what the question requests if read verbatim, but you probably don't want it.  So, you need one of:
-e 's/\[[^]]*]://g'        # Remove the square brackets and colon too
-e 's/\[[^]]*]:/[]:/g'     # Retain the square brackets and colon

The trick is that in a character class […], the ] must be the first character after the [ or [^ at the start of the character class.  On its own in a regex, ] is not a metacharacter; it becomes a metacharacter only after a [.
Note that both of these only match up to the first ].  If you use .* in place of [^]]*, you eliminate too much on:
a line [like]: this [one]: or [something]: similar.

Then, the other operation is simple unless you want to leave examples and unexampled untouched:
-e 's/example//g'      # Remove the string example when it appears

If you want to deal with word boundaries, you need to read the sed manual for your machine.  Different variants of sed have different options for marking word boundaries; some don't have any option for it.  When they do support it, \<example\> is one notation; \bexample\b is another.


text:
Q: How Read .text file line by line and the stored in database in sql server I have a module which upload report and then stored in database in sql server. Now I have come up with this code to read .txt file line by line.
Protected Sub ibtnTxtUpload_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
    Dim jsbldr As New StringBuilder
    Try
        If FileUpload1.HasFile Then

            Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)

            If Extension = ".txt" Then

                Dim Request_Val As String = ""

                Dim sFileName As String = FileUpload1.FileName

                'Read Line by Line

                Using sRead As New StreamReader(FileUpload1.PostedFile.FileName)
                    sFileName = sRead.ReadToEnd
                End Using

                Dim sFileLines() As String = sFileName.Split(vbCrLf)

                'Trim the line
                Dim dt As New DataTable("XmlData")

                dt.Columns.Add("Item", GetType(String))
                dt.Columns.Add("Description", GetType(String))
                dt.Columns.Add("Rev", GetType(String))
                dt.Columns.Add("Locator", GetType(String))
                dt.Columns.Add("UOM", GetType(String))
                dt.Columns.Add("Quantity", GetType(Double))

                Dim writer As New StringWriter
                Dim sline As String

                Dim i As Integer = 0
                Dim lStart As Boolean = False

                For Each sline In sFileLines

                    If sline.TrimStart.TrimEnd <> "" Then

                        If lStart = True Then

                            If sline.Substring(0, 10).TrimStart.TrimEnd <> "-------" Then

                                Dim newRow As DataRow = dt.NewRow

                                newRow("Item") = sline.Substring(0, 32).TrimStart.TrimEnd
                                newRow("Description") = sline.Substring(33, 53).TrimStart.TrimEnd
                                newRow("Rev") = sline.Substring(86, 3).TrimStart.TrimEnd
                                newRow("Locator") = sline.Substring(89, 26).TrimStart.TrimEnd
                                newRow("UOM") = sline.Substring(115, 3).TrimStart.TrimEnd
                                newRow("Quantity") = sline.Substring(124, 7).TrimStart.TrimEnd

                                dt.Rows.Add(newRow)

                            End If

                        End If

                        If sline.Substring(0, 32).TrimStart.TrimEnd = "Item" Then
                            lStart = True
                        End If

                        If sline.TrimStart.TrimEnd = "" Then
                            lStart = False
                        End If
                    End If

                Next

                'Execute SQL Stored Procedure
                Using cn As New SqlConnection(cls.strConnString)

                    Using cmd As New SqlCommand()

                        With cmd

                            .CommandType = CommandType.StoredProcedure
                            .CommandText = "USP_XML_SOH_ACCOUNT_MAINT"
                            .Parameters.Add("@XMLdata", SqlDbType.Xml) : .Parameters("@XMLdata").Value = writer.ToString
                            .Parameters.Add("@USR_ID", SqlDbType.VarChar, 30) : .Parameters("@USR_ID").Value = cls.GetUserName
                            .Parameters.Add("@FILE_NAME", SqlDbType.VarChar, 255) : .Parameters("@FILE_NAME").Value = sFileName
                            .Parameters.Add("@RET_VAL", SqlDbType.VarChar, 255)
                            .Parameters("@RET_VAL").Direction = ParameterDirection.Output

                            .Connection = cn
                            cn.Open()

                            .ExecuteNonQuery()

                            Request_Val = .Parameters("@RET_VAL").Value.ToString

                        End With

                    End Using

                End Using

                Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", "")

            Else

                jsbldr.Append("")
                Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", jsbldr.ToString)

            End If

        End If

    Catch ex As Exception

        jsbldr.Append("")
        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Javascript", jsbldr.ToString)

    End Try

End Sub

Here's the actual text file, in every end of the record there is an end symbol, I'm trying to put here but it can't capture.
  Item                          Description                                         Rev Locator                   UOM     Quantity
  -------------------------------------------------------------------------------   --- ------------------------- --- ------------
  604K23660                      KIT-FDR HCF MSI                                        ANG.2.0.0                 PC          1.00

  604K23670                      KIT FEEDER TM                                          ANG.2.0.0                 PC          3.00

  604K26021                      LEN ASSY                                               ANG.2.0.0                 PC          1.00

  CT200541                       AP/DCC4400/4300/3300/2200 Cartridge Toner              ANG.2.0.0                 Unt         3.00
                             (Magenta)
  CT200542                       AP/DCC4400/4300/3300/2200 Cartridge Toner (Yellow)     ANG.2.0.0                 Unt         6.00

 Subinventory: NEI-OLO    Description: Non-Equipment Inventory of Olongapo

  Item                          Description                                         Rev Locator                   UOM     Quantity
  -------------------------------------------------------------------------------   --- ------------------------- --- ------------
  CT350769                       DC-III 3007/2007 Drum Cartridge Standard                                         PC          7.00

  CT350851                       AP/DC-IV C5570/4470/3370/3371/2270 Long Life Drum                                PC          2.00
                             Cartridge (1 piece)

I put some condition in my For Each for the file. Now the condition read each line where to start reading and where to end and then add each row in my datatable, it loop until lStart = FALSE but I have an error on my condition if the record reached the ending symbol lSTart = False and then will loop again to find the "Item".
For Each sline In sFileLines

                If sline.TrimStart.TrimEnd <> "" Then

                    If lStart = True Then

                        If sline.Substring(0, 10).TrimStart.TrimEnd <> "-------" Then

                            Dim newRow As DataRow = dt.NewRow

                            newRow("Item") = sline.Substring(0, 32).TrimStart.TrimEnd
                            newRow("Description") = sline.Substring(33, 53).TrimStart.TrimEnd
                            newRow("Rev") = sline.Substring(86, 3).TrimStart.TrimEnd
                            newRow("Locator") = sline.Substring(89, 26).TrimStart.TrimEnd
                            newRow("UOM") = sline.Substring(115, 3).TrimStart.TrimEnd
                            newRow("Quantity") = sline.Substring(124, 7).TrimStart.TrimEnd

                            dt.Rows.Add(newRow)

                        End If

                    End If

                    If sline.Substring(0, 32).TrimStart.TrimEnd = "Item" Then
                        lStart = True
                    End If

                    If sline.TrimStart.TrimEnd = "" Then
                        lStart = False
                    End If

Here's my condition on the ending symbol, apparently the symbol can't capture here,but on visual studio it can.
If sline.TrimStart.TrimEnd = "" Then
                    lStart = False
                End If

After reading all the data, I need an XMLData to write this on the database in sql server. So I have a stored procedure for this. It is not working yet because the error on my For Each Condition.
I appreciate the suggestion and help, feel free to right my codes. Thanks

A: I picked to put them in a list but you could use an array. I don't need to show you how to insert values inside excel as you seem to know already. Skip the 2 first line or insert them as headers inside your excel file. concept is the same.
        Dim xstr As String = "007K88431                      GEAR ASSY-20/46                                        ANG.2.0.0                 PC          1.00"
        Dim xline As New List(Of String)
        xline.Add(Strings.Mid(xstr, 1, 30).Trim)
        xline.Add(Strings.Mid(xstr, 31, 56).Trim)
        xline.Add(Strings.Mid(xstr, 87, 26).Trim)
        xline.Add(Strings.Mid(xstr, 113, 4).Trim)
        xline.Add(Strings.Mid(xstr, 117).Trim)

A: That seems like a lot of surpfluous code for uploading a file!  To load a Text file or a CSV, which is the same thing, run the following script.
BULK INSERT TmpStList FROM 'c:\TxtFile1.txt' WITH (FIELDTERMINATOR = '","')


text:
Q: What does `pr -e` mean? From coreutils' manual about pr:

'-e[in-tabchar[in-tabwidth]]'
'--expand-tabs[=in-tabchar[in-tabwidth]]'

Expand tabs to spaces on input. Optional argument in-tabchar is the
  input tab character (default is the TAB character). Second optional
  argument in- tabwidth is the input tab character's width (default is
  8).

Does -e[in-tabchar[in-tabwidth]] mean to replace each in-tabchar with in-tabwidth number of whitespaces?
In the following two examples, why are a, b and c separated by one whitespace, while 1 and 3 by three whitespaces in the first example, and two whitespaces in the second example? Thanks.
$ printf "a:b:c\n1::3\n" | pr -t -e:2
a b c
1   3

$ printf "a:b:c\n1::3\n" | pr -t -e:1
a b c
1  3

A: pr -e does the same job as the expand command. It expands tabs in a similar way as your terminal emulator typically would. TAB is a control character which terminals understand as moving the cursor to the next tab-stop, it is meant for tabular formatting and alignment.
On most terminals, tab stops by default are every 8 columns. So sending them a TAB will have the same effect as sending a number of spaces ranging from 1 to 8 depending on the current cursor position:
 $ printf '%b\n' 'a\tb' 'abcde\tg'
 a       b
 abcde   g

The first tab moved the cursor 7 columns to the right, the second 3 columns to the right.
pr -e would replace those \t with as many spaces as necessary to have the same effect:
$ printf 'abcde\tg\n' | sed l
abcde\tg$
abcde   g
$ printf 'abcde\tg\n' | pr -te | sed l
abcde   g$
abcde   g

Note that GNU pr suffers from the same limitation as GNU expand in that it  assumes all characters are made of one byte and take one column to display.


text:
Q: Insert values only in defined sheets using NEXT function I have the following VBA to insert a value into each sheet except for Sheet1, Sheet5, Sheet8:
Sub Insert_Values()
Dim b As Worksheet
For Each b In Worksheets
    If b.CodeName <> "Sheet1" _
    And b.CodeName <> "Sheet5" _
    And b.CodeName <> "Sheet8" _
    Then
        Dim Range As Range
        Set Range = b.Range("B2:C4")
        b.Select
        Range.Value = 1
    End If
Next b

End Sub

All this works fine.

However, now I want to change the code so it works exactly the other way around.
Therefore, only in Sheet1, Sheet5 and Sheet8 the values are inserted.
I tried to go with this:
Sub Insert_Values()
Dim b As Worksheet
For Each b In Worksheets
    If b.CodeName = "Sheet1" _
    And b.CodeName = "Sheet5" _
    And b.CodeName = "Sheet8" _
    Then
        Dim Range As Range
        Set Range = b.Range("B2:C4")
        b.Select
        Range.Value = 1
    End If
Next b
End Sub

However, when i run this code nothing happens.
In none of the sheets the values are inserted.
What do I need to change in my code to make it work?

A: A sheet's code name can't be Sheet1 and Sheet5 and Sheet8. You want Or, not And.
A shorter way to do this could be the following:
For Each b in Array(Sheet1, Sheet5, Sheet8)
    b.Range("B2:C4").Value = 1
Next


text:
Q: Xcode 4.2.1: universal app runs on iPad but not on iPhone I am working on a universal application where I am stuck at one point. I was able to successfully launch my application both on iPhone and iPad but since 2-3 days, I am not able to launch my application on neither iPhone nor iPhone simulator but it runs smoothly on iPad/iPad simulator.
Also when I run my app choosing iPhone device it shows message like Running the App on iPhone simulator but I am not able to see any effect on my simulator. I am using Xcode 4.2.1 and I guess the issue is pertains to the same.

A: I have faced same problem. This probably happens when you replace the application with the newScheme/EditScheme by mistake.
Just carefully check when you run your application is there your application name appear. This will be immediate left at where you choose iPhone simulator or iPad simulator version.

A: I don't know whether it is a solution or not but got a way out by reinstalling the iOS Simulator.


text:
Q: Bundle knockout.js in ASP.NET Web Application - VS2013 I'm trying to add a bundle for Knockout in my application. From NuGet, I got two scripts:
knockout-3.0.0.debug.js and
knockout-3.0.0.js
I'm using the following code.
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                        "~/Scripts/knockout-{version}.js"));

For some reason, it will include the "debug" version:
<script src="/Scripts/knockout-3.0.0.debug.js"></script>

My question:
How can I get the non-debug version?
(I have tried running in both debug and release configurations, with the same result)
Best regards,
Thomas

A: Unless EnableOptimizations is true or the debug attribute in the compilation Element  in the Web.config file is set to false, files will not be bundled or minified. Additionally, the .min version of files will not be used,  the full debug versions will be selected. EnableOptimizations  overrides the debug attribute in the compilation Element  in the Web.config file
more info


text:
Q: Apache httpd version for Red Hat Enterprise Linux 4 Can anyone suggest the appropriate version for Apache httpd for RHEL 4 ? I know its not supported by RHEL anymore but the application demands this version. So, any leads will be highly appreciated.

A: If you're going to stick with RHEL 4 or any of its downstream rebuilds like CentOS 4, you have two choices:

*

*Use the version of the httpd package that came with the OS, 2.0.52. Despite the name, this is Apache.

*Build whatever you'd prefer to use from source. Assuming you build a current version and keep it up to date, this is better for security, but then the resulting combination can't really be said to be "RHEL 4" any more, which may bother the application that demands RHEL 4.


text:
Q: Remove padding from body bottom in HTML/CSS My Code

<!DOCTYPE html>

<meta charset="UTF-8">

This is Header of body

This is cntnt of body

This Footer of body

This is my Layout
In the above code you can notice padding after "This Footer of body" content.
I don't understand where this padding is coming from.
Due to this padding the page is slightly vertical scroll-able ( at least in Firefox ), The page is not supposed to be scroll able unless there is extra content.
How can i fix this.
EDIT
Even if you run snippet here, you can notice its slightly scroll able (vertically) which is undesired behavior.
EDIT 2
Color of the slight space in the bottom is same as of body tag.
So i am assuming, its either bottom padding of body or bottom margin of div with id body__

A: Try this code:

A: I got it solved
Initially i was using reset.css
Now i am using normalize.css
Though i still don't know what was causing this weird behavior


text:
Q: How to get logs of last hour in linux using awk command I have a logs file named source.log having time format like :-
Fri, 09 Dec 2016 05:03:29 GMT 127.0.0.1

and i am using script to get logs from a logs file for last 1 hour.
Script:-
awk -vDate=`date -d'now-1 hour' +[%d/%b/%Y:%H:%M:%S` '$4 > Date {print Date, $0}' source.log > target.log

But this script gives the result same as like the source file.
There is something wrong in time format matching, due to which it is not giving last hour records.

A: I know I'm late to help the OP, but maybe this answer can help anyone else in this situation.
First it's necessary to compare the whole date and not only the time part, because times near midnight.
Note that awk can only compare strings and numbers. Some awk implementations have the mktime() function that converts a specifically formatted string into UNIX timestamp, in order to make datetime comparisons, but it doesn't support any datetime format, so we can't use it.
The best way would be changing (if possible) the datetime format of the log entries, using 'YYMMDDhhmmss' datetime format or ISO format. In this way, comparing  two datetimes is simple as compare strings or numbers.
But let's assume that we can't change log entries date format, so we'll need to convert ourselves inside awk:
awk -vDate="`date -d'now-1 hour' +'%Y%m%d%H%M%S'`" '
    BEGIN{
        for(i=0; i<12; i++)
            MON[substr("JanFebMarAprMayJunJulAugSepOctNovDec", i*3+1, 3)] = sprintf("%02d", i+1);
    }
    toDate() > Date
    function toDate(){
        time = $5; gsub(/:/, "", time);
        return $4 MON[$3] $2 time;
    }' source.log

Explanation

*

*-vDate=... sets the Date awk variable with the initial datetime (one hour ago).

*BEGIN section creates an array indexed by the month abbreviation (it's especific to english)

*toDate() function converts the line's fields into a string with the same format as Date variable (YYYMMDDhhmmss).

*Finally when the condition toDate() > Date is true, awk prints the current line (log entry).


text:
Q: How to Pause Circular Reveal Animation I am using CircularRevealLibrary to make my header layout reveal. But what I want is to be able to stop the animation in half way. How to do this? Im using the following code.
int x = v.getRight(), y = v.getBottom(), startRadius = 0;
int endRadius = (int) Math.hypot(v.getWidth(), v.getHeight());

SupportAnimator animator = ViewAnimationUtils.createCircularReveal(v, x, y, startRadius, endRadius);
animator.start();

Im getting this

But I want to pause the animation in half way


text:
Q: Database.insert issue I have this piece of code,where i am trying to insert a record(which throws me duplicate issue).But i am trying to insert it using database.insert
EntitySubscription e = [select id from EntitySubscription where ParentId = 'a0CM0000005hyYAMAY' and SubscriberId= '005M0000005BqhVIAS'];
//e exists
EntitySubscription a = new EntitySubscription(ParentId = 'a0CM0000005hyYAMAY',SubscriberId= '005M0000005BqhVIAS');
List<EntitySubscription> collaborationBetMembers = new List<EntitySubscription>();
collaborationBetMembers.add(a);
Database.Saveresult[] saveResult;
saveResult = Database.insert(collaborationBetMembers);
system.debug(saveresult);

Now my issue is above code throws an exception
but when i specify false parameter explicityly in
saveResult = Database.insert(collaborationBetMembers,false);

It doesnt throw exception.
which is confusing because this documentation shows,its false my default..so my assumption is you dont need to write it explicitly.any idea why
http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#CSHID=apex_methods_system_database_saveresult.htm|StartTopic=Content%2Fapex_methods_system_database_saveresult.htm|SkinName=webhelp
Exception i get is below
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []:

A: This code does throw exception.
It is just handled and saved in SaveResult Object.
Quite similarly like try{} Catch(exception ex){} - here it also does throw exception but don't break session because you handle it.
Solution for you is to create method that will check SaveResult and look for error.
for(Database.SaveResult sr : saveResult){
    if (!sr.isSuccess()) {
        /** Some tasks if Error found **/
    }
}


text:
Q: Creating UI components dynamically in a Model-PassiveView-Controller In a GUI application, I am using an MVC with a Passive View, as described here.

This pattern is yet another variation on model-view-controller and model-view-presenter. As with these the UI is split between a view that handles display and a controller that responds to user gestures. The significant change with Passive View is that the view is made completely passive and is no longer responsible for updating itself from the model. As a result all of the view logic is in the controller. As a result, there is no dependencies in either direction between the view and the model.

So far, my Controller registers as a listener to existing, static components created by the Passive View itself at initialization. Now, the Controller needs to dynamically create a variable amount of UI components, depending on the Model (concretely, right now I am talking of a grid of checkboxes - the grid's dimensions is variable).
Here is where my hesitation lies:

*

*Should this dynamic UI creation code be implemented in the Controller? This would lead to less complex code resulting from keeping the View unaware of the Model, but a part of the presentation would be decided by the Controller...

*Should the View propose a generic, Model-independent way to create the UI components on demand, let the Controller use it and register listeners to the retrieved UI components? Here the Controller would have to convert back and forth between Model objects and generic objects (concretely, strings, integers, ...).

A: Whenever a view needs dynamic control creation, it tends to be for a collection of something. This means your Presenter/Controller does not need to create all of the logic, but call a method on the view which will create the controls.
On the View:
void PopulateUserOptions(IEnumerable<String> options)
{
    foreach (var item in options)
    {
        \\create and add your controls to the form
    }
}

This way the controller is expressing when a controll should be created etc, but leaving it to the view to decide how to do it.


text:
Q: Running puppeteer in Ruby on Rails controller kills the Docker container In Rails application I am trying to generate PDF basing on HTML page using Grover gem:
https://github.com/Studiosity/grover
PDF is generated properly, but just after that my Docker container is instantly killed. Problem doesn't occur in local environment, only inside docker.
Controller action:
   def generate_pdf
    grover = Grover.new('http://google.com', format: 'A4')

    pdf = grover.to_pdf

    send_data(pdf, filename: 'dummypdf.pdf', type: 'application/pdf')
  end

config/initializers/grover.rb
Grover.configure do |config|
  config.options = {
    format: 'A4',
    margin: {
      top: '5px',
      bottom: '10cm'
    },
    viewport: {
      width: 640,
      height: 480
    },
    prefer_css_page_size: true,
    emulate_media: 'screen',
    cache: false,
    timeout: 0, # Timeout in ms. A value of `0` means 'no timeout'
    request_timeout: 10000, # Timeout when fetching the content (overloads the `timeout` option)
    convert_timeout: 20000, # Timeout when converting the content (overloads the `timeout` option, only applies to PDF conversion)
    launch_args: ['--font-render-hinting=medium', '--no-sandbox', '--lang=ja', '--disable-dev-shm-usage', '--disable-gpu', '--disable-setuid-sandbox'],
    wait_until: 'domcontentloaded'
  }
end

Server log:
test_container_1           | 14:54:11 rails.1   | 2022-02-18 14:54:11.885970 I [7:puma server threadpool 003] {request_id: d9fc817c-1a51-4c25-80ac-da0f5c224f34} (4.743s) ProfilesController -- Completed #generate_pdf -- { :controller => "ProfilesController", :action => "generate_pdf", :params => { "kid_id" => "2" }, :format => "HTML", :method => "GET", :path => "/records/2/profile/generate_pdf", :status => 200, :view_runtime => 7.61, :allocations => 51203, :status_message => "OK" }
test_container_1           | 14:54:12           | exited with code 0
test_container_1           | 14:54:12 system    | sending SIGTERM to all processes
test_container_1           | 14:54:12           | exited with code 0
test_container_1           | 14:54:12 rails.1   | - Gracefully stopping, waiting for requests to finish
test_container_1           | 14:54:12 rails.1   | Exiting
test_container_1           | 14:54:12           | exited with code 0
test_container_1           | 14:54:12 rails.1   | terminated by SIGTERM
test_container_1           | 14:54:12 webpack.1 | exited with code 0

I will be grateful for any suggestions how to deal with this issue (I also tried Dhalang gem instead of Grover but the result was the same)


text:
Q: Create a Database Diagram based on MS SSAS Data Source View in a printable format in Visual Studio (2017 SSDT), if I open my MS SSAS cube, in the "Cube Structure" tab, under "Data Source View" I see all the tables/views that are used with all the relationships.
Since there are a lot of tables (with a lot of attributes) it is not possible to see all of them on the screen.
Is it somehow possible to export this Data Source View from Visual Studio or any other tool in a printable version (into jpg, pdf,... any format), to see all tables and attributes, and relationships?
Thank you.
BR, Tadej


text:
Q: Função para checar palíndromo Eu tenho o desafio de escrever um código para checar se um texto é um palíndromo ou não. Ainda não terminei o código, no momento, está assim:
function checkPalindrome(str) {
var direita = [];
for(var i = 0; i<str.length; i++){
    direita.unshift(str.charAt(i));
    }
    console.log(direita);
var esquerda = [];
for (var j=str.length-1; j>=0; j--){
    esquerda.push(str.charAt(j));
}
    console.log(esquerda);
    };

Até aqui eu quis ver se eu poderia ler uma string normalmente e ao contrário. Jogaria as duas leituras em 1 vetor cada para depois, compará-los e dizer se é palíndromo ou não.Enfim, ocorre que, ao testarmos no console do Google Chrome ou outro, ele executa só esquerda.push(str.charAt(j)); para os dois vetores, não lendo a expressão nos dois sentidos necessários. O que pode estar errado?
Um palíndromo é um texto que pode ser lido normalmente, ou invertido, que terá o mesmo significado. Exemplo: "reviver", "luz azul", "radar".

A: Podes reverter a string e comparar assim: str === str.split('').reverse().join('')

const testes = ["reviver", "luz azul", "radar", "manhã"];
const checkPalindrome = str => str === str.split('').reverse().join('');
const resultados = testes.map(checkPalindrome);
console.log(resultados);
// dá: true, false, true, false

Para ignorar espaços em branco podes fazer:

const testes = ["reviver", "luz azul", "radar", "manhã"];
const ignoreSpaces = str => str.split(' ').join('');
const checkPalindrome = str => ignoreSpaces(str) === ignoreSpaces(str.split('').reverse().join(''));
const resultados = testes.map(checkPalindrome);
console.log(resultados);
// dá: true, true, true, false

A: Se a função é para checar, e tem isso até no nome, é altamente provável que ela deva retornar se é verdadeiro ou falso. E mesmo que não fosse isso, só se ela dissesses explicitamente que deve imprimir é que deveria fazê-lo.
Não entendi o que está tentando fazer nesse código, mas se for o que está descrito na pergunta é mais simples, é só ir verificando o primeiro com o último, o segundo com o penúltimo, e assim por diante até chegar no meio, por isso só precisa ir até a metade. Qualquer um par que fure a condição já garante que não é um palíndromo e nem precisa continuar, somente será um palíndromo se passar por todas sem falhar.

function checkPalindrome(str) {
    for(var i = 0; i < str.length / 2; i++) if (str[i] != str[str.length - i - 1]) return false;
    return true;
}
console.log(checkPalindrome("radar"));
console.log(checkPalindrome("reviver"));
console.log(checkPalindrome("palindromo"));

Coloquei no GitHub para referência futura.
A pergunta não deixa claro se deve aceitar frases, se for necessário teria que eliminar os espaços antes. Aí pode-se adicionar um passo anterior, que é menos eficiente, ou terá que fazer uma algoritmo mais complexo que vai ignorando o espaço, o que é significativamente mais complexo e nem sei se será tão mais eficiente assim.

A: para que o palíndromo que comece com letras maiúsculas tb seja contado como true use:
function checkPalindrome(str) {
  return str.toLowerCase()==str.split('').reverse().join('').toLowerCase()
}

A: *

*Divida a palavra em um array, salvando-a em uma variável.

*Inverta o array.

*Monte de novo.

*Compare a string inicial com a reversa.

0.52 ms

function checkPalindrome(str){
  let reversed = str.split("").reverse().join("")
  return str === reversed
}

console.log(checkPalindrome("reviver"));

console.log(checkPalindrome("luz azul"));

console.log(checkPalindrome("manhã"));

Você pode simplificar ainda mais usando ES6:

function checkPalindrome(str){
  let reversed = [...str].reverse().join("")
  return str === reversed
}

 console.log(checkPalindrome("reviver"));

console.log(checkPalindrome("luz azul"));

console.log(checkPalindrome("manhã"));

0.30 ms

function checkPalindrome(str){
  let le = str.length;
  if (le === 0 || le === 1) {
    return true;
  }
  if (str[0] === str[le - 1]) {
    return checkPalindrome(str.slice(1, le - 1) );
  }
  return false;
};

    console.log(checkPalindrome("reviver"));

    console.log(checkPalindrome("luz azul"));

    console.log(checkPalindrome("manhã"));

0.20 ms
Nesta solução, iremos inverter a string, desta vez usando um loop for para verificar se as letras são exatamente as mesmas em ambos os lados.

*

*Declare uma variável com o comprimento da string.

*Declare um loop for, usando metade do comprimento da string como ponto de referência.

*Verifique se cada letra é igual ao seu equivalente do outro lado (medido com índice - 1).

function checkPalindrome(str) {
 let l = str.length;
 for (let i = 0; i < l/2; i++) {
  if (str[i] !== str[l - 1 - i]) {
   return false;
  }
 }
 return true;
}

        console.log(checkPalindrome("reviver"));

        console.log(checkPalindrome("luz azul"));

        console.log(checkPalindrome("manhã"));

Fonte
Veja mais soluções no StackOverflow em inglês

A: melhorando o codigo de uma resposta dada. Ela não pegava o caso da palavra começar sendo iguais, ela ja retornava true, mas nao necessariamente era um palíndromo!
const checkPalindrome = (str) => {
    let result = ''
    for (var i = 0; i<str.length / 2; i++ ) {
        if (str[i] !== str[str.length -i -1]) return result = false
        result = true
    }
    return result
}

console.log(checkPalindrome("palindromo"));
console.log(checkPalindrome("radar"));
console.log(checkPalindrome("reviver"));
console.log(checkPalindrome("antgretdna"));


text:
Q: Handling Timeouts In A Website SQLCommand Object and c# I'm using visual studio 2008 and sql server 2005 and everything is working just fine under normal use. However if a user is on a page for a while several minutes with no activity then clicks a button on occassion  the site throws the following exception ...
Procedure or Function "sp_name" parameter '@SomeParameterName', which was not supplied
I'm also encountering this error in Visual Studio while debugging the application, in otherwords run the site from visual studio then make some change to the html in VS save the changes and refresh the page.
The error is not consistent nor is the time the page has to stay idle in order for it to occur....
The current sql command object timeout is 30 secs and the website timeout is 30 minutes.
Has anyone else experienced this scenario and what is the fix as I would not except anything to go out of scope until the website timeout occurs ...
Any insight will be appreciated.

A: Seems you're passing a value (SomeParameterName) stored on the user session to procedure sp_name. When the user is inactive long enough his session expires so you lost the stored value and you end up passing null on SomeParameterName.


text:
Q: How to execute 'npm link' directly on install I have an internal project where I want to link a command to a file with bin. Like expect this package.json:
{
  "name": "my-project",
  "bin": {
    "cli-name": "./bin/my-executable.js"
  },
  "dependencies": {
    "node-red": "^1.0.0"
  }
}

When executing npm install, all dependencies will be installed, and the bin configuration of node-red will be created too.
But my own bin will be completely ignored. It's not possible to use cli-name in cmd. It's necessary to execute npm link too, in a second step. Then cli-name will be available as command in console. I've even tried to use a postinstall script of npm with npm link in it, but then I got a loop ...
Is there a way to do this in one step on npm install?

A: You can try changing you package.json to something like this:
{
  "name": "my-project",
  "script": {
    "cli-name": "./bin/my-executable.js",
    "postinstall": "npm run cli-name"
  },
  "dependencies": {
     "node-red": "^1.0.0"
  }
}

And just run:
npm install

A: There seems actually no build-in way to execute this tasks togeter automatically. So I've created an request for this feature directly to npm. It seems that a new command like npm il could be implemented.
I will updates this here when this or another way is available.
https://github.com/npm/npm/issues/15999

A: npm-link is for a different purpose really. The moment you do npm install, you should be able to use it in the command line already.
npm link is for linking your current development folder to the installed directory of your package. This is so that, as you are making changes in your development folder, it is been automatically avaliable on the cli and you do not have to re-install.
After installing, try going to usr/local/bin <- This is where it should be. if you cannot find my-executable.js here. Then something is wrong along that installation process.

A: In order to run a global binary (bin) module you need to install it globally.
npm -g install
https://bretkikehara.wordpress.com/2013/05/02/nodejs-creating-your-first-global-module/
Another option (if you're on linux) is to use $(npm bin)/<module> if it is not installed globally.

A: You can create a script in your package.json to do both tasks in one command like so:
{
  "name": "my-project",
  "bin": {
    "cli-name": "./bin/my-executable.js"
  },
  "scripts": {
    "install-link": "npm install && npm link my-project"
  },
  "dependencies": {
    "node-red": "^1.0.0"
  }
}

Then just run npm run install-link, and it will run both commands.

A: Try npm ln. An alias to npm link by npm documentation, worked for me on PowerShell 5.
npm-link documentation.

A: Surprised that all the other answers are basically wrong. To avoid a loop, simply:
"preinstall": "npm link"


text:
Q: Where does the tradition of shell prompts in code snippets come from? Most code samples I see that demonstrate shell code preface each command with $. Having a prefix makes sense, but I'm confused as to why $ is used in particular. Some other symbol, like !, that can be copied and pasted into a prompt without affecting the command's execution makes far more sense to me. So where does this notation come from?

A: $ is the default prompt prefix for a non-escalated bourn or sh shell on most *nix systems.  It signifies that the code exemplified should be executed using one of those associated shells.  zsh and csh have % as a prefix.  The fish shell uses >.  Putting the prefix is simply a quick way to let the reader know what shell the command is destined for.


text:
Q: VB.NET check if form is focused I can't seem to find the answer to this seemingly simple question anywhere D:
I want to detect if a form/window is focused so that I can only flash the window If Not Focused, here is the bit of the code:
If Me.Focused = False Then ' Doesn't work D: please fix
    Dim flash As New FLASHWINFO
    flash.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(flash) '/// size of structure in bytes
    flash.hwnd = MyBase.Handle '/// Handle to the window to be flashed
    flash.dwFlags = FLASHW_ALL '/// to flash both the caption bar + the tray
    flash.uCount = 5 '/// the number of flashes
    flash.dwTimeout = 1000 '/// speed of flashes in MilliSeconds ( can be left out )
    '/// flash the window you have specified the handle for...
    FlashWindowEx(flash)
End If

Is there a simple way to make this work?

A:   Private Sub Form1_LostFocus(sender As Object, e As System.EventArgs) Handles Me.LostFocus
    Dim flash As New FLASHWINFO
    flash.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(flash) '/// size of structure in bytes
    flash.hwnd = MyBase.Handle '/// Handle to the window to be flashed
    flash.dwFlags = FLASHW_ALL '/// to flash both the caption bar + the tray
    flash.uCount = 5 '/// the number of flashes
    flash.dwTimeout = 1000 '/// speed of flashes in MilliSeconds ( can be left out )
    '/// flash the window you have specified the handle for...
    FlashWindowEx(flash)

  End Sub


text:
Q: Force to using NavigationController? I'm new to iOS. I've read lot of tutorial and I see that all most of example using NavigationController in multiple view. We always force to use NavigationController?
If I have a single view, on my view I have a button1, and when I click on that button it's will open a new view. I also have another button2, when I click on button2, a dialog display on original view. So in this case, I still have to use NavigationController? Another controller I can use?
Thanks in advance!

A: It's mainly for aesthetic reasons and continuity of user experience that you use navigation controller. You of course can use buttons, but navigation controller is more like the standard for multiple views.

A: Navigation controller is not an only option... If u made the flow of your app in such a way that it requires navigation,then only u should use navigation controller.. otherwise there is an another option like presentModalViewController,and u can also use hide/show view while showing dialog in your original view. If you can elaborate your question ,then i might help you.

A: It is not necessary to use the Navigation controller..You can give similar kind of side transition(LEFT to Right or right to left) using Quartz-core animation effect.
Home *homeObject=[[Home alloc] init];
CATransition *animation = [CATransition animation];
[self presentModalViewController:homeObject animated:NO];
[animation setDuration:0.40];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromLeft];
[[homeObject.view layer] addAnimation:animation forKey:@"SwitchToView1"];
[homeObject release];


text:
Q: Root partition smaller than partition size I have Ubuntu installed on VMware. Previous user expanded the size of the partition (I believe by using GParted in boot mode). Now I get warning about free space left on root partition. Unfortunately, it shows everything is 80G except in disk usage tool.
> sudo lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,LABEL
NAME                  FSTYPE        SIZE MOUNTPOINT                      LABEL
loop0                 squashfs    132,2M /snap/1password/66
loop1                 squashfs     83,3M /snap/1password/61
loop2                 squashfs        4K /snap/bare/5
loop3                 squashfs     10,2M /snap/canonical-livepatch/104
loop4                 squashfs     55,4M /snap/core18/2128
loop5                 squashfs     10,2M /snap/canonical-livepatch/105
loop6                 squashfs    208,4M /snap/code/75
loop7                 squashfs       13M /snap/dmd/102
loop8                 squashfs    216,3M /snap/code/76
loop9                 squashfs      219M /snap/gnome-3-34-1804/72
loop10                squashfs     99,3M /snap/core/11743
loop11                squashfs     55,5M /snap/core18/2074
loop12                squashfs      167M /snap/gitkraken/182
loop13                squashfs      219M /snap/gnome-3-34-1804/66
loop14                squashfs    162,9M /snap/gnome-3-28-1804/145
loop15                squashfs     65,2M /snap/gtk-common-themes/1519
loop16                squashfs     65,1M /snap/gtk-common-themes/1515
loop17                squashfs    164,8M /snap/gnome-3-28-1804/161
loop18                squashfs        7M /snap/dub/53
loop19                squashfs     32,3M /snap/snapd/13170
loop20                squashfs    346,9M /snap/wine-platform-runtime/249
loop21                squashfs    322,8M /snap/wine-platform-6-stable/8
loop22                squashfs     61,4M /snap/prospect-mail/11
loop23                squashfs    303,1M /snap/wine-platform-5-stable/16
loop24                squashfs    126,6M /snap/slack/44
loop25                squashfs    303,1M /snap/wine-platform-5-stable/18
loop26                squashfs       51M /snap/snap-store/547
loop27                squashfs    168,1M /snap/postman/147
loop28                squashfs     32,4M /snap/snapd/13270
loop29                squashfs       51M /snap/snap-store/518
loop30                squashfs      5,5M /snap/notepad-plus-plus/292
loop31                squashfs    322,8M /snap/wine-platform-6-stable/5
loop32                squashfs      5,7M /snap/notepad-plus-plus/307
loop33                squashfs    127,2M /snap/slack/46
loop34                squashfs     99,4M /snap/core/11606
loop35                squashfs    346,9M /snap/wine-platform-runtime/250
loop36                squashfs    165,9M /snap/gitkraken/183
loop37                squashfs    168,1M /snap/postman/148
loop38                squashfs     64,9M /snap/prospect-mail/16
sda                                  80G
├─sda1                vfat          512M /boot/efi
├─sda2                                1K
├─sda5                ext4          731M /boot
└─sda6                crypto_LUKS  78,8G
  └─sda6_crypt        LVM2_member  78,8G
    ├─vgubuntu-root   ext4         77,8G /
    └─vgubuntu-swap_1 swap          980M [SWAP]
sr0

A: Looks like your partition is about 80GB but your filesystem is about 30 GB. If you are using ext4, ext3 or ext2 there is a simple way to extend the filesystem using the resize2fs command. You are using LVM so this guide below should solve your problem. You only need to do the resize2fs step but there are a number of other commands there that will help you understand the LVM setup on your machine
https://www.tecmint.com/extend-and-reduce-lvms-in-linux/
Since this is performing significant disk operations you should backup anything you cannot afford to loose.


text:
Q: discord.ext.commands.errors.CommandNotFound how can I fix it? i'm making a discord bot for my server, but my codes continue to give me this error. My goal is to have a class with some commands, but I always get the error "discord.ext.commands.errors.CommandNotFound". These are my code:
import discord
from discord.ext import commands

class General_commands(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def message(self, ctx:commands.context, *, channel: discord.VoiceChannel):
        await ctx.channel.send('message')

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(command_prefix='-', intents=intents)

@bot.event
async def on_ready():
    print('Logged in as {0.user}'.format(bot))

bot.add_cog(General_commands(bot))

bot.run(token)

Do you know what I do wrong? If something is unclear you can simply ask :)
I've already tried to use examples saw in github but I didn't menage to solve my problem :(
If I put the command outside the function, with some adjustments it works, but would preferably have it in the class.

A: Cog loading became asynchronous in 2.0, your code is very outdated. Read the migration  guide: https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous

ext.commands.Bot.add_cog() must now be awaited.


text:
Q: Do HDs, Thumb Drives or Dvds Have The Longest Shelf Life I'm trying to backup fairly sensitive data.
Which of the three has the longest shelf life?

*

*Hard Drives(Regular)

*Thumbdrives

*Dvds/Blurays

There are obvious cost and size differences.
Related
DVD RW: Are they still relevant for backups?

A: I would have to say hard drives because CDs get scratched easy. I've seen data on USB sticks corrupt a few times. Usually that takes a while, but they are not as stable as hard drives. And as far as hardware that has been properly taken care of, I've only seen 1 hard drive die. (And that was an old one) EDIT: I'm just going off of what I've seen happen. And external hard drives are better for backing up data, but its not impossible to do with regular ones. If you use a regular one, just be careful about what you do so you don't break it.


text:
Q: DataTable.AsEnumerable().ToList(); min/max return invalid if data is int var list = ProcessedInformationTable.AsEnumerable().ToList();
                        var minValue = list.Min(v => v["Rank"]);
                        var maxValue = list.Max(v => v["Rank"]);

In the code above if I had the values of

*ColumnA|Rank

*Heart|9

*Lung|10
minValue will return as 10 and maxvalue will return as 9.  My guess is because it's treated as a string even though every value is an int.  Is there a way around this?

A: Don't create a List<T> from the DataTable, that just doubles the required memory without any benefit. Use Linq-To-DataSet which is a subset of Linq-To-Objects.
Either the column is already of type int, then you have to cast it accodingly or it's actually string. Then you have to change that or use ìnt.Parse first:
var rows = ProcessedInformationTable.AsEnumerable();
int minValue = rows.Min(r => r.Field<int>("Rank"));
int maxValue = rows.Max(r => r.Field<int>("Rank"));

If it's string:
int minValue = rows.Min(r => int.Parse(r.Field<string>("Rank")));
int maxValue = rows.Max(r => int.Parse(r.Field<string>("Rank")));

A: Provided that your Rank column is an integer and doesn't contain nulls:
var list = ProcessedInformationTable.AsEnumerable().ToList();
var minValue = list.Min(v => (int)v["Rank"]);
var maxValue = list.Max(v => (int)v["Rank"]);

v["Rank"] is most likely casting as a string using the built-in object.ToString() when evaluating.


text:
Q: Inspec/Serverspec grabbing multiple stdouts from command and describing them I'm attempting to create an inspec control that searches through every line that starts with kernel (and ignores whitespace) in /boot/grub/grub.conf and then checking every line to see if it has 'nousb' somewhere in the line. I'd like it to return a failure if nousb is not found.
My issue is that I cannot figure out a way to grab/describe multiple stdouts from the grep in the event more than one line starts with kernel. Is that something I can accomplish using .each? Here is my code:
control 'os-disable-usb-pcmcia' do
  impact 0.5
  title 'Disable USB and PCMCIA Devices'
  desc "ensure default kernel in grub has 'nousb' option"

  output = command('egrep "^[[:space:]]*kernel" /boot/grub/grub.conf')
  describe output do
    its('stdout') { should match /^\s*kernel[^#]*nousb\b/ } # match nousb anywhere in the 'kernel' line
  end
end

Edit for clarification.
Say I have these lines in my conf file
kernel 1 nousb
kernel 2
kernel 3
kernel 4

the test will consider it passing because the initial one matched what it was looking for despite multiple kernel lines not having the nousb requirement.

A: Use a file resource and Ruby's RegExp matching (as you are already doing).
describe file('/boot/grub/grub.conf') do
  its(:content) { is_expected.to match /whatever/ }
end

EDIT to show how to do this with Ruby code instead of fancy regexps:
describe file('/boot/grub/grub.conf') do
  it do
    # Get all the lines in the file.
    lines = subject.content.split(/\n/)
    # Check for any line that _doesn't_ match the regexp.
    without_nousb = lines.any? {|line| line !~ /^.*?kernel.*?nousb.*?$/ }
    # Make a test assertion.
    expect(without_nousb).to be false
  end
end

A: Test Your Parse Results, Not a Content Match
You have to write some code inside the block that will parse your grub.conf file and ensure that there is a nousb command for each record. You might also try the Augeas lens for grub to validate the grub.conf for you. For example:
describe 'validate kernel parameters' do
  it 'should include a "nousb" parameter on each line' do
    # 1. parse your file however you like, then
    # 2. store result as a Boolean.
    expect(result).to be_true
  end
end

Check Running Kernel
Alternatively, if you only care about the result of the running kernel, you can check the value with something similar to:
# 1. read the remote's /proc/cmdline however you like, then
# 2. evaluate your match.
expect(command_line_contents).to match /\bnousb\b/

A: I finally got the question. Since you want to check all kernels:
output = command('egrep "^[[:space:]]*kernel" /boot/grub/grub.conf')
ok = output.split("\n")
           .group_by { |line| line[/(?<=kernel )(\S*)/] }
           .map { |kernel, lines| lines.any? { |line| line =~ /nousb/ } }
           .all?

describe output do
  # OK must be TRUE
end

Here we:

*

*split the output by lines

*group lines by kernel name (regexp might require adjustment)

*map the hash { kernel ⇒ lines } to true/false, depending on whether nousb is presented

*check that all kernels have this nousb line.

The code above is aware of grub.cfg might contain many lines for the same kernel.
Hope it helps.


text:
Q: Python selenium clicking a button I am trying to write a python script to automatically download csv using the "Download CSV" button from the below link:
https://chartink.com/screener/copy-supertrend-negative-breakout-1103
from selenium import webdriver
import pandas as pd

DRIVER_PATH = r"C:\Users\u123456\Downloads\chromedriver\chromedriver.exe"
d = webdriver.Chrome(executable_path=DRIVER_PATH)
d.get('https://chartink.com/screener/copy-supertrend-negative-breakout-1103')
download_button = pd.read_html(d.find_element_by_class_name('btn btn-default buttons-excel buttons-html5 btn-primary'))[0]
#table = pd.read_html(d.find_element_by_id('DataTables_Table_0').get_attribute('outerHTML'))[0]
print(download_button)

I am not finding any clue on how to click that button and download it to local drive. Any help would be highly appreciated.
Edit: I tried the below code and got it working, Now I would like to know if we can find the filename and load it into pandas dataframe.
element = d.find_element_by_link_text("Download csv")
element.click()

Thanks,
mc

A: To click on the element Download csv you can use either of the following Locator Strategies:

*

*Using link_text:
driver.find_element_by_link_text("Download csv").click()

*Using css_selector:
driver.find_element_by_css_selector("a.btn.btn-default.buttons-excel.buttons-html5.btn-primary[value='Download backtest']").click()

*Using xpath:
driver.find_element_by_xpath("//a[@value='Download backtest' and text()='Download csv']").click()

Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

*

*Using LINK_TEXT:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Download csv"))).click()

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.btn-default.buttons-excel.buttons-html5.btn-primary[value='Download backtest']"))).click()

*Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@value='Download backtest' and text()='Download csv']"))).click()

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: creating a cpio archive ingnoring modification time of files how can I create a cpio archive by ignoring the modification times of the files (or imposing them at a known value)?
The context is as follows: in the build process of an embedded project some "intermediate" files are stored in a cpio archive. They will be used by the FW of a microcontroller, so neither uid/gid nor modification time is involved. My constraint is that I must be able to rebuild a certain version at any time, ensuring that I always get the exact same binary (bit by bit). But if the modification time is also stored in the cpio this constraint is no longer met.


text:
Q: Next.js Prop `href` did not match. Server: "/" Client: "/#page3" Hi I'm developing a web page using Next.js and using hash to make it work like fullpage.js.
(fullpage.js : https://alvarotrigo.com/fullPage/ko/#page2)
It's a problem when I refresh the browser and in my opinion, it's because the route path on the server is '/', but on the browser is '/#page3'.
How do I remove this warning?

The code below is to push the path to the router when scrolling down

and when the menu is clicked to change language, the hash value is pushed to the router and the browser is refreshed.
router.push(router.asPath, router.asPath, { locale: 'en' });
router.reload(router.asPath);


text:
Q: Can't get recurring GCal event to show up in FullCalendar with rrule I'm making calls to the Google Calendar API to retrieve event data. I want to display the events in a FullCalendar in my app. While normal events show up, I'm now working on getting recurring events to show up with all their instances.
Per the FullCalendar documentation, I'm using the rrule plugin. I have an event with data like this:
{
    "id": "6cvikr7n7g7ctler24dr1lgkjf",
    "title": "Test recurring event",
    "backgroundColor": "#9fe1e7",
    "borderColor": "#9fe1e7",
    "rrule": {
        "freq": "daily",
        "dtstart": "2022-09-14T15:00:00.000Z",
        "interval": 1,
        "until": "2022-12-31"
    },
    "duration": "00:30"
}

But this is not showing up in the FullCalendar. It ought to be an event that happens every day, starting 9/14/22, at 11am ET = 3pm UTC.
Am I missing something about how rrule and FullCalendar work?
Bonus: are there any tools that help translate a Google Calendar event's recurrence rules to a working rrule configuration?

A: Dumb mistake on my part - I forgot to include rrulePlugin in the config for FullCalendar, i.e.:
<FullCalendar
...
    plugins={[ timeGridPlugin, rrulePlugin ]}
...


text:
Q: Access and modify values within an array in a HashMap: Typescript I have two hashmaps which both have a string as a key and an array of strings as a value. I need to modify one of the values in one HashMap based on the values in the other.
So basically I have an HashMap called genericSlots and another called bookedSlots. If the bookedSlots HashMap values are also contained in the genericSlots values I would like those values to be removed from the genericSlots HashMap
I have tried doing this as shown in the code below but the values in the genericSlotsAsArray are not being removed.
Here is the code:
  checkForBookedSlots(date:string){

  let genericSlots = new Map<string,string[]>();
  let bookedSlots = new Map<string,string[]>();

  let bookedArray = ['09:00','11:00']
  let slotTimes = ["09:00", "09:30","10:00", "10:30", "11:00", "11:30", "12:00", "12:30","13:00","13:30", "14:00","14:30","15:00","15:30","16:00","16:30"]

  bookedSlots.set("09/10/2021",bookedArray)
  genericSlots.set(date,slotTimes)

  let genericSlotsAsArray = Array.from(genericSlots.values());
  let bookedSlotsAsArray = Array.from(bookedSlots.values())

  for(let i=0;i< genericSlotsAsArray.length; i++){
      for(let j=0;j<bookedSlotsAsArray.length;j++){
          let mValue = bookedSlotsAsArray[j];
          if(mValue === genericSlotsAsArray[i]){
              const index = genericSlotsAsArray.indexOf(mValue, 0)
              genericSlotsAsArray.splice(index, 1)
          }

      }
  }
  console.log('Generic Slots -> ', genericSlotsAsArray)
  console.log('Booked Slots -> ',  bookedSlotsAsArray) }

Expected output:
Generic Slots - > ["09:30","10:00", "10:30","11:30", "12:00", "12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30"]

Booked Slots -> ["09:00","11:00"]

Actual Output:
Generic Slots - > ["09:00","09:30","10:00", "10:30","11:00","11:30", "12:00", "12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30"]

Booked Slots -> ["09:00","11:00"]

A: You can do something like this
checkForBookedSlots(date: string) {
    let genericSlots = new Map<string, string[]>();
    let bookedSlots = new Map<string, string[]>();

    let bookedArray: string[] = ['09:00', '11:00'];
    let slotTimes: string[] = ['09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30'];
    let genericSlotsArray: string[] = slotTimes.filter(slot => !bookedArray.includes(slot));

    genericSlots.set(date, genericSlotsArray);
    bookedSlots.set(date, bookedArray);

    console.log('Generic Slots -> ', genericSlotsArray);
    console.log('Booked Slots -> ', bookedArray);
}


text:
Q: How to avoid invalid certificate warnings when browsing to my custom local HTTPS server? What I'm doing: running a simple HTTPS server in my PC, browsing to localhost, and trying to avoid the warning by installing a temporary certificate.
The following code is based on what I found in this example of the QtHttpServer library:
https://github.com/qt-labs/qthttpserver/blob/master/tests/auto/qhttpserver/tst_qhttpserver.cpp
The library was built and tested with no problems.
This is my code:
#include <QCoreApplication>
#include <QtHttpServer/QtHttpServer>

static const char g_privateKey[] = R"(-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDykG51ZjNJra8iS27g3DJojH1qG8C3Z+Avo5U6Qz6NkOsjvr22
gXqOS4uwVUXdCAKxsP0Wwn2zGz5vxGpLPVKtbAmaqHYZuipMG/Qun3t+QYBgR+9t
lmHdI8TNP2Om8stDO5uQyBH7DcMjPyIgpfc8fBoNLhCn4oC2n6JK9EMuhQIDAQAB
AoGAUHTLzrEJjgTINI3kxz0Ck18WMl3mPG9+Ew8lbl/jnb1V4VNhReoIpq40NVbz
h28ixaG5MRVt8Dy3Jwd1YmOCylHSujdFQ2u0pcHFmERgDS2bOMwMTRoFOj2qgMGS
9SM+iXlPY5AQY8nEg7rLjMSfaC/8Hq4RXpkj4PeHh6N7AzkCQQD++HzM3xBr+Gvh
zco9Kt8IiKNlfeiA5gUQq1UPJzcWIEgW1Tgr5UzMUOcZ0HfYwhqL3+wMhzN4sba+
1plB1QRXAkEA84sfM0jm9BRSqtYTPlhsYAmuPjeo24Pxel8ijEkToAu0ppEC6AQ3
zfwZD0ISgaWQ7af5TN/RCsoNVX79twP6gwJBANbtB+Z6shERm38ARdZB6Tf8ViAb
fn4JZ4OhqVXYrKrOE3aLzYnTBGXGXMh53kytcksuOoBlB5JZ274Kj63arokCQFPo
9xMAZzJpXiImJ/MvHAfqzfH501/ukeCLrqeO9ggKgG9zPwEZkvCRj0DGjwHEPa7k
VOy7oJaLDxUJ7/iCkmkCQQCtTLsvDbGH4tyFK5VIPJbUcccIib+dTzSTeONdUxKL
Yk+C6o7OpaUWX+ikp4Ow/6iHOAgXaeA2OolDer/NspUy
-----END RSA PRIVATE KEY-----)";

static const char g_certificate[] = R"(-----BEGIN CERTIFICATE-----
MIICrjCCAhegAwIBAgIUcuXjCSkJ2+v/Rqv/UHThTRGFlpswDQYJKoZIhvcNAQEL
BQAwaDELMAkGA1UEBhMCRlIxDzANBgNVBAgMBkZyYW5jZTERMA8GA1UEBwwIR3Jl
bm9ibGUxFjAUBgNVBAoMDVF0Q29udHJpYnV0b3IxHTAbBgNVBAMMFHFodHRwc3Nl
cnZlcnRlc3QuY29tMCAXDTE5MDkyNjA4NTc1MloYDzIyNTUwMzEzMDg1NzUyWjBo
MQswCQYDVQQGEwJGUjEPMA0GA1UECAwGRnJhbmNlMREwDwYDVQQHDAhHcmVub2Js
ZTEWMBQGA1UECgwNUXRDb250cmlidXRvcjEdMBsGA1UEAwwUcWh0dHBzc2VydmVy
dGVzdC5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPKQbnVmM0mtryJL
buDcMmiMfWobwLdn4C+jlTpDPo2Q6yO+vbaBeo5Li7BVRd0IArGw/RbCfbMbPm/E
aks9Uq1sCZqodhm6Kkwb9C6fe35BgGBH722WYd0jxM0/Y6byy0M7m5DIEfsNwyM/
IiCl9zx8Gg0uEKfigLafokr0Qy6FAgMBAAGjUzBRMB0GA1UdDgQWBBTDMYCcl2jz
UUWByEzTj5Ew/LWkeDAfBgNVHSMEGDAWgBTDMYCcl2jzUUWByEzTj5Ew/LWkeDAP
BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4GBAMNupAOXoBih6RvuAn3w
W8jOIZfkn5CMYdbUSndY/Wrt4p07M8r9uFPWG4bXSwG6n9Nzl75X9b0ka/jqPjQ3
X769simPygCblBp2xwE6w14aHEBx4kcF1p2QbC1vHynszJxyVLvHqUjuJwVAoPrM
Imy6LOiw2tRTHPsj7UH16M6C
-----END CERTIFICATE-----)";

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);
    QHttpServer httpServer;

    httpServer.route("/", []() { return "Hello world"; });

    httpServer.sslSetup(QSslCertificate(g_certificate),
                        QSslKey(g_privateKey, QSsl::Rsa));

    if (httpServer.listen(QHostAddress("127.0.0.1"),443)) {
        qDebug() << "Server started";
        return a.exec();
    }
    else {
        qDebug() << "Server failed to start";
        return 0;
    }
}

The Private Key and Certificate values were copied literally from the QtHttpServer example.
The server starts, and I'm able to browse to localhost (or qhttpsservertest.com, which I've created an alias for in the etc file just to be sure it matches the cert's CN).
However, as expected, a warning is shown and I need to confirm before actually browsing anything.
I know I can add a trusted certificate in the OS (Windows in my case). Other programs, like Fiddler or Burp Suite need something similar to work transparently with the browsers.
But I don't know what to do here. I just copied the certificate content in a .cert file, and successfully imported it with certmgr but I keep getting the same warnings when I browse to my custom server. Why?
-- EDIT --
It seems this has nothing to do with Qt or QtHttpServer.
I tested the certificate with Nginx, and still getting the same browser warning (ERR_CERT_COMMON_NAME_INVALID).
FYI, the nginx.conf file:
# ...
http {
    # ...
    server {
        listen       443 ssl;
        server_name  qhttpsservertest.com;
        ssl_certificate     qhttpsservertest.pem;
        ssl_certificate_key qhttpsservertest.key;
        # ...
    }
    # ...
}

This opens the question to a more general public.
What kind of manipulation I need to do in my system to get rid of these warnings?

A: Fortunately, I found a concise step-by-step guide here.
I was ignoring the first two steps. I was adding the signed certificate to Trusted Root.
I hope this question helps another newbie in the future.


text:
Q: Is it OK to combine several email records (GSuite + Amazon SES)? Just to be clear, is it ok for me to do this:

*

*Continue using Gmail (GSuite) for my business domain (email address);

*Also allow Amazon SES to work using the same email (by adding MX, TXT and CNAME) records?

In other words, can I have both and will both work w/out issues?
Thanks

A: You can do this, with no issues at all.  We do this regularly; all our inbound and day-to-day user mail is handled by GSuite, but we send marketing and transactional mails through SES.
When you validate your domain with SES you'll receive a set of DNS records to insert in to your zonefile. One of those will be an MX record that will look something like
10 inbound-smtp.regionInboundUrl.amazonaws.com

To have GSuite or another provider handle your incoming (and some outgoing) mail, simply do not create that MX record.
The other DNS records (DKIM, SPF etc) are best practice for sending emails as, at a very high level, they prove to the receiving server that the server that is delivering the message to them is authorized by the domain to send mail on its behalf.
From a practical perspective, sending mail from many places isn't really an issue, but receiving mail at multiple places isn't really possible.


text:
Q: Unable to start Kudu master While starting kudu-master, I am getting the below error and unable to start kudu cluster.
F0706 10:21:33.464331 27576 master_main.cc:71] Check failed: _s.ok() Bad status: Invalid argument: Unable to initialize catalog manager: Failed to initialize sys tables async: on-disk master list (hadoop-master:7051, slave2:7051, slave3:7051) and provided master list (:0) differ. Their symmetric difference is: :0, hadoop-master:7051, slave2:7051, slave3:7051
It is a cluster of 8 nodes and i have provided 3 masters as given below in master.gflagfile on master nodes.
    --master_addresses=hadoop-master,slave2,slave3

A: TL;DR
If this is a new installation, working under the assumption that master ip addresses are correct, I believe the easiest solution is to

*

*Stop kudu masters

*Nuke the <kudu-data-dir>/master directory

*Start kudu masters

Explanation
I believe the most common (if not only) cause of this error (Failed to initialize sys tables async: on-disk master list (hadoop-master:7051, slave2:7051, slave3:7051) and provided master list (:0) differ.) is when a kudu master node gets added incorrectly. The error suggests that kudu-master thinks it's running on a single node rather than 3-node cluster.
Maybe you did not intend to "add a node", but that's most likely what happened. I'm saying this because I had the same problem; after some googling and debugging, I discovered that during the installation, I started kudu-master before putting the correct IP address in master.gflagfile, so that kudu-master was spun up thinking it was running on a single node, not 3 node. Using steps above to clean install kudu-master again, my problem was solved.