问:
Chaining MapReduces - Google AppEngine
I'm trying to send the output of a reduce to a map, by chaining in a pipeline, similar to this guy:
I would like to chain multiple mapreduce jobs in google app engine in Python
I tried his solution, but it didn't work.
The flow of my pipeline is:

Map1

Reduce1

Map2

Reduce2

I'm saving the output of Reduce1 to the blobstore under a blob_key, and then trying to access the blob from Map2. But I get the following error while executing the second map: "BadReaderParamsError: Could not find blobinfo for key <blob_key here>".

Here's the pipeline code:

```<code>class SongsPurchasedTogetherPipeline(base_handler.PipelineBase):

  def run(self, filekey, blobkey):
    bucket_name = app_identity.get_default_gcs_bucket_name()
    intermediate_output = yield mapreduce_pipeline.MapreducePipeline(
        "songs_purchased_together_intermediate",
        "main.songs_purchased_together_map1",
        "main.songs_purchased_together_reduce1",
        "mapreduce.input_readers.BlobstoreLineInputReader",
        "mapreduce.output_writers.GoogleCloudStorageOutputWriter",
        mapper_params={
            "blob_keys": blobkey,
        },
        reducer_params={
            "output_writer": {
                "bucket_name": bucket_name,
                "content_type": "text/plain",
            }
        },
        shards=1)
    yield StoreOutput("SongsPurchasedTogetherIntermediate", filekey, intermediate_output)

    intermediate_output_key = yield BlobKey(intermediate_output)
    output = yield mapreduce_pipeline.MapreducePipeline(
        "songs_purchased_together",
        "main.songs_purchased_together_map2",
        "main.songs_purchased_together_reduce2",
        "mapreduce.input_readers.BlobstoreLineInputReader",
        "mapreduce.output_writers.GoogleCloudStorageOutputWriter",
        mapper_params=(intermediate_output_key),
        reducer_params={
            "output_writer": {
                "bucket_name": bucket_name,
                "content_type": "text/plain",
            }
        },
        shards=1)
    yield StoreOutput("SongsPurchasedTogether", filekey, output)
</code>```

and here's the BlobKey class which takes the intermediate output and generates the blob key for Map2 to use:

```<code>class BlobKey(base_handler.PipelineBase):

  def run(self, output):
    blobstore_filename = "/gs" + output[0]
    blobstore_gs_key = blobstore.create_gs_key(blobstore_filename)
    return {
      "blob_keys": blobstore_gs_key
    }
</code>```

The StoreOutput class is the same as the one in Google's MapReduce demo https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/master/python/demo/main.py, and does the same thing as the BlobKey class, but additionally sends the blob's URL to HTML as a link.

Manually visiting the URL appname/blobstore/<blob_key>, by typing it into a browser (after Reduce1 succeeds, but Map2 fails) displays the output expected from Reduce1. Why can't Map2 find the blob? Sorry I'm a newbie to AppEngine, and I'm probably going wrong somewhere because I don't fully understand blob storage.

答:
Okay, I found out that Google has removed the BlobstoreOutputWriter from the list of standard writers on the GAE GitHub repository, which makes things a little more complicated. I had to write to the Google Cloud Store, and read from there. I wrote a helper class which generates mapper parameters for the GoogleCloudStorageInputReader.

```<code>class GCSMapperParams(base_handler.PipelineBase):

  def run(self, GCSPath):
    bucket_name = app_identity.get_default_gcs_bucket_name()
    return {
            "input_reader": {
                "bucket_name": bucket_name,
                "objects": [path.split('/', 2)[2] for path in GCSPath],
            }
        }
</code>```

The function takes as argument the output of one MapReduce stage which uses a GoogleCloudStorageOutputWriter, and returns a dictionary which can be assigned to mapper_params of the next MapReduce stage.

Basically, the value of the output of the first MapReduce stage is a list containing <app_name>/<pipeline_name>/key/output-[i], where i is the number of shards. In order to use a GoogleCloudStorageInputReader, the key to the data should be passed through the variable objects in the mapper_params. The key must be of the form key/output-[i], so the helper class simply removes the <app_name>/<pipeline_name>/ from it.

Title: Chaining MapReduces - Google AppEngine

Body:
I'm trying to send the output of a reduce to a map, by chaining in a pipeline, similar to this guy:
I would like to chain multiple mapreduce jobs in google app engine in Python
I tried his solution, but it didn't work.
The flow of my pipeline is:

Map1

Reduce1

Map2

Reduce2

I'm saving the output of Reduce1 to the blobstore under a blob_key, and then trying to access the blob from Map2. But I get the following error while executing the second map: "BadReaderParamsError: Could not find blobinfo for key <blob_key here>".

Here's the pipeline code:

class SongsPurchasedTogetherPipeline(base_handler.PipelineBase):

  def run(self, filekey, blobkey):
    bucket_name = app_identity.get_default_gcs_bucket_name()
    intermediate_output = yield mapreduce_pipeline.MapreducePipeline(
        "songs_purchased_together_intermediate",
        "main.songs_purchased_together_map1",
        "main.songs_purchased_together_reduce1",
        "mapreduce.input_readers.BlobstoreLineInputReader",
        "mapreduce.output_writers.GoogleCloudStorageOutputWriter",
        mapper_params={
            "blob_keys": blobkey,
        },
        reducer_params={
            "output_writer": {
                "bucket_name": bucket_name,
                "content_type": "text/plain",
            }
        },
        shards=1)
    yield StoreOutput("SongsPurchasedTogetherIntermediate", filekey, intermediate_output)

    intermediate_output_key = yield BlobKey(intermediate_output)
    output = yield mapreduce_pipeline.MapreducePipeline(
        "songs_purchased_together",
        "main.songs_purchased_together_map2",
        "main.songs_purchased_together_reduce2",
        "mapreduce.input_readers.BlobstoreLineInputReader",
        "mapreduce.output_writers.GoogleCloudStorageOutputWriter",
        mapper_params=(intermediate_output_key),
        reducer_params={
            "output_writer": {
                "bucket_name": bucket_name,
                "content_type": "text/plain",
            }
        },
        shards=1)
    yield StoreOutput("SongsPurchasedTogether", filekey, output)

and here's the BlobKey class which takes the intermediate output and generates the blob key for Map2 to use:

class BlobKey(base_handler.PipelineBase):

  def run(self, output):
    blobstore_filename = "/gs" + output[0]
    blobstore_gs_key = blobstore.create_gs_key(blobstore_filename)
    return {
      "blob_keys": blobstore_gs_key
    }

The StoreOutput class is the same as the one in Google's MapReduce demo https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/master/python/demo/main.py, and does the same thing as the BlobKey class, but additionally sends the blob's URL to HTML as a link.

Manually visiting the URL appname/blobstore/<blob_key>, by typing it into a browser (after Reduce1 succeeds, but Map2 fails) displays the output expected from Reduce1. Why can't Map2 find the blob? Sorry I'm a newbie to AppEngine, and I'm probably going wrong somewhere because I don't fully understand blob storage.

Body:
Okay, I found out that Google has removed the BlobstoreOutputWriter from the list of standard writers on the GAE GitHub repository, which makes things a little more complicated. I had to write to the Google Cloud Store, and read from there. I wrote a helper class which generates mapper parameters for the GoogleCloudStorageInputReader.

class GCSMapperParams(base_handler.PipelineBase):

  def run(self, GCSPath):
    bucket_name = app_identity.get_default_gcs_bucket_name()
    return {
            "input_reader": {
                "bucket_name": bucket_name,
                "objects": [path.split('/', 2)[2] for path in GCSPath],
            }
        }

The function takes as argument the output of one MapReduce stage which uses a GoogleCloudStorageOutputWriter, and returns a dictionary which can be assigned to mapper_params of the next MapReduce stage.

Basically, the value of the output of the first MapReduce stage is a list containing <app_name>/<pipeline_name>/key/output-[i], where i is the number of shards. In order to use a GoogleCloudStorageInputReader, the key to the data should be passed through the variable objects in the mapper_params. The key must be of the form key/output-[i], so the helper class simply removes the <app_name>/<pipeline_name>/ from it.


来源: stackexchange

问:
In C++, How std::list in a struct will allocate memory and while using this in file mapping, the list result as empty
Problem faced :
List shared by using file mapping does'nt provide any data inside the list...

I have a process 1, in which i store all my datas as a List of hash_map and then i try to share that using File mapping ... in Process2 while i try to retrieve the datas inside list, there is no data found inside list..

PS: My exe is bundled with dll, I make my dll as process1 and exe as process2...

Here is my code,

Process1

```<code>/* this is in common headerFile */
typedef hash_map <std::wstring,std::wstring> AttrValues;
CString FileName = L"E:\\DataLog.txt";
</code>```

TCHAR szName[]=TEXT("Local\MyFileMappingObject");

