问:
why cant I define a global function in a header file?
I have this function I am trying to define in  my header in which i also have defined a class, but for some reason it this not possible, as I don't see why it is causing so many problems.

database.h

```<code>//#pragma once

#ifndef DATABASE_H
#define DATABASE_H

#include "record.h"
#include "spectogram.h"
#include <iostream>
#include <experimental/filesystem>

#define string_dir_to_test_files "/home/noob/soundcloud/src/include/database/test_files/"

class database {
public:
    vector<AudioFile<SAMPLE>> list_of_files;
    database();

};

int number_of_files(std::experimental::filesystem::path path);

#endif DATABASE_H
</code>```

database.cpp

```<code>#include "database.h"

int number_of_files(std::experimental::filesystem::path path)
{
    using std::experimental::filesystem::directory_iterator;
    return std::distance(directory_iterator(path),directory_iterator(path));
}

database::database()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << "\n"
             << "root_name() = " << _path.root_name() << "\n"
             << "root_path() = " << _path.root_path() << "\n"
             << "relative_path() = " << _path.relative_path() << "\n"
             << "parent_path() = " << _path.parent_path() << "\n"
             << "filename() = " << _path.filename() << "\n"
             << "stem() = " << _path.stem() << "\n"
             << "extension() = " << _path.extension() << "\n";

        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
    }

}
</code>```

spectogram.h

```<code>#pragma once

#include <sigpack.h>
#include "AudioFile.h"
#include <iostream>

typedef float SAMPLE;

class spectogram {
public:
    spectogram();
    arma::mat generate_spectogram(const AudioFile<SAMPLE> *file)
    {
        arma::mat output;
        if(file->getNumChannels() == 2)
        {
            std::cout << "I am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::Col<SAMPLE> ch2 = file->samples[1];
            arma::mat output = sp::specgram(ch1);
            return output;
        }
        else
        {
            std::cout << "I am am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::mat output = sp::specgram(ch1);
            std::cout << output << std::endl;
            return output;
        }

    }
};
</code>```

record.h the audiofile include is this one

```<code>#pragma once
#include <iostream> // Functionality: COUT
#include "portaudio.h"
#include <stdio.h>
#include <stdlib.h>
#include <chrono>  //Functionality: Sleep
#include <thread>   //Functionality: Sleep
#include <algorithm> //Functionality: fill_n
#include "AudioFile.h"
#define SAMPLE_RATE (44100)

typedef float SAMPLE;

#define NUM_SECONDS 10
#define NUM_CHANNELS  1
#define SAMPLE_SILENCE 0.0f
#define PA_SAMPLE_TYPE  paFloat32
#define FRAMES_PER_BUFFER (512)
#define TRUE (1==1)
#define FALSE (!TRUE)
#define WRITE_TO_FILE   TRUE

typedef struct
{
    int     frameIndex;
    int     maxFrameindex;
    SAMPLE  *recordedSamples;
}
paTestData;

class record {
public:
    record();
    void start_record();
    AudioFile<SAMPLE>           file;

private:
    PaStreamParameters  inputParameters,
                        outputParameters;
    PaStream*           stream;
    PaError             err = paNoError;
    paTestData          data;
    int                 totalFrames;
    int                 numSamples;
    int                 numBytes;
    SAMPLE              max, val;
    double              average;
    int recordCallback(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer,
                       const PaStreamCallbackTimeInfo* timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData);

    static int recordCallbackSub(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData)
    {
        auto pThis = reinterpret_cast<record*>(userData);  // get back the this pointer.
        return pThis->recordCallback( inputBuffer, outputBuffer,framesPerBuffer, timeInfo,statusFlags, nullptr);

    }
};
</code>```

match.h

```<code>#pragma once
#include <iostream>

class match {
public:

};
</code>```

main.cpp

```<code>#include <record.h>
#include <database.h>
#include <match.h>
#include <spectogram.h>
#include <iostream>

int main()
{
    database start;
    //record  somethis;
    //somethis.start_record();
    //spectogram specto;
    //specto.generate_spectogram(&somethis.file);
    return 0;
}
</code>```

gives me these warnings:

```<code>make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
Scanning dependencies of target match
[ 84%] Building CXX object src/include/match/CMakeFiles/match.dir/match.cpp.o
[ 89%] Linking CXX static library libmatch.a
[ 89%] Built target match
Scanning dependencies of target cmakeDemo
[ 94%] Building CXX object src/CMakeFiles/cmakeDemo.dir/main.cpp.o
In file included from /home/noob/soundcloud/src/main.cpp:2:0:
/home/noob/soundcloud/src/include/database/database.h:25:8: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif DATABASE_H
        ^~~~~~~~~~
[100%] Linking CXX executable ../cmakeDemo
[100%] Built target cmakeDemo
</code>```

but the warnings remove if #include<match.h> is commented?

```<code>make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
[ 89%] Built target match
[100%] Built target cmakeDemo
</code>```

Something is very weird?

答:
Based on your output, I see one warning here:

```<code>In file included from /home/noob/soundcloud/src/main.cpp:2:0:
/home/noob/soundcloud/src/include/database/database.h:25:8: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif DATABASE_H
        ^~~~~~~~~~
</code>```

At the end of database.h, the #endif preprocessor has an extra DATABASE_H token at the end.  #endif doesn't take any additional tokens, so remove it:

```<code>...
#endif
</code>```

Body:
I have this function I am trying to define in  my header in which i also have defined a class, but for some reason it this not possible, as I don't see why it is causing so many problems.

database.h

//#pragma once

#ifndef DATABASE_H
#define DATABASE_H

#include "record.h"
#include "spectogram.h"
#include <iostream>
#include <experimental/filesystem>

#define string_dir_to_test_files "/home/noob/soundcloud/src/include/database/test_files/"

class database {
public:
    vector<AudioFile<SAMPLE>> list_of_files;
    database();

};

int number_of_files(std::experimental::filesystem::path path);

#endif DATABASE_H

database.cpp

#include "database.h"

int number_of_files(std::experimental::filesystem::path path)
{
    using std::experimental::filesystem::directory_iterator;
    return std::distance(directory_iterator(path),directory_iterator(path));
}

database::database()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << "\n"
             << "root_name() = " << _path.root_name() << "\n"
             << "root_path() = " << _path.root_path() << "\n"
             << "relative_path() = " << _path.relative_path() << "\n"
             << "parent_path() = " << _path.parent_path() << "\n"
             << "filename() = " << _path.filename() << "\n"
             << "stem() = " << _path.stem() << "\n"
             << "extension() = " << _path.extension() << "\n";

        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
    }

}

spectogram.h

#pragma once

#include <sigpack.h>
#include "AudioFile.h"
#include <iostream>

typedef float SAMPLE;

class spectogram {
public:
    spectogram();
    arma::mat generate_spectogram(const AudioFile<SAMPLE> *file)
    {
        arma::mat output;
        if(file->getNumChannels() == 2)
        {
            std::cout << "I am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::Col<SAMPLE> ch2 = file->samples[1];
            arma::mat output = sp::specgram(ch1);
            return output;
        }
        else
        {
            std::cout << "I am am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::mat output = sp::specgram(ch1);
            std::cout << output << std::endl;
            return output;
        }

    }
};

record.h the audiofile include is this one

#pragma once
#include <iostream> // Functionality: COUT
#include "portaudio.h"
#include <stdio.h>
#include <stdlib.h>
#include <chrono>  //Functionality: Sleep
#include <thread>   //Functionality: Sleep
#include <algorithm> //Functionality: fill_n
#include "AudioFile.h"
#define SAMPLE_RATE (44100)

typedef float SAMPLE;

#define NUM_SECONDS 10
#define NUM_CHANNELS  1
#define SAMPLE_SILENCE 0.0f
#define PA_SAMPLE_TYPE  paFloat32
#define FRAMES_PER_BUFFER (512)
#define TRUE (1==1)
#define FALSE (!TRUE)
#define WRITE_TO_FILE   TRUE

typedef struct
{
    int     frameIndex;
    int     maxFrameindex;
    SAMPLE  *recordedSamples;
}
paTestData;

class record {
public:
    record();
    void start_record();
    AudioFile<SAMPLE>           file;

private:
    PaStreamParameters  inputParameters,
                        outputParameters;
    PaStream*           stream;
    PaError             err = paNoError;
    paTestData          data;
    int                 totalFrames;
    int                 numSamples;
    int                 numBytes;
    SAMPLE              max, val;
    double              average;
    int recordCallback(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer,
                       const PaStreamCallbackTimeInfo* timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData);

    static int recordCallbackSub(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData)
    {
        auto pThis = reinterpret_cast<record*>(userData);  // get back the this pointer.
        return pThis->recordCallback( inputBuffer, outputBuffer,framesPerBuffer, timeInfo,statusFlags, nullptr);

    }
};

match.h

#pragma once
#include <iostream>

class match {
public:

};

main.cpp

#include <record.h>
#include <database.h>
#include <match.h>
#include <spectogram.h>
#include <iostream>

int main()
{
    database start;
    //record  somethis;
    //somethis.start_record();
    //spectogram specto;
    //specto.generate_spectogram(&somethis.file);
    return 0;
}

gives me these warnings:

make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
Scanning dependencies of target match
[ 84%] Building CXX object src/include/match/CMakeFiles/match.dir/match.cpp.o
[ 89%] Linking CXX static library libmatch.a
[ 89%] Built target match
Scanning dependencies of target cmakeDemo
[ 94%] Building CXX object src/CMakeFiles/cmakeDemo.dir/main.cpp.o
In file included from /home/noob/soundcloud/src/main.cpp:2:0:
/home/noob/soundcloud/src/include/database/database.h:25:8: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif DATABASE_H
        ^~~~~~~~~~
[100%] Linking CXX executable ../cmakeDemo
[100%] Built target cmakeDemo

but the warnings remove if #include<match.h> is commented?

