text:
Q: Loop through list of email addresses in recordset to send tailored emails I want to loop through a table and to email each user an individually tailored email with their prefix and last name.
It seems to be only emailing the first person on the list.
Design mode

Form mode with dummy data

Private Sub SendEmail_Click()

    Dim oOutlook As Outlook.Application
    Dim oEmailItem As MailItem
    Dim rs As DAO.Recordset

    On Error Resume Next
    Err.Clear
    Set oOutlook = GetObject(, "Outlook.Application")

    If Err.Number <> 0 Then
        Set oOutlook = New Outlook.Application
    End If

    Set oEmailItem = oOutlook.CreateItem(olMailItem)
    Set rs = CurrentDb.OpenRecordset("SELECT * FROM list_of_emails")

    If Not (rs.BOF And rs.EOF) Then
        rs.MoveFirst
        Do Until rs.EOF = True

            With oEmailItem
                .To = rs!Email
                .Subject = "NKS: Test"
                .Body = "Hi " & [Prefix] & " " & [lname] & ":" & vbCrLf & vbCrLf & "This is a test."
                .Send
            End With
            rs.MoveNext
        Loop
    End If
    rs.Close

    Set oEmailItem = Nothing
    Set oOutlook = Nothing
    Set rs = Nothing

End Sub

If I remove the On Error Resume Next, I get the following error when I assign the recipient address (.To = rs!Email):

The item has been moved or deleted.

A: as the comments indicate you just have a bunch of errors.  assuming you have a reference to outlook 16 object library added and Prefix and lname are columns in the list_of_emails table then:
Private Sub SendEmail_Click()

    Dim oOutlook As Outlook.Application
    Dim oEmailItem As MailItem
    Dim rs As DAO.Recordset

    'On Error Resume Next
    'Err.Clear
    'Set oOutlook = GetObject(, "Outlook.Application")

    'If Err.Number <> 0 Then
       ' Set oOutlook = New Outlook.Application
    'End If

    Set oOutlook = New Outlook.Application 'open outlook before start the loop
    Set rs = CurrentDb.OpenRecordset("SELECT * FROM list_of_emails")

    If Not (rs.BOF And rs.EOF) Then
        rs.MoveFirst
        Do Until rs.EOF = True
        Set oEmailItem = oOutlook.CreateItem(olMailItem) 'create new email for each email address

            With oEmailItem
                .To = rs!Email
                .Subject = "NKS: Test"
                .Body = "Hi " & rs!Prefix & " " & rs!lname & ":" & vbCrLf & vbCrLf & "This is a test."
                .Send
            End With
            rs.MoveNext
        Loop
    End If
    rs.Close

    Set oEmailItem = Nothing
    Set oOutlook = Nothing
    Set rs = Nothing

End Sub


text:
Q: printing the function is producing output but call it is not (python) This function, when printed, outputs 7 but when called, does not output anything. Can someone please explain why this is happening?
def myfunc(x, y):
    return (x+y)

myfunc(3,4)

This does not output anything. But if I write print(myfunc(3,4)), the output is 7. How does this work?

A: Well it does the computation and returns the value.
But since you do not print it it just stays there.
The function executes but it does not print to console.
Simple as that

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable VAT conditionally for specific product categories on Woocommerce checkout In woocommerce I am using Timologia for WooCommerce plugin, which checks if user wants invoice or plain receipt (this is required in Greece). So this plugin add a select field in checkout page with "No" (default) or "Yes" as options.
If customer select "Yes" then "zero vat" is applied for products in specific categories and everything works fine in the checkout page.
But when customer place the order, on the order received page and on backend (order edit page) the specific item prices are not anymore without VAT.
Here is my code:
add_action( 'woocommerce_checkout_update_order_review', 'tfwc_taxexempt_checkout_based_invoice_choice' );

function tfwc_taxexempt_checkout_based_invoice_choice( $post_data ) {
    global $woocommerce;
    $woocommerce->customer->set_is_vat_exempt( false );
    parse_str($post_data);
    if ( $billing_timologio == 'Y' )

    add_filter( 'woocommerce_product_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );

    function wc_diff_rate_for_user( $tax_class, $product ) {

    // let's get all the product category for this product...

    $terms = get_the_terms( $product->id, 'product_cat' );
    foreach ( $terms as $term ) { // checking each category

    // if it's one of the category we'er looking for
    if(in_array($term->term_id, array(228,231,222))) {
        $tax_class = 'Zero Rate';
        // found it... no need to check other $term
        break;
    }
}

    return $tax_class;
  }
}

This code was working fine on WC version 2.X, and stopped working fine in version 3+
Any help is appreciated.

A: Update 3
The plugin and your code are outdated, with some mistakes and errors. In the code below I am using another way with ajax and WC_Session.

The "Tax rate" behavior on products entered including taxes.
To make any code that manipulate tax rates effective, the products prices need to be entered excluding taxes. If not, additional code is required to grab the product price excluding taxes as custom cart item data, to make the "Zero rate" tax effective.

I have added a custom function partially copied from the plugin code, that adds a checkout select field billing_timologio, to make the code testable.
Also the add to cart ajax button is replaced by a button linked to single product pages for the defined product categories, as we add the product price excluding taxes as custom cart item data.
The code (only for Woocommerce version 3.3+):
// Your product categories settings
function get_my_terms(){
    return array( 'clothing' );
    return array( 222, 228, 231 );
}

// Change add to cart ajax button to a button linked to single product pages for specific product categories
add_filter( 'woocommerce_loop_add_to_cart_link', 'conditionally_replace_add_to_cart', 10, 2 );
function conditionally_replace_add_to_cart( $html, $product ) {
    if ( has_term( get_my_terms(), 'product_cat', $product_id )  && $product->is_type('simple') ) {
        // Set HERE your button link
        $link = get_permalink($product_id);
        $text = __("Read More", "woocommerce");
        $html = '' . $text . '';
    }
    return $html;
}

// Adding a custom checkout select field
add_filter( 'woocommerce_billing_fields', 'custom_billing_fields', 20, 1 );
function custom_billing_fields($billing_fields) {

    $billing_fields['billing_timologio'] = array(
        'type'        => 'select',
        'label'       => __('INVOICE'),
        'placeholder' => _x('INVOICE', 'placeholder'),
        'required'    => false,
        'class'       => array('form-row-wide'),
        'clear'       => true,
        'options'     => array(
            'N' => __('No'),
            'Y' => __('Yes'),
        ),
        'value' => '',
    );
    return $billing_fields;
}

// The jQuery Ajax script
add_action( 'wp_footer', 'custom_checkout_script' );
function custom_checkout_script() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    // Removing WC_Session "
    if( WC()->session->__isset('billing_timologio') ){
        WC()->session->__unset('billing_timologio');
    }
    ?>

    <?php
    endif;
}

// The Wordpress Ajax receiver
add_action( 'wp_ajax_get_ajax_billing_timologio', 'get_ajax_billing_timologio' );
add_action( 'wp_ajax_nopriv_get_ajax_billing_timologio', 'get_ajax_billing_timologio' );
function get_ajax_billing_timologio() {
    if ( $_POST['b_timologio'] == '1' ){
        WC()->session->set('billing_timologio', '1');
    } else {
        WC()->session->set('billing_timologio', '0');
    }
    die();
}

// Save the product price excluding tax as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_price_excl_vat_as_custom_cart_item_data', 20, 3);
function add_price_excl_vat_as_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
    if ( ! wc_prices_include_tax() )
        return $cart_item_data;

    $_product_id = $variation_id > 0 ? $variation_id : $product_id;
    $product = wc_get_product($_product_id); // The WC_Product Object

    // Save the price excluding tax as custom cart item data
    if( has_term( get_my_terms(), 'product_cat', $product_id ) ) {
        $cart_item_data['price_excl_tax'] = wc_get_price_excluding_tax( $product, array( 'price' => $product->get_price() ) );
    }

    return $cart_item_data;
}