```<code>struct ADstruct
{
    std::list<AttrValues> StList;
    int i;
};

/*Sharememory.cpp*/
DWORD SharedMemory()
{
                AttrValues HardCode;//Sample data which i am hard coding for testing
                HardCode[L"NAme"] = L"Test";
                HardCode[L"D.Name"] = L"SAP";
                std::list <AttrValues> HardCodedList;
                HardCodedList.push_back(HardCode);

ADstruct CheckStruct;

CheckStruct.i = 10;
        CheckStruct.StList = HardCodedList;

HANDLE hFile = INVALID_HANDLE_VALUE;// HANDLE  hFile;

    hFile = CreateFile(FileName.GetBuffer(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Error in creating a file..!");
        return 0;
    }
hMapFile = CreateFileMapping(
        hFile, // use paging file
        NULL, // default security
        PAGE_READWRITE, // read/write access
        0, // maximum object size (high-order DWORD)
        sizeof(ADstruct), // maximum object size (low-order DWORD)
        szName); // name of mapping object

    if (hMapFile == NULL)
    {
        _tprintf(TEXT("Could not create file mapping object (%d).\n"),
                                                                     GetLastError());
        return 1;
    }
ADstruct *ADobj = new ADstruct;

ADobj = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
                                  FILE_MAP_ALL_ACCESS, // read/write permission
                                  0,
                                  0,
                                sizeof(ADstruct) );

    CopyMemory( (ADstruct *) ADobj, &CheckStruct , sizeof(ADstruct) );
UnmapViewOfFile(pBuf);

    CloseHandle(hMapFile);
return 0
}
</code>```

Process 2:

```<code>BOOL ReadMemoryMapping()
{
    hash_map<LPWSTR,LPWSTR> ADdata;

   HANDLE hMapFile;

   HANDLE hFile = INVALID_HANDLE_VALUE;
   hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not open file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }
ADstruct * readstruct;

    readstruct = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_ALL_ACCESS,  // read/write permission
               0,
               0,
              sizeof(ADstruct));
    _tprintf(L"\nprint data%d\n",readstruct->i);

    AttrValues At ;
    for(std::list<AttrValues>::iterator list_iter = readstruct->StList.begin();
        list_iter != readstruct->StList.end(); list_iter++)
    {
        At.clear();
         At = *list_iter; //*****Here the code crashes as there is no datas inside***
        if(At.empty() == 1)
            printf("List is empty\n");
        std::wcout<<endl<<endl<<"Attribute List In EXE : StList"<<endl;

        for(AttrValues :: iterator it1 = list_iter->begin(); it1!= list_iter->end(); it1++)
        {
            std::wcout<<it1->first<<endl;
            std::wcout<<it1->second<<endl;

        }
    }
 UnmapViewOfFile(readstruct);

   CloseHandle(hMapFile);

   return 0;
}
</code>```

答:
That’s possible for you to change.  The standard library template is:

```<code>template<class T, class Allocator = std::allocator<T> > class list;
</code>```

So you can provide your own memory allocator if you want, as the second template parameter.  If you use the default one, which is basically new, it would allocate nodes off the heap, which would not be in shared memory.  (That appears to be how you’re using the memory-mapped file.)  The other process would be able to read the head of each list, but not the rest of the nodes, allocated wherever.

You could instead, however, allocate a pool of nodes in shared memory and write your own allocator that handed out chunks of that shared memory until it was gone.  (If each shared-memory block is re-usable, the shared memory could be its own mini-heap.  If you can just delete all the lists at the same time when you’re done with them, though, it would suffice to unmap the shared-memory block.)

Or you could write your own list class that used indices into the pool of nodes in shared memory, rather than pointers, which is a layout that it would actually make potential sense to store in a file.  Or you could allocate a std::array statically in shared memory.  All its storage is inside the class object itself, and it’s fixed size, so it doesn’t allocate any memory outside the shared block and would work out of the box.

ContentLicense: CC BY-SA 3.0

Body:
Problem faced :
List shared by using file mapping does'nt provide any data inside the list...

I have a process 1, in which i store all my datas as a List of hash_map and then i try to share that using File mapping ... in Process2 while i try to retrieve the datas inside list, there is no data found inside list..

PS: My exe is bundled with dll, I make my dll as process1 and exe as process2...

Here is my code,

Process1

/* this is in common headerFile */
typedef hash_map <std::wstring,std::wstring> AttrValues;
CString FileName = L"E:\\DataLog.txt";

TCHAR szName[]=TEXT("Local\MyFileMappingObject");

struct ADstruct
{
    std::list<AttrValues> StList;
    int i;
};

/*Sharememory.cpp*/
DWORD SharedMemory()
{
                AttrValues HardCode;//Sample data which i am hard coding for testing
                HardCode[L"NAme"] = L"Test";
                HardCode[L"D.Name"] = L"SAP";
                std::list <AttrValues> HardCodedList;
                HardCodedList.push_back(HardCode);

ADstruct CheckStruct;

CheckStruct.i = 10;
        CheckStruct.StList = HardCodedList;

HANDLE hFile = INVALID_HANDLE_VALUE;// HANDLE  hFile;

    hFile = CreateFile(FileName.GetBuffer(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Error in creating a file..!");
        return 0;
    }
hMapFile = CreateFileMapping(
        hFile, // use paging file
        NULL, // default security
        PAGE_READWRITE, // read/write access
        0, // maximum object size (high-order DWORD)
        sizeof(ADstruct), // maximum object size (low-order DWORD)
        szName); // name of mapping object

    if (hMapFile == NULL)
    {
        _tprintf(TEXT("Could not create file mapping object (%d).\n"),
                                                                     GetLastError());
        return 1;
    }
ADstruct *ADobj = new ADstruct;

ADobj = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
                                  FILE_MAP_ALL_ACCESS, // read/write permission
                                  0,
                                  0,
                                sizeof(ADstruct) );

    CopyMemory( (ADstruct *) ADobj, &CheckStruct , sizeof(ADstruct) );
UnmapViewOfFile(pBuf);

    CloseHandle(hMapFile);
return 0
}

Process 2:

BOOL ReadMemoryMapping()
{
    hash_map<LPWSTR,LPWSTR> ADdata;

   HANDLE hMapFile;

   HANDLE hFile = INVALID_HANDLE_VALUE;
   hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not open file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }
ADstruct * readstruct;

    readstruct = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_ALL_ACCESS,  // read/write permission
               0,
               0,
              sizeof(ADstruct));
    _tprintf(L"\nprint data%d\n",readstruct->i);

    AttrValues At ;
    for(std::list<AttrValues>::iterator list_iter = readstruct->StList.begin();
        list_iter != readstruct->StList.end(); list_iter++)
    {
        At.clear();
         At = *list_iter; //*****Here the code crashes as there is no datas inside***
        if(At.empty() == 1)
            printf("List is empty\n");
        std::wcout<<endl<<endl<<"Attribute List In EXE : StList"<<endl;

        for(AttrValues :: iterator it1 = list_iter->begin(); it1!= list_iter->end(); it1++)
        {
            std::wcout<<it1->first<<endl;
            std::wcout<<it1->second<<endl;

        }
    }
 UnmapViewOfFile(readstruct);

   CloseHandle(hMapFile);

   return 0;
}

Body:
That’s possible for you to change.  The standard library template is:

template<class T, class Allocator = std::allocator<T> > class list;

So you can provide your own memory allocator if you want, as the second template parameter.  If you use the default one, which is basically new, it would allocate nodes off the heap, which would not be in shared memory.  (That appears to be how you’re using the memory-mapped file.)  The other process would be able to read the head of each list, but not the rest of the nodes, allocated wherever.

You could instead, however, allocate a pool of nodes in shared memory and write your own allocator that handed out chunks of that shared memory until it was gone.  (If each shared-memory block is re-usable, the shared memory could be its own mini-heap.  If you can just delete all the lists at the same time when you’re done with them, though, it would suffice to unmap the shared-memory block.)

Or you could write your own list class that used indices into the pool of nodes in shared memory, rather than pointers, which is a layout that it would actually make potential sense to store in a file.  Or you could allocate a std::array statically in shared memory.  All its storage is inside the class object itself, and it’s fixed size, so it doesn’t allocate any memory outside the shared block and would work out of the box.


问:
Codeigniter Htaccess didn't work on win 64-bit
My .htaccess file that worked in my Windows 32-bit XAMPP did not work when  moving my directory to a 64-bit Windows.

This URL works in my 32-bit windows but not on my 64-bit setup for which I get "object not found":

```<code>localhost/folder/controller
</code>```

But this URL does work:

```<code>localhost/folder/index.php/controller
</code>```

Here is my .htaccess file:

```<code>RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L]
</code>```

答:
I am on Windows 10 and XAMPP I use this.

htdocs > yourprojectname > .htaccess

```<code>Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

You can also try some more htaccess from here

https://github.com/wolfgang1983/htaccess_for_codeigniter

htdocs > yourprojectname > application > config.php

```<code>// Must set your base_url in config.php
$config['base_url'] = 'http://localhost/yourprojectname/';
$config['index_page'] = '';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My .htaccess file that worked in my Windows 32-bit XAMPP did not work when  moving my directory to a 64-bit Windows.

This URL works in my 32-bit windows but not on my 64-bit setup for which I get "object not found":

localhost/folder/controller

But this URL does work:

localhost/folder/index.php/controller

Here is my .htaccess file:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L]

Body:
I am on Windows 10 and XAMPP I use this.

htdocs > yourprojectname > .htaccess

Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

You can also try some more htaccess from here

https://github.com/wolfgang1983/htaccess_for_codeigniter

htdocs > yourprojectname > application > config.php

// Must set your base_url in config.php
$config['base_url'] = 'http://localhost/yourprojectname/';
$config['index_page'] = '';


问:
Session lost after form submit in wordpress
The session I set is lost after the form is submitted.

I had built the session class to set new session, unset and so on. In function.php of wordpress template.

function.php

```<code>if (!session_id()) {
    session_start();
}
include get_template_directory() . "/custom/session.php";
</code>```

Session.php

