text:
Q: How to use same MPLS Traffic Engineering tunnel for ipv4 and ipv6 I have MPLS TE configured and working, but it is currently using IPV4 and I needed to include IPV6.
My current tunnel configuration is the following:
interface Tunnel1
 ip unnumbered Loopback0
 ipv6 enable
 tunnel destination 200.0.0.2
 tunnel mode mpls traffic-eng
 tunnel mpls traffic-eng autoroute announce
 tunnel mpls traffic-eng priority 7 7
 tunnel mpls traffic-eng bandwidth  2000
 tunnel mpls traffic-eng path-option 1 dynamic
 no routing dynamic
!

I know I need to activate ipv6 cef.
I have currently configured PBR (Policy Based Routing) to route all the traffic I need through this tunnel:
access-list 101 permit icmp 81.100.1.192 0.0.0.63 81.100.1.0 0.0.0.63

route-map trafficTOOPorto permit 10
 match ip address 101
 set interface Tunnel1
!

I wanted to know how can I achieve the same but using IPV6 (which I have configured in all other interfaces of the network). I already know that IPV6 is not supported by MPLS. So what should I do?

A: The setup required for forwarding IPv6 traffic over an MPLS network is called 6PE. Rather than using RSVP or LDP to distribute labels, BGP Labeled Unicast (BGP-LU) is used. They key to enabling 6PE is the activation of the BGP-LU Network Layer Reachability Information (NLRI).
Here are configuration examples for Junos and IOS.

Junos
[edit protocols bgp]
group 6PE {
    [...]
    family inet6 {
        labeled-unicast {
            explicit-null;
        }
    }
    [...]
}

IOS
address-family ipv6
  neighbor x.x.x.x activate
  neighbor x.x.x.x send-label
  network 2001:DB8:FFFF::/48
  exit-address-family

There are some tricky issues involved such as setting of the BGP next hop. All of these are documented on the web. You can find numerous example configurations as well. Use the text "6PE" and your vendor's name.


text:
Q: How do I get multiple rows for a node's data section in NetworkX I have the following pandas data frame:
    Node      Col1  Col2  Col3
     1         A     B     C
     1         D     E     F
     1         G     H     I
     2         A     B     I
     2         G     E     F

I need to put each Node into a Graph (which I can do) but I need the data section to include all rows for each Column. Such that I can access each columns' data and retrieve the correct row.
I think I want a Dictionary where for Node 1: {Col1: [A, D, G], Col2: [B, E, H], Col3: [C, F, I]} but I know lists/dictionaries can be weird each row data would need to be accessed so if I want access Col1: D; I can also access Col2: E, and Col3: F.
In other words, the ordinal position of each list in the dictionary accesses the correct data.
I've done a groupby on the data frame such as:
    df.groupby('Node')['Col1'].apply(list)

will give me the list I want but am I guaranteed that each list will have the correct ordinal position of the data.
Is there a way to combine multiple dictionary values into a Node's data section and then access it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server getting values from 4 tables into ONE I have 5 Tables :
1- UserAccount : Has AccountNumber field
2- Total Amount : Has AccountNumber field
3- Total Withdrawal : Has AccountNumber field
4- Total Profit : Has AccountNumber field
5- Balance : Has AccountNumber field

I need to get the values of [Total Amount], [Total Withdrawal], [Total Profit] & [Balance] for each user in ONE table to be like:
AccountNumber   Balance   Total Amount  Total Withdrawal  Total Profit
----------------------------------------------------------------------------------
201               450           600              150                250
222               600           800              200                150

I used this query but the results isn't correct:
SELECT DISTINCT
dbo.useraccount.AccountNumber,
dbo.useraccount.FirstName,
dbo.useraccount.SecondName,
dbo.Balance.Balance,
sum(dbo.[Total Amount].DepositTotal) AS [Total Deposit],
Sum(dbo.[Total Profit].ProfitTotal) AS [Total Profit],
Sum(dbo.[Total Withdrawal].WithdrawalTotal) AS [Total Withdrawal]

FROM
dbo.useraccount ,
dbo.Balance ,
dbo.[Total Amount] ,
dbo.[Total Profit] ,
dbo.[Total Withdrawal]
WHERE
dbo.useraccount.AccountNumber = dbo.Balance.AccountNumber AND
dbo.useraccount.AccountNumber = dbo.[Total Amount].AccountNumber AND
dbo.useraccount.AccountNumber = dbo.[Total Profit].AccountNumber AND
dbo.useraccount.AccountNumber = dbo.[Total Withdrawal].AccountNumber
GROUP BY
dbo.useraccount.AccountNumber,
dbo.useraccount.FirstName,
dbo.useraccount.SecondName,
dbo.Balance.Balance

Any help please?
The results i am getting is something like this:
AccountNumber   Balance   Total Amount  Total Withdrawal  Total Profit
-----------------------------------------------------------------------
201         5316.52    291060.00      86328.20         51150.00
220         35000.00   2086400.00     648000.00        532800.00
221         12000.00   192000.00      44548.00         44548.00
222          8500.00   76500.00       12003.75         12003.75
224          4000.00   484000.00      120780.00        120780.00
226          2393.50   48000.00       5206.50          10736.00

When i run this query for [Total Profit] i get correct results:
SELECT DISTINCT
dbo.[Total Profit].AccountNumber,
Sum(dbo.[Total Profit].ProfitTotal) As [Total Deposit]

FROM
dbo.[Total Profit]
GROUP BY
dbo.[Total Profit].AccountNumber

A: Well, given that you haven't posted your tables definition, you can do this to avoid the duplication of rows:
SELECT  UA.AccountNumber,
        UA.FirstName,
        UA.SecondName,
        B.Balance,
        TA.DepositTotal [Total Deposit],
        TP.ProfitTotal [Total Profit],
        TW.WithdrawalTotal [Total Withdrawal]
FROM dbo.useraccount UA
LEFT JOIN ( SELECT AccountNumber, SUM(Balance) Balance
            FROM dbo.Balance
            GROUP BY AccountNumber) B
    ON UA.AccountNumber = B.AccountNumber
LEFT JOIN ( SELECT AccountNumber, SUM(DepositTotal) DepositTotal
            FROM dbo.[Total Amount]
            GROUP BY AccountNumber) TA
    ON UA.AccountNumber = TA.AccountNumber
LEFT JOIN ( SELECT AccountNumber, SUM(ProfitTotal) ProfitTotal
            FROM dbo.[Total Profit]
            GROUP BY AccountNumber) TP
    ON UA.AccountNumber = TP.AccountNumber
LEFT JOIN ( SELECT AccountNumber, SUM(WithdrawalTotal) WithdrawalTotal
            FROM dbo.[Total Withdrawal]
            GROUP BY AccountNumber) TW
    ON UA.AccountNumber = TW.AccountNumber

Of course, you shouldn't need to do that aggregation for every table, only the ones that have multiple rows for each AccountNumber.


text:
Q: C# - Variable does not exists in current context I have a problem I can't seem to solve.
I created a class function called test and in the function I declared a variable.
On the next line I fill the function with a string.
During debugging the variable does not get declared, my variable watcher in VS tells me that the variable does not exists in the current context.
Can you all help me solve this problem ?
Here is my code:
public void Test()
{
    string DirectoryPath;
    DirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
}

A: My guess is you're using a Release configuration - the optimizer may have removed the variable, as it's pointless other than for debugging. You assign it a value, but never read it. In a Debug configuration, I'd expect it to be fine (but possibly create a warning).
EDIT: Of course, this is assuming that you were in the Test() method that you couldn't see the variable. If Test() had already completed then Likurg's answer is probably more appropriate.

A: If i'm not mistake you want to do this
    public class MyTest
    {
        string DirectoryPath = "";
        public void Test()
        {
            DirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache);
        }
        public void UseString()
        {
            //Use DirectoryPath
        }
    }


text:
Q: Issue With Pear DB In Many Hosting Providers I Connect and Query My Db Using PEAR DB Like This:
if(stristr($_SERVER['HTTP_HOST']  , 'localhost')){
    $dsn = 'mysql://root:@localhost/xxx' ;
}else{
    $dsn = 'mysql://xxx:xxx@localhost/xxx' ;
}
$dbc =& DB::connect($dsn);
$dbc->query("set names utf8" );
if (PEAR::isError($dbc , array('debug'=>3))) {
    die($dbc->getMessage());
}

In some hosting providers it's working perfectly and for example, if the database user doesn't have sufficient permissions, it says: Insufficient Permission, and some other errors. Also, when I fix the problem, the site will come up and runs well.
However, in many hosting providers it doesn't show many errors! And nothing on the page either! The page is completely blank, no errors, no notice, nothing! I've also set error_reporting(E_ALL) in top of my script, and I still can't find the bug. Is there any solution for such a problem?

A: Make sure display_errors is on (or check the logs):
ini_set('display_errors', true);


text:
Q: Postgres 11 - COMMIT Procedure With the recent update of Postres 11. It now supports stored procedures. Transactions are finally supported in stored procedures in Postgres. However, I have been trying to perform a commit within a procedure with no luck.
    CREATE OR REPLACE PROCEDURE test_update(
        IN pid character,
        IN pcategoryname character varying,
        IN pwebcode character varying,
        IN porder numeric,
        IN pupdatedby character varying,
        IN pupdateddate timestamp without time zone,
        IN plang character varying,
        INOUT cresults refcursor)
      LANGUAGE plpgsql
    AS
    $BODY$
    DECLARE

      cnt bigint;
      rtnCode char(1);

    BEGIN
     cresults := 'cur';

        BEGIN
        update test_table
        set  FCATEGORYNAME   = pCategoryName,
             FWEBCODE        = pWebCode,
             FORDER          = pOrder,
             FUPDATEDBY      = pUpdatedBy,
             FUPDATEDDATE    = pUpdatedDate,
             FLANGCODE       = pLang
        where lower(FID) = lower(pId);
        COMMIT;
        end;
      .
      .
      EXCEPTION WHEN ....
      .
      .
     OPEN cresults FOR VALUES ('stringresult');

    end;
    $BODY$;

UPDATED
Edited so that the Update and Commit is within a block that does not have any exception.
This was previously used to execute the procedure. I was able to fetch the result of the refcursor. Does not work anymore after the commit is added.:
begin;
CALL testupdate('ad3caecb-9235-4945-b37a-9b7ff89fdfe0','aa','138',0,'test','2018/06/29 18:04:03','zh-cn','');
fetch all in cur;
commit;

but when i execute with:
CALL testupdate('ad3caecb-9235-4945-b37a-9b7ff89fdfe0','aa','138',0,'test','2018/06/29 18:04:03','zh-cn','');

.. it runs fine and the row got updated, but this way of running doesnt allow me to fetch the result my refcursor.
Is there any way to get the result of my refcursor when excuting a procedure with COMMIT. Any help is greatly appreciated. Thanks