// Changing conditionally specific items tax rate
add_action( 'woocommerce_before_calculate_totals', 'zero_tax_items_based_on_invoice_choice', 30, 1 );
function zero_tax_items_based_on_invoice_choice( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Check for product categories and enabled "billing_timologio" field
        if( has_term( get_my_terms(), 'product_cat', $cart_item['product_id'] ) && WC()->session->get('billing_timologio') ){
            // Set the item tax rate to "Zero rate"
            $cart_item['data']->set_tax_class('Zero Rate');

            // Set price excluding taxes
            if( isset($cart_item['price_excl_tax']) ){
                $cart_item['data']->set_price($cart_item['price_excl_tax']);
            }
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

On order received, order view and (admin) order edit pages, the tax will be set to "Zero Rate" for the specific items when customer has selected "Yes" for "BILLING INVOICE" (ΤΙΜΟΛΟΓΙΟ).
The related product price remaining to the defined product categories will have this time the correct price excluding taxes…

Original answer.
I seems that there is 2 errors:

*

*The first is $product->id to be replaced by $product->get_id()

*The second, you need to put the internal function outside

Also the code can be simplified.
Without any guaranty as your code can't be tested for real, try this instead:
add_action( 'woocommerce_checkout_update_order_review', 'tfwc_taxexempt_checkout_based_invoice_choice' );
function tfwc_taxexempt_checkout_based_invoice_choice( $post_data ) {
    WC()->customer->set_is_vat_exempt( false );

    parse_str($post_data);

    if ( $billing_timologio == 'Y' )
        add_filter( 'woocommerce_product_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );
    }
}

function wc_diff_rate_for_user( $tax_class, $product ) {
    // Checking for specific product categories
    if( has_term( array(228,231,222), 'product_cat', $product->get_id() ) ) {
        return 'Zero Rate';
    }
    return $tax_class;
}

I hope it will work.


text:
Q: Unsure of how to catch and reassign synthetic members in a class I'm currently using the jacoco maven plugin in my project. I've written my unit tests using mockito. I've read the jacoco FAQs, the Google Groups page, and the Jacoco github issues threads about catching synthetic member fields in a Unit Test class and reassigning them as the jacoco injected object doesn't know what to do with synthetic members.
However a great many of my unit tests are setup and mocked using the mockito framework, and I don't think Jacoco likes the MockMvc object class. I think the class itself is implemented somehow using reflection which is causing jacoco to fail.
My error when I run mvn test is:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is my.project.submodule.controller.ControllerException: Unknown property '$jacocoData'

My code snippet that's triggering this is:
mockMvc.perform(
            get("/api/substituteStuff"))
            .andExpect(jsonPath("$", hasSize(10)))
            .andExpect(status().isOk())

A:
I think the class itself is implemented somehow using reflection which is causing jacoco to fail.

There are many cases in which compiler can generate synthetic members, for one of examples - presence of assertions in class. And this will cause the same failure, so this is not JaCoCo failure, but failure of your code/library. Solution is to update your code or library to ignore such members.
Quoting http://www.jacoco.org/jacoco/trunk/doc/faq.html :

My code uses reflection. Why does it fail when I execute it with JaCoCo?
To collect execution data JaCoCo instruments the classes under test
  which adds two members to the classes: A private static field
  $jacocoData and a private static method $jacocoInit(). Both members
  are marked as synthetic.
Please change your code to ignore synthetic members. This is a good
  practice anyways as also the Java compiler creates synthetic members
  in certain situation.

And as a workaround - exclude class from instrumentation.


text:
Q: Sum of three perfect cubes is equal to a perfect fourth How many answers does the following equation have?
$a^3+b^3+c^3=d^4$ where $a, b, c, d\in \mathbb{Z}^+$.
This was asked in a test for gifted math students in 7th grade in Finland. I have been thinking about this and couldn't solve this for my number theory isn't that good.
Could someone help me? Thank you in advance.

A: Note that if $a^3 + b^3 + c^3 = n$, then $(na)^3 + (nb)^3 + (nc)^3 = n^4$.
So you have infinitely many solutions even if you require $a,b,c$ to be distinct.
There are also solutions where $a,b,c$ are pairwise coprime, e.g.
$$ \eqalign{19^3 + 89^3 + 117^3 &= 39^4\cr
            107^3 + 163^3 + 171^3 &= 57^4\cr
            81^3 + 167^3 + 266^3 &= 70^4\cr
            75^3 + 164^3 + 293^3 &= 74^4} $$
Are there infinitely many of those?
[EDIT] See OEIS sequence A327586

A: It has an infinite number of solutions. For instance, for any $k\in \mathbb{N}$, take $d=3k^3$, and $a=b=c=3k^4$.
Then
$$ a^3+b^3+c^3=3\cdot 3^3k^{12} = 3^4k^{12}=d^4.$$


text:
Q: Custom Params in URL Here is the URL I currently Have working :
www.Mysite.com?b=ex%2021

I thought I could just add some rules in the .htaccess file, so i added this :
RewriteEngine On
RewriteRule /b/(.*)/$ index.php?b=$1

When i visit www.Mysite.com/b/ex1/ I get forwarded to the front page, after playing around for a while i discovered I either get Error 404 or a redirect to the main page depending on how i set up the rule.
I guess this wont work because this Wordpress is taking over and messing things up - so so i begin to look into how to do this the WP way, and tried this from some code examples i found :
// rewrite
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
    $vars[] = 'b';
    return $vars;
}
function custom_rewrite_basic()
{
add_rewrite_rule('b/(.*)/', 'b/?b=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');

But I get page not found... I have updated/flushed out the page rules. Should both methods work? Is my code wrong for either?
EDIT : thanks for the help, I have updated the question to show the new rewrite rule. I have tried multiple regex, I believe the above should be working. If i type in myurl.com/b/ex2/ i get page not found. If i type in myurl.com/b/22/ it seems to work? - So i tried (a-zA-Z0-9) and with that i get 404. the code i posted above validates as i need in a regex validator.

A: The regex you have in the rewrite rule, ([0-9]+), will not match your query string ex%2021. Try ?b=21 and see if that works.
Also, new rewrite rules require that the rewrite rules are flushed. You can do this one of two ways. Either call flush_rewrite_rules(); or go to Settings > Permalinks and click save.
Please note, you DO NOT want flush_rewrite_rules(); to be called on a live site, so remove it when you're done developing.


text:
Q: Parsing HTML with LINQ I'm trying to take all cells from a HTML table using Html Agility Pack and LINQ.
I have loaded the HTML source in a HtmlAgilityPack.HtmlDocument and selected the  tags with LINQ. However after using foreach to iterate the result, it crashes in the second record.
This is a fragment of the HTML source:

    New York
    Card 1

    London
    Card 2

    Tokyo
    Card 3

    Berlin
    Card 4

And this is what I made:
htmlDoc.LoadHtml(await msgRecived.Content.ReadAsStringAsync());

var tds=
    from td in htmlDoc.DocumentNode.Descendants("td")
    where td.Attributes["class"].Value == "city"
    select td.InnerText;

foreach (var td in tds)
{
    citiesText = citiesText + " " + td;
}

It only return the first element, e.g. if instead of using foreach I do:
citiesText = tds.ElementAt(0);

It returns New York, but if I try ElementAt(1) it crashes with Object reference not set to an instance of an object.
Any help? Thanks

A: You need to make sure that Attributes["class"] is not null:
var tds =
    from td in doc.DocumentNode.Descendants("td")
    where td.Attributes["class"] != null && td.Attributes["class"].Value == "city"
    select td.InnerText;

The second  retrieved has no class attribute, so when you access Attributes["class"] in that case, you're getting null. Calling .Value on null is causing the exception.
Alternatively you could use GetAttributeValue:
var tds =
    from td in doc.DocumentNode.Descendants("td")
    where td.GetAttributeValue("class", null) == "city"
    select td.InnerText;

A: Just a guess but you are probably only looking at the td on the first element. Maybe you need
htmlDoc.DocumentNode.Descendants("table") instead.


text:
Q: Re attempt server connection after some time I have a client which is a windows process to get updates from server in c#. The server may be down for maintainance for some time, the client wont not be able to connect to server at this point if it needs to update.
I want to design so that the client re attempts connection after 30 min if connection attempt fails. I understand Thread.Sleep would be bad idea so I would like some suggestions on how to do it.
Thanks in advance.

A: Use a timer. If the function fails to connect, then set a timer to call it again...
e.g.
    class MyClass
    {

 System.Timers.Timer m_ConnectTimer = null;

        ..
        ..

    void ConnecToServer()
    {
        if (m_ConnectTimer != null)
        {
            m_ConnectTimer.Enabled = false;
            m_ConnectTimer.Dispose();
            m_ConnectTimer = null;
        }

        //Try to connect to the server

        if (bConnectedToTheServer)
        {
            //Do the servery stuff
        }
        else //set the timer again
        {
            m_ConnectTimer = new Timer(30 * 60 * 1000);
            m_ConnectTimer.Elapsed += new ElapsedEventHandler(TimerHandler)
            m_ConnectTimer.Enabled = true;
        }

    }

    void TimerHandler(object sender, ElapsedEventArgs e)
    {
        ConnectToServer();
    }

}


text:
Q: JCEF functions only work from the second call onwards (Java Chromium Embedded Framework) I recently integrated the Java Chromium Embedded Framework (https://github.com/chromiumembedded/java-cef) in a Netbeans (RCP) Application Project (Java: JDK11).
The Browser Window is shown in a Netbeans TopComponent and generally works just fine.
However I have several rather small, but nasty bugs that I noticed which are always following the same pattern:
Whatever code I execute that concerns the jcef browser always only works when I execute it a second time and is all but ignored the first time around.
However there are no error messages or logs or any thing like that and the code seems to be executed when I go through it with the debugging tool.
Three examples:

*

*Implementing a return button: This just checks whether the CefBrowser instance returns true for browser.canGoBack(). If it returns true a button is activated. The value starts correctly at false, but it returns true just after the second change of url.(Should obviously happen after the first) From there on out it works just fine....Unless you go back (with the return button) to the home page. It should then obviously return false again - Which it doesn't. Calling a different URL again returns false for canGoBack() (which should then obviously be true) and only returns true after the second URL change again. So the return from canGoBack always shows the return it should have shown from its previous execution, as if lagging behind one time.

*Implementing a "go to" function: This function just takes you to a specified other website than the home page. Again works fine from the 2nd time onwards, but the first time the code is simply ignored. (although I confirmed via Debugger that the code is executed without errors even the first time around)

*Implementing a login dialog: If the browser notices that authentication is required, this opens up a dialog where the user can enter BASIC credentials. And again the dialog gets opened, the credentials are returned correctly (confirmed via Log), are handed over to the appropriate function and it works for the second try but not the first. (credentials were identical) Indeed I confirmed via Wireshark, that the first time that callback.Continue(ad.getUsername(), ad.getPassword()); is executed, nothing at all is actually send to the server...

Code for the third example:
cefClient_.addRequestHandler(new CefRequestHandlerAdapter() {
            @Override
            public boolean getAuthCredentials(CefBrowser browser, String origin_url, boolean isProxy, String host,
                    int port, String realm, String scheme, CefAuthCallback callback) {

                AuthenticationDialog ad = new AuthenticationDialog();
                ad.authenticate(); // Shows Login Dialog
                LOGGER.log(Level.INFO, String.format("--->%s:%s", ad.getUsername(), ad.getPassword())); //This confirms that the variables are indeed correct even the first time around
                callback.Continue(ad.getUsername(), ad.getPassword());
                return true;
            }
        });

Sadly I don't have any clue anymore what could possibly cause these problems.
If anyone of you has had these same problems or has any idea as to how to fix them or even where to start looking for a fix I would very much appreciate your comments.
Thanks in advance!

A: I found the answer(s) to the afore mentioned questions. In case someone else will stumble upon similar issues in the future I'm going to shortly summarize what fixed it for me.
Apparently most of the problems I faced arose from threading problems. It seems like when you execute a command on the jcef browser while it's thread is still working on something, your command will not be executed, but there also won't be any error messages or other unwanted behaviour.
Example for the second problem:
When the go(url) command was executed the browser had not finished loading the initial home page completely yet. That's why the command was ignored.
To fix this I added a simple String variable that will save the URL that someone wants to load until the browser has finished loading the previous page.
Only then will this url be loaded in the browser and consequently be deleted from the variable.
This could of course also be done with something like a list, but I can't think of a scenario where that would be useful.
Checking whether the browser is done loading should be done in the overridden method onLoadingStateChange of the CefLoadHandlerAdapter.
client_.addLoadHandler(new CefLoadHandlerAdapter() {
        @Override
        public void onLoadingStateChange(CefBrowser browser, boolean isLoading,
                boolean canGoBack, boolean canGoForward) {
            if (!isLoading) {
                browser_ready = true;
                if (goOnReady != null) {
                    goURL(goOnReady);
                }
            }
        }
    });

A similar issue was present with the first example from the original question.
Activating the "Back" button within the afore mentioned onLoadingStateChange via the canGoBack variable did the trick for me in the end.
Now the third example (the login dialog showing twice) turned out to be a problem that was also present in the official detailed example code from the jcef github page.
This problem seems like it might be a threading problem again, but I'm not sure this time.
As a workaround I implemented the following solution:

*

*add class variables for username and password

*if these variables are empty start the login dialog within the getAuthCredentials method (see original question) and save the given username and password in these class variables.

*then execute browser.reload();

*the browser will then go through authentication again, but this time the variables won't be empty and you can hand them to callback.Continue(username, password); thus only showing one login dialog to the user.

This process is also very quick so the user want be able to notice the reload.


text:
Q: Error: Cannot set headers after they are sent to the client while using express ERROR: [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I have an Express Server( ^4.17.1) and a MySQL database. This is the code

exports.postFormInput = async (req, res, next) => {

  jwt.verify(req.body.jwt, process.env.SECRET_FOR_JWT, (err, decoded) => {
    if (err) {
      res.sendStatus(403);
      res.end();
    }
    else if (decoded.userId !== req.body.userId) {
      res.sendStatus(403);
      res.end();
      return;
    }
    else {
      username = decoded.username;
      userId = decoded.userId;
    }
  })

  let sql = "SELECT status FROM form_input WHERE user_id = '" + userId + "'";

  try {

    const status = await db.execute(sql);
    status[0].forEach(status1 => {
      if (status1.status == 'processing') {
        return res.json({ message: 'previous result not finished' }).end();

      }
    })
  } catch (e) {
    // return res.status(500);
    next(e);
    return;
  }

const project_name = req.body.ProjectInput.project_name;
  let sql1 = "SELECT project_name FROM form_input WHERE user_id = '" + userId + "'";
  try {
    const project_names = await db.execute(sql1);
    project_names[0].forEach(name1 => {
      if (name1.project_name == project_name) {
        return res.json({ message: 'two projects with the same name' }).end();
      }
    })
  } catch (e) {
    next(e);
    return;
  }
}

Error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/response.js:267:15)
    at exports.get500 (/home/anurag-gupta/test_del/part1/backend1/controllers/error.js:10:7)
    at Layer.handle_error (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/router/index.js:315:13)
    at /home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/router/index.js:335:12)
    at next (/home/anurag-gupta/test_del/part1/backend1/node_modules/express/lib/router/index.js:275:10)

A: I think if there is an error at the first if statement in your JWT.verify, you do not return the function.
Just try to generate a random number as statuscode, and see which res.send() is sending too early.
Just remember, this error means that you have called res.send() already!

A: This particular error message occurs when you try to send more than one response to the same request.
There are multiple issues here and they will all have to be fixed before this problem goes away:

*

*When you call res.sendStatus(...), do NOT call res.end() afterwards.  res.sendStatus() sends the whole response, you're done after that.

*After you send a response, you have to make sure that no more code that can also send a response executes.  In some cases, you can do that with a simple return statement, but if you're inside an asynchronous callback and there's other code that can execute outside that asynchronous callback, then you have to do more to make sure that each path through your code can only send one response.

*You're executing multiple separate asynchronous operations in this function in parallel (jwt.verify() and db.execute()) so you have no control flow between them and they each have code paths that can send a response (thus multiple responses are sent).

*You have a .forEach() loop that can send a response inside the loop with no particular protection against that loop attempting to send more than one response.


text:
Q: How to run Jekyll on a virtual box server? I'm on a Windows 7 x64 machine with Virtual Box and Vagrant installed. I installed

*

*Ruby

*Rubygems

correctly and installed jekyll. The final message I received on my PuTTY terminal is :
Server address: http://127.0.0.1:4000/
Server running... press ctrl-c to stop.

When I visit the url on Windows Chrome browser, it says
This site can't be reached
127.0.0.1 refused to connect.

What are the extra configurations that needs to be done so that Jekyll can run on the virtual box server?

A: To access the jekyll instance in the virtual box server, run Jekyll with the server IP.
Usage:

  jekyll serve [options]

Options:

   -H, --host [HOST]  Host to bind to

Supposing the virtual server IP is 192.168.1.100 then run the following command in the server to make the jekyll instance accesible from outside:
jekyll serve -H 192.168.1.100

Then it will be accessible at http://192.168.1.100:4000

A: If you dont use a static IP as mentioned in the other OP, you need to forward the port where jekyll will run
In your Vagrantfile
  config.vm.network :public_network
  config.vm.network :forwarded_port, guest: 4000, host: 4000,

You will start jekyll using the command
jekyll serve --host 0.0.0.0

Then you could access your site from http://localhost:4000/ from your host machine


text:
Q: Display specific highest custom field value from cart items in WooCommerce I am using Advanced Custom Fields plugin with WooCommerce and I have a custom field get_post_meta( get_the_ID(), "lead_time", true );" for my WooCommerce products.  When a person is checking out this field displays the lead time for each product if out of stock.
I need to find the highest "lead time" from all cart items / order items and then show that number as the final lead time on the order.
The following code shows the lead time for all products in the cart,:
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $leadTimes = get_post_meta($cart_item['product_id'] , 'lead_time', true );
    echo $leadTimes;
}

As an example would be 3 products in cart/order:

*

*the first has a 7 day lead time,

*the second has a lead time of 14 days,

*and the third has a lead time of 7 days.

But it displays  7147.
I would need to display "lead time = 14 days" since 14 is the greatest lead time of the 3 items in cart. I have tried every possible combination that I can think of using the above foreach loop, for 3 days now. With many different results but not the one I need.
Any help would be greatly appreciated.

A: Try the following using php max() function:
$lead_time = array(); // Initializing

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $lead_time[] = get_post_meta( $cart_item['product_id'], 'lead_time', true);
}