```<code>class session {
    function __construct() {

    }

    function set_flashdata($name, $value) {
        $_SESSION[$name] = $value;
    }

    function flashdata($name) {
        if (isset($_SESSION[$name])) {
            $str = $_SESSION[$name];
            return $str;
        } else {
            return FALSE;
        }
    }

    function userdata($name) {
        if (isset($_SESSION[$name])) {
            return $_SESSION[$name];
        } else {
            return FALSE;
        }
    }

    function set_userdata($name, $value) {
        $_SESSION[$name] = $value;
    }

    function unset_userdata($name) {
        if (isset($_SESSION[$name])) {
            unset($_SESSION[$name]);
        }
    }
}
</code>```

I try to set session as :

```<code><?php
    $sess = new session();
    $sess->set_userdata('sess_name',"some value");
?>
<form action="get_permalink(212);">
    //input buttons
</form>
</code>```

After submit the form it goes to the permalink(212). Then I tried.

```<code><?php
    $sess = new session();
    $value = $sess->userdata('sess_name');
    var_dump($value);      //returns false. That means session is lost after form submit. Why?
?>
</code>```

答:
You need to use wordpress global variable for condition that session is set or not something like :</p>

```<code>global $session;
if (!session_id()) {
    session_start();
}
include get_template_directory() . "/custom/session.php";
</code>```

Body:
The session I set is lost after the form is submitted.

I had built the session class to set new session, unset and so on. In function.php of wordpress template.

function.php

if (!session_id()) {
    session_start();
}
include get_template_directory() . "/custom/session.php";

Session.php

class session {
    function __construct() {

    }

    function set_flashdata($name, $value) {
        $_SESSION[$name] = $value;
    }

    function flashdata($name) {
        if (isset($_SESSION[$name])) {
            $str = $_SESSION[$name];
            return $str;
        } else {
            return FALSE;
        }
    }

    function userdata($name) {
        if (isset($_SESSION[$name])) {
            return $_SESSION[$name];
        } else {
            return FALSE;
        }
    }

    function set_userdata($name, $value) {
        $_SESSION[$name] = $value;
    }

    function unset_userdata($name) {
        if (isset($_SESSION[$name])) {
            unset($_SESSION[$name]);
        }
    }
}

I try to set session as :

<?php
    $sess = new session();
    $sess->set_userdata('sess_name',"some value");
?>
<form action="get_permalink(212);">
    //input buttons
</form>

After submit the form it goes to the permalink(212). Then I tried.

<?php
    $sess = new session();
    $value = $sess->userdata('sess_name');
    var_dump($value);      //returns false. That means session is lost after form submit. Why?
?>

Body:
You need to use wordpress global variable for condition that session is set or not something like :

global $session;
if (!session_id()) {
    session_start();
}
include get_template_directory() . "/custom/session.php";


问:
How does Python bitshift opeartors translate to set_downstream and set_upstream functionality in Airflow
I want to understand how Python bitshift operators >> and << are used for defining operator relationships in Airflow. I am not able to figure out the logic that can be used for translating the functionality of set_upstream() and set_downstream() methods using the bitshift operators. It will be helpful if someone can also point me to the relevant module in the Airflow code repo.

```<code>what makes       op1 >> op2 >> op3 << op4

equivalent to    op1.set_downstream(op2)
                 op2.set_downstream(op3)
                 op3.set_upstream(op4)
</code>```

答: >> and << are translated to the __lshift__/__rlshift__ and __rshift__/__rrshift__ methods of the relevant object.

Body:
I want to understand how Python bitshift operators >> and << are used for defining operator relationships in Airflow. I am not able to figure out the logic that can be used for translating the functionality of set_upstream() and set_downstream() methods using the bitshift operators. It will be helpful if someone can also point me to the relevant module in the Airflow code repo.

what makes       op1 >> op2 >> op3 << op4

equivalent to    op1.set_downstream(op2)
                 op2.set_downstream(op3)
                 op3.set_upstream(op4)


问:
Check if the string contains all the characters from a to z
I have to write a C# code to check if a string contains all the alphabets from a to z ."this is a test" (without quotes). It doesn't contain all alphabets from a to z so the  output is no.
 "abcdefghijklmnopqrstuvwxyz". It contains all alphabets from a to z so the  output is yes.</p>

答:
Here's how I'd approach it, initialise an array containing every letter:

```<code>char[] letters = new []{"a","b","c"...};
</code>```

Then initialise a list to hold all of the letters present in your string:

```<code>List<char> lettersInString = new List<char>();
</code>```

Now loop through your string adding distinct letters:

```<code>foreach (char letter in myString){if (!lettersInString.Contains(char)){lettersInString.Add(char);}}
</code>```

Finally, see if the list contains every letter:

```<code>if (letters.All(letter=>lettersInString.Contains(letter)){DoSomething();}
</code>```

That should do the trick!

Body:
Here's how I'd approach it, initialise an array containing every letter:

char[] letters = new []{"a","b","c"...};

Then initialise a list to hold all of the letters present in your string:

List<char> lettersInString = new List<char>();

Now loop through your string adding distinct letters:

foreach (char letter in myString){if (!lettersInString.Contains(char)){lettersInString.Add(char);}}

Finally, see if the list contains every letter:

if (letters.All(letter=>lettersInString.Contains(letter)){DoSomething();}

That should do the trick!


问:
cakePHP security
I am thinking of using cakePHP to build a web app. My question is how much of security stuff will I have to code myself to prevent (SQL injection etc)? What security stuff cakePHP takes care of by itself and what will I have to code?</p>

答:
Security in cake can be enable with few lines of code and using it's built in classes.

For Sql Injection protection

use cakephp $this->find will automatically sanitize your parameters but if you want to use raw query you can still sanitize your data using Sanitize::escape() method

For CSRF protection

you can enable it app/Controller/AppController.php

```</p>

```public $components = [
   'Security' => [
       'csrfUseOnce' => false,
       'csrfExpires' => '+1 hour',
   ],
];
```

<p>```

For XSS

if possible, always use cakephp Form Helper (http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html)

when your data is from text field, always print it using h() (Text to wrap through htmlspecialchars)

https://book.cakephp.org/2.0/en/core-libraries/components/security-component.html

ContentLicense: CC BY-SA 2.5

Title: cakePHP security

Body:
Security in cake can be enable with few lines of code and using it's built in classes.

For Sql Injection protection

use cakephp $this->find will automatically sanitize your parameters but if you want to use raw query you can still sanitize your data using Sanitize::escape() method

For CSRF protection

you can enable it app/Controller/AppController.php

```</p>

<pre><code>public $components = [
   'Security' => [
       'csrfUseOnce' => false,
       'csrfExpires' => '+1 hour',
   ],
];
</code></pre>

<p>```

For XSS

if possible, always use cakephp Form Helper (http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html)

when your data is from text field, always print it using h() (Text to wrap through htmlspecialchars)

https://book.cakephp.org/2.0/en/core-libraries/components/security-component.html


问:
Storing Images to use in application
I would like to store some images to use in my C# application.  They are png files and are currently in a folder with the dlls.  Ideally I would like to have them included with the dll so i dont have to include the actual images with the installation.

What is the best way to do this?

I have though about resx but i am unsure as to the best way to go about it.  Should I use create the resx file using another project, and then add it to the one I want to use it with?

Thanks in advance.

答: Put them in a resource file. You can add it to the same project, no need to create another one.</p>

Title: Storing Images to use in application


问:
computing Std deviation using RDD v/s SparkSQL in Python
I am pretty new to the world of spark ( and to an extend even Python , but better). I am trying to compute the standard deviation and had used the following code. The first using SparkSQL and the code is as follows:

```<code> sqlsd=spark.sql("SELECT STDDEV(temperature) as stdtemp from
 washing").first().stdtemp
 print(sqlsd)
</code>```

The above works fine ( I think) and it gives the result as 6.070

Now when I try to do this using RDD with the following code:-

```<code> def sdTemperature(df,spark):
    n=float(df.count())
    m=meanTemperature(df,spark)
    df=df.fillna({'_id':0,'_rev':0,'count':0,'flowrate':0,'fluidlevel':0,
   'frequency':0,'hardness':0,'speed':0,'temperature':0,'ts':0,'voltage':0})
    rddT=df.rdd.map(lambda r: r.temperature)
    c=rddT.count()
    s=rddT.map(lambda x: pow(x-m,2)).sum()
    print(n,c,s)
    sd=sqrt(s/c)
    return sd
</code>```

when I run the above code, I get a different result. the value I get is 53.195

what I am in doing wrong?. All I am trying to do above is to compute the std deviation for a spark dataframe column temperature and use lambda.

thanks in advance for help ..

答:
There are two types of standard deviations - please refer to this : https://math.stackexchange.com/questions/15098/sample-standard-deviation-vs-population-standard-deviation

Similar question -
Calculate the standard deviation of grouped data in a Spark DataFrame

The stddev() in Hive is a pointer to the stddev_samp(). The stddev_pop() is what you are looking for(inferred from the 2nd part of you code). So your sql query should be select stddev_pop(temperature) as stdtemp from washing

Body:
I am pretty new to the world of spark ( and to an extend even Python , but better). I am trying to compute the standard deviation and had used the following code. The first using SparkSQL and the code is as follows:

 sqlsd=spark.sql("SELECT STDDEV(temperature) as stdtemp from
 washing").first().stdtemp
 print(sqlsd)

The above works fine ( I think) and it gives the result as 6.070

Now when I try to do this using RDD with the following code:-

 def sdTemperature(df,spark):
    n=float(df.count())
    m=meanTemperature(df,spark)
    df=df.fillna({'_id':0,'_rev':0,'count':0,'flowrate':0,'fluidlevel':0,
   'frequency':0,'hardness':0,'speed':0,'temperature':0,'ts':0,'voltage':0})
    rddT=df.rdd.map(lambda r: r.temperature)
    c=rddT.count()
    s=rddT.map(lambda x: pow(x-m,2)).sum()
    print(n,c,s)
    sd=sqrt(s/c)
    return sd

when I run the above code, I get a different result. the value I get is 53.195

what I am in doing wrong?. All I am trying to do above is to compute the std deviation for a spark dataframe column temperature and use lambda.

thanks in advance for help ..


问:
How do I split a list of array?
Here is the list array:

```<code>{"things":{"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}
</code>```

here is the code:

```<code>var t = things;
string aa = t[0].ToString();
</code>```

How do I split the above array in , separator and _ .
from the above array i want only 1_4,3_13...this column and save in two different var.

when I am using

```<code>string[] ss = aa.Split(new char[] { ',', '|', }, System.StringSplitOptions.RemoveEmptyEntries);
</code>```

the problem is that in first list {"things":{"1":"1_4".
comes

so how to remove {"things"??

答:
You should first split by { then discard the first and after that you are left with:

"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}

Now you split with , and get

"1":"1_4"

"3":"3_13" and so on.

Then you split each with : and take the second one.

Only remember that the last one is "7_32"}} which you should remove the trailing }}

Like this:

```<code>var elems = aa.Split(new[] { '{' })[1].Split(new[] { ',' });
var res = elems.Select(obj => obj.Trim("}".ToCharArray()).Split(new[] { ':' }));
</code>```

Hope this is what you want :)

Title: How do I split a list of array?

Body:
Here is the list array:

{"things":{"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}

here is the code:

var t = things;
string aa = t[0].ToString();

How do I split the above array in , separator and _ .
from the above array i want only 1_4,3_13...this column and save in two different var.

when I am using

string[] ss = aa.Split(new char[] { ',', '|', }, System.StringSplitOptions.RemoveEmptyEntries);

the problem is that in first list {"things":{"1":"1_4".
comes

so how to remove {"things"??

Body:
You should first split by { then discard the first and after that you are left with:

"1":"1_4","3":"3_13","4":"4_18","5":"5_25","6":"6_28","7":"7_32"}}

Now you split with , and get

"1":"1_4"

"3":"3_13" and so on.

Then you split each with : and take the second one.

Only remember that the last one is "7_32"}} which you should remove the trailing }}

Like this:

var elems = aa.Split(new[] { '{' })[1].Split(new[] { ',' });
var res = elems.Select(obj => obj.Trim("}".ToCharArray()).Split(new[] { ':' }));

Hope this is what you want :)