make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
[ 89%] Built target match
[100%] Built target cmakeDemo

Something is very weird?

Body:
Based on your output, I see one warning here:

In file included from /home/noob/soundcloud/src/main.cpp:2:0:
/home/noob/soundcloud/src/include/database/database.h:25:8: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif DATABASE_H
        ^~~~~~~~~~

At the end of database.h, the #endif preprocessor has an extra DATABASE_H token at the end.  #endif doesn't take any additional tokens, so remove it:

...
#endif


来源: stackexchange

问:
When is StringIO used, as opposed to joining a list of strings?
Using StringIO as string buffer is slower than using list as buffer.

When is StringIO used?

```<code>from io import StringIO

def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()

if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
</code>```

Results:

```<code>16.7872819901
18.7160351276
</code>```

答:
The main advantage of StringIO is that it can be used where a file was expected. So you can do for example (for Python 2):</p>

```<code>import sys
import StringIO

out = StringIO.StringIO()
sys.stdout = out
print "hi, I'm going out"
sys.stdout = sys.__stdout__
print out.getvalue()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using StringIO as string buffer is slower than using list as buffer.

When is StringIO used?

from io import StringIO

def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()

if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())

Results:

16.7872819901
18.7160351276

Body:
The main advantage of StringIO is that it can be used where a file was expected. So you can do for example (for Python 2):

import sys
import StringIO

out = StringIO.StringIO()
sys.stdout = out
print "hi, I'm going out"
sys.stdout = sys.__stdout__
print out.getvalue()


问:
Error: specify a date within the permissible range
We are trying to create a Sales Order and are receiving "specify a date within the permissible range".

So after some Googling, I have seen that the most common reason for this is that your Due Date and Document Date are not within the same Posting Period as the Posting Date.

As seen here in the SAP documentation:

https://help.sap.com/saphelp_sbo900/helpdata/en/e4/428eaaf7d941448a591699918fcc06/frameset.htm

However, as you can see from our screen shot, this is already correct. Further, this only started happening overnight and no one touched a thing, I swear! :)

Does anyone have any advice please?

答: I did not fully trust being told that NOTHING had changed. By clicking on the Yellow arrow beside the Posting Period in the posting period window, I saw that the document date range had been changed from ending in May 2018 to May 2017. Job done. This was found by sticking close to the error message and not straying too far in my thinking. Reagan had it right! Trust but verify! ;)</p>

ContentLicense: CC BY-SA 3.0


问:
How to import the same txt file (That updated daily) to Excel
I have a txt file that automatically do updates in a daily bases, I have to open that txt file in Excel (Delimited) and review the data.
What is the way to make Excel automatically import that specific txt file?
Or in another words: I need to Double click on a saved Excel file and it will automatically import that specific txt file (instead of doing File->open->Browse...)
Thanks!</p>

答:
What version of Excel do you have? If you have Excel 2016 or later, you can use the new functionality under the 'Get and Transform' tab to do this really easily. In previous versions, you can download the free Microsoft "PowerQuery" addin that was the forerunner for this.  It was previously a separate add-in called PowerQuery, and is now bulk standard in Excel.

There's many excellent walkthroughs on the internet showing this exact type of activity. Google "PowerQuery" and put a date filter on your results to show just the last year, as the functionality is constantly being updated. Add "Ken Puls" to your search term, and see what bubbles to the top. Then replace Ken "Mike Girvin" or "ExcelIsFun" and you should see like a zillion excellent tutorials on PowerQuery. Try "ExcelCampus" too, as Jon has great tutorials, as does "Chandoo". Also replace PowerQuery with "Get and Transform" and repeat those same searches.

PowerQuery is simple to learn, and lets you do stuff just by "muddling through" that would otherwise take a year or more to learn if you wanted to pick up VBA.

It acts like a user-friendly macro recorder, only unlike the macro recorder it spits out reusable code that doesn't have hard coded references in it, meaning all you need to do his hit Refresh.


问:
HTML5 Video autoplay on Mobile Browser
I am using the following HTML5 and JQuery code to play a playlist of videos whose URLs are in an array URLArray[].

```<code>function NextFrag(){

 if (index < URLArray.length)
 {
   $("#VideoContainer").html('<video  id="video1" controls autoplay width="95%"> "<source src= "'+ URLArray[index]+ '" type="video/mp4"></source> </video>' );
   index++;
   $("#video1").bind( "ended", NextFrag);
 }
}
</code>```

As we know that the autoplay feature of HTML5 is disabled in all mobile phones, as a result I have to play manually each video clip on mobile phone. which is definitely what I do not want.

I really want to know the alternative to this. I am really interested in code segment that I can include to make like autoplay without involving user to interact.

Is it possible to convert this to an android app to work. I am really in need to make it work like a play list, and I have no concern about how, I just need this functionality.

Please help.

答: On Mobile Chrome I had the Data-Saving option enabled, which by default disables autoplay muted videos, for which case GIF's are a partial low-quality+high-bandwith solution.</p>

Title: HTML5 Video autoplay on Mobile Browser

Body:
I am using the following HTML5 and JQuery code to play a playlist of videos whose URLs are in an array URLArray[].

function NextFrag(){

 if (index < URLArray.length)
 {
   $("#VideoContainer").html('<video  id="video1" controls autoplay width="95%"> "<source src= "'+ URLArray[index]+ '" type="video/mp4"></source> </video>' );
   index++;
   $("#video1").bind( "ended", NextFrag);
 }
}

As we know that the autoplay feature of HTML5 is disabled in all mobile phones, as a result I have to play manually each video clip on mobile phone. which is definitely what I do not want.

I really want to know the alternative to this. I am really interested in code segment that I can include to make like autoplay without involving user to interact.

Is it possible to convert this to an android app to work. I am really in need to make it work like a play list, and I have no concern about how, I just need this functionality.

Please help.


问:
VS 2017 Debug Error
I'm getting an error when I try to inspect variables in my VS 2017 C# code.  The errors started with an upgrade.

```<code>Native View To inspect the native object, enable native code debugging.
</code>```

The a google search suggests the following fix, but I cannot find this option on y Project-Properties-Debug page.

```<code>To enable debugging of unmanaged code
</code>```

With a project selected in Solution Explorer, on the Project menu, click Properties.
Click the Debug tab.
Select the Enable unmanaged code debugging check box.

答:
Try This

add the following to your profile in launchsettings.json

"nativeDebugging" : true

I have also read some posts it says like
starting in Visual Studio 2017 version 15.5 you should be able to set <EnableUnmanagedDebugging>true</EnableUnmanagedDebugging> in your .csproj file.

Title: VS 2017 Debug Error

Body:
I'm getting an error when I try to inspect variables in my VS 2017 C# code.  The errors started with an upgrade.

Native View To inspect the native object, enable native code debugging.

The a google search suggests the following fix, but I cannot find this option on y Project-Properties-Debug page.

To enable debugging of unmanaged code

With a project selected in Solution Explorer, on the Project menu, click Properties.
Click the Debug tab.
Select the Enable unmanaged code debugging check box.


问:
Get-Process Couldn't Connect to remote machine
I was recently attempting to setup a script using powershell so that I could monitor a critical process on a remote computer.

```<code>Get-Process -ComputerName myremotepc myprocess
</code>```

This was giving me the following error.

```<code>Get-Process : Couldn't connect to remote machine.
At line:1 char:1
+ Get-Process -ComputerName myremotepc myprocess
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-Process],     InvalidOperationException
+ FullyQualifiedErrorId :     System.InvalidOperationException,Microsoft.PowerShell.Commands.GetProcessCommand
</code>```

After checking to see that the correct services were enabled. I still can not connect.

答:
I came across the following link.

https://social.technet.microsoft.com/Forums/projectserver/en-US/f58c4ca9-0708-401a-8d66-86195006174d/simple-remote-command-getprocess-how-to-get-the-two-machines-talking-to-each-other?forum=winserverpowershell

On that page one user suggested that enable remoting be turned on in powershell for the pc you want to connect to.

```<code># Enable Remoting
Enable-PSRemoting
</code>```

After running this in powershell in an elevated prompt I can query the remote pc.

```<code>Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
811      38        27696      28568   233              3196 explorer
</code>```

Body:
I was recently attempting to setup a script using powershell so that I could monitor a critical process on a remote computer.

Get-Process -ComputerName myremotepc myprocess

This was giving me the following error.

Get-Process : Couldn't connect to remote machine.
At line:1 char:1
+ Get-Process -ComputerName myremotepc myprocess
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Get-Process],     InvalidOperationException
+ FullyQualifiedErrorId :     System.InvalidOperationException,Microsoft.PowerShell.Commands.GetProcessCommand

After checking to see that the correct services were enabled. I still can not connect.

Body:
I came across the following link.

https://social.technet.microsoft.com/Forums/projectserver/en-US/f58c4ca9-0708-401a-8d66-86195006174d/simple-remote-command-getprocess-how-to-get-the-two-machines-talking-to-each-other?forum=winserverpowershell

On that page one user suggested that enable remoting be turned on in powershell for the pc you want to connect to.

# Enable Remoting
Enable-PSRemoting

After running this in powershell in an elevated prompt I can query the remote pc.

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
811      38        27696      28568   233              3196 explorer


问:
Does anybody know good graphical morphing code or algorithm?
I'm building a small app and I need to be able to morph one image into another. Any pointers would be appreciated.</p>

答:
Thanks for these pointers! I think I need to morph the image on the client, in Flex/Flash. My current thought is that I'll interpret a homework assignment that I found:

http://cns-web.bu.edu/~oph/cs580_assign1/p1.html

into ActionScript and build a UI around it. It uses the Beier-Neely algorithm that nickspilman mentioned. I'll let y'all know how it turns out.

OwnerDisplayName: Vineel Shah

ContentLicense: CC BY-SA 2.5


问:
How do you switch pages in Xamarin.Forms?
How do you switch between pages in Xamarin Forms?

My main page is a ContentPage and I don't want to switch to something like a Tabbed Page.

I've been able to pseudo-do it by finding parents of the controls that should trigger the new page until I find the ContentPage and then swap out the Content with controls for a new page. But this seems really sloppy.

答:
XAML page  add this </p>

```<code><ContentPage.ToolbarItems>
            <ToolbarItem Text="Next" Order="Primary"
            Activated="Handle_Activated"/>