echo '
Max Lead time: ' . max($lead_time) . ' days
';

You will get the max value (displayed).
Or as you using Advanced Custom Fields, this should also work:
$lead_time = array(); // Initializing

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
    $lead_time[] = get_field('lead_time', $cart_item['product_id']);
}

echo '
Max Lead time: ' . max($lead_time) . ' days
';


text:
Q: jQuery validation engine won't work with jQuery 1.8+ I updated jQuery 1.8.3 to latest version and jQuery validation engine stopped working. I tested it with 1.8.3+ (any version) but it doesn't work.
JS:
$(document).ready(function() {
    $("#source").select2({
        closeOnSelect: false,
        formatResult: format,
        formatSelection: format,
        blurOnChange: true
    });
    $('#testform').validationEngine({ prettySelect: true, usePrefix: 's2id_', autoPositionUpdate: true });
});

function format(state) {
    // Update: Made it work by changing "state.element" to $(state.element).
    var originalOption = $(state.element);
    return originalOption.data('foo') + " " + state.text;
}

How do I fix this ?
Demo in JSfiddle  (changed to jQuery 1.8.3) validation worked.

A: The problem is the usage of .live() method in validate engine 2.6 which was removed in jQuery 1.9.
You can update the validate engine to 2.6.2 or latest where it is fixed by using .on()


text:
Q: Stripe Api call Generate double Invoice on Firebase cloud function call Why when i call this function Stripe generate 2 invoice?
I want to set a custom price % for the invoice and not using a fixed price as suggested on the documentation.
I want that the invoice is automatically payed by the customer.
exports = module.exports = functions.https.onRequest(
  async (request, response) => {
    let data = request.body;

    var imponibile = 100;
    const { stripe } = require("./stripe");
    const { db } = require("./admin");

    const invoiceItem = await stripe.invoiceItems.create({
      customer: data.customerId,
      description: data.description,
      amount: imponibile,
      currency: "eur",
    });

    const invoice = await stripe.invoices.create({
      customer: data.customerId,
      auto_advance: true, // Auto-finalize this draft after ~1 hour
      collection_method: "charge_automatically",
    });

    const payinvoice = await stripe.invoices.pay(invoice.id);
    return payinvoice;
  }
);

A: Solved, the problem was that i was returning the actual payment function recursively.
Solution :
return respond.status(200).send('ok')


text:
Q: Trying to select nav ul li ul li in javascript I have tried many options, but this what I have so far and it doesnt work.
document.querySelectorAll('ul li').querySelectorAll('ul li').style.background = color;

document.getElementsByTagName("NAV").getElementsByTagName("UL").getElementsByTagName("LI").getElementsByTagName("UL").getElementsByTagName("LI").style.background = color;

my html

            <form name = "searchField">
                <input name = "search" type = "text" placeHolder = "" id = "search">
            </form>

            HOME

            ABOUT

            PHOTOGRAPHY

San Francisco

Lake Tahoe

            PROJECTS

Informative

Profile

            CONTACT

Twitter

Instagram

Email

 Some things here

Does anyone have an idea how to select nav ul li ul li with javascript?
P.S. I havent learned jquery. So I want to do it with pure javascript.

A: "how to select nav ul li ul li with javascript"
Do you mean this?
document.querySelectorAll('nav > ul > li > ul > li');