问:
store username in keychain with different key
I want to store username and password in keychain.  As far I have explored we can store it and retrieve it like this

Store username and password

```<code>[_keychainObject setObject:username forKey:(id)kSecAttrAccount];
[_keychainObject setObject:password forKey:(id)kSecValueData];
</code>```

Retrieve username and password

```<code>NSLog(@"%@", [_keychainObject objectForKey:(id)kSecAttrAccount]);
NSLog(@"%@", [_keychainObject objectForKey:(id)kSecValueData]);
</code>```

Why can't we store it like this

```<code>[_keychainObject setObject:username forKey:@"username"];
</code>```

If I do so its not storing the data.  Is it mandatory to use predefined keys to store an item in keychain?

答:
For Objective-C try

https://github.com/kishikawakatsumi/UICKeyChainStore

for Swift try

https://github.com/kishikawakatsumi/KeychainAccess

```<code>var keychain = Keychain()
keychain["username"] = "abc" // Set string
var userName = keychain["username"] // Get string
</code>```

Body:
I want to store username and password in keychain.  As far I have explored we can store it and retrieve it like this

Store username and password

[_keychainObject setObject:username forKey:(id)kSecAttrAccount];
[_keychainObject setObject:password forKey:(id)kSecValueData];

Retrieve username and password

NSLog(@"%@", [_keychainObject objectForKey:(id)kSecAttrAccount]);
NSLog(@"%@", [_keychainObject objectForKey:(id)kSecValueData]);

Why can't we store it like this

[_keychainObject setObject:username forKey:@"username"];

If I do so its not storing the data.  Is it mandatory to use predefined keys to store an item in keychain?

Body:
For Objective-C try

https://github.com/kishikawakatsumi/UICKeyChainStore

for Swift try

https://github.com/kishikawakatsumi/KeychainAccess

var keychain = Keychain()
keychain["username"] = "abc" // Set string
var userName = keychain["username"] // Get string


问:
Set Toolbar logo in XML
Is it possible to set Toolbar logo in xml? I have tried this so far:

1.

```<code><android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
    android:logo="@drawable/my_logo"
    />
</code>```

2.

```<code><android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
    app:logo="@drawable/my_logo"
    />
</code>```

EDIT

I'm using toolbar as an actionbar in my AppCompatActivity:

```<code>setSupportActionBar(findViewById(R.id.toolbar));
</code>```

I'm able to set logo from code:

```<code>((Toolbar) findViewById(R.id.toolbar)).setLogo(R.drawable.my_logo);
</code>```

But I'd like to set logo either from layout XML or from Style/Theme XML.

答:
Using xml only

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

<style name="ActionbarLogo">
    <item name="android:logo">@drawable/ic_menu_camera</item>
    <item name="android:displayOptions">useLogo</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="android:actionBarStyle">@style/ActionbarLogo</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

Now apply AppTheme.NoActionBar theme to your activity( and if you want to remove toolbar title use getSupportActionBar().setDisplayShowTitleEnabled(false); after setSupportActionBar(toolbar);)

```<code><activity
  android:name=".MainActivity"
  android:theme="@style/AppTheme.NoActionBar">
  <intent-filter>
      <action android:name="android.intent.action.MAIN"/>

      <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
</activity>
</code>```

Title: Set Toolbar logo in XML

Body:
Is it possible to set Toolbar logo in xml? I have tried this so far:

1.

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
    android:logo="@drawable/my_logo"
    />

2.

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
    app:logo="@drawable/my_logo"
    />

EDIT

I'm using toolbar as an actionbar in my AppCompatActivity:

setSupportActionBar(findViewById(R.id.toolbar));

I'm able to set logo from code:

((Toolbar) findViewById(R.id.toolbar)).setLogo(R.drawable.my_logo);

But I'd like to set logo either from layout XML or from Style/Theme XML.

Body:
Using xml only

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

<style name="ActionbarLogo">
    <item name="android:logo">@drawable/ic_menu_camera</item>
    <item name="android:displayOptions">useLogo</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="android:actionBarStyle">@style/ActionbarLogo</item>
    <item name="windowNoTitle">true</item>
</style>

Now apply AppTheme.NoActionBar theme to your activity( and if you want to remove toolbar title use getSupportActionBar().setDisplayShowTitleEnabled(false); after setSupportActionBar(toolbar);)

<activity
  android:name=".MainActivity"
  android:theme="@style/AppTheme.NoActionBar">
  <intent-filter>
      <action android:name="android.intent.action.MAIN"/>

      <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
</activity>


问:
Shift + Enter no longer adds a new line in Visual Studio
I installed the Visual Studio 2010 productivity power tools, and since then Shift + Enter does not add a new line in the text editor. I've tried disabling all of the productivity tools settings and even uninstalling the productivity power tools entirely, but Shift + Enter still does nothing. I can't find the setting for this.

How can I re-enable shift + enter to add a space (just like enter alone does)?

答: From Options menu, select "Environment", then "Keyboard" that gives you the option of setting keyboard shortcuts. The one you want should be "Edit.BreakLine" - you can search for them. Selecting this, you can then add/remove assosciated shortcuts.</p>


问:
codenvy: How to create a persistent file?
I'm learning codenvy.io, and have most of my code in git. This part works well with projects.

However, the code has a secrets file, which is not in git, but is created on the individual computers that you are running the code on. Using codenvy, this file is removed everytime I restart my workplace.

Is there a way to tag this file as "persistent", even though it cannot be in git?

答:
You could add to your git repo a  smudge script as a filter content driver in a (also versioned) .gitattribute file:

On any git checkout, the smudge script will be called and can fetch your secret file (provided it can access the file on the individual computer, or provided that file is stored in a shared accessible path somehow), and create it in your working tree (as a file ignored by the .gitignore)


问:
Angular2 RC7 ng2-datetime Error- ($(...).datepicker is not a function)
I declare some var and replace $ to jQuery.

1.i declare var jQuery: any;
   2. replace $ to jQuery;  (error clear in ts)
   3. configure in system.config.json and import in app.module
   4. And i have bootstrap-datepicker in node-module

The error is datetime input box didn't work and the error show in console like this ($(...).datepicker is not a function). I changed $ to jQuery in ts.Please Help Me.

ng2-datetime.ts