</ContentPage.ToolbarItems>
</code>```

<p>on the CS page </p>

```<code> async void Handle_Activated(object sender, System.EventArgs e)
        {
            await App.Navigator.PushAsync(new PAGE());
        }
</code>```

Body:
XAML page  add this

<ContentPage.ToolbarItems>
            <ToolbarItem Text="Next" Order="Primary"
            Activated="Handle_Activated"/>

</ContentPage.ToolbarItems>

on the CS page

 async void Handle_Activated(object sender, System.EventArgs e)
        {
            await App.Navigator.PushAsync(new PAGE());
        }


问:
Maven fails to find local artifact
Occasionally maven complains that a particular dependency, which is built and packaged locally, cannot be found in the local repository while building another project that has it as a dependency.  We get an error like:

Failed to execute goal on project X: Could not resolve dependencies for project X: Failure to find Y in [archiva repository] was cached in the local repository, resolution will not be reattempted until the update interval of internal has elapsed or updates are forced ->

Where X is the project being built, and Y is the supposedly missing artifact.  If you look in the local repository, the artifact is there.  This artifact is never installed in our archiva repository, so the problem is purely based in the local repository.

We have tried various profiles in settings.xml, and of course "mvn -U".  Neither do any good, nor should they because this artifact never goes any further than the local repository.

The only two things that seem to work are to wait a very long time until maven smartens up, or to completely delete the local repository.  Presumably the waiting option is related to the aforementioned update interval.

We have experienced this problem with maven 3.0.2 and 3.0.3.  We are using Archiva 1.0.3 (but again this shouldn't be a factor).  Any help would be greatly appreciated.

答:
Even in offline mode, maven will check remote repositories if there is a _remote.repositories marker for the dependency. If you need to operate in offline mode, you may need to delete these files.

The simple shell command below deletes these marker files. This is safe to do if you only use offline mode for the machine. I would NOT do this on a machine that needs to pull files down from the web.

I have used this strategy on a build server that is disconnected from the web. We have to transfer the repository to it, delete the marker files and then run in offline mode.

On Linux / Unix you can delete the remote repository marker files this way:

```<code>cd ~/.m2
find . -name "_remote.repositories" -type f -delete
</code>```

Title: Maven fails to find local artifact

Body:
Even in offline mode, maven will check remote repositories if there is a _remote.repositories marker for the dependency. If you need to operate in offline mode, you may need to delete these files.

The simple shell command below deletes these marker files. This is safe to do if you only use offline mode for the machine. I would NOT do this on a machine that needs to pull files down from the web.

I have used this strategy on a build server that is disconnected from the web. We have to transfer the repository to it, delete the marker files and then run in offline mode.

On Linux / Unix you can delete the remote repository marker files this way:

cd ~/.m2
find . -name "_remote.repositories" -type f -delete


问:
Elasticsearch match string to field with fuzziness
I'm trying to match a string to a field and only want to apply fuzziness.

For example, with these documents:

```<code>{ title: "replace oilfilter" }, { title: "replace motoroil" }
</code>```

The following queries should match only the first document:

```<code>"Replace oilfilter", "Replace oilsfilter", "Replaze oilfilter"
</code>```

The following queries should NOT match any document:

```<code>"replace", "oilfilter", "motoroil"
</code>```

What I got so far is the following:

index

I'm using the keyword analyzer so it sees the (potential) phrase as a single word, this way it does not match a document when searching for "replace" but it does find a document when searching for the exact term "Replace oilfilter".

```<code>    "mappings": {
        "blacklist": {
            "properties": {
                "title": {
                    "type": "text",
                    "analyzer": "keyword"
                }
            }
        }
    }
</code>```

search

I've tried multiple queries to search the documents. I got close with the following query:

```<code>    "query": {
        "query_string": {
            "default_field": "title",
            "fuzziness": "3",
            "query": query
        }
    }
</code>```

results

With this query the following are the results:

```<code>> "Replace oilfilter" (exact words)
< doc: { title: "replace oilfilter" }, score: 0.5753..
< doc: { title: "replace motoroil" }, score: 0.2876..

> "Replace iolfilter" (typo)
< doc: { title: "replace oilfilter" }, score: 0.2876..

> "oilfilter" (other term)
< doc: { title: "replace oilfilter" }, score: 0.2876..
</code>```

problem

The results aren't that bad, but I need the scores to be more accurate. The second query with only the simple typo should get a much higher score than the second result in the first query and the only result in the third query.

What I'm trying to achieve is that it matches the whole query against the whole field in the document, that's why I'm using keyword analyzer. On top of that I only want to apply some fuzziness.

Hope someone can shed some light on this issue.

Thanks!

答:
The following search should achieve what you want:

```<code>{
  "query": {
      "bool": {
        "must": {
          "multi_match": {
            "query": "replace oilfliter",
            "fuzziness": "3",
            "fields": [
              "title"
            ],
            "minimum_should_match": "75%",
            "type": "most_fields"
          }
        }
      }
  }
}
</code>```

You can increase the minimum_should_match to 100% if you want require a match on all the query terms no matter how long the query string is.

Body:
I'm trying to match a string to a field and only want to apply fuzziness.

For example, with these documents:

{ title: "replace oilfilter" }, { title: "replace motoroil" }

The following queries should match only the first document:

"Replace oilfilter", "Replace oilsfilter", "Replaze oilfilter"

The following queries should NOT match any document:

"replace", "oilfilter", "motoroil"

What I got so far is the following:

index

I'm using the keyword analyzer so it sees the (potential) phrase as a single word, this way it does not match a document when searching for "replace" but it does find a document when searching for the exact term "Replace oilfilter".

    "mappings": {
        "blacklist": {
            "properties": {
                "title": {
                    "type": "text",
                    "analyzer": "keyword"
                }
            }
        }
    }

search

I've tried multiple queries to search the documents. I got close with the following query:

    "query": {
        "query_string": {
            "default_field": "title",
            "fuzziness": "3",
            "query": query
        }
    }

results

With this query the following are the results:

> "Replace oilfilter" (exact words)
< doc: { title: "replace oilfilter" }, score: 0.5753..
< doc: { title: "replace motoroil" }, score: 0.2876..

> "Replace iolfilter" (typo)
< doc: { title: "replace oilfilter" }, score: 0.2876..

> "oilfilter" (other term)
< doc: { title: "replace oilfilter" }, score: 0.2876..

problem

The results aren't that bad, but I need the scores to be more accurate. The second query with only the simple typo should get a much higher score than the second result in the first query and the only result in the third query.

What I'm trying to achieve is that it matches the whole query against the whole field in the document, that's why I'm using keyword analyzer. On top of that I only want to apply some fuzziness.

Hope someone can shed some light on this issue.

Thanks!

Body:
The following search should achieve what you want:

{
  "query": {
      "bool": {
        "must": {
          "multi_match": {
            "query": "replace oilfliter",
            "fuzziness": "3",
            "fields": [
              "title"
            ],
            "minimum_should_match": "75%",
            "type": "most_fields"
          }
        }
      }
  }
}

You can increase the minimum_should_match to 100% if you want require a match on all the query terms no matter how long the query string is.


问:
How to import rest_framework to public Django project?
i just wanted to publish my Django project but have the following problem:

```<code>ImportError at /
No module named rest_framework.views
Request Method: GET
Request URL:    http://165.227.154.0/
Django Version: 1.8.7
Exception Type: ImportError
Exception Value:
No module named rest_framework.views
Exception Location: /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__, line 93
Python Executable:  /usr/bin/python
Python Version: 2.7.12
Python Path:
['/home/django/django_project',
 '/home/django/django_project',
 '/usr/bin',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']
Server time:    Thu, 16 Nov 2017 19:30:11 +0000
</code>```

If i run the project locally everything works. Now i have signed up at Digital Ocean and created a one click app. Started their server and uploaded all my files properly via FileZilla into the server directory.

When I enter the IP adress into my browser I also get the reply: It worked!
Congratulations on your first Django-powered page.

But after I uploaded my files, installed the new apps and added the urls,
I receive the Error from above.

Apparently, the rest_framework module can not be imported and I don't know how to fix it.

Is here someone who can help me?

Thanks and kind regards

Marcel

答: It looks like you didn't install the django-rest-framework library in the server. You have to check which package you have installed in your local environment, usually you should use pip to freeze all the dependency to a file called requirement.txt, and when you push the codes to server, you can use the requirement.txt file to reproduce the same environment as your local envirionment.  </p>

Body:
i just wanted to publish my Django project but have the following problem:

ImportError at /
No module named rest_framework.views
Request Method: GET
Request URL:    http://165.227.154.0/
Django Version: 1.8.7
Exception Type: ImportError
Exception Value:
No module named rest_framework.views
Exception Location: /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__, line 93
Python Executable:  /usr/bin/python
Python Version: 2.7.12
Python Path:
['/home/django/django_project',
 '/home/django/django_project',
 '/usr/bin',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']
Server time:    Thu, 16 Nov 2017 19:30:11 +0000

If i run the project locally everything works. Now i have signed up at Digital Ocean and created a one click app. Started their server and uploaded all my files properly via FileZilla into the server directory.

When I enter the IP adress into my browser I also get the reply: It worked!
Congratulations on your first Django-powered page.

But after I uploaded my files, installed the new apps and added the urls,
I receive the Error from above.

Apparently, the rest_framework module can not be imported and I don't know how to fix it.

Is here someone who can help me?

Thanks and kind regards

Marcel


Title: Pandas DataFrame- create a 14 day moving average, but show simple averages for the first 14 days of data?

Body:
I have a pandas dataframe similar to this.

             score   avg
 date
 1/1/2017        0      0
 1/2/2017        1    0.5
 1/3/2017        2      1
 1/4/2017        3    1.5
 1/5/2017        4      2
 1/6/2017        5    2.5
 1/7/2017        6      3
 1/8/2017        7    3.5
 1/9/2017        8      4
 1/10/2017       9    4.5
 1/11/2017      10      5
 1/12/2017      11    5.5
 1/13/2017      12    7.5
 1/14/2017      13    6.5
 1/15/2017      14    7.5
 1/16/2017      15    8.5
 1/17/2017      16    9.5
 1/18/2017      17   10.5
 1/19/2017      18   11.5
 1/20/2017      19   12.5
 1/21/2017      20   13.5
 1/22/2017      21   14.5
 1/23/2017      22   15.5
 1/24/2017      23   16.5
 1/25/2017      24   17.5
 1/26/2017      25   18.5
 1/27/2017      26   19.5
 1/28/2017      27   20.5
 1/29/2017      28   21.5

Basically I am looking to create a 14 day rolling average of the data, but instead of showing NaNs for the first 14 days, simply showing the simple averages. For example, the average on day 2 is the average of day 1 and 2, the average on day 10 is the averages of days 1-10, etc. How would I go about doing this without having to manually create averages? Thanks for the help!

Body:
What you need to use is rolling with min_periods=1 as paramter:

df['avg2'] = df.rolling(14, min_periods=1)['score'].mean()

Output:

         date  score   avg  avg2
0  2017-01-01      0   0.0   0.0
1  2017-01-02      1   0.5   0.5
2  2017-01-03      2   1.0   1.0
3  2017-01-04      3   1.5   1.5
4  2017-01-05      4   2.0   2.0
5  2017-01-06      5   2.5   2.5
6  2017-01-07      6   3.0   3.0
7  2017-01-08      7   3.5   3.5
8  2017-01-09      8   4.0   4.0
9  2017-01-10      9   4.5   4.5
10 2017-01-11     10   5.0   5.0
11 2017-01-12     11   5.5   5.5
12 2017-01-13     12   7.5   6.0
13 2017-01-14     13   6.5   6.5
14 2017-01-15     14   7.5   7.5
15 2017-01-16     15   8.5   8.5
16 2017-01-17     16   9.5   9.5
17 2017-01-18     17  10.5  10.5
18 2017-01-19     18  11.5  11.5
19 2017-01-20     19  12.5  12.5
20 2017-01-21     20  13.5  13.5
21 2017-01-22     21  14.5  14.5
22 2017-01-23     22  15.5  15.5
23 2017-01-24     23  16.5  16.5
24 2017-01-25     24  17.5  17.5
25 2017-01-26     25  18.5  18.5
26 2017-01-27     26  19.5  19.5
27 2017-01-28     27  20.5  20.5
28 2017-01-29     28  21.5  21.5


问:
OutOfRangeError (see above for traceback): RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed
Tensorflow 1.3 Windows 7, Python 3.6

I'm running into this error:

```<code>OutOfRangeError (see above for traceback): RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 3, current size 0)
     [[Node: shuffle_batch = QueueDequeueManyV2[component_types=[DT_FLOAT], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](shuffle_batch/random_shuffle_queue, shuffle_batch/n)]]