Note that you can remove the direct children condition > where it suits you.
Also note that querySelectorAll returns a collection (non-live NodeList) so you must iterate over it to manipulate every elements.
   var nestedLis = document.querySelectorAll('nav > ul > li > ul > li'),
       i = 0,
       len = nestedLis.length;

   for (; i < len; i++) nestedLis[i].style.backgroundColor = 'red';

Since most array functions can manipulate array-like objects, you can also apply [].forEach to the node list.
[].forEach.call(nestedLis, function (li) {
    //manipulate li
});

A: QuerySelectorAll return a NodeList of objects, even if there is only one.
So you need to give the element position in the NodeList like so
document.querySelectorAll('ul li')[0]

For the first element.
If you need to go trough all the elements, you'll need a loop like so
var elems = document.querySelectorAll('ul li');

for (var i=0; i<elems.length; i++) {
    elems[i].style.background = color;
}

A: This should work
document.querySelectorAll('NAV ul li ul li')

A: Just for the sake of including the jQuery solution..
$('nav ul li ul li')

or add a class to your sub menus like #myID and target
$('#myID li')


text:
Q: Spring boot GET datatype conversion not working I am getting following exception while trying to use Spring boot. Its not able to convert request parameter. What am I missing here ? How do I customize request datatype converter in Spring boot ?
2018-02-23 17:05:11.868  WARN 13976 --- [nio-9988-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiParam @org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] for value '2017-07-21'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017-07-21]

2018-02-23 17:18:29.582  WARN 13976 --- [nio-9988-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.OffsetDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@io.swagger.annotations.ApiParam @org.springframework.web.bind.annotation.RequestParam java.time.OffsetDateTime] for value '2017-07-21T17:32:28Z'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017-07-21T17:32:28Z]

My Controller method look like this.
@RequestMapping(value = "/mypath/status",
        produces = { "application/json" },
        method = RequestMethod.GET)
default ResponseEntity<MyStatusResponse> _getMyStatusByQuery(@RequestHeader(value="myId", required=true) Integer myId,
@Valid @RequestParam(value = "param1", required = false) String param1,
@Valid @RequestParam(value = "param2", required = false) String param2,
@Valid @RequestParam(value = "dueDateStart", required = false) LocalDate dueDateStart,
@Valid @RequestParam(value = "dueDateEnd", required = false) LocalDate dueDateEnd,
@Valid @RequestParam(value = "sentOnEnd", required = false) OffsetDateTime sentOnEnd) {
    return getMyStatusByQuery(myId, param1, param2, dueDateStart, dueDateEnd, sentOnStart, sentOnEnd);
}

I also have added converter for OffsetDateTime (basically this is generated by swagger)
public class RFC3339DateFormat extends ISO8601DateFormat {

  // Same as ISO8601DateFormat but serializing milliseconds.
  @Override
  public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
    String value = ISO8601Utils.format(date, true);
    toAppendTo.append(value);
    return toAppendTo;
  }

}

application.properties
spring.jackson.date-format=my.test.RFC3339DateFormat
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false

Following is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.jigarshah.api</groupId>
    <artifactId>test-me</artifactId>
    <packaging>jar</packaging>
    <name>test-me</name>
    <version>1.0.0</version>
    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <springfox-version>2.8.0</springfox-version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
    </build>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!--SpringFox dependencies -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-version}</version>
        </dependency>

        <!-- XML processing: Jackson -->
        <dependency>
          <groupId>com.fasterxml.jackson.dataformat</groupId>
          <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>
    <!-- Bean Validation API support -->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
        <scope>provided</scope>
    </dependency>
    </dependencies>
</project>

A: You can achieve this by creating classes that implements JsonDeserializer and then add them to the Jackson's ObjectMapper.
An example of a configuration class for this :
@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addDeserializer(LocalDate.class, new JsonDateDeserializer());
        simpleModule.addDeserializer(OffsetDateTime.class, new JsonDateTimeDeserializer());
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }

}

Where JsonDateDeserializer and JsonDateTimeDeserializer are your classes with your implementation of the conversion with the right pattern formats.

A: https://blog.codecentric.de/en/2017/08/parsing-of-localdate-query-parameters-in-spring-boot/
This was right solution. Spring Boot 2 might have better solution for this.
https://github.com/spring-projects/spring-boot/commit/2fa0539e7f7bf93505f67303955cc7da6f9f5846


text:
Q: When I use apply function to a single column returns error I'm learning Python and want to use the "apply" function. Reading around the manual I found that if a I have a simple dataframe like this:
df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])

   A  B
0  4  9
1  4  9
2  4  9

and then I use something like this:
df.apply(lambda x:x.sum(),axis=0)

output works because according to theory x receives every column and apply the sum to each so the the result is correctly this:
A    12
B    27
dtype: int64

When instead I issue something like:
df['A'].apply(lambda x:x.sum())

result is: 'int' object has no attribute 'sum'
question is: why is that working on a dataframe by column, it's ok and working on a single column is not ? In the end the logic should be the same. x should receive in input one column instead of two.
I know that for this simple example I should use other functions like df.agg or even df['A'].sum() but the question is to understand the logic of apply.

A: if you look at a specific column of a pandas.DataFrame object, you working with a pandas.Series with (in your case) integers as values. Well and integers don't have a sum() method.
(Run type(df['A']) to see that you are working with a series and not a data frame anymore when slicing a single column).
The irritating part is that if you work with an actual pandas.DataFrame object, every column is a pandas.Series object and they have a sum() method.
So there are two ways to fix your problem

*

*Work with a pandas.DataFrame and not with a pandas.Series: df[['A']]. The additional brackets force pandas to return a pandas.DataFrame object. (Verify by type(df[['A']])) and use the lambda function just as you did before

*use a function rather than a method when using lambda: df['A'].apply(lambda x: np.sum(x)) (assuming that you have imported numpy as np)

I would recommend to go with the second option as it seems to me the more generic and clearer way
However, this is only relevant if you want to apply a certain function to ever element in a pandas.Series or pandas.DataFrame. In your specific case, there is no need to take the detour that your are currently using. Just use df.sum(axis=0).
The approach with apply is over complicating things. The reason why this works is that every element of a pandas.DataFrame is a pandas.Series, which as a sum method. But so does a pandas.DataFrame has, so you can use this right away.
The only way, where you actually need to take the way with apply is if you had arrays in every cell of the pandas.DataFrame


text:
Q: How to tell .htaccess to only allow requests to index.php and app/dist/* folder? This is the current folder:
/app
  /dist
    /index.html
    /index.css
    /index.js
  /src
    /configurations.json
/index.php
/configurations.php

I have sensitive data everywhere:

*

*app/src/...

*/...
I want the users to only be able to access to:

*

*index.php

*app/dist/whateverfile.whateverformat
The dist folder can change, so I have to let them access this directory statically, so I do not have to list every single file.
How is this suposed to be done with this .htaccess syntax?
I have this configuration, that lets me access the index.php. But no clue to achieve it for the dist folder...
Options -Indexes
DirectoryIndex index.php

<FilesMatch ".*">
    Order allow,deny
    Deny from all
    Satisfy All
</FilesMatch>

<Files index.php>
    Order allow,deny
    Allow from all
    Satisfy All
</Files>

<Files "">
    Order allow,deny
    Allow from all
    Satisfy All
</Files>

Thanks in advance.

A: The <Files> and <FilesMatch> directives only target files, not directories. If you have access to the server config then you'd perhaps use a <Directory> container.
Using mod_rewrite
In .htaccess you can use mod_rewrite to restrict access to anything other than /index.php or /app/dist/.
For example:
RewriteEngine On

RewriteRule !^(index\.php$|app/dist/) - [F]

