Q: How to retrieve array in php sent from iOS Following is my iOS code that sends NSmutable Array to PHP webservice:
 // Getting Server Address
            AppDelegate *appDelegate =
            [[UIApplication sharedApplication] delegate];

            NSString *serverAddress = [appDelegate getServerAddress];

            serverAddress = [serverAddress stringByAppendingString:@"ABC.php"];

            NSLog(@"Server Address: %@",serverAddress);

            NSData *post = [NSJSONSerialization dataWithJSONObject:UsersArray options:NSJSONWritingPrettyPrinted error:nil];
            NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:serverAddress]];

            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:post];
            [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
            [request setTimeoutInterval:30];
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error){
                //Do whatever with return data

                NSString *result = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
                NSLog(@"Result : %@",result);
            }];

I want to retrive that array in PHP. How can I do that?
Here is the php which I tried but returns null:
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);

echo json_encode($decoded);

A: I use a slightly different Content-Type (which shouldn't matter):
[request addValue:@"text/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

And I use a slightly different PHP, too:
<?php

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

$json_data = json_decode($http_raw_post_data, true);

echo json_encode($json_data);

?>

If you're getting a blank response, I'd wager you have some PHP error. I'd you check out your server's error log, or temporarily changing the display_errors setting in your php.ini as follows:
display_errors = On


Q: WCF un-domain system I have developed WCF windows service using net tcp binding. Its working fine when wcf client and wcf service both on the same system.
Getting error when both system are in work group not - Client and Service are on different machines
please suggest what configuration i need to change .
SocketId:61017335 to remote address :8005 had a connection reset error.
Error :System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:58.9879193'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
I am using Certificate authentication - I know without a domain I lack the necessary Kerberos infrastuture to authenticate UPNs and SPNs but shouldn't that be resolved because I am using certificates.
Client’s Config File
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint kind="discoveryEndpoint" address="net.tcp://localhost:8005/Probe" binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding">
      </endpoint>
      <endpoint binding="netTcpBinding" bindingConfiguration="RequestReplyNetTcpBinding" contract="Test2ServLib.IService1" behaviorConfiguration="LargeEndpointBehavior">
        <identity>
          <dns value="WCFServer" />
        </identity>
      <!--The behaviorConfiguration is required to enable WCF deserialization of large data sets -->
      </endpoint>
    </client>
 <behaviors>
      <endpointBehaviors>
        <behavior name="disableEndpointDiscovery">
          <endpointDiscovery enabled="false" />
          <!--The behavior is required to enable WCF deserialization of large data sets -->
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <clientCredentials>
            <clientCertificate findValue="WCFClient"
                               storeLocation="LocalMachine"
                               storeName="TrustedPeople"
                               x509FindType="FindBySubjectName" />
                        <serviceCertificate >
                            <authentication certificateValidationMode="PeerTrust" revocationMode="NoCheck"/>
                        </serviceCertificate>
          </clientCredentials>
        </behavior>
        <behavior name="LargeEndpointBehavior">
          <!--The behavior is required to enable WCF deserialization of large data sets -->
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
            <clientCredentials>
              <clientCertificate findValue="WCFClient"
                                 storeLocation="LocalMachine"
                                 storeName="TrustedPeople"
                                 x509FindType="FindBySubjectName" />
                        <serviceCertificate >
                            <authentication certificateValidationMode="PeerTrust" revocationMode="NoCheck"/>
                        </serviceCertificate>
            </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <netTcpBinding>
        <binding name="RequestReplyNetTcpBinding" receiveTimeout="05:00:00" openTimeout="00:00:59" closeTimeout="00:00:59" maxBufferPoolSize="524288" maxBufferSize="25000000" maxConnections="50" maxReceivedMessageSize="25000000" sendTimeout="00:05:00" listenBacklog="1500">
          <reliableSession ordered="false" inactivityTimeout="00:01:00" enabled="true" />
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security>
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

Service Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="announcementBehavior">
      <!--The following behavior attribute is required to enable WCF serialization of large data sets -->
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
      <serviceDiscovery>
        <announcementEndpoints>
          <endpoint kind="announcementEndpoint"
        address="net.tcp://localhost:8005/Announcement"
        binding="netTcpBinding"
        bindingConfiguration="RequestReplyNetTcpBinding"/>
        </announcementEndpoints>
      </serviceDiscovery>
      <serviceThrottling
              maxConcurrentCalls="1500"
              maxConcurrentSessions="1500"
              maxConcurrentInstances="1500"/>
      <serviceCredentials>
        <serviceCertificate findValue="WCFServer"
                            storeLocation="LocalMachine"
                            storeName="TrustedPeople"
                            x509FindType="FindBySubjectName" />
        <clientCertificate>
          <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="LocalMachine" revocationMode="NoCheck"/>
        </clientCertificate>
      </serviceCredentials>
    </behavior>
 </serviceBehaviors>
 </behaviors>
 <service name="Test2ServLib.IService1"
   behaviorConfiguration="announcementBehavior">
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://localhost:8006/Service1"/>
      </baseAddresses>
    </host>
    <endpoint binding="netTcpBinding"
              bindingConfiguration="RequestReplyNetTcpBinding"
              contract="Test2ServLib.IService1"
              behaviorConfiguration="LargeEndpointBehavior" />
        <bindings>
            <netTcpBinding>
                <binding name = "RequestReplyNetTcpBinding">
                    <security>
                        <message clientCredentialType="Certificate" />
                    </security>
                </binding>
            </netTcpBinding>
        </bindings>
  </system.serviceModel>
</configuration>


Q: Android build failed and error message is "More than one file was found with OS independent path 'org/apache/pdfbox/debugger/real.png'" In my Android App I used pdfbox to generate PDF file. I was able to compile but when I build and try to deploy to a simulator. I got the following error message: "More than one file was found with OS independent path 'org/apache/pdfbox/debugger/real.png'". In my build.gradle file I include a libs path and all the jar were copy to libs path
compile fileTree(include: ['*.jar'], dir: 'libs')
// implementation 'libs/*.jar'
implementation files('libs/jfreechart-1.0.19.jar')

All the jars were included in the app/libs path
The following jars were included in the app/libs path
jfreechart-1.0.0.19 jar
pdfbox-2.0.13.jar
pdfbox-app-2.0.13.jar
pdfbox-debugger-2.0.13.jar
pdfbox-tools-2.0.13.jar


Q: MongoDb: Match value on foreign collection I have the collection USER:
{
    "_id" : ObjectId("5d64d2bf48dd17387d77d27a"),
    "name" : "John",
    "notifications" : {
        "email" : false,
        "sms" : true
    }
},
{
    "_id" : ObjectId("5da9586911e192081ee1c6be"),
    "name" : "Mary",
    "notifications" : {
        "email" : false,
        "sms" : false
    }
}

And this other collection ALERT:
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a551e"),
    "active" : true,
    "user_id" : ObjectId("5d64d2bf48dd17387d77d27a")
},
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a551f"),
    "active" : false,
    "user_id" : ObjectId("5d64d2bf48dd17387d77d27a")
},
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a552e"),
    "active" : true,
    "user_id" : ObjectId("5da9586911e192081ee1c6be")
},
{
    "_id" : ObjectId("5d54f04dbe5e6275e53a552f"),
    "active" : true,
    "user_id" : ObjectId("5da9586911e192081ee1c6be")
}

I want a MongoDB query that lists the documents on collection ALERT that have property "active" as TRUE and whose matching USER has element "sms" on property "notifications" as TRUE too.

A: You can use Uncorelated sub queries in $lookup

*

*$match to get the "notifications.sms": true

*$lookupto join two collections. We are assigning uId = _id from USER collection. Inside the pipeline, we use $match to find the active :true, and _id=uId
here is the script
db.USER.aggregate([
  {
    "$match": {
      "notifications.sms": true
    }
  },
  {
    "$lookup": {
      "from": "ALERT",
      "let": {
        uId: "$_id"
      },
      "pipeline": [
        {
          $match: {
            $and: [
              {
                active: true
              },
              {
                $expr: {
                  $eq: [
                    "$user_id",
                    "$$uId"
                  ]
                }
              }
            ]
          }
        }
      ],
      "as": "joinAlert"
    }
  }
])