</code>```

I've look at  similar thread:

OutOfRangeError (see above for traceback): RandomShuffleQueue '_5_shuffle_batch_1/random_shuffle_queue' is closed and has insufficient elements

OutOfRangeError (see above for traceback): FIFOQueue '_1_batch/fifo_queue' is closed and has insufficient elements (requested 32, current size 0)

OutOfRangeError: RandomShuffleQueue '_2_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 1, current size 0)

Tried the solutions listed (excepted the annotation one, which I don't understand)

Here is my code:

```<code>#more testing tfrecords
</code>```

Creating TFREcords

```<code>import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread, imresize
import os
import tensorflow as tf
import numpy
import cv2

#Gather image paths

DIR = r'C:\Users\Moondra\Desktop\DATA\IMAGE_2'

images = [os.path.join(DIR, image) for image in os.listdir(DIR)]

# len(images) is 41

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

tfrecords_filename = 'testing_2.tfrecords'

writer = tf.python_io.TFRecordWriter(tfrecords_filename)

for image in images:
    img = cv2.imread(image)
    img = cv2.resize(img, (300, 300), interpolation=cv2.INTER_CUBIC)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = img.astype(np.float32)

    feature ={'train/image': _bytes_feature(tf.compat.as_bytes(img.tostring()))}

    example = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(example.SerializeToString())

writer.close()
</code>```

Loading TFREcords into Batches

```<code>#absolute path
tfrecords_filename = r'C:\Users\Moondra\Desktop\Transfer Learning Tutorials\testing_2.tfrecords'

with tf.Session() as sess:
    feature = {'train/image': tf.FixedLenFeature([],tf.string)
               }

    filename_queue = tf.train.string_input_producer([tfrecords_filename],num_epochs=1)
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(serialized_example, features=feature)
    image = tf.decode_raw(features['train/image'], tf.float32)
    image = tf.reshape(image, [299, 299, 3])

    images = tf.train.shuffle_batch([image], batch_size=3, capacity=12, num_threads=1, min_after_dequeue=10)

    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    sess.run(init_op)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for batch_index in range(2):
        img  = sess.run([images])
        print(img.shape)
        img = img.astype(np.uint8)
        for j in range(6):
            plt.subplot(2, 3, j+1)
            plt.imshow(img[j, ...])
            plt.show()
    coord.request_stop()
    coord.join(threads)
    sess.close()
</code>```

If needed I've uploaded the images as a zip file onto my github:

https://github.com/moondra2017/Testing_Cat_classifier_Tensorflow

labeled as IMAGE_2.7z

Thank you.

答:
Figured out the mistake.

My saved dimensions were [300,300]

The dimensions I was trying to load were [299,299]

```<code>#Image = tf.reshape(image, [299, 299, 3])
</code>```

Body:
Tensorflow 1.3 Windows 7, Python 3.6

I'm running into this error:

OutOfRangeError (see above for traceback): RandomShuffleQueue '_1_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 3, current size 0)
     [[Node: shuffle_batch = QueueDequeueManyV2[component_types=[DT_FLOAT], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](shuffle_batch/random_shuffle_queue, shuffle_batch/n)]]

I've look at  similar thread:

OutOfRangeError (see above for traceback): RandomShuffleQueue '_5_shuffle_batch_1/random_shuffle_queue' is closed and has insufficient elements

OutOfRangeError (see above for traceback): FIFOQueue '_1_batch/fifo_queue' is closed and has insufficient elements (requested 32, current size 0)

OutOfRangeError: RandomShuffleQueue '_2_shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 1, current size 0)

Tried the solutions listed (excepted the annotation one, which I don't understand)

Here is my code:

#more testing tfrecords

Creating TFREcords

import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import imread, imresize
import os
import tensorflow as tf
import numpy
import cv2

#Gather image paths

DIR = r'C:\Users\Moondra\Desktop\DATA\IMAGE_2'

images = [os.path.join(DIR, image) for image in os.listdir(DIR)]

# len(images) is 41

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

tfrecords_filename = 'testing_2.tfrecords'

writer = tf.python_io.TFRecordWriter(tfrecords_filename)

for image in images:
    img = cv2.imread(image)
    img = cv2.resize(img, (300, 300), interpolation=cv2.INTER_CUBIC)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = img.astype(np.float32)

    feature ={'train/image': _bytes_feature(tf.compat.as_bytes(img.tostring()))}

    example = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(example.SerializeToString())

writer.close()

Loading TFREcords into Batches

#absolute path
tfrecords_filename = r'C:\Users\Moondra\Desktop\Transfer Learning Tutorials\testing_2.tfrecords'

with tf.Session() as sess:
    feature = {'train/image': tf.FixedLenFeature([],tf.string)
               }

    filename_queue = tf.train.string_input_producer([tfrecords_filename],num_epochs=1)
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(serialized_example, features=feature)
    image = tf.decode_raw(features['train/image'], tf.float32)
    image = tf.reshape(image, [299, 299, 3])

    images = tf.train.shuffle_batch([image], batch_size=3, capacity=12, num_threads=1, min_after_dequeue=10)

    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    sess.run(init_op)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    for batch_index in range(2):
        img  = sess.run([images])
        print(img.shape)
        img = img.astype(np.uint8)
        for j in range(6):
            plt.subplot(2, 3, j+1)
            plt.imshow(img[j, ...])
            plt.show()
    coord.request_stop()
    coord.join(threads)
    sess.close()

If needed I've uploaded the images as a zip file onto my github:

https://github.com/moondra2017/Testing_Cat_classifier_Tensorflow

labeled as IMAGE_2.7z

Thank you.

Body:
Figured out the mistake.

My saved dimensions were [300,300]

The dimensions I was trying to load were [299,299]

#Image = tf.reshape(image, [299, 299, 3])


问:
What does "JVM processes" mean?
From Java In a Nutshell

jps  provides a list of all active JVM processes on the local machine (or a remote machine, if a suitable instance of  jstatd  is running on the remote side).

What does "JVM processes" here mean,

processes of the underlying OS which run JVM exactly, or

processes that are supported by Java via Process, ProcessBuilder and Runtime.exec()...

Thanks.

答:
A running Java Virtual Machine (JVM) instance is materialized by a native process launched by an OS while a Process class instance is a native process launched by a running JVM.

As each Java Virtual Machine is associated to a specific native process, instead of saying a process that runs a JVM, we could so shortcut it by a JVM process.

Title: What does "JVM processes" mean?


问:
How innodb tables are locked when ON INSERT trigger is processed?
I have two innodb tables:

articles

```<code>id     | title    | sum_votes
------------------------------
1      | art 1    | 5
2      | art 2    | 8
3      | art 3    | 35
</code>```

votes

```<code>id     | article_id    | vote
------------------------------
1      | 1             | 1
2      | 1             | 2
3      | 1             | 2
4      | 2             | 10
5      | 2             | -2
6      | 3             | 10
7      | 3             | 15
8      | 3             | 12
9      | 3             | -2
</code>```

When a new record is inserted into the votes table, I want to update the sum_votes field in articles table by calculating the sum of all votes.

The question

Which way is more efficient, if the SUM() calculation itself is a very heavy one (votes table has 700K records).

1. Creating a trigger

```<code>CREATE TRIGGER `views_on_insert`
AFTER INSERT
ON `votes`
FOR EACH ROW
BEGIN
   UPDATE `articles` SET
       sum_votes = (
           SELECT SUM(`vote`)
           FROM `votes`
           WHERE `id` = NEW.article_id
       )
    WHERE `id` = NEW.article_id;