text:
Q: Describe all k-tuples (n1, n2,...,nk) of natural numbers, k = 1, 2,..., such that complete bipartite graph K(n1,n2,...,nk) is a planar graph. I have tried this question by drawing different graphs and guessing but nothing general in is coming to be true for all complete bipartite graphs.
Question-
Describe all k-tuples $(n_1, n_2,...,n_k)$ of natural numbers, $k = 1, 2,...,$
such that complete bipartite graph $K(n_1,n_2,...,n_k)$ is a planar graph.


text:
Q: Override Extension (/vendor) in app/frontend I'm trying to override a layout .phtml file for a 3rd party extension which is located in /var/vendor_name/extension.
As I understand, I should not be modifying the /vendor files, but this extension has no files located in the app/code or app/frontend.
The file I'm trying to override is located in <magento_root>/vendor/vendor_name/module_name/view/frontend/templates/product/view/list.phtml
I read through the following thread but I'm not sure how to apply it in my situation Magento 2: How to Override File in Vendor Folder
Please let me know if more information needed.
Thanks

A: You can do that two ways:

*

*Create a module and overwrite the template

*Copy that template under your current theme

Here is the solution for #2.

*

*Create a directory VendorName_ModuleName under app/design/frontend/ThemeVendor/ThemeName/

*Copy templates/product/view/list.phtml to app/design/frontend/ThemeVendor/ThemeName/VendorName_ModuleName/templates/product/view/list.phtml


text:
Q: Is there a way to define a skew_symmetric variable in cvxpy? I want to define a 'skew_symmetric' variable in cvxpy, with real elements. Is there a short way to do this? The package supports defining 'symmetric' variables but not 'skew_symmetric' variables.
Thanks.

A: As far as I know, there is no direct way to declare 'skew_symmetric' variable. But you can easily enforce it with a relevant constraint over the variable.
A matrix is skew symmetric if A^T = -A, so you can add it as a constraint:
skew_constraint = [A.T == -A]


text:
Q: KendoUI Grid issue I have this KendoUI Grid which calls a controller method to display some data. The call is successful, and by looking at Fiddler, I could find that data is actually returned. But it is not displaying in the columns at all.
Here is my grid:
$("#someGrid").kendoGrid({
    height: 400,
    columns: [
        { field: "ProductID", width: "60px", title: "ID" },
        { field: "ProductName", width: "150px", title: "Name" },
        { field: "Price", width: "300px", title: "Price" },
        { field: "VAT", width: "100px", title: "VAT" },
        { field: "Discount", width: "100px", title: "Discount" }
    ],
    editable: false, // enable editing
    //editable: "inline",
    //pageable: false,
    //sortable: false,
    //filterable: false,
    dataSource: {
    //    serverPaging: true,
    //    serverFiltering: true,
    //    serverSorting: true,
        pageSize: 10,
        schema: {

            model: { // define the model of the data source. Required for validation and property types.
                id: "ProductID",
                fields: {
                    ProductID: { editable: false, nullable: true},
                    ProductName: { type: "string", editable: false },
                    Price: { type: "number", validation: { required: true, min: 1 } },
                    VAT: { type: "number",  validation: { required: true, min: 1 } },
                    Discount: { type: "number", editable: true, validation: {required: false} }
                }
            }
        },
        //requestEnd: onRequestEnd,
        //batch: true, // enable batch editing - changes will be saved when the user clicks the "Save changes" button
        transport: {
            read: {
                url: "Product/GetPrices?productIDs="+productIDs, //specify the URL which should return the records. This is the Read method of the HomeController.
                contentType: "application/json",
                type: "POST" //use HTTP POST request as by default GET is not allowed by ASP.NET MVC
            },
            parameterMap: (ProductsPriceList)=> JSON.stringify(ProductsPriceList)
            }
        }
    });

Here is my controller method:
public ActionResult GetPrices(List<string> productIDs)
{
    var prodIDs = ParseHelper.ParseDelimitedString(productIDs, ',');

    var productsPriceList = new List<ProductPriceVM>();

    var productSelectorVM = new ProductSelectorVM();

    foreach (var prodID in prodIDs)
    {
        if (!string.IsNullOrEmpty(prodID))
        {
            var productPriceVM = new ProductPriceVM();
            int intProdID;
            var result = int.TryParse(prodID, out intProdID);
            var product = _productRepository.GetAllProducts().SingleOrDefault(p => p.ProductID == intProdID);
            if (product != null)
            {
                productPriceVM.ProductName = product.ProductName;
                productPriceVM.ProductID = product.ProductID;

                productPriceVM.Price = product.UnitPrice;

                productPriceVM.VAT = product.VAT;
            }
            productsPriceList.Add(productPriceVM);
            productSelectorVM.ProductPriceList = productsPriceList;
        }
    }
    return Json(new { ProductsPriceList = productsPriceList.ToList(), ok = true }, JsonRequestBehavior.AllowGet);
}

A: try to change transport->read->dataType to json. because kendo ui datasource default read, dataType jsonp.
 transport: {
        read: {
            url: "Product/GetPrices?productIDs="+productIDs,
            contentType: "application/json",
            type: "POST",
            dataType: "json"
        },
        parameterMap: (ProductsPriceList)=> JSON.stringify(ProductsPriceList)
        }
    }

A: Try this, in parameterMap, don't stringify the result. You are already returning JSON, so there is no need to stringify a result that is already a JSON string.
FYI, the HTML5 kendo demos include this:
 if (operation !== "read" && options.models) {
     return {models: kendo.stringify(options.models)};
 }

... in other words, they don't stringify the read result.


text:
Q: Fatal Error: error when reading "C:\OpenSSL-Win32\lib\libeay32.lib": unexpected end-of-file i want to implement cryptographic algorithm to the arm at91sam7 micro. so i started with simple sha-1 openssl hash function. i could compile this sample code of sha-1 with code::block software and got true output. but when i want to use this code in my micro, i must compile and built it with arm compiler (for example IAR Workbench especially). i could compile the code in IAR truly but when i want to built it, i give no definitions errors. so i added C:\OpenSSL-Win32\lib\libeay32.lib to the linker additional library but i give this linker error:
'Fatal Error: error when reading "C:\OpenSSL-Win32\lib\libeay32.lib": unexpected end-of-file'.
could every one help me?Appreciate the help.
my sample code is:
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>

int main (){

   EVP_MD_CTX sha1ctx;
  unsigned char sha1val[EVP_MAX_MD_SIZE];
  unsigned int i, sha1len;
  char buf[2]="80";
  int numIn;
  EVP_DigestInit(&sha1ctx, EVP_sha1());
    numIn=2;
    EVP_DigestUpdate(&sha1ctx, buf, numIn);
  EVP_DigestFinal(&sha1ctx, sha1val, &sha1len);

  printf("SHA1: ");
  for(i=0; i<sha1len; i++)
    printf("%02x", sha1val[i]);
  printf("\n");
  EVP_MD_CTX_cleanup(&sha1ctx);

return 0;
}

A: The library C:\OpenSSL-Win32\lib\libeay32.lib is probably for the wrong architecture.  You are cross-compiling for an embedded system target (at91sam7), use the library for that target.


text:
Q: What's the best way to write a wrapper for a C++ library, when rust-bindgen doesn't work on the original headers? I'm trying to port a C++ library to Rust. One dependency isn't open-source, and I only have access to the header files. rust-bindgen doesn't generate valid bindings from these header files, and after searching online for a while, I came to the conclusion that I needed to write a wrapper for the aforementioned library. (This header files for this library are from https://github.com/wpilibsuite/ni-libraries, if it matters).
Because of these issues, I can't include the original header files in the wrapper's header files, but I can include the original headers in the actual cpp files.
To use classes, I've just forward-declared them, but some of these headers use typedefs and other fields inside the class as return types. There doesn't seem to be a (good) way to forward-declare or otherwise use these.
I'd like to know if my approach is correct, or if there's a better way to do this and I'm going the wrong way about this (it could be either in C++ or with rust-bindgen itself).
An example of my current setup:
closed-source.h
class Foo {
    Foo* create();
    int getBar();
}

wrapper.hpp
class Foo;
Foo* foo_create();
int foo_getBar();

wrapper.cpp
#include "closed-source.h"
#include "wrapper.hpp"

Foo* foo_create() {
    return Foo::create();
}
int foo_getBar(Foo* self) {
    return self->getBar();
}


text:
Q: How can I distinguish the different Textarea fields in apex? In Salesforce there are 3 different Text Area fields:
Text Area, Text Area (Long), and Text Area (Rich).
I'm doing some processing in a custom class and I need to distinguish between the 3 different kinds.  My first thought was using Describe but the Schema.DisplayType enum value for all three is simply TextArea.

A: This seems to work for short vs long:
http://www.fishofprey.com/2011/03/find-length-of-salesforce-field-in-apex.html
When I test the following in my org:
System.debug(
    Schema.SObjectType.Contact.fields.Description.getLength()
);

I get 32000 back. When I try custom text areas, rich or not, I get the appropriate values back too. Doesn't indicate richness though. For that you can use .Description.isHtmlFormatted() which seems to return TRUE for rich and FALSE for plaintext.


text:
Q: How to check if string is a valid Figma link? I'm building an app on NodeJS that uses Figma API, and I need to check if the string passed by a user is a valid Figma link. I'm currently using this simple regex expression to check the string:
/^https\:\/\/www.figma.com\/.*/i

However, it matches all links from figma.com, even the home page, not only links to the files and prototypes. Here is an example Figma link that should match:
https://www.figma.com/file/OoYmkiTlusAzIjYwAgSbv8wy/Test-File?node-id=0%3A1

Also the match should be positive if this is a prototype link, with proto instead of file in the path.
Moreover, since I'm using the Figma API, it would be useful to extract necessary parts of the URL such as the file ID and node ID at the same time.

A: TL;DR
✅ Use this expression to capture four most important groups (type, file id, file name and URL properties) and work from there.
/^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/?([^\?]+)?(.*))?$/

From the docs
This is the regex expression code provided by Figma on their developer documentation page about embeds:
/https://([w.-]+.)?figma.com/(file|proto)/([0-9a-zA-Z]{22,128})(?:/.*)?$/

 However, it doesn't work in JS as the documentation is currently wrong and this expression has multiple issues:

*

*Slashes and a dots are not escaped with backslashes.

*It doesn't match from the start of the string. I added the start of string anchor ^ after VLAZ pointed it out in the comments. This way we will avoid matching strings that don't start with https, for example malicious.site/?link=https://figma.com/...

*It will match not only www. subdomain but any other amount of W which is not great (e.g. wwwww.) — it can be fixed by replacing letter match with a simpler expression. Also this is a useless capturing group, I'll make it non-capturing.

*It would be nice if the link matched even if it doesn't begin with https:// as some engines (e.g. Twitter) strip this part for brevity and if person is copying a link from there, it should still be valid.
After applying all the improvements, we are left with the following expression:
/^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?$/