```<code>  import {
            Component, Output, Input, EventEmitter, HostListener, AfterViewInit, OnDestroy,
            SimpleChanges, OnChanges
        } from '@angular/core';
        import { ControlValueAccessor, NgControl } from '@angular/forms';
        import { TimepickerEvent } from './timepicker-event-interface';
        declare var jQuery: any;

    @Component({
        selector: 'datetime',
        template: `
        <div class="form-inline">
            <div id="{{idDatePicker}}" class="input-group date">
                <input type="text" class="form-control"
                       [attr.readonly]="readonly"
                       [attr.placeholder]="datepickerOptions.placeholder || 'Choose date'"
                       [(ngModel)]="dateModel"
                       (keyup)="checkEmptyValue($event)"/>
                <div class="input-group-addon">
                    <span [ngClass]="datepickerOptions.icon || 'glyphicon glyphicon-th'"></span>
                </div>
            </div>
            <div class="input-group bootstrap-timepicker timepicker">
                <input id="{{idTimePicker}}" type="text" class="form-control input-small"
                       [attr.readonly]="readonly"
                       [attr.placeholder]="timepickerOptions.placeholder || 'Set time'"
                       [(ngModel)]="timeModel"
                       (keyup)="checkEmptyValue($event)">
                <span class="input-group-addon"><i [ngClass]="timepickerOptions.icon || 'glyphicon glyphicon-time'"></i></span>
            </div>
            <button *ngIf="hasClearButton" type="button" (click)="onClearClick()">Clear</button>
        </div>
       `
    })
    export class NKDatetime implements ControlValueAccessor, AfterViewInit, OnDestroy, OnChanges {
        @Output()
        dateChange: EventEmitter<Date> = new EventEmitter<Date>();

        @Input('timepicker')
        timepickerOptions: any = {};

        @Input('datepicker')
        datepickerOptions: any = {};

        @Input('hasClearButton')
        hasClearButton: boolean = false;

        @Input()
        readonly: boolean = null;

        date: Date; // ngModel
        dateModel: string;
        timeModel: string;

        // instances
        datepicker: any;
        timepicker: any;

        private idDatePicker: string = uniqueId('q-datepicker_');
        private idTimePicker: string = uniqueId('q-timepicker_');

        @HostListener('dateChange', ['$event'])
        onChange = (_: any) => {
        };
        onTouched = () => {
        };

        constructor(ngControl: NgControl) {
            ngControl.valueAccessor = this; // override valueAccessor
        }

        ngAfterViewInit() {
            this.init();
        }

        ngOnDestroy() {
            if (this.datepicker) {
                this.datepicker.datepicker('destroy');
            }
            if (this.timepicker) {
                this.timepicker.timepicker('remove');
            }
        }

        ngOnChanges(changes: SimpleChanges) {
            if (changes) {
                if (changes['datepickerOptions'] && this.datepicker) {
                    this.datepicker.datepicker('destroy');

                    if (changes['datepickerOptions'].currentValue) {
                        this.datepicker = null;
                        this.init();
                    } else if (changes['datepickerOptions'].currentValue === false) {
                        this.datepicker.remove();
                    }
                }
                if (changes['timepickerOptions'] && this.timepicker) {
                    this.timepicker.timepicker('remove');

                    if (changes['timepickerOptions'].currentValue) {
                        this.timepicker = null;
                        this.init();
                    } else if (changes['timepickerOptions'].currentValue === false) {
                        this.timepicker.parent().remove();
                    }
                }
            }
        }

        writeValue(value: any): void {
            this.date = value;
            if (isDate(this.date)) {
                setTimeout(() => {
                    this.updateModel(this.date);
                }, 0);
            }
        }

        registerOnChange(fn: (_: any) => void): void {
            this.onChange = fn;
        }

        registerOnTouched(fn: () => void): void {
            this.onTouched = fn;
        }

        checkEmptyValue(e: any) {
            const value = e.target.value;
            if (value === '' && (
                    this.timepickerOptions === false ||
                    this.datepickerOptions === false ||
                    (this.timeModel === '' && this.dateModel === '')
                )) {
                this.dateChange.emit(null);
            }
        }

        onClearClick() {
            this.dateChange.emit(null);
            if (this.timepicker) {
                this.timepicker.timepicker('setTime', null);
            }
            this.updateDatepicker(null);
        }

        //////////////////////////////////

        private init(): void {
            if (!this.datepicker && this.datepickerOptions !== false) {
                let options = jQuery.extend({ enableOnReadonly: !this.readonly }, this.datepickerOptions);
                this.datepicker = (<any>jQuery('#' + this.idDatePicker)).datepicker(options);
                this.datepicker
                    .on('changeDate', (e: any) => {
                        let newDate: Date = e.date;

                        if (isDate(this.date) && isDate(newDate)) {
                            // get hours/minutes
                            var h = this.date.getHours();
                            var m = this.date.getMinutes();
                            newDate.setHours(h);
                            newDate.setMinutes(m);
                        }

                        this.date = newDate;
                        this.dateChange.emit(newDate);
                    });
            } else if (this.datepickerOptions === false) {
                (<any>jQuery('#' + this.idDatePicker)).remove();
            }

            if (!this.timepicker && this.timepickerOptions !== false) {
                let options = jQuery.extend({ defaultTime: false }, this.timepickerOptions);
                this.timepicker = (<any>jQuery('#' + this.idTimePicker)).timepicker(options);
                this.timepicker
                    .on('changeTime.timepicker', (e: TimepickerEvent) => {
                        let { meridian, hours } = e.time;

                        if (meridian) {
                            // has meridian -> convert 12 to 24h
                            if (meridian === 'PM' && hours < 12) {
                                hours = hours + 12;
                            }
                            if (meridian === 'AM' && hours === 12) {
                                hours = hours - 12;
                            }
                            hours = parseInt(this.pad(hours));
                        }

                        if (!isDate(this.date)) {
                            this.date = new Date();
                            this.updateDatepicker(this.date);
                        }

                        this.date.setHours(hours);
                        this.date.setMinutes(e.time.minutes);
                        this.dateChange.emit(this.date);
                    });
            } else if (this.timepickerOptions === false) {
                (<any>jQuery('#' + this.idTimePicker)).parent().remove();
            }
        }

        private updateModel(date: Date): void {
            this.updateDatepicker(date);

            // update timepicker
            if (this.timepicker !== undefined) {
                let hours = date.getHours();
                if (this.timepickerOptions.showMeridian) {
                    // Convert 24 to 12 hour system
                    hours = (hours === 0 || hours === 12) ? 12 : hours % 12;
                }
                const meridian = date.getHours() >= 12 ? ' PM' : ' AM';
                const time =
                    this.pad(hours) + ':' +
                    this.pad(this.date.getMinutes()) +
                    (this.timepickerOptions.showMeridian || this.timepickerOptions.showMeridian === undefined
                        ? meridian : '');
                this.timepicker.timepicker('setTime', time);
                this.timeModel = time; // fix initial empty timeModel bug
            }
        }

        private updateDatepicker(value?: any) {
            if (this.datepicker !== undefined) {
                this.datepicker.datepicker('update', value);
            }
        }

        private pad(value: any): string {
            return value.toString().length < 2 ? '0' + value : value.toString();
        }
    }

    let id: number = 0;
    function uniqueId(prefix: string): string {
        return prefix + ++id;
    }

    function isDate(obj: any) {
        return Object.prototype.toString.call(obj) === '[object Date]';
    }
</code>```

```<code>System.config.json
</code>```