The above will respond with a 403 Forbidden for any request that is not /index.php or does not start /app/dist/. If you wish to return a 404 instead then change F to R=404.
The ! prefix on the regex negates the regex. Note that the URL-path matched by the RewriteRule pattern does not start with a slash.
If you only want to respond with a 403 for requests that would map to actual files or directories (and 404 otherwise) then add a couple of conditions that check the filesystem (but note that filesystem checks are relatively expensive, so unless you need them, don't use them). For example:
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule !^(index\.php$|app/dist/) - [F]

Only if the requested URL is not in the allowed "group" and maps to a file or directory is the RewriteRule directive actioned.
However, I would assume your URLs don't actually contain index.php (do they?), in which case the user requests / and mod_dir issues an internal subrequest for /index.php (the DirectoryIndex). In which case, you'll need to make the index.php optional.
For example:
RewriteRule !^((index\.php)?$|app/dist/) - [F]

Using an Apache Expression
Alternatively, you can do this with an Apache expression (Apache 2.4)
<If "%{REQUEST_URI} !~ m#^/((index\.php)?$|app/dist/)#">
    Require all denied
</If>

The above responds with a 403 for any URL request that is not /, /index.php or start with /app/dist/.
Note that Order, Allow, Deny, etc. are older Apache 2.2 directives and are officially deprecated on Apache 2.4.

Using mod_setenvif
Another alternative is to use mod_setenvif and set an environment variable if one of the permitted URL-paths is requested and only permit access if this env var is set.
For example:
SetEnvIf Request_URI "^/((index\.php)?$|app/dist/)" ALLOWED
Require env ALLOWED

The above sets the ALLOWED env var if the any of the permitted URL-paths are requested. The Require directive then requires this env var to be set to grant access, otherwise a 403 is returned.

A: If this is your main problem: "I have sensitive data everywhere"
That is solved the easiest and most reliably by moving that  sensitive to somewhere outside of your web root...
Consider a web root (your DocumentRoot) that only contains the index.php
When there is no other data in there you don't need any complex rules to protect it either...

You can then use for instance the Alias directive (in preferably your main server configuration file, or if you prefer a .htaccess file in your web root) or mod_rewrite rules to map URI's to documents stored in directories outside of  your DocumentRoot directories/files to specifically allow access.
i.e.
.
`-- some-path
    |-- app
    |   `-- dist
    |       |-- index.css
    |       |-- index.html
    |       `-- index.js
    |-- src
    |   `-- configurations.json
    `-- www.example.com
        |-- .htaccess
        `-- index.php

Where your main apache configuration defines /some-path/www.example.com as the DocumentRoot for www.example.com.
The .htaccess can then be something such as this exposes the /some-path/app/ directory and all its contents as the URI path http://www.example.com/app/
# /some-path/www.example.com/.htaccess
# exposes/some-path/app/ directory  as the URI path `http://www.example.com/app/`

Alias "/app" "/some-path/app"

Or be more specific with Alias "/app/dist" "/some-path/app/dist" or creative with a regex in an AlaisMatch directive.

A: This is how:
Options -Indexes
ServerSignature Off
DirectoryIndex index.php

RewriteEngine on
RewriteRule ^ui(/)?$ app/dist/index.html [QSA,END,NC,L]
RewriteRule ui/(.*) app/dist/$1 [QSA,END,NC,L]
RewriteRule !(ui/.*) index.php [QSA,END,NC,L]

Notice the END flag after every match. This flag is required to simulate the typical if-else syntax. But it is not documented on the official docs.
I moved to Node.js finally.


text:
Q: Can't create extensions plv8 postgresql After install postgres, can't create extension plv8.
I'm use: CREATE EXTENSION plv8;
I'm getting:
ERROR:  could not open extension control file "/usr/local/share/postgresql/extension/plv8.control": No such file or directory
********** Error **********

ERROR: could not open extension control file "/usr/local/share/postgresql/extension/plv8.control": No such file or directory
SQL state: 58P01

version postgres: 9.6.2
version pgAdmin4: 1.4
How to install plv8?

A: This should work on most platforms (https://github.com/plv8/plv8/issues/212#issuecomment-287589193):
$ easy_install pgxnclient
$ pgxnclient install plv8

It didn't work for me though. The only solution I came up with was building the library from source.
If you don't have wget installed, run:
$ brew install wget

Then run:
$ wget https://github.com/plv8/plv8/archive/v2.0.0.tar.gz
$ tar -xvzf v2.0.0.tar.gz
$ cd plv8-2.0.0
$ make static
$ make install

It worked for me.

A: I. Docker-images with postgres and plv8. It's free, images for Postgres 13, 14, and 15 based on Debian and Alpine are available, amd64 and arm64 architectures supported.
docker pull sibedge/postgres-plv8

Default is Alpine/last Postgres version. the complete tag list
Pay attention, that BigInt is not serializable in v8 and by default in plv8 v3.0.0 and higher BigInt numbers are converted into string(!). But if you need BigInt as numbers support, use this image with Postgres and specific version of plv8:
docker pull sibedge/postgres-plv8-bigint

II. Or, you can build images (for PostgreSQL with installed plv8) yourself with Dockerfiles:
Postgres 14.2, plv8 v3.0.0, Alpine based. size of image is 235MB.
Postgres 13.6, plv8 v3.0.0, Alpine based. size of image is 231MB.
Postgres 13.4, plv8 v2.13.15, Debian based. size of image is 351MB.
Postgres 13.6, plv8 v3.0.0, Debian based. size of image is 427MB.
III. Simple installing plv8 v3.0.0 on Debian Linux (PostgreSQL 13 must be preinstalled) :
$ git clone https://github.com/sibedge-llc/plv8-build.git
$ cd plv8-build
$ git checkout pg13-3.0.0-debian
$ sudo make install

A: I find a new way. Just copy and Paste!
if you using postgresql version of: 9.5, 9.6 beta, 10 go this link to download package and learn what shoud you copy and where to past:
https://github.com/JasperFx/marten/blob/master/documentation/documentation/admin/installing-plv8-windows.md
if you using postgresql version of: 9.3, 9.4, 9.5, 9.6, 10, 11 and 12 for downloading package you can go here:
http://updates.xtuple.com/updates/plv8/win/xtuple_plv8.zip
for downloading package and then copy past like has mentioned in first link


text:
Q: Interpretation 0f percentile How do we interpret the meaning of a percentile?
What I have learned from books is as follows: "If a score is the 40th percentile, this means that it is larger than 40% of the distribution, while the other 60% of scores are greater than or equal to the score."
My question is when that specific score equals to the previous score, shouldn't we say 40% of the distribution is "less or equal" to that score, instead of "less than" that score?
For example, say there are 500 students, and they are scored from 0 to 100. Say student A gets a score 80 and he is in 85th percentile, which traditionally means 85 percent student is less than his score and 15% is greater or equal to his score. In a specific case let 250 higher scorer students get all equal to a score of 80. Then student A is not higher than 85%. Or his score is not higher than the other student who also get 80. Is he?

A: You can define the percentile in different way with respect to duplicate values.
Let's choose a really simple corner case: we have 10 times the value 0.
Then the empirical c.d.f. goes from 0 to 1 at 0. There is little mathematical reason to prefer the $cdf(0)$ to be 0 or 1. One could also define it as 0.5 but that causes just as much trouble as the other two. The most common choice (and in my experience the least problematic) is to choose the upper value. i.e. all observed values would be in the 100% quantile, which begins at 0 or larger, while values strictly less than 0 have the 0% quantile.
A similar problem also exists with the median (cf. upper median, lower median).


text:
Q: rename files containing _2_ to -2- returns invalid option -- '2' I am trying to rename all files containing _2_ to -2-
find ./ -depth -name "*_2_*" -exec /usr/bin/rename  _2_ '-2-' {} \+

but I get the following error:
/usr/bin/rename: invalid option -- '2'

A: This is a common problem when dealing with filenames that have a leading -, because this is the same character used to indicate command line options.
A fairly common behavior is to interpret the argument -- to mean "end of options", so you can do something like:
find ./ -depth -name "*_2_*" -exec /usr/bin/rename -- _2_ '-2-' {} \+

I've tested this locally and that seems to Do The Right Thing on my system.


text:
Q: Logical operator treating fractions as FALSE I am getting an unexpected result when using logical operators on numbers less than 1.
I thought VBA would treat any number other than zero as TRUE, but it seems to be treating fractions as FALSE. So strange.
What am I misunderstanding.
I have boiled it down to these two line of VBA code. The first returns what I expect, but not the second.
Thanks
kbrown4600
MsgBox 1 And True   ' returns 1
MsgBox 0.5 And True ' returns 0. Unexpected result

A: Bitwise operators don't do floating-point math, so there's an implicit conversion going on before the operands are given for the And operator to do its bitwise thing.

 "Logical" operators are a scam. There's no such thing, we've been lied to all this time - it's another Santa / Tooth Fairy / Easter Bunny (never mind, I'm being told the Easter Bunny is real): they're bitwise operators, always, regardless of what you give them.

And since the bitwise math yields 0, then it can only mean that the implicit conversion is simply slicing off the decimal portion.
Bottom line, ...don't do bitwise stuff with non-integers, and avoid implicit type conversions in general. The standard library has a bunch of explicit conversion functions for that:
Debug.Print VBA.Conversion.CLng(0.5) And True '<~ explicit conversion

CLng is documented to round 0.5 down to 0,  If you need to determine whether to round down to 0 or up to 1, then be explicit about it:
Debug.Print CInt(0.5 + 0.01) And True '<~ explicit "round 0.5 up to 1"

In any case, working with non-integer operands to a bitwise operator makes no sense.

When the fractional part is exactly 0.5, CInt and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Javascript has worse quirks than that around those parts, not sure how fair calling implicit type conversions "strange" is.

I thought VBA would treat any number other than zero as TRUE

That depends on the context. -1 is True, but True is Not False. That makes True -1 internally, probably as a 32-bit integer, so in binary it might look like this:
11111111 11111111 11111111 11111111

Bit-wise, the Boolean value True must have this representation, because this needs to be the representation for False:
00000000 00000000 00000000 00000000

Bitwise logic needs the two operands to be the same type, so that the bits mean the same thing on both sides, otherwise the bitwise operation - which is supposed to be simple and fast - needs to start doing complicated analysis to work out what it's looking at, when it simply doesn't need to.. if we accept that bitwise logic works with integer types, period.
You can do MsgBox 42 And 12, you'll get the bitwise result 8:
00000000 00000000 00000000 00101010 ' 42
00000000 00000000 00000000 00001100 ' 12
00000000 00000000 00000000 00001000 '  8 (AND)

The result of the And operator is always going to be a bitwise-and result - what we call "logical operators" is just bitwise operators working with Boolean operands:
00000000 00000000 00000000 00000000 ' False
11111111 11111111 11111111 11111111 ' True
00000000 00000000 00000000 00000000 ' False (AND)

But if the operand themselves aren't of an integer type, then they get converted to one before the operator gets to look at them. That's when True becomes -1, and that's when 0.5 becomes 0.


text:
Q: How do I center a Fab inside a circular progress? I am trying to center an fab inside the circular progress bar. I was told I could use relative position for the parent and the children have absolute position. I would like to keep it responsive so if the screen is scaled down it will look the same.
These are both Material UI components.

                <DialogTitle id="form-dialog-title">Event Details</DialogTitle>

                { props.selectedEvent &&
                    <Fab aria-label="delete" size="small" onClick={handleOpenAlert} >
                        {success ? <CheckIcon /> : <DeleteIcon />}
                    </Fab>
                }
                <CircularProgress size={68}  />

.event-dialog {
    .event-dialog-header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        .event-dialog-delete {
            position: relative;
            .MuiCircularProgress-root {
                position: absolute;
                top: 0;
                right: 0;
            }
            .MuiFab-sizeSmall {
                position: absolute;
                top: 0;
                right: 0;
            }
        }
    }
}

This is what I am trying to do:

A: You have the right starting point. You just need to adjust the position of the Fab and the size of the CircularProgress.
Here is a working example:
import React from "react";
import ReactDOM from "react-dom";