There is also a dedicated NPM package that simply checks the URL against the similar pattern. However, it contains some of the flaws listed above so I don't advice using it, especially for just one line of code.

Extracting parts of the URL
This expression is extremely useful to use with Figma API as it even extracts necessary parts from the URL such as type of link (proto/file) and the file key. You can access them by indexes.
You can also add a piece of regex to match specific keys in the query such as node-id:
/^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?node-id=([^&]*)$/

Now you can use it in code and get all the parts of the URL separately:

var pattern = /^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?node-id=([^&]*)$/

var matched = 'https://www.figma.com/file/OoYmkiTlusAzIjYwAgSbv8wy/Test-File?node-id=0%3A1'.match(pattern)

console.log('url:', matched[0]) // whole matched string
console.log('type:', matched[1]) // group 1
console.log('file key:', matched[2]) // group 2
console.log('node id:', matched[3]) // group 3

Digging deeper
I spent some time recreating this expression almost from scratch so it would match as many possible Figma file/prototype URLs without breaking things. Here are three similar versions of it that would work for different cases.
✅ This version captures the URL parameters and the name of the file separately for easier processing. You can check it here. I added it in the beginning of the answer, because I think it's the cleanest and most useful solution.
/^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/?([^\?]+)?(.*))?$/

The groups in it are as following:

*

*Group 1: file/proto

*Group 2: file key/id

*Group 3: file name (optional)

*Group 4: url parameters (optional)

✅ Next up, I wanted to do the same but separating the /duplicate part that can be added in the end of any Figma URL to create a duplicate of the file upon opening.
/^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/?([^\?]+)?([^\/]*)(\/duplicate)?)?$/

✅ And back to the node-id parameter. The following regex expression finds and captures multiple URLs inside a multiline string successfully. The only downside that I found in the end is that it (as well as all the previous ones) doesn't check if this URL contains unencoded special characters meaning that it can potentially break things, but it can be avoided by manually encoding all parameters using encodeURI() function.
/^(?:https:\/\/)?(?:www\.)?figma\.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/([^\?\n\r\/]+)?((?:\?[^\/]*?node-id=([^&\n\r\/]+))?[^\/]*?)(\/duplicate)?)?$/gm

There are six groups that can be captured by this expression:

*

*Group 1: file/proto

*Group 2: file key/id

*Group 3: file name (optional)

*Group 4: url parameters (optional)

*

*Group 5: node-id (optional; only present when group 4 is present)

*Group 6: /duplicate

And, finally, here is the example of a match and its groups (or try it yourself):


text:
Q: Opening URL inside iframe tag targeting parent Problem: how to open URL from within iframe tag.
I have an asp.net web application, which includes a shopping cart located in a subfolder, although for test purposes another URL entirely.
I include a portion of the shopping cart on the main site using an iframe tag.
<iframe name="iCartInfo" id="Iframe1" runat="server" src="https://www.mysite.domain/shop/cart/MyShoppingCartLine.aspx" scrolling="no" seamless="seamless" style="float: right; border: none; overflow-y: hidden;" width="380" height="40"></iframe>

If I include the
<base target="_parent" />

in the destination, then the request does not work. If I do not include the request, the URL opens in the iframe.
I traced the code that opens the URL to a button's code behind.
Response.Redirect("~/whatever.aspx");

I changed that to an absolute URL from a relative URL to see if that resolves the issue, when including the base tag in the head of the iframe page, but nope, nothing happens when I click. The nearest that I can see is that other pages or code gets affected by some means.
Is there any other way without upsetting the code inside the iframe to have the request open in the parent's browser window and not inside the iframe?


text:
Q: Gradle/Groovy syntax confusion Can anyone explain/comment on this fraction of Groovy code?
task copyImageFolders(type: Copy) {
    from('images') {
        include '*.jpg'
        into 'jpeg'
    }

    from('images') {
        include '*.gif'
        into 'gif'
    }

    into 'build'
}

More specifically about the from method.
Is this the
from(sourcePaths)

or the
from(sourcePath, configureAction)

If its the one with the 2 arguments, why it's written this way and not something like:
 from('images', {
     include '*.jpg'
     into 'jpeg'
 })

A: The short answer is it's calling from(sourcePath, configureAction).
Groovy has optional brackets in a number of cases and accepts the last parameter (if it's a closure) outside of brackets and in this case that's the closure that you're passing to from().
This is a good blog post explaining the different ways a closure can be passed to a method in Groovy if you want more examples and this offers more examples of optional brackets in general.

A: It's Syntactic Sugar, to make things easier to read (very useful for Gradle configuration)
In this case it's all about parentheses.

When a closure is the last parameter of a method call, like when using
  Groovy's each{} iteration mechanism, you can put the closure outside
  the closing parentheses, and even omit the parentheses:

list.each( { println it } )
list.each(){ println it }
list.each  { println it }

In your case, everything below is working fine :
from('images', {
    include '*.jpg'
    into 'jpeg'
})

from('images') {
    include '*.gif'
    into 'gif'
}

from 'images', {
    include '*.gif'
    into 'gif'
}


text:
Q: Using GLKTextureLoader to load a texture atlas I seem to be a little restricted by openGLs GLKTextureLoader. I'm trying to get sprite animation working so I'm trying to load a texture atlas. The texture loader doesn't seem to allow me to break the image into pieces.
This is the relevant code
    NSDictionary * options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
                              GLKTextureLoaderOriginBottomLeft, nil];

    NSError * error;
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:nil];

    self.textureInfo = [GLKTextureLoader textureWithContentsOfFile:path options:options error:&error];

any thoughts?

A: Why would you need to break the image into pieces? The whole point of a texture atlas is that you can use bits of it just by choosing appropriate texture coordinates to only show part of it.


text:
Q: image not changing on click - javascript I apologise if it sounds similar to a previous question, but I've gone over those similar questions and I still can't figure out what the problem is with my code. it's petty simple yet it doesn't work.
I have an image. I want it to change to a second image when I click on it, and to a third image when I click on the second image. and then, I want it to change back to the first image when the third image is clicked.
html:
           <img id="narrow" class="item" src="images/joe2.jpg" style="cursor:pointer" onclick="changeImage(this);">

javascipt:
  function changeImage(imgl) {
       if(imgl.src=="images/joe2.jpg") {
            imgl.src="images/stray_cat.jpg";
       }
       else if (imgl.src=="images/stray_cat.jpg") {
            imgl.src="images/mathewgarber.jpg";
       }
       else // (imgl.src=="images/mathewgarber.jpg") {
            imgl.src="images/joe2.jpg";
       }
  }

what happens is that nothing happens when I click on the first image. thanks for your help.

A: Try something like this:
var images = [
    'http://lorempixel.com/100/100/nature/1',
    'http://lorempixel.com/100/100/nature/2',
    'http://lorempixel.com/100/100/nature/3'
],
i = 0;

function changeImage(img) {
    img.src = images[++i % images.length];
}

Comparing image src with a string is not very reliable because it can contain full domain and protocol. Instead you can store images in array and use % operator which is very useful for such kind of cycling.
Demo: http://jsfiddle.net/phJA4/

A: First of all you have the last { commented out by your imgl.src=="images/mathewgarber.jpg").
Secondly, the img1.src gives you a different string, take a look at this Demo
You should check for the src like this:
if(imgl.src.indexOf("images/joe2.jpg") > -1)

A: As dsfq above said, the image src url will be relative, including the site host.
function changeImage(imgl) {
        if (imgl.src.indexOf('images/joe2.jpg') > -1) {
            imgl.src = "images/stray_cat.jpg";
        } else if (imgl.src.indexOf("images/stray_cat.jpg") > -1) {
            imgl.src = "images/mathewgarber.jpg";
        } else // (imgl.src=="images/mathewgarber.jpg")
        {
            imgl.src = "images/joe2.jpg";
        }
    }

If you have your heart set on your method, you can use a indexOf check to determine if the image name is part of the full src url.


text:
Q: Conversion of a timedelta to int very slow in python I have a dataframe with two columns, each one formed by a set of dates.
I want to compute the difference between dates and return the the number of days. However, the process (described above) is very slow. Does anyone knows how to accelerate the process? This code is being used in a big file and speed is important.
dfx = pd.DataFrame([[datetime(2014,1,1), datetime(2014,1,10)],[datetime(2014,1,1), datetime(2015,1,10)],[datetime(2013,1,1),  datetime(2014,1,12)]], columns = ['x', 'y'])

dfx['diffx'] = dfx['y']-dfx['x']
dfx['diff'] = dfx['diffx'].apply(lambda x: x.days)
dfx

Final goal:

A: You may find a marginal massive speed-up dropping down to NumPy, bypassing the overhead associated with pd.Series objects.
See also pd.Timestamp versus np.datetime64: are they interchangeable for selected uses?.
# Python 3.6.0, Pandas 0.19.2, NumPy 1.11.3

def days_lambda(dfx):
    return (dfx['y']-dfx['x']).apply(lambda x: x.days)

def days_pd(dfx):
    return (dfx['y']-dfx['x']).dt.days

def days_np(dfx):
    return (dfx['y'].values-dfx['x'].values) / np.timedelta64(1, 'D')

# check results are identical
assert (days_lambda(dfx).values == days_pd(dfx).values).all()
assert (days_lambda(dfx).values == days_np(dfx)).all()

dfx = pd.concat([dfx]*100000)

%timeit days_lambda(dfx)  # 5.02 s per loop
%timeit days_pd(dfx)      # 5.6 s per loop
%timeit days_np(dfx)      # 4.72 ms per loop


text:
Q: Pick some properties from generated Instance of type is not working, why? Trying to generate an new type with only some properties, but I'm getting nothing..
const User = types.model({
    id: types.identifier,
    username: types.maybe(types.string),
    email: types.maybe(types.string),
});
type TUser = Instance<typeof User>;
type TDatabaseUser = Pick<TUser, 'id' | 'email'>

TDatabaseUser has no properties.. and should have id and email

What I'm doing wrong ?

A: Your code seems to be working as intended.
import { Instance, types } from "mobx-state-tree";

const User = types.model({
  id: types.identifier,
  username: types.maybe(types.string),
  email: types.maybe(types.string)
});
type TUser = Instance<typeof User>;
type TDatabaseUser = Pick<TUser, "id" | "email">;

const dbUser: TDatabaseUser = {
  id: "1",
  email: "test@test.com",
  // id and email works, but username gives rise to an error.
  username: "does not work"
};


text:
Q: How to update the jquery FullCalendar appointment after i have created the event what is the event or method name that i have to call or handle to update an existing event in the calendar(the event i click on). full calendar can be found here http://arshaw.com/fullcalendar/

A: When you initialize the FullCalendar instance, bind the eventClick handler:
var calendar = $('#calendar');
var curr_event = null;
calendar.fullCalendar({
    ...

    events: [],
    eventClick: function(event, jsEvent, view) {
        curr_event = event;
        show_form_or_something();
    },

    ...
});