END;
</code>```

2. Using two queries in my application

```<code>SELECT SUM(`vote`) FROM `votes` WHERE `article_id` = 1;
UPDATE `articles`
   SET sum_votes = <1st_query_result>
 WHERE `id` = 1;
</code>```

1st way seems cleaner, but will the table be locked the whole time the SELECT query runs?

答:
try this:

PHP: Star rating system concept?

EDIT: changed schema to allow a user to vote for the same image many times:

```<code>drop table if exists image;
create table image
(
image_id int unsigned not null auto_increment primary key,
caption varchar(255) not null,
num_votes int unsigned not null default 0,
total_score int unsigned not null default 0,
rating decimal(8,2) not null default 0
)
engine = innodb;

drop table if exists image_vote;
create table image_vote
(
vote_id int unsigned not null auto_increment primary key,
image_id int unsigned not null,
user_id int unsigned not null,
score tinyint unsigned not null default 0,
key (image_id, user_id)
)
engine=innodb;

delimiter #

create trigger image_vote_after_ins_trig after insert on image_vote
for each row
begin
 update image set
    num_votes = num_votes + 1,
    total_score = total_score + new.score,
    rating = total_score / num_votes
 where
    image_id = new.image_id;
end#

delimiter ;

insert into image (caption) values ('image 1'),('image 2'), ('image 3');

insert into image_vote (image_id, user_id, score) values
(1,1,5),(1,2,4),(1,3,3),(1,4,2),(1,5,1),(1,5,2),(1,5,3),
(2,1,2),(2,2,1),(2,3,4),(2,3,2),
(3,1,4),(3,5,2);

select * from image;
select * from image_vote;
</code>```

Body:
I have two innodb tables:

articles

id     | title    | sum_votes
------------------------------
1      | art 1    | 5
2      | art 2    | 8
3      | art 3    | 35

votes

id     | article_id    | vote
------------------------------
1      | 1             | 1
2      | 1             | 2
3      | 1             | 2
4      | 2             | 10
5      | 2             | -2
6      | 3             | 10
7      | 3             | 15
8      | 3             | 12
9      | 3             | -2

When a new record is inserted into the votes table, I want to update the sum_votes field in articles table by calculating the sum of all votes.

The question

Which way is more efficient, if the SUM() calculation itself is a very heavy one (votes table has 700K records).

1. Creating a trigger

CREATE TRIGGER `views_on_insert`
AFTER INSERT
ON `votes`
FOR EACH ROW
BEGIN
   UPDATE `articles` SET
       sum_votes = (
           SELECT SUM(`vote`)
           FROM `votes`
           WHERE `id` = NEW.article_id
       )
    WHERE `id` = NEW.article_id;
END;

2. Using two queries in my application

SELECT SUM(`vote`) FROM `votes` WHERE `article_id` = 1;
UPDATE `articles`
   SET sum_votes = <1st_query_result>
 WHERE `id` = 1;

1st way seems cleaner, but will the table be locked the whole time the SELECT query runs?

Body:
try this:

PHP: Star rating system concept?

EDIT: changed schema to allow a user to vote for the same image many times:

drop table if exists image;
create table image
(
image_id int unsigned not null auto_increment primary key,
caption varchar(255) not null,
num_votes int unsigned not null default 0,
total_score int unsigned not null default 0,
rating decimal(8,2) not null default 0
)
engine = innodb;

drop table if exists image_vote;
create table image_vote
(
vote_id int unsigned not null auto_increment primary key,
image_id int unsigned not null,
user_id int unsigned not null,
score tinyint unsigned not null default 0,
key (image_id, user_id)
)
engine=innodb;

delimiter #

create trigger image_vote_after_ins_trig after insert on image_vote
for each row
begin
 update image set
    num_votes = num_votes + 1,
    total_score = total_score + new.score,
    rating = total_score / num_votes
 where
    image_id = new.image_id;
end#

delimiter ;

insert into image (caption) values ('image 1'),('image 2'), ('image 3');

insert into image_vote (image_id, user_id, score) values
(1,1,5),(1,2,4),(1,3,3),(1,4,2),(1,5,1),(1,5,2),(1,5,3),
(2,1,2),(2,2,1),(2,3,4),(2,3,2),
(3,1,4),(3,5,2);

select * from image;
select * from image_vote;


问:
Session Fixation - Change sessionId on asp.net core 2
Based on what i have understood we have

sessionId is stored in the cookie .AspNetCore.Session

Deleting the cookies and Clearing the session does nothing.

```<code>context.HttpContext.Session.Clear();
foreach (var cookie in context.HttpContext.Request.Cookies.Keys)
{
     context.HttpContext.Response.Cookies.Delete(cookie);
}
</code>```

So the question is can we change the sessionId somehow, or is there a way to protect us from Session-Fixing?

答:
Session.Clear only removes all data from the session, it does not actually remove the session itself. That will occur when the timeout is hit. It was an odd choice, in my opinion, for the ASP.NET Core team to not have implemented Session.Abandon, as previously existed, since that actually would remove the actual session, itself.

As long as the actual session still exists, even if the data for it no longer does, it can still be retrieved by that session id, as a result, the problem shifts to the client-side.

Importantly, the server cannot actually make the client do anything. Calling Cookies.Delete really only sends a new Set-Cookie response header for the same cookie with an expiration date in the past. This should prompt the client (browser, most likely) to then remove that cookie, since it is now expired. However, that is totally 100% on the client, so if there's a bug or the client otherwise is not picking up the change or the client simply refuses to comply for whatever reason, the cookie will remain. Then, again, if the cookie still exists and the session identified by the session id it contains still exists, it can be restored.

Long and short, the code you have should work, and there's really not anything else you can do other than what you're already doing. If the session isn't being abandoned, there's some other issue somewhere (most likely with the client).

Body:
Based on what i have understood we have

sessionId is stored in the cookie .AspNetCore.Session

Deleting the cookies and Clearing the session does nothing.

context.HttpContext.Session.Clear();
foreach (var cookie in context.HttpContext.Request.Cookies.Keys)
{
     context.HttpContext.Response.Cookies.Delete(cookie);
}

So the question is can we change the sessionId somehow, or is there a way to protect us from Session-Fixing?


问:
How to deal with tasks running too long (comparing to others in job) in yarn-client?
We use a Spark cluster as yarn-client to calculate several business, but sometimes we have a task run too long time:

We don't set timeout but I think default timeout a spark task is not too long such here ( 1.7h ).

Anyone give me an ideal to work around this issue ???

答: The trick here is to login directly to the worker node and kill the process.  Usually you can find the offending process with a combination of top, ps, and grep.  Then just do a kill pid.


问:
Git init -q Permissions error while installing Homebrew
I'm attempting to install HomeBrew on OS X 10.12.6. When I use the autoinstall script from Homebrew's website:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

Everything runs smoothly until it begins actually downloading and installing Homebrew, at which point it returns the following error:

```<code>==> Downloading and installing Homebrew...
/usr/local/homebrew/.git: Permission denied
Failed during: git init -q
</code>```

Any tips of how to resolve this? Any assistance would be greatly appreciated!

答:
You should make your /usr/local/bin and /usr/local/opt writeable, i.e.:

```<code>chmod +w /usr/local/bin
chmod +w /usr/local/opt
</code>```

Depending on your user's permissions you may have to use sudo to achieve it.

Body:
I'm attempting to install HomeBrew on OS X 10.12.6. When I use the autoinstall script from Homebrew's website:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Everything runs smoothly until it begins actually downloading and installing Homebrew, at which point it returns the following error:

==> Downloading and installing Homebrew...
/usr/local/homebrew/.git: Permission denied
Failed during: git init -q

Any tips of how to resolve this? Any assistance would be greatly appreciated!

Body:
You should make your /usr/local/bin and /usr/local/opt writeable, i.e.:

chmod +w /usr/local/bin
chmod +w /usr/local/opt

Depending on your user's permissions you may have to use sudo to achieve it.


问:
Using str_replace to alter a field's display in a Drupal 7 view
I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

```<code><?php
$output = str_replace(" | My Site", "", $output);
print $output;
?>
</code>```

this doesn't seem to work...

答:
Using the a preprocessor into the template.php will definitely works. There is other options to change the page, but it depends of what modules and what set up you are using to generate that title, clearly is using a patter define somewhere,  so without know that my advice is use a preprocessor like this</p>

```<code> function THEME_NAME_preprocess_page(&$variables) {
   //you could use arg to identify your page page
  //https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7.x
    // if the page is the one you are looking then override the title
     drupal_set_title('mytitle');
 }