import Fab from "@material-ui/core/Fab";
import DeleteIcon from "@material-ui/icons/Delete";
import CircularProgress from "@material-ui/core/CircularProgress";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  eventDialogDelete: {
    position: "relative",
    "& .MuiCircularProgress-root": {
      position: "absolute",
      // Moving this a little off the edge prevents horizontal scrollbar from flickering in and out
      top: 3,
      right: 3
    },
    "& .MuiFab-sizeSmall": {
      position: "absolute",
      top: 9,
      right: 9
    }
  }
});

function App() {
  const classes = useStyles();
  return (

      <Fab aria-label="delete" size="small">
        <DeleteIcon />
      </Fab>
      <CircularProgress size={52} />

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: App gets stuck on splash screen when running in the emulator When running in the emulator the splash screen gets stuck and never starts the next activity. I removed the splash Activity from the manifest file and made the next Activity as my launcher.  Still, when I run the app I get the splash screen. I have done everything like restarting eclipse, made new avd but I don't know from where it is getting the splash screen. I don't know why this is happening.
This works fine when running on a device, the issue only occurs when running in the emulator.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kaizen"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.kaizen.Login"
        android:configChanges="keyboardHidden"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

A: You have to uninstall all JRE 7 and install latest JRE 6 (http://www.oracle.com/technetwork/java/javase/downloads/jre6downloads-1902815.html). It will immediately fixed the problem.
See this for installation help

A: Uninstall app from emulator and then re run your app. Hope it will help you.


text:
Q: implement compareTo in generic class I wrote a class with this prototype:
public class AkbarWorks<T implements Comparable>

This class contains 2 ArrayLists:
private ArrayList<T> elements = new ArrayList<>();
private ArrayList<T> removed = new ArrayList<>();

My problem is, I want to compare 2 Objects of T, but compareTo does not work, and I could not override it. I use compareTo in this function:
 public T getMin() throws IllegalStateException {
    if (elements.size() == 0) {
        throw new IllegalStateException();
    } else {
        T min = elements.get(0);
        for (int i = 1; i < elements.size(); i++) {
            if (elements.get(i).compareTo(min) < 0)
                min = elements.get(i);
        }
        return min;
    }
}

A: the answer is : T must extends Comparable not implements.


text:
Q: Draw polygons on existing SVG to capture coordinate data We have a web application that displays a SVG map of an office. The map has small icons that represent users walking around with RF tags. This allows administrators of the system to see what rooms users are in. We are using Snap.SVG to load the office SVG file and manipulate it to display the user icons. The challenge is that the map scales to the size of the browser. Using JavaScript to determine the coordinates is not always accurate because the position of the SVG changes based on the browser size.
Here is an example of the map with the icons:

The icons are placed on the map based on X Y coordinates coming from our database. The values for the X Y coordinates are set for each location and were determined using Adobe Illustrator. Currently, we can only place one icon in a room at a time. Because we only have 1 set coordinates the icons overlap if more than one person is in a room at one time.
The second phase of this project is to allow users to draw on of the map to specify locations. Essentially, the user will set points and create a polygon to represent each location on the map. We would use the coordinates of the polygon along with the total area of the polygon to know where on the map we can place icons. This would allow users to define areas without a developer getting involved.
Here is an example of what we want to achieve .

I have been researching how to do this, but have not found anything outside of using something like the Google Maps API to draws polygons on a map. I did find this article that outlines how to dynamically pull points. We thought about using a grid system that is an overlay on the map and the user defines what grid elements are in what locations. So something like [A1,A2,B1,B2]. I persoanlly like the polygon approach as it is more visually appealing and is easier for a user to adopt.
We need some advice on where to start with this and if something like snap.svg is all we need or if we have to rely on other libraries in conjunction with snap.
Update:
With Ian's advice I found a fiddle that describes what he was talking about.
var S;
var pt;
var svg
var box;

window.onload = function(){
    svg = $('#mysvg')[0];
    S = Snap(svg);
    console.log( S );

    pt = pt = svg.createSVGPoint(); // create the point

    // add the rectangle
    box = S.rect(12,12, 12, 12);
    box.attr({ fill : 'red', stroke : 'none' });

    S.drag(
        function(dx, dy, posX, posY, e){

            //onmove
            pt.x = posX - S.node.offsetLeft;
            pt.y = posY - S.node.offsetTop;
            console.log(pt.x + "," + pt.y);

            // convert the mouse X and Y
            //so that it's relative to the svg element
            var transformed = pt.matrixTransform(svg.getCTM().inverse());
            box.attr({ x : transformed.x, y : transformed.y });
        },
        function(){
            //onstart
        },
        function(){
            //onend
        }
    );

}

The Fiddle


text:
Q: Remove duplicates without changing the order in two dimension list How could I remove duplicates two dimension list without changing the order?
list_j = [[100,2,3,3], [4,98,99,98], [5,99,98,4], [5,99,98,5], [100,99,98,100,100,6]]

list_pre = [list(set(i)) for i in list_j]
print(list_pre)

[[2, 3, 100], [98, 99, 4], [98, 99, 4, 5], [98, 99, 5], [98, 99, 100, 6]]

As you can see it changed the order. What I want is [[100,2,3,],...]
Desired output [[100,2,3,], [4,98,99], [5,99,98,4], [5,99,98], [100,99,98,6]]

A: Use OrderedDict to maintain the order of insertion of keys:
from collections import OrderedDict
list_j = [[100,2,3,3], [4,98,99,98], [5,99,98,4], [5,99,98,5], [100,99,98,100,100,6]]
output = [list(OrderedDict.fromkeys(x)) for x in list_j]

gives
[[100, 2, 3], [4, 98, 99], [5, 99, 98, 4], [5, 99, 98], [100, 99, 98, 6]]

If you using Python 3.7 or higher, you can use normal dictionaries as well since they also maintain the order of insertion:
output = [list(dict.fromkeys(x)) for x in list_j]

A: Same question here:
def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

list_j = [[100,2,3,3], [4,98,99,98], [5,99,98,4], [5,99,98,5], [100,99,98,100,100,6]]

list_pre = [f7(i) for i in list_j]

print(list_pre)

This will give the desired output

A: Try this:
def remove_duplicates(my_list):
    result_list = []
    for _list in my_list:
        result_list.append(sorted(set(_list), key=lambda ind: _list.index(ind)))
    return result_list


text:
Q: Running in circles with errors trying to git push heroku master and yarn I've been trying for 2 days to deploy my Rails/React app to Heroku and it's been a nightmare. I think I finally have the Rails side up but the React side is nothing but grief. The latest issue is a problem with yarn. I've tried to upgrade it. I updated npm, node, etc.
The issue is then I try to git push heroku master. I get the following errors which is the ending of many warning resolution incompatible errors.
emote:        warning Resolution field "whatwg-url@6.5.0" is incompatible with requested version "whatwg-url@^7.0.0"
remote:        error Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.
remote:        info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
remote:
remote: -----> Build failed
remote:
remote:  !     Outdated Yarn lockfile
remote:
remote:        Your application contains a Yarn lockfile (yarn.lock) which does not
remote:        match the dependencies in package.json. This can happen if you use npm
remote:        to install or update a dependency instead of Yarn.
remote:
remote:        Please run the following command in your application directory and check
remote:        in the new yarn.lock file:
remote:
remote:        $ yarn install
remote:        $ git add yarn.lock
remote:        $ git commit -m "Updated Yarn lockfile"
remote:        $ git push heroku master
remote:
remote:        https://kb.heroku.com/why-is-my-node-js-build-failing-because-of-an-outdated-yarn-lockfile
remote:
remote:  !     Push rejected, failed to compile React.js (create-react-app) multi app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to faunagram-app.
remote:
To https://git.heroku.com/faunagram-app.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/faunagram-app.git'

Here's what my package-json file looks like:
{
  "name": "faunagram-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "eslint-plugin-react": "^7.12.4",
    "fsevents": "^2.0.6",
    "ip-locator": "0.0.1",
    "iplocation": "^6.1.0",
    "react": "^16.8.4",
    "react-activestorage-provider": "^0.8.0",
    "react-dom": "^16.8.4",
    "react-geolocated": "^2.4.1",
    "react-router-dom": "^4.4.0-beta.7",
    "react-scripts": "3.0.1",
    "semantic-ui-react": "^0.86.0",
    "yarn": "^1.16.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "description": "An informative and social media app for all things urban wildlife. As our urban centers have cleaned up through the years, many animal species are returning. This app allows for people to share sightings of these creatures. See video DEMO here. Screenshot",
  "main": "index.js",
  "devDependencies": {},
  "repository": "git+https://github.com/dsound-zz/faunagram-frontend.git",
  "author": "Demian Sims",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/dsound-zz/faunagram-frontend/issues"
  },
  "homepage": "https://github.com/dsound-zz/faunagram-frontend#readme",
  "resolutions": {
    "fsevents": "1.2.9",
    "doctrine": "3.0.0",
    "resolve": "1.1.7",
    "js-tokens": "3.0.2",
    "debug": "2.6.9",
    "ms": "2.0.0",
    "tough-cookie": "2.5.0",
    "punycode": "1.3.2",
    "extsprintf": "1.4.0",
    "@babel/runtime": "7.4.3",
    "regenerator-runtime": "0.11.1",
    "path-to-regexp": "0.1.7",
    "core-js": "2.6.5",
    "promise": "8.0.2",
    "iconv-lite": "0.4.23",
    "isarray": "1.0.0",
    "@babel/core": "7.4.4",
    "camelcase": "4.1.0",
    "fs-extra": "4.0.3",
    "jest-resolve": "24.8.0",
    "semver": "5.5.0",
    "json5": "1.0.1",
    "source-map": "0.6.1",
    "chalk": "1.1.3",
    "ansi-styles": "2.2.1",
    "supports-color": "2.0.0",
    "color-name": "1.1.4",
    "jsesc": "0.5.0",
    "minimist": "0.0.10",
    "@babel/preset-env": "7.4.4",
    "@babel/plugin-proposal-object-rest-spread": "7.4.4",
    "@babel/plugin-transform-classes": "7.4.4",
    "@babel/plugin-transform-destructuring": "7.4.4",
    "browserslist": "4.5.4",
    "cosmiconfig": "4.0.0",
    "import-fresh": "2.0.0",
    "parse-json": "2.2.0",
    "resolve-from": "3.0.0",
    "callsites": "2.0.0",
    "esprima": "3.1.3",
    "is-arrayish": "0.3.2",
    "vfile": "3.0.1",
    "parse5": "4.0.0",
    "is-buffer": "1.1.6",
    "unist-util-stringify-position": "1.1.2",
    "vfile-message": "1.1.1",
    "clone-deep": "0.2.4",
    "kind-of": "3.2.2",
    "for-own": "0.1.5",
    "lazy-cache": "0.2.7",
    "shallow-clone": "0.1.2",
    "for-in": "0.1.8",
    "isobject": "2.1.0",
    "is-extendable": "1.0.1",
    "css-select": "2.0.2",
    "css-tree": "1.0.0-alpha.29",
    "domutils": "1.7.0",
    "eslint-scope": "4.0.3",
    "slash": "1.0.0",
    "normalize-path": "2.1.1",
    "readable-stream": "3.3.0",
    "inherits": "2.0.1",
    "string_decoder": "1.1.1",
    "pump": "2.0.1",
    "string-width": "1.0.2",
    "strip-ansi": "3.0.1",
    "is-fullwidth-code-point": "1.0.0",
    "ansi-regex": "2.1.1",
    "define-property": "0.2.5",
    "extend-shallow": "2.0.1",
    "is-descriptor": "0.1.6",
    "is-accessor-descriptor": "0.1.6",
    "is-data-descriptor": "0.1.4",
    "has-value": "0.3.1",
    "set-value": "0.4.3",
    "has-values": "0.1.4",
    "find-up": "2.1.0",
    "locate-path": "2.0.0",
    "p-locate": "2.0.0",
    "path-exists": "3.0.0",
    "p-limit": "1.3.0",
    "p-try": "1.0.0",
    "read-pkg-up": "4.0.0",
    "require-main-filename": "2.0.0",
    "read-pkg": "3.0.0",
    "load-json-file": "4.0.0",
    "path-type": "3.0.0",
    "pify": "2.3.0",
    "find-cache-dir": "0.1.1",
    "pkg-dir": "2.0.0",
    "postcss-selector-parser": "3.1.1",
    "cssesc": "2.0.0",
    "ignore": "3.3.10",
    "inquirer": "6.2.2",
    "acorn": "5.7.3",
    "mimic-fn": "1.2.0",
    "wordwrap": "0.0.3",
    "commander": "2.17.1",
    "uglify-js": "3.5.12",
    "yargs": "12.0.5",
    "jsdom": "11.12.0",
    "whatwg-url": "6.5.0",
    "ws": "5.2.2",
    "decamelize": "1.2.0",
    "yargs-parser": "11.1.1",
    "address": "1.1.0",
    "globby": "6.1.0",
    "opn": "5.5.0",
    "is-glob": "3.1.0",
    "faye-websocket": "0.10.0",
    "mime": "1.4.1",
    "util": "0.10.3",
    "array-flatten": "1.1.1",
    "statuses": "1.5.0"
  }
}

There's also a yarn error file:
Arguments:
  /Users/demiansims/.nvm/versions/node/v12.2.0/bin/node /usr/local/Cellar/yarn/1.16.0/libexec/bin/yarn.js install

PATH:
  /Users/demiansims/.nvm/versions/node/v12.2.0/bin:/Users/demiansims/.rvm/gems/ruby-2.6.0/bin:/Users/demiansims/.rvm/gems/ruby-2.6.0@global/bin:/Users/demiansims/.rvm/rubies/ruby-2.6.0/bin:/usr/local/opt/ruby/bin:/Applications/Postgres.app/Contents/Versions/latest/bin:/usr/local:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin:/opt/X11/bin:/usr/local/git/bin:/Applications/Postgres.app/Contents/Versions/latest/bin:/usr/local/opt/ruby/bin:/usr/local:/usr/local/sbin:/Users/demiansims/.rvm/bin

Yarn version:
  1.16.0

Node version:
  12.2.0

Platform:
  darwin x64

Trace:
  SyntaxError: /Users/demiansims/Development/Faunagram/Faunagram-frontend/package.json: Unexpected token } in JSON at position 161
      at JSON.parse (<anonymous>)
      at /usr/local/Cellar/yarn/1.16.0/libexec/lib/cli.js:1625:59
      at Generator.next (<anonymous>)
      at step (/usr/local/Cellar/yarn/1.16.0/libexec/lib/cli.js:304:30)
      at /usr/local/Cellar/yarn/1.16.0/libexec/lib/cli.js:315:13

npm manifest:
  {
    "name": "vulture",
    "version": "1.0.0",
    "description": "vulture",
    "main": "index.js",
    "private": true,
    "scripts": {
      "start": "node index.js",
    },
    "author": "vulture",
    "license": "ISC",
    "dependencies": {
      "node": "8.4.0",
      "npm": "5.4.0"
    }
  }

yarn manifest:
  No manifest

Lockfile:
  No lockfile

I've tried following the instructions listed in the error but keeps coming back to this. I also had a problem with installing yarn with something called fsevents having a problem with the version of node I'm using. I brew updated node to fix that (I think). Sorry to be a pain but this is my first attempt at deploying an app and it's been nothing but hell. Seems like it shouldn't be this difficult.


text:
Q: Is there any group of order 12 which has a unique Sylow 3-subgroup and unique Sylow 2-subgroup? Is there any group of order 12 which has a unique Sylow 3-subgroup and unique Sylow 2-subgroup?
In my text, Dummit and Foote, in applications of Sylow theorems, it's mentioned that  either if $G$ is a group and $|G|=12$ then $G$ has a normal Sylow 3-subgroup or $G \cong A_4 $ (in the later case $G$ has normal Sylow 2-subgroup) and I wonder is "either, or " exclusive or ? or is it inclusive or ?

A: Yes, the cyclic group $\mathbb{Z}_{12}$ has unique Sylow $2$- and $3$-subgroups. In general, an abelian group will have a normal (hence unique) Sylow $p$-subgroup for every prime $p$ dividing the group order. Thus, $\mathbb{Z}_6 \times \mathbb{Z}_2$ also has this property, being the (unique) non-cyclic abelian group of order $12$.


text:
Q: How to write config.yml file in circleCI for java-maven based appium scripts? Unable to write configyml in circleCI for java-mave based appium scripts I have written scripts using appium java client and maven and i need to run the with circleCI
can anyone help me with this?
Below is the yml file I wrote but its not working for me
version: 2
jobs:
  build:
    docker:
      # specify the version you desire here
      - image: circleci/openjdk:8-jdk-node
      - image: appium/appium-emulator

    environment:
      # Customize the JVM maximum heap limit
      MAVEN_OPTS: -Xmx3200m

    steps:
      - checkout
      # Download and cache dependencies
      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "pom.xml" }}
            # fallback to using the latest cache if no exact match is found
            - v1-dependencies-
      - run: mvn dependency:go-offline

      - save_cache:
          paths:
            - ~/.m2
          key: v1-dependencies-{{ checksum "pom.xml" }}

        # run tests!
      - run: mvn clean
      - run: mvn test
    workflows:
    maven_test:
    jobs:
      - maven/test