You might want to show a form or something in order to allow the user to modify the event properties (title, start etc). Then to update the event back in the FullCalendar instance:
$.extend(curr_event, {
    title: 'New Event Title',
    start: new Date()
});
calendar.fullCalendar('updateEvent', curr_event);

And to address jmeho question:
When you add the event to FullCalendar either through renderEvent() or event source, you can specify id for each event. After you added the event, you can retrieve the event hash/object by using:
var event_obj = calendar.fullCalendar('clientEvents', 'specific event id');

Then you can modify the has/object and use the updateEvent() method to update the FullCalendar display.

A: This code is perfect for update the calendar after update the event.
First remove date event, then render it again.
function updateCalenderUP(id, title, Sessiontitle, SessionStart, Sessionend, color) {
    title = title;
    var id1 = id;

    $('#calendar').fullCalendar( 'removeEvents', id1);
    $('#calendar').fullCalendar('refresh');
    title = title;

    if (title) {
        calendar.fullCalendar('renderEvent', {
                id: Eventid,
                title: title,
                start:startDate,
                end: EndDate,
                allDay: false,
                backgroundColor:color
            }, true // make the event "stick"
        );
    }
    calendar.fullCalendar('unselect');
}


text:
Q: jQuery doesn't addClass to HTML element When try to addClass('hidden') to $(this) it seems to add it to jQuery object [textarea.form-control.hidden, prevObject: n.fn.init[1], context: button.btn.btn-info.btn-flat.hidden, selector: "textarea"], but not to actual HTML element. What am I missing?
jsfiddle

A: This is because you have already function called on main div '.item' so when you click on button the above function on '.item' calls again as button is child of .item.
Use e.stopPropagation(); to stop calling function from parent div.
$('.item button').click(function(e) {
    e.stopPropagation();
    $parent = $(this).parent().parent();
    $parent.find('span').removeClass('hidden');
    $parent.find('textarea').addClass('hidden');
    $parent.find('button').addClass('hidden');

    console.log($parent.find('textarea'));
  })

fiddle : https://jsfiddle.net/34sdrrnf/1/


text:
Q: Can we have ng-change globally in anjularjs There are 5 text boxes in my form and i want to trigger the ng-change when the contents of any text boxes is changed.Now my question is "instead of writing the ng-change 5 times for 5 text boxes, Is there any way to write the ng-change globally i.e in the form tag so that if any text box contents with in the form the corresponding function of ng-change should be triggered
can any one help me please.....

A: I would make a $watch expression on that part of the model. See the documentation for $watch.

A: I agree with marko that the easiest way is with $watch.
$scope.$watch('area1 + area2 + area3 + area4 + area5', function (newVal, oldVal) {
  if(oldVal && newVal !== oldVal) {
    console.log('Changed')
  }
});

Here is a Plunker

A: I have a similar case when I have a grid with hundreds of inputs, where the inputs are dynamic, and I need to autosave the data after the input has changed
I used the vanilla onChange on the wrapper body then checking the target value.
<div class="wrapper" onchange="onChangeHanler(event)">
   <input ng-repeat="item in items" ng-model="item.value">
</div>

In my controller:
angular.controller('gridController', function($scope) {

   // this method belongs to window and not the current $scope, remember we are breaking ng rules here :(
   window.onChangeHandler = function(ev) {
      console.log(ev.target.value) // print out the value changed
      queueForAutoSave($scope.items);
   }
})

PS.
Downvoters I know that this is not the best way to implement this since its againts angular norms, and cause problems to unit tests, etc ...,
but for now in case of performance it's 100x better than binding the ng-change for hundreds of inputs


text:
Q: HTML file not sending to HP ePrint App for Print from Android App I tried for text(*.txt) file print its working good but when I try for HWML file its not working.  Here is my code.
Home.java
public class Home extends Activity{

    private static final String FileName = "file.html";

    Button button1;

    final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), FileName);

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Uri uri = Uri.fromFile( file );
                Intent intent = new Intent ("org.androidprinting.intent.action.PRINT");
                intent.setDataAndType( uri, "text/html" );
                startActivity(intent);
                //startActivityForResult(intent, 0);

            }
        });

    }
}