</code>```

Body:
I am using the Google Analytics module to retrieve the most popular articles on my site during the past day to populate a 'trending' block.

The problem is that the PageTitle field comes from the meta data and includes a pipe and the site name. I would like to strip that off the end of the string, but I can't figure out how to do it within the view using rewrite results.

I created a views-view-field--pageTitle.tpl.php file and edited it to this:

<?php
$output = str_replace(" | My Site", "", $output);
print $output;
?>

this doesn't seem to work...

Body:
Using the a preprocessor into the template.php will definitely works. There is other options to change the page, but it depends of what modules and what set up you are using to generate that title, clearly is using a patter define somewhere,  so without know that my advice is use a preprocessor like this

 function THEME_NAME_preprocess_page(&$variables) {
   //you could use arg to identify your page page
  //https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7.x
    // if the page is the one you are looking then override the title
     drupal_set_title('mytitle');
 }


问:
PHP how to check if a day was a holiday (in a specified country)?
Is there some function that would tell me if a date was a holiday in a certain country?

I know this is probably futile question as it would be difficult to have a function like that.

答: There is no built-in function for this, but you might be able to roll-your-own using the holiday script at AbleDesign as the base</p>


问:
Count not adding for each item, adding as a total C# console application
trying to get a count of each item in the array, however its adding a total number.

```<code>  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };

        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }

        Console.ReadLine();
        }
</code>```

E.g. Input: 1,10

Expected output:

```<code>hello: 3
world: 5
helloworld: 1
integer: 11
</code>```

Run below dotnet fiddle to find issue:

https://dotnetfiddle.net/eKHb5x

答:
Change your ArrayList to a List<string>.

When you iterate over it, use the item variable as the key to your dictionary.

```<code>        foreach(string item in list) {
            if(counts.ContainsKey(item)) {
                counts[item]++;
            } else {
                counts["integer"]++;
            }
        }
</code>```

Body:
trying to get a count of each item in the array, however its adding a total number.

  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };

        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }

        Console.ReadLine();
        }

E.g. Input: 1,10

Expected output:

hello: 3
world: 5
helloworld: 1
integer: 11

Run below dotnet fiddle to find issue:

https://dotnetfiddle.net/eKHb5x

Body:
Change your ArrayList to a List<string>.

When you iterate over it, use the item variable as the key to your dictionary.

        foreach(string item in list) {
            if(counts.ContainsKey(item)) {
                counts[item]++;
            } else {
                counts["integer"]++;
            }
        }


问:
Converting struct with embedded interface into JSON
I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

```<code>package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}
</code>```

I need to output to look like this (it needs to be flat, not nested):

```<code>{"foo": "foo", "bar": "bar"}
</code>```

答:
I would write a custom marshaller, like so:

```<code>func (f foo) MarshalJSON() ([]byte, error) {
    type tmp foo
    g := tmp(f)
    first, err := json.Marshal(g)
    if err != nil {
        return nil, err
    }
    second, err := json.Marshal(f.data)
    if err != nil {
        return nil, err
    }
    data := make(map[string]interface{})
    json.Unmarshal(first, &data)
    json.Unmarshal(second, &data)
    return json.Marshal(data)
    //{"bar":"bar","foo":"foo"}
}
</code>```

https://play.golang.org/p/TENiCe9nR0

Body:
I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}

I need to output to look like this (it needs to be flat, not nested):

{"foo": "foo", "bar": "bar"}

Body:
I would write a custom marshaller, like so:

func (f foo) MarshalJSON() ([]byte, error) {
    type tmp foo
    g := tmp(f)
    first, err := json.Marshal(g)
    if err != nil {
        return nil, err
    }
    second, err := json.Marshal(f.data)
    if err != nil {
        return nil, err
    }
    data := make(map[string]interface{})
    json.Unmarshal(first, &data)
    json.Unmarshal(second, &data)
    return json.Marshal(data)
    //{"bar":"bar","foo":"foo"}
}

https://play.golang.org/p/TENiCe9nR0


问:
Mongoose populate returns empty array but returns data without populate
I am trying to fetch appointments and populate them with user details and doctor details. I have a schema like this

```<code>let appointmentSchema = new Schema({
  reason: String,
  start: DateType,
  end: DateType,
  appointmentStamp: Number,
  userId: {
    type: ObjectId,
    ref: 'User'
  },
  doctorId: {
    type: ObjectId,
    ref: 'Doctor'
  },
  approved: Boolean,
  held: Boolean,
  timeOfAcceptance: Number,
  createdOn: { type: Number, default: (new Date().getTime()) },
  updatedAt: Mixed
}, {runSettersOnQuery: true})
</code>```

And on running

```<code>Appointment.find({userId: authId}).populate('userId doctorId').exec()
</code>```

I get an empty array
but
Appointment.find({userId: authId}).exec()
return all the appointments for that user with the userId supplied in find
what am I missing out

Here is a sample appointment

```<code>  {
    "_id": "5a0d424079191657fca9e853",
    "reason": "Say Hello",
    "approved": false,
    "held": false,
    "doctor": "5a0add9b577d7916187cd9f2",
    "patient": "59f5df20a3071554c5f843e1",
    "appointmentStamp": 1510927380000,
    "__v": 0,
    "createdOn": 1510817910134
  }
</code>```

答:
I tried this and it worked, don't know why

```<code>patient: {
   type: String,
   ref: 'patient'
},
doctor: {
   type: String,
   ref: 'doctor'
}
</code>```

instead of ObjectId I used type of String
then the query be like

```<code>Appointment.find({patient: authId, canceled: false})
  .populate('patient doctor').exec()
</code>```

Body:
I am trying to fetch appointments and populate them with user details and doctor details. I have a schema like this

let appointmentSchema = new Schema({
  reason: String,
  start: DateType,
  end: DateType,
  appointmentStamp: Number,
  userId: {
    type: ObjectId,
    ref: 'User'
  },
  doctorId: {
    type: ObjectId,
    ref: 'Doctor'
  },
  approved: Boolean,
  held: Boolean,
  timeOfAcceptance: Number,
  createdOn: { type: Number, default: (new Date().getTime()) },
  updatedAt: Mixed
}, {runSettersOnQuery: true})

And on running

Appointment.find({userId: authId}).populate('userId doctorId').exec()

I get an empty array
but
Appointment.find({userId: authId}).exec()
return all the appointments for that user with the userId supplied in find
what am I missing out

Here is a sample appointment

  {
    "_id": "5a0d424079191657fca9e853",
    "reason": "Say Hello",
    "approved": false,
    "held": false,
    "doctor": "5a0add9b577d7916187cd9f2",
    "patient": "59f5df20a3071554c5f843e1",
    "appointmentStamp": 1510927380000,
    "__v": 0,
    "createdOn": 1510817910134
  }

Body:
I tried this and it worked, don't know why

patient: {
   type: String,
   ref: 'patient'
},
doctor: {
   type: String,
   ref: 'doctor'
}

instead of ObjectId I used type of String
then the query be like

Appointment.find({patient: authId, canceled: false})
  .populate('patient doctor').exec()


问:
How to mock private method using Power Mockito?
I am trying to mock my private method , but I am getting java.lang.IllegalArgumentException: object is not an instance of declaring class .Below is my method

```<code>private String decodeResponse(byte bresp[])
    {

        String spresp = null;
        //
        return spresp;
    }
</code>```

Below is my test class ,

```<code>@PrepareForTest(MyClass.class)
    @RunWith(PowerMockRunner.class)
    public class MyClassTest{

    @Test
    public void test() throws Exception {
        PowerMockito.spy(MyClass.class);
        PowerMockito.doReturn("abcdefg").when(MyClass.class, "decodeResponse",Matchers.anyByte());
    }
    }
</code>```

I am stuck in this issue for past 3 hours . Any help will be highly appreciable.

答:
```<code>    @PrepareForTest(MyClass.class)
    @RunWith(PowerMockRunner.class)
    public class MyClassTest{

    @Test
    public void test() throws Exception {
        MyClass myClassSpy = PowerMockito.spy(MyClass.class);
        PowerMockito.doReturn("abcdefg").when(myClassSpy, "decodeResponse",any(byte[].class));
    }
    }
</code>```

Body:
I am trying to mock my private method , but I am getting java.lang.IllegalArgumentException: object is not an instance of declaring class .Below is my method

private String decodeResponse(byte bresp[])
    {

        String spresp = null;
        //
        return spresp;
    }

Below is my test class ,

@PrepareForTest(MyClass.class)
    @RunWith(PowerMockRunner.class)
    public class MyClassTest{

    @Test
    public void test() throws Exception {
        PowerMockito.spy(MyClass.class);
        PowerMockito.doReturn("abcdefg").when(MyClass.class, "decodeResponse",Matchers.anyByte());
    }
    }

I am stuck in this issue for past 3 hours . Any help will be highly appreciable.


答: I might be wrong, but I think you are going to have to roll your own. And even if there is already a lib that does this for you, you are going to have to be careful - the definition of holiday will vary, even for a given country. (E.g does a religious holiday mean the banks are shut?). I.e what constitutes a holiday is likely to be application dependent. Take a look at this wikipedia page for lists of national holidays: http://en.wikipedia.org/wiki/List_of_holidays_by_country</p>

Title: PHP how to check if a day was a holiday (in a specified country)?

Body:
Is there some function that would tell me if a date was a holiday in a certain country?

I know this is probably futile question as it would be difficult to have a function like that.


问:
Create a column based on other columns value
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

```<code>WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |
</code>```

To this:

```<code>WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |
</code>```

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

答:
Using dplyr

```<code>your_data %>%
  group_by(cluster) %>%
  mutate(Name = first(WORD))
</code>```

It assumes your rows are already sorted by SCORE. If needed, you can do that sorting too:

```<code>your_data %>%
  group_by(cluster) %>%
  arrange(desc(SCORE)) %>%
  mutate(Name = first(WORD))