Working Mongo playground


Q: xml extension type and user defined I've a xml document that according to its schema definition for a certain node "level" only allows a predefined list of values (aka enumeration if not wrong). This predefined values are ok for a country, but if we change country the values might change.
For this the "level" node allows ( and here starts my doubts) attribute "userDefined" and sub nodes such as <extension> and I believe is through this <extension> node or maybe userdefined attr that I will be able to specify other value and thus get the doc validated.
The xsd file is here: http://utdanning.no/schemas/CDM/2.1/CDM.xsd and the xml sample file here
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CDM xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://utdanning.no/schemas/CDM/2.1/CDM.xsd">
    <orgUnit>
        <orgUnitID>217</orgUnitID>
        <orgUnitName>Contoso Inc [TEST PURPOSES ONLY]</orgUnitName>
        <webLink>
            <href>http://www.google.com</href>
        </webLink>
        <course>
            <courseID>341</courseID>
            <courseCode>FWTEST2222222</courseCode>
            <courseName>Another field course test imported</courseName>
            <courseDescription>Testing purposes only test teste teste</courseDescription>
            <level level="other_value"/><!--This is where i want to add a diff value other than the allowed list: vgs, folkehogskole, bachelor, master, phd, fagskole, evu, aarsstudium -->
            <credits ECTScredits="45"/>
            <admissionInfo/>
            <teachingPlace>
                <adr>
                  <country>NORWAY</country>
                </adr>
            </teachingPlace>
            <formOfTeaching>Field course</formOfTeaching>
            <instructionLanguage>Norske</instructionLanguage>
        </course>
    </orgUnit>
</CDM>

A: This schema does not allow arbitrary values in the "level" attribute. There is no way to extend the set of valid values.


Q: Error Unknown FileSystem: Grub Rescue? I had a dual boot system for Windows 7 and Linux 10.10 . I am new to linux and hadnt upgraded it before ir reached its end-of-life. So I decided to delete the partition in which linux was installed and in the same session downloaded the latest linux version 12.04 using WUBI in windows. When I rebooted my computer, I get this error:
"Unknown Filesystem"
Grub Rescue >
I have seen other threads that involve making a livecd. As it turns out I have already installed the latest linux, so is there a way to get my PC to boot to either 12.04 Linux or Windows 7 without making a live CD

A: Latest Ubuntu is 13.04. You could make livecd (on USB for example) and install new Ubuntu on older one (don't forget to format old Ubuntu partition). Then when booting - GRUB should see both Ubuntu and Windows. Always worked for me.
I understand that you are not able to boot neither Linux nor Windows?


Q: Differentiating Between an AJAX Call / Browser Request Is there anything in the header of an HTTP request that would allow me to differentiate between an AJAX call and a direct browser request from a given client? Are the user agent strings usually the same regardless?

A: If you use Prototype, jQuery, Mootools or YUI you should find a X-Requested-With:XMLHttpRequest header which will do the trick for you. It should be possible to insert whatever header you like with other libraries.
At the lowest level, given a XMLHttpRequest or XMLHTTP object, you can set this header with the setRequestHeader method as follows:
xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

A: After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.


Q: Log4j properties | Create new log file with timestamp for every run I'm quite new to log4j and have managed to create the logs for my code.
But what I need is, a new file to be created for each run, rather than appending the logs to the same file.
Below are the properties I'm setting (found somewhere on google).
Please suggest changes, so that new file will be created with the timestamp after each run.
// Here we have defined root logger
log4j.rootLogger=INFO,R,HTML

// Here we define the appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.HTML=org.apache.log4j.FileAppender

// Here we define log file location
log4j.appender.R.File=./Logs/LastRunLog.log
log4j.appender.HTML.File=./Logs/LastRunLog.html

// Here we define the layout and pattern
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application log
log4j.appender.HTML.layout.LocationInfo=true

A: You can use a system property to set the log4j file names with it's value and give that property an unique value for each run.
Something like this on your starter class (timeInMillis and a random to avoid name clashes):
static {
    long millis = System.currentTimeMillis();
    System.setProperty("log4jFileName", millis+"-"+Math.round(Math.random()*1000));
}

And then you refer to the system property on log4j conf properties:
log4j.appender.R.File=./Logs/${log4jFileName}.log
log4j.appender.HTML.File=./Logs/${log4jFileName}.log

Hope it helps!

A: You need to write (or find) a custom appender which will create the file with a timestamp in the name.
The 3 defaults implementation for file logging in log4j are :

*

*FileAppender : One file logging, without size limit.

*RollingFileAppender : Multiple files and rolling file when current file hits the size limit

*DailyRollingFileAppender : A file per day

The simpliest way is to extend FileAppender and overwrite the setFile and getFile methods.

A: i think this answer would be helpful for you click here
i have ran code as the page said, and i got a new log file each time i start my application.
result like that :
and all code in my Test.java is :`
private static final Logger log = Logger.getLogger(Test.class);

public static void main(String[] args) {
    log.info("Hello World");
}

`


Q: How to select checkbox button and NavigationLink to another view independently in SwiftUI List row I hope to make a list just like to-do list, the cell has a checkbox and Text. And I want when list cell selected, the view could be translate to detailView. Meanwhile I also could select the checkbox, but don't trigger the view translate to the detailView.
I removed the List{}, the code run ok, but the List property and method can't use any more. So I plan to code a customer list view. But I don't think it will be the good method. So if I still can't find a good way to make it, I may implement in this way at last.
NavigationView {
     VStack {
        List {
                 ForEach(todayDietModel.todayDietItems) { item in
                     NavigationLink(destination: DietItemDetailView()) {
                            TodayDietRow(todayDietItem: item)
                                .animation(.spring())
                        }
                    }
                }

            }
            .frame(width: 352, height: 400)
            .background(Color.white)
            .cornerRadius(16)

}

struct TodayDietRow: View {
   @State var isFinished: Bool = false

    var body: some View {
        HStack(spacing: 20.0) {
            Button(action: {self.isFinished.toggle()}) {
                if self.isFinished {
                    Image("icon_checked_s001")
                        .resizable()
                        .renderingMode(.original)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 24, height: 24)
                } else {
                    Image("icon_unchecked_s001")
                        .resizable()
                        .frame(width: 24, height: 24)
                }

            }
            .padding(.leading, 10)

            Text("DietName")
                .font(.system(size:13))
                .fontWeight(.medium)
                .foregroundColor(Color.black)

        }
        .frame(width: 327, height: 48)

    }
}

A: This works quite well with a gesture on the checkbox image. Two Buttons didn't work since every tap went to both buttons.
struct TodayTodoView2: View {
    @ObservedObject var todayDietModel = TodayDietModel()

    func image(for state: Bool) -> Image {
        return state ? Image(systemName: "checkmark.circle") : Image(systemName: "circle")
    }

    var body: some View {
        NavigationView {
            VStack {
                List {
                    ForEach($todayDietModel.todayDietItems) { (item: Binding<TodayDietItem>) in
                        HStack{
                            self.image(for: item.value.isFinished).onTapGesture {
                                item.value.isFinished.toggle()
                            }
                            NavigationLink(destination: DietItemDetailView2(item: item)) {
                                Text("DietNamee \(item.value.dietName)")
                                    .font(.system(size:13))
                                    .fontWeight(.medium)
                                    .foregroundColor(Color.black)
                            }
                        }
                    }
                }
                .background(Color.white)
            }
        }
    }
}