here is the error it gave
Its showing the app is not present at given location but i have checked manually its there
is there a way to solve this?
Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command. Original error: Could not find app apk at /home/circleci/project/App/eezy-uat-2.apk (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 38.57 seconds Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: '8908ccb13df1', ip: '192.168.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-1092-aws', java.version: '1.8.0_265' Driver info: driver.version: AndroidDriver Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: '8908ccb13df1', ip: '192.168.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-1092-aws', java.version: '1.8.0_265' Driver info: driver.version: AndroidDriver

      org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command. Original error: Could not find app apk at /home/circleci/project/App/app.apk (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 38.57 seconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: '8908ccb13df1', ip: '192.168.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-1092-aws', java.version: '1.8.0_265'
Driver info: driver.version: AndroidDriver
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: '8908ccb13df1', ip: '192.168.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-1092-aws', java.version: '1.8.0_265'
Driver info: driver.version: AndroidDriver
at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:208)
at io.appium.java_client.remote.AppiumCommandExecutor.createSession(AppiumCommandExecutor.java:217)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:41)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
at io.appium.java_client.AppiumDriver.startSession(AppiumDriver.java:336)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
at io.appium.java_client.DefaultGenericMobileDriver.<init>(DefaultGenericMobileDriver.java:37)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:88)
at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:98)
at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:94)
at com.eezy.generics.BaseTest.beforeMethod(BaseTest.java:132)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:186)
... 42 more
Caused by: org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Could not find app apk at /home/circleci/project/App/app.apk (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 38.57 seconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: '8908ccb13df1', ip: '192.168.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0-1092-aws', java.version: '1.8.0_265'
Driver info: driver.version: AndroidDriver
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at org.openqa.selenium.remote.JsonWireProtocolResponse.lambda$errorHandler$0(JsonWireProtocolResponse.java:54)
at org.openqa.selenium.remote.HandshakeResponse.lambda$getResponseFunction$0(HandshakeResponse.java:30)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:126)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:128)
... 47 more
... Removed 33 stack frames


text:
Q: Xcode: Delete files but still tracked by git I delete files from my project that I no longer want. But when I want to commit, git keeps tracking them as "new file: project / myFile.swift"
How can I do to delete files permanently in Xcode? so they don't show up in git when I want to commit ?
is it possible to fix this without using git ignore?

A: Delete files from Xcode
Instead of clicking Remove Reference, click Move to Trash.
Removing the reference only removes the file from Xcode project but it does not remove it from the project directory.


text:
Q: How do I implement option buttons and change the button color in PyGame? Pls suggest how can I change the color of the button when I pressed it, and the color of the first button will be changed to the default color when I pressed the second button.
For example, After I clicked the STRAIGHT Button, the button will become green color and when I click the LEFT button the LEFT button will change to green color and the STRAIGHT button will become the default color which is white color. Thanks in advance :)