</code>```

Body:
I'm looking for a way to create a new column with values based on the value in the first column, with the highest score in the same cluster.

The goal is to move from this:

WORD     | SCORE | Cluster |
diptyqu  | 19750 |    1    |
daptyqu  | 8830  |    1    |
dyptiqu  | 29    |    1    |
deptiqu  | 2     |    1    |
parfume  | 300   |    2    |
parfum   | 14    |    2    |

To this:

WORD     | SCORE | Cluster | Name    |
diptyqu  | 19750 |    1    | diptyqu |
daptyqu  | 8830  |    1    | diptyqu |
dyptiqu  | 29    |    1    | diptyqu |
deptiqu  | 2     |    1    | diptyqu |
parfume  | 300   |    2    | parfume |
parfum   | 14    |    2    | parfume |

I'm litteraly stuck and don't really know how to make it. Do you have any suggestion on a method to do this?

Body:
Using dplyr

your_data %>%
  group_by(cluster) %>%
  mutate(Name = first(WORD))

It assumes your rows are already sorted by SCORE. If needed, you can do that sorting too:

your_data %>%
  group_by(cluster) %>%
  arrange(desc(SCORE)) %>%
  mutate(Name = first(WORD))


问:
Wordpress author name coming twice
I am using Wordpress to create a blog. I am showing author name in the article but it is repeating. I am using the get_the_author(); function

Here is my wordpress site: http://hideawayharbor.org/blog/

答:
You should open up /wp-content/themes/YOURTHEME/single.php in an editor (such as Dreamweaver)
and do a search on the string "Posted by"

Then check your code and you may find it's echo'ing it twice there.

You would also have to fix this in page.php, archive.php and possibly others.

Post the code you find here if you need more help.

Title: Wordpress author name coming twice


问:
How tell an other component of changement state of redux?
I have two components reactjs , I create an state redux to handle this state from two components .

```<code>  `appcomponent.js
import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state=[], action) {
      switch (action.type) {
        case 'ADD_USER':
      return [
        {user:action.user}
      ];
      default:
      return state;
  }
     }
class appcomponent extends Component {
    constructor(props) {
        super(props);
        this.state = {Users:[]};
        //this.addUser=this.addUser.bind(this);
        this.onFormSubmit=this.onFormSubmit.bind(this);
        this.get=this.get.bind(this);
      }
get(){
    console.log(this.props.r);
}
onFormSubmit() {
  this.props.send('user');
}
  render() {
  return (
    <div>
   <br /><br /><br />
     <button onClick={this.onFormSubmit}>redux</button><br /><br /><br /><br />
     <button onClick={this.get}>REDUX</button>
    </div>
  )}
}
// action
export function addUser(user) {
  return {
    type: 'ADD_USER',
    user,
  };
}
function mapDispatchToProps (dispatch)  {
  return {
    send: user => dispatch(addUser(user))
  };
};
const mapStateToProps = (state, ownProps) => {
  return  { r:state};

};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);
</code>```

In this component when I click "redux" button then onclick "REDUX" button I get the state changed.
In the other component I have this code :

```<code> class App extends Component {
constructor(props) {
    super(props);
    }
render() {
    return (
<div><h1>{this.props.user}</h1></div>
)
}}
const mapStateToProps = (state, ownProps) => {
  return  { user: state[0].user};//.user
};
function mapDispatchToProps (dispatch)  {
  return {
    get: user => dispatch(addUser('username'))
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
</code>```

In the last component always I get the initial state created in index.js

```<code>var store = createStore(get_user,[{user:'hhhh'}]);
ReactDOM.render( <Provider store={store}>
</code>```

Please who can help me ?

答:
in the first component try use the following code </p>

```<code>import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state={user:[]}, action) {
      switch (action.type) {
        case 'ADD_USER':
      return {
        ...state,
        user:action.user
      }

      default:
      return state;
  }
     }
class appcomponent extends Component {
    constructor(props) {
        super(props);
        this.state = {Users:[]};
        //this.addUser=this.addUser.bind(this);
        this.onFormSubmit=this.onFormSubmit.bind(this);
        this.get=this.get.bind(this);
      }
get(){
    console.log(this.props.r);
}
onFormSubmit() {
  this.props.send('user');
}
  render() {
  return (
    <div>
   <br /><br /><br />
     <button onClick={this.onFormSubmit}>redux</button><br /><br /><br /><br />
     <button onClick={this.get}>REDUX</button>
    </div>
  )}
}
// action
export function addUser(user) {
  return {
    type: 'ADD_USER',
    user,
  };
}
function mapDispatchToProps (dispatch)  {
  return {
    send: user => dispatch(addUser(user))
  };
};
const mapStateToProps = (state, ownProps) => {
  return  { r:state};

};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);
</code>```

<p>and on the second component use the following code </p>

```<code>class App extends Component {
constructor(props) {
    super(props);
    }
render() {
    return (
<div><h1>{this.props.user}</h1></div>
)
}}
const mapStateToProps = (state, ownProps) => {
  return  { user: state.user};//.user
};
function mapDispatchToProps (dispatch)  {
  return {
    get: user => dispatch(addUser('username'))
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App);
</code>```

Body:
I have two components reactjs , I create an state redux to handle this state from two components .

  `appcomponent.js
import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state=[], action) {
      switch (action.type) {
        case 'ADD_USER':
      return [
        {user:action.user}
      ];
      default:
      return state;
  }
     }
class appcomponent extends Component {
    constructor(props) {
        super(props);
        this.state = {Users:[]};
        //this.addUser=this.addUser.bind(this);
        this.onFormSubmit=this.onFormSubmit.bind(this);
        this.get=this.get.bind(this);
      }
get(){
    console.log(this.props.r);
}
onFormSubmit() {
  this.props.send('user');
}
  render() {
  return (

     <button onClick={this.onFormSubmit}>redux</button>

     <button onClick={this.get}>REDUX</button>

  )}
}
// action
export function addUser(user) {
  return {
    type: 'ADD_USER',
    user,
  };
}
function mapDispatchToProps (dispatch)  {
  return {
    send: user => dispatch(addUser(user))
  };
};
const mapStateToProps = (state, ownProps) => {
  return  { r:state};

};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);

In this component when I click "redux" button then onclick "REDUX" button I get the state changed.
In the other component I have this code :

 class App extends Component {
constructor(props) {
    super(props);
    }
render() {
    return (

{this.props.user}

)
}}
const mapStateToProps = (state, ownProps) => {
  return  { user: state[0].user};//.user
};
function mapDispatchToProps (dispatch)  {
  return {
    get: user => dispatch(addUser('username'))
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App);

In the last component always I get the initial state created in index.js

var store = createStore(get_user,[{user:'hhhh'}]);
ReactDOM.render( <Provider store={store}>

Please who can help me ?

Body:
in the first component try use the following code

import React, { Component } from 'react';
import { createStore } from 'redux';
import { connect } from 'react-redux';
//reducer
export function get_user(state={user:[]}, action) {
      switch (action.type) {
        case 'ADD_USER':
      return {
        ...state,
        user:action.user
      }

      default:
      return state;
  }
     }
class appcomponent extends Component {
    constructor(props) {
        super(props);
        this.state = {Users:[]};
        //this.addUser=this.addUser.bind(this);
        this.onFormSubmit=this.onFormSubmit.bind(this);
        this.get=this.get.bind(this);
      }
get(){
    console.log(this.props.r);
}
onFormSubmit() {
  this.props.send('user');
}
  render() {
  return (
    <div>
   <br /><br /><br />
     <button onClick={this.onFormSubmit}>redux</button><br /><br /><br /><br />
     <button onClick={this.get}>REDUX</button>
    </div>
  )}
}
// action
export function addUser(user) {
  return {
    type: 'ADD_USER',
    user,
  };
}
function mapDispatchToProps (dispatch)  {
  return {
    send: user => dispatch(addUser(user))
  };
};
const mapStateToProps = (state, ownProps) => {
  return  { r:state};

};
export default connect(mapStateToProps,mapDispatchToProps)(appcomponent);

and on the second component use the following code

class App extends Component {
constructor(props) {
    super(props);
    }
render() {
    return (
<div><h1>{this.props.user}</h1></div>
)
}}
const mapStateToProps = (state, ownProps) => {
  return  { user: state.user};//.user
};
function mapDispatchToProps (dispatch)  {
  return {
    get: user => dispatch(addUser('username'))
  };
};
export default connect(mapStateToProps,mapDispatchToProps)(App);


问:
SKLabelNode Creating Black Rectangle
I saw this question, but it did not have a definite solution to the issue, nor is it the exact same. I am trying to simply add a SKLabelNode with some text. I have never had issues but for some reason this is happening:

Here is the code I am using to generate the node:

```<code>var announceLabel = SKLabelNode(fontNamed: "Baskerville")
announceLabel.text = "ERROR LOADING ANNOUNCEMENT"
announceLabel.fontColor = UIColor.blackColor()
announceLabel.fontSize = 200
announceLabel.setScale(twitterButton.frame.height / announceLabel.frame.height)
announceLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(announceLabel)
</code>```

I am testing this on my iPhone 6, and I have never had this happen while creating a label node. I have attempted different fonts, positions, and scales with no effect. Any help is greatly appreciated! Thanks!

答:
Two and a half years later, and I'm running into the same problem. It seems like when the width of the SKLableNode exceeds a certain size, it just shows as a black rectangle. I did a quick binary search and found the bad size is between 2038 and 2054, so I'm going to go out on a limb here and say the cutoff is at 2048. I guess it's a bug in SpriteKit? I don't see any documentation on it...

Work arounds:

Halve your font size and double your scale. This is what I'm doing for now, i.e. my fontSize went from 64 to 32, and setScale(2). Downside is that the font isn't as high quality. Also this only increases your limit to effective 4096 points. So a really long label still won't work.

Cut your text up into chunks that produce SKLabelNodes no larger than 2048. Might be painful to get text layout just right this way.

Title: SKLabelNode Creating Black Rectangle

Body:
I saw this question, but it did not have a definite solution to the issue, nor is it the exact same. I am trying to simply add a SKLabelNode with some text. I have never had issues but for some reason this is happening:

Here is the code I am using to generate the node:

var announceLabel = SKLabelNode(fontNamed: "Baskerville")
announceLabel.text = "ERROR LOADING ANNOUNCEMENT"
announceLabel.fontColor = UIColor.blackColor()
announceLabel.fontSize = 200
announceLabel.setScale(twitterButton.frame.height / announceLabel.frame.height)
announceLabel.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
self.addChild(announceLabel)

I am testing this on my iPhone 6, and I have never had this happen while creating a label node. I have attempted different fonts, positions, and scales with no effect. Any help is greatly appreciated! Thanks!


问:
What does mean by ↓ and C besides file name in Xcode9 Project Navigator?

I know about M, A, U, ?, R, I.

I searched for the ↓ and C  but not found any helpful resources.

This post doesn't contain info about ↓.

Can anyone tell me what indicates these symbols?

Thank you in advance.

答:
C means conflict — you tried to merge (or implicitly merge due to a pull) a branch where, in the marked file, git can't automatically resolve the differences between your working copy and the other branch. You'll need to use Xcode's version editor or an external tool to manually decide which changes from each side to keep, then tell git that the conflicts are resolved (IIRC in Xcode you can do this by right-clicking on the file in the navigator).

↓ means your working copy is "behind" the other branch by some number of commits (in this case, because the conflict meant it couldn't catch up).


问:
Sample REST Observable service and a remote subscriber client in Java 9/RxJava 2
Here is the background:
 We have  a cluster (of 3) different services deployed on various containers (like Tomcat, TomEE, JBoss) etc.  Each of the services does one thing. Like one service manages a common DB and provides REST services to CRUD the db. One service puts some data into a JMS Queue, Another service reads from the Queue and updates the DB.  There is a client app that makes a REST service call to one of the service that sets off creating a row in the db, pushing that row into a queue etc.

Question: We need to implement the client app so that we know at any given point in time where the processing is. How do I implement this in RcJava 2/Java 9?

答:
First, you need to determine what functionality in RxJava 2 will benefit you.

Coordination between asynchronous sources. Since you have a) event-driven requests from one side, and b) network queries on the other sides, this is a good fit so far.

Managing a stream of data, transforming and combining from one or more sources. You have given no indication that this is required.

Second, you need to determine what RxJava 2 does not provide:

Network connections. This is provided by your existing libraries.

Database management. Again, this is provided in your existing solutions.

Now, you have to decide whether the firstlies add up to something you can benefit from, given the up-front costs of learning a new library.


问:
Should I just be using std::vector?
I've created a function that takes in an array with a unknown size.
I then want to simply call that function and pass in a array with a certain size, and then get the number of elements within that passed in array.

All of this is fine except for of course getting the number of elements in the array as it seems there isn't a simple way to calculate that. So I was wondering if it would be right just to use a std::vector instead for all this? The only problem with that is that it feels like kinda a waste as I don't need the additional functionality that a std::vector provides.

So I was wondering if it's worth it or is there another "better" way to do what I want to do?

答: Absolutely yes you should be using std::vector for this. The "extra functionality" is all free. A std::vector is a template class so it won't even create the functions you don't use. Also the functions are trivial and inline so it won't even generate function calls, the compiler will strip away everything so the generated code will be nearly the same as if you had coded a built in dynamic array by hand.

Title: Should I just be using std::vector?


问:
C - How to get string from user when using typedef?
I have the following typedef in my code:

```<code>typedef char * string;
</code>```

And I need to have the user input a string so that I can then parse it and use the contents later. If I am just declaring a string with this definition it works, like this:

```<code>string bob = "My name is bob!;
printf("%s\n", bob);
</code>```

What should I use to get user input when using this, scanf() and fgets()
both give me Segmentation fault (core dumped) errors when I try to use them.

This is for school, which is why I need to use the typedef this way.

答:
That's because you have to set your starting value.

Assume you have char * a;

a has an undefined value, maybe pointing to an unauthorized area. You can not write in there.

What should you do? If you must use typedef char * string; , you have to write it on:
1) Dynamic heap, 2) on a buffer at the stack.

1) Use malloc - a function which has to be included from stdlib.h, and allocates memory at the Dynamic heap. The function returns a pointer to the start of the memory allocated.
Don't forget after using it to free the allocated memory to avoid leak, by free() function.

2) Declaring a foretold array size of chars, and give it's address to your variable.

```<code>#include <stdio.h>
#include <stdlib.h>