Q: cudaMemcpy returns cudaErrorInvalidArgument when reading from Device to Host, unclear why first post here. I'm currently working on a project that requires writing a large 2d array (on the order of 1,000,000x7) into my GPU, doing some computation, and returning it to the Host. Since I want to do so quickly and with such a large array, I attempted to flatten the array to help pass it into the GPU fairly straightforwardly. The array successfully writes (or at least cudaMalloc and cudaMemcpy both return cudaSuccess when I write to the device), but when I try to read it out cudaMemcpy returns an invalid argument error.
I've not been able to figure out why this is, since I think I should be writing a valid 1d array (flattened) onto the device and reading it back out, and I thought I was feeding the right arguments to do this. The only results for this error I've found online involve swapping the dst and src arguments for cudaMemcpy, but I think I've got those right here.
This is a simplified version of my code that reproduces the problem:
#include <iostream>

using namespace std;

void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){

    arr = new float*[rows];

    arr[0] = new float[rows * cols];

    for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}

void write2dArrayToGPU(float ** arr, float * devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";

    if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}

void read2dArrayFromGPU(float ** arr, float * devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}

int main(){

int R = 100;
int C = 7;

cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);

cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
        arrA[i][j] = i*C + j;
    }
}
cout << "Done!" << endl;

cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, Darr, R, C);
cout << " Done!" << endl;

cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;

cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, Darr, R, C);

}

I compile and run this on my laptop with
 $nvcc -arch=sm_30 test.cu -o test
 $optirun cuda-memcheck ./test

and get the result:
========= CUDA-MEMCHECK
Allocating an 100x7 array ...Assigning some values ...Done!
Writing to the GPU ... Done!
Allocating second 100x7 array ...Done!
========= Program hit cudaErrorInvalidValue (error 11) due to "invalid argument" on CUDA API call to cudaMemcpy.
=========     Saved host backtrace up to driver entry point at error
Reading from the GPU into the new array ...=========     Host Frame:/usr/lib64/nvidia-bumblebee/libcuda.so.1 [0x2ef343]
cudaMemcpy Read Failed=========     Host Frame:./test [0x38c6f]
=========     Host Frame:./test [0x2f08]
=========     Host Frame:./test [0x3135]
=========     Host Frame:/usr/lib64/libc.so.6 (__libc_start_main + 0xf1) [0x20401]
=========     Host Frame:./test [0x2c6a]

=========
========= ERROR SUMMARY: 1 error

I'm moderately new to CUDA, and still learning, so any help would be appreciated, thanks!

A: Thanks to Robert Crovella for pointing me in the right direction with a comment above, and linking a similar question.
The gist is that by passing devPtr by value rather than by pointer or by reference into my GPU write and read functions, the cudaMalloc and cudaMemcpy functions were acting only on a copy in the function scope.
Two solutions - (both of these run without throwing errors for me)
First: Pass devPtr by reference into write2dArrayToGPU and read2dArrayFromGPU the solution then looks like.
#include <iostream>

using namespace std;

void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){

    arr = new float*[rows];

    arr[0] = new float[rows * cols];

    for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}

//changed float * devPtr to float *  &devPtr
void write2dArrayToGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMalloc((void**)&devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";

    if(cudaSuccess != cudaMemcpy(devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}

//changed float * devPtr to float * &devPtr
void read2dArrayFromGPU(float ** arr, float * &devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMemcpy(arr[0], devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}

int main(){

int R = 100;
int C = 7;

cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);

cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
        arrA[i][j] = i*C + j;
    }
}
cout << "Done!" << endl;

cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, Darr, R, C);
cout << " Done!" << endl;

cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;

cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, Darr, R, C);

}

Second: Pass devPtr by pointer so the solution looks like
#include <iostream>

using namespace std;

void alloc2dArray(float ** &arr, unsigned long int rows, unsigned long int cols){

    arr = new float*[rows];

    arr[0] = new float[rows * cols];

    for(unsigned long int i = 1; i < rows; i++) arr[i] = arr[i - 1] + cols;
}

//changed float * devPtr to float ** devPtr
void write2dArrayToGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMalloc((void**)devPtr, sizeof(float) * rows * cols)) cerr << "cudaMalloc Failed";

    if(cudaSuccess != cudaMemcpy(*devPtr, arr[0], sizeof(float) * rows * cols, cudaMemcpyHostToDevice)) cerr << "cudaMemcpy Write Failed";
}

//changed float * devPtr to float ** devPtr
void read2dArrayFromGPU(float ** arr, float ** devPtr, unsigned long int rows, unsigned long int cols){

    if(cudaSuccess != cudaMemcpy(arr[0], *devPtr, sizeof(float) * rows * cols, cudaMemcpyDeviceToHost)) cerr << "cudaMemcpy Read Failed" << endl;
}

int main(){

int R = 100;
int C = 7;

cout << "Allocating an " << R << "x" << C << " array ...";
float ** arrA;
alloc2dArray(arrA, R, C);

cout << "Assigning some values ...";
for(int i = 0; i < R; i++){
    for(int j = 0; j < C; j++){
        arrA[i][j] = i*C + j;
    }
}
cout << "Done!" << endl;

cout << "Writing to the GPU ...";
float * Darr = 0;
write2dArrayToGPU(arrA, &Darr, R, C); \\changed Darr to &Darr
cout << " Done!" << endl;

cout << "Allocating second " << R << "x" << C << " array ...";
float ** arrB;
alloc2dArray(arrB, R, C);
cout << "Done!" << endl;

cout << "Reading from the GPU into the new array ...";
read2dArrayFromGPU(arrB, &Darr, R, C); // changed Darr to &Darr

}