```<code>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      moment:'node_modules/moment/moment.js',
      '@ng-bootstrap/ng-bootstrap': 'node_modules/@ng-bootstrap/ng-bootstrap/bundles/ng-bootstrap.js',

      'mydatepicker' :'npm:mydatepicker',

      'ng2-datetime': "npm:ng2-datetime",
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                       'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      'ng2-datetime': {
                main: './ng2-datetime.js',
                defaultExtension: 'js'
            },
      mydatepicker : {
        main :'./index.js',
        defaultExtension:'js'
      },
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

error console image

答:
just import these lines to index.html after

```<code><script src="node_modules/systemjs/dist/system.src.js"></script>
</code>```

lines:

```<code><script src="node_modules/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap-datepicker/dist/css/bootstrap-datepicker3.min.css">
<script src="node_modules/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap-timepicker/css/bootstrap-timepicker.min.css">
<script src="node_modules/bootstrap-timepicker/js/bootstrap-timepicker.js"></script>
</code>```

Body:
I declare some var and replace $ to jQuery.

1.i declare var jQuery: any;
   2. replace $ to jQuery;  (error clear in ts)
   3. configure in system.config.json and import in app.module
   4. And i have bootstrap-datepicker in node-module

The error is datetime input box didn't work and the error show in console like this ($(...).datepicker is not a function). I changed $ to jQuery in ts.Please Help Me.

ng2-datetime.ts

  import {
            Component, Output, Input, EventEmitter, HostListener, AfterViewInit, OnDestroy,
            SimpleChanges, OnChanges
        } from '@angular/core';
        import { ControlValueAccessor, NgControl } from '@angular/forms';
        import { TimepickerEvent } from './timepicker-event-interface';
        declare var jQuery: any;

    @Component({
        selector: 'datetime',
        template: `

                <input type="text" class="form-control"
                       [attr.readonly]="readonly"
                       [attr.placeholder]="datepickerOptions.placeholder || 'Choose date'"
                       [(ngModel)]="dateModel"
                       (keyup)="checkEmptyValue($event)"/>

                <input id="{{idTimePicker}}" type="text" class="form-control input-small"
                       [attr.readonly]="readonly"
                       [attr.placeholder]="timepickerOptions.placeholder || 'Set time'"
                       [(ngModel)]="timeModel"
                       (keyup)="checkEmptyValue($event)">

            <button *ngIf="hasClearButton" type="button" (click)="onClearClick()">Clear</button>

       `
    })
    export class NKDatetime implements ControlValueAccessor, AfterViewInit, OnDestroy, OnChanges {
        @Output()
        dateChange: EventEmitter<Date> = new EventEmitter<Date>();

        @Input('timepicker')
        timepickerOptions: any = {};

        @Input('datepicker')
        datepickerOptions: any = {};

        @Input('hasClearButton')
        hasClearButton: boolean = false;

        @Input()
        readonly: boolean = null;

        date: Date; // ngModel
        dateModel: string;
        timeModel: string;

        // instances
        datepicker: any;
        timepicker: any;

        private idDatePicker: string = uniqueId('q-datepicker_');
        private idTimePicker: string = uniqueId('q-timepicker_');

        @HostListener('dateChange', ['$event'])
        onChange = (_: any) => {
        };
        onTouched = () => {
        };

        constructor(ngControl: NgControl) {
            ngControl.valueAccessor = this; // override valueAccessor
        }

        ngAfterViewInit() {
            this.init();
        }

        ngOnDestroy() {
            if (this.datepicker) {
                this.datepicker.datepicker('destroy');
            }
            if (this.timepicker) {
                this.timepicker.timepicker('remove');
            }
        }

        ngOnChanges(changes: SimpleChanges) {
            if (changes) {
                if (changes['datepickerOptions'] && this.datepicker) {
                    this.datepicker.datepicker('destroy');

                    if (changes['datepickerOptions'].currentValue) {
                        this.datepicker = null;
                        this.init();
                    } else if (changes['datepickerOptions'].currentValue === false) {
                        this.datepicker.remove();
                    }
                }
                if (changes['timepickerOptions'] && this.timepicker) {
                    this.timepicker.timepicker('remove');

                    if (changes['timepickerOptions'].currentValue) {
                        this.timepicker = null;
                        this.init();
                    } else if (changes['timepickerOptions'].currentValue === false) {
                        this.timepicker.parent().remove();
                    }
                }
            }
        }

        writeValue(value: any): void {
            this.date = value;
            if (isDate(this.date)) {
                setTimeout(() => {
                    this.updateModel(this.date);
                }, 0);
            }
        }

        registerOnChange(fn: (_: any) => void): void {
            this.onChange = fn;
        }

        registerOnTouched(fn: () => void): void {
            this.onTouched = fn;
        }

        checkEmptyValue(e: any) {
            const value = e.target.value;
            if (value === '' && (
                    this.timepickerOptions === false ||
                    this.datepickerOptions === false ||
                    (this.timeModel === '' && this.dateModel === '')
                )) {
                this.dateChange.emit(null);
            }
        }

        onClearClick() {
            this.dateChange.emit(null);
            if (this.timepicker) {
                this.timepicker.timepicker('setTime', null);
            }
            this.updateDatepicker(null);
        }

        //////////////////////////////////

        private init(): void {
            if (!this.datepicker && this.datepickerOptions !== false) {
                let options = jQuery.extend({ enableOnReadonly: !this.readonly }, this.datepickerOptions);
                this.datepicker = (<any>jQuery('#' + this.idDatePicker)).datepicker(options);
                this.datepicker
                    .on('changeDate', (e: any) => {
                        let newDate: Date = e.date;

                        if (isDate(this.date) && isDate(newDate)) {
                            // get hours/minutes
                            var h = this.date.getHours();
                            var m = this.date.getMinutes();
                            newDate.setHours(h);
                            newDate.setMinutes(m);
                        }

                        this.date = newDate;
                        this.dateChange.emit(newDate);
                    });
            } else if (this.datepickerOptions === false) {
                (<any>jQuery('#' + this.idDatePicker)).remove();
            }

            if (!this.timepicker && this.timepickerOptions !== false) {
                let options = jQuery.extend({ defaultTime: false }, this.timepickerOptions);
                this.timepicker = (<any>jQuery('#' + this.idTimePicker)).timepicker(options);
                this.timepicker
                    .on('changeTime.timepicker', (e: TimepickerEvent) => {
                        let { meridian, hours } = e.time;

                        if (meridian) {
                            // has meridian -> convert 12 to 24h
                            if (meridian === 'PM' && hours < 12) {
                                hours = hours + 12;
                            }
                            if (meridian === 'AM' && hours === 12) {
                                hours = hours - 12;
                            }
                            hours = parseInt(this.pad(hours));
                        }

                        if (!isDate(this.date)) {
                            this.date = new Date();
                            this.updateDatepicker(this.date);
                        }

                        this.date.setHours(hours);
                        this.date.setMinutes(e.time.minutes);
                        this.dateChange.emit(this.date);
                    });
            } else if (this.timepickerOptions === false) {
                (<any>jQuery('#' + this.idTimePicker)).parent().remove();
            }
        }

        private updateModel(date: Date): void {
            this.updateDatepicker(date);

            // update timepicker
            if (this.timepicker !== undefined) {
                let hours = date.getHours();
                if (this.timepickerOptions.showMeridian) {
                    // Convert 24 to 12 hour system
                    hours = (hours === 0 || hours === 12) ? 12 : hours % 12;
                }
                const meridian = date.getHours() >= 12 ? ' PM' : ' AM';
                const time =
                    this.pad(hours) + ':' +
                    this.pad(this.date.getMinutes()) +
                    (this.timepickerOptions.showMeridian || this.timepickerOptions.showMeridian === undefined
                        ? meridian : '');
                this.timepicker.timepicker('setTime', time);
                this.timeModel = time; // fix initial empty timeModel bug
            }
        }

        private updateDatepicker(value?: any) {
            if (this.datepicker !== undefined) {
                this.datepicker.datepicker('update', value);
            }
        }

        private pad(value: any): string {
            return value.toString().length < 2 ? '0' + value : value.toString();
        }
    }

    let id: number = 0;
    function uniqueId(prefix: string): string {
        return prefix + ++id;
    }

    function isDate(obj: any) {
        return Object.prototype.toString.call(obj) === '[object Date]';
    }

System.config.json

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      moment:'node_modules/moment/moment.js',
      '@ng-bootstrap/ng-bootstrap': 'node_modules/@ng-bootstrap/ng-bootstrap/bundles/ng-bootstrap.js',

      'mydatepicker' :'npm:mydatepicker',

      'ng2-datetime': "npm:ng2-datetime",
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                       'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      'ng2-datetime': {
                main: './ng2-datetime.js',
                defaultExtension: 'js'
            },
      mydatepicker : {
        main :'./index.js',
        defaultExtension:'js'
      },
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

error console image

Body:
just import these lines to index.html after

<script src="node_modules/systemjs/dist/system.src.js"></script>

lines:

<script src="node_modules/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap-datepicker/dist/css/bootstrap-datepicker3.min.css">
<script src="node_modules/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap-timepicker/css/bootstrap-timepicker.min.css">
<script src="node_modules/bootstrap-timepicker/js/bootstrap-timepicker.js"></script>


问:
Convert an indexed pandas matrix to a flat dataframe
Given the dataframe:

```<code>df = pd.DataFrame([['foo', 123, 4, 5, 0, 1], ['foo', 123, 4, 0, 9, 1], ['bar', 33, 0, 0, 3, 5]], columns=list('ABCDEF'))
</code>```

[out]:

```<code>    A   B   C   D   E   F
0   foo 123 4   5   0   1
1   foo 123 4   0   9   1
2   bar 33  0   0   3   5
</code>```

The goal is to sum certain columns ('C', 'D', 'E', F') using other columns ('A' and 'B') as keys to achieve:

```<code>    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5
</code>```

I've tried:

```<code>df.groupby(['A', 'B']).sum()
</code>```

[out]:

```<code>        C   D   E   F
A   B
bar 33  0   0   3   5
foo 123 8   5   9   2
</code>```

How do I change it back to the non-indexed matrix? i.e.

```<code>    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5
</code>```

答:
You can use parameter as_index=False for return df:

```<code>df1 = df.groupby(['A', 'B'], as_index=False).sum()
print (df1)
     A    B  C  D  E  F
0  bar   33  0  0  3  5
1  foo  123  8  5  9  2
</code>```

Body:
Given the dataframe:

df = pd.DataFrame([['foo', 123, 4, 5, 0, 1], ['foo', 123, 4, 0, 9, 1], ['bar', 33, 0, 0, 3, 5]], columns=list('ABCDEF'))

[out]:

    A   B   C   D   E   F
0   foo 123 4   5   0   1
1   foo 123 4   0   9   1
2   bar 33  0   0   3   5

The goal is to sum certain columns ('C', 'D', 'E', F') using other columns ('A' and 'B') as keys to achieve:

    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5

I've tried:

df.groupby(['A', 'B']).sum()

[out]:

        C   D   E   F
A   B
bar 33  0   0   3   5
foo 123 8   5   9   2

How do I change it back to the non-indexed matrix? i.e.

    A   B   C   D   E   F
0   foo 123 8   5   9   2
2   bar 33  0   0   3   5

Body:
You can use parameter as_index=False for return df:

df1 = df.groupby(['A', 'B'], as_index=False).sum()
print (df1)
     A    B  C  D  E  F
0  bar   33  0  0  3  5
1  foo  123  8  5  9  2


问:
Usergrid system requirements?
question, how much resources I need to run apache usergrid?
I mean hardware resources, RAM CPU

I want to deploy apache usergrid to be used as backed in our apps, the apps have a low traffic now, are custom projects to be used in small users groups (<10k)

I want to know the minimum requirements to know if it is viable for us, thanks.

答:
From what I see of usergrid, I can think that the most hungry for resources component will be Elasticsearch, so to have a production environment that's working well, I guess you should start following ES' requirements:

At least 8 GB of RAM

At least 4 cores (the more cores you give Elasticsearch, the more love you get as it tends to works with a lot of threading, i.e. give more cores rather than more CPU processing power)

Fast HDDs should perform fine

See this article on Elasticsearch.A last thing is that depending on your system, you can tune several settings on Elasticsearch to achieve a better throughput. (For instance see https://www.elastic.co/guide/en/elasticsearch/reference/master/tune-for-indexing-speed.html)

Title: Usergrid system requirements?


问:
Groovy JsonSlurper and Maps with (Sub) Objects
I am trying to marshal and unmarshal a groovy bean. I am using the functionality later on in Java. The idea is I am marshalling the object using the JsonOutput and unmarshal it with the JsonSlurper. My bean includes a map of sub objects.

The problem is, that JsonSlurper is unmarshalling the values of the map to a LazyMap and not to the original object. If I include the object directly the unmarshalling works.

Here an example of what I am doing...

```<code>import java.util.Map

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

