text:
Q: AppSync HTTP Resolver IAM Authorization Error I am trying to use http resolvers with AWS AppSync so that we can support using graphQL and our REST APIs simultaneously. I got the AppSync http resolver working when the API Gateway did not have any authorization setup on it. However, I've now locked down the gateway with IAM and I am trying to call it with the http resolver.
Using Axios, I am able to call the API Gateway with and I get a good 200 response with these params.
Request Params
{
  "body": "{\"id\":1234}",
  "data": "{\"id\":1234}",
  "headers": {
    "Content-Type": "application/json; charset=UTF-8",
    "x-amz-date": "20190209T101242Z",
    "X-Amz-Security-Token": "AgoGb3JpZ2luEF4aCXVzLWVhc3QtMSKAAh9+SISFQH3bbHNLD47h5yCUsPmQhQ4Td74A1HmI/2jSu/Mg8mvK5IiMAMAMXokFQF8hZfzqsjfNWs+GcYkDRqhJbk7uaEaZFpjn5urgDAKVP/m5gywvnLnMWUXSOxTKe0kX+wTwHgnrV1wKR4+Fo97ykZPDasOPddw7HzSr9i2xKlKWEFB5iliZ08zvvA1OKUQ9gNdv6i+Cfwph/XGt0J7xvFtuYfOyZ5QRlyzggjS9cYbdaQ05A5vd+vAuDsdM7WXrU4OFN1ykRyw29VJU6eGFZTmBDX1AH7qI44ggjvwPOVUC/syAktuHgqqrADjleGdkRj0jZ+VoCybxAQYJEAQqpgUIcxAAGgw0OTc5OTY0NTMyNDgiDM9ufuhpC5ebbAUHHiqDBQ8P5DRX/leNqZEVIfcGahfFH6QfK9GZYDyW7iAVxHTEAL0ebMKi4Xo+vfatiISGgbTJuSB/csXvECTFkkuU1TNK21knO/WD5dWIIcKTSdQjZITMMtvTWk5JQWCFPrJ6ya6WENME3aYhfxXdCMuyL0EyFhx7A2J+GfukovfLRIU/CJl6GsyxSz0twNdBB71m7izPQ3rjN0ihNNayLWAfLhcU93Zq38BSavIesLYvqCpSYFH0fXrzhYaS+PRgKpvhgyR0r495OIIJfmSrMUZ2JZ/ct6YXanZCbEcFEwk91KPQDuG/NZhZcLpSPafU/HqkvaZ6gHSUpAR3jAi6XpLpaXHKS0vQnWV1ORnuIS/j9piDKe3HD42PsII9vgB69fZJK7wHImrqWwo9iKgHpiAYpJhs9K7lcznZ440NpjcA7VMBGBrvpFnLLv/VhTLVsYdNAeVfXMBshhEVsFVHvQstE/PHVvPTNMbk1eQwObKpQ/nprABPc4xWSKeF8w9TggwBrxemkDv+P0LhWqGso6WRssLH3GoKRE9znEawhvlxIbtDGJI38/j++zRTcreuduwbD29t+1pEk/5KJAnyxcQZmzTPlPTCA/TgRkeCEcOn7Xx/OZnG5137yK65xvHb2n1tPJsIDOlsD0AFP6me21sNkl5R4me746CR3ki0XUdIh4hPocKvlW+g32uWGBd6PMe+YwrCq8mD0NMxK3kgNMBtzX5IAyw51VTOIr01xCWrSegRbBtflYRtyHee2js3gu9N3ZfGHX13MDwvZi1WCfTDx3eP6wuPM4qcnJF/WBbkRU16PH8/Agkgxt5fQ4yaOOPv38GD1TRkGvWyshE2DJCilw27Qm8wms/64gU=",
    "Authorization": "AWS4-HMAC-SHA256 Credential=ASIAXH4XG2WACM4YOUAC/20190209/us-east-1/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-security-token, Signature=3b72f69aa94fe41026a7d8806cccfe50dd24b247df6681065435f7eba135d02e"
  },
  "method": "POST",
  "path": "/Prod/test",
  "url": "https://q1gyu9a0he.execute-api.us-east-1.amazonaws.com/Prod/test"
}

Response
{
  "data": "Hello from Lambda!",
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-type": "application/json"
  },
  "config": {
    "transformRequest": {},
    "transformResponse": {},
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/json; charset=UTF-8",
      "x-amz-date": "20190209T101418Z",
      "X-Amz-Security-Token": "AgoGb3JpZ2luEF4aCXVzLWVhc3QtMSKAAoEkajE677gfDz3UMEhI27lvIHgikCQIVivGmUBKwcIjfz+JH9z4ILd/HBp2i/fFwtOjUNpo0fFnJeN73QkY18BRdtuTwtbBmS0B+kcOIvkaZnNMVEinUFIANxRxvhLET7koVenwtsGY+Tppv5NaUPNw5RERr1pzCO7HgeiQixG2rToTrqsiYCNLvTHTuojHSHZpISXdpV7vusWzjFJTQgR+sSvo9kjNYUBzbLCCBxmVv0KFzEf8dzxUEP2N92aExKW7cq98wakh440vt3gfpkG7Yg/wkGmABnwSgUlP2IVF7717oN7yoTlFFul1EDUwJs/VvWkueGUnfKRMKXkGg74qpgUIcxAAGgw0OTc5OTY0NTMyNDgiDN9R1UCNsLAVF3x6lyqDBXcq3VNhWLCYe8jpUgM2j9AMzyK6eS7LBAgaAYQiisdcFSVmMDIYL2AeMzgX/76UjaA73MFOKPmfBR4hrzk0wnwOjpz/FlLwU47teaqtjZZoxlTtk8X7xLj7wk5j6XnLRRjpOBXmVytEzTst4yKnFxFR2PDACFZfuPF+VPWPEttJ3eGuDAPITQPXvRUnpc+kl04BZsb72w31zP7kFl1EQqabJpz2ie41ObQbp4DZ9XhSzWrQvrovnu/mG0m6cWJeXG03Xee7SHmAVMAsvrpZ0OeBFl4nY4HM8L2SHiivwX/NnAkrrKxjO07ARunp4k30jxkZi0xQISp0qowboovVP0uPwQTwDty4FaT2EN+5CqJVqXGLioKo2GG1wjCAwinUcYt8iCq1A1lcTf2boYEjqmZyJ0apQAsNeD/wa0dqfKM5BwBz4G/JyxDo/tvtJ93RlcKg4rhaEf0NvsFvoHve0sUNJXh/LsGK4aZpkNS3Kbgrc8PZ2CsYADRW7b5V8uk8WAQ207SRHi8SUXWlDp9dYLgsQ2AUiUwel5Ph2iyKWxAVZ+h32Wmx6W2PJ8L9jWZsdmH7DYFwpWHpn8GmicXkSdVXnLD6WwaVtvDRjr8CKNrY/HZvyxU7zrRKFX141pEhEyzmyNboUR1XFRXvSnCoRxtBbIGgsTLjEpcdpCKWrwxplPVMY1MI/oD4waFJrJaO78VOy/2h0FylwaI4PVONgSkw2VWk4dD0Okr71Jx9A2h1P4zC3PnyUc6rfj5sk8ZabYShuY3WTIjW+j4j8ApEdjEAv8uguEoF9t4F4/3gt0g/0WAU1wX5kNGfpphpmeE6Do0rPCdlW3JDqNiZ7arsrAFgRSIw+s/64gU=",
      "Authorization": "AWS4-HMAC-SHA256 Credential=ASIAXH4XG2WAC2MDEECX/20190209/us-east-1/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-security-token, Signature=664af118dadc082a7fa72a7e51266c2e42fcd3a4a83813032087898490a3eeca"
    },
    "method": "post",
    "body": "{\"id\":1234}",
    "data": "{\"id\":1234}",
    "path": "/Prod/test",
    "url": "https://q1gyu9a0he.execute-api.us-east-1.amazonaws.com/Prod/test"
  },
  "request": {}
}

Using AppSync with the following http resolver request mapping template, I am able to call the API Gateway as long as it is not configured to authorize with IAM.
HTTP Resolver Request Mapping Template
{
    "version": "2018-05-29",
    "method": "POST",
    ## E.G. if full path is https://api.xxxxxxxxx.com/posts then resourcePath would be /posts **
    "resourcePath": "/Prod/test",
    "params":{
        "body":$util.toJson($ctx.args)
    }
}

Working Response
{
  "data": {
    "test": "Hello from Lambda!"
  }
}

Now I'm trying to call the API Gateway with the http resolver after I lock down the gateway with IAM. I use the following request mapping template to try and pass the fields and headers required, but I get an error. Not really sure where to go from here.
Request Mapping Template Trying for IAM
{
    "version": "2018-05-29",
    "method": "POST",
    ## E.G. if full path is https://api.xxxxxxxxx.com/posts then resourcePath would be /posts **
    "resourcePath": "/Prod/test",
    "params":{
        "body":$util.toJson($ctx.args),
        "headers":{
            "Authorization": "$ctx.request.headers.httpAuth",
            "Content-Type": "$ctx.request.headers.conType",
            "X-Amz-Security-Token": "$ctx.request.headers.secToken",
            "x-amz-date": "$ctx.request.headers.newDate"
        }
    }
}

Error Received
"{message=The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

The Canonical String for this request should have been
'POST
/Prod/test

content-type:application/json; charset=UTF-8
host:q1gyu9a0he.execute-api.us-east-1.amazonaws.com
x-amz-date:20190209T103353Z
x-amz-security-token:AgoGb3JpZ2luEF4aCXVzLWVhc3QtMSKAAi+vyglsAoh1DSzupAqx2f+vbwUM9PicHyM3p8IHX5VG3rZqH4sGlAu8SsAWtnmHeqYdjoQ7CESKAr9qjL7Vg07ooYnGNeuoHA4hiZghN9Y6iFOVcM2zA7bTGTN2RCmxYsJZ965dX1N0BpvvUcN6fDr8PP7Zoo1crt0e4DD3N/4yjZNYcor1sv58fkicTRTwQp5CYtVn5nQ9vsLg+4QW1btsKIhjsbgRYXGhD2kmJc8nhQvPJp9wq0AlL4FjECToWE7Gpo/C358sQvOHBqbxrFqduAIi4eCW8yrJQ9Az17BB0FlyvUpPAwDsWDprB3AvIZnFIDnZAjNv1bjY+OxCyqkqpgUIdBAAGgw0OTc5OTY0NTMyNDgiDE7sXyPsvDNEdskDXiqDBYgF4RTqVkYl5HJv+W8hk3VPMaMPkiEgpOvfryaDgN94rfr2RjNDnQA/r9QrL1TLn8SYG5v0IMnpW1jEUUN4PVxZUL/LB/8UpaMUCbviMy0Mz8e3PdOPpMShCbkL/iMS8jxOWXNgN3Y0Pjr2sivkndTpuIV44JvMG2UON57Vxxjl55KS7FT2jQMIBx7FAGe8nwYY/hYdl6dbzudHIjZuofOWjr5KPaAS38FTyXQGcqo+SaQHHDd9gUnYhRwtHy9pepPFwPY9BGJzW2hnS54jYixaZnwf+wewyALkXi3t749jPVDk0jyXMHgO57lK8lqqL3GL9GxQEMq0Ebga3nUuL8tuOLlOU5qrvS6l0fiTUkOZuwX2/Tkr6dc3cn12m9L3aNfg0UlAO2cR1ginMux6HIwmaeh2ycbmbR2zWd6ObRjDTc573zzX5x/sXkMWkOunR7B7NtAnMlbcNzQmf7KlAVzaP2f42V2e1HGjyJLHhCqGV9alf8Nj+BKi4njIZQHb/KxnmnZ+ZJcyn0DVtvFM+h/0eylAVXFwQh8TP7rVNsI72gtxiC39mWdJ7xKoqbX1jSjfjE8JBej2SEbYrXI/m2043Mv02sfgzHcOWDl7NFw+7zGScwVSBjkEYL8f55U1HbRrP1CuJYo7OlL8Y/0KxttfK6vPK7BLUAe9UpT0Yzh7Fz/5OXDs7n9s94iHRhOFj038akBB/Ye2v5fBEkPBbmGelD+7CGVNmMKgpnqHlzNpm3q3Gu2tcElSuF/3kUm4Eg0ElJbsRDEnsy5qhWt1fpeBrscpsfyifnZZOHL7enen0cK/iJY8SeJFnImj6eNhL/ymOrV1Sls90JF89F3tZfUvAGkwkdn64gU=