CODE:
def draw_button(self):

    global clicked
    action = False

    # get mouse position
    pos = pygame.mouse.get_pos()

    # create pygame Rect object for the button
    button_rect = Rect(self.x, self.y, self.width, self.height)

    # check mouseover and clicked conditions
    if button_rect.collidepoint(pos):
        if pygame.mouse.get_pressed()[0] == 1:
            clicked = True
            pygame.draw.rect(screen, self.click_col, button_rect)
        elif pygame.mouse.get_pressed()[0] == 0 and clicked == True:
            clicked = False
            action = True

        else:
            pygame.draw.rect(screen, self.hover_col, button_rect)
    else:
        pygame.draw.rect(screen, self.button_col, button_rect)

A: When you draw the button, you have to set the color dependent on the global variable clicked:
def draw_button(self):

    global clicked

    # get mouse position
    pos = pygame.mouse.get_pos()

    # create pygame Rect object for the button
    button_rect = Rect(self.x, self.y, self.width, self.height)

    # check mouseover and clicked conditions
    hover = button_rect.collidepoint(pos)
    if hover and pygame.mouse.get_pressed()[0] == 1:
        clicked = not clicked

    color = self.button_col
    if clicked:
        color = self.click_col
    elif hover:
        color = self.hover_col

    pygame.draw.rect(screen, color, button_rect)

Anyway, that won't satisfy you, because pygame.mouse.get_pressed() returns a list of Boolean values that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down.
You have to use MOUSEBUTTONDOWN event. The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked.

If you have multiple buttons that you have to interact with each other, a single clicked status is not enough. You need a separate "clicked" state for each button. If the clicked state of 1 button becomes True, the states of the other keys must be set to False. I recommend to implement a RadioButton class for this.
See also Mouse and Sprite.
Minimal example:
 repl.it/@Rabbid76/PyGame-RadioButton

import pygame

class RadioButton(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h, font, text):
        super().__init__()
        text_surf = font.render(text, True, (0, 0, 0))
        self.button_image = pygame.Surface((w, h))
        self.button_image.fill((96, 96, 96))
        self.button_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        self.hover_image = pygame.Surface((w, h))
        self.hover_image.fill((96, 96, 96))
        self.hover_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        pygame.draw.rect(self.hover_image, (96, 196, 96), self.hover_image.get_rect(), 3)
        self.clicked_image = pygame.Surface((w, h))
        self.clicked_image.fill((96, 196, 96))
        self.clicked_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        self.image = self.button_image
        self.rect = pygame.Rect(x, y, w, h)
        self.clicked = False
        self.buttons = None

    def setRadioButtons(self, buttons):
        self.buttons = buttons

    def update(self, event_list):
        hover = self.rect.collidepoint(pygame.mouse.get_pos())
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if hover and event.button == 1:
                    for rb in self.buttons:
                        rb.clicked = False
                    self.clicked = True

        self.image = self.button_image
        if self.clicked:
            self.image = self.clicked_image
        elif hover:
            self.image = self.hover_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
font50 = pygame.font.SysFont(None, 50)

radioButtons = [
    RadioButton(50, 40, 200, 60, font50, "option 1"),
    RadioButton(50, 120, 200, 60, font50, "option 2"),
    RadioButton(50, 200, 200, 60, font50, "option 3")
]
for rb in radioButtons:
    rb.setRadioButtons(radioButtons)
radioButtons[0].clicked = True

group = pygame.sprite.Group(radioButtons)

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

A: your_button_rect = pygame.Rect(x,y,width,height)
color = (0,0,0)
pos = pygame.mouse.get_pos()
def change_button_color():
    if your_button_rect.colliderect(pos):
        if event.type == pygame.MOUSEBUTTONDOWN: #checks if mouse button is pressed down while the cursor is on the rectangle
            color = (your_desired_Color_RGBvalue)

while True:
    pygame.draw.rect(screen,color,your_button_rect)
    change_button_color()


text:
Q: One USB device, two serial interfaces: how to? I have a serial device that should be exposed as two serial ports: /dev/ttyACM0 and /dev/ttyACM1.
Currently I only get the first one despite the same unit under Windows exposes as the expected two serials.
My dmesg reports this:
[ 2738.788150] usb 2-1.2: new full-speed USB device number 3 using ehci-pci
[ 2738.876575] usb 2-1.2: New USB device found, idVendor=152a, idProduct=8230
[ 2738.876584] usb 2-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 2738.876590] usb 2-1.2: Product: Septentrio USB Device
[ 2738.876594] usb 2-1.2: Manufacturer: Septentrio
[ 2738.941229] cdc_acm 2-1.2:1.0: ttyACM0: USB ACM device
[ 2738.942171] usbcore: registered new interface driver cdc_acm
[ 2738.942174] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN

While lsusb -vvv says this.
The relevant part from /sys/kernel/debug/usb/devices is this:
T:  Bus=01 Lev=02 Prnt=02 Port=02 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
D:  Ver= 1.10 Cls=02(comm.) Sub=00 Prot=00 MxPS= 8 #Cfgs=  2
P:  Vendor=152a ProdID=8230 Rev= 1.10
S:  Manufacturer=Septentrio
S:  Product=Septentrio USB Device
C:  #Ifs= 4 Cfg#= 2 Atr=c0 MxPwr=  2mA
I:  If#= 0 Alt= 0 #EPs= 0 Cls=02(comm.) Sub=02 Prot=ff Driver=
I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=ff Driver=
E:  Ad=01(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms
E:  Ad=82(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms
I:  If#= 2 Alt= 0 #EPs= 0 Cls=02(comm.) Sub=02 Prot=ff Driver=
I:  If#= 3 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=ff Driver=
E:  Ad=04(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms
E:  Ad=85(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms
C:* #Ifs= 2 Cfg#= 1 Atr=c0 MxPwr=  2mA
I:* If#= 0 Alt= 0 #EPs= 1 Cls=02(comm.) Sub=02 Prot=01 Driver=cdc_acm
E:  Ad=83(I) Atr=03(Int.) MxPS=  64 Ivl=1ms
I:* If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
E:  Ad=01(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms
E:  Ad=82(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms

Here my device (a GPS modem) is Bus 001 Device 004: ID 152a:8230 Thesycon Systemsoftware & Consulting GmbH.
I thought that the cdc_acm module had some option to be used with modprobe/insmod, but it seems it's not easy to find anything about it.
How can I have both serial ports recognized/created/enabled under Ubuntu?
TIA.
[UPDATE] I have also found another question tightly linked to mine. But have no idea on how to implement the suggested changes.

A: The solution requires you to load of a kernel module, namely drivers/usb/serial/option.ko and to ask udev to apply some changes as soon as the device gets recognized (switch to the second configuration and enable the serial driver for the specific device). So:

*

*Have the option.ko module loaded at boot

*Create a brand new udev rule like this very one:
SUBSYSTEMS=="usb", ATTRS{product}=="Septentrio USB Device", ATTR{bConfigurationValue}="2", PROGRAM+="/bin/bash -c \"/bin/echo $VENDOR $PRODUCT > /sys/bus/usb-serial/drivers/option1/new_id\""


text:
Q: Is it possible to hide the Toolbar and disable the scroll when swiping to specific page? I would like to be able to hide the Toolbar on swipe to a specific tab and then lock it. Expanding it and then locking would also work for me although i prefer the first.
I have tried doing stuff like in the code below, but it gives rise to some snappy behavior because the page is scrolled of the screen originally. As soon as i set the scroll flags to 0, the whole page snaps back up and then locks the screen with the toolbar expanded which makes sense because with scroll flags set to zero, the page should not be able to scroll off the screen at all so it just snaps back up.
The page I am tending to is a chat page and in order to have a static text input bar at the bottom I really need to disable the scrolling for that page while making it possible for the others.
Can you guys think of some way to accomplish this?
Activity:
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group);
    appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // add all the needed fragments for the tabs inside a Vector
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(pagerAdapter);
    viewPager.setOffscreenPageLimit(4);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    viewPager.clearOnPageChangeListeners();
    viewPager.addOnPageChangeListener(new TabLayoutOnPageChangeListenerGroups(tabLayout, this, fab, appBarLayout));

    viewPager.setCurrentItem(CURRENT_TAB);
}

public void disableToolbarScrolling()
{
    logger.d("disabling scrolling toolbar");
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    params.setScrollFlags(0);  // clear all scroll flags
    toolbar.setLayoutParams(params);
}

public void enableToolbarScrolling()
{
    logger.d("enabling scrolling toolbar");
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);  // clear all scroll flags
    toolbar.setLayoutParams(params);
}

And then using a PageChangeListener to handle the event:
public TabLayoutOnPageChangeListenerGroups(TabLayout tabLayout, Activity activity, FloatingActionsMenu fab, AppBarLayout appBarLayout)
{
    ...
    this.appBarLayout = appBarLayout;
    ...
}

private void enableScrolling()
{
    ((GroupActivity) mActivity).enableToolbarScrolling();
    toolbarState = toolbarState_enabled;
}

private void disableScrolling()
{
    ((GroupActivity) mActivity).disableToolbarScrolling();
    toolbarState = toolbarState_disabled;
}

@Override
public void onPageSelected(int position)
{
    if(position == 0)
    {
        logger.d("pos 0");
        disableScrolling();
        appBarLayout.setExpanded(false);
    }
    else
    {
        logger.d("pos != 0");
        enableScrolling();
    }
}

EDIT 1:
I have tried setting toolbar visibility to both GONE or INVISIBLE. But they only make the toolbar white, giving a white bar at the top of the screen. Still allowing for the scrolling behaviour.

A: add this line to your code in onCreate
setSupportActionBar(toolbar); and then add
toolbar.setVisibility(View.GONE);

A: For hiding the toolbar you can just try :
getSupportActionBar().hide();