A: you directly pass image don't need to html text. try below code:
Intent intent = new Intent ("org.androidprinting.intent.action.PRINT");
intent.setDataAndType( Uri.fromFile(new File("assets/subba.jpg"), "image/jpeg" );
startActivity(intent);


text:
Q: Can I use Nuxt Apollo local state to replace Vuex entirely? I am building a Nuxt app with a GraphQL API, connected via the nuxt module of Vue Apollo.
I'm currently using Vuex to store app-wide things, and in this one specific case a property called alert. The alert object stored in Vuex tells me what type of alert it is, what its message is, and whether it's active or not.
Since introducing GraphQL to my app though, I was wondering if it's possible to store that type of state data through Vue Apollo instead of Vuex? I read this in the documentation... would this be a better solution than mixing Vuex with Apollo, or is it better to separate state so that app-wide state is handled with Vuex, and API state is handled with Apollo?

A: No. Vuex combined with apollo creates two different truths aka. duplicate information. As documentation suggest apollo is able to handle local states the same way as vuex, but using the graphql way.
Take a look at: Apollo local state and Nuxt local state example

A: Yes, it is better to separate the state so that the app-wide state is handled with Vuex, and the API state is handled with Apollo?
This will EXTRACT DATA LAYER which will be S.O.L.I.D compatible.


text:
Q: Баг работы кастомного select Есть кастомный select с функцией сортировки элементов списка, всё бы хорошо но после первого выбора элемента списка select перестаёт работать вовсе
https://codepen.io/fN9ne/pen/PompmLW

12 июля

13 июля

14 июля

15 июля

.wrapper {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #131620;
}
.select {
    position: relative;
}
.select._active .select__current {
    border-radius: 23px 23px 0 0;
    border-bottom: 1px solid #919191;
    transition: .5s;
}
.select._active .select__list {
    opacity: 1;
    visibility: visible;
    transition: .5s .4s;
}
.select__current {
    background: #f1f1f1;
    color: #222;
    padding: 10px 30px;
    font-size: 24px;
    border-radius: 23px 23px 23px 23px;
    cursor: pointer;
    transition: .5s .4s;
}
.select__current:hover {
    background: #c4c4c4;
}
.select__current li {
    list-style: none;
}
.select__list {
    position: absolute;
    top: 100%;
    opacity: 0;
    visibility: hidden;
    transition: .5s;
    background: #f1f1f1;
    width: 100%;
    border-radius: 0 0 23px 23px;
    padding: 0 0 12px 0;
    overflow: hidden;
}
.select__list li {
    padding: 7px 30px;
    width: 100%;
    text-align: center;
    font-size: 18px;
    color: #222;
    cursor: pointer;
    border-bottom: 1px solid #919191;
    transition: 0.5s;
}
.select__list li:hover {
    background: #d9d9d9;
}

$(document).ready(function() {
    $(document).on('click', function(e) {
        if (!e.target.closest('.select__current, .select__list')) $('.select').removeClass('_active');
    });

    $('.select__current').on('click', function() {
        $(this).closest('.select').toggleClass('_active');
    });

    $('.select__list li').on('click', function() {
        let list = $(this).closest('.select__list');
        let current = $(this).closest('.select').find('.select__current');
        list.append(current.find('li'));
        current.append($(this));
        ordering(list);
        $(this).closest('.select').removeClass('_active');
    });

    function ordering(list) {
        let listItems = list;
        let item;
        let itemNum;
        let arr = [];
        for (let i = 0; i < listItems.find('li').length; i++) {
            item = listItems.find('li').eq(i);
            arr.push(item);
        }
        let sorted = [...arr].sort(function(a, b) {
            return a.attr('data-order') - b.attr('data-order');
        });

        listItems.html('');

        for (let li of sorted) {
            listItems.append(li);
        }
    }
});

A: Проблема заключается в данном коде $('.select__current').on('click', он вешает обработчик события на все li которые ему известны. Но вы потом добавляете новые li и о них уже не известно. Когда вы делаете $('.select').on('click', '.select__list li', срабатывает делегирование, то есть событие срабатывает на всей области .select и проверяет, что клик был именно по нужному нам элементу.

$(document).ready(function() {
    $(document).on('click', function(e) {
        if (!e.target.closest('.select__current, .select__list')) $('.select').removeClass('_active');
    });

    $('.select').on('click', '.select__current', function() {
        $(this).closest('.select').toggleClass('_active');
    });

    $('.select').on('click', '.select__list li', function() {
        let list = $(this).closest('.select__list');
        let current = $(this).closest('.select').find('.select__current');
        list.append(current.find('li'));
        current.append($(this));
        ordering(list);
        $(this).closest('.select').removeClass('_active');
    });

    function ordering(list) {
        let listItems = list;
        let item;
        let itemNum;
        let arr = [];
        for (let i = 0; i < listItems.find('li').length; i++) {
            item = listItems.find('li').eq(i);
            arr.push(item);
        }
        let sorted = [...arr].sort(function(a, b) {
            return a.attr('data-order') - b.attr('data-order');
        });

        listItems.html('');

        for (let li of sorted) {
            listItems.append(li);
        }
    }
});
.wrapper {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #131620;
}
.select {
    position: relative;
}
.select._active .select__current {
    border-radius: 23px 23px 0 0;
    border-bottom: 1px solid #919191;
    transition: .5s;
}
.select._active .select__list {
    opacity: 1;
    visibility: visible;
    transition: .5s .4s;
}
.select__current {
    background: #f1f1f1;
    color: #222;
    padding: 10px 30px;
    font-size: 24px;
    border-radius: 23px 23px 23px 23px;
    cursor: pointer;
    transition: .5s .4s;
}
.select__current:hover {
    background: #c4c4c4;
}
.select__current li {
    list-style: none;
}
.select__list {
    position: absolute;
    top: 100%;
    opacity: 0;
    visibility: hidden;
    transition: .5s;
    background: #f1f1f1;
    width: 100%;
    border-radius: 0 0 23px 23px;
    padding: 0 0 12px 0;
    overflow: hidden;
}
.select__list li {
    padding: 7px 30px;
    width: 100%;
    text-align: center;
    font-size: 18px;
    color: #222;
    cursor: pointer;
    border-bottom: 1px solid #919191;
    transition: 0.5s;
}
.select__list li:hover {
    background: #d9d9d9;
}

12 июля

13 июля

14 июля

15 июля


text:
Q: Returning a function from inside another function in Java Since we can adopt some functional programming concept in Java programming language is it also possible to write a function which returns an other function? Since Higher order functions do that. Just like JavaScript ?
Here is a JavaScript code that returns a function.
function magic() {
  return function calc(x) { return x * 42; };
}

var answer = magic();
answer(1337); // 56154

A: The closest Java equivalent is this:
public static void main(String[] args) {
    UnaryOperator<Integer> answer = magic();
    System.out.println(magic().apply(1337));  // 56154
    System.out.println(answer.apply(1337));   // 56154
}

static UnaryOperator<Integer> magic() {
    return x -> x * 42;
}

A: Yes you can
Function<String, Integer> getLengthFunction() {
    return String::length;
}

And you can take this further. E.g. implement currying:
static <T, U, R> Function<T, Function<U, R>> curry(BiFunction<T, U, R> f) {
    return t -> u -> f.apply(t, u);
}

A: Here's another example I wrote a while back.  It returns a conversion function base on supplied arguments.
// generate a Celsius to Fahrenheit Converter.
DoubleUnaryOperator cToF = conversionGen(9 / 5., 32);

// Fahrenheit to Celsius
DoubleUnaryOperator fToC =
        conversionGen(5 / 9., (-32 * 5 / 9.));

// kilometers to miles
DoubleUnaryOperator kiloToMiles = conversionGen(.6, 0);

// and pounds to Kilograms.
DoubleUnaryOperator lbsToKgms = conversionGen(1 / 2.2, 0);

Now all you have to do is call them with the single argument.
double farTemp = cToF.applyAsDouble(100);
double celTemp = fToC.applyAsDouble(212);
System.out.println(farTemp);
System.out.println(celTemp);
System.out.println(kiloToMiles.applyAsDouble(1500));
System.out.println(lbsToKgms.applyAsDouble(4.4));

Prints
212.0
100.0
900.0
2.0

The generator.
public static DoubleUnaryOperator conversionGen(double factor,
            double base) {
        return unit -> unit * factor + base;
}


text:
Q: C++ Linked List isEmpty Function I want to check, whether a linked list in C++ is empty or not. I have following class:
class IntLinkedList
{
    private:
        struct LinkedListNode        // Structure for linked list
        {
            int value;
            struct LinkedListNode *next;
        };
        LinkedListNode *head;       // List head pointer

    public:
        IntLinkedList(void)         // Constructor
        { head = NULL; }

        ~IntLinkedList(void);       // Destructor
        void AppendNode(int);
        void InsertNode(int);
        void DeleteNode(int);
        void DisplayList(void);
        bool isEmpty(LinkedListNode*);
};

// isEmpty function
bool IntLinkedList::isEmpty(LinkedListNode *node)
{
    bool status;
    node = head;
    if ( node->next == NULL )
        status = true;
    else
        status = false;
    return status;
}

But I can't use this function in other class via an object of the same class.
How can I check the empty list using a function that would be accessible in another class through the object of the same class?

A: The error you are getting is caused by the fact that you declared your function as bool isEmpty(LinkedListNode) but you are trying to define it as bool isEmpty(LinkedListNode*). The difference is that in the definition you have a pointer, while in the declaration there is just an object. You have to pick one, as these are completely different things.
That said, I don't see why you need the argument at all to check whether your list is empty. Just drop the argument altogether and use if ( head->next == NULL ) - non-static member functions are always called through an instance of the class.
Just for completeness, first item in your list is pointed to by head, so in order to check if there is anything in the list, you should check if it is a null pointer:
bool IntLinkedList::isEmpty() const
{   //added const for const-correctness, should be added to declaration as well
    return head == nullptr;
}

A: Following list.empty(),

Returns whether the list container is empty (i.e. whether its size is
  0).

Two suggestions:
Have a size variable that checks for the number of nodes in your list, this way your isEmpty() is just return size == 0;
Or in your current implementation, just modify to:
bool isEmpty() {
   return head == null; // if head is null, there's no node in list
}


text:
Q: How to open a URL and estimate the word count using JavaScript?

The code above did not work, how to access DOM for a different URL?
I'd like to open an URL and show the word count of that URL.

A: You can't simply open another window and page and expect to have access to it. The web follows many security policies to prevent operations like this, such as the Same-Origin policy. Long-story short, you can't access URLs that don't fall under the same-origin as the page you're calling from. You couldn't therefore access Yahoo finance in your example (most likely).
If you were calling from the same origin, you could use an API like fetch to get just the text and do a word count there, or you could even load an iframe and query that: myIframe.contentWindow.document.body.innerHTML.
So knowing that you cannot do this from the browser, you could do it from a NodeJS application (perhaps also using fetch):
var fetch = require('node-fetch');

fetch('https://finance.yahoo.com/')
    .then(function(res) {
        return res.text();
    }).then(function(body) {
        console.log(body);
        // perform word-count here
    });

I understand that you were hoping to do this from the browser, but unfortunately you will not be able to do so for origins that you do not control.

A: You can try this out.
In you index.html (suppose) write this:

   <title>Index Page</title>

Hello this can Work

And suppose your new_window.html is like this:

This is the new window


text:
Q: Bootstrap: Popover dismiss not working in iOS browser I have used Bootstrap Popover and added JS code for popover dismiss on tap in the body. It works on Android but not iOS.

$(document).ready(function () {
  $("body").tooltip({
    selector: "[data-toggle='tooltip']",
    container: "body"
  })
  .popover({
    selector: "[data-toggle='popover']",
    container: "body",
    html: true
  });
});

$('body').on('click', function (e) {
  $('[data-toggle="popover"]').each(function () {
    if(!$(this).is(e.target) &&
       $(this).has(e.target).length === 0 &&
       $('.popover').has(e.target).length === 0) {
      $(this).popover('hide');
    }
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Click here

A: Got the answer:


text:
Q: Computing sum of elements in array I have a class Mold with the following constructor
public Mold(int[][] mold){
    this.mold = mold;
  }

I also have a method sum() which looks like this:
public int sum(){
    int sum = 0;
    for( int i = 0; i <matrix.length; i++) {
      sum += matrix[i][i];
    }
    return sum;
  }

What I am trying to do is compute the sum of all the elements in Mold but I am unsure as to what to put in the sum += matrix[i][i]; part in place of 'i'. I might even be doing it the complete wrong way. I have been stuck on this for a while and I cannot seem to figure it out.
An example of the output I would like to get is: int[][] test1 = { { 10, 5 }, { 2, 8 } }; should give 25 one the sum method has been applied.
If someone could push me in the right direction that would be great!
Many thanks,

A: You are doing this:
Supposing a bi-dimensional array of 3x3 elements these are their coordinates (row, column):
[0,0][0,1][0,2]
[1,0][1,1][1,2]
[2,0][2,1][2,2]

The way you are counting using only one loop and only one variable in the loop is doing this:
i = 0 (counting the elemen 0,0)
[*][ ][ ]
[ ][ ][ ]
[ ][ ][ ]

i = 1 (counting the elemen 1, 1)
[ ][ ][ ]
[ ][*][ ]
[ ][ ][ ]

i = 2 (counting the elemen 2,2)
[ ][ ][ ]
[ ][ ][ ]
[ ][ ][*]

You need to use a double loop to do the sum. Loop every row and for every row looped you have to loop for each column of that row.
Something like this:
for (i = 0; i < maxRows; i++){
 for (j = 0; j < maxCols; j++{
  //
 }
}

A: The way you have it, you will only sum up positions [0][0], [1][1], [2][2], ..., [i][i] and you will miss most of the elements.
You have 2 dimensions in your array, so you need 2 loops.
Create another for loop inside your existing for loop, with a different looping variable, j.  It will stop when it reaches the end of the current row's length: matrix[i].length.  When adding to sum, use both looping variables: matrix[i][j].

A: In your current approach, you're just adding the elements in the diagonal (0,0), (1,1), (2,2). If handling an array of array, you can use the enhanced for loop twice: one to loop over the elements in the array and another to loop over the elements in the array of the array:
int sum = 0;
for(int[] moldElement : mold) {
    for(int element : moldElement) {
        sum += element;
    }
}
return sum;

A: Think about what you are doing exactly and how to accomplish it.
Remember a 2d array is an array of arrays.
for( int i = 0; i <matrix.length; i++) {
      sum += matrix[i][i];
}

`sum[i][i]` in this code is essentially doing this.
     0  0
     1  1
     2  2
     3  3
     4  4
     ...

What you need it to be doing is
     0   0
     0   1
     0   2
     ...
     1   0
     1   1
     1   2
     ...

Think of it like coordinates X and Y!
this would be your answer.
for(int i = 0; i < matrix.length; i++){
    for(int j = 0; z < matrix[j].length; j++{
        sum += matrix[i][j];
    }
}

Notice this line in particular. matrix[i].length What if the array wasn't completely uniform??
for instance.
  i
j[0][][][][][]
 [1][]
 [2][][][]
 [3][][][][][][]

this still would able to iterate through.

A: do double for loops.
int sum = 0;
for(int i = 0; i < matrix.length; i++)
{
    for(int j = 0; j < matrix[0].length; j++)
    {
        sum += matrix[i][j];
    }
}
return sum;

A: Nest the for loop
 public int sum(){
    int sum = 0;
    for( int i = 0; i <matrix.length; i++) {
        for (int j = 0; k < matrix[i].length; j++){
            sum += matrix[i][j];
        }
    }
    return sum;
  }

As someone said, you're only iterating over one dimension of the array.  When you have n dimensions of an array, you need n loops.


text:
Q: How can I process listbox items and save them in a SQL database? I am using a multi-select listbox to show a date. I want to process all selected values and store them in my database.
How do I process all the selected dates and save them in a database?
Is it possible to store all the selected dates in a single row?
Is there an alternative for storing the value?

A: This is too broard of a question to answer.
In regards to processing the selected values you can do something like this
foreach (ListItem listitem in ListBox1.Items)
{
    if (listitem.Selected)
        Save(listitem);
}

In regards to database you can both save in one row and multible rows. It depends on what you want to do


text:
Q: Laurent Series at Infinity I thought that finding the Laurent series was something that was straightforward, however, I am having some difficulty of finding the Laurent series of
$$f(z) = \frac{1}{z(1-z)}$$
for $z= \infty$.  Any suggestions?

A: Make the change of variable $w= 1/z$ and then find the Laurent series around $w=0$

A: We can write for $|z|>1$,
$$\frac{1}{z(1-z)}=-\frac1{z^2}\frac{1}{1-z^{-1}}=-\sum_{n=0}^{\infty}z^{-n-2}$$

A: Using generalized Laurentseries with two poles
$$\sum _{k=0}^{n-1} x^k-\frac{x^n}{x-1}+\frac{1}{x}$$


text:
Q: Cannot click on SWF when small size in Mac OSX I have this website here http://www.innovie.com/morgan
If I use PC, I can drag and change volume on top left just fine. But if I use Mac OSX, either Safari or Firefox, I cannot drag the volume in the Flash, although I can see the mouse turn into pointer. Can someone help on why?
Where is the SWF: h**p://www.innovie.com/morgan/sound.swf

A: Not sure how to help -- it works for me on Safari 4, Flash version 10,0,22,87.
What happens when you try to drag? Just no effect? What browser and flash version?


text:
Q: ConnectWise SDK, bad request when creating products I am trying to work with the ConnectWise SDK to create tickets and products in ConnectWise Manage.
I have managed to get the connection to work and I can create tickets without a problem, but I keep getting a "400 - Bad Request" when I try to create a product.
I am using C# in Visual Studio.
Can anyone tell me what I am doing wrong?
private static async Task TestPost()
{
    //Create the client
    var client = getApiClient();

    //Get a ticket to duplicate
    var ticketsApi = new TicketsApi(client);
    var getResponse = await ticketsApi.GetTicketByIdAsync(55482);
    var ticket = await getResponse.GetResultAsync<Ticket>();                //I get the correct ticket here

    //Create the duplicate ticket
    var createResponseTicket = await ticketsApi.CreateTicketAsync(ticket);  //This works without error
    var newTicket = await createResponseTicket.GetResultAsync<Ticket>();
    Console.WriteLine("Ticket ID: " + newTicket.Id);

    //Get a product to duplicate
    var productsApi = new ProductsItemApi(client);
    var response = await productsApi.GetProductByIdAsync(1);
    var product = await response.GetResultAsync<ProductItem>();             //I get the correct product here

    //Create the duplicate product
    var createResponseProduct = await productsApi.CreateProductAsync(product);  //Here I get a "400 - Bad Request" error
    var newProduct = await createResponseProduct.GetResultAsync<ProductItem>();
    Console.WriteLine("Product ID: " + newProduct.Id);
}


text:
Q: Change to date format I have some data with a date column:

The format here is month-year. However this column is in a factor format and I need it as a date.
> str(data$date)
 Factor w/ 211 levels "01-1994","01-1996",..: 88 157 125 137 139 106 11 204 45 173 ...

I tried to change it this way but the outcome was a column of NA's. Where is the error?
data$date <- as.Date(data$date, format = "%m-%Y")

A: You may consider looking into the "zoo" package which has a yearmon format:
## Some sample data
test <- data.frame(date = c("05-2010", "09-2007", "01-2013"))
str(test)
# 'data.frame': 3 obs. of  1 variable:
#  $ date: Factor w/ 3 levels "01-2013","05-2010",..: 2 3 1

Converting to yearmon:
library(zoo)
as.yearmon(test$date, format="%m-%Y")
# [1] "May 2010" "Sep 2007" "Jan 2013"

FYI: It is possible to wrap as.yearmon in as.Date if you need the regular date format.
as.Date(as.yearmon(test$date, format="%m-%Y"))
# [1] "2010-05-01" "2007-09-01" "2013-01-01"

A: You do not have dates.  You have a factor variable as str() tells you.
More generally, looks into stringsAsFactors=FALSE, either as an option to data reading (including from data base) or a global option.
For the issue at hand:  combine
as.Date(paste0(as.character(date$date), "-01"), "%m-%Y-%d")

as you also need a day to create a valid date.


text:
Q: How to access session token with next-auth in order to attach it to a API request header? Hello I'm new to NextJS and React, but my project currently has a 3rd party api that I'm working with that requires a session token input in the header for all requests.
So I picked next-Auth for authentication but I have problem accessing that chunk of raw jwt.

I tried useSession but it only gives me info within JWT (users, expiration, etc). I found a server side function in documentation called getToken() but the sample requires a line like this:

const secret = process.env.SECRET

Does that mean i need the secret key to the jwt signature in order to retrieve the raw jwt?
I can see that session token in my cookie under my localhost file and I tried to use js-cookie to get() that cookie, but I still can't get deeper to get the inner cookies. I wonder how I should approach this problem and what's the proper way to attach session token in API requests for next-auth setup.
Thanks!


text:
Q: ios - make keyboard disappear when UIButton is pressed I am trying to make the keyboard disappear when a UIButton is pressed -
-(IBAction)nextButtonPressed{
    [usernameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
}

I have declared the button as IBOutlet and connected it to the IBAction in the storyboard. But the code however does not work and keyboard remains visible. What am I doing wrong ?

A: First you need to subscribe to the UITextFieldDelegate Protocol in your View/ViewController's header file like this:
@interface YourViewController : UIViewController <UITextFieldDelegate>

Make sure you're setting your view/viewcontroller to be the UITextField's delegate after you init the textfield in the .m:
yourTextField.delegate = self;

And you can do this :
-(IBAction)nextButtonPressed{
    [usernameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];
}

Hope it'll help

A: You forgot this:
usernameTextField.delegate = self;
passwordTextField.delegate = self;


text:
Q: How should I handle heavy audio load with JavaScript/HTML5? I'm building a little sequencer like this one, but want to use HTML/JavaScript exclusively (i.e: no Flash).
As you play around with the applet in the link above, you'll notice the potential for several sounds to play simultaneously and/or in rapid succession. I'm using an array of audio objects simulating different 'slots' or channels to achieve the desired polyphony and, as a concept, this seems to work. I'm not experiencing any clipping or cutouts in my audio.
However, this process becomes prohibitively resource-intensive very quickly, regardless of source filetype/compression. It's not uncommon for the web browser itself to crash as the number of sounds playing increases.
So, I"m wondering: What, if any, is the best way to facilitate a fairly heavy audio load without choking the browser? Or, is trying to make HTML/JS work for this purpose a fool's errand?
Any insight would be much-appreciated. Here is a version without sound.

A: I cant say myself, but here's some examples making use of the new web audio api.
http://chromium.googlecode.com/svn/trunk/samples/audio/index.html
The drum machine is pretty taxing on my system, though. In any case, I figure you'd be interested in the link.


text:
Q: Unable to show user specific link to specific page in django I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in  create/ form.
So my problem is, when I filled out the form and redirect to list/ page, there are no links.
My code:
models.py
from django.db import models
from django.contrib.auth.models import User

class File(models.Model):
    file = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    #Further, they are fileds, which is nececary to create schedule.
    #title = models.CharField('Название Графика', max_length = 50)
    #x_title = models.CharField('Название Оси Х', max_length = 50)
    #y_title = models.CharField('Название Оси Y', max_length = 50)
    #etc...

views.py:
def create(request):

    error = ''
    if request.method == 'POST':
        form = FileForm(request.POST)
        if form.is_valid():
            form.save()

            return redirect('grafic:list')
        else:
            error = 'Форма была неверной('

    form = FileForm()

    data = {
        'form': form,
        'error': error,
    }

     return render(request, 'graf/create.html', data)

def list(request):
    qs = File.objects.filter(file=request.user)

    context = {
        'user': request.user,
        'qs': qs,
    }

    return render(request, 'graf/list.html', context)

list.html
{% extends 'base.html' %}

{% block content %}

{% if user.is_authenticated %}

{% block title %} Profile {% endblock %}

Username: {{ user }}

{% for b in qs %}

Твой график

                            {{b.graf_title}}

{% endfor %}

{% endif %}
{% endblock %}
urls.py
from django.urls import path

from . import views

app_name = 'grafic'
urlpatterns = [
    path('', views.first, name = 'first'),
    path('create/', views.main, name = 'main'),
    path('list/', views.list, name = 'list'),
    path('files/<int:grafics>', views.index, name = 'index'),
    path('login/', views.loginpage, name = 'loginpage'),
    path('register/', views.registerpage, name = 'registerpage'),
]

That's all. Sorry if my code is such inconvenient. Thank you in advance for your cooperation)
enter image description here
That is my problem. In the 'file' field there are no user.


text:
Q: SMTP Outgoing IP ( source ip ) I'm trying to change the outgoing smtp ip address, i succeeded to change ip address using source_address=(host,port)
example :         smtpserver = smtplib.SMTP("smtp.gmail.com", 587,source_address=('185.193.157.60',12323)
But i can't find how to add username and password of the proxy ( if the proxy requires username and password )
I tried : smtpserver = smtplib.SMTP("smtp.gmail.com", 587,source_address=('185.193.157.60',12323, 'username', 'password')
But it didn't work

A: From the docs...
SMTP.login(user, password, *, initial_response_ok=True)


text:
Q: Smarty: extract first word of variable I'm using smarty template engine to implement my templates for a website.
I have to extract the first word of a varible, e.g. the variable "$a" with the content   "hello world foo ..." must be seperated into two variables: "$b" = "hello" and "$c" with the rest  (which can be of different size) of "$a", so "world foo ...".

A: {assign 'tsplit' ' '|explode:'Hello world foo'}
{assign 'a' $tsplit|array_shift}
{assign 'b' $tsplit|array_shift}
{assign 'c' $tsplit|implode:' '}
{$a} - {$b} - {$c}

This could give an unexpected result when you have combined words such as hamster wheel or similar
EDIT
I accidentally misread the question. Here is a decent update
{assign 'a' 'Hello world foo'}
{assign 'tsplit' ' '|explode:$a}
{assign 'b' $tsplit|array_shift}
{assign 'c' $tsplit|implode:' '}
{$a} - {$b} - {$c}


text:
Q: How to run python from different drive using Visual Studio Code My OS is Windows 10.
I have test.py file in E drive.
I installed Python 3.7.2 and Visual Studio Code in C drive.
I set system path for Python 3.7.2 so I could run python on CMD on both of the drives.

I also set python.pythonPath in setting.json file in .vscode under my work folder.
So python.pythonPath is same as the system path.
but I can't run that test.py file on VScode.
It shows python 3.7.2 file's path and says "No such file or directory".
Is there a way to run python file on different drive using VScode?

A: You can use debugging to run specific files in a reusable way.
https://code.visualstudio.com/docs/python/debugging
It will create a launch.json file with contents similar to this. You can add additional
properties. VSCode is good about helping you create and edit the launch.json file.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "RunPython",
            "type": "python",
            "request": "launch",
            // run a file by specifying a full path
            "program": "E:/FullPathTo/FileA.py",
            // OR run the file currently open in VSCode
            // // "program": "${file}",
            // OR run a file relative to the current folder you have open
            // // "program": "${workspaceFolder}/folder/FileB.py"
            "console": "integratedTerminal",
            "args": ['InputArg1','InputArg2']
        }
    ]
}

A: If you've already set Python as an environment variable, you can simply route to the directory where the file is present (in this case E: drive) and run the command:
python test.py

A: I installed Code Runner Extension and it followed my system path of python 3.7.2 automatically.
Now I can simply run my code with this short cut "Crtl+Alt+N" instead of entering "python test.py" every time on the terminal.


text:
Q: How do I modify this page template to show subpage excerpts (not post excerpts)? I have made a page template which shows linked subpages using this bit of code:
<?php
        $mypages = get_pages( array( 'child_of' => $post->ID, 'sort_column' => 'menu_order', 'sort_or

        foreach( $mypages as $page ) {
                $content = $page->post_content;
                if ( ! $content ) // Check for empty page
                        continue;

                $content = apply_filters( 'the_content', $content );
?>

<a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?><

<?php echo $content; ?>

<?php
}
?>

I got the code from here and have changed it to order subpages in the order of their Page Order.
It works, but it displays the full pages' contents.  I only want it to show page excerpts, with the featured image.
(I have enabled page excerpts in the editor by adding add_post_type_support( 'page', 'excerpt' ); to functions.php)
How do I modify this page template to show subpage excerpts?

A: Slightly modify these lines
$content = $page->post_content;
if ( ! $content ) // Check for empty page
    continue;

$content = apply_filters( 'the_content', $content );

to
$content = $page->post_excerpt;
if ( ! $content ) // Check for empty excerpt content & fallback to full content
    $content = $page->post_content;
if ( ! $content ) // Check for empty page
    continue;

$content = apply_filters( 'the_excerpt', $content );

UPDATE:
for adding featured image use

<?php echo get_the_post_thumbnail($page->ID);?>

A: A reworked example of your snippet
This sample shows you how you can make use of plugins that hook their actions into filters or hooks. It also allows to use password protection for the child post incl. default core translation strings.
$wpse69264_child_pages = get_pages( array(
     'child_of'    => in_the_loop ? get_the_ID() : $post->ID // Are we in the loop?
    ,'sort_column' => 'menu_order'
    ,'sort_order'  => DESC
) );

foreach ( $wpse69264_child_pages as $child )
{
    // Default filters: Excerpt length - Also takes languages in account where 1 char = 1 word (like Chinese)
    $output = $child->post_excerpt ? $child->post_excerpt : apply_filters( 'excerpt_length', $child->post_content );

    if ( post_password_required( $child ) )
    {
        // Default translation
        _e( 'There is no excerpt because this is a protected post.' );
        continue;
    }

    // Just in case
    $output = force_balance_tags( $output );

    // Default filters:
    $output = apply_filters( 'get_the_excerpt', $output );
    echo apply_filters( 'the_excerpt', $output );
}
unset( $wpse69264_child_pages, $child );


text:
Q: Given array=[72,20,73,42,11,80,39,30,100,46,88,32,21], using quicksort, what is the max number of inversions removed by a single comparsion and swap Using 72 as pivot, I reached [72,20,42,11,39,30,46,32,21,73,88,80,100]. Here number of inversions is 22.
After swapping pivot(72) and 21, the number of inversions is 11 so I am getting max. number of inversions removed to be 11.
Is this correct or am I missing something?
I'm assuming swapping that the subfiles after quicksorting recursively will not have a decrease of inversions more than 11.


text:
Q: Focus stacking images using feature matching I am trying to build a code using python where I am trying to align multiple images at least 10 with a reference image. All the images are taken on a smartphone camera. I have come across several documentation which does this for 2 images. But can not find any for multiple images. Can any suggest something which might be helpful. The link to the documentation I mentioned earlier is: https://www.learnopencv.com/image-alignment-feature-based-using-opencv-c-python/. This is what I have tried to iterate through the images. What I expect at the end is that an aligned image from the all the images should be output.
 # Read reference image
  refFilename = "images/image12.jpg"
  print("Reading reference image : ", refFilename)
  imReference = cv2.imread(refFilename, cv2.IMREAD_COLOR)

   #Load all the images
  all_images_to_compare=[]
  all_images = glob.iglob("images/*.jpg")
  for images in all_images:
    imFilename =cv2.imread(images)
    all_images_to_compare.append(imFilename)

  for images_to_compare in all_images_to_compare:
  #imFilename = cv_image
  #print("Reading image to align : ", imFilename);
  #im = cv2.imread(imFilename, cv2.IMREAD_COLOR)

      print("Aligning images ...")
      # Registered image will be resotred in imReg.
      # The estimated homography will be stored in h.
      imReg, h = alignImages(images_to_compare, imReference)

      # Write aligned image to disk.
      outFilename = "aligned.jpg"
      print("Saving aligned image : ", outFilename);
      cv2.imwrite(outFilename, imReg)

      # Print estimated homography
      print("Estimated homography : \n",  h)


text:
Q: Joining two columns with month and year separated into one to do the subtraction for days I have two columns separated in my dataframe, one have month and the other have the year when the store received a competitor. What I am trying to do is join those columns and then subtract from the date to get the values day by day. But running my code that I leave below, I get  an error that I am not able to unveil what that means. I will let the error bellow code.
# competition since
df2['competition_since'] = df2.apply(lambda x: datetime( year=x['competition_open_since_year'], month=x['competition_open_since_month'], day=1, axis=1 ))
df2['competition_time_month'] = ( ( df2['date'] - df2['competition_since'])/30 ).apply(lambda x: x.days).astype(int)

Error
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3079             try:
-> 3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: 'competition_open_since_year'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
<ipython-input-30-ac751656b323> in <module>
      1 # competition since
----> 2 df2['competition_since'] = df2.apply(lambda x: datetime( year=x['competition_open_since_year'], month=x['competition_open_since_month'], day=1, axis=1 ))
      3 df2['competition_time_month'] = ( ( df2['date'] - df2['competition_since'])/30 ).apply(lambda x: x.days).astype(int)

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   7766             kwds=kwds,
   7767         )
-> 7768         return op.get_result()
   7769
   7770     def applymap(self, func, na_action: Optional[str] = None) -> DataFrame:

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/apply.py in get_result(self)
    183             return self.apply_raw()
    184
--> 185         return self.apply_standard()
    186
    187     def apply_empty_result(self):

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/apply.py in apply_standard(self)
    274
    275     def apply_standard(self):
--> 276         results, res_index = self.apply_series_generator()
    277
    278         # wrap results

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/apply.py in apply_series_generator(self)
    288             for i, v in enumerate(series_gen):
    289                 # ignore SettingWithCopy here in case the user mutates
--> 290                 results[i] = self.f(v)
    291                 if isinstance(results[i], ABCSeries):
    292                     # If we have a view on v, we need to make a copy because

<ipython-input-30-ac751656b323> in <lambda>(x)
      1 # competition since
----> 2 df2['competition_since'] = df2.apply(lambda x: datetime( year=x['competition_open_since_year'], month=x['competition_open_since_month'], day=1, axis=1 ))
      3 df2['competition_time_month'] = ( ( df2['date'] - df2['competition_since'])/30 ).apply(lambda x: x.days).astype(int)

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/series.py in __getitem__(self, key)
    851
    852         elif key_is_scalar:
--> 853             return self._get_value(key)
    854
    855         if is_hashable(key):

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/series.py in _get_value(self, label, takeable)
    959
    960         # Similar to Index.get_value, but we do not fall back to positional
--> 961         loc = self.index.get_loc(label)
    962         return self.index._get_values_for_loc(self, loc, label)
    963

~/opt/anaconda3/envs/sales_predict_rossmann/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   3080                 return self._engine.get_loc(casted_key)
   3081             except KeyError as err:
-> 3082                 raise KeyError(key) from err
   3083
   3084         if tolerance is not None:

KeyError: 'competition_open_since_year'

A: When you apply lambda functions to dataframes, the values of the columns get passed to it. So the input for your lambda function is values of the dataframe. I think you're trying to do something like this:
import datetime

df2['competition_since'] = df2['competition_open_since_month'] + "/1/" + df2['competition_open_since_month']

df2['competition_since'] = df2['competition_since'].apply(lambda x: datetime.datetime.strptime(x, "%m/%d/%Y"))

After this you could subtract from the date column to find the difference over each day. Like this (I don't think you need to divide by 30):
(df2['date'] - df2['competition_since']).apply(lambda x: x.days)


text:
Q: Mapfragment is not loaded within fragment the second time MapFragment is not loaded within fragment the second time. I have tried to change some code within override methods but still it's not working. And I'm implementing these interfaces
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
NavigationView.OnNavigationItemSelectedListener

Here is the code
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.activity_new1, container, false);

        FragmentManager manager =getChildFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        fragment = new SupportMapFragment();
        transaction.replace(R.id.map, fragment);
        transaction.commit();

        shared = getActivity().getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        // value_latLan=new ArrayList<>();

        app_bar = (CoordinatorLayout) view.findViewById(R.id.app_bar);
        layoutCartNoItems = (LinearLayout) view.findViewById(R.id.layout_cart_empty);
        hv = (HorizontalScrollView) view.findViewById(R.id.hv);
        l11 = (LinearLayout) view.findViewById(R.id.l1);
        l2 = (LinearLayout) view.findViewById(R.id.l2);

        // fragment.getView().setVisibility(View.GONE);
        l11.setBackgroundColor(Color.parseColor("#dddddd"));
        hv.setHorizontalScrollBarEnabled(false);
        //  app_bar.setVisibility(View.GONE);
        // getActivity().getActionBar().hide();

        l11.setVisibility(View.GONE);
        l2.setVisibility(View.GONE);
        layoutCartNoItems.setVisibility(View.VISIBLE);
        // Toast.makeText(getContext().getApplicationContext(), "hello", Toast.LENGTH_SHORT).show();
        fragment.setRetainInstance(true);
        fragment.getMapAsync(this);

    return view;
}

@Override
public void onPause() {
    super.onPause();
      //stop location updates when Activity is no longer active
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap)
{
    mGoogleMap=googleMap;
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            //Location Permission already granted
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        } else {
            //Request Location Permission
            checkLocationPermission();
        }
    }
    else {
        buildGoogleApiClient();
        mGoogleMap.setMyLocationEnabled(true);
    }
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

Thanks in advance..


text:
Q: Using external accessory framework to read all protocols I want to make an app that interfaces with a sony radio that has an app to control the unit. It uses external accessory framework from iPhone so how can i get all the protocols from the radio or is there anyway to read the protocols coming from the sony app that would communicate with the radio. In short can i get the protocols from the sony radio using external accessory framework?

A: How does the device connect to the radio? 30 pin/lightning?  Bluetooth? or WiFi?
Only the manufacturer who has entered into the MFI license agreement with Apple will have the details on how to interface with their device via cable or Bluetooth, so it is unlikely that you will be able to discover the protocols without some fairly low-level electronic monitoring of the signals.
If it is a WiFi connection then you may be able decode the protocol using Wireshark or similar.

A: You can use this app to get the supported protocols: https://developer.apple.com/library/ios/samplecode/EADemo/Introduction/Intro.html
But you won't be able to do much without reverse engineering the protocol.


text:
Q: How to choose between additive and multiplicative decomposition in time series I have a time series which is the number of weekly flu cases from 2010 to early 2018 in one county. I want to remove seasonality from my data so I can have a clearer data to infer the relationship with environmental factor PM2.5. I know if the amplitude over time is constant I can use additive model to extract seasonality and if it changes (decrease or increase over time) I use multiplicative model.
My problem is in my time series the amplitude does not increase or decrease monotonically and it kind of fluctuate. I searched a lot and went through couple of books but not sure what to use here.

Can you please help me what time of decomposition I can use to remove the seasonality from the data?
Also if I use additive model, when I subtract the seasonal component from the flu cases, I get a lot of negative values which do not make sense in terms of count. Is there any thing I can do about it?


text:
Q: Evaluate A line Integral Via Green's theorem. Find the value of Line Integral $\int_{C}F.dr$ where $\vec{F} = (x + y)\hat{i} + (1-x)\hat{j}$ where $C$ is the portion of the curve $x^2/4 + y^2/9 = 1$ that is in 4th quadrant with  anti clockwise notation.
Now, using Green's theorem this Line integral is
$\displaystyle \int \int -2 dx dy$ , Since ellipse is symmetric in all quadrants, area in 4th quadrant  = 1/4 area of ellipse,
This gives me $-3\pi$
However, the answer given to me is $5 - 3\pi$
Can anyone tell me the error in my solution  ?
Thank you.


text:
Q: Can Windows phone 8 SDK be installed on a Windows 8 32 bit machine I have been trying to install the Windows Phone 8 SDK on a Windows 8 (x86) machine. But to no avail even though I read somewhere on the site that it will install but I will not be able to run the emulator.
Is Microsoft serious that Win Phone 8 apps can only be developed on 64-bit machines?

A: They make it quite clear the x64 is required on the download page:

Windows 8 64-bit (x64) client versions

I can't say with any authority, but I suspect it is because the emulator uses Hyper-V, which also requires x64:

Hyper-V requires a 64-bit system that has Second Level Address Translation (SLAT).


text:
Q: can a void * be malloced? I have been using ODBC in C. They have a defined type:
typedef void *          SQLPOINTER;
typedef unsigned int    SQLUINTEGER;

I have a function alloc_buffer:
void db_alloc_buffer(SQLUINTEGER buffSize, SQLPOINTER *Ptr)
{
    *Ptr = malloc(buffSize);
    memset(*Ptr, ' ', buffSize);
}

Is is safe/correct to de reference Ptr? or can I do:
void db_alloc_buffer(SQLUINTEGER buffSize, SQLPOINTER *Ptr)
{
    Ptr = malloc(buffSize);
    memset(Ptr, ' ', buffSize);
}

A: No, it's not safe to dereference Ptr the way you are in the second version. Ptr is a pointer to a pointer, not a pointer directly to the buffer. The purpose of this function is to allocate a buffer that can be used by the caller. The caller provides the address of their pointer variable, and your function is supposed to allocate a buffer and set that variable to the address of the buffer, and it does that by dereferencing Ptr with the result of malloc().
If you assign to Ptr instead of *Ptr, that just assigns to the local variable, not the caller's variable.

A:
can a void * be malloced?

Yes. Why couldn't it: void** p = malloc(sizeof(void*));

Is is safe/correct to de reference Ptr?

Safe? Only if Ptr points to valid memory. If someone calls db_alloc_buffer(n, NULL) then it definitely isn't safe.
Correct? That depends on what you're trying to do. The second code doesn't seem useful because you're ignoring the value of the argument that was passed in as Ptr.
The first version seems more useful, since it at least has some observable effects outside the function, namely that it modifies the SQLPOINTER that was passed as Ptr.
It seems that you want something like this:
SQLPOINTER db_alloc_buffer(SQLUINTEGER buffSize)
{
    SQLPOINTER Ptr = malloc(buffSize);
    if (Ptr == NULL) return NULL;
    memset(Ptr, ' ', buffSize);
    return Ptr;
}


text:
Q: Вывод данных в цикле while (PHP) из массива JSON Есть массив JSON:
{"city":{"id":2013159,"name":"London", "list":
[
{"dt":1459360800,"main":{"temp":-6.55,"temp_min":-6.55,"temp_max":-2.34}}
{"dt":1459425600,"main":{"temp":-8.55,"temp_min":-10.55,"temp_max":-4.34}}
{"dt":1459458000,"main":{"temp":-10.56,"temp_min":-15.55,"temp_max":-8.34}}
]}

он в переменной $weatherDatas_json
Преобразовал данные формата JSON в переменную массива
$weatherDatas = json_decode($weatherDatas_json, true);

Чтобы вывести данные dt с 1(нулевого) элемента массива делаю следующее:
$weatherDt = $weatherDatas['city']['list'][0][dt];
echo $weatherDt;

как вывести все dt из массива? Подскажите пожалуйста конструкцию while. не могу подставить номер элемента массива автоматически, причем данных dt(элементов массива) может быть разное количество

A: зачем тебе while? Тут однозначно foreach (while - медленнее в порядок просто)
Как ограничивать кол-во выводимых? заводишь счетчик $limit, плюсуешь его когда надо, а в начале цикла проверку:
foreach ($weatherDatas["list"] as $key => $value) {
     if ($limit == 5) break;
     echo $value["dt"],"\n";
     $limit++;
}

A: https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/ - вот здесь описано очень хорошо
Сделал следующим образом:
в первую очередь, для визуального понимания массива, лучше его вывести через оператор:
print_r($weatherDatas);

далее для выборки всех элементов из массива используется оператор:
foreach ($weatherDatas["list"] as $key => $value) {
    echo $value["dt"],"\n";
  }

единственное, как ограничить количество выводимых элементов, например выводить 5 первых элементов массива?


text:
Q: Loop through cells and import CSV files, by using the cells' value in the file path I have 1 sheet with asset names in the top row and dates in the first column.

I need to loop trough all cells in the first row, take the cell's value and include it in the file path to import column 6 from a text file.
So far I've got this:
For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column
    If HCP.Cells(1, i).Value <> "" Then
        j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column + 1
            With HCP.QueryTables.Add(Connection:="TEXT;" & Folder & "\" & i & "1440.CSV", Destination:=HCP.Cells(2, j + 1))
                .TextFileParseType = xlDelimited
                .TextFileCommaDelimiter = True
                .TextFileSpaceDelimiter = True
                .TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
                .Refresh BackgroundQuery:=False
                i = i + 1
            End With
    End If
Next

And I get this at the .Refresh BackgroundQuery:=False line:

I reckon I am not using the variables in the loop correctly.

A: It's because you're not actually setting i to any value in a cell, it's only your counter.  You need to set HCP.Cells(1, i).Value to a variable and pass that variable through your file path.
Try this:
For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column

    rowContent = HCP.Cells(1, i).Value

    If rowContent <> "" Then
        j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column + 1
            With HCP.QueryTables.Add(Connection:="TEXT;" & Folder & "\" & rowContent & "1440.CSV", Destination:=HCP.Cells(2, j + 1))
                .TextFileParseType = xlDelimited
                .TextFileCommaDelimiter = True
                .TextFileSpaceDelimiter = True
                .TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
                .Refresh BackgroundQuery:=False

            End With
    End If
Next

Also you dont need i = i + 1 in your code, the Next will automatically increment your i number up To the value you specified.


text:
Q: 3D rotation matrix with zero determinant I have a 3D vector from the following shape:
\begin{gather}
p = \begin{bmatrix} 0 \\ 0 \\ z \end{bmatrix}
\end{gather}
I had like to find a rotation matrix that will make p(1) and p(2) small non zero numbers and p(3) to be close to z value.
basically, by writting,
\begin{gather}
p' = \begin{bmatrix} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{bmatrix} \begin{bmatrix} 0 \\ 0 \\ z\end{bmatrix} = \begin{bmatrix} a_{13} \\ a_{23} \\ a_{33} \end{bmatrix} \cdot z
\end{gather}
Since it is rotational matrix I had expect it to have the same magnitude and therefore:
\begin{gather}
\sqrt{a_{11}^2 + a_{23}^2 + a_{33}^2} = 1
\end{gather}
The first idea that I had is something from the form of
\begin{gather}
p' = \begin{bmatrix} 0 & 0 & \sin(\alpha) \\ 0 & 0 & 1 \\ 0 & 0 & \cos(\alpha) \end{bmatrix} \begin{bmatrix} 0 \\ 0 \\ z\end{bmatrix} = \begin{bmatrix} \sin(\alpha) \\ 1 \\ \cos(\alpha) \end{bmatrix} \cdot z \qquad, \alpha<1
\end{gather}
However, this matrix is problematic from my understanding because its determinant is zero and also the value of p'(2) is equal to z and I was looking for small value.
Is there any idea how to overcome these problems?
Thank you!


text:
Q: Returning data from AsyncTask without blocking UI I have a conceptual problem related to AsyncTask class. We use AsyncTask so that the main UI is not blocked.
But suppose, I want to retrieve some data from the device's memory, and I use AsyncTask class for this. The relevant line of the code will be as follows (assuming the data type returned is String):
  //code
    String data = new ExtendedAsyncTask().execute(param1, param2).get();
  //use this returned value.

Won't the above line block the UI, defeating the purpose of using the AsyncTask ? If yes, then how do I get the relevant data without blocking UI ? I would like to add that the next line of code will need this data to perform some task, and hence depends on the returned value.
Thanks

A: get() method will block the UI thread. To get the relavent data you need to return the value from doInBackground and capture the value in onPostExecute parameter.

Value returned by doInBackground is captured by onPostExecute method

Example:
public class BackgroundTask extends AsyncTask<String, Integer, String >{
       private ProgressDialog mProgressDialog;
       int progress;
       public BackgroundTask() {
           mProgressDialog = new ProgressDialog(context);
             mProgressDialog.setMax(100);
             mProgressDialog.setProgress(0);
    }

       @Override
    protected void onPreExecute() {
           mProgressDialog =ProgressDialog.show(context, "", "Loading...",true,false);
        super.onPreExecute();
    }
     @Override
     protected void onProgressUpdate(Integer... values) {
     setProgress(values[0]);
  }

    @Override
    protected String doInBackground(String... params) {
            String data=getDatafromMemoryCard();

        return data;  // return data you want to use here
    }
    @Override
    protected void onPostExecute(String  result) {  // result is data returned by doInBackground
        Toast.makeText(context, result, Toast.LENGTH_LONG).show();
        mProgressDialog.dismiss();
        super.onPostExecute(result);
    }
   }

If you are using asynctask in separate class, then use AsyncTask with callback interface like this

Here is the answer I have  provided earlier about the same AsyncTask with Callback

A: When an asynchronous task is executed, the task goes through 4 steps:
1.onPreExecute(), invoked on the UI thread before the task is executed. use this to diaply progress dialog.

2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. Can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). Used to publish progress.

4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

In your activity onCreate()
    TextView tv;
   @Override
   protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv= (TextView)findViewById(R.id.textView);
    new TheTask().execute();

  }
class TheTask extends AsyncTask<Void, Void,String> {

  protected void onPreExecute() {
  //dispaly progress dialog
 }

 protected String doInBackground(Void... params) {
   //do network operation
     return "hello";
 }

 protected void onPostExecute(String result) {
  //dismiss dialog. //set hello to textview
      //use the returned value here.
     tv.setText(result.toString());
 }
 }

Make asynchronous calls, Notifies on the ui thread.
Update: AsyncTask is deprecated. Switch to kotlin coroutines. https://developer.android.com/kotlin/coroutines

A: You don't get the result this way. See this link for an example : https://github.com/levinotik/ReusableAsyncTask/tree/master/src/com/example
Basically, here is what you need to do :

*

*Define an interface (= a listener) that your activity implements

*Set the listener in the asynctask

*Call yourListener.yourMethod() in the onPostExecute