content-type;host;x-amz-date;x-amz-security-token
583ff6a2cabb532c16553f12958ec329caf1fe48d171d529b5e144f7a2c3f8f5'

The String-to-Sign should have been
'AWS4-HMAC-SHA256
20190209T103353Z
20190209/us-east-1/execute-api/aws4_request
2dcd7c552c2fec47b88e6f7d711b9a61879d8a12fc327a1a3f327287405ca0e5'
}"

A: AppSync can also compute the sigv4 signature required by  Api Gateway on your behalf if you are using HTTP resolvers.
The configuration changes to your HTTP data source are not available through the console but using the AWS CLI you can pass the following paramaters:
aws appsync update-data-source --api-id yojcj4cdzzhizkscqocnr5xhem --name ApiGatewayTest --type HTTP --service-role-arn arn:aws:iam::769682826941:role/ApiGatewayRole --http-config file:///home/yourdir/apigateway.json

and the json file containing:
{
    "endpoint": "https://apigateway.us-east-1.amazonaws.com/",
    "authorizationConfig": {
       "authorizationType": "AWS_IAM",
       "awsIamConfig": {
         "signingRegion": "us-east-1",
         "signingServiceName": "apigateway"
       }
    }
}

AppSync does assume role on the role you provide, so it needs to allow AppSync to assume the role and call your API Gateway API.
You can find more info about the headers API Gateway expects in their documentation, here:
https://docs.aws.amazon.com/apigateway/api-reference/signing-requests/


text:
Q: Unable to install a package from the postinst of another package I have Ubuntu 14.04.
I have 2 deb packages, deb1 and deb2
I'm trying to install deb2 in the postinst of deb1 using dpkg -i deb2 but I get this error:
dpkg: error: dpkg status database is locked by another process

To get around that, in my postinst I added this instruction to remove the lock:
sudo rm /var/lib/dpkg/lock

But then deb1 installation failed:
dpkg: unrecoverable fatal error, aborting:
unable to install updated status of `deb1':
No such file or directory`

However, when I don't try to install deb2 from deb1 the installation of deb1 succeeds.
How can I achieve what I want?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use the 'as' keyword to alias a table in Oracle? I'm trying to execute this query in Oracle SQL Developer:
SELECT G.Guest_ID, G.First_Name, G.Last_Name
FROM Guest AS G
  JOIN Stay AS S ON G.Guest_ID = S.Guest_ID
WHERE G.City = 'Miami' AND S.Room = '222';

However, I get the following error:
ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 2 Column: 12

I don't see any problem in line 2 and the error is not very descriptive. It appears to be something to do with the as keyword. If I remove it, it works fine. However, I want my queries to be very verbose. Therefore, I must figure out a way to fix whatever the problem is without removing the as keyword.
This is the structure of the tables involved:
CREATE TABLE GUEST
(
  GUEST_ID       NUMBER               NOT NULL,
  LAST_NAME      VARCHAR2(50 BYTE),
  FIRST_NAME     VARCHAR2(50 BYTE),
  CITY           VARCHAR2(50 BYTE),
  LOYALTY_NUMBER VARCHAR2(10 BYTE)
);

CREATE TABLE STAY
(
  STAY_ID        NUMBER                         NOT NULL,
  GUEST_ID       NUMBER                         NOT NULL,
  HOTEL_ID       NUMBER                         NOT NULL,
  START_DATE     DATE,
  NUMBER_DAYS    NUMBER,
  ROOM           VARCHAR2(10 BYTE)
);

Thanks for any help in advance.

A: You can use AS for table aliasing on many SQL servers (at least MsSQL, MySQL, PostrgreSQL) but it's always optional and on Oracle it's illegal.
So remove the AS :
SELECT G.Guest_ID, G.First_Name, G.Last_Name
FROM Guest G

A: Omit the AS for table alias in Oracle.
SELECT G.Guest_ID, G.First_Name, G.Last_Name
FROM Guest G
  JOIN Stay S ON G.Guest_ID = S.Guest_ID
WHERE G.City = 'Miami' AND S.Room = '222';

This will give you the output without errors.


text:
Q: How to delete a row in a XAML DataGrid which is bound to a sqlite? I got a xaml datagrid:
<DataGrid Grid.Row="0" x:Name="productTransactionsGrid"
          CanUserAddRows="true"
          CanUserDeleteRows  ="True"
          RowEditEnding="productTransactionsGrid_RowEditEnding"
          CurrentCellChanged="productTransactionsGrid_CurrentCellChanged"/>

witch is initialized like this from a row in sqlite:
private void InitTransactions()
{
    productTransactionsGrid.ItemsSource = (from p in m_DbSession.Query<ProductTransaction>()
                                          where (p.Product.Id == m_DBProduct.Id)
                                          orderby p.Date
                                          select new ProductTransactionDatasource(p, m_DbSession)).ToList();
    productTransactionsGrid.ScrollIntoView(CollectionView.NewItemPlaceholder);
}

The product datasource looks like this
class ProductDatasource : AddableDatasource
{
    Product m_Product;

    public ProductDatasource()
    {
        m_Product = new Product();
    }

    public ProductDatasource(Product initialProduct, ISessionWrapper dbSession)
    {
        m_Product = initialProduct;
        SetSession(dbSession);
    }

    //...some properties

    internal Product GetProduct()
    {
        return m_Product;
    }

    protected override object GetDbObject()
    {
        return m_Product;
    }

}

Now the user can press "delete" and the selected row is removed from the datagrid. But it is not removed from the database. So I think this is not saved.
I thought that I have to save it by myself. So I tried to find an event which triggers when the user deletes a row, but I was not able to find such an event.


text:
Q: How to combine rows to change the shape of a pandas dataframe I would like to rearrange a dataframe so that every 2 rows are combined into one row.
For example
0  a  b  c  d
1  e  f  g  h
2  i  j  k  l
3  m  n  o  p

into:
0  a  b  c  d  e  f  g  h
1  i  j  k  l  m  n  o  p

I need to do this for quite a large table of data and have been unable to find a solution.
I'm a complete python novice and would appreciate any help.
Thanks