#define MY_SIZE 50
typedef char * string;

int main() {
    string s;

    // 1)
    s = malloc(MY_SIZE);
    // some code
    free(s);

    // 2)
    char buf[MY_SIZE];
    s = buf;

    return 0;
}
</code>```

You have to practice both ways.
Hope that I've helped!

Body:
I have the following typedef in my code:

typedef char * string;

And I need to have the user input a string so that I can then parse it and use the contents later. If I am just declaring a string with this definition it works, like this:

string bob = "My name is bob!;
printf("%s\n", bob);

What should I use to get user input when using this, scanf() and fgets()
both give me Segmentation fault (core dumped) errors when I try to use them.

This is for school, which is why I need to use the typedef this way.

Body:
That's because you have to set your starting value.

Assume you have char * a;

a has an undefined value, maybe pointing to an unauthorized area. You can not write in there.

What should you do? If you must use typedef char * string; , you have to write it on:
1) Dynamic heap, 2) on a buffer at the stack.

1) Use malloc - a function which has to be included from stdlib.h, and allocates memory at the Dynamic heap. The function returns a pointer to the start of the memory allocated.
Don't forget after using it to free the allocated memory to avoid leak, by free() function.

2) Declaring a foretold array size of chars, and give it's address to your variable.

#include <stdio.h>
#include <stdlib.h>

#define MY_SIZE 50
typedef char * string;

int main() {
    string s;

    // 1)
    s = malloc(MY_SIZE);
    // some code
    free(s);

    // 2)
    char buf[MY_SIZE];
    s = buf;

    return 0;
}

You have to practice both ways.
Hope that I've helped!


问:
How to find if a JSON object contains numbers and return them?
Lets say I have a jsonobject and this is coming from a random dataset dynamically. I would like to search through the jsonand do some manipulation on the number values of that jsonobject if there are any. I could loop through the Object by using a simple for..of and get the whole key but I am not sure how to go through every key value pair in the object and return the numbers. The following gives an example:

```<code>var obj = {
  "a0": {
    "count": 41,
    "name": "Park",

  },
  "a1": {
    "count": 52,
    "name": "Greg",

  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  },
  "a3": {
    "count": 276,
    "name": "Macho",

  },
  "a4": {
    "count": 36,
    "name": "Mariam",

  },
  "a5": {
    "count": 39,
    "name": "Blanca",

  }

}
</code>```

I can loop through it as follows:

```<code>for (let i of Object.keys(obj)) {
  console.log(obj[i]);
}
</code>```

I couldn't find any other properties on the Object other than hasOwnProperty and keys which could actually give me the values. I could simply access the values of the count by doing obj[i].count, but I wouldn't know if it has count. I am looking for a generic way to get the values and check for its type and return them as an array or do some manipulation with the number values.

Edit: I am looking to extract the properties which have numeric values in the object.

Could any one help me with this.

Thank you.

答:
Use Object.keys(), and iterate the array of keys with Array.map(). In the map use Array.reduce() to get just the properties that has numeric values:

to create an array of numbers:

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.keys(obj).map((key) => {
  const o = obj[key];

  return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ?
    Object.assign(r, { [k]: o[k] }) : r , {});
});

console.log(result);```
</div>
</div>
</p>

<p>And you can shorten it a bit by using Object.value(), and Object.entries() if they are supported by the target browser:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.values(obj).map((o) =>
  Object.entries(o).reduce((r, [k, v]) => typeof v === 'number' ?
    Object.assign(r, { [k]: v }) : r , {})
);

console.log(result);</code>```

If you can use Object.fromEntries(), you can use Array.filter() to remove properties which value is not a number, and then convert back to an object using Object.fromEntries():

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.values(obj)
  .map((o) => Object.fromEntries(
    Object
      .entries(o)
      .filter(([,v]) => typeof v === 'number')
  ))

console.log(result);```

Body:
Lets say I have a jsonobject and this is coming from a random dataset dynamically. I would like to search through the jsonand do some manipulation on the number values of that jsonobject if there are any. I could loop through the Object by using a simple for..of and get the whole key but I am not sure how to go through every key value pair in the object and return the numbers. The following gives an example:

var obj = {
  "a0": {
    "count": 41,
    "name": "Park",

  },
  "a1": {
    "count": 52,
    "name": "Greg",

  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  },
  "a3": {
    "count": 276,
    "name": "Macho",

  },
  "a4": {
    "count": 36,
    "name": "Mariam",

  },
  "a5": {
    "count": 39,
    "name": "Blanca",

  }

}

I can loop through it as follows:

for (let i of Object.keys(obj)) {
  console.log(obj[i]);
}

I couldn't find any other properties on the Object other than hasOwnProperty and keys which could actually give me the values. I could simply access the values of the count by doing obj[i].count, but I wouldn't know if it has count. I am looking for a generic way to get the values and check for its type and return them as an array or do some manipulation with the number values.

Edit: I am looking to extract the properties which have numeric values in the object.

Could any one help me with this.

Thank you.

Body:
Use Object.keys(), and iterate the array of keys with Array.map(). In the map use Array.reduce() to get just the properties that has numeric values:

to create an array of numbers:

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.keys(obj).map((key) => {
  const o = obj[key];

  return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ?
    Object.assign(r, { [k]: o[k] }) : r , {});
});

console.log(result);

And you can shorten it a bit by using Object.value(), and Object.entries() if they are supported by the target browser:

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.values(obj).map((o) =>
  Object.entries(o).reduce((r, [k, v]) => typeof v === 'number' ?
    Object.assign(r, { [k]: v }) : r , {})
);

console.log(result);

If you can use Object.fromEntries(), you can use Array.filter() to remove properties which value is not a number, and then convert back to an object using Object.fromEntries():

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.values(obj)
  .map((o) => Object.fromEntries(
    Object
      .entries(o)
      .filter(([,v]) => typeof v === 'number')
  ))

console.log(result);