Q: AJAX load more posts script out putting nothing, no warnings, no notices, no data Can anyone tell me why this is outputting nothing.. at all? No errors, no notices. Nada.
I really need help with this, theres nothing wrong with the SQL details. The codes purpose is too display Mysql data with an AJAX div that loads more posts. If theres anything that could be causing this please post below. Thanks!:)
Source code:
 <?php
    /* grab stuff */
    function get_posts($start = 0, $number_of_posts = 5) {
        /* connect to the db */
        $connection = mysql_connect('localhost','root','');
        mysql_select_db('draft2',$connection) or die(mysql_error());
        $posts = array();
        /* get the posts */
        $query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT $start,$number_of_posts" or die(mysql_error());

        $result = mysql_query($query);
        while($row = mysql_fetch_assoc($result)) {
            preg_match("/
(.*)<\/p>/",$row['item_content'],$matches);
            $row['item_content'] = strip_tags($matches[1]);
            $posts[] = $row;
        }
        /* return the posts in the JSON format */
        return json_encode($posts);
    }

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Load More

I actually have posted this problem before, i know that will get you all angry. But i tried fixing it for a while but im just not as experienced as the people on here so I return. Please dont hate me.

A: @user663049: I think your problem is this line --
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT $start,$number_of_posts" or die(mysql_error());

It should be --
$query = "SELECT item_id, username, item_content FROM updates ORDER BY update_time DESC LIMIT " . $start . ", " . $number_of_posts;

$result = mysql_query($query) or die(mysql_error());

A: If it displays nothing maybe because of web server configuration. Could you just try to insert at the begining of the PHP block the following, so you may see at least errors and make the debugging
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
?>


Q: How do I customize theme in magento 1.9? I am trying to customize design in magento. Magento version is 1.9.2.0.

This is my design settings in Magento Admin. Though I can not find any package rwd in magento/skin/frontend, so i created new package rwd/trend but it is not working.

When I create another package named ksade/trend, magento gives me this error. Can somebody help me to sort it out and guide me on how to customize a theme?
Edit
Skin/frontend dir

app/design/frontend dir

This is how site design look like

A: Magento theme packages are in app/design/frontend/ directory. You can see the rwd package there.
The css, images and j files are in skin/frontend/ directory.
In order to customize the theme you need to create a new theme. As a good starting point you can use rwd packge.
Read https://www.flinttechnology.co.uk/customising-rwd-magento-responsive-theme/

A: On both app/design/frontend and skin/frontend there is a rwd folder. From there you can modify what you want.
Also check the below links:
http://devdocs.magento.com/guides/m1x/ce19-ee114/RWD_dev-guide.html
http://docs.magento.com/m1/ce/user_guide/Resources/archive/magento_community_edition_user_guide_v.1.9.pdf


Q: How can I define an ext property from Heap.io with gradle kotlin dsl Im using the heap.io and their Android SDK and they advise you to setup their library like:

*

*build.gradle:

android {
    defaultConfig {
        // Add this section to enable Heap event capture.
        ext {
          heapEnabled = true
        }
        // ...
    }
    // ...
}

But this is using the gradle groovy sintax, Im trying to use it with the Kotlin DSL of gradle like:

*

*build.gradle.kts
android {
    defaultConfig {
        ext {
            set("heapEnabled", true)
        }

But it does not work for some reason, so:
Why that may be happening?

A: This works:
(this as ExtensionAware).extensions.extraProperties.set("heapEnabled", true)

I believe Heap is looking into making it so the cast isn't necessary.

A: extra.set("heapEnabled", false)

A: I was able to make it work using withGroovyBuilder like:
android {
    defaultConfig {
        withGroovyBuilder {
            "ext" {
                setProperty("heapEnabled", LhConfig.isAnalyticEnabled(project))
            }
        }

I still dont understand where is the issue :(


Q: I am writing a regular expression to get the string between the curly bracket I am trying to get all the string from a defined text using pattern class using regex.
Pattern MyPattern = Pattern.compile('/[^{\}]+(?=})/g');

but it is throwing an error

Illegal string literal: Invalid string literal '/[^{}]+(?=})/g'.
  Illegal character sequence }' in string literal.

Any idea ?

A: Here \ is a special character which you need to escape to make it work. So you need something like
Pattern MyPattern = Pattern.compile('/[^{\\}]+(?=})/g');

Check I have used extra \ to escape the sign.
Also, the JavaScript notation (//g) won't work the way you expect in Apex Code, because it uses the Java syntax. Instead, to turn on the "g" flag, you'd use (?g):
Pattern MyPattern = Pattern.compile('(?g)[^{\\}]+(?=})');

You can read more about how patterns work in the Java documentation.


Q: How to add a new line in text field of dropdown in semantic-ui react? Here is the render function
render(){
    const { members, user } = this.props;
    let memberOptions = [];
    members.forEach((member, i) => {
      memberOptions.push({
        key: i,
        text: member.user.name,
        value: member.user.id,
        image: { avatar: true, src: member.user.gravatar },
      });
    });
    return (
      <Dropdown placeholder='Select User' fluid selection options={memberOptions} />
    )
  }

This will render perfectly. But I also want to add one more text(say email) in this text field in a new line. So that dropdown items show  similar to this : https://react.semantic-ui.com/elements/list#list-example-relaxed
How can I achieve this?

A: Akhila, I would recommend that you use the content prop instead of the text prop for your Dropdown.Item that you are rendering from your memberOptions array. The text prop specifically expects a string. The content prop will accept anything, including other React components or nodes. So instead of returning text as a string, you could do something like this for content, maybe as a separate class method on your component:
const renderItemContent = (member) => {
  const {
    email,
    name,
  } = member.user;

  const emailStyle = {
    color    : '#333',
    fontSize : '.875em',
  }

  return(
    <React.Fragment>
      {name}
      {email &&

{email}

      }
    </React.Fragment>
  )
}

Then set content: this.renderItemContent(member) on your memberOptionsArray.


Q: How set set bash variable to file name in Docker I have a Dockerfile in which files in a directory are downloaded:
RUN wget https://www.classe.cornell.edu/~cesrulib/downloads/tarballs/ -r -l1 --no-parent -A tgz \
                                     --cut=99 -nH -nv --show-progress --progress=bar:force:noscroll

I know that there is exactly one file here of the form "bmad_dist_YYYY_MMDD.tgz" where "YYYY_MMDD" is a date. For example, the file might be named "bmad_dist_2020_0707.tgz". I want to set a bash variable to the file name without the ".tgz" extension. If this was outside of docker I could use:
FULLNAME=$(ls -1 bmad_dist_*.tgz)
BMADDIST="${FULLNAME%.*}"

So I tried in the dockerfile:
ENV FULLNAME $(ls -1 bmad_dist_*.tgz)
ENV BMADDIST "${FULLNAME%.*}"

But this does not work. Is it possible to do what I want?

A: Shell expansion does not happen in Dockerfile ENV. Then workaround that you can try is to pass the name during Docker build.
Grab the filename during build name and discard the file or you can try --spider for wget to just get the filename.
ARG FULLNAME
ENV FULLNAME=${FULLNAME}

Then pass the full name dynamically during build time.
For example
docker build --build-args FULLNAME=$(wget -nv https://upload.wikimedia.org/wikipedia/commons/5/54/Golden_Gate_Bridge_0002.jpg 2>&1 |cut -d\" -f2) -t my_image .

A: The ENV ... ... syntax is mainly for plaintext content, docker build arguments, or other environment variables. It does not support a subshell like your example.
It is also not possible to use RUN export ... and have that variable defined in downstream image layers.
The best route may be to write the name to a file in the filesystem and read from that file instead of an environment variable. Or, if an environment variable is crucial, you could set an environment variable from the contents of that file in an ENTRYPOINT script.


Q: Exporting a document set I have a Powershell script that I am using to move SharePoint 2010 Document Sets from one document library to another document library in the same site.  The script works fine for most of the document sets, but for some it does not.  Here is the relevant portion of the script:
$web = get-spweb http://mysite
$list = $web.Lists["Purchase Orders Archive"]
$item = getItem $list "7581"
$docSet = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::GetDocumentSet($item.Folder)
[Byte[]] $compressedFile = $docset.Export()

The getItem function locates a specific document set within the library.  I know that I am getting the correct document library item back because I have inspected the return $item variable values.  The problem is that on some document sets, the final Export() call never completes.  There are no errors or messages, no return from the call; no CPU or memory or disk I/O is being utilized by the process.  The process just seems to go into an infinite wait.  There are no messages in the Windows Error Log and no messages in the ULS log.
Does anyone know what may be happening and how I might fix this?  We are running a fairly early patch level of SharePoint 2010 if that enters into the discussion, but I don't want to just start patching a production system unless there is evidence of a fix that will help.

A: Though an old post, I wanted to add my findings using the same code as above with SharePoint 2013. Instead of nothing returning, I would get this error:
Exception calling "Export" with "0" argument(s): "Unable to determine identity of domain."
Interestingly, in the cases where this occurred, the document set contained a file larger than 10MB. When I removed the file from the document set, it exported successfully.
I don't know yet how this can be fixed, but at least I know what was causing it.


Q: Test services with real backend in angular I want to test a service, which calls a real backend url and can not find the solution for it. My service has to call data from server and I want to be sure, that the data comes to the service and the service handle it right.
So here is just a simple example of my Login Service:
@Injectable()
export class LoginService {
/**
 * The token, which will be stored on the localStorage.
 */
public token: string;
//Eventemitter, for updating the navigation, when the user logs in
@Output() loggedInEm:EventEmitter<any> = new EventEmitter();

constructor(private http: Http) {
    // set token if saved in local storage
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.token = currentUser && currentUser.token;
}

login(_mail, _pass): Observable<number> {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    var data = {
        mail: _mail,
        pass: _pass
    };
    return this.http.post('/login', JSON.stringify(data), {
        headers : headers
    }).map((response: Response) => {
        let res = response.json();
        this.logged = res;
    });
}

public loggedIn() : boolean {
    return this.logged;
}

This is how I want to test it:
describe('Login Service', () => {

    let loginService: LoginService;

    beforeEach(() =>  {
        TestBed.configureTestingModule({
            declarations: [
            ],
            providers: [
                LoginService
            ],
            imports: [
                FormsModule,
                IonicModule
            ],
        });
        inject([LoginService], (service) => {
            loginService = service;
        });
    });

    it("Should login user", () => {
        loginService.login("mail@mail.ru", "123456");
        let loggedIn = loginService.loggedIn();
        expect(loggedIn).toBe(true);
    });
});

But I get following error:
TypeError: Cannot read property 'login' of undefined, so the service must be undefined. I could mock the service, but I want to work it with the real database, which I have on my backend server.
So what could be the problem and how can I solve it?
Kind regards,
Andrej

A: Try this :
it("Should login user", () => {
    loginService.login("mail@mail.ru", "123456").subscribe(value => {
      let loggedIn = loginService.loggedIn();
      expect(loggedIn).toBe(true);
      done();
    });
})


Q: TypeError: _onRequestWithOpts is not a function at Object.httpsProvider._onRequestWithOpts I'm creating an app that uses firebase-functions.  I created my app directory and ran firebase init.  After that was completed I tried to run the hello world program that it gives you using firebase serve, and I get this error:
TypeError: _onRequestWithOpts is not a function
at Object.httpsProvider._onRequestWithOpts

from what it looks like, it seems to be an issue with the onRequest() method but I have made apps using this before and have never ran into this issue.  I literally didn't change a single piece of code that they initially give you so unless they decided to change something overnight i'm not sure what the issue is.
using firebase deploy works, but firebase serve does not.  Using express and adding new functions, the error pops up when running firebase deploy and serve.
const functions = require('firebase-functions');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-
functions
//
exports.helloWorld = functions.https.onRequest((request, response)
=> {
response.send("Hello from Firebase!");
});

    Gabriels-MacBook-Pro:functions Mike$ firebase serve

    === Serving from '/Users/Gabe/Desktop/mycart-functions'...

   ⚠  Your requested "node" version "8" doesn't match your global
    version "10"
    ✔  functions: Emulator started at http://localhost:5000
    i  functions: Watching "/Users/Gabe/Desktop/mycart-
   functions/functions" for Cloud Functions...
   ⚠  TypeError: _onRequestWithOpts is not a function
    at Object.httpsProvider._onRequestWithOpts
   (/usr/local/lib/node_modules/firebase-
  tools/lib/emulator/functionsEmulatorRuntime.js:278:24)
    at Object.httpsProvider.onRequest
   (/usr/local/lib/node_modules/firebase-
  tools/lib/emulator/functionsEmulatorRuntime.js:283:34)
    at Object.<anonymous> (/Users/Gabe/Desktop/mycart-
   functions/functions/index.js:6:39)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js
   (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)
   ⚠  We were unable to load your functions code. (see above)


Q: SQLite query running successfully in version 3.5.2 but giving error in version 3.7.11 - using aggregate functions My query was working fine in Sqlite 3.5.1 version but when I run the same query in 3.7.11 version am getting misuse of aggregate function min() error. Below one is my query. Please help me in this regard
select distinct category from m_ipaperdara  order by min(displayorder) asc

A: DISTINCT is not a grouping that can be used for aggregate functions.
If you want take the smalled displayorder in each category, you have to explicitly group by that column:
SELECT category FROM m_ipaperdara GROUP BY category ORDER BY MIN(displayorder)


Q: Is PyCharm Community Edition doesn't have Database Tool? I'm using pycharm 2020.3 community edition. but id doesn't showing database tool. it means this edition comes without that option? or any action we have to do for this?
*Note: some people saying add plugin data base browser. but that is not built in. I want database tool.

A: PyCharm Community doesn't have database tools. See comparison matrix https://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html


Q: solr LowerCaseFilterFactory should not filter number I'm using a query schema which need to let abc match Abc and 400 match 400 (user name match).
But I found when I use LowerCaseFilterFactory, It not return any result when I query 400.
I digg into the source code, and found LowerCaseTokenizerFactory use LowerCaseTokenizer which extends LetterTokenizer, and it filter all the numbers.
How should I fix this?

A: You are right that LowerCaseTokenizer will remove all non-letters.  It would very useful (as far as providing a meaningful answer) to see your schema, as I don't believe just using the lowercase filter factory should generate a Tokenizer of any kind.
At any rate, though, there are plenty of other options for tokenizers.  Both Standard or Classic might suit your needs better.
Something along the line of:
<analyzer>
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
</analyzer>

Might do well for you.


Q: ErrorException: Creating default object from empty value - Laravel I have just got this error all the tries while updating my table data.

ErrorException: Creating default object from empty value

AdminController.php
public function update(Request $r, $post_id) {
    $post = Post::find($post_id);

    $post->post_title = $r->post_title;
    $post->post_image = $r->post_image;
    $post->post_details = $r->post_details;
    $post->post_rating = $r->post_rating;
    $post->id = $r->id;

    $post->save();

    return back();
}

My Resource Route
Route::resource('post', AdminController::class);

Blade File

    <form action="{{ route('post.update',$list->post_id) }}" method="POST">
        @csrf
        @method('PUT')

        <input type="hidden" name="id" value="{{$list->id}}">
        <input type="hidden" name="post_rating" value="{{$list->post_rating}}">

            Edit Title: <input class="form-control" name="post_title" type="text" id="exampleFormControlInput1" value="{{$list->post_title}}" aria-label="default input example">

            Edit Description:
            <textarea class="form-control" id="exampleFormControlTextarea1"  name="post_details"  rows="3">
                {{ $list->post_details }}
            </textarea>

            post_image))}}" alt="" width="120px;">
            Edit Photos:
            <input id="formFileMultiple" class="form-control form-control-lg" name="post_image" type="file" value="{{ $list->post_image }}" multiple>

        <button type="submit" class="btn btn-primary">Save Changes</button>
    </form>

Could someone help me, please?

A: There is a chance that the model doesn't exist. You can add a check for this in your controller as follows:
public function update(Request $r, $post_id) {
    $post = Post::find($post_id);
    if (!$post) {
        // You can add code to handle the case when the model isn't found like displaying an error message
        return back();
    }

    $post->post_title = $r->post_title;
    $post->post_image = $r->post_image;
    $post->post_details = $r->post_details;
    $post->post_rating = $r->post_rating;
    $post->id = $r->id;

    $post->save();

    return back();
}


Q: Is tensor product commutative for symmetric tensors? Let $V$ be a vector space over $\mathbb{R}$ and $V^*$ the dual vector space. I'm trying to show that for a symmetric tensor  $T = T_{\mu\nu}e^{\mu}\otimes e^\nu$ where
$T(v_1,v_2)=T(v_2,v_1)$, the tensor components $T_{\mu\nu}$ is unchanged by permutation of indices, i.e. $$T_{\mu\nu}=T_{\nu\mu}.$$
I started off with the definition of a symmetric tensor $T(v_1,v_2)=T(v_2,v_1)$:
$$T_{\mu\nu}e^{\mu}(v_1)\otimes e^\nu(v_2)=T_{\mu\nu}e^{\mu}(v_2)\otimes e^\nu(v_1)$$
Rearraging indices $\mu$ and $\nu$ on the RHS,
$$T_{\mu\nu}e^{\mu}(v_1)\otimes e^\nu(v_2)=T_{\nu\mu}e^{\nu}(v_2)\otimes e^\mu(v_1).$$
So it seems that the tensor product of $$e^{\mu}(v_1)\otimes e^\nu(v_2)=e^{\nu}(v_2)\otimes e^\mu(v_1)$$ is commutative for symmetric tensors if we require $T_{\mu\nu}=T_{\nu\mu}$. But I read that tensor products are in general not commutative. Why is it commutative in this case?

A: What you write as $e^{\mu}(v_1)\otimes e^\nu(v_2)$ should really be $(e^{\mu}\otimes e^\nu)(v_1, v_2)=e^{\mu}(v_1)\, e^\nu(v_2),$ where the last expression is a product of two real values $e^{\mu}(v_1)$ and $e^\nu(v_2)$ and is therefore commutative, i.e. $e^{\mu}(v_1)\, e^\nu(v_2) = e^\nu(v_2) \, e^{\mu}(v_1).$


Q: Internet connectivity drops intermittently on El Capitan I've got the following setup: A 2010 MBA and a 2013 rMBP, both running El Capitan (same issues on Yosemite though), connected to an AirPort Express 802.11n (1st Generation), which is connected via an ethernet cable to a Cisco router/modem. Airport is running in bridge mode.
10-20 times a day, internet connectivity will drop for between 10 and 90 seconds. iPads and iPhones never have issues, only the macs. The wifi connection is fine, it's just internet. Generally, only one mac loses internet connectivity, the other mac remains connected.
I'm pinging an external server, the modem and the airport continuously. During downtime, the external server is unreachable, but both the airport and the modem remain reachable.
What immediately restores the connection is clicking "Renew DHCP Lease" in the Network Preferences.
I tried to programmatically renew the DHCP lease as soon as downtime was detected (sudo ipconfig set en1 DHCP), but that seemed to confuse the wifi connection status in the menu bar.
I'd like to solicit tips to pin down the problem in more detail, or to solve the problem entirely. (Cutting out the Airport and using the cisco router/modem directly produced similar problems).
UPDATE:
My connection goes down every 15 minutes, like clockwork. When it's down, the DHCP entry for my laptop disappears from the list of DHCP entries in the web interface of the Cisco, even though it was not about to expire.

A: I run into the same issue with El Capitan on a mid-2014 MBP 13". Did run a wireless diagnostic and captured the drop, the RSSI value seems to change the most but I don't know what that could mean or if it's actually part of the problem.
Turning wifi off and back on fixes it.
10/08/15 12:34:31.0430  Link Quality Changed : rssi=-59 dBm, txRate=117 Mbps
10/08/15 12:34:44.0550  Link Quality Changed : rssi=-62 dBm, txRate=104 Mbps
10/08/15 12:34:45.1200  LAN: WiFi interface can ping IPv4 router 192.168.0.1 . . . YES —— [1/1 (0% loss) min=2.1 max=2.1 avg=2.1]
10/08/15 12:34:54.4610  WAN: WiFi interface can ping DNS server 17.254.0.50 . . . YES —— [1/1 (0% loss) min=24.5 max=24.5 avg=24.5]
10/08/15 12:34:54.4610  moto / ch1 [RSSI=-62 dBm, Noise=-95 dBm, SNR=33, Tx=78 Mbps]
10/08/15 12:34:54.4610  AWDL: Disabled [0 ]
10/08/15 12:34:55.0640  Link Quality Changed : rssi=-62 dBm, txRate=52 Mbps
10/08/15 12:35:08.0790  Link Quality Changed : rssi=-61 dBm, txRate=78 Mbps
10/08/15 12:35:09.5260  LAN: WiFi interface can ping IPv4 router 192.168.0.1 . . . YES —— [1/1 (0% loss) min=4.1 max=4.1 avg=4.1]
10/08/15 12:35:17.6310  WAN: WiFi interface can ping DNS server 17.254.0.50 . . . NO —— [0/1 (1% loss) min=0.0 max=0.0 avg=0.0]
10/08/15 12:35:17.6320  moto / ch1 [RSSI=-58 dBm, Noise=-94 dBm, SNR=36, Tx=78 Mbps]
10/08/15 12:35:17.6320  AWDL: Disabled [0 ]
10/08/15 12:35:17.6320  UNEXPECTED DROP DETECTED!!!

A: On upgrading to El Capitan I had a similar problem, but with an ethernet connection.  In fact I couldn't connect at all - I could ping the DNS server, but nothing beyond.
Anyhow, I did a clean install of El Capitan (after backing everything up!) and the problem has disappeared.  So perhaps that would be a possible remedy.  (One of our network gurus suggested that it might have been trying to use IPv6, which the DNS servers wouldn't handle properly.)

A: Please try reset NVRAM on your Mac:

*

*Shut down your Mac.

*Locate the following keys on the keyboard: Command (⌘), Option, P, and R.

*Turn on your Mac.

*Press and hold the Command-Option-P-R keys immediately after you hear the startup sound.

*Hold these keys until the computer restarts and you hear the startup sound for a second time.

*Release the keys.


Q: Communicating between Kernel Threads in Linux I am porting a app/PCI driver from vxWorks to Linux and I would like to keep the same architecture if possible.  The current driver has 2 tasks(threads) that communicate with each other using message queues.  Is there a mechanism to communicate between kernel threads?  The message queues are being used to pass buffer addresses and size info so the tasks can use DMA to move large amounts of data.

A: It sounds like the workqueue interface might be what you're after - or for something lighter-weight, a kfifo combined with a rwsem semaphore.

A: I would strongly advise against keeping the VxWorks architecture on Linux. Kernel thread proliferation is frowned upon, your code will never make it into official kernel tree. Even if you don't care about that, are you 100% sure that you want to develop a driver in a non-standard way ? Things would be much simpler if you would just get rid of these two tasks. BTW, why on earth you need tasks for PCI driver to begin with ?


Q: Django Attribute Error - Form object has no attribute 'is_valid' I am receiving an error, object has no attribute 'is_valid', when trying to insert form data into a form. Below is the structure of my code:
Views.py:
def add_user(request):
    form = Car(request.POST)
    if request.method == 'POST' and form.is_valid():
        last_store = form.cleaned_data.get['value']
        make = request.POST.get('make', '')
        model = request.POST.get('model', '')
        ..

        car_obj = Car(last_store = last_store, make = make, model = model, series = series, series_year = series_year, price_new = price_new, engine_size = engine_size, fuel_system = fuel_system, tank_capacity = tank_capacity, power = power, seating_capacity = seating_capacity, standard_transmission = standard_transmission,  body_type = body_type, drive = drive, wheelbase = wheelbase, available = available)
        car_obj.save()
        return HttpResponseRedirect('/inventory/add/')
    else:
        form = Car()

    return render(request, 'cars/inventory-add.html', {})

Class:
class Car(models.Model):
    make = models.CharField(max_length=200, null=False)
    model = models.CharField(max_length=200, null=False)
    series = models.CharField(max_length=200, null=False)
    series_year = models.IntegerField(null=False)
    price_new = models.IntegerField(null=False)
    ..
    last_store = models.ForeignKey(Store, on_delete=models.DO_NOTHING, related_name="last_store")
    available = models.BooleanField(null=False, default=True)

    def __str__(self):
        return(self.make + " " + self.model)

CarForm (forms.py)
class CarForm(forms.ModelForm):
    class Meta:
        model = Car
        fields = ['last_store', 'make', 'model', 'series', 'series_year', 'price_new', 'engine_size', 'fuel_system', 'tank_capacity', 'power', 'seating_capacity', 'standard_transmission', 'body_type', 'drive', 'wheelbase', 'available']

The error lies within the last_store as without form.is_valid(), apparently I cannot use form.cleaned_data, but form.is_valid() seems to not even exist? As seen in the class, last_store is of type a foreign key, therefore I am struggling to set the default value for it when the user enters input into the form. The last_store variable is attempting to fetch the value from the inputted form data which consists of a SELECT option..

A: You have a clash between your model and form, which are both named Car. Typically you would fix this by renaming the form CarForm.
Note that you shouldn't normally need to create the object with car_obj = Car(...). If you use a model form, you can simplify your code to car_obj = form.save(). You should also move CarForm(request.POST) inside the if request.method == 'POST' check, and include form in the template context. Putting that together, you get something like:
def add_user(request):
    if request.method == 'POST':
        form = CarForm(request.POST)
        if form.is_valid():
            car_obj = form.save()
            return HttpResponseRedirect('/inventory/add/')
    else:
        form = CarForm()
    return render(request, 'cars/inventory-add.html', {'form': form})

A: In your views.py file line 2
form = Car(request.POST):

change it to
form = CarForm(request.POST):

Hope it works!


Q: Sent e-mails into mbox with getmail I'm using getmail to fetch my e-mail inbox into an mbox file (with IMAP). It works great, but the process got only Inbox folder's content.
Is there a way to include sent e-mails too? Official documentation do not mention that.
Tx.

A: In the retriever section add a mailboxes section. The getmail configuration guide gives this example:
mailboxes = ("INBOX", "INBOX.spam",
"mailing-lists.model-railroading")

You might have to play around to find out whether your sent mail folder is called

*

*Sent

*"Sent Mail"

*INBOX.Sent

*...

It depends on the configuration of your mailserver. Configuring Thunderbird as a one off should show you your folder names if you can't find another way of doing it.


Q: how do i define props in a function i am new to react and i am trying to use props in a function and i am not sure how to use it. This is the code.
import React from 'react';
import './Card.css';
import { connect } from 'react-redux';
import { addBasket } from '../actions/addAction';
function Card({props},{image, title,author,price}) {
    return (

{props.title}

{props.author}

 £{props.price}

                <button>

                        Add to Basket

                </button>

    );
}

export default connect(null, { addBasket })(Card);

And that's the error i am getting.
TypeError: Cannot read property 'title' of undefined

{props.title}

{props.author}

A: Replace
function Card({props},{image, title,author,price}) {

with
function Card(props) {

I recommend working through the official React tutorial before using Redux.


Q: How To get the Check Rule Constraint How can I get the expression of a check constraint?
With MSSMS I can easly see that Table Person has a CHECK constraint named CK_Person validating the expression ([DateOfBirth]<[DateOfDeath]).
With this query I can get the COLUMN_NAME, CONSTRAINT_NAME and CONSTRAINT_TYPE:
SELECT CCU.COLUMN_NAME, CCU.CONSTRAINT_NAME,  TC.CONSTRAINT_TYPE
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
    INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CCU ON TC.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME
    WHERE TC.TABLE_NAME = 'Person'

Resulting
+-------------+-----------------+-----------------+
| COLUMN_NAME | CONSTRAINT_NAME | CONSTRAINT_TYPE |
+-------------+-----------------+-----------------+
| PersonID    | PK_Person       | PRIMARY KEY     |
| DateOfBirth | CK_Person       | CHECK           |
| DateOfDeath | CK_Person       | CHECK           |
+-------------+-----------------+-----------------+

But how can I get the actual expression itself?

A: Try this...
SELECT definition AS Check_Expression
      ,name       AS ConstraintName
FROM sys.check_constraints
WHERE Parent_object_ID = OBJECT_ID('TableName')


Q: Custom view, onSaveInstanceState is not called I created a custom view, and tried to restore the state automatically on screen rotation (just as EditText restores current input text automatically), but when I see the log, onSaveInstanceState is not called, and only onRestoreInstanceState is called. What is wrong?
class MyView:LinearLayout
{
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
            context, attrs, defStyleAttr)

    init
    {
        isSaveEnabled=true
    }

    override fun onSaveInstanceState(): Parcelable
    {
        return super.onSaveInstanceState()
        Log.d("ss", "save")
    }

    override fun onRestoreInstanceState(state: Parcelable?)
    {
        super.onRestoreInstanceState(state)
        Log.d("ss", "restore")
    }
}

Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/top"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.loser.mylayouttest.MyView
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</AbsoluteLayout>

Activity:
class MainActivity : AppCompatActivity()
{

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

A: The reason why you can't see Log.d("ss", "save") being called is simply that the code line is invoked after the return statement. The onSaveInstanceState() is actually called. To see the log move Log.d("ss", "save") above return super.onSaveInstanceState().


Q: MySQL : Updating a table having a 'where' clause with a max value I want to update the last generated row (the max(id) row.
I tried this code but it doesn't work
update person t1
set t1.age = 25
where t1.id = (select max(t2.id)  from person t2
            where t2.address = 'LA, California');

MySQL tells me that : Error Code: 1093. You can't specify target table 't1' for update in FROM clause
So, I suppose that I cannot reach the same tale while performing operations such as updates.
How can I sole this problem ?
Regards.

A: You cannot reference the same table in a subquery, but you can instead do it in a JOIN (which is allowed in UPDATE and DELETE statements):
UPDATE person a
JOIN   (SELECT MAX(id) AS id FROM person WHERE address = 'LA, California') b
       ON a.id = b.id
SET    a.age = 25

Another way you can do it is by using the ORDER BY / LIMIT technique:
UPDATE   person
SET      age = 25
WHERE    address = 'LA, California'
ORDER BY id DESC
LIMIT    1

A: You can try as:
UPDATE person t1
    INNER JOIN (SELECT MAX(id) AS id  FROM person
            WHERE t2.address = 'LA, California') t2
        ON t1.id = t2.id
SET t1.age = 25;

or
SELECT MAX(t2.id)
INTO @var_max_id
FROM person t2
WHERE t2.address = 'LA, California';

UPDATE person t1
SET t1.age = 25
WHERE t1.id = IFNULL(@var_max_id, -1);


Q: How does Arthur Dent see English vocalizations, not Vogon ones? When Ford Prefect shoved the Babel Fish in the ear of Arthur Dent, he is able to understand and comprehend speech by Vogons instead of hearing the screeches of their native language. But in the film, the Vogon's animations show their lips moving in such a fashion that it could be lip-read as normal Earth English.
The out of universe explanation is simple, and that is because it would be a bit weird to see Vogons screeching their native language but hear them speaking comprehensible English.
So how is this possible in universe? Is the Babel Fish capable of changing vision as well as hearing?

A: You are focusing too much on one alien species.
If you expect the Vogons lips to move differently to English, then so should the lips of every character.  Including Zaphod Beeblebrox, Ford Prefect, Slartibartfast, etc.  None of them are native English speakers, no matter how human they look.
Now consider:

*

*The film's budget in dubbing everyone.

*The entire thing would look like a badly dubbed chop-socky opus

In short - it's a comedy, don't overthink it.

A: There's no reason why it could change the sound but not the vision to a listener who cares about the lip movements.  You see, the Babel fish isn't like a headphone, it doesn't just whisper the translation to your ear.  Let me quote The Hitch Hiker's Guide to the Galaxy chapter 6.

‘The Babel fish,’ said The Hitch Hiker's Guide to the Galaxy quietly, ‘is small, yellow and leech-like, and probabliy the oddest thing in the Universe. It feeds on brainwave energy to nourish itself with. It then excretes into the mind of its carrier a telepathic matrix formed by combining the conscious thought frequencies with nerve signals picked up from the speech centres of the brain which has supplied them. The practical upshot of all this is that if you stick a Babel fish in your ear you can instantly understand anything said to you in any language. The speech patterns you actually hear decode the brainwave matrix which has been fed into your mind by your Babel fish.[’]

Also, let me quote chapter 5 for the description of what using a Babel fish felt like to Arthur.  Note that at that time he was listening to a loudspeaker without seeing the Vogon captain, so there was no way to see the lips.

He was still listening to the howling gargles, he knew that, only now it had somehow taken on the semblance of perfectly straight-forward English.

From this, I think the Babel fish simply gives you the meaning of the Vogon speech, and it's your brain that creates the illusion of the sound of English words or the lip movements for them.  That experience would be impossible to show in a movie with current technology, so the movie simply shows the Vogon speaking English.

A: Sadly, in the books, Douglas Adams neglected to elucidate on alien lip synchronisation in relation to Babel fish third party observations.
So, here is my guess.
The reason the Vogons lips are moving in English is because ifs a film. If the vocals didn't sinc with lip moments it would look like someone had messed up the animatronics in the vogon mask. Also, and more to the point, it would have looked silly.


Q: Definition of locally integrable If $m$ is a Lebesgue measure on $\mathbb{R}^n$, then the wikipedia says

(1) $f$ is locally integrable if $\int_K f dm < \infty$ for every compact set $K$.

But why is this condition equivalent to

(2) $f$ is locally integrable if $\int_B f dm < \infty$ for every bounded measurable set $B$?
  as defined in Folland's book Real Analysis?

The direction $(2) \rightarrow (1)$ is clear, but what about the other direction?

A: Both definitions need a correction. $f$ is locally integrable if $\int_K |f| <\infty$ for every compact set $K$ and this is equivalent to the condition  $\int_K |f| <\infty$ for every bounded measurable set $K$. You cannot drop the absolute value sign in the definitions. The equivalence is obvious because any compact set is a bounded measurable set and any bounded measurable set is contained in a closed ball which is a compact set.


Q: ClosedXML Copy and Paste Range of formulas as values I have a function ApplyFormulas() that will obviously apply formulas like so
detailWs.Range(companyModel.RevenueFormulaRangeDollars).FormulaR1C1 = companyModel.RevenueFormulaDollars;

However Now I need to copy that range and paste it in the same spot so the values are real and not just formula references.
I am able to do this in VBA with excel interop but I am utilizing ClosedXML. Does anyone know of a way to do this? I tried CopyTo() but there is no paste special etc.
I also attempted
detailWs.Range(companyModel.NoChargeFormulaRangePercent).Value = detailWs.Range(companyModel.NoChargeFormulaRangePercent).Value;

but im getting a property or indexer cant be used because it lacks a getter but from what I can tell both have a get; set; property.
I've tried a couple for things and still not working..
    var test = detailWs.Range(companyModel.NoChargeFormulaRangePercent).CellsUsed();
    foreach(var c in test)
    {
        c.Value = c.Value.ToString();
    }

A: Here's what I created a few months ago to copy all the formulas in one worksheet to another.
Note: I am having a problem where some formulas using a Name are not correctly copying the Name because something thinks the Name(i.e. =QF00) is a reference and will change it with AutoFill. Will update when I figure it out.
cx.IXLWorksheet out_buff
cx.IXLRange src_range
cx.IXLCells tRows = src_range.CellsUsed(x => x.FormulaA1.Length > 0);

foreach (cx.IXLCell v in tRows)
{
    cell_address = v.Address.ToString();
    out_buff.Range(cell_address).FormulaA1 = v.FormulaA1;
}


Q: Only the last usercontrol shows contentcontrol I have a weird problem. I've created a usercontrol with a label and a canvas.
The canvas references a resource.
But the canvas is only shown on the last control in my stackpanel.
This is my window
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlSolution" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="UserControlSolution.MainWindow"
    Title="MainWindow" Height="836" Width="270.5" Background="#FF2B2B2B" BorderBrush="{DynamicResource Border}" Loaded="Window_Loaded" >

<Window.Resources>

    <LinearGradientBrush x:Key="Border" EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
        <GradientStop Color="#FF6C6C6C" Offset="0.009"/>
        <GradientStop Color="#FFA1A1A1" Offset="1"/>
    </LinearGradientBrush>
    <SolidColorBrush x:Key="Orange" Color="#FFF5610E"/>
    <SolidColorBrush x:Key="Red" Color="#FFE51400"/>
    <SolidColorBrush x:Key="Blue" Color="#FF1BA1E2"/>
    <SolidColorBrush x:Key="Yellow" Color="#FFFFC40D"/>

</Window.Resources>

<StackPanel Margin="0,10,0,0">
    <local:UserControlButton x:Name="Robby" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
    <local:UserControlButton x:Name="Erwin" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" />
    <local:UserControlButton x:Name="Laurens" Height="50" VerticalAlignment="Top"  Margin="2,0,0,5"/>
    <local:UserControlButton x:Name="Kevin" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
    <local:UserControlButton x:Name="Liesbeth" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" Background="{DynamicResource Orange}"/>
    <local:UserControlButton x:Name="Jack" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
    <local:UserControlButton x:Name="Filip" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
    <local:UserControlButton x:Name="Stefaan" Height="50" VerticalAlignment="Top" Margin="2,0,0,5" Background="{DynamicResource Red}"/>
    <local:UserControlButton x:Name="Sami" Height="50"  VerticalAlignment="Top" Margin="2,0,0,5" Background="{DynamicResource Blue}"/>
    <local:UserControlButton x:Name="Jurgen" Height="50" VerticalAlignment="Top" Margin="2,0,0,5"/>
</StackPanel>

This is my usercontrol, in the contentcontrol at the bottom I reference my canvas.
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
mc:Ignorable="d"
x:Class="UserControlSolution.UserControlButton"
x:Name="UserControl"
Height="50" Background="#FF2F2F2F">

<i:Interaction.Triggers>
    <i:EventTrigger EventName="MouseEnter">
        <ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="Expand"/>
    </i:EventTrigger>
    <i:EventTrigger EventName="MouseLeave">
        <ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="Collapse"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Grid x:Name="LayoutRoot" Height="50" RenderTransformOrigin="0.5,0.5">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="VisualStateGroup">
            <VisualState x:Name="Expand">
                <Storyboard>
                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="LayoutRoot">
                        <EasingDoubleKeyFrame KeyTime="0" Value="80"/>
                    </DoubleAnimationUsingKeyFrames>
                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="UserControl">
                        <EasingDoubleKeyFrame KeyTime="0" Value="79"/>
                    </DoubleAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
            <VisualState x:Name="Collapse"/>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Rectangle x:Name="rectangle" RenderTransformOrigin="0.5,0.5" Width="230" Height="50"/>
    <TextBlock x:Name="NameLabel" FontSize="16" Foreground="#FFE5E5E5" Height="34" Width="149" Text="Onthaal Telefoon" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,10,0,0" FontFamily="Segoe UI Semibold"/>
    <Viewbox HorizontalAlignment="Right" VerticalAlignment="Top" Height="50" Width="58.789">
        <ContentControl Content="{DynamicResource appbar_close}" Width="91.96" Height="79.911" />
    </Viewbox>
</Grid>
</UserControl>

And this is my App file where I define my resources
<Application x:Class="UserControlSolution.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <Canvas x:Key="appbar_close" x:Name="appbar_close" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
        <Path Width="31.6666" Height="31.6667" Canvas.Left="22.1666" Canvas.Top="22.1667" Stretch="Fill" Fill="#FFEE1111" Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z " Stroke="#FF2F2F2F"/>
    </Canvas>

    <Canvas x:Key="appbar_check" x:Name="appbar_check" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
        <Path Width="37.9998" Height="31.6665" Canvas.Left="19.0001" Canvas.Top="22.1668" Stretch="Fill" Fill="#FF00A300" Data="F1 M 23.7501,33.25L 34.8334,44.3333L 52.2499,22.1668L 56.9999,26.9168L 34.8334,53.8333L 19.0001,38L 23.7501,33.25 Z " Stroke="#FF2F2F2F"/>
    </Canvas>

    <Canvas x:Key="appbar_arrow_right" x:Name="appbar_arrow_right" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
        <Path Width="39.25" Height="28" Canvas.Left="19.0002" Canvas.Top="24" Stretch="Fill" Fill="#FF2B5797" Data="F1 M 19.0002,34L 19.0002,42L 43.7502,42L 33.7502,52L 44.2502,52L 58.2502,38L 44.2502,24L 33.7502,24L 43.7502,34L 19.0002,34 Z " Stroke="#FF2F2F2F"/>
    </Canvas>

    <SolidColorBrush x:Key="UserControlBackground" Color="#FF2F2F2F"/>

</Application.Resources>

As you can see in the screenshot, only the last control shows the canvas..

A: Since you have only one Canvas and each Visual can have only one parent in visual tree therefore each time you place your resource it's put in that place of visual tree and removed from the previous place. You can either put Canvas directly into ViewBox in UserControl and make Path a resource or you can try setting x:Shared attribute to false on your Canvas which should result in new instance of resource being created each time you refer to it:
<Application.Resources>
    <Canvas x:Key="appbar_close" x:Shared="False" ...>
        <!-- -->
    </Canvas>
</Application.Resources>

A: Set x:Shared=false on resource. It will work.
<Canvas x:Key="appbar_close" x:Name="appbar_close" x:Shared="false" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0" >


Q: iPad is stuck in Guided Access My daughter accidentally turned on the Guided access, and the dilemma here is that we forgot the password, and we can't turn off the iPad to reboot, because it is stuck in app which she is using. How can I remove the Guided Access ?

A: That is a dilemma. If you know the password to access the iPad itself, hold the home and power button down until the iPad reboots.
When it starts, it should not boot back into Guided Access and you shouldn't have to remember the password.