A: You can use the underlying numpy array and numpy's reshape method:
df2 = pd.DataFrame(df.to_numpy().reshape((len(df)//2, -1)))

output:
   0  1  2  3  4  5  6  7
0  a  b  c  d  e  f  g  h
1  i  j  k  l  m  n  o  p

alternatively using pandas:
pd.concat([df.iloc[::2].reset_index(drop=True),
           df.iloc[1::2].reset_index(drop=True)],
           axis=1)

but you will have duplicated column names:
   0  1  2  3  0  1  2  3
0  a  b  c  d  e  f  g  h
1  i  j  k  l  m  n  o  p


text:
Q: Windows C++ CMD window switching Hello fellow programmers, I have a problem with some console applications in a C++ program, and my objective is as follows.

*

*Create first CMD window.

*Execute a command. (system("print some error text");)

*Create second CMD window.

*Change system(...) focus to second CMD window.

*Execute a command.

*Change system(...) focus to first CMD window.

*Execute a command.

The end goal of all this is to create a function that will be executed by a CMD application that will spawn another CMD window, execute a command on it, and then return focus to the original CMD window to continue executing other code. I do not need to keep track of the window, or be able to return to it. Just create new window, switch focus to it, execute a command, return focus to original window.

*

*The first CMD window is created when the application is started.

*Executing a command to this window with system(...); works fine.

*I create a second CMD window with
HWND new_hWnd = NULL;
ShellExecute(new_hWnd, "open", "cmd.exe", NULL, NULL, SW_SHOW);

*This is where I have problems, I have not been able to redirect system(...) to a different CMD window, and this is the part I need help with because if I can figure this out, then steps 5, 6 and 7 will be easy to complete.

I've tried researching this online and have come across some different examples using "pipes" but have not been able to recreate them, or understand them. Also, I noticed there is a
    GetConsoleWindow();

function that returns a handle to the current CMD window, which to me kinda signals that there should be a way to switch between CMD windows by using handles, but since I have not switched focus to the other CMD window I can not call that function to get it's handle.
So, how do I make system(...) target different CMD windows with handles? If that is not possible, how can I implement this "pipe" system.
If the solution is the latter, please try to be as detailed and simple as possible with it because every example of it I have found online is really large and hard to read/understand.
If there is no easy way to implement "pipes" then please post or point me to the best(something that will help me understand how pipes work) example you can find and I will keep working with it till I figure it out. Thank you in advance!

A: You can create a new console for the new process by specifying the dwCreationFlags value CREATE_NEW_CONSOLE when calling CreateProcess.
See the documentation:

*

*Process Creation Flags: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx

*CreateProcess function: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx


text:
Q: Failed to load dynamic library 'libiris_event_handler.so': dlopen failed: library "libiris_event_handler.so" not found in Agora.io's newest SDK(6.0.0) So, I just updated my Flutter App to run in the SDK 6.0.0, but for some reason, whenever I start the app in the emulator, I get this error message:
E/flutter (15665): [ERROR:flutter/runtime/dart_isolate.cc(1111)] Unhandled exception:
E/flutter (15665): Invalid argument(s): Failed to load dynamic library 'libiris_event_handler.so': dlopen failed: library "libiris_event_handler.so" not found
E/flutter (15665): #0      _open (dart:ffi-patch/ffi_dynamic_library_patch.dart:12:43)
E/flutter (15665): #1      new DynamicLibrary.open (dart:ffi-patch/ffi_dynamic_library_patch.dart:23:12)
E/flutter (15665): #2      IrisEvent._loadAgoraRtcWrapperLib
package:iris_event/iris_event.dart:23
E/flutter (15665): #3      new IrisEvent
package:iris_event/iris_event.dart:15
E/flutter (15665): #4      _ApiCallExecutorInternal.initilize
package:agora_rtc_engine/…/impl/api_caller.dart:429
E/flutter (15665): #5      _ApiCallExecutor._execute
package:agora_rtc_engine/…/impl/api_caller.dart:183
E/flutter (15665): #6      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:300:17)
E/flutter (15665): #7      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

And yeah, I have no idea of what's going on. I even installed this library, the iris_event, but still, same error


text:
Q: Is there a lazy loading implementation of JList? Is there a way to implement lazy loading with Swing's JList?

A: I solved it. I had missed the solution discussed at the top of the JList API documentation.
In the example source code I posted in another answer on this topic, add this line (and comment) after creating the JList:
  // Tell JList to test rendered size using this one value rather
  // than every item in ListModel. (Much faster initialization)
  myList.setPrototypeCellValue("Index " + Short.MAX_VALUE);

The problem is that JList, by default, is accessing every item in the entire ListModel to determine at runtime the necessary display size. The line added above overrides that default, and tells JList to examine just the one value as passed. That one value acts as a template (prototype) for sizing the display of the JList.
See:
http://java.sun.com/javase/6/docs/api/javax/swing/JList.html#prototype_example

A: Just to add to the other answer, when you create your own implementation of ListModel, while you are loading the data you will want to call:
fireIntervalAdded(Object source,int index0, int index1)

Assuming that you are loading data into your list incrementally. This will cause the JList that is using it as a model to update.
See Javadoc for fireIntervalAdded

A: In a way, yes. You can create a custom ListModel which uses the getElementAt(int index) method to load the correct value if it hasn't already been loaded. See the example in the Javadocs for JList:
// This list model has about 2^16 elements.  Enjoy scrolling.

ListModel bigData = new AbstractListModel() {
    public int getSize() { return Short.MAX_VALUE; }
    public Object getElementAt(int index) { return "Index " + index; }
};

A: Incorrect. That JList above is NOT lazily loaded.
Swing insists on accessing each item in the entire ListModel while getting it displayed on screen. Furthermore, after accessing all the items, Swing then re-accesses the first n number of items visible on screen (in the viewport, not off screen below).
Run this simple "TestJList" class to prove it. I call println each time 'getElementAt' is executed. You can plainly see that Swing calls that method for every item in the ListModel.
This happens for me on a MacBook unibody running Mac OS X 10.6.2 with Java:

"1.6.0_17" Java(TM) SE Runtime
  Environment (build 1.6.0_17-b04-248-10M3025)
  Java HotSpot(TM) 64-Bit Server VM (build
  14.3-b01-101, mixed mode)

import javax.swing.*;

/**
 *  This example proves that a JList is NOT lazily-loaded.
 */
public class TestJList {
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create an artificial ListModel.
        ListModel bigData =
            new AbstractListModel() {
                public int getSize() {
                    // return Short.MAX_VALUE;  // Try this if you have a long while to waste.
                    return 10;
                }

                public Object getElementAt(int index) {
                    System.out.println("Executing 'getElementAt' # " + index);
                    return "Index " + index;
                }
            };

        // Create a JList.
        JList myList = new JList(bigData);

        // Add the JList to the frame.
        frame.getContentPane().add(myList);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(
            new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
    }
}

Run that code, and you'll see:
Executing 'getElementAt' # 0
Executing 'getElementAt' # 1
Executing 'getElementAt' # 2
Executing 'getElementAt' # 3
Executing 'getElementAt' # 4
Executing 'getElementAt' # 5
Executing 'getElementAt' # 6
Executing 'getElementAt' # 7
Executing 'getElementAt' # 8
Executing 'getElementAt' # 9
Executing 'getElementAt' # 0
Executing 'getElementAt' # 1
Executing 'getElementAt' # 2
Executing 'getElementAt' # 3
Executing 'getElementAt' # 4
Executing 'getElementAt' # 5
Executing 'getElementAt' # 6
Executing 'getElementAt' # 7
Executing 'getElementAt' # 8
Executing 'getElementAt' # 9

-fin-


text:
Q: Gulp is throwing syntax error, probbably compiling dependencies I have the following gulp file:
var paths = {
    all: ['*.js', '**/*.js', 'index.html'],
    js: ['*.js', '**/*.js'],
    html: 'index.html',
    dist: 'dist'
};

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
    gulp.src(paths.html)
        .pipe(gulp.dest(paths.dist));
    return gulp.src(paths.js)
        .pipe(babel())
        .pipe(gulp.dest(paths.dist));
});

gulp.task('watch', function(){
    gulp.watch(paths.all, ['default']);
});

When I run it, I get this error
 SyntaxError: d:/project_folder/node_modules/gulp-babel/node_modules/gulp-util/node_modules/beeper/index.js: 'return' outside of function (9:1) ...`

I read somewhere that I shouldn't compile dependencies. I run just gulp with no following flags. So I don't know wehether or not I do compile them. But gulp seems slow because it takes few seconds to get to first task. How to get rid of this error? And am I doing something wrong with dependencies?

A: Yes, you are currently including all .js files from the current directory, not the source directories. Your application code (lets assume app.js) will "include" your dependencies by using common js requires, such as:
var request = require('request');

In order to actually map the require statements you would want to use a module loader, or packer such as: Browserify or Webpack
The following gulp task will solve the module errors:
var paths = {
    all: ['./src**/*.js', 'index.html'],
    js: ['./src/**/*.js'],
    html: 'index.html',
    dist: 'dist'
};

var gulp = require('gulp');
var babel = require('gulp-babel');

gulp.task('default', function () {
    gulp.src(paths.html)
        .pipe(gulp.dest(paths.dist));
    return gulp.src(paths.js)
        .pipe(babel())
        .pipe(gulp.dest(paths.dist));
});

gulp.task('watch', function(){
    gulp.watch(paths.all, ['default']);
});

This only includes all the .js files in the src folder, not **/*.js which will include all *.js files in every folder including node_modules bower_components.
Regarding module loading:
You would probably want to use a loader task to bundle all your client code instead of just copying them to the dist, such as:
gulp.task("webpack", function(callback) {
    // run webpack
    webpack({
        // configuration
    }, function(err, stats) {
        if(err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        callback();
    });
});


text:
Q: How to show price shipping without tax in shipping method step Magento 2 I want to display price shipping without tax in shipping method step, I have configured it like this but it is not working. It still shows at price 4.40 while without tax is 3.70, please help me.

Shipping method step it show 4.40

Cart and payment method it show 3.70


text:
Q: Change Style of GridView Select Button I have a GridView with selection enabled. I'd like to programmatically change the style of these links, but I'm not sure how to access them. I've applied CSS to them using the a selector, but I can't do this through the code.
How can I modify the appearance of these buttons using C#?

A: Try Below Code:
<asp:GridView ID="gvUserInfo" runat="server"
    onrowdatabound="gvUserInfo_RowDataBound1">
 <Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkButton" runat="server" Text="Link"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

protected void gvUserInfo_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lnk = e.Row.FindControl("lnkButton") as LinkButton;
            lnk.ForeColor = System.Drawing.Color.Red;
        }
    }

A: Because I grid view is a Table you can use CSS
<html>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RegNo" DataSourceID="SqlDataSource1" Width="931px" CellPadding="4" ForeColor="#333333" GridLines="None" Height="170px" AutoGenerateDeleteButton="True">
</asp:GridView>
<style>
    td > a {
        /*button*/
        display: inline-block;
        margin-bottom: 0;
        font-weight: normal;
        text-align: center;
        vertical-align: middle;
        -ms-touch-action: manipulation;
        touch-action: manipulation;
        cursor: pointer;
        background-image: none;
        border: 1px solid transparent;
        white-space: nowrap;
        padding: 4px 8px;
        font-size: 14px;
        line-height: 1.42857143;
        border-radius: 4px;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        /*button color*/
        color: #ffffff;
        background-color: #c71c22;
        border-color: #c71c22;
    }

        td > a:hover {
            color: #555555;
            text-decoration: none;
            background-color: #9a161a;
            border-color: #911419;
        }


text:
Q: Resizeable widget in ConstraintLayout I've got a ListView item with three components aligned horizontally:

*

*an ImageView containing an icon

*a TextView with a headline

*another ImageView wit a status icon

Currently, I have them arranged via a RelativeLayout and my TextView is 'elastic'.
Is it possible to create the same layout in ConstraintLayout? Basically, what I'm asking is if I can create 2 fixed-length constraints instead of percentages.

A: yes, do the following, with the elements contains in a ConstraintLayout such as:
ImageView1 TextView ImageView2

*

*ImageView1 : constraint left to ConstraintLayout left side

*ImageView2 : constraint right to ConstraintLayout right side

*TextView

*

*constraint left to ImageView1 right side

*constraint right to ImageView2 left side

*layout_width="0dp"

"0dp" tells CL to stretch the widget up to meet the constraints set. You can add margins on the constraints as well.


text:
Q: How to hide the app status bar I THINK it is called the status bar? The one with the power meter, clock etc. Took me ages to work out to "hide" it but all it did was hide the icons, it is still taking real-estate.
And so, when the wkwebview scrolls up, its scrolls under the status bar and looks awful.
I either want to completely hide the status bar or have it there but block colour so nothing can be seen under it. I have looked at 100 SO questions that talk about app settings in xcode, info.plist, appdelegate settings, viewcontroller settings, navigationcontroller settings (mine is hidden), but nothing gets round this.
Things Tried:

*

*UIStatusBarHidden=true in info.plist

*Project > General > Hide Status Bar = checked (guessing that's 1)

*UIViewControllerBasedStatusBarAppearance=false in info.plist

*This code in ViewController
override func prefersStatusBarHidden() -> Bool {
    return true
}

*in AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions       launchOptions: [NSObject: AnyObject]?) -> Bool {
    application.statusBarHidden = true
    return true
}
HELP PLEASE!
Screenshot:

A: Turns out I was previously compensating for the status bar being there with:
webView.scrollView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

changed the top value to 0 and along with the 5 steps in the question and that has worked.

A: You can get access to status bar via private API
- (UIView *)statusBarView {
    return [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
}

A: *

*Try to go to your project settings by right-clicking it in Project navigator.

*Select General tab

*Scroll down and find checkbox "Hide status bar" in "Deployment Info" section


text:
Q: How to prove roots of several univariate polynomials is a solution of a multivariable polynomial When I study the existence of certain spherical polygon, I have encountered the following problem.
Let $\gamma$ and $\delta$ be angles such that
$1216\cos^6\gamma-1056\cos^4\gamma+84\cos^2\gamma-1=0, \ \cos\gamma\approx -0.8839453420007384$.
$1216\sin^6\gamma-2592\sin^4\gamma+1620\sin^2\gamma-243=0, \
\sin\gamma\approx-0.4675902397989036$.
$1216\cos^6\delta-2496\cos^4\delta+1668\cos^2\delta-361=0,\
\cos\delta\approx 0.8469176972278768$.
$1216\sin^6\delta-1152\sin^4\delta+324\sin^2\delta-27=0,\
\sin\delta\approx
0.5317240018301108$.
When I put $\cos\gamma=-0.8839453420007384$, $\sin\gamma=-0.4675902397989036$, $\cos\delta= 0.8469176972278768$ and $\sin\delta=0.5317240018301108$ into
$(\dfrac{\sin\frac{2\pi}{9}}{6}-\dfrac{\cos\frac{2\pi}{9}}{6\sqrt{3}}-\dfrac{4}{3\sqrt{3}})\sin\delta\sin\gamma+(\dfrac{5\cos\frac{2\pi}{9}}{18}-\frac{\sin\frac{2\pi}{9}}{6\sqrt{3}}-\dfrac{4}{9})\cos\delta\sin\gamma$
$-(\dfrac{\sin\frac{2\pi}{9}}{2\sqrt{3}}+\dfrac{\cos\frac{2\pi}{9}}{2})\cos\gamma\sin\delta+(\dfrac{5\sin\frac{2\pi}{9}}{6}+\dfrac{\cos\frac{2\pi}{9}}{2\sqrt{3}})\cos\delta\cos\gamma$, I get $5.551115123125783\times 10^{-17}$.

How to prove/disprove
  $(\dfrac{\sin\frac{2\pi}{9}}{6}-\dfrac{\cos\frac{2\pi}{9}}{6\sqrt{3}}-\dfrac{4}{3\sqrt{3}})\sin\delta\sin\gamma+(\dfrac{5\cos\frac{2\pi}{9}}{18}-\frac{\sin\frac{2\pi}{9}}{6\sqrt{3}}-\dfrac{4}{9})\cos\delta\sin\gamma$
$-(\dfrac{\sin\frac{2\pi}{9}}{2\sqrt{3}}+\dfrac{\cos\frac{2\pi}{9}}{2})\cos\gamma\sin\delta+(\dfrac{5\sin\frac{2\pi}{9}}{6}+\dfrac{\cos\frac{2\pi}{9}}{2\sqrt{3}})\cos\delta\cos\gamma=0$.

Remark: In order to make sure there is no typo, I include the picture of the expression and the computation result in wxmaxima:

where $cga=\cos\gamma$, $sga=\sin\gamma$, $cde=\cos\delta$ and $sde=\sin\delta$.
Note that $2 \  3^{3/2}=2\times 3^{3/2}$.

A: This is a standard problem of algebraic geometry, which admits a completely algorithmic solution. We note that $\cos\frac{2\pi}9$ is a root $x$ of the equation $1 - 6 x + 8 x^3 = 0$. The rest of the task a computer algebra program can do easily, as seen in the following image of a Mathematica notebook, confirming your conjecture by giving the exact (zero) value of your big expression:

A: This is a more hands-on answer than the previous one; it is based on resultants.
Here we again note that
$$x_*:=\cos\tfrac{2\pi}9$$
is a root of the equation
$$p_1(x):=1 - 6 x + 8 x^3 = 0.$$
Next, using the formula $\cos^2=\frac1{1+\tan^2}$, we see that
$$V_*:=\tan\gamma$$
is a root of the equation
$$P_2(V):=243 - 891 V^2 + 81 V^4 - V^6 = 0$$
and
$$T_*:=\tan\delta$$
is a root of the equation
$$P_3(T):=27 - 243 T^2 + 585 T^4 - 361 T^6 = 0.$$
Moreover, the pair $(x_*,y_*)$ with
$$y_*:=\sin\tfrac{2\pi}9$$
is a root of the equation
$$p_4(x,y):=x^2+y^2 - 1 = 0.$$
We have to show that the quadruple $(x_*,y_*,V_*,T_*)$ is a root $(x,y,V,T)$ of the equation
$$L:=L(x,y,V,T):=\left(\frac{x}{2 \sqrt{3}}+\frac{5 y}{6}\right)+V\left(\frac{5 x}{18}-\frac{y}{6
   \sqrt{3}}-\frac{4}{9}\right)-T\left(\frac{x}{2}+\frac{y}{2 \sqrt{3}}\right)+T V \left(-\frac{x}{6
   \sqrt{3}}+\frac{y}{6}-\frac{4}{3 \sqrt{3}}\right)=0;$$
this simplification of the big expression in question is crucial, as it allows to reduce the calculations to a feasible level.
Let us now quote the following property of the resultant:
"The resultant of two polynomials with coefficients in an integral domain is zero if and only if they have a common root in an algebraically closed field containing the coefficients."
Consider successively the resultants
$$r_1(c,x,V,T):=R(L(x,y,V,T)-c,p_4(x,y),y),$$
$$r_2(c,V,T):=R(r_1(c,x,V,T),p_1(x),x),$$
$$r_3(c,T):=R(r_2(c,V,T),P_2(V),V),$$
$$r_4(c):=R(r_3(c,T),P_3(T),T),$$
where $R(P,Q,w)$ denotes the resultant of polynomials $P$ and $Q$ with respect to a variable $w$. (It takes about 30 sec for Mathematica to compute each of the resultants $r_3(c,T)$ and $r_4(c)$.)
It follows from the quoted property of the resultant that the real number $L(x_*,y_*,V_*,T_*)$ must be in the set of all real roots of the polynomial $r_4(c)$.  In fact, $r_4(c)$ has the root $0$ (of multiplicity $3$), whereas all the other $213$ real roots of $r_4(c)$ are $>1/2$ in absolute value. However, a direct numerical calculation shows that $|L(x_*,y_*,V_*,T_*)|\le1/2$.
Thus, $L(x_*,y_*,V_*,T_*)=0$, as desired.


text:
Q: In ZF2, how to write a single Plugin to be used both in Controller and View? In my ZF2 application, I am trying to write a plugin to provide a wrapper around PHP Date utilities. I have planed this plugin would have apis to initialize, convert and retrieve date values.
I know how to write a plugin for Controller by extending

Zend\Mvc\Controller\Plugin\AbstractPlugin class

and also know hot to write a plugin for View by extending

Zend\View\Helper\AbstractHelper class.

But how we can write a single plugin which would be used both in Controller and View?

A: I would write an class (factory or invokable) that can be retrieved from the ServiceManager and let both plugin types access this class. This allows you to keep your logic and functionality in a single class, Zend Navigation takes a similar approach with data for the navigation being stored within a factory class shared between the helpers.
A very hacky alternative is to create a Controller plugin and then request your controller plugin through the controller plugin manager, which is available from the ServiceManager. Of course the View plugin would need to be of ServiceManagerAwareInterface to access the ServiceManager.
$plugin = $this->getServiceManager()->get('ControllerPluginManager')->get('myplugin');

Then pass the __invoke() parameters to the plugin. Whilst this is doable the first approach is much better.

A: You can't. As you've stated correctly, controller plugins and viewhelpers extend different classes which makes them incompatible to each other.
Also, it doesn't really make sense to mix controller plugins with view helpers because they both fulfill completely different purposes. Controller plugins are used to perform commonly used portions of business logic, viewhelpers, however, provide reusable view logic.
I'd suggest to create a class which is capable of date conversion (or whatever you need) and create an atomic view helper to render dates in the desired format (using this class). However, I wouldn't necessarily create a controller plugin for this, because you can easily retrieve the instance of this class using the service manager.
Note: I consider my answer to be rather general -- I haven't really taken into account what exactly you're trying to do (with other words: I didn't think about if it makes sense to create a wrapper for Date functions). If my answer doesn't fit your problem, please, feel free to state your question more closely.

A: If you're using php 5.4, consider creating a trait that is used in a plugin and view helper.


text:
Q: How to upload an image to firebase using AngularFire? I have been looking for an official instruction on how to do upload an image (under 10 mb) to Firebase, but I could not find one. Any ideas?

A: just use the input type=file function


text:
Q: Suppressing fields of embedded documents inside an array Here is an example of the situation I am encountering (pretend each school has an array of students and there is only 1 result):
db.students.find(_id: { $in: school.students })

{
    _id: 1,
    zipcode: "63109",
    students: [
          { name: "john", school: 102, age: 10 },
          { name: "jess", school: 102, age: 11 },
          { name: "jeff", school: 108, age: 15 }
       ]
}

How would I do a similar query that omits the "school" fields from the students array inside students?
For example, how do I make the result look like this?
{
    _id: 1,
    zipcode: "63109",
    students: [
          { name: "john", age: 10 },
          { name: "jess", age: 11 },
          { name: "jeff", age: 15 }
       ]
}

A: You can try something like below. Use projection to keep the fields you like.
db.students.find({}, {zipcode:1,"students.name" :1,"students.age" : 1})


text:
Q: JavaScript to parse a soap request Hi i wanto to Parse the following XML file, as you can see its a webService request:
importPackage(Packages.java.io);
importPackage(Packages.java.lang);
importPackage(Packages.java.util);
importPackage(Packages.org.w3c.dom);
importPackage(Packages.com.vordel.circuit);
importPackage(Packages.com.vordel.common.base64);
importPackage(Packages.com.vordel.dwe);
importPackage(Packages.com.vordel.mime);
importPackage(Packages.com.vordel.trace);
importPackage(Packages.com.vordel.common.util);
importPackage(Packages.com.vordel.es);
importPackage(Packages.com.vordel.es.xes);

function invoke(msg)         {
var Container = msg.get ("container");
var Policy= msg.get ("Policy_AccountActivity");
    try {
var espk = PortableESPKFactory.newInstance().createPortableESPK(
    "<key type='CircuitContainer'>" +
        "<id field='name' value='"+Container+"'/>" +
        "<key type='FilterCircuit'>" +
            "<id field='name' value='"+Policy+"'/>" +
        "</key>" +
    "</key>");
// Here obtaining a reference on the Policy to be invoked
var circuit = Service.getInstance().getLocalPack().cache.getCircuit(espk);
// Setting up a dummy context, needed to invoke the Policy afterwards
var context = new java.lang.String("DefaultContext");
        // get the xml body
        var body = XMLBody.locate(msg);
        var doc = body.getDocument();
        var root = doc.getDocumentElement();
        var NameElement = "get_Account_Activity_Request";

        var nodes =
            root.getElementsByTagName(NameElement);

        if ((nodes == null) || (nodes.getLength() <= 0)) {
           Trace.error("There were no "+NameElement+" elements found in the message");
           return false;
        }
        var content = new StringBuffer();
        var compteur =  1;

        for (i = 0; i < nodes.getLength(); i++) {
            var toProcess = nodes.item(i);

            if (toProcess == null)
               continue;

            // get the contents of the element
            var children = toProcess.getChildNodes();
            Trace.debug("Getting children");
             msg.put("MessageIDCTP",compteur.toString());
           compteur+=1;

             for (j = 0; j < children.getLength(); j++) {

                 var node = children.item(j);
                if (node.getNodeName() == "mob:maxNbRecord") {
                        var childrenMaxNbRecord= node.getChildNodes();
                        var nodeMaxNbRecord= childrenMaxNbRecord.item(0);
                        var value= nodeMaxNbRecord.getNodeValue();
                msg.put ("account.MaxNbRecord" , value.toString() ) ;
                   }
                    if (node.getNodeName() == "mob:startDate") {
                        var childrenStartDate= node.getChildNodes();
                        var nodeStartDate= childrenStartDate.item(0);
                        var value= nodeStartDate.getNodeValue();

                msg.put ("account.StartDate" , value.toString() ) ;

                   }

                    if (node.getNodeName() == "mob:endDate") {
                        var childrenEndDate= node.getChildNodes();
                        var nodeEndDate= childrenEndDate.item(0);
                        var value= nodeEndDate.getNodeValue();

                msg.put ("account.EndDate" , value.toString() ) ;
                }

                if (node.getNodeName() == "mob:minAmount") {
                        var childrenMinAmount= node.getChildNodes();
                        var nodeMinAmount= childrenMinAmount.item(0);
                        var value= nodeMinAmount.getNodeValue();

                msg.put ("account.MinAmount" , value.toString() ) ;
                }
                        if (node.getNodeName() == "mob:maxAmount") {
                        var childrenMaxAmount= node.getChildNodes();
                        var nodeMaxAmount= childrenMaxAmount.item(0);
                        var value= nodeMaxAmount.getNodeValue();

                msg.put ("account.MaxAmount" , value.toString() ) ;

                InvocationEngine.invokeCircuit(circuit, context, msg);
                }
            }
      }
 }

catch (exp) {
        Trace.error(exp);
    }
    return true;
}

     <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org           /soap/envelope/" xmlns:acc="URL" xmlns:mob="URL">
      <soapenv:Header/>
     <soapenv:Body>
         <acc:get_Account_Activity_RequestFlow>
        <mob:requestHeader>
        <mob:requestId>1</mob:requestId>
        <mob:serviceName>WS_WebserviceName</mob:serviceName>
        <mob:timestamp>2015-04-22T18:12:06.84585</mob:timestamp>
        </mob:requestHeader>
        <acc:get_Account_Activity_Request>
        <mob:accountID>
           <mob:Code1>0003</mob:Code1>
           <mob:Code2>552</mob:Code2>
           <mob:Code3>056897</mob:Code3>
        </mob:accountID>
        <!--Optional:-->
        <mob:maxNbRecord>1</mob:maxNbRecord>
        <mob:startDate>2015-04-22T18:12:06.00000</mob:startDate>
        <mob:endDate>2015-04-22T19:12:06.00000</mob:endDate>
        <!--Optional:-->
        <mob:minAmount>0000.0000</mob:minAmount>
        <!--Optional:-->
        <mob:maxAmount>6000.0000</mob:maxAmount>
         </acc:get_Account_Activity_Request>
      </acc:get_Account_Activity_RequestFlow>
      </soapenv:Body>
      </soapenv:Envelope>

My script is gathering the following elements that come in an immediate level under acc:get_Account_Activity_Request.
But my issue is that i dont know how to retrieve the elements code1, 2 and 3 that come inside the  tag:
When i do an "if (node.getNodeName() == "mob:Code1")" this element is not found.
Any advise would be hugely appreciated


text:
Q: Installing NPM on OSX Lion I am trying to install NPM on OSX Lion, I run this command:
curl https://npmjs.org/install.sh | sudo sh

After asking to type "yes" and I do I get this:
All clean!
! [ -d .git ] || git submodule update --init --recursive
node cli.js rm npm -g -f
node cli.js cache clean
Assertion failed: ((req->result == -1 && req->ptr == NULL) || (req->result >= 0 && req->ptr != NULL)), function uv_fs_req_cleanup, file src/unix/fs.c, line 89.
make: *** [clean] Abort trap: 6
node(21572,0x7fff73d64960) malloc: *** error for object 0x7ff772051000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
npm-install-20221.sh: line 211: 21572 Abort trap: 6           "$node" cli.js install -gf
It failed

Did some research and couldn't find anyone else with this exact issue. My node version is v.0.5.7-pre.
EDIT
For those looking how to install npmjs the url has changed to https only (url fixed above).

A: Yup.
tjameson is right.
Install the stable version before installing npm.
Get the source code directly from node website:
node-v0.4.11.tar.gz Source Code


text:
Q: Why magnetic dipole moment are important After reading the Chapter 35 of Halliday Resnick and Krane's Physics, which is the section on magnetism in which magnetic dipoles are introduced, I still don't understand why the particular quantity
  $$\mu:= iA$$
  of a loop of wire with area $A$ and current $i$ is important.
Searching online gives not very satisfying answers like "The torque on the loop is written in a compact way as $\mu \times B$" but that shouldn't be the reason the quantity was defined in the first place.
Why the quantity is important ?

A: You can always define whatever quantity you want, so long as you take appropriate care to justify its appropriateness in the cases where you're (completely or partially) using existing terminology. What really matters is your ability to take the concepts you've defined and put them to use in an effective manner.
Thus, when you define the concept of the magnetic dipole moment of a current loop and then you go on to show something like

The torque on the loop is written in a compact way as $\mu \times B$,

i.e. you go on to show that all of your system's interactions of a given type (in this case, the torque exerted by an external field) are not only (i) compactly encapsulated by your new concept, but also (ii) completely encapsulated by your new concept (i.e. you've proved that the spatial layout of your current loop is irrelevant, and that the only thing that matters is the dipole moment), then your new concept has already earned its place as a relevant concept in the theory.
The dipole moment of a current loop, of course, is indeed more important than just that isolated property. The thing that makes it really important is that it is the initial member of a series of moments, known as the multipole expansion of your current distribution, which is able to completely capture your current distribution's interactions with the outside world.
In other words, for any given interaction $I$, you're generally able to decompose it as
$$
I = \sum_\ell \mathrm{moment}_\ell[\mathbf J] \times \mathrm{property}_\ell[\mathbf B]
$$
where

*

*$\mathrm{moment}_\ell[\mathbf J]$ is some function of your current distribution $-$ generally some integral of the current density times some polynomial of the position's cartesian coordinates $-$ not unlike the dipole moment,

*$\mathrm{property}_\ell[\mathbf B]$ is the magnetic or electric field, or some combination of its derivatives,

*the sum goes from the dipole case $\ell=1$ upwards, and most importantly

*if your circuit is small enough compared to the length-scale of the variation of the external field, then the sum is dominated by the dipole component, so long as the dipole moment is nonzero.

That's plenty to earn a central place in the theory.


text:
Q: House roaming profiles on realm trusted samba server? Raison D'être
I am attempting, so far unsuccessfully, to house roaming profiles for an Active Directory domain on a realm trusted Ubuntu 12.04LTS ZFS-on-Linux file server. The end goal is to have an inter-operable file server to house autofs nfs home directories for Linux and roaming profiles for Windows. It is politically difficult for me to do this purely with Windows Servers or joining Linux servers into Active Directory. As such, I am looking for technical solutions or proof that such technical solutions are less tenable than fighting political battles.
I suspect my current difficulty has something to do with the windows client to samba interactions rather than zfs, but I'm a bit out of my depth, so I'm not ruling it completely out. Could you, dear reader, point out why what I'm doing is incorrect and explain the correct procedure?

What I think I know

*

*The user can successfully log onto the client machine from the kerberos realm. However, the user is logged in with a temporary profile.

*A profile folder is created (presumably by login process) on the file server, but no other files are made in that newly created profile folder.

*The profile folder is created automatically with the proper owner/group.

*Given that, it seems unlikely the the profile is loaded before the credential cache is instantiated or the krbtgt is granted.

*While logged into the temporary profile, the user can create files on the file server without having to supply the file server with any (additional) credentials. That is there is no prompt. These files are also created with the proper owner/group.

Additional Information
This is all the configuration I think you'll want to know about, but I could be wrong.
I apologize for not finding a way to have it be collapsible.
A Brief Overview of Systems and Machines Involved
AD domain: ad.example.com  (Functional Level 2012)
domain controllers: dc1.ad.example.com, dc2.ad.example.com (OS: Windows Server 2012 Std)
mit-krb5 realm: EXAMPLE.COM
mit-krb5 kdcs: kdc1.example.com, kdc2.example.com (mit-krb5: 1.9.4)
smb/cifs server: zfs.example.com  (OS: Ubuntu 12.04LTS)
client: client.ad.example.com (OS: Windows 8 Enterprise)

The Samba Log
root@zfs:~# cat /var/log/samba/client.log
[2013/06/14 14:37:26.194496,  0] param/loadparm.c:9114(process_usershare_file)
  process_usershare_file: stat of /var/lib/samba/usershares/tank_test failed. Permission denied
[2013/06/14 14:37:26.460344,  0] param/loadparm.c:9114(process_usershare_file)
  process_usershare_file: stat of /var/lib/samba/usershares/tank_test failed. Permission denied
[2013/06/14 14:44:04.352344,  0] param/loadparm.c:9114(process_usershare_file)
  process_usershare_file: stat of /var/lib/samba/usershares/tank_test failed. Permission denied

Not sure what it's complaining about...
root@zfs:~# ls -l /var/lib/samba/usershares/tank_test
-rw-r--r-- 1 root root 110 Jun 14 12:57 /var/lib/samba/usershares/tank_test

The File Server Share Pre-login
root@zfs:~# ls -la /tank/test/
total 38
drwxrwxrwt 2 root root 2 Jun 14 09:12 .
drwxr-xr-x 5 root root 5 Jun 13 15:52 ..

File Server Share Post-login:
root@zfs:~# ls -la /tank/test/
total 57
drwxrwxrwt 3 root root 3 Jun 14 09:16 .
drwxr-xr-x 5 root root 5 Jun 13 15:52 ..
drwxr-xr-x 2 user user 2 Jun 14 09:16 user.V2
root@zfs:~# find /tank/test
/tank/test
/tank/test/user.V2/

User's Credential Cache upon Login
Current LogonId is 0:0x6c79e3

Cached Tickets: (7)

#0> Client: user @ EXAMPLE.COM
    Server: krbtgt/EXAMPLE.COM @ EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x60a90000 -> forwardable forwarded renewable pre_authent name_canonicalize 0x80000
    Start Time: 6/14/2013 14:44:24 (local)
    End Time:   6/15/2013 2:44:24 (local)
    Renew Time: 6/21/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0x2 -> DELEGATION
    Kdc Called: kdc2.example.com

#1> Client: user @ EXAMPLE.COM
    Server: krbtgt/AD.EXAMPLE.COM @ EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x40a90000 -> forwardable renewable pre_authent name_canonicalize 0x80000
    Start Time: 6/14/2013 14:44:24 (local)
    End Time:   6/15/2013 2:44:24 (local)
    Renew Time: 6/14/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0
    Kdc Called: kdc2.example.com

#2> Client: user @ EXAMPLE.COM
    Server: krbtgt/EXAMPLE.COM @ EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x40e10000 -> forwardable renewable initial pre_authent name_canonicalize
    Start Time: 6/14/2013 14:44:24 (local)
    End Time:   6/15/2013 2:44:24 (local)
    Renew Time: 6/21/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0x1 -> PRIMARY
    Kdc Called: kdc2.example.com

#3> Client: user @ EXAMPLE.COM
    Server: ldap/dc1.ad.example.com @ AD.EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x40a50000 -> forwardable renewable pre_authent ok_as_delegate name_canonicalize
    Start Time: 6/14/2013 14:44:31 (local)
    End Time:   6/15/2013 0:44:31 (local)
    Renew Time: 6/14/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0
    Kdc Called: dc1.ad.example.com

#4> Client: user @ EXAMPLE.COM
    Server: LDAP/dc1.ad.example.com/ad.example.com @ AD.EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x40a50000 -> forwardable renewable pre_authent ok_as_delegate name_canonicalize
    Start Time: 6/14/2013 14:44:25 (local)
    End Time:   6/15/2013 0:44:25 (local)
    Renew Time: 6/14/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0
    Kdc Called: dc1.ad.example.com

#5> Client: user @ EXAMPLE.COM
    Server: cifs/dc1.ad.example.com @ AD.EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x40a50000 -> forwardable renewable pre_authent ok_as_delegate name_canonicalize
    Start Time: 6/14/2013 14:44:24 (local)
    End Time:   6/15/2013 0:44:24 (local)
    Renew Time: 6/14/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0
    Kdc Called: dc1.ad.example.com

#6> Client: user @ EXAMPLE.COM
    Server: cifs/zfs.example.com @ EXAMPLE.COM
    KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96
    Ticket Flags 0x40a90000 -> forwardable renewable pre_authent name_canonicalize 0x80000
    Start Time: 6/14/2013 14:44:24 (local)
    End Time:   6/15/2013 2:44:24 (local)
    Renew Time: 6/14/2013 14:44:24 (local)
    Session Key Type: AES-256-CTS-HMAC-SHA1-96
    Cache Flags: 0
    Kdc Called: kdc2.example.com

The REALM Trust
ldapsearch -h ad.example.com -LLL cn=EXAMPLE.COM  objectClass trustPartner instancetype trustDirection trustAttributes
SASL/GSSAPI authentication started
SASL username: user@EXAMPLE.COM
SASL SSF: 56
SASL data security layer installed.
dn: CN=EXAMPLE.COM,CN=System,DC=ad,DC=example,DC=com
objectClass: top
objectClass: leaf
objectClass: trustedDomain
instanceType: 4
trustDirection: 3
trustPartner: EXAMPLE.COM
trustAttributes: 1

The Active Directory User
ldapsearch -h ad.example.com -LLL samaccountname=user profilePath altSecurityIdentities
SASL/GSSAPI authentication started
SASL username: user@EXAMPLE.COM
SASL SSF: 56
SASL data security layer installed.
dn: CN=Test User,OU=managed users,DC=ad,DC=example,DC=com
profilePath: \\zfs.example.com\tank_test\user
altSecurityIdentities: Kerberos:user@EXAMPLE.COM

The Basic ZFS information
root@zfs:~#  zfs get mountpoint,casesensitivity,sharesmb,available tank/test
NAME       PROPERTY         VALUE        SOURCE
tank/test  mountpoint       /tank/test   default
tank/test  casesensitivity  mixed        -
tank/test  sharesmb         on           local
tank/test  available        26.1T        -

ZFS created smb share
    root@zfs:~# cat /var/lib/samba/usershares/tank_test
    #VERSION 2
    path=/tank/test
    comment=Comment: /tank/test
    usershare_acl=S-1-1-0:F
    guest_ok=n
    sharename=tank_test
The Samba Configuration
root@zfs:~# grep -v -e ^$ -e ^\; -e ^# /etc/samba/smb.conf
[global]
   workgroup = EXAMPLE.COM
   server string = %h server (Samba, Ubuntu)
   dns proxy = no
   log file = /var/log/samba/%M.log
   max log size = 1000
   syslog = 3
   panic action = /usr/share/samba/panic-action %d
security = ADS
realm = EXAMPLE.COM
kerberos method = system keytab
map to guest = bad user

The File Server's Keytab
root@zfs:~# ktutil
ktutil:  rkt /etc/krb5.keytab
ktutil:  list -e
slot KVNO Principal
---- ---- ---------------------------------------------------------------------
   1    2  host/zfs.example.com@EXAMPLE.COM (aes256-cts-hmac-sha1-96)
   2    2  host/zfs.example.com@EXAMPLE.COM (aes128-cts-hmac-sha1-96)
   3    2  host/zfs.example.com@EXAMPLE.COM (arcfour-hmac)
   4    2   nfs/zfs.example.com@EXAMPLE.COM (aes256-cts-hmac-sha1-96)
   5    2   nfs/zfs.example.com@EXAMPLE.COM (aes128-cts-hmac-sha1-96)
   6    2   nfs/zfs.example.com@EXAMPLE.COM (arcfour-hmac)
   7    2  cifs/zfs.example.com@EXAMPLE.COM (aes256-cts-hmac-sha1-96)
   8    2  cifs/zfs.example.com@EXAMPLE.COM (aes128-cts-hmac-sha1-96)
   9    2  cifs/zfs.example.com@EXAMPLE.COM (arcfour-hmac)

The Server's Identity Mapping (via sssd)
root@zfs:~# cat /etc/sssd/sssd.conf
# SSSD configuration generated using /usr/lib/sssd/generate-config
[sssd]
config_file_version = 2
reconnection_retries = 3
sbus_timeout = 30
services = nss, pam
domains = example.com
[nss]
filter_groups = root
filter_users = root
reconnection_retries = 3
[pam]
reconnection_retries = 3
[domain/example.com]
enumerate = false
cache_credentials = true
id_provider = ldap
auth_provider = krb5
chpass_provider = krb5
ldap_uri = ldap://ldap.example.com
ldap_search_base = dc=example,dc=com
ldap_tls_reqcert = demand
ldap_tls_cacert = /etc/ssl/certs/ca-certificates.crt
krb5_kdcip = kerberos.example.com
krb5_realm = EXAMPLE.COM
krb5_changepw_principle = kadmin/changepw
krb5_auth_timeout = 15

The Server's (Relavent) Packages
root@zfs:~# uname -a
Linux zfs 3.5.0-23-generic #35~precise1-Ubuntu SMP Fri Jan 25 17:13:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
root@zfs:~# dpkg --get-selections | grep -e samba -e zfs -e krb -e sssd
krb5-config                                     install
krb5-locales                                    install
krb5-user                                       install
libgssapi-krb5-2                                install
libkrb5-26-heimdal                              install
libkrb5-3                                       install
libkrb5support0                                 install
libpam-krb5                                     install
libzfs1                                         install
samba                                           install
samba-common                                    install
samba-common-bin                                install
samba-tools                                     install
sssd                                            install
ubuntu-zfs                                      install
zfs-dkms                                        install
zfsutils                                        install

A: By default Windows clients must verify a roaming profile folders ACLs by using use SIDs when loading the roaming profiles. Even having the Active Directory user with the same uid, uidNumber, gidNumber and a proper altSecurityIdentites attribute is insufficient.
While the SID requirement cannot be disabled. The ACL check itself can be. The folder must still be readable by either the user or the Administrators group.
Under Server 2012 this policy is called
Do not check for user ownership of Roaming Profile Folders
and is found at
Computuer Configuration \ Administrative Templates \ System \ User Profiles

I should have looked at the Windows client logs earlier; I've not no excuse for that.
Windows log: Windows could not load your roaming profile and is attempting to log you on with your local profile. Changes to the profile will not be copied to the server when you log off. Windows could not load your profile because a server copy of the profile folder already exists that does not have the correct security. Either the current user or the Administrators group must be the owner of the folder.


text:
Q: LXC Container Networking I just started to experiment with LXC containers. I was able to create a container and start it up but I cannot get dhcp to assign the container an IP address. If I assign a static address the container can ping the host IP but not outside the host IP.
The host is CentOS 6.5 and the guest is Ubuntu 14.04LTS.  I used the template downloaded by lxc-create -t download -n cn-01 command.
If I am trying to get an IP address on the same subnet as the host I don't believe I should need the IP tables rule for masquerading but I added it anyways.  Same with IP forwarding.
I compiled LXC by hand from the following source https://linuxcontainers.org/downloads/lxc-1.0.4.tar.gz
Host Operating System Version
#> cat /etc/redhat-release
CentOS release 6.5 (Final)

#> uname -a
Linux localhost.localdomain 2.6.32-431.20.3.el6.x86_64 #1 SMP Thu Jun 19 21:14:45 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

Container Config
#> cat /usr/local/var/lib/lxc/cn-01/config
# Template used to create this container: /usr/local/share/lxc/templates/lxc-download
# Parameters passed to the template:
# For additional config options, please look at lxc.container.conf(5)

# Distribution configuration
lxc.include = /usr/local/share/lxc/config/ubuntu.common.conf
lxc.arch = x86_64

# Container specific configuration
lxc.rootfs = /usr/local/var/lib/lxc/cn-01/rootfs
lxc.utsname = cn-01

# Network configuration
lxc.network.type = veth
lxc.network.flags = up
lxc.network.link = br0

LXC default.confu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:12:30:f2 brd ff:ff:ff:ff:f

#> cat /usr/local/etc/lxc/default.conf
lxc.network.type = veth
lxc.network.link = br0
lxc.network.flags = up

#> lxc-checkconfig
Kernel configuration not found at /proc/config.gz; searching...
Kernel configuration found at /boot/config-2.6.32-431.20.3.el6.x86_64
--- Namespaces ---
Namespaces: enabled
Utsname namespace: enabled
Ipc namespace: enabled
Pid namespace: enabled
User namespace: enabled
Network namespace: enabled
Multiple /dev/pts instances: enabled

--- Control groups ---
Cgroup: enabled
Cgroup namespace: enabled
Cgroup device: enabled
Cgroup sched: enabled
Cgroup cpu account: enabled
Cgroup memory controller: /usr/local/bin/lxc-checkconfig: line 103: [: too many arguments
enabled
Cgroup cpuset: enabled

--- Misc ---
Veth pair device: enabled
Macvlan: enabled
Vlan: enabled
File capabilities: /usr/local/bin/lxc-checkconfig: line 118: [: -gt: unary operator expected

Note : Before booting a new kernel, you can check its configuration
usage : CONFIG=/path/to/config /usr/local/bin/lxc-checkconfig

Network Config (HOST)
#> cat /etc/sysconfig/network-scripts/ifcfg-br0
DEVICE=br0
TYPE=Bridge
BOOTPROTO=dhcp
ONBOOT=yes

#> cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
ONBOOT=yes
TYPE=Ethernet
IPV6INIT=no
USERCTL=no
BRIDGE=br0

#> cat /etc/networks
default 0.0.0.0
loopback 127.0.0.0
link-local 169.254.0.0

#> ip a s
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:12:30:f2 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::20c:29ff:fe12:30f2/64 scope link
       valid_lft forever preferred_lft forever
3: pan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN
    link/ether 42:7e:43:b3:61:c5 brd ff:ff:ff:ff:ff:ff
4: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
    link/ether 00:0c:29:12:30:f2 brd ff:ff:ff:ff:ff:ff
    inet 10.60.70.121/24 brd 10.60.70.255 scope global br0
    inet6 fe80::20c:29ff:fe12:30f2/64 scope link
       valid_lft forever preferred_lft forever
12: vethT6BGL2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether fe:a1:69:af:50:17 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::fca1:69ff:feaf:5017/64 scope link
       valid_lft forever preferred_lft forever

#> brctl show
bridge name bridge id       STP enabled interfaces
br0     8000.000c291230f2   no      eth0
                        vethT6BGL2
pan0        8000.000000000000   no

#> cat /proc/sys/net/ipv4/ip_forward
1

# Generated by iptables-save v1.4.7 on Fri Jul 11 15:11:36 2014
*nat
:PREROUTING ACCEPT [34:6287]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
# Completed on Fri Jul 11 15:11:36 2014

Network Config (Container)
#> cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

#> ip a s
11: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 02:69:fb:42:ee:d7 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::69:fbff:fe42:eed7/64 scope link
       valid_lft forever preferred_lft forever
13: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever

A: This is a limitation of virtualized network you're using under VMware. Bridge adds a possibility for virtual machine to appear on the network with it's own MAC. But hypervisor know nothing about these additional MAC-s. Under VirtualBox it can be resolved by going into VM's Network settings and allowing Promiscuous Mode on bridged interface. Similar option exists for VMware involving setting permissions on vmnet interface(s).
You can also create a new VM in VirtualBox using existing disk VMDK file from VMware.

A: Try this: (source: http://www.linuxfoundation.org/collaborate/workgroups/networking/bridge#No_traffic_gets_trough_.28except_ARP_and_STP.29)
No traffic gets trough (except ARP and STP)
Your kernel might have ethernet filtering (ebtables, bridge-nf, arptables) enabled, and traffic gets filtered. The easiest way to disable this is to go to /proc/sys/net/bridge. Check if the bridge-nf-* entries in there are set to 1; in that case, set them to zero and try again.
 cd /proc/sys/net/bridge
 ls bridge-nf-call-arptables bridge-nf-call-iptables bridge-nf-call-ip6tables bridge-nf-filter-vlan-tagged
 for f in bridge-nf-*; do echo 0 > $f; done


text:
Q: How to echo an array only if it has values in php? I run a foreach loop, where some of the loops contain nothing into the following variables, they are empty.
However, the "hi world" is echoed always.
How can I show the "hello world" only if at least one of the $row['utm_source'],$row['utm_medium'],$row['utm_campaign'] has a value?
$arr = array($row['utm_source'],$row['utm_medium'],$row['utm_campaign']);

if (!empty($arr)) {
    echo "hi world";
}

A: You an do it using count() and array_filter() :-
$arr = array($row['utm_source'],$row['utm_medium'],$row['utm_campaign']);

if (count(array_filter($arr))>0) {
  echo "hi world";
}

A: You can use two methods:
1. implode + trim
implode joins the array items if they are strings together with the provided delimiter.
if( trim(implode("", $arr)) !== ""){
    echo "hi world";
}

2. array_filter
array_filter returns the items which returns true to the provided callback function.
$arr = array_filter($arr, function($d) { return trim($d) !== ""; });

if(count($arr)){
   echo "hi world";
}

A: Here is a rough way you can do it
<?php
$row = array();
$row['utm_source'] = null;
$row['utm_medium'] = null;
$row['utm_campaign'] = 1;
foreach ($row as $key => $value) {
        if(isset($key)){
        echo 'Hello';
        break;
    }
}

Here's the eval link
Also you can check it by
if (!empty($row['utm_source'])) {...}


text:
Q: Use imported javascript function in HTML What i'm trying to do is have a button that, when clicked, calls an ajax function that will add an element to the document. I started using modules in my project because I find it "cleaner" than just have files using the same scope, but i have a hard time understanding how some things works.
So I have something like this:
html:
<button onclick="addEvent(this, dayPlanningId)">+</button>


text:
Q: WARNING: No file found for: /sign I am trying to run the App Engine Tutorial available on https://developers.google.com/appengine/docs/java/gettingstarted/usingjsps . As asked by the tutorial, I have mapped the new servlet SignGuestbookServlet.java to the url-pattern "/sign" in web.xml but when I try to access the resource on localhost:8888/sign, I get a 404 error.
Web.xml:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
    <servlet-name>SignGuestbookServlet</servlet-name>
    <servlet-class>guestbook.SignGuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SignGuestbookServlet</servlet-name>
    <url-pattern>/sign</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>Guestbook</servlet-name>
    <servlet-class>guestbook.GuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Guestbook</servlet-name>
    <url-pattern>/guestbook</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>guestbook.jsp</welcome-file>
</welcome-file-list>
</web-app>

SignGuestbookServlet.java:
package guestbook;

import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class SignGuestbookServlet extends HttpServlet {

private static final Logger log = Logger.getLogger(SignGuestbookServlet.class.getName());

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
 resp.getWriter().println("Hello");
    /*UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    String content = req.getParameter("content");
    if (content == null) {
        content = "(No greeting)";
    }
    if (user != null) {
        log.info("Greeting posted by user " + user.getNickname() + ": " + content);
    } else {
        log.info("Greeting posted anonymously: " + content);
    }
    resp.sendRedirect("/guestbook.jsp");
    */
}
}

Any reason as to why this is happening? Any help will be appreciated.
P.S.: I am using the get method to send data from the form so I have used the doGet() instead of doPost().

A: The name of your Servlet class and the fully qualified name in your web.xml does NOT match. Your servlet class name is SignGuestbookServlet
public class SignGuestbookServlet extends HttpServlet

but in your web.xml it is specified as GuestbookServlet
<servlet-class>guestbook.GuestbookServlet</servlet-class>

Update your web.xml with the right servlet class name as mentioned here
<servlet-class>guestbook.SignGuestbookServlet</servlet-class>

A: There is nothing wrong with your Java code. The problem is that there are erroneous (extra) entries in your web.xml due to which you start the Local Development Server, there is an error and hence the context is not initialized correctly. As a result, though the server is running, you get an error when you try to access the /sign endpoint.
To fix the problem, do the following :
Currently your web.xml is shown below:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
   <servlet-name>SignGuestbookServlet</servlet-name>
   <servlet-class>guestbook.SignGuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>SignGuestbookServlet</servlet-name>
  <url-pattern>/sign</url-pattern>
</servlet-mapping>
<servlet>
   <servlet-name>Guestbook</servlet-name>
   <servlet-class>guestbook.GuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>Guestbook</servlet-name>
   <url-pattern>/guestbook</url-pattern>
</servlet-mapping>
<welcome-file-list>
   <welcome-file>guestbook.jsp</welcome-file>
</welcome-file-list>
</web-app>

Remove the entries for :
<servlet>
   <servlet-name>Guestbook</servlet-name>
   <servlet-class>guestbook.GuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>Guestbook</servlet-name>
   <url-pattern>/guestbook</url-pattern>
</servlet-mapping>

Your final web.xml should look like:
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
   <servlet-name>SignGuestbookServlet</servlet-name>
   <servlet-class>guestbook.SignGuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>SignGuestbookServlet</servlet-name>
  <url-pattern>/sign</url-pattern>
</servlet-mapping>

<welcome-file-list>
   <welcome-file>guestbook.jsp</welcome-file>
</welcome-file-list>
</web-app>

Save your web.xml. Stop the Local Server. Start the Local Server again. And all should be fine.


text:
Q: Using pycrypto PKCS#7 to create a signature I'm looking at the Apple docs for PassBook, and I need to:

*

*create a "PKCS #7 detached signature of the manifest file".

I'd ideally like to do this with Python and I'd ideally like to use pycrypto for the task, the trouble is, I can't find any example code on the web on how to do this, there's lots of code like this:
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA

message = 'To be encrypted'
h = SHA.new(message)

key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_v1_5.new(key)
ciphertext = cipher.encrypt(message+h.digest())

but not knowing enough about the specifics of PKCS#7, I don't know what I need to do...
Does anyone have any ideas?
Thanks

A: This works for me , I was trying to sign a string for NSDL,
from OpenSSL import crypto
import base64
try:
    p12 = crypto.load_pkcs12(open("/DSCPFX.pfx", 'rb').read(), "XXXX")
    # print("p12 : ", p12)
    signcert = p12.get_certificate()
    pkey = p12.get_privatekey()

    text = "This is the text to be signed"
    bio_in = crypto._new_mem_buf(text.encode())
    PKCS7_NOSIGS = 0x4
    pkcs7 = crypto._lib.PKCS7_sign(signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS)
    bio_out = crypto._new_mem_buf()
    crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7)

    sigbytes = crypto._bio_to_string(bio_out)

    signed_data = base64.b64encode(sigbytes)
    return SUCCESS, signed_data
except Exception as err:
    print("Exception happens in sign_data and error is: ", err)
    return 0, str(err)

A: With a lot of help from this answer, I did it!
I know op probably moved past this, but this answer is nowhere in the internet, so here's the solution, for posterity's sake!
from OpenSSL import crypto

with open(cert) as cert_file:
    cert_buf = cert_file.read()

with open(key) as key_file:
    key_buf = key_file.read()

pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_buf)
signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_buf)

bio_in = crypto._new_mem_buf(text.encode())
PKCS7_NOSIGS = 0x4  # defined in pkcs7.h
pkcs7 = crypto._lib.PKCS7_sign(signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS)  # noqa
bio_out = crypto._new_mem_buf()
crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7)
sigbytes = crypto._bio_to_string(bio_out)

Keep in mind, it uses some undocumented pyopenssl functions.

A: cryptography package (version 3.2+) can do this without using undocumented features:
https://cryptography.io/en/3.4.8/hazmat/primitives/asymmetric/serialization.html#cryptography.hazmat.primitives.serialization.pkcs7.PKCS7SignatureBuilder


text:
Q: Using Firefox with Selenium webdriver does not record history I am running FF 39 with python Selenium webdriver 2.47.
from selenium import webdriver
profile = webdriver.FirefoxProfile('C:\\Users\\Mike\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\kgbrptal.default')
b = webdriver.Firefox(profile)

In C:\Users\Mike\AppData\Roaming\Mozilla\Firefox\Profiles\kgbrptal.default\places.sqlite I should see history updated. But nothing get updated?
I am expecting all actions been recorded in the profile database.

A: The Problem
The problem you're facing is that Selenium creates a new and temporary profile from the profile you tell it to use. It does this because it has to add an add-on that it uses to establish communication between the browser and your script. If it did not copy your profile to a new location, the add-on would be added to the profile you gave to Selenium. Many users would find this unacceptable. So it creates a new temporary profile from the one you specify and deletes it after it is done.
A Solution
There is no flag you can give it to prevent the deletion of the temporary profile. However, you could save it before calling the .quit() method. The code that deletes the temporary profile goes:
        try:
            shutil.rmtree(self.profile.path)
            if self.profile.tempfolder is not None:
                shutil.rmtree(self.profile.tempfolder)
        except Exception as e:
            print(str(e))

If you assigned your WebDriver to b, you could do:
shutil.copytree(b.profile.path, "where/you/want/to/save/it",
                ignore=shutil.ignore_patterns("parent.lock",
                                              "lock", ".parentlock"))
b.quit()

The ignore is needed to avoid copying some lock files that would cause the copy to fail.
Here's a complete example:
import shutil
from selenium import webdriver

profile = webdriver.FirefoxProfile(path_to_your_profile)
driver = webdriver.Firefox(profile)
driver.get("http://google.com")
shutil.copytree(driver.profile.path, "./here",
                ignore=shutil.ignore_patterns("parent.lock",
                                              "lock", ".parentlock"))
driver.quit()

You need to set path_to_your_profile to the actual path. It will copy the temporary profile to a subdirectory named here in the current working directory of the script.


text:
Q: Opencv4Android Unsatisfied Linker Error Moments I am getting the following error when I try to run my android application:
java.lang.UnsatisfiedLinkError: No implementation found for double[] org.opencv.imgproc.Imgproc.moments_1(long) (tried Java_org_opencv_imgproc_Imgproc_moments_11 and Java_org_opencv_imgproc_Imgproc_moments_11__J)
Here is the code where the problem is occurring:
  Imgproc.findContours(temp, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    if(contours.size() > 0) {
        int numObjects = contours.size();

        if (numObjects < MAX_OBJECTS) {

            for (int i = 0; i < contours.size(); i++) {
                //moments causing unsatisfied linker error
                Moments moment = Imgproc.moments((Mat)contours.get(i));
                double area = moment.m00;
            }
        }
    }

Can anyone help me with this problem? Thanks in advance!

A: This seems to be an omission bug with some of the native libs for OpenCV 3.0 and 3.1.   Until fixed, the suggested workaround is to use java code to calculate the moments.  See this thread.


text: Q: Monitoring SignalR Core message size I am looking for a way to monitor the exact size of each message sent through an aspnetCORE SignalR hub (both directions). I tried to use DI, middleware, HubDispatcher including inheriting IHubProtocol in HubConnectionContext since it seemed the most reasonable solution but had no result. All the other approaches I found may suit for the old SignalR but not for the netcore's one. Client's monitoring also won't do. Does someone have hands-on experience, at least using some Prometheus exporter?


text:
Q: return of ThreadPoolExecutor to array of tasks Below is an  example code I got from https://tutorialedge.net/python/concurrency/python-threadpoolexecutor-tutorial/
from concurrent.futures import ThreadPoolExecutor
import threading
import random

taskarr = []

def task(n,c):
    print("Executing our Task = {} and {}".format(n,c))
    print("Task Executed {}".format(threading.current_thread()))

def main():
    executor = ThreadPoolExecutor(max_workers=3)
    task1 = executor.submit(task(1,'A'))
    task2 = executor.submit(task(2,'B'))

if __name__ == '__main__':
    main()

in this, if executor.submit is returned to simple variable task1, it works. But my requirement is to return it to an array. so when i do,
    taskarr[0] = executor.submit(task(1,'A'))
it throws error as,
TypeError: 'function' object does not support item assignment

A: I could not reproduce your TypeError; apparently you have some more code that you did not show us. As rocksportrocker pointed out in their comment, you can't assign values to an index that does not yet exist, as in your attempt to assign the future returned from executor.submit() to index 0 of the empty list typearr. This will raise the mentioned IndexError.
However, I could produce some TypeError and that is due to the fact that you call submit incorrectly.
The Executor documentation defines the parameter fn to be a callable object, e.g. a function. Now, when you call submit like you do:
executor.submit(task(1,'A'))

task(1,'A') is executed in your main thread and its return value (None in your case) is then passed to the pool thread. The pool thread then tries to execute None(1, 'A') and raises a TypeError: 'NoneType' object is not callable, which you don't see, because it is wrapped in the future. You would see it if you called task1.result().
That means, that it is your main thread that executes your task instead of your pool threads, as should have become visible from your second print statement in task:
Task Executed <_MainThread(MainThread, started 11064)>

In order to have your pool threads do the work, you need to pass the function object task to executor.submit, like so:
taskarr = []

def task(n,c):
    print("Executing our Task = {} and {}".format(n,c))
    time.sleep(3)  # added this to make sure that two different threads from the pool get a task
    print("Task Executed {}".format(threading.current_thread()))

def main():
    executor = ThreadPoolExecutor(max_workers=3)
    taskarr.append(executor.submit(task, 1,'A'))
    taskarr.append(executor.submit(task, 2,'B'))
    # to show that the main thread continues to execute
    # while the pool threads work on the tasks
    print("{}: tasks submitted".format(threading.current_thread().name))

if __name__ == '__main__':
    main()

Output:
Executing our Task = 1 and A
Executing our Task = 2 and B
MainThread: tasks submitted
Task Executed <Thread(ThreadPoolExecutor-0_0, started daemon 12192)>
Task Executed <Thread(ThreadPoolExecutor-0_1, started daemon 11800)>


text:
Q: Запись в .txt файл переменой типа long Подскажите, как записать в файл данные переменой finish.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Speed {

    private static long finish;

    public static void main(String[] args) {
        List<Integer> linkedList =new LinkedList<>();
        List<Integer> arrayList = new ArrayList<>();
        timeSpead(linkedList);
        timeSpead(arrayList);
        System.out.println(finish);
        // запись в файл text.txt переменной finish
    }

    public static void timeSpead(List<Integer>list) {
        long start = System.currentTimeMillis();
        for(int i = 0; i < 1000000; i++)
            list.add(i);
        long end = System.currentTimeMillis();
        finish = end - start;
        System.out.println(finish);
    }
}

A: Вот например как можно записать long в файл:
public static void main(String[] args) throws IOException
{
    long[] latency = { 123456789000L, 234567890000L, 345678901000L };

    BufferedWriter out = new BufferedWriter(new FileWriter("latency.txt"));
    for (int i = 0; i < 3; ++i) {
        out.write(latency[i] + "\n");
    }
    out.close();
}

B вашем случае можно вынести необходимый функционал в отдельную функцию и передавать в нее данные. Либо второй вариант:
public static void main(String[] args) throws Exception {
    FileOutputStream fos = new FileOutputStream("C:/WriteLong.txt");
    DataOutputStream dos = new DataOutputStream(fos);

    long l = 65;
    dos.writeLong(l);

    for (int i = 0; i < 10; i++)
      dos.writeInt(i);

    dos.close();
  }

Вот первоисточники и подобные вопросы на enSO: 1, 2 и 3.


text:
Q: How to get my register taxonomy My taxonomy
    register_taxonomy(
        'king_blog_category',
        'king_blogs',
         array(
            "hierarchical"          => true,
            "label"                 => "King blog Category",
            "singular_label"        => "label of taxonomy",
            'update_count_callback' => '_update_post_term_count',
            'query_var'             => true,
            'rewrite'               => array(
                'slug'              => 'king_blog_category',
                'with_front'        => true
            ),
            'public'                => true,
            'show_ui'               => true,
            'show_tagcloud'         => true,
            '_builtin'              => true,
            'show_in_nav_menus'     => true
        )
    );

//Get method
//1:
$taxonomy = 'king_blog_category';
$tax_terms = get_terms($taxonomy);

//2 :
$taxonomy = 'king_blog_category';
$tax_terms = get_terms($taxonomy, array('hide_empty' => 0, 'parent' =>0));

//Result :
array([invalid_taxonomy] => array([0] => Invalid taxonomy.))

A: get_terms first and only parameter should be an array. docs
get_terms([
    'taxonomy' => 'king_blog_category',
    'hide_empty' => 0,
    'parent' => 0
]);


text:
Q: Can a replacement iPad screen be used on a BeagleBoard? I have been trying to find a good touchscreen with multitouch support for the BeagleBoard. I have not had much success, but have noticed that iPad replacement screens are available fairly inexpensively. Is it possible to use one of these as the display/touchscreen for a BeagleBoard?

A: I assume you are talking about this touch screen:
http://www.repairsuniverse.com/ipad-2-touch-screen-digitizer-replacement.html
However, without the touch screen controller, it is basically useless. That's because a special controller chip is required to perform the high speed capacitance measurements.
Take a look at this touch screen from 3M (one of the few capacitive touch screens on digi-key, but there are many more out there)
http://search.digikey.com/us/en/products/17-8031-205/3M5745-ND/1886090
It requires this controller module:
Digikey part No: 3M9138-ND
I'm willing to bet that controllers are rarely compatible with other touch pannels becuase of the variety of technologies out there.
Also note that Cypress makes a line of capacitive touch screen controllers, called TrueTouch.


text:
Q: Shrink root partition How is possible to shrink root partition on VPS (without unmount).
df -h command:
Filesystem              Size  Used Avail Use% Mounted on
udev                    485M     0  485M   0% /dev
tmpfs                   100M  7.9M   92M   8% /run
/dev/mapper/vg-lv_root   19G  1.2G   17G   7% /
tmpfs                   496M     0  496M   0% /dev/shm
tmpfs                   5.0M     0  5.0M   0% /run/lock
tmpfs                   496M     0  496M   0% /sys/fs/cgroup
/dev/sda1               236M   37M  187M  17% /boot
tmpfs                   100M     0  100M   0% /run/user/0

fdisk -l command:
Disk /dev/sda: 20 GiB, 21474836480 bytes, 41943040 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xdfc30638

Device     Boot    Start      End  Sectors  Size Id Type
/dev/sda1           2048   499711   497664  243M 83 Linux
/dev/sda2         499712 20971519 20471808  9.8G 8e Linux LVM
/dev/sda3       20971520 41943039 20971520   10G 8e Linux LVM

Disk /dev/mapper/vg-lv_root: 18.8 GiB, 20136853504 bytes, 39329792 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/mapper/vg-lv_swap: 1 GiB, 1073741824 bytes, 2097152 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

I would like to create 12 GB partition from root partition and then root partition should have 7 GB.
I know that I may lost data.


text:
Q: .Net 4.0 WCF Service failing when passing parameters I am trying to test a WCF service using the basichttpbinding endpoint from the WCF test client. I can test methods that I don't pass parameters to with no issue, but when I need to pass a parameter I get the following error:

Failed to invoke the service. Possible
  causes: The service is offline or
  inaccessible; the client-side
  configuration does not match the
  proxy; the existing proxy is invalid.
  Refer to the stack trace for more
  detail. You can try to recover by
  starting a new proxy, restoring to
  default configuration, or refreshing
  the service.
An error occurred while executing the
  command definition. See the inner
  exception for details.
Server stack trace:     at
  System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message
  reply, MessageFault fault, String
  action, MessageVersion version,
  FaultConverter faultConverter)    at
  System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
  operation, ProxyRpc& rpc)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway,
  ProxyOperationRuntime operation,
  Object[] ins, Object[] outs, TimeSpan
  timeout)    at
  System.ServiceModel.Channels.ServiceChannel.Call(String
  action, Boolean oneway,
  ProxyOperationRuntime operation,
  Object[] ins, Object[] outs)    at
  System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime
  operation)    at
  System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)
Exception rethrown at [0]:     at
  System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)    at
  System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)    at
  IErouter.GetClientSearch(String
  surname, String forename, String
  street, String postcode)    at
  ErouterClient.GetClientSearch(String
  surname, String forename, String
  street, String postcode)

Due to the fact I can make calls to parameterless methods this error makes no sense to me.
[ServiceContract]
public interface IErouter
{
    #region Client Search

    [OperationContract]
    SelectClientSearch_Result[] GetClientSearch(
        string surname, string forename, string street, string postcode);

    #endregion

    #region Changes

    [OperationContract]
    ChangeForBlackBerry[] GetClientChanges(string blackberryPin);

    [OperationContract]
    bool AcceptChange(int changeId, string blackberryPin);

    [OperationContract]
    bool AcknowledgeChange(int changeId, string blackberryPin);

    [OperationContract]
    ChangeForBlackBerry[] GetManagerChangesForShiftType(string blackberryPin,
        string date, int shiftTypeId);

    [OperationContract]
    ClientDetailChangeViewModel GetClientDetailChange(int changeId);

    #endregion

    #region Client Details

    [OperationContract]
    ClientDetailViewModel GetClientDetails(int clientId);

    [OperationContract]
    SelectUserLevel_Result GetUserLevel(string blackberryPin);

    #endregion

    #region Useful Contacts

    [OperationContract]
    SelectAdminCentreTelNo_Result[] GetAdminCentreTelNos();

    [OperationContract]
    string GetDutyEmail();

    [OperationContract]
    SelectDutyManager_Result[] GetDutyManagerTelNos();

    [OperationContract]
    string GetGhaHandyTelNo();

    [OperationContract]
    SelectHospitalNos_Result[] GetHospitalTelNos();

    [OperationContract]
    string GetICTTelNo();

    [OperationContract]
    string GetMAHMobileTelNo();

    [OperationContract]
    SelectMyManagerNo_Result[] GetMyManagerTelNo(string blackberryPin);

    [OperationContract]
    string GetNHSDirectTelNo();

    [OperationContract]
    string GetOOHEmail();

    [OperationContract]
    string GetOOHTelNo();

    [OperationContract]
    string GetOperationsEmail();

    [OperationContract]
    string GetOperationsTelNo();

    [OperationContract]
    string GetOtherHandyPersonTelNo();

    [OperationContract]
    SelectSWTelNos_Result[] GetSWTelNo();

    #endregion

    #region Gaurdian 24 Visit Monitoring

    [OperationContract]
    string StartVisitMonitoring(int clientId, int activityDuration,
        string activityText, string blackberryPin);

    [OperationContract]
    string StopVisitMonitoring(int clientId, string activityId,
        string blackberryPin);

    #endregion
}

A: It could be serialization error - check if you have [DataContract] or [Serializable] at your return class SelectClientSearch_Result.

A: It may be worth trying to add the following to the web.config:
<serviceHostingEnvironment>
    <baseAddressPrefixFilters>
        <add prefix="http://host:port"/>
    </baseAddressPrefixFilters>
</serviceHostingEnvironment>

If that doesn't work, you could try adding the above and removing the  elements: <host></host> (idea from the last link I've linked)
Just adding the following to the web.config may help.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

The sites I've read are:
http://msdn.microsoft.com/en-us/library/aa702682.aspx
http://msdn.microsoft.com/en-us/library/ms731336.aspx
http://community.discountasp.net/showthread.php?t=7719

One mentioned the WCF service behaving exactly like an ASMX service which is why I thought it may be relevant.
EDIT:
May be worth a quick read? http://support.microsoft.com/kb/958478

A: The error was coming from elsewhere in the application... WCF errors are not the greatest! :)


text:
Q: How to debug unhandle exception handling My current install of Visual Studio 2015 will not allow me to throw an unhandled exception while running code from the IDE. I want to exercise my unhandled exception code but my code:
Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
    Throw New System.Exception("An unhandled test exception has occurred.")
End Sub

only works during a normal runtime, not when the code is executed in the IDE.
How can I debug my unhandled exception code in the IDE?
I looked in Debug, Windows, Exception Settings but I don't see a way to do what I want to do. Is there another more global setting that will allow an unhandled exception without the IDE capturing the exception?

I'm using the ApplicationsEvents.vb to hook the event:
Namespace My

' The following events are available for MyApplication:
'
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
    Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
        ExpLog.LogUnhandledException(e, sender)
        e.ExitApplication = Not ExpLog.InformUser
    End Sub
End Class
End Namespace

Resolution was to create a test stub that exercised the code that was called by the handler:
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles btnMisc_Throw.Click

    If ExpLog.InformUser() Then
        MsgBox("Continue")
    Else
        MsgBox("End Program")
    End If

    ExpLog.LogMsgBox(New System.Exception("test unhandled exception"), "test LogMsgBox()",,, "programmer note")

End Sub

This doesn't allow for testing the handler but it does exercise the code the handler calls. Looking at some old comments I figured this out five+ years ago... :(

A: Add a handler to AppDomain.CurrentDomain.UnhandledException
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Throw New System.Exception("An unhandled test exception has occurred.")
End Sub

Public Shared Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
    MessageBox.Show(CType(args.ExceptionObject, Exception).Message)
End Sub


text:
Q: Django FOREIGN KEY constraint failed on OneToOneField So I've created 2 classes of models. One has an OneToOneField and this class was referenced by the other using the ForeignKey field. It returns an error whenever I save it even in Django admin.
Model classes
class First(models.Model):
  sample_field = models.OneToOneField(Person, on_delete=models.CASCADE, primary_key=True)

# This is where I suppose to add data.
class Second(models.Model):
  another_field = models.ForeignKey(First, on_delete=models.CASCADE, blank=True, null=True, related_name='sample_related_name')

Error Message
IntegrityError at /admin/management/group/add/
FOREIGN KEY constraint failed
Thank you!

A: So, I've just deleted the db.sqlite3, other migrations and migrated it again. It works fine!