class ClassA {

    ClassB subClass

    Map<String, ClassB> subClasses = [:]

    static def ClassA build(String json){
        new JsonSlurper().parseText(json)
    }

    def String toString() {
        JsonOutput.toJson(this)
    }
}
</code>```

...and ClassB...

```<code>import groovy.json.JsonOutput

class ClassB {

    String message = [:]

    def String toString() {
        JsonOutput.toJson(this)
    }
}
</code>```

...and here the Java code that fails...

```<code>ClassA classA = new ClassA();
ClassB classB = new ClassB();
classB.setMessage("Hello World!");
classA.setSubClass(classB);
classA.getSubClasses().put("First", classB);

System.out.println(ClassA.build(classA.toString()).getSubClass().getMessage());
System.out.println(ClassA.build(classA.toString()).getSubClasses().get("First").getMessage());
</code>```

...the second last line prints "Hello World!", as expected but the last line fails with...

```<code>java.lang.ClassCastException: groovy.json.internal.LazyMap cannot be cast to ClassB
</code>```

Is there a (better) way to marshal and unmarshal a groovy object to json?

Regards,
Thomas

答:
Jackson does the trick and works reliable...

ClassA

```<code>import com.fasterxml.jackson.databind.ObjectMapper

class ClassA {

    ClassB subClass

    Map<String, ClassB> subClasses = [:]

    static def ClassA build(String json){
        new ObjectMapper().readValue(json, ClassA.class)
    }

    def String toString() {
        StringWriter writer = new StringWriter()
        try {
            new ObjectMapper().writeValue(writer, this)
            return writer.toString()
        }
        finally {
            writer.close()
        }
    }
}
</code>```

And ClassB

```<code>import com.fasterxml.jackson.databind.ObjectMapper

class ClassB {

    String message = [:]

    def String toString() {
        StringWriter writer = new StringWriter()
        try {
            new ObjectMapper().writeValue(writer, this)
            return writer.toString()
        }
        finally {
            writer.close()
        }
    }
}
</code>```

Body:
I am trying to marshal and unmarshal a groovy bean. I am using the functionality later on in Java. The idea is I am marshalling the object using the JsonOutput and unmarshal it with the JsonSlurper. My bean includes a map of sub objects.

The problem is, that JsonSlurper is unmarshalling the values of the map to a LazyMap and not to the original object. If I include the object directly the unmarshalling works.

Here an example of what I am doing...

import java.util.Map

import groovy.json.JsonOutput
import groovy.json.JsonSlurper

class ClassA {

    ClassB subClass

    Map<String, ClassB> subClasses = [:]

    static def ClassA build(String json){
        new JsonSlurper().parseText(json)
    }

    def String toString() {
        JsonOutput.toJson(this)
    }
}

...and ClassB...

import groovy.json.JsonOutput

class ClassB {

    String message = [:]

    def String toString() {
        JsonOutput.toJson(this)
    }
}

...and here the Java code that fails...

ClassA classA = new ClassA();
ClassB classB = new ClassB();
classB.setMessage("Hello World!");
classA.setSubClass(classB);
classA.getSubClasses().put("First", classB);

System.out.println(ClassA.build(classA.toString()).getSubClass().getMessage());
System.out.println(ClassA.build(classA.toString()).getSubClasses().get("First").getMessage());

...the second last line prints "Hello World!", as expected but the last line fails with...

java.lang.ClassCastException: groovy.json.internal.LazyMap cannot be cast to ClassB

Is there a (better) way to marshal and unmarshal a groovy object to json?

Regards,
Thomas

Body:
Jackson does the trick and works reliable...

ClassA

import com.fasterxml.jackson.databind.ObjectMapper

class ClassA {

    ClassB subClass

    Map<String, ClassB> subClasses = [:]

    static def ClassA build(String json){
        new ObjectMapper().readValue(json, ClassA.class)
    }

    def String toString() {
        StringWriter writer = new StringWriter()
        try {
            new ObjectMapper().writeValue(writer, this)
            return writer.toString()
        }
        finally {
            writer.close()
        }
    }
}

And ClassB

import com.fasterxml.jackson.databind.ObjectMapper

class ClassB {

    String message = [:]

    def String toString() {
        StringWriter writer = new StringWriter()
        try {
            new ObjectMapper().writeValue(writer, this)
            return writer.toString()
        }
        finally {
            writer.close()
        }
    }
}


问:
django: Selecting a freign key from 2 models
I am developing a blog styled application. I want to implement something like custom tags. (Trying to do the tag app myself, so I can learn something).

So I want to be able to create tags in admin interface, and want to be able to assign the to either my Section or Article model. I wonder if that's possible to make an model which will give ability to chose object (e.g. article or section)

I was looking on django comments app, but I would like to do something more simple. Is that possible?

答:
Have a look at generic relations. A generic foreign key enables you to have have a foreign key relationship without having to define the target model in the code.

But I'd recommend to use django-tagging, which is a ready-made generic django tagging application which provides you a lot of additional functionality and is pretty easy to integrate (it also works via generic relations).


问:
Context.getContentResolver().query() gives null pointer exception
I am working on a music project where I am using a song's id to find out its title. This is the function that I use to do so. It is in MetadataFinder class.

```<code>public static String getSongFromID(long id, Context context) {
        Uri mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE};
        String selection = MediaStore.Audio.Media._ID + "=?";
        String[] selectionArgs = new String[]{"" + id}; //This is the id you are looking for

        Cursor mediaCursor = context.getContentResolver().query(mediaContentUri, projection, selection, selectionArgs, null);

        if (mediaCursor.getCount() >= 0) {
            mediaCursor.moveToPosition(0);
            String title = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            return title;
            //Do something with the data
        }
        return null;
    }
</code>```

This has worked very well so far. But now when I am calling this method from another portion of code it gives null pointer exception.

I have two fragments from where I send broadcast to the main activity. The main activity broadcast receiver calls a function in a service, lets call it MainService. This method in the service calls the above method getSongFromID. I am calling this method from both the fragments. For the same values of 'id' and context 'MainService.this', I get exception in one case while the other works fine.

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getCount()' on a null object reference
at com.app.utils.MetadataFinder.getSongFromID(CommonUtils.java:331)
at com.app.services.MainService.playSong(MainService.java:189)
at com.app.activity.MainActivity.initPanelBottom(MainActivity.java:235)
at com.app.activity.MainActivity$1.onReceive(MainActivity.java:155)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

I can't understand what the reason behind this might be as I see no difference in any of the involved parameters. Can someone please help me !!

```<code>String title = MetadataFinder.getSongFromID(i, MainService.this);
</code>```

This is how I am calling getSongFromId() function. It is a static function in MetadataFinder class.

答:
make sure you initialize your Helper Class's object in Content Provider's class's onCreate() method.

For example:

Body:
I am working on a music project where I am using a song's id to find out its title. This is the function that I use to do so. It is in MetadataFinder class.

public static String getSongFromID(long id, Context context) {
        Uri mediaContentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE};
        String selection = MediaStore.Audio.Media._ID + "=?";
        String[] selectionArgs = new String[]{"" + id}; //This is the id you are looking for

        Cursor mediaCursor = context.getContentResolver().query(mediaContentUri, projection, selection, selectionArgs, null);

        if (mediaCursor.getCount() >= 0) {
            mediaCursor.moveToPosition(0);
            String title = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            return title;
            //Do something with the data
        }
        return null;
    }

This has worked very well so far. But now when I am calling this method from another portion of code it gives null pointer exception.

I have two fragments from where I send broadcast to the main activity. The main activity broadcast receiver calls a function in a service, lets call it MainService. This method in the service calls the above method getSongFromID. I am calling this method from both the fragments. For the same values of 'id' and context 'MainService.this', I get exception in one case while the other works fine.

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getCount()' on a null object reference
at com.app.utils.MetadataFinder.getSongFromID(CommonUtils.java:331)
at com.app.services.MainService.playSong(MainService.java:189)
at com.app.activity.MainActivity.initPanelBottom(MainActivity.java:235)
at com.app.activity.MainActivity$1.onReceive(MainActivity.java:155)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

I can't understand what the reason behind this might be as I see no difference in any of the involved parameters. Can someone please help me !!

String title = MetadataFinder.getSongFromID(i, MainService.this);

This is how I am calling getSongFromId() function. It is a static function in MetadataFinder class.


问:
SAPUI5 - Refrech OData model
I'm working on a SAPUI5 Master Detail application with Odata model Two Way Binding.
When I click on a header element and enter data for its items and click submit, the entered data is still there.
Even if I click on another Header element, if I go back to the previous header element its data is still there.
I want the entire model to be completely refreshed on every click on a header element.
I tried SubmitChanges method, but it's not working ... </p>

答:
Check out the below sap archive

https://archive.sap.com/discussions/thread/3649362

Title: SAPUI5 - Refrech OData model


问:
Not able to get iframe to work
I'm basically trying to create a page that can show 3 Google searches of the user's choice simultaneously. I had code that did this for images (would go search for the input on Flickr and display the image) but I thought it would be cool to apply the same concept with Google searches. What am I doing wrong?

```<code></style>
 </head>
  <body>

<div class="comic" >
  <div id="panel-1" class="scene" >
    <iframe id="search-1"></iframe>
    <p   id="topic-1">
      Topic: <input type="text" id="topic-input-1">
      <button onclick="setSearch(1)" class="set-search-button">Go</button>
    </p>
  </div>

  <div id="panel-2" class="scene">
    <iframe id="search-2"></iframe>
    <p   id="topic-2">
      Topic: <input type="text" id="topic-input-2">
      <button onclick="setSearch(2)" class="set-search-button">Go</button>
    </p>
  </div>

  <div id="panel-3" class="scene">
    <iframe id="search-3"></iframe>
    <p   id="topic-3">
      Topic: <input type="text" id="topic-input-3">
      <button onclick="setSearch(3)" class="set-search-button">Go</button>
    </p>
  </div>

<script>
  function setSearch(panel){
    var query;
    query=document.getElementById("topic-input-"+panel).value
    document.getElementById("search-"+panel).src ="https://www.google.ca/#q="+ query +"&*"

    document.getElementById("topic-"+panel).style.display="none";
  }

</script>
</code>```

Here's the CSS code:

```<code><style>
.comic {
  max-width: 826px;
  margin: 60px auto 0;

}
.scene {
  width: 250px;
  height: 250px;
  border: 3px solid black;
  background: white;
  margin: 8px;
  display: inline-block;
  position: relative;
}
.scene img {
  width: 100%;
  height: 100%;
  display: block;
}

</style>
</code>```

答:
Google is preventing cross origin framming. Some servers however do set that X-Frame Header for cross domain request.

Also keep in mind the contents will also be blocked if your a trying to access secure info (https) from an insecure source (http)

This is the message from the browser console

```<code>Load denied by X-Frame-Options: https://www.google.ca/#q=f&* does not permit cross-origin framing.
</code>```

Title: Not able to get iframe to work

Body:
I'm basically trying to create a page that can show 3 Google searches of the user's choice simultaneously. I had code that did this for images (would go search for the input on Flickr and display the image) but I thought it would be cool to apply the same concept with Google searches. What am I doing wrong?

</style>

      Topic: <input type="text" id="topic-input-1">
      <button onclick="setSearch(1)" class="set-search-button">Go</button>

      Topic: <input type="text" id="topic-input-2">
      <button onclick="setSearch(2)" class="set-search-button">Go</button>

      Topic: <input type="text" id="topic-input-3">
      <button onclick="setSearch(3)" class="set-search-button">Go</button>

Here's the CSS code:

Body:
Google is preventing cross origin framming. Some servers however do set that X-Frame Header for cross domain request.

Also keep in mind the contents will also be blocked if your a trying to access secure info (https) from an insecure source (http)

This is the message from the browser console

Load denied by X-Frame-Options: https://www.google.ca/#q=f&* does not permit cross-origin framing.


问:
Reading HTML content from a UIWebView
Is it possible to read the raw HTML content of a web page that has been loaded into a UIWebView?

If not, is there another way to pull raw HTML content from a web page in the iPhone SDK (such as an equivalent of the .NET WebClient::openRead)?

答:
Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

Also note that the @"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

Title: Reading HTML content from a UIWebView


问:
Disable all events in Print preview mode
In chrome print preview mode, I can able to click some links and it's navigating to that urls. I want to disable all events in chrome print preview mode. I tried multiple ways none is worked out.</p>

答:
You could do something like this. Using CSS, in print view, disable click for all anchor tags.</p>

```<code>@media print
{
  a {pointer-events: none; cursor: default;}
}
</code>```

Body:
You could do something like this. Using CSS, in print view, disable click for all anchor tags.

@media print
{
  a {pointer-events: none; cursor: default;}
}


答:
You need loc:

```<code>print (df_freq.loc['2012-03-04 21:00:00'])
freq    0
Name: 2012-03-04 21:00:00, dtype: int64
</code>```

First snippet works, because use datetimeindex partial string indexing:

```<code>print (df_freq['2012-03-04'])
</code>```

Title: Referencing Pandas dataframe using a datetimeindex

Body:
I'm having difficulty accessing a pandas dataframe using a DateTimeIndex. I have created a dataframe with a DateTimeIndex and a column of zeros

import pandas as pd
earliest = pd.Timestamp('2012-01-01 06:00:00')
latest = pd.Timestamp('2014-12-01 23:00:00')
dr = pd.date_range (start=earliest, end=latest,freq="30min" )
df_freq = pd.DataFrame(index=dr, columns=['freq'])
df_freq = df_freq.fillna(0)

I can reference the dataframe using a date formatted as a string:

df_freq['2012-03-04']

gives

                         freq
2012-03-04 00:00:00     0
2012-03-04 00:30:00     0
2012-03-04 01:00:00     0
2012-03-04 01:30:00     0
2012-03-04 02:00:00     0
2012-03-04 02:30:00     0
2012-03-04 03:00:00     0
2012-03-04 03:30:00     0
2012-03-04 04:00:00     0
2012-03-04 04:30:00     0
2012-03-04 05:00:00     0
2012-03-04 05:30:00     0
2012-03-04 06:00:00     0
2012-03-04 06:30:00     0
2012-03-04 07:00:00     0
2012-03-04 07:30:00     0
2012-03-04 08:00:00     0
2012-03-04 08:30:00     0
2012-03-04 09:00:00     0
2012-03-04 09:30:00     0
2012-03-04 10:00:00     0
2012-03-04 10:30:00     0
2012-03-04 11:00:00     0
2012-03-04 11:30:00     0
2012-03-04 12:00:00     0
2012-03-04 12:30:00     0
2012-03-04 13:00:00     0
2012-03-04 13:30:00     0
2012-03-04 14:00:00     0
2012-03-04 14:30:00     0
2012-03-04 15:00:00     0
2012-03-04 15:30:00     0
2012-03-04 16:00:00     0
2012-03-04 16:30:00     0
2012-03-04 17:00:00     0
2012-03-04 17:30:00     0
2012-03-04 18:00:00     0
2012-03-04 18:30:00     0
2012-03-04 19:00:00     0
2012-03-04 19:30:00     0
2012-03-04 20:00:00     0
2012-03-04 20:30:00     0
2012-03-04 21:00:00     0
2012-03-04 21:30:00     0
2012-03-04 22:00:00     0
2012-03-04 22:30:00     0
2012-03-04 23:00:00     0
2012-03-04 23:30:00     0

but if I reference a specific datetime, I get an error:

df_freq['2012-03-04 21:00:00']

gives

        Traceback (most recent call last):
      File "...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1945, in get_loc
        return self._engine.get_loc(key)
      File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
      File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
      File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
      File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
    KeyError: '2012-03-04 21:00:00'
    During handling of the above exception, another exception occurred:
    Traceback (most recent call last):
      File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-31-d748d9ec4f91>", line 1, in <module>
        df_freq['2012-03-04 21:00:00']
      File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__
        return self._getitem_column(key)
      File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column
        return self._get_item_cache(key)
      File "...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache
        values = self._data.get(item)
      File "...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py", line 3290, in get
        loc = self.items.get_loc(item)
      File "...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
        return self._engine.get_loc(self._maybe_cast_indexer(key))
      File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
      File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
      File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
      File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
    KeyError: '2012-03-04 21:00:00'

Also, I don't understand why I can't reference the dataframe using a Timestamp object, rather than a string

    ts=pd.Timestamp('2012-03-04')
    df_freq[ts]

gives this error:

    Traceback (most recent call last):
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1945, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
  File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
  File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
  File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: Timestamp('2012-03-04 00:00:00')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-37-29e033bc2394>", line 1, in <module>
    df_freq[ts]
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__
    return self._getitem_column(key)
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column
    return self._get_item_cache(key)
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1350, in _get_item_cache
    values = self._data.get(item)
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\internals.py", line 3290, in get
    loc = self.items.get_loc(item)
  File "...AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 1947, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154)
  File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018)
  File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368)
  File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12322)
KeyError: Timestamp('2012-03-04 00:00:00')

Body:
You need loc:

print (df_freq.loc['2012-03-04 21:00:00'])
freq    0
Name: 2012-03-04 21:00:00, dtype: int64

First snippet works, because use datetimeindex partial string indexing:

print (df_freq['2012-03-04'])


问:
java : Is it possible to dynamically modify the code of a servlet's method (like doPost)
I'm trying to write a Framework like Spring MVC.
I'm looking for a way to modify the code of the doPost/doGet method of a servlet 3.0 deployed on tomcat using javassist or reflection or whatever so the doPost can call a service method dynamically defined .

```<code>doPost(...){

    ServiceClassName.methodeName(); // dynamic line of code

}
</code>```

Thanks

答: It is possible using javassist. Refer this to write your Transformer class.</p>

Body:
I'm trying to write a Framework like Spring MVC.
I'm looking for a way to modify the code of the doPost/doGet method of a servlet 3.0 deployed on tomcat using javassist or reflection or whatever so the doPost can call a service method dynamically defined .

doPost(...){

    ServiceClassName.methodeName(); // dynamic line of code

}

Thanks