text:
Q: Importing json into couchdb such that each object becomes a document I have a JSON file in the following format:
"rows": [
        {
            "key": [
                null,
                null,
                "dco_test_group",
                "3d3ce6270fdfuashge12e1d41af93179",
                "test_djougou"
            ],
            "value": {
                "lat": "31.538208354844658",
                "long": "91.98762580927113"
            }
        },
        {
            "key": [
                null,
                null,
                "dco_test_group",
                "4cda7jhsadgfs6123hsdaa9069ade2",
                "test_ouake"
            ],
            "value": {
                "lat": "59.696798503352547",
                "long": "11.6626995307082464"
            }
        },

I want to import the file such that each object inside rows becomes a couchdb document. Right now, I have the following code:
curl -X PUT --data-binary @"C:\Users\me\Dropbox (Personal)\Research\Folder\location.json" http://127.0.0.1:5984/db/document_name

This adds all the data inside document_name.
If I try:
curl -X PUT --data-binary @"C:\Users\me\Dropbox (Personal)\Research\Folder\location.json" http://127.0.0.1:5984/db

a new db is created but no data gets added. How do I edit the code to get the desired output?
UPDATE 1
Does it matter if all the data is in record? Are there any rules analogous to 5 normal forms of RDB?

A: Use the bulk-document-api for this. Here is an example from the docs >> https://wiki.apache.org/couchdb/HTTP_Bulk_Document_API#Modify_Multiple_Documents_With_a_Single_Request
$ DB="http://127.0.0.1:5984/mydb"
$ curl -H "Content-type:application/json" -d '{"docs":[{"key":"baz","name":"bazzel"},{"key":"bar","name":"barry"}]}' -X POST $DB/_bulk_docs
$ curl -H "Content-type:application/json" -d @your_file.json -X POST $DB/_bulk_docs

Note, that all docs are items within a 'docs' array.


text:
Q: whats wrong with a simple IOC container class? last day I implemented a simple class to serve as IOC container (not much like that) in one of my playground projects and some pro guy told me that is going to have some problem when testing the code (too vein to share what exactly is the problem !!)
although I always use IOC frameworks myself, I wanted to know why exactly this methodology is bad ?
I even wrote many tests (using mock frameworks) using this methodology and never had a problem.
I want your Idea about design problems of this:
public class IocContainer{

  private static IocContainer instance;

  private IocContainer(){
  }

  public static IocContainer getInstance()
  {
    if(instance == null){
      instance = new IocContainer();
    }
    return instance;
  }

  public ChatPresenter getChatPresenter(ChatView chatView)
  {
    return new ChatPresenterImpl(chatView, getChatRepo() , getMessagingService());
  }

  private ChatRepo getChatRepo()
  {
    return new ChatRepoImpl(getDbHelper(), getRemoteService());
  }

  private MessagingService getMessagingService()
  {
    return new MessagingServiceImpl()
  }

  private DbHelper getDbHelper()
  {
    return new DbHelperImpl();
  }

  private RemoteService getRemoteService()
  {
    return new RemoteServiceImpl();
  }
}

as you see I only made getChatPresenter accessible and I use this like below in my view and it works well.
ChatPresenter presenter = IocContainer.getInstance().getChatPresenter(this)

the code handles inversion of control without any tight coupling (using interfaces).
I wanna know any wrong thing with this approach ?  (I want answers from technical point of view cuz I already know using a Ioc container library is easier has more features like scopes and so ...)
Actually I want to know any problem and limitation this approach would make in the future ?
be cruel and kill me :D

A: To summarize the comment trail:
Your approach looks like the service locator as described here by Martin Fowler: http://martinfowler.com/articles/injection.html#InversionOfControl
There's a major difference between what Martin describes and your code: your code directly creates instances of your services and thus is more of a factory than a registry.
The basic idea/goal of inversion-of-control is to reduce coupling by reducing dependencies, which doesn't happen if your container depends on the service implementations (which it needs to directly call the constructors). So the implementation in your question somewhat opposes that basic idea.
One of the disadvantages of depending on the implementations would be that the services can't be replaced without having to recompile the container. That might not be a problem if you'll most likely never have different implementations anyway but if you might need it, a service registry would be more useful.
A registry normally provides for methods to register implementations of services and deliver one upon request. Which is delivered depends on your needs but it could be as simple as the first implementation found or be more complex, e.g. by matching some parameters (for some idea on that have a look at CDI injection point parameters and alternatives).
The registry is generally accompanied by some means to configure the registry, e.g. via config files or classpath scanning (automatic lookup on plugins that are present). However, it might also be sufficient to just write some code that configures the registry. It all depends on what coupling you need to get rid of (to solve a problem you face) and which coupling is acceptable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: vhdl code understanding, if there is modelsim error about possible infinite loop --
-- VHDL Architecture di_lib.ShiftRegister1.ShiftRegister1
--
-- Created:
--          by - 294162.UNKNOWN (VD1210)
--          at - 14:19:36 10-04-2015
--
-- using Mentor Graphics HDL Designer(TM) 2010.2a (Build 7)
--
LIBRARY ieee;
USE ieee.std_logic_1164.all;

LIBRARY WORK;
USE WORK.CALC_PKG.ALL;
LIBRARY di_lib;
USE di_lib.calc_pkg.all;
USE ieee.NUMERIC_STD.all;

ENTITY ShiftRegister1 IS
   PORT(
      d_out       : OUT    Std_Logic_Vector (7 DOWNTO 0);
      multiplexer : IN     Std_Logic_Vector (7 DOWNTO 0);
      carry       : IN     std_logic;
      load_out    : IN     std_logic;
      f_code      : IN     std_logic_vector (2 DOWNTO 0);
      out_loaded  : OUT    std_logic
   );

-- Declarations

END ShiftRegister1 ;

--
ARCHITECTURE ShiftRegister1 OF ShiftRegister1 IS
BEGIN

  ShiftRegister1 : process

  variable remember, multiplexer_var       : std_logic_vector(7 DOWNTO 0);
  variable state          : std_logic_vector(2 DOWNTO 0);
  variable counter        : integer := 0;
        begin

          state := f_code;

        case state is

        when "000" =>
            d_out <= multiplexer;

        when "001" =>
            d_out <= multiplexer;

        when "010" =>
                multiplexer_var := multiplexer;
            if load_out = '1' then
              if carry = '1' then
                --shifting is done without function SRL
                remember(0) := multiplexer_var(1);
                remember(1) := multiplexer_var(2);
                remember(2) := multiplexer_var(3);
                remember(3) := multiplexer_var(4);
                remember(4) := multiplexer_var(5);
                remember(5) := multiplexer_var(6);
                remember(6) := multiplexer_var(7);
                remember(7) := '1';
                d_out <= remember;
                out_loaded <= '1';

              elsif  carry = '0' then
                remember(0) := multiplexer_var(1);
                remember(1) := multiplexer_var(2);
                remember(2) := multiplexer_var(3);
                remember(3) := multiplexer_var(4);
                remember(4) := multiplexer_var(5);
                remember(5) := multiplexer_var(6);
                remember(6) := multiplexer_var(7);
                remember(7) := '0';
                d_out <= remember;
                out_loaded <= '1';
              end if;
            end if;

        when "011" =>
            if load_out = '1' then
              d_out <= multiplexer;
              out_loaded <= '1';
            end if;

        when others => null;

        end case;
   end process;

END ARCHITECTURE ShiftRegister1;

--ERROR GIVEN --

-- Compiling architecture shiftregister1 of shiftregister1
  **Warning: [2] <...>vhd(109): (vcom-1090) Possible infinite loop:   Process contains no WAIT statement.
  Warning: Cannot create unmappedlibrary work

QUESTION:
where possibly in this code an infinite loop can occur?

A: In VHDL, a process's execution time is instantaneous. Also, a process is re-executed as soon as it finishes. Thus your process forms an infinite loop.
To fix this, whether add a wait statement, or use sensitivity list. A process with a sensitivity list will only execute when one of sensitivity list signals changes. Something like:
process(load_out, carry, multiplexer, f_code)

You have to make sure to add all signals that the process uses on the sensitivity list, otherwise you will get a simulation mismatch, as sensitivity list is ignored for synthesis.


text:
Q: Autorotation in multi window in iOS I'm building a library in which I'm creating a window and then attaching my own view controller (subclass of UIViewController class) to it. Now I need to use it in a test application. Now when I'm trying to rotate this screen on changing the orientation, it is not happening as my own view controller is not getting the shouldAutoRotateOnOrientaionChange notification. How to solve this problem?

A: Set the Supported Device Orientations in the Summary tab of your target's settings.


text:
Q: VB .Net GeckoFx openload or ok.ru embeds doesn't work THIS EXAMPLE IMAGE 1
VB.Net Project;
Doesn't work clicks, and doesn't work play button on iframe.
Web Resource:

<iframe id="x" width="708" height="450" src="//ok.ru/videoembed/96229591732" frameborder="0" allowfullscreen></iframe>

I'm use SkyBound GeckoFx v1.9.1.0

A: SOLVED!
UPDATE LASTEST VERSION
Package Manager Console:
Install-Package GeckoFX


text:
Q: javascript object literal - object creation I'm trying to create an object in which some properties rely on other previously defined properties, while trying to rely on object literals. Otherwise put, I'm trying to accomplish something like the following code (which is incorrect):
var mesh = {
            offset   : $('#mesh').offset(),
            position : $('#mesh').position(),
            height   : win.height - this.offset.top - 12,
            width    : win.width - this.offset.left - 12,
            limits   : {}
        }

as opposed to something of this sort (which works):
var mesh = {};
        mesh.offset   = $('#mesh').offset();
        mesh.position = $('#mesh').position();
        mesh.height   = win.height - mesh.offset.top - 12;
        mesh.width    = win.width - mesh.offset.left - 12;
        mesh.limits = {};

So my question is rather simple:  what is actually wrong with the first block of code and how can I correct it in order to create those new properties based on previously defined ones?

A: There is no name that references the currently-building object literal.  You'll need to use the second form, or have the values in variables that you can reference:
var offset = $('#mesh').offset();
var mesh = {
    offset   : offset,
    position : $('#mesh').position(),
    height   : win.height - offset.top - 12,
    width    : win.width - offset.left - 12,
    limits   : {}
}

A: you can create a constructor function
var Mesh = function(mesh_id){
    var mesh = $(mesh_id);
    this.offset = mesh.offset();
    this.position = mesh.position();
    this.height = win.height - this.offset.top - 12;
    this.width = win.width - offset.left - 12
    this.limits = {}

};

and then use it like this
var myMesh = new Mesh('#mesh')

*note that this code is assuming some variable win is defined.  you have probably defined it as var win = $(window)


text:
Q: VB.NET and EWS Unread Mail Count caching Exception I have a problem wit some VB.Net code using EWS (Exchange Web Services) to acces a mailbox and count the number of unread mails.
And it works but my problem is that i want to buld in some error handeling eg when wrong login informationen.
When i tets my code with a wrong username i get an ServiceRequestException in this code
Dim emails = service.FindItems(WellKnownFolderName.Inbox, sf, iv)

I have tryed with some Try Cach and so on but it docent seems to catch the error.
Hope someone can help me how to catch such an error so my code docent stop and crashe.
Try

            Dim service = New ExchangeService(ExchangeVersion.Exchange2010_SP1)
            Dim credential As New NetworkCredential("username", "password", "localdomain")
            Dim Url = New Uri("https://mail.mydomain.com/EWS/Exchange.asmx")
            Dim prop As New PropertySet(BasePropertySet.FirstClassProperties)

            service.Url = Url
            service.Credentials = credential

            Dim arrSearchFilter(1) As SearchFilter
            arrSearchFilter(0) = New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, True)
            arrSearchFilter(1) = New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False)

            Dim oSearchFilter As SearchFilter = Nothing
            oSearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.Or, arrSearchFilter)

            Dim oView As ItemView = New ItemView(20)

            Dim iv = New ItemView(5) ' get last 5 emails

            iv.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending)

            Dim sf As SearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.And, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False))

            Dim emails = service.FindItems(WellKnownFolderName.Inbox, sf, iv)

            tAntal.Text = emails.Count ' Writs the number of unread Mails

Catch
            MsgBox("Error4")
End Try

See image for error message.
enter image description here

A: Try specifying the type of Exception you want to catch, and also leave only the line where the Exception is thrown inside the "Try" block:
Dim service = New ExchangeService(ExchangeVersion.Exchange2010_SP1)
Dim credential As New NetworkCredential("username", "password", "localdomain")
Dim Url = New Uri("https://mail.mydomain.com/EWS/Exchange.asmx")
Dim prop As New PropertySet(BasePropertySet.FirstClassProperties)

service.Url = Url
service.Credentials = credential

Dim arrSearchFilter(1) As SearchFilter
arrSearchFilter(0) = New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, True)
arrSearchFilter(1) = New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False)

Dim oSearchFilter As SearchFilter = Nothing
oSearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.Or, arrSearchFilter)

Dim oView As ItemView = New ItemView(20)

Dim iv = New ItemView(5) ' get last 5 emails

iv.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending)

Dim sf As SearchFilter = New SearchFilter.SearchFilterCollection(LogicalOperator.And, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False))

Try
    Dim emails = service.FindItems(WellKnownFolderName.Inbox, sf, iv)
Catch Ex As ServiceRequestException
    MsgBox(Ex.Message)
End Try

tAntal.Text = emails.Count ' Writs the number of unread Mails


text:
Q: Can we Access Multi-Currency Values from Custom Setting using Apex Trigger I have a Standard Object "Opportunity" I want to access a custom-setting with multiple currency
I have multi-currency enabled in my org.
Generally a custom setting can be accessed like follows
Using Hierarchy :
Custom_Setting_Name__c mysetting = Custom_Setting_Name__c.getInstance();

Using List :
CustomSettingName__c mySetting = CustomSettingName.getValues('SomeValue');

or
CustomSettingName__c.getAll().values();

I would like to know if we can access the multi-currency values ( Type : Picklist ) the same way as above or is there a special way of handling multi-currency in force.com.
Any head-up will be much appreciated.

A: You only need to define the currency iso code on your account records. Then once you create a new opportunity for a particular account, it will default the currency automatically from your account.
To define the currency automatically on the account. I would create a custom setting list with the country as the Name and a text field for the IsoCode.
Then with a trigger before insert, set the CurrencyIsoCode based on the custom setting.
account.CurrencyIsoCode = CountryCurrency__c.get(account.BillingCountry).CurrencyIsoCode__c;


text:
Q: Group by multiple columns ( one with comma separated and other with sum ) using Unix I have a text/csv file as follows:
EDMP_SCI|INACTIVE|12|AE

EDMP_SCI|INACTIVE|10|AO

EDMP_SCI|ACTIVE|20|IN

EDMP_SCI|ACTIVE|30|US

EDMP_EBBS|UNKNOWN|10|HK

I need to group by based on column1 and column2
(Column3 should have the sum of numbers and column4 should have comma separated values)
The required output should be like:
EDMP_SCI|INACTIVE|22|AE,AO

EDMP_SCI|ACTIVE|50|IN,US

EDMP_EBBS|UNKNOWN|10|HK

I am able to get sum and comma separated columns separately, but I need then to be done parallelly. I need this either by Unix shell script or any single command in Unix.

A: You can use awk.
For example:
awk -F '|' '{print $1 "|" $2 " " $3" " $4}' input | awk '{sum[$1]+=$2}{loc[$1]=loc[$1]$3","}END{for(c in sum){print c"|"sum[c]"|"substr(loc[c],0,length(loc[c])-1)}}'

input is your data file.


text:
Q: Custom Valid URL validation using regular expression in Javascript Here,
I am validating URL with following string which either it should be http/https or ip address along with query string and different parenthesis square bracket [] .
I want to prevent following url parenthesis
2)http://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]Id] - Not Allowed
what should be regular expression to prevent [publisher[client_id]Id] sting ?
I'm using following regular expression for above strings
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
        if(!regex .test(str)) {

            return false;
        } else {
            return true;
        }

what should be changed code for same?
Please help me for the same.

A: Try this:

var strings = [
   '[publisher[client_id]Id]',
   '[publisher_id]'
];

var pattern = /\[.*\[.*\].*\]/;

strings.forEach(function(string){
   if(pattern.test(string)) {
      console.log(string + " -> matched");
   }
   else {
      console.log(string + " -> not matched");
   }
});

A: try this. the first group return url without parameter (withour your publiser, etc)
sorry didn't read it carefully. try that one and return true if valid
edited

var t1 = "htts:/192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]";
var t2 = "https://192.0.0.0/b4d2f30f-d617-403a-bb2f-dec755d01192";
var t3 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?[publisher[client_id]]";
var t4 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?name=[publisher[client_id]]";
var t5 = "https://192.0.0 .0/b4d2f30f-d617-403a-bb2f-dec755d01192?foo=bar&name=[publisher[client_id]]";

function check(str) {
  var url = /((http[s]?:\/\/){1,1}(\w+[-.\/]{0,1}\w?)*)/g,
    p = /([\?\&](\w+=){0,1}\[\w+\[\w+\]\w*\])/g;
  /*check for url*/
  if (!url.test(str)) {
    return "invalid url";
  }
  /*check for [userid[userid]]*/
  return p.test(str) ? "invalid" : "valid";
}
document.body.innerHTML = check(t1) + "
";
document.body.innerHTML += check(t2) + "
";
document.body.innerHTML += check(t3) + "
";
document.body.innerHTML += check(t4) + "
";
document.body.innerHTML += check(t5) + "
";

regards


text:
Q: Problem with Line spacing in wysiwyg editor in WP 3.5.1 Since updating to 3.5.1, I can no longer get single line breaks in the WYSIWYG editor.  I used to be able to shift-return for a line break and return for a paragraph break.  But now all lines have double spacing.  Hitting "delete" at the beginning of the line does not help.
I can of course fix this by switching out of WYSWYG mode, but this makes no sense to me.  I tried replacing the WP-ADMIN folder with a fresh copy, no change.
Any ideas?

A: A "workaround" that I found which made it work for me today is to add:
define( 'CONCATENATE_SCRIPTS', false );

to the end of wp-config.php

A: On windows, I use ALT + SHIFT + ENTER, for Mac I think that would be OPTION + SHIFT + RETURN


text:
Q: RSA Key only seems to contain its memory address. Swift, MacOS I am currently trying to generate a CSR for a mac app, and have narrowed down an issue within my key generation.
I am currently using the code below to generate the keys, which for the most part works. However, from a lot of the references I have been using, the expected output should be along the lines of:
<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: 0x600001ae74c0>
However, on checking the SecKeyRef output in debug after key generation, all I get is this:
<SecKeyRef: 0x600000cbd6e0>
I suspect this is the reason when I check the CSR out put on Red Kestrel that the key size is 0 and the CSR signature can't be read.
Just wondering if this might be why?
        let publicKeyParameters: [String: Any] = [
        String(kSecAttrIsPermanent): true,
        String(kSecAttrAccessible): kSecAttrAccessibleAfterFirstUnlock,
        String(kSecAttrApplicationTag): tagPublic.data(using: .utf8)!
    ]

    let privateKeyParameters: [String: Any] = [
        String(kSecAttrIsPermanent): true,
        String(kSecAttrAccessible): kSecAttrAccessibleAfterFirstUnlock,
        String(kSecAttrKeySizeInBits): 2048,
        String(kSecAttrApplicationTag): tagPrivate.data(using: .utf8)!
    ]

    let parameters: [String: Any] = [
        String(kSecAttrKeyType): algorithm.secKeyAttrType,
        String(kSecAttrKeySizeInBits): keySize,
        String(kSecReturnRef): true,
        String(kSecPublicKeyAttrs): publicKeyParameters,
        String(kSecPrivateKeyAttrs): privateKeyParameters
    ]

    var error: Unmanaged<CFError>?
    let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error)


text:
Q: Get a signed url for Amazon's Product Advertising API I have this function in PHP in Windows with easyPHP to sign a request for Amazon's Product Advertising API but doesn't work, because the output doesn't generate a correct signature and I don't know why. When I make the request with the generate url, Amazon says that the SignatureDoesNotMatch
function amazon_get_signed_url($searchTerm) {
    $keyword = $searchTerm; // The keywords you're searching for
    $aws = array();
    $keyword = urlencode($keyword);
    $url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService";
    $url .= "&AWSAccessKeyId=".AWS_ACCESS_KEY_ID;
    $url .= "&Operation=ItemSearch";
    $url .= "&SearchIndex=DVD";
    $url .= "&Keywords=".$keyword."";
    $url .= "&ResponseGroup=Small,OfferFull,Images,Reviews,ItemAttributes,SalesRank";
    $url .= "&Timestamp=".gmdate('Y-m-d\TH:i:s\Z');
    $url = str_replace("+",urlencode("+"),$url);
    $url_a = parse_url($url);
    $url_a['query'] = str_replace(',',urlencode(','),$url_a['query']);
    $url_a['query'] = str_replace(';',urlencode(':'),$url_a['query']);
    parse_str($url_a['query'],$params);
    uksort($params, 'strnatcmp');
    $qstr = '';
    foreach ($params as $key => $val) {
    $qstr .= "=".rawurlencode($val);
    }
    $qstr = substr($qstr, 1);
    $qstr = str_replace('%20',urlencode('+'),$qstr);
    $qstr = str_replace(',',urlencode(','),$qstr);
    $qstr = str_replace(';',urlencode(':'),$qstr);
    $sig = "GET\nwebservices.amazon.com\n/onca/xml\n".$qstr;
    $sig = base64_encode(hash_hmac('sha256', $sig, AWS_SECRET_ACCESS_KEY, true));
    $sig = str_replace('+','%2B',$sig);
    $sig = str_replace('=','%3D',$sig);
    $params['Signature'] = $sig;
    $p = array();
    foreach($params as $k=>$v) {
    $p[]=$k."=".$v;
    }
    $qstr = implode("&",$p);
    $rebuilt_url = $url_a['scheme']."://".$url_a['host'].$url_a['path']."?".$qstr;
    $aws['url'] = $url."&Signature=".$sig;
    return $aws['url'];
}

A: I got this to work, though I've had to modify it.  Google Sameer Borate and Ulrich Mierendorff I use their code.
My code is found here
But there seems to be something wrong with my webhost right now. :-(


text:
Q: How do you write a when clause with a comparison of several columns in SQLite? I'm making a SQLite database where I want to have three tables: Users, Books and Bought. Users exists of the columns username, password, name, street, housenumber, postcode and country, where username is the primary key. Books exists of the columns ISBN, year, title, genre, price, author, publisher, summary, numberofpages and amountinstock, where ISBN and year are the primary key. And Bought exists of the columns username, ISBN, year, amount and time, where username, ISBN and year are foreign keys.
I want to add a trigger in such a way that when there will be added a tuple to Bought the SQL will check whether there's enough of that book in stock and if so then it will change the stock number of that book in Books and add the order to Bought.
I've tried already something, but it still gives me a syntax error around the when clauses, but I do not know why.
Here is the insert trigger that I made:
CREATE TRIGGER BoughtInStockTrigger
BEFORE INSERT ON Bought
FOR EACH ROW
WHEN (NEW.amount <= (SELECT SUM(amountinstock) FROM Books B WHERE B.ISBN = NEW.ISBN AND B.year = NEW.year))
BEGIN
    UPDATE Books
    SET amountinstock = amountinstock - NEW.amount
    WHERE ISBN = NEW.ISBN AND year = NEW.year;
END
WHEN (NEW.amount > (SELECT SUM(amountinstock) FROM Books B WHERE B.ISBN = NEW.ISBN AND B.year = NEW.year))
BEGIN
    ROLLBACK;
END;

Where did I make a syntax mistake?


text:
Q: Python+numpy: a lucky floating point case? I'm inverting a very simple matrix, and I stumbled in something which I don't understand.
EDIT: In the original post I forgot to take care of the fact that numpy defaults to float64, hence the float32 computation was actually happening with double precision. I replaced the original version with a corrected one which casts the matrixes to the correct type before performing the operation.
When using float32 everything seems fine:
In [1]: import numpy as np

In [2]: t='float32'

In [3]: np.set_printoptions(precision=50)

I need a couple of costants:
In [4]: z1 = np.float32((1+np.sqrt(5))/2)

In [5]: z2 = np.float32((1-np.sqrt(5))/2)

In [6]: print "%.50f" % z1
1.61803400516510009765625000000000000000000000000000

In [7]: print "%.50f" % z2
-0.61803400516510009765625000000000000000000000000000

In [8]: print "%.50f" % (z1+z2)
1.00000000000000000000000000000000000000000000000000

C is the main matrix:
In [9]: C = np.array([[1., 1.],
   ...:              [z1, z2]]).astype(t)

In [10]: print C
[[ 1.                         1.                       ]
 [ 1.61803400516510009765625 -0.61803400516510009765625]]

And Cinv is the inverse:
In [11]: Cinv = np.array([[-z2/(z1-z2), 1/(z1-z2)],
   ....:                  [-z1/(z2-z1), 1/(z2-z1)]]).astype(t)

In [12]: print Cinv
[[ 0.2763932049274444580078125  0.447213590145111083984375 ]
 [ 0.723606765270233154296875  -0.447213590145111083984375 ]]

Finally, the dot product:
In [13]: print np.dot(Cinv, C)
[[  1.00000000000000000000000000000000000000000000000000e+00
    0.00000000000000000000000000000000000000000000000000e+00]
 [ -5.96046447753906250000000000000000000000000000000000e-08
    1.00000000000000000000000000000000000000000000000000e+00]]

(EDIT: for the record, performing the same computation with double precision (C and Cinv defaulting to .astype('float64') yields worse results:
[[  9.99999999394382443895779033482540398836135864257812e-01
   -6.05617556104220966517459601163864135742187500000000e-10]
 [ -2.91967048315910915334825403988361358642578125000000e-08
    9.99999970803295168408908466517459601163864135742188e-01]]

)
That is, multiplying C by it's inverse yelds [[1,0],[0,1]] within float32  precision as expected, which on my machine numpy says to be:
In [13]: np.finfo('float32')
Out[13]: finfo(resolution=1e-06, min=-3.4028235e+38, max=3.4028235e+38, dtype=float32)

Switching to float64 yields:
In [14]: z1 = np.float64((1+np.sqrt(5))/2)

In [15]: z2 = np.float64((1-np.sqrt(5))/2)

In [16]: print "%.50f" % z1
1.61803398874989490252573887119069695472717285156250

In [17]: print "%.50f" % z2
-0.61803398874989490252573887119069695472717285156250

In [18]: print "%.50f" % (z1+z2)
1.00000000000000000000000000000000000000000000000000

In [19]: C = np.array([[1., 1.],
   ....:              [z1, z2]])

In [20]: print C
[[ 1.                                                   1.                                                 ]
 [ 1.6180339887498949025257388711906969547271728515625
  -0.6180339887498949025257388711906969547271728515625]]

In [21]: Cinv = np.array([[-z2/(z1-z2), 1/(z1-z2)],
   ....:                  [-z1/(z2-z1), 1/(z2-z1)]])

In [22]: print Cinv
[[ 0.27639320225002106390377321076812222599983215332031
   0.44721359549995792770360480972158256918191909790039]
 [ 0.72360679774997893609622678923187777400016784667969
  -0.44721359549995792770360480972158256918191909790039]]

In [23]: print np.dot(Cinv, C)
[[ 1.  0.]
 [ 0.  1.]]

How comes the result of the last dot product is exact?
I would have expected, as in the float32 case, to get some error, this time in the e-15 region, especially considering that there are divisions and multiplications involved.
In [24]: np.finfo('float64')
Out[24]: finfo(resolution=1e-15, min=-1.7976931348623157e+308, max=1.7976931348623157e+308, dtype=float64)

Moreover, without going again through the intermediate results, float128 yields again a quite good but still perturbated result:
In [38]: print np.dot(Cinv, C)
[[ 1.0 -2.710505431213761085018632002174854278564453125e-20]
 [-5.42101086242752217003726400434970855712890625e-20  1.0]]

In [28]: np.finfo('float128')
Out[28]: finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

So I guess my question is if there is some particular known optimization going on with float64 on 64 bits processors (i'm getting same results on intel i7 and an old amd64 X2), is it just a lucky case or I am missing something very very important?
I tried this on different python versions (some 2.7.x and 3.x) with the same results.
Post-post small update:
Interestingly enough, in C with doubles I get exact results as well:
#include<stdio.h>
#include <math.h>

int main()
{
    double z1 = (1+sqrt(5))/2;
    double z2 = (1-sqrt(5))/2;
    printf("z1 %5.50f\n", z1);
    printf("z2 %5.50f\n", z2);

    double C[2][2];
    C[0][0] = 1;
    C[0][1] = 1;
    C[1][0] = z1;
    C[1][1] = z2;

    double Cinv[2][2];
    Cinv[0][0] = -z2/(z1-z2);
    Cinv[0][1] = 1/(z1-z2);
    Cinv[1][0] = -z1/(z2-z1);
    Cinv[1][1] = 1/(z2-z1);

    double Cres[2][2];

    Cres[0][0] = Cinv[0][0]*C[0][0] + Cinv[0][1]*C[1][0];
    Cres[0][1] = Cinv[0][0]*C[0][1] + Cinv[0][1]*C[1][1];
    Cres[1][0] = Cinv[1][0]*C[0][0] + Cinv[1][1]*C[1][0];
    Cres[1][1] = Cinv[1][0]*C[0][1] + Cinv[1][1]*C[1][1];

    printf("Cres[0][0] %5.50f\n", Cres[0][0]);
    printf("Cres[0][1] %5.50f\n", Cres[0][1]);
    printf("Cres[1][0] %5.50f\n", Cres[1][0]);
    printf("Cres[1][1] %5.50f\n", Cres[1][1]);

    return 0;
}

yields:
z1 1.61803398874989490252573887119069695472717285156250
z2 -0.61803398874989490252573887119069695472717285156250
Cres[0][0] 1.00000000000000000000000000000000000000000000000000
Cres[0][1] 0.00000000000000000000000000000000000000000000000000
Cres[1][0] 0.00000000000000000000000000000000000000000000000000
Cres[1][1] 1.00000000000000000000000000000000000000000000000000

which is in total accordance with the python code. I think it can be safely concluded that this particular computation is just a lucky coincidence and we get exact results. In fact, using a different root for the zs (say sqrt(2)), yields perturbated results.
For the record, the same computation with all floats yields:
z1 1.61803400516510009765625000000000000000000000000000
z2 -0.61803400516510009765625000000000000000000000000000
Cres[0][0] 1.00000000000000000000000000000000000000000000000000
Cres[0][1] 0.00000000000000000000000000000000000000000000000000
Cres[1][0] -0.00000005960464477539062500000000000000000000000000
Cres[1][1] 1.00000000000000000000000000000000000000000000000000

again in total accordance with the corrected version of the python code float32 version.


text:
Q: Lambda nested stream Filter by Method with Exception I answered this question
This is the code:
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

The method!
private String[] getHostAddresses() {
  Set<String> HostAddresses = new HashSet<>();
  try {
    for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
      if (!ni.isLoopback() && ni.isUp() && ni.getHardwareAddress() != null) {
        for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
          if (ia.getBroadcast() != null) {  //If limited to IPV4
            HostAddresses.add(ia.getAddress().getHostAddress());
          }
        }
      }
    }
  } catch (SocketException e) { }
  return HostAddresses.toArray(new String[0]);
}

Now I want to translate using Lamba Stream Java 8 based on.
Here my code:
try {

  Collections.list(NetworkInterface.getNetworkInterfaces())
      .stream()
      .filter(ni -> !ni.isLoopback())  //unreported exception SocketException; must be caught or declared to be thrown
      .filter(ni -> ni.isUp())  //unreported exception SocketException; must be caught or declared to be thrown
      .filter(ni -> ni.getHardwareAddress() != null)  //unreported exception SocketException; must be caught or declared to be thrown
      .flatMap(ni -> ni.getInterfaceAddresses().stream())
      .filter(ia -> ia.getBroadcast() != null)
      .forEach(ia -> HostAddresses.add(ia.getAddress().getHostAddress()));

} catch (SocketException e) {
  System.out.println(e.getMessage());
}

But When I change to use Try catch...
    try {
      Collections.list(NetworkInterface.getNetworkInterfaces())
          .stream()
          .filter(ni -> {  //incompatible types: bad return type in lambda expression missing return value
            try {
              !ni.isLoopback(); //not a statement cannot find symbol symbol:   method isLoopback() location: variable ni of type T where T is a type-variable: T extends Object declared in interface Stream
            } catch (SocketException ex) {  //exception SocketException is never thrown in body of corresponding try statement
              Logger.getLogger(JPanelServerClient.class.getName()).log(Level.SEVERE, null, ex);
            }
          })
          .filter(ni -> ni.isUp())
          .filter(ni -> ni.getHardwareAddress() != null)
          .flatMap(ni -> ni.getInterfaceAddresses().stream())
          .filter(ia -> ia.getBroadcast() != null)
          .forEach(ia -> HostAddresses.add(ia.getAddress().getHostAddress()));

    } catch (SocketException e) {
      System.out.println(e.getMessage());
    }

According to tip @Jacob-G this solve the problem (But he has reason with "Not everything has to be functional")
try {
  Collections.list(NetworkInterface.getNetworkInterfaces())
  .stream()
  .filter(ni -> {
    try {
      return !ni.isLoopback();
    } catch (SocketException ex) {
      System.out.println(ex.getMessage());
      return false;
    }
  })
  .filter(ni -> {
    try {
      return ni.isUp();
    } catch (SocketException ex) {
      System.out.println(ex.getMessage());
      return false;
    }
  })
  .filter(ni -> {
    try {
      return ni.getHardwareAddress() != null;
    } catch (SocketException ex) {
      System.out.println(ex.getMessage());
      return false;
    }
  })
  .flatMap(ni -> ni.getInterfaceAddresses().stream())
  .filter(ia -> ia.getBroadcast() != null)
  .forEach(ia -> HostAddresses.add(ia.getAddress().getHostAddress()));
} catch (SocketException e) {
  System.out.println(e.getMessage());
}

How I can translate it (simpler)?
How I can translate it?

A: Unfortunately dealing with checked exceptions in java streams is ugly.
You have to create a separate function which takes the predicate(filter operation) catch any checked exception, rethrow it as runtime exception
For the lack of my imagination, consider the following two functions which you have no control of(think part of a library or jdk):
boolean isEven(int i) throws IOException {
    return i % 2 == 0;
}

boolean isOdd(int i) throws IOException {
    return i % 2 == 1;
}

Stream.of(1, 2, 3, 4, 5)
        .filter(i -> isEven(i))// compilation error
        .filter(i -> isOdd(i))// compilation error
        .collect(Collectors.toList());

Approach 1: Write a wrapper method for each of two functions and handle the exceptions there:
boolean isEvenWrapper(int i){
  try{
    return isEven(i);
   } catch (IOException ex){
     throw new UnCheckedIOException(ex);
}

And then your stream looks like:
Stream.of(1, 2, 3, 4, 5)
        .filter(i -> isEvenWrapper(i))
        .filter(i -> isOddWrapper(i))          //compiles and runs.
        .collect(Collectors.toList());

Approach 2: Approach 1 is easy if we have 1 or 2 filter functions, but if we have more filter functions, writing a wrapper function for each throwable method becomes tedious.
We need to create a Functional Interface for a predicate which throws exception.
@FunctionalInterface
public interface CheckedPredicate<T> {
    boolean test(T t) throws Throwable;
}

And another Predicate or method which takes this CheckedPredicate and safely evaluates it.
public static <T> Predicate<T> uncheckedPredicate(CheckedPredicate<T> predicate) {
    return t -> {
        try {
            return predicate.test(t);
        } catch (Throwable x) {
            throw new RuntimeException(x);
        }
    };
}

And now our stream becomes,
Stream.of(1, 2, 3, 4, 5)
        .filter(uncheckedPredicate(i -> isEven(i)))
        .filter(uncheckedPredicate(i -> isOdd(i)))  //compiles and runs.
        .collect(Collectors.toList());

The approach 2 functionality which I have described, is provided by JOOL
and specifically by this class Unchecked


text:
Q: Camera2 API Out of Bound exception on Pie I am using an sdk to process image which is using camer2 api, but it is not working on android Pie (28) devices and working on earlier version correctly. It s automatically closing camera and sometimes throwing out of bound exception on below marked line in the code:
 class CWorker
  {
    /**
     * Set the current capture to evaluate.
     * @param argImage The capture to evaluate.
     */
    void setCurrentCapture ( final Image argImage )
    {
      // copy the image planes to the byte array then the array to the YUV allocation
      final ByteBuffer objImageBufferY = argImage.getPlanes ()[ 0 ].getBuffer ();
      final ByteBuffer objImageBufferU = argImage.getPlanes ()[ 1 ].getBuffer ();
      final ByteBuffer objImageBufferV = argImage.getPlanes ()[ 2 ].getBuffer ();
      final int iBufferYSize = objImageBufferY.remaining ();
      final int iBufferUSize = objImageBufferU.remaining ();
      final int iBufferVSize = objImageBufferV.remaining ();
      objImageBufferY.get ( m_xbYuvBuffer, 0, iBufferYSize );
      objImageBufferV.get ( m_xbYuvBuffer, iBufferYSize, iBufferVSize );
     ****objImageBufferU.get ( m_xbYuvBuffer, iBufferYSize + iBufferVSize, iBufferUSize );****
      m_objRenderscriptMemYuv.copy1DRangeFromUnchecked ( 0, iBufferYSize + iBufferVSize + iBufferUSize, m_xbYuvBuffer );
    }
}

I have no idea why it is not working on android Pie (28) devices.
Here is the manifest file code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xxx.xxx.xxx">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera2" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera2.autofocus" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:networkSecurityConfig="@xml/network_security_config"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.xxx.xxx.xxx.activities.DashboardActivity"
            android:label=""
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar" />
      <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xxx.xxx.xxx.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider" />
        </provider>
    </application>

</manifest>

A: change minimum sdk 15 target sdk to 29 compile sdk to 29


text:
Q: Convergence of $\sum_{n=1}^{\infty}{(1-2c^2)^n \over n \ln{n} + \cos{n\pi}}$ Let
$$\sum_{n=1}^{\infty}{(1-2c^2)^n \over n \ln{n} + \cos{n\pi}}$$
$c \in \mathbb{R}$. For what values of $c$ is this series:
1) convergent?
2) absolutely convergent?
Do you have any suggestions?

A: Hint: concentrate on the numerator. Do a case division $|c|>,=,<\sqrt{2}/2$. The denominator is pretty much irrelevant

A: Considering:
$$ n\log{n}+\cos{n\pi} = n\log{n}+(-1)^n \approx n\log{n} \quad\{\text{for}\,n\rightarrow\infty\} \quad\qquad\qquad\qquad\qquad\qquad $$
Let:
$$\color{red}{A=1-2c^2} \quad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad $$
Thus:
$$
\sum_{n=\color{red}{2}}^{\infty}\frac{A^n}{n\log{n}} = \begin{cases}
-\infty\lt \,A\, \lt-1 &\Rightarrow \sum\frac{(-1)^n|A|^n}{n\log{n}} \space\space\space\quad\rightarrow\quad \text{Diverge by Limit test} \\[2mm]
-1\,\,\lt \,A\, \lt0 &\Rightarrow \sum\frac{(-1)^n}{(1/|A|)^n n\log{n}} \space\rightarrow\quad \text{Converge by Ratio test} \\[2mm]
\,\,\,0\,\,\,\lt \,A\, \lt+1 &\Rightarrow \sum\frac{1}{(1/|A|)^n n\log{n}} \space\rightarrow\quad \text{Converge by Ratio test} \\[2mm]
+1\,\,\lt \,A\, \lt+\infty &\Rightarrow \sum\frac{|A|^n}{n\log{n}} \space\space\space\qquad\rightarrow\quad \text{Diverge by Limit test} \\[2mm]
\end{cases}
$$
Also:
$$
\sum_{n=\color{red}{2}}^{\infty}\frac{A^n}{n\log{n}} = \begin{cases}
A=-1 &\implies \sum\frac{(-1)^n}{n\log{n}} \quad\rightarrow\quad \text{Converge by Dirichlet test} \\[2mm]
A=0 &\implies \sum\frac{(0)^n}{n\log{n}} = 0 \qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad \\[2mm]
A=+1 &\implies \sum\frac{1}{n\log{n}} \quad\rightarrow\quad \text{Diverge by Comparison test} \\[2mm]
\end{cases}
$$
Hence:
$$
\sum_{n=1}^{\infty}\frac{\left(1-2c^2\right)^n}{n\log{n}+\cos{n\pi}} = \begin{cases}
\text{Convergent for} &A\in\,\color{blue}{[}-1,\,+1\color{red}{[} \quad\rightarrow\quad c\in\,\color{blue}{[}-1,\,+1\color{blue}{]}-\color{red}{\{0\}} \\[2mm]
\text{|Convergent| for} &A\in\,\color{blue}{]}-1,\,+1\color{red}{[} \quad\rightarrow\quad c\in\,\color{blue}{]}-1,\,+1\color{blue}{[}-\color{red}{\{0\}} \\[2mm]
\end{cases}
$$


text:
Q: matplotlib for c++ gives this error: 'PyObject_CallObject': function does not take 3 arguments I have microsoft visual studio 2019 and installed matplotlib for it using nuget but when I want to build this code:
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
int main() {
    plt::plot({ 1,3,2,4 });
    plt::show();
}

it gives this error: 'PyObject_CallObject': function does not take 3 arguments
this is the build output:
1>------ Build started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1>ConsoleApplication3.cpp
1>C:\Users\matthijs\source\repos\ConsoleApplication3\packages\matplotlib-cpp.1.1.0.92\include\matplotlibcpp\imshow.h(58,21): error C2660: 'PyObject_CallObject': function does not take 3 arguments
1>C:\Users\matthijs\source\repos\ConsoleApplication3\packages\matplotlib-cpp.1.1.0.92\sandbox\include\abstract.h(363,29): message : see declaration of 'PyObject_CallObject'
1>C:\Users\matthijs\source\repos\ConsoleApplication3\packages\matplotlib-cpp.1.1.0.92\include\matplotlibcpp\imshow.h(58,40): message : 'PyObject_CallObject': function declaration must be available as none of the arguments depend on a template parameter
1>Done building project "ConsoleApplication3.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

and the full error:

Severity    Code    Description Project File    Line    Suppression State   Suppression State
Error   C2660   'PyObject_CallObject': function does not take 3 arguments   ConsoleApplication3 C:\Users\matthijs\source\repos\ConsoleApplication3\packages\matplotlib-cpp.1.1.0.92\include\matplotlibcpp\imshow.h  58

how to fix this?
I used nuget to install the lasted version of matplotlib
the error happens here:
PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_imshow, plot_args, kwargs);
I have a windows 10 laptop and I use python 3.7

A: As the error says, "PyObject_CallObject" does not take 3 args.
Looking at some docs I found on a quick google , it looks like your args (plot_args, kwargs) need to be in a tuple - they need to all be within one arg to PyObject_CallObject.


text:
Q: Formatting data for clogit model I have a survey with 53 respondents answering 8 questions each.
Currently it's in an Excel document in the format:
Person # | Q1 | Q2 | Q3 | Q4 | Q5 | Q6 | Q7 | Q8
Each question had three possible responses, "1", "2", or "3". For a given person, each question has a single number indicating the response.
I need to transform the answers from each person into one long column vector with responses coded in binary for each of the three choices. So for each person, there should be 24 rows (3 for each question), and for each question, there should be one row with a 1 (indicating the choice that was made) and two rows with 0's.
I've tried doing this in Excel and in R and cannot figure out how to do it without manually entering each value.
Please tell me there's a better way?

A: See explanation of code as inline comments
Sub Demo()
    Dim wsSource  As Worksheet
    Dim wsDest As Worksheet
    Dim rSource As Range
    Dim rDest As Range
    Dim vSource As Variant

    Dim i As Long, j As Long

    '--> adjust to suit your needs
    ' set up source and destination references
    Set wsSource = Worksheets("SourceData")
    Set wsDest = Worksheets("DestData")

    '--> adjust to suit your needs
    ' Assumes source data has header in row 1, names in column A and responces in B..I
    With wsSource
        Set rSource = .Range(.Cells(2, 9), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    '--> adjust to suit your needs
    ' Assumes generated data starts as cell A1
    Set rDest = wsDest.Cells(1, 1)

    ' Get Source data
    vSource = rSource.Value

    ' Size Destination data array
    ReDim vDest(1 To UBound(vSource, 1) * 24, 1 To 2)

    ' Generate reformated data
    For i = 1 To UBound(vSource, 1) ' For each Person
        For j = 1 To 24 ' Add person name
            vDest((i - 1) * 24 + j, 1) = vSource(i, 1)
        Next
        For j = 1 To 8 ' Code 8 results
            vDest((i - 1) * 24 + (j - 1) * 3 + 1, 2) = IIf(vSource(i, j + 1) = 1, 1, 0)
            vDest((i - 1) * 24 + (j - 1) * 3 + 2, 2) = IIf(vSource(i, j + 1) = 2, 1, 0)
            vDest((i - 1) * 24 + (j - 1) * 3 + 3, 2) = IIf(vSource(i, j + 1) = 3, 1, 0)
        Next
    Next

    ' Place result on sheet
    rDest.Resize(UBound(vDest, 1), UBound(vDest, 2)) = vDest

End Sub


text:
Q: Charting with WPF VS 2010 (.NET 4) I need to add chart to my WPF application and I can't understand do I need to install the WPF toolkit if i work with .net 4?
On one hand I read everywhere that the toolkit is already integrated in .net 4, on the other hand I can't find system.windows.controls.datavisualization.toolkit where I'm trying to add it as a reference
please help

A: There are a number of controls that haven't been integrated (and might never).
There are also a number of controls that ought to have been there several releases ago.  Numeric up/down is on the top of that list for me.


text:
Q: I want the Collection view to show 2 Columns per Row, how do I do that? [with Swift 5 answers please]     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! SkrapCollectionViewCell

        cell.myLabel.text = self.items[indexPath.item]

        return cell
    }

This is my collection view code where I need to place the code to edit the number of columns it
is 6 now.

A: You need not check the device size because we can use the collectionView width to calculate the width of the cell. Using the cell width you can calculate the height as per your need.
One more thing: You need to use UICollectionViewDelegateFlowLayout & confirm the delegate & implement method below
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let padding: CGFloat =  25
    let collectionViewSize = collectionView.frame.size.width - padding
    return CGSize(width: collectionViewSize/2, height: 115)
}


text:
Q: Sass migration (to libsass 3.0) generate massive selectors On my project, I am currently using grunt-sass 0.14.1. Everything seems ok.
When I tried to migrate to more recent version of grunt-sass, the 0.16.1 (embedding the libsass 3.0 release) my compiled css result in having massive (useless) selectors.
I saw on the release that the @extend may have change. I suppose it could came from that...
But I can't manage to understand where useless selectors come from.
Do you have any tracks to find out where the problem is.
He is a cssmetrics of the same files compile with each version of grunt-sass:
0.14.1

*

*Total rules: 8355

*Total selectors: 21679

*Average selectors per rule: 2.6

*File size: 1.60 MB

*GZip size: 202.15 KB

0.15.0 Same as 0.14.1
0.16.1

*

*Total rules: 8373

*Total selectors: 31118

*Average selectors per rule: 3.7

*File size: 2.36 MB

*GZip size: 256.77 KB

Thank you.
PS: my scss code base is pretty big, so I don't know if pieces of scss code would be usefull.


text:
Q: Renaming a file using file.move, but adding a string for every new text Beginner coder here.
I need to add the GetLastWriteTime string to my filename using the (rename) file.move method. How do I add a string using file.move?
I've looked up some similar info, and I've gotten part of the answer I need. System.IO.File.Move("oldfilename", "newfilename"); is the code I'll need help with. I tried adding a string to the newfilename, but it only supports directory.
string[] files = Directory.GetFiles("C:/foto's", "*", SearchOption.TopDirectoryOnly);

string filename = Path.GetFileName(photo);

DateTime fileCreatedDate = System.IO.File.GetLastWriteTime(filename);

System.IO.File.Move(@"C:\foto's", @"C:\foto's" + fileCreatedDate);

Expected error, string cannot be accepted in a directory place.

A: I've always preferred to use FileInfo objects for stuff like this as they have the dates built in, have MoveTo rather than using the static File.Move etc ...
  FileInfo[] fis = new DirectoryInfo(@"C:\foto's").GetFiles("*", SearchOption.TopDirectoryOnly);

  foreach(FileInfo fi in fis){

    //format a string representing the last write time, that is safe for filenames
    string datePart = fi.LastWriteTimeUtc.ToString("_yyyy-MM-dd HH;mm;ss"); //use ; for time because : is not allowed in path

    //break the name into parts based on the .
    string[] nameParts = fi.Name.Split('.');

    //add the date to the last-but-one part of the name
    if(nameParts.Length == 1) //there is no extension on the file
      nameParts[0] += datePart;
    else
      nameParts[nameParts.Length-1] += datePart;

    //join the name back together
    string newName = string.Join(".", nameParts);

    //move the file to the same directory but with a new name. Use Path.Combine to join directory and new file name into a full path
    fi.MoveTo(Path.Combine(fi.DirectoryName, newName));

  }

  Directory.Move(@"c:\foto's", @"c:\photos"); //fix two typos in your directory name ;)


text:
Q: Dynamic array of template objects in C++ #include <vector>

using namespace std;

int main()
{
    vector<int> *list = new vector<int>[33];
    delete[] list;
    return 0;
}

Any reason why the delete SIGSEGVs?

A: It doesn't matter if the type is a template or not.  The compiler will expand the code to a normal type.  Deleting an array created with new[] you always use delete[].
The code you pasted is a little unusual but technically valid.


text:
Q: Spring boot common logging I'm very new to the spring boot..
I understood that Spring Boot uses Commons Logging for all internal logging.
logging.level.root=warn
logging.level.org.springframework.web=debug
logging.level.org.hibernate=error

after adding this into application.properties file, application logs all the output and exceptions in the console..
so I have a requirement to print the logs only when the system throws the error not for the success response..

A:
so I have a requirement to print the logs only when the system throws the error not for the success response..

The implementation of this requirement IMO heavily depends on your system
From the word "response" I understand that you're working with some kind of controller (like in spring mvc). But the controller method is only an entry point to your backend.
What if the controller calls the service that logs something (message logA), then (after logging) it calls another service that again logs something (message logB) and then in turn calls, dao to call the datatbase?
If, say, DB threw an error, the logA and logB messages are already logged and you can't "take that back".
So, in general, you can log that there was an error by explicitly catching the exception in controller and logging the error, or using Controller advice to intercept and log the exceptions "globally".
When you reach the point where you log the message you can log it with severity, say, ERROR and the logging framework will log it as long as its configured to log messages of that level from that logger.


text:
Q: SharePoint 2010 approval task locked When I am running the workflow, sometimes I get this error for particular item:

'This task is currently locked by a running workflow and cannot be edited'.

How can we solve the above error?
Please share the solution.

A: It may be the nature of your WF. Are you doing update to that task in wf? if so you need put a wait action after it. Sometimes WF is faster than sharepoint due to async calls and hits race condition. Put a 5 min wait after update of the task and see if that solves your problem.

A: When a workflow processes a task normally, the following sequence of events is expected to occur:

*

*The process begins.

*The workflow places a 'lock' on the task so nothing else can change the values while the workflow is processing.

*The workflow processes the task.

*The lock is released when the task processing is finished.

When the message is encountered, it usually indicates that an error occurred between step 2 and 4. As a result, the lock is never released.
Try to stop workflow and start new workflow for the item


text:
Q: I cannot publish a simple JAX-RS service using TomEE and Eclipse (IllegalArgumentException) The problem seems to be some poor error message.
I've created a dynamic web app project in eclipse and the runtime is TomEE+ 1.7.2
So this is the publisher
package study;

import java.io.IOException;
import java.net.InetSocketAddress;
import javax.ws.rs.ext.RuntimeDelegate;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class StandaloneJaxRsServer {

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(
                "localhost", 8765), 8);
        HttpHandler requestHandler = RuntimeDelegate.getInstance()
                .createEndpoint(new JaxRSApplication(), HttpHandler.class); //<<<<< line 15
        server.createContext("/jaxrs/", requestHandler);
        server.start();
    }
}

this is the app
package study;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath(value="/jaxrs")
public class JaxRSApplication extends Application{

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> set = new HashSet<>();
        set.add(NotSingletonResource.class);
        return set ;
    }
//
//  @Override
//  public Set<Object> getSingletons() {
//      Set<Object> set = new HashSet<>();
//      set.add(new SingletonResource());
//      return set ;
//  }

}

and this is the resource
package study;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/notSingletonResource")
public class NotSingletonResource {

    private volatile int counter = 0;

    @GET
    @Produces({MediaType.TEXT_HTML})
    public String getHello() {
        return "Not singleton resource " + counter++;
    }

}

when I try to run StandaloneJaxRsServer.main() I get
Exception in thread "main" java.lang.IllegalArgumentException
    at org.apache.cxf.jaxrs.impl.RuntimeDelegateImpl.createEndpoint(RuntimeDelegateImpl.java:104)
    at study.StandaloneJaxRsServer.main(StandaloneJaxRsServer.java:15)

However, IllegalArgumentException does not tell much. What am I doing wrong?

A: The javadoc for the RuntimeDelegate interface states "Throws: IllegalArgumentException - if application is null or the requested endpoint type is not supported.'  For a JAX-RS Application, I think you're supposed to use org.apache.cxf.jaxrs.JAXRSServerFactoryBean, and use the result of creating the endpoint to set up a server.

A: I won't accept my own answer, I just want to keep here some useful information just in case someone needs it.
TomEE+ does not have the libraries to make this work. Instead, what I've did was to remove all the TomEE+ dependencies from my eclipse project, then I've converted it to a maven project just to include this dependency according to @lmiguelmh answer to this question:
Latest Jersey example does not work
Then I've just added these jersey libraries

I'll wait a little bit more before accepting an answer here, because I really would like a better answer. I am following the steps described in the book "Java Web Services, Up and Running", so I think people will really need to know this information.


text:
Q: In an instance of a class, can you use a value returned from a one method, as a parameter for calling another method class A:
   def __init__(self, matrix=[]):
       self.matrix = matrix

   def dimension(self):
       return len(self.matrix), len(self.matrix[0])

   def reduce_matrix(self, i, j):
       temp = self.matrix[:i-1] + self.matrix[i:]
       M = A([row[:j-1] + row[j:] for row in temp])
       return M

   def determinant(self):
       (nrows, ncols) = self.dimension()
       if nrows != ncols:
           return ("Cannot find determinant of non-square matrix.")
       elif nrows == 1:
           return self.matrix[0][0]
       else:
           M = A(sum([ ((-1)**j) * self.matrix[0][j] * self.reduce_matrix(1,
                   j+1).determinant() for j in range(ncols) ]))
           return M

Hello, I just started OOP so I have a question regarding using the returned value of a method in place of the "instance name" that is passed as "self" for some other method.
I included the rest of the code that just makes the calculations for a matrix problem, but I'm only focusing on the "self.reduce_matrix(1, j+1)).determinant()" bit of it. I need to take a matrix (which is a list of lists ex. [[1,2,3],[4,5,6]] ), and perform the "reduce_matrix" method 1 time per column in the matrix, and each time, the "determinant(self)" method passes in the value returned from the other method. When I run it, it says that "list object has no attribute "determinant"" because I can't pass in "self" to the determinant method like I usually do --> "self.determinant(self)"
Any suggestions will be very appreciated

A: In reduce_matrix:

*

*create M as M = A([row[:j-1] + row[j:] for row in temp])

*do not return M.matrix but M itself.

That said, numpy is there for all kind of matrix operations and more.


text:
Q: apply templates to immediate self node I've an XML of below format.
 <book:para>
                <book:page num="228"/>
                <book:page num="229"/>
Other data
 </book:para>

Here I want to apply-templates to immediate page nodes before the text. I'm currently using the below XSLT for doing this task. This matches only one direct page before text.
<xsl:apply-templates select="./node()[1][self::book:page]" mode="first"/>

Please let me know how can I do it for more than one page.
Thanks


text:
Q: Ladder Operators I want to show that the following formula for the ground state $\psi_0$ of the harmonic oscillator is valid:$$<\psi_0,\hat x^{2n}\psi_0>=\frac{(2n)!}{2^{2n}n!}(\frac{h}{m \omega})^n$$Ok
I want to use ladder operators to do this: $$\hat a_+={\frac{1}{\sqrt{2hm\omega}}}(-i\hat p+m\omega\hat x)$$ "raising operator"$$\hat a_-={\frac{1}{\sqrt{2hm\omega}}}(i\hat p+m\omega\hat x)$$  "lowering operator" I used this to express the operator $\hat x$ as follows:$$\hat x=\frac{\sqrt{2hm\omega}}{2m\omega}(\hat a_++\hat a_-)$$Then I tried to use induction over n to prove the formula, however I can´t show the step n-->n+1Can someone help me with this please? (If you want see more details of my attempt just ask.)

A: Induction won't work very well for this problem.
A better way is to start with a variant of the Baker-Campbell-Hausdorff formula, a.k.a the Zassenhaus formula:
$$
e^{\lambda({\hat A}+{\hat B})} = e^{\lambda {\hat A}}e^{\lambda {\hat B}}e^{-\frac{\lambda^2}{2}[ {\hat A}, {\hat B}]}\cdot \dots
$$
Factors not shown become $\hat I$ when $[ {\hat A}, {\hat B}] \sim {\hat I}$ and will not be needed in the following. For the present case take
$$
\lambda({\hat A}+{\hat B}) = {\hat x} \equiv \sqrt{\frac{h}{2m\omega}}\left( {\hat a}^\dagger + {\hat a}\right)
$$
with $[{\hat a}, {\hat a}^\dagger] = {\hat I}$. This gives immediately
$$
e^{\lambda\left( {\hat a}^\dagger + {\hat a}\right)} = e^{\lambda {\hat a}^\dagger}e^{\lambda {\hat a}}e^{\frac{\lambda^2}{2}}
$$
The idea is now to take the ground state matrix element on both sides, calculate the tractable right hand side, then expand on $\lambda$ and identify coefficients of corresponding powers. So, we have successively,
$$
\langle 0 | e^{\lambda\left( {\hat a}^\dagger + {\hat a}\right)} | 0 \rangle = \langle 0 | e^{\lambda {\hat a}^\dagger}e^{\lambda {\hat a}} | 0 \rangle e^{\frac{\lambda^2}{2}} = e^{\frac{\lambda^2}{2}}
\\
\Rightarrow\;\; \; \langle 0 |\left( {\hat a}^\dagger + {\hat a}\right)^{2n+1}|0\rangle = 0
\\
\Rightarrow \;\;\; \langle 0 |\left( {\hat a}^\dagger + {\hat a}\right)^{2n}|0\rangle = \frac{(2n)!}{2^n n!}
\\
\langle 0 |{\hat x}^{2n}|0\rangle \equiv \langle 0 |\left[ \sqrt{\frac{h}{2m\omega}}\left( {\hat a}^\dagger + {\hat a}\right)\right]^{2n}|0\rangle =  \frac{(2n)!}{2^{2n} n!}\left( \frac{h}{m\omega} \right)^n
$$


text:
Q: AWS SDK CPP and EBS fecthing Based on my research, I found out that AWS SDK CPP allows upload/download  files to bucket.
I need to have same upload/download access on an AWS EBS
 volume of types st1, but I could not find any example or tutorials about it. Is there some way to do that ? I search in the very large documentation without success.

A: EBS volumes can only be accessed via EC2 instances. Unlike S3, for example, it's not a standalone service offering by AWS.


text:
Q: add hyperlinks to table entries I have an html table and I want to hyperlink the entries in one column.
fiddle example here: http://jsfiddle.net/hohenheim/uF4H7/5/ - note once you click on any bar in the graph, there will be an onclick event to show the table.
On the table I want to be able link from clicking on any adId. ie once an adId is clicked it should go to 'www.url.com/adId#. Can this be done in html/js? I've tried creating the link and appending it but haven't had much success. Do I need to refactor how I append entries to the table? Or is it possible rather to create an on-click event on the table?
here is the code on how the table is generated:
function appendAds(date1) {
    nonUTCdate = new Date(date1);
    UTCdate = new Date(nonUTCdate.getUTCFullYear(), nonUTCdate.getUTCMonth(), nonUTCdate.getUTCDate());
    $('#tableTitle').html("Info for " + timeConverter(UTCdate) + ":");
    $("#table").find("tr:gt(0)").remove();
    $("#table tr").show();
    for (var i = 0; i < preGroupData.length; i++) {
        if ((date1 >= preGroupData[i].startDate) && (date1 <= preGroupData[i].endDate)) {;
        $('#table').append('
' + timeConverter(preGroupData[i].startDate) + '	' + timeConverter(preGroupData[i].endDate) + '	' + preGroupData[i].adId + '	' + preGroupData[i].impressions + '
');
       }
   }
}

A: If I'm understanding you correctly, you can simply turn the column with preGroupData[i].adId into a link to 'www.url.com/#adId' by adding the anchor text to the html string you are inserting into the html.
replace
' + preGroupData[i].adId + '

in your string with:
"
              + preGroupData[i].adId + "	"

A: the click handler:
$('tr td:nth-child(3)').click(function(){
   window.location.href = $(this).text()
}

As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

like if you click on a link (it will be saved in the session history, so back button will work as expected)
window.location.href = "http://www.google.com";

A: If you save the cell to a variable, you can easily add an "on click" event, like this:
function appendAds(date1) {
    nonUTCdate = new Date(date1);
    UTCdate = new Date(nonUTCdate.getUTCFullYear(), nonUTCdate.getUTCMonth(),     nonUTCdate.getUTCDate());
    $('#tableTitle').html("Info for " + timeConverter(UTCdate) + ":");
    $("#table").find("tr:gt(0)").remove();
    $("#table tr").show();
    for (var i = 0; i < preGroupData.length; i++) {
        if ((date1 >= preGroupData[i].startDate) && (date1 <= preGroupData[i].endDate)) {;
        var row = $("
")
            .append("" + timeConverter(preGroupData[i].startDate) + "	")
            .append("" + timeConverter(preGroupData[i].endDate) + "	");
        var adIdCell = $("" + preGroupData[i].adId + "	").appendTo(row);

        row.append("" + preGroupData[i].impressions + "	");

            row.appendTo("#table");
            adIdCell.on("click", function() {
                location.href = "./#" + preGroupData[i].adId;
            });
       }
   }
}


text:
Q: Dynamic image/animation combining I'm working on a solution for my new project (in C#). I'm trying to make a dynamic image/animation combiner (maybe later even work with video's, but that's not required atm).
So basically my program is reading a xml file with all kinds of instructions the user needs to do. In the xml file it is possible that for 1 instruction multiple pictures are needed. So when there are 2 or 3 pictures (the maximum amount of pictures is 4) they need to be combined to 1 picture so I can show that on the image object on the main form. Also it is important that the pictures keep there proportions so the image doesn't look deformed.
I found a solution with GDI+ but it isn't that good as I wanted it and runs pretty slow on a bit older computers. Also combining animations with normal images is a real pain and goes very slow!
Is there a faster/easier way to do this? Maybe WPF is a solution but I got no experience with this.
Thnx for any help in advance!

A: This questsion is open now for mor then a year but I found the solution some time ago so I will post it here in case it is usefull for somebody else.
The best way to do this was creating to set up a grid dynamic. And then fill up each element of the grid with the needed media (Video, Image, animated gif's and even Viewport3D from another xaml file). Creating a grid in code is really easy so it should be a good solution for everybody who wants to do this in WPF.


text:
Q: Extending the result $\int_{0}^{\infty} \left( ( 1 - 2C(x))^{2} + (1-2S(x))^{2} \right) \, dx = \frac{4}{\pi} $ While generalizing this result, I succeeded in proving that for $\alpha > 0$, $\beta < 1$ and $1 < 2\alpha + \beta < 3$, we have
\begin{align*}
&\int_{0}^{\infty} \left[ \left( \int_{x}^{\infty} \frac{\cos t}{t^{\alpha}} \, dt \right)^{2} + \left( \int_{x}^{\infty} \frac{\sin t}{t^{\alpha}} \, dt \right)^{2} \right] \, \frac{dx}{x^{\beta}} \\
& \hspace{10em} = \frac{\pi}{1-\beta} \frac{\Gamma(2-\alpha-\beta)}{\Gamma(\alpha)} \csc \left( \pi \alpha + \frac{\pi (\beta-1)}{2} \right).
\end{align*}
My question is

*

*Is this a known result?

*My ultimate goal is to examine whether the integral
$$ I(\alpha, \beta) := \int_{0}^{\infty} \left[ \left( \int_{x}^{\infty} \frac{\cos t}{t^{\alpha}} \, dt \right)^{2} + \left( \int_{x}^{\infty} \frac{\sin t}{t^{\alpha}} \, dt \right)^{2} \right]^{2} \, \frac{dx}{x^{\beta}} $$
has closed from or not for general $\alpha$ and $\beta$. I know that
$$ I \left(\tfrac{1}{2}, 0 \right) = 2\pi (\log 4 - 1) \qquad \text{and} \qquad I \left(1, 0 \right) = \frac{2\pi^{3}}{3}, \tag{1} $$
but I know nothing for the other cases. (Here, the former identity in $(1)$ corresponds to the motivating problem linked above.) Is there any other known result concerning this integral?

A further inspection showed that
\begin{align*}
\int_{0}^{\infty} \left( ( 1 - 2C(x))^{2} + (1-2S(x))^{2} \right)^{2} \, dx
&= \frac{16}{\pi} \left( 1 - \frac{2\sqrt{2}}{\pi} \log \left( 1 + \sqrt{2} \right) \right) \\
&\approx 1.0516193625061961290 \cdots,
\end{align*}
where
$$ C(x) = \int_{0}^{x} \cos \left( \tfrac{\pi t^2}{2} \right) \, dt \quad \text{and} \quad S(x) = \int_{0}^{x} \sin \left( \tfrac{\pi t^2}{2} \right) \, dt $$
are Fresnel integrals. Indeed, this corresponds to
$$ I \left( \tfrac{1}{2}, \tfrac{1}{2} \right) = \sqrt{\pi} \left( 4 \sqrt{2} \pi - 16 \log \left( 1 + \sqrt{2} \right) \right). $$
Note that major inverse symbolic calculators do not yield this result.

A: Pardon My Progress...
First, the sum of squared integrals inside the brackets, which for convenience we shall denote by $f{\left(x;\alpha\right)}$, may be rewritten as a single double integral with a little algebra and trigonometry:
$$\begin{align}
f{\left(x;\alpha\right)}
&:=\left(\int_{x}^{\infty}\frac{\cos{t}}{t^\alpha}\,\mathrm{d}t\right)^2+\left(\int_{x}^{\infty}\frac{\sin{t}}{t^\alpha}\,\mathrm{d}t\right)^2\\
&=\small{\left(\int_{x}^{\infty}\frac{\cos{t_1}}{t_1^\alpha}\,\mathrm{d}t_{1}\right)\cdot\left(\int_{x}^{\infty}\frac{\cos{t_2}}{t_2^\alpha}\,\mathrm{d}t_{2}\right)+\left(\int_{x}^{\infty}\frac{\sin{t_1}}{t_1^\alpha}\,\mathrm{d}t_{1}\right)\cdot\left(\int_{x}^{\infty}\frac{\sin{t_2}}{t_2^\alpha}\,\mathrm{d}t_{2}\right)}\\
&=\int_{x}^{\infty}\int_{x}^{\infty}\left(\frac{\cos{t_1}}{t_1^\alpha}\cdot\frac{\cos{t_2}}{t_2^\alpha}\right)\,\mathrm{d}t_{1}\mathrm{d}t_{2}+\int_{x}^{\infty}\int_{x}^{\infty}\left(\frac{\sin{t_1}}{t_1^\alpha}\cdot\frac{\sin{t_2}}{t_2^\alpha}\right)\,\mathrm{d}t_{1}\mathrm{d}t_{2}\\
&=\int_{x}^{\infty}\int_{x}^{\infty}\left(\frac{\cos{\left(t_1\right)}\cos{\left(t_2\right)}+\sin{\left(t_1\right)}\sin{\left(t_2\right)}}{\left(t_{1}t_{2}\right)^\alpha}\right)\,\mathrm{d}t_{1}\mathrm{d}t_{2}\\
&=\int_{x}^{\infty}\int_{x}^{\infty}\frac{\cos{\left(t_1-t_{2}\right)}}{\left(t_{1}t_{2}\right)^\alpha}\,\mathrm{d}t_{1}\mathrm{d}t_{2}.\\
\end{align}$$
Next, we apply a sequence of two two-variable transformations to put the integral into a more tractable form.  The first substitution is a simple scaling transformation, $(1)$$(t_{1},t_{2})=(xu_{1},xu_{2})$;  the second substitution is the more complicated transformation, $(2)$ $(u_{1}-u_{2},u_{1}u_{2})=(w_{1},w_{2})$:
$$\begin{align}
\mathcal{I}{\left(\alpha,\beta\right)}
&=\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta}}\,\left[\left(\int_{x}^{\infty}\frac{\cos{t}}{t^\alpha}\,\mathrm{d}t\right)^2+\left(\int_{x}^{\infty}\frac{\sin{t}}{t^\alpha}\,\mathrm{d}t\right)^2\right]^2\\
&=\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta}}\,\left[f{\left(x;\alpha\right)}\right]^2\\
&=\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta}}\,\left[\int_{x}^{\infty}\int_{x}^{\infty}\frac{\cos{\left(t_1-t_{2}\right)}}{\left(t_{1}t_{2}\right)^\alpha}\,\mathrm{d}t_{1}\mathrm{d}t_{2}\right]^2\\
&=\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta}}\,\left[\int_{1}^{\infty}\int_{1}^{\infty}\frac{\cos{\left[x\left(u_1-u_{2}\right)\right]}}{\left(x^2u_{1}u_{2}\right)^\alpha}\,x^2\,\mathrm{d}u_{1}\mathrm{d}u_{2}\right]^2\tag{1}\\
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{1}^{\infty}\int_{1}^{\infty}\frac{\cos{\left[x\left(u_1-u_{2}\right)\right]}}{\left(u_{1}u_{2}\right)^\alpha}\,\mathrm{d}u_{1}\mathrm{d}u_{2}\right]^2\\
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{1}^{\infty}\mathrm{d}w_{2}\int_{1-w_{2}}^{w_{2}-1}\mathrm{d}w_{1}\,\frac{w_{2}^{-\alpha}\cos{\left(x\,w_{1}\right)}}{\sqrt{w_{1}^2+4w_{2}}}\right]^2\tag{2}\\
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{-\infty}^{\infty}\mathrm{d}w_{1}\int_{1+|w_{1}|}^{\infty}\mathrm{d}w_{2}\,\frac{w_{2}^{-\alpha}\cos{\left(x\,w_{1}\right)}}{\sqrt{w_{1}^2+4w_{2}}}\right]^2\\
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[2\int_{0}^{\infty}\mathrm{d}w_{1}\int_{1+w_{1}}^{\infty}\mathrm{d}w_{2}\,\frac{w_{2}^{-\alpha}\cos{\left(x\,w_{1}\right)}}{\sqrt{w_{1}^2+4w_{2}}}\right]^2\\
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}\mathrm{d}w_{1}\int_{1+w_{1}}^{\infty}\mathrm{d}w_{2}\,\frac{w_{2}^{-\alpha}\cos{\left(x\,w_{1}\right)}}{\sqrt{\frac14w_{1}^2+w_{2}}}\right]^2\\
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}\mathrm{d}w_{1}\,\cos{\left(x\,w_{1}\right)}\int_{1+w_{1}}^{\infty}\,\frac{w_{2}^{-\alpha}\,\mathrm{d}w_{2}}{\sqrt{\frac14w_{1}^2+w_{2}}}\right]^2.\\
\end{align}$$
To perform the integration with respect to $w_{2}$, I appeal to Gradshteyn 3.197(2): under the conditions $|\arg{\frac{u}{\beta}}|<\pi\lor |\frac{\beta}{u}|<1$, and $0<\Re{\left(\mu\right)}<\Re{\left(\lambda-\nu\right)}$, we have the result,

$$\int_{u}^{\infty}x^{-\lambda}(x+\beta)^{\nu}(x-u)^{\mu-1}\,\mathrm{d}x=u^{-\lambda}(\beta+u)^{\mu+\nu}\operatorname{B}{\left(\lambda-\mu-\nu,\mu\right)}\times{_2F_1}{\left(\lambda,\mu;\lambda-\mu;-\frac{\beta}{u}\right)}.$$

Let $\mu=1$, $\nu=-\frac12$, $\lambda=\alpha$, $u=1+w_{1}$, and $\beta=\frac14w_{1}^2$. Then for $\frac12<\Re{\left(\alpha\right)}<1\land w_{1}>0$,
$$\begin{align}
\int_{1+w_{1}}^{\infty}\frac{w_{2}^{-\alpha}\,\mathrm{d}w_{2}}{\sqrt{\frac14w_{1}^2+w_{2}}}
&=\small{\left(w_{1}+1\right)^{-\alpha}\sqrt{\frac14w_{1}^2+w_{1}+1}\,\operatorname{B}{\left(\alpha-\frac12,1\right)}\,{_2F_1}{\left(\alpha,1;\alpha-1;-\frac{\frac14w_{1}^2}{1+w_{1}}\right)}}\\
&=\left(w_{1}+1\right)^{-\alpha}\left(\frac{w_{1}+2}{2}\right)\,\left(\frac{2}{2\alpha-1}\right)\,{_2F_1}{\left(\alpha,1;\alpha-1;-\frac{w_{1}^2}{4\left(1+w_{1}\right)}\right)}\\
&=\frac{\left(w_{1}+2\right)\left(w_{1}+1\right)^{-\alpha}}{2\alpha-1}\,{_2F_1}{\left(\alpha,1;\alpha-1;-\frac{w_{1}^2}{4\left(1+w_{1}\right)}\right)}.\\
\end{align}$$
The hypergeometric function above quite conveniently reduces to a rational function for the specified combination of parameters: for $\alpha\neq1$,
$${_2F_1}{\left(\alpha,1;\alpha-1;-z\right)}=\frac{\alpha\,z+\alpha-2z-1}{(\alpha-1)(z+1)^2},\\
\implies {_2F_1}{\left(\alpha,1;\alpha-1;-\frac{w_{1}^2}{4\left(1+w_{1}\right)}\right)}=\frac{4\left(w_{1}+1\right)\left[\alpha(w_{1}+2)^2-2(w_{1}+1)^2-2\right]}{(\alpha-1)(w_{1}+2)^4}.\\$$
Thus, for $\frac12<\Re{\left(\alpha\right)}<1\land w_{1}>0$,
$$\begin{align}
\int_{1+w_{1}}^{\infty}\frac{w_{2}^{-\alpha}\,\mathrm{d}w_{2}}{\sqrt{\frac14w_{1}^2+w_{2}}}
&=\frac{\left(w_{1}+2\right)\left(w_{1}+1\right)^{-\alpha}}{2\alpha-1}\,{_2F_1}{\left(\alpha,1;\alpha-1;-\frac{w_{1}^2}{4\left(1+w_{1}\right)}\right)}\\
&=\frac{4\left(w_{1}+1\right)^{1-\alpha}\left[\alpha(w_{1}+2)^2-2(w_{1}+1)^2-2\right]}{(2\alpha-1)(\alpha-1)(w_{1}+2)^3},\\
\end{align}$$
and hence:
$$\begin{align}
\mathcal{I}{\left(\alpha,\beta\right)}
&=\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}\mathrm{d}w_{1}\,\cos{\left(x\,w_{1}\right)}\int_{1+w_{1}}^{\infty}\,\frac{w_{2}^{-\alpha}\,\mathrm{d}w_{2}}{\sqrt{\frac14w_{1}^2+w_{2}}}\right]^2\\
&=\small{\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta-4\left(1-\alpha\right)}}\left[\int_{0}^{\infty}\frac{4\left(w_{1}+1\right)^{1-\alpha}\left[\alpha(w_{1}+2)^2-2(w_{1}+1)^2-2\right]\cos{\left(xw_{1}\right)}}{(2\alpha-1)(\alpha-1)(w_{1}+2)^3}\,\mathrm{d}w_{1}\right]^2}\\
&=\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta-4\left(1-\alpha\right)}}\left[\int_{0}^{\infty}\frac{4\left(y+1\right)^{1-\alpha}\left[\alpha(y+2)^2-2(y+1)^2-2\right]\cos{\left(xy\right)}}{(2\alpha-1)(\alpha-1)(y+2)^3}\,\mathrm{d}y\right]^2\\
&=\small{\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\frac{\mathrm{d}x}{x^{\beta-4\left(1-\alpha\right)}}\left[\int_{0}^{\infty}\frac{\left(y+1\right)^{1-\alpha}\left[\alpha(y+2)^2-2(y+1)^2-2\right]\cos{\left(xy\right)}}{(y+2)^3}\,\mathrm{d}y\right]^2},\\
&=:\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}g{\left(y;\alpha\right)}\,\cos{\left(xy\right)}\,\mathrm{d}y\right]^2,\\
\end{align}$$
where in the third line we've made the substitution $w_{1}=y$ for the sake of eliminating the dependency on subscripted variables, and where in the last line we've introduced the auxiliary function $g{\left(y;\alpha\right)}$ simply for the sake conveniently denoting the function,
$$\begin{align}
g{\left(y;\alpha\right)}
&:=\frac{\left(y+1\right)^{1-\alpha}\left[\alpha(y+2)^2-2(y+1)^2-2\right]}{(y+2)^3}\\
&=\frac{\alpha\left(y+1\right)^{1-\alpha}}{y+2}-\frac{2\left(y+1\right)^{3-\alpha}}{(y+2)^3}-\frac{2\left(y+1\right)^{1-\alpha}}{(y+2)^3}.\\
\end{align}$$
Now if we repeat our initial trick of rewriting the square of an integral as a double integral, we can arrive at an expression for $\mathcal{I}{\left(\alpha,\beta\right)}$ as an ordinary triple integral:
$$\begin{align}
\mathcal{I}{\left(\alpha,\beta\right)}
&=\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}g{\left(y;\alpha\right)}\,\cos{\left(xy\right)}\,\mathrm{d}y\right]^2\\
&=\small{\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}g{\left(y;\alpha\right)}\,\cos{\left(xy\right)}\,\mathrm{d}y\right]\cdot\left[\int_{0}^{\infty}g{\left(z;\alpha\right)}\,\cos{\left(xz\right)}\,\mathrm{d}z\right]}\\
&=\small{\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}x\,x^{4\left(1-\alpha\right)-\beta}\left[\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\,\cos{\left(xz\right)}\cos{\left(xy\right)}\right]}\\
&=\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}x\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\,\frac{g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\,\cos{\left(xz\right)}\cos{\left(xy\right)}}{x^{\beta-4\left(1-\alpha\right)}}.\\
\end{align}$$
Change the order of integration so that the integration over $x$ is first:
$$\begin{align}
\mathcal{I}{\left(\alpha,\beta\right)}
&=\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}x\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\frac{g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\,\cos{\left(xz\right)}\cos{\left(xy\right)}}{x^{\beta-4\left(1-\alpha\right)}}\\
&=\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\int_{0}^{\infty}\mathrm{d}x\frac{g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\,\cos{\left(xz\right)}\cos{\left(xy\right)}}{x^{\beta-4\left(1-\alpha\right)}}\\
&=\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\int_{0}^{\infty}\mathrm{d}x\frac{\cos{\left(xy\right)}\cos{\left(xz\right)}}{x^{\beta-4\left(1-\alpha\right)}}.\\
\end{align}$$
Then the inner integral with respect to $x$ may be evaluated in closed form with an appeal to another result from Gradshteyn. Proposition 3.762(3) of Gradshteyn states that, given $a,b\in\mathbb{R}$ and $\mu\in\mathbb{C}$ such that $a>0,~b>0$, and $0<\Re{(\mu)}<1$, then the following improper integral has the closed form:

$$\int_{0}^{\infty}x^{\mu-1}\cos{\left(ax\right)}\cos{\left(bx\right)}\,\mathrm{d}x=\frac12\cos{\left(\frac{\mu\pi}{2}\right)}\,\Gamma{\left(\mu\right)}\,\left[\left(a+b\right)^{-\mu}+|a-b|^{-\mu}\right].$$

Setting $(a,b,\mu)\mapsto(y,z,4(1-\alpha)-\beta+1)$ in the above proposition yields the following corrollary: given $y,z\in\mathbb{R}$ and $p\in\mathbb{C}$ such that $y>0,~z>0$, and $-1<\Re{\left(4(1-\alpha)-\beta\right)}<0$, then the following improper integral has the closed form,
$$\small{\int_{0}^{\infty}\frac{\cos{\left(xy\right)}\cos{\left(xz\right)}}{x^{\beta+4\alpha-4}}\mathrm{d}x=\frac12\sin{\left[\frac{\pi\left(4\alpha+\beta\right)}{2}\right]}\,\Gamma{\left(5-4\alpha-\beta\right)}\,\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right].}$$
Thus, we may reduce our integral representation of $\mathcal{I}{\left(\alpha,\beta\right)}$ to a single double integral:
$$\begin{align}
\mathcal{I}{\left(\alpha,\beta\right)}
&=\frac{16}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\int_{0}^{\infty}\mathrm{d}x\frac{\cos{\left(xy\right)}\cos{\left(xz\right)}}{x^{\beta-4\left(1-\alpha\right)}}\\
&=\small{\frac{8\sin{\left[\frac{\pi\left(4\alpha+\beta\right)}{2}\right]}\,\Gamma{\left(5-4\alpha-\beta\right)}}{(2\alpha-1)^2(\alpha-1)^2}\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]}\\
&=:\frac{8\sin{\left[\frac{\pi\left(4\alpha+\beta\right)}{2}\right]}\,\Gamma{\left(5-4\alpha-\beta\right)}}{(2\alpha-1)^2(\alpha-1)^2}\tilde{\mathcal{I}}{\left(\alpha,\beta\right)}.\\
\end{align}$$

Update:
Now we'll focus on reducing the previously defined function $\tilde{\mathcal{I}}{\left(\alpha,\beta\right)}$. First of all, by symmetry we can reduce the region of integration to one where the absolute value bars are no longer necessary inside the integrand, which will obviate some of tedium of evaluation:
$$\begin{align}
\tilde{\mathcal{I}}{\left(\alpha,\beta\right)}
&=\int_{0}^{\infty}\mathrm{d}y\int_{0}^{\infty}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&=\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&~~~~~ +\int_{0}^{\infty}\mathrm{d}y\int_{y}^{\infty}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&=\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&~~~~~ +\int_{0}^{\infty}\mathrm{d}z\int_{0}^{z}\mathrm{d}y\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&=\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&~~~~~ +\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(z;\alpha\right)}\,g{\left(y;\alpha\right)}\left[\left(z+y\right)^{\beta+4\alpha-5}+|z-y|^{\beta+4\alpha-5}\right]\\
&=\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&~~~~~ +\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&=2\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+|y-z|^{\beta+4\alpha-5}\right]\\
&=2\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+\left(y-z\right)^{\beta+4\alpha-5}\right].\\
\end{align}$$
Next, we rescale the interval of integration of the inner integral to the unit interval via the substitution $z=y\,\omega$:
$$\begin{align}
\tilde{\mathcal{I}}{\left(\alpha,\beta\right)}
&=2\int_{0}^{\infty}\mathrm{d}y\int_{0}^{y}\mathrm{d}z\,g{\left(y;\alpha\right)}\,g{\left(z;\alpha\right)}\left[\left(y+z\right)^{\beta+4\alpha-5}+\left(y-z\right)^{\beta+4\alpha-5}\right]\\
&=2\int_{0}^{\infty}\mathrm{d}y\int_{0}^{1}y\,\mathrm{d}\omega\,g{\left(y;\alpha\right)}\,g{\left(y\,\omega;\alpha\right)}\left[\left(y+y\,\omega\right)^{\beta+4\alpha-5}+\left(y-y\,\omega\right)^{\beta+4\alpha-5}\right]\\
&=2\int_{0}^{\infty}\mathrm{d}y\int_{0}^{1}y^{\beta+4\alpha-4}\,\mathrm{d}\omega\,g{\left(y;\alpha\right)}\,g{\left(y\,\omega;\alpha\right)}\left[\left(1+\omega\right)^{\beta+4\alpha-5}+\left(1-\omega\right)^{\beta+4\alpha-5}\right]\\
&=2\int_{0}^{\infty}\mathrm{d}y\,y^{\beta+4\alpha-4}\,g{\left(y;\alpha\right)}\int_{0}^{1}\mathrm{d}\omega\,g{\left(y\,\omega;\alpha\right)}\left[\left(1+\omega\right)^{\beta+4\alpha-5}+\left(1-\omega\right)^{\beta+4\alpha-5}\right].\\
\end{align}$$
At this stage, the inner integral over $\omega$ may be evaluated in terms of the Appell hypergeometric function, $F_{1}$.


text:
Q: How to Insert JSON into array's before last item? I want to build a function that will always insert JSON Items in an array at the last item before.
const array = [
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  // Insert Items Here
  { 'Index Value': 12 }
]

const insert = (arr, index, newItem) => [
    ...arr.slice(0, index),
    newItem,
    ...arr.slice(index)
]

var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];

// I have tried like this: array.slice(-1) to insert item one step before always

const result = insert(array,array.slice(-1),insertItems)

console.log(result);

OutPut:

[ [ { Japan: [Object] }, { Japan: [Object] } ],     //Not at Here
  { India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' } },
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 } ]

Expected Output:
[
  { India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' } },
  { USA: { Score: '15', PlayedMatched: '06' } },
  [ { Japan: [Object] }, { Japan: [Object] } ],      //At here
  { 'Index Value': 12 }
]

How should i do this? And I also want to remove the this: [] in my Output Results. :)
Like This:
 [
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Japan': { Score: "54", PlayedMatched: "56" } },
  { 'Russia': { Score: "99", PlayedMatched: "178" } },
  { 'Index Value': 12 }
]

A: Use the splice function like so:
const array = [
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 }
]

var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];

array.splice(array.length - 1, 0, ...insertItems)

console.log(array);

Notice that splice modify the same array you give it and doesn't create a modified copy of it.

A: Just pass the index number where you want to insert as index parameter in insert function to get the job done. In your case last second place so, you can pass array.length - 1
const array = [
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 }
]

const insert = (arr, index, newItem) => [
    ...arr.slice(0, index),
    ...newItem,
    ...arr.slice(index)
]

var insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];

const result = insert(array,array.length - 1,insertItems)

console.log(result);


text:
Q: Regex to split a string when there's nothing between two occurrences of the delimiter Suppose I want to split this string a^b^c^d^e^^^f^g^h^^^ , I simply do string.split("\\^") which returns me an array of length 10 i.e [a, b, c, d, e, , , f, g, h] . However I want an array of length 13 which takes occurrences of the delimiter after h into consideration.
I can do something like this to achieve what I want
    string = string.replace("^", "^ ");
    String[] split = string.split("\\^");

    for(String x : split){
        System.out.println(x.trim());
    }

but this seems like an overburden. Is there a regex to do this?

A: You can do this
String[] split = string.split("\\^", -1);

and it won't drop trailing separators.

If you really want to trim the last separator to get 12 values, you can do
String[] split = string.replaceAll("\\^$", "").split("\\^", -1);

or this will ensure you always have 12. It will either trim or expand the number of elements as required (adding null if expanding)
String[] split = Arrays.copyOf(string.split("\\^", -1), 12);


text:
Q: Twitter "View Summary" button I noticed on Hollywood Reporter that within their tweets they have a "view summary" button, which when clicked on, gives you a preview of a post on their site with a title, excerpt, and preview picture.

Any clue as to where some documentation is on how to accomplish this? Ive browsed the twitter API for a bit and had no success finding anything.

A: According to Twitter To Tweet More Interactive Content by Social Bakers
"We followed the Wall Street Journal on Twitter to see how it works. When the Tweet contains a link to an article on its website, you will see the View Summary option instead of Expand. The summary will provide you with the article´s preview, sometimes even Twitter accounts of the publishers and writers. And when you click anywhere on the preview, you will get navigated to the article on the website. The number of retweets and favorites will appear as before. You can continue to read the article, follow these accounts, reply, favorite or retweet the Tweet just as you are used to."
Apparently all you need is a link to your content. However, I'm sure there's more to this because it doesn't always seem to work.
** EDIT **
It's actually called a Twitter Card and here is the documentation for Twitter Cards


text:
Q: Convert date (PHP) I am using JDF library for converting databases dates in my panel. My programming language is php and i am using while loop for show data. database date type is datetime.For example : 2018-07-21 11:14:19.678896
<?php
Include_once "jdf.php";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $array = explode(' ', $row['date']);
    list($year, $month, $day) = explode('-', $array[0]);
    list($hour, $minute, $second) = explode(':', $array[1]);
    $timestamp = mktime($hour, $minute, $second, $month, $day, $year);
    date_default_timezone_set("Asia/Tehran");
    $converted_date = jdate("Y/m/d H:i:s", $timestamp);
    echo $row['full_name'] . ", reg date:" . $converted_date;
}

When i run code, Y/m/d become convert BUT for H:i:s just first row become convert. I really dont know why ...
Can you help me ?

A: It's probably simpler to use the inbuilt DateTime class to process your data:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $date = date_create_from_format('Y-m-d H:i:s.u', $row['date'], new DateTimeZone('UTC'));
    $date->setTimeZone(new DateTimeZone('Asia/Tehran'));
    $converted_date = jdate('Y/m/d H:i:s', (int)$date->format('U'));
    echo $row['full_name'] . ", reg date:" . $converted_date;
}

Output:
2018/07/21 15:44:19

Demo on 3v4l.org


text:
Q: Combine elements within list of lists python I have a list of the form
in_list = [[10, 15], [16,21], [22,25], [26,30], [35,40], [45,50],[51,55]]

And I need to combine consecutive lists that contain consecutive integers in the last and first position into lists. So
if in[1][0] = in[0][1] + 1:
    out[0] = [in[0][0],in[1][1]]

The output will be of the form of
out_list = [[10,30], [35, 40], [45,55]]

Right now, the code I have does multiple iterations on the out list and combines the elements, continuing till the number of elements in the list stops changing after an iteration. How can I achieve this in a more pythonic way?

A: This should do the trick
out = [inp[0]]
for l in inp[1:]:
    if l[0] == out[-1][1] + 1:
        out[-1][1] = l[1]
    else:
        out.append(l)

A: Did you mean one-line stuff using numpy? :)
Try the following shortcut:
import numpy as np

# data is of shape (n,2), n=6
data = np.array([[10, 15], [16,21], [22,25], [26,30], [35,40], [45,50],[51,55]])

# seek for consecutive numbers
marks = (data[:-1,1]+ 1) == data[1:,0]

# re-arrange and return to python lists
output = np.stack([data[:-1,0][marks],data[1:,1][marks]],axis=1).tolist()

EDIT:
Another option using lists:
data = [[10, 15], [16,21], [22,25], [26,30], [35,40], [45,50],[51,55]]

mylist = []

def func(x1,x2):
    if x1[1] +1 == x2[0]:
        mylist.append((x1[0],x2[1]))

list(map(func,data[:-1],data[1:]))
print(mylist)

Output:
[(10, 21), (16, 25), (22, 30), (45, 55)]


text:
Q: Small picture of code on the side of IDE I have no idea what this feature is called, but in sublime text, you can see a small picture of your code at the side of the screen

Does Visual studio have a similar  feature? If so, how do you enable it?

A: Yes, it is called "map mode" scroll bar. Simply type the word in the quick navigator. Ctrl-Q

A: It is called map mode you can change it in the scroll bar options to show annotations scroll bar, it is very useful for checking for errors in code.


text:
Q: How to add an eventlistener to a button javascript How can I add an eventlistener to my button? When the button is clicked the function speler1gooien has to run. When I run my example code below the function speler1gooien is fired on page load. What is the correct way to run my function only when clicked?
window.onload = function () {
            buttonSpeler1 = document.getElementById("buttonspeler1");
            buttonSpeler2 = document.getElementById("buttonspeler2");
            tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
            resultaat = document.getElementById("resultaat");
            buttonSpeler1.addEventListener("click", speler1gooien());
        };

        var speler1gooien =  function() {
            // some code

        }

A: Remove the parenthesis in the call speler1gooien() because it's causing your function to be executed immediately, and the return value is being passed as the click event handler.
buttonSpeler1.addEventListener("click", speler1gooien);
//                                                   ^ removed ()

By removing the parenthesis, you are passing the function object, instead of executing it.

A: You are trying to attach function speler1gooien as onclick handler, but your code attaches as handler the result of spele1gooien function. Just remove () following name of that function
window.onload = function () {
        buttonSpeler1 = document.getElementById("buttonspeler1");
        buttonSpeler2 = document.getElementById("buttonspeler2");
        tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
        resultaat = document.getElementById("resultaat");
        buttonSpeler1.addEventListener("click", speler1gooien);
};

var speler1gooien =  function() {
   // some code
}