问:
trying to manage the value of 2 inputs
I'm not really good for speaking english, but this problem could kill me.. I'm on since 3 days..

I have 2 inputs, each input can be 1 to 100.
But i need that the addition of the both is never below 100.
Exemple : 40 & 60, 30 & 70, ...

I tried to change the second input with a focusout (rly that i need), to add to the second input the value that i needed.
Exemple :
Input 1 : value 40
Input 2 : Value 20 (In this case i need that this input change to 60 whenever i focusout it)

Sorry for this poor english, but instead of reading a solution this time i need to post (Never posted before because i always find what i needed ).

This is my code :

```<code>if($("#coemp_pret1").val() == "1"){
    $(this).val(function(index, value) {
        var tempValue = $(this).val($(this).val() + $("#QuotDecAdh_s3p1").val());

        if( tempValue < "100" ){
            return value
                .replace(/\d{1,2}(?!\d)|100/, "");

            $(this).val(100 - $("#QuotDecAdh_s3p1").val());
        }
    });
}
</code>```

Thanks i hope you can help me, byebye !

答:
You can use 'blur' event on the second input & keyup on first input.

blur will start calculation as soon as focus is removed from the second input.
On updating first input the second field will set to empty

$("#coemp_pret1").on("keyup", function() {
  $("#QuotDecAdh_s3p1").val("");
});
$("#QuotDecAdh_s3p1").on("blur", function() {
  if ("" !== $("#coemp_pret1").val() && ($(this).val(), 100 > $(this).val() + $("#coemp_pret1").val())) {
    var a = 100 - $("#coemp_pret1").val();
    $(this).val(a);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="coemp_pret1">
<input type="text" id="QuotDecAdh_s3p1"></code>```

Title: trying to manage the value of 2 inputs

Body:
I'm not really good for speaking english, but this problem could kill me.. I'm on since 3 days..

I have 2 inputs, each input can be 1 to 100.
But i need that the addition of the both is never below 100.
Exemple : 40 & 60, 30 & 70, ...

I tried to change the second input with a focusout (rly that i need), to add to the second input the value that i needed.
Exemple :
Input 1 : value 40
Input 2 : Value 20 (In this case i need that this input change to 60 whenever i focusout it)

Sorry for this poor english, but instead of reading a solution this time i need to post (Never posted before because i always find what i needed ).

This is my code :

if($("#coemp_pret1").val() == "1"){
    $(this).val(function(index, value) {
        var tempValue = $(this).val($(this).val() + $("#QuotDecAdh_s3p1").val());

        if( tempValue < "100" ){
            return value
                .replace(/\d{1,2}(?!\d)|100/, "");

            $(this).val(100 - $("#QuotDecAdh_s3p1").val());
        }
    });
}

Thanks i hope you can help me, byebye !

Body:
You can use 'blur' event on the second input & keyup on first input.

blur will start calculation as soon as focus is removed from the second input.
On updating first input the second field will set to empty

$("#coemp_pret1").on("keyup", function() {
  $("#QuotDecAdh_s3p1").val("");
});
$("#QuotDecAdh_s3p1").on("blur", function() {
  if ("" !== $("#coemp_pret1").val() && ($(this).val(), 100 > $(this).val() + $("#coemp_pret1").val())) {
    var a = 100 - $("#coemp_pret1").val();
    $(this).val(a);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="coemp_pret1">
<input type="text" id="QuotDecAdh_s3p1">


来源: stackexchange

问:
use shared_ptr array for execl()
I have a shared_ptr to an array of char, like this:

```<code>std::shared_ptr<char[]> tmp [ 10 ] ;
</code>```

I have populated tmp, and now want to pass the data to execl(), which takes a char * const *.  What's the right way to do it?

答:
I have a shared_ptr to an array of char

What you have is a static array of 10 default-constructed std::shared_ptr objects.  Is that what you really want?

Or do you need a single std::shared_ptr object that holds a pointer to a single array?

```<code>std::shared_ptr<char[]> tmp(new char[10]);
</code>```

I have populated tmp, and now want to pass the data to execl(), which takes a char * const *.

No, it does not.  It takes 2+ const char* parameters.  Look at the declaration more carefully:

```<code>int execl(const char *path, const char *arg, ...);
</code>```

There is a big difference between const char* and char * const *.

What's the right way to do it?

The std::shared_ptr<char[]>::get() method will return a char*,  which can be passed to a const char* parameter.

Update: if you are trying to pass 10 seperate char[] arrays to execl(), one for each argument, then your static array is fine. Simply call tmp[index].get() for each argument you want to pass to execl():

```<code>std::shared_ptr<char[]> tmp[10];
// populate tmp, then ...
execl(file, tmp[0].get(), tmp[1].get(), ..., tmp[9].get());
</code>```

Alternatively, use execv() instead:

```<code>std::shared_ptr<char[]> tmp[10];
// populate tmp, then ...

char* args[11];
for (int i = 0; i < 10; ++i)
    args[i] = tmp[i].get();
args[10] = nullptr;

execv(file, args);
</code>```

Which is especially useful if you don't know the number of arguments ahead of time:

```<code>std::vector<std::shared_ptr<char[]>> tmp;
// populate tmp, then ...

std::vector<char*> args;
for (auto &p : tmp)
    args.push_back(p.get());
args.push_back(nullptr);

execv(file, args.data());
</code>```

ContentLicense: CC BY-SA 3.0

Title: use shared_ptr array for execl()

Body:
I have a shared_ptr to an array of char, like this:

std::shared_ptr<char[]> tmp [ 10 ] ;

I have populated tmp, and now want to pass the data to execl(), which takes a char * const *.  What's the right way to do it?

Body:
I have a shared_ptr to an array of char

What you have is a static array of 10 default-constructed std::shared_ptr objects.  Is that what you really want?

Or do you need a single std::shared_ptr object that holds a pointer to a single array?

std::shared_ptr<char[]> tmp(new char[10]);

I have populated tmp, and now want to pass the data to execl(), which takes a char * const *.

No, it does not.  It takes 2+ const char* parameters.  Look at the declaration more carefully:

int execl(const char *path, const char *arg, ...);

There is a big difference between const char* and char * const *.

What's the right way to do it?

The std::shared_ptr<char[]>::get() method will return a char*,  which can be passed to a const char* parameter.

Update: if you are trying to pass 10 seperate char[] arrays to execl(), one for each argument, then your static array is fine. Simply call tmp[index].get() for each argument you want to pass to execl():

std::shared_ptr<char[]> tmp[10];
// populate tmp, then ...
execl(file, tmp[0].get(), tmp[1].get(), ..., tmp[9].get());

Alternatively, use execv() instead:

std::shared_ptr<char[]> tmp[10];
// populate tmp, then ...

char* args[11];
for (int i = 0; i < 10; ++i)
    args[i] = tmp[i].get();
args[10] = nullptr;

execv(file, args);

Which is especially useful if you don't know the number of arguments ahead of time:

std::vector<std::shared_ptr<char[]>> tmp;
// populate tmp, then ...

std::vector<char*> args;
for (auto &p : tmp)
    args.push_back(p.get());
args.push_back(nullptr);

execv(file, args.data());


问:
Firefox display=block problem
I have a the following HTML

```<code> <a id="rptQuestions_ctl01_hlQuestion" onclick="rptQuestions_ctl01_pnlAnswer.style.display = rptQuestions_ctl01_pnlAnswer.style.display == 'none'? 'block' : 'none';" href="javascript:">Header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">

            My Text to display

</div>
</code>```

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

```<code>        <a id="rptQuestions_ctl01_hlQuestion" onclick="jasvascript:document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block';" href="#">My header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
My Text

</div>
</code>```

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

答:
The "onclick" attribute should have the following code:-

```<code>onclick="document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display = document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display == 'none' ? 'block' : 'none';"
</code>```

Hope it helps.

ContentLicense: CC BY-SA 2.5

Title: Firefox display=block problem

Body:
I have a the following HTML

 Header Link

            My Text to display

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

        My header Link

My Text

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

Body:
The "onclick" attribute should have the following code:-

onclick="document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display = document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display == 'none' ? 'block' : 'none';"

Hope it helps.


问:
Better to |> ignore or return ()
So this is just a curiosity question.

If I want to return unit, which is better practice?

```<code>|> ignore
</code>```

or

```<code>()
</code>```

There's probably other ways as well. I just want to know what's best, considering these:

What is most performant

What is best practice for a production environment

What is most readable for long term maintanance

答:
ignore is an inlined function so both will produce exactly the same IL.

ignore is more explicit and therefore more readable, and that's why it exists, so you should probably prefer that.

Title: Better to |> ignore or return ()

Body:
So this is just a curiosity question.

If I want to return unit, which is better practice?

|> ignore

or

()

There's probably other ways as well. I just want to know what's best, considering these:

What is most performant

What is best practice for a production environment

What is most readable for long term maintanance


问:
Why org.lwjgl.opengl.GL43 class has no glDrawElements method?
My question is more theoretical than practial. I want to understand idea behind OpenGL API design in LWJGL.

For example in Android OpenGL API each following OpenGL API version just extends previous, I mean:
android.opengl.GLES30 extends android.opengl.GLES20
android.opengl.GLES31 extends android.opengl.GLES30
etc

You can see source code here: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/opengl/GLES20.java, http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/opengl/GLES30.java, http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/opengl/GLES31.java

Why in Lwjgl there is no such concept? What is the reason behind such design when I have to use GL11.glDrawElements(); instead of GL43.glDrawElements(); ?

答:
It's a choice they made with LWJGL. Submission of indexed geometry has been around since OpenGL 1.1 and they make it a habit of exposing what was added in later revisions, instead of giving you a cumulative set of entry points, as is common with extension loaders like GLEW.

It doesn't have to be like this (clearly, Google went down a different path and so did others, independent of the programming language) but in the end, it doesn't matter. All that matters is that the entry point is exposed to you. Sometimes it's good to see (and to know) at which point in time a particular API was promoted to core, but dividing stuff up like this can be quite cumbersome for the developer.

If it were defined in another way in the language of your choice and provided that this language supports interfacing with native code, the function you'd be ultimately calling would still be the same, because under the hood, the corresponding function pointer is retrieved with some form of GetProcAddress (depending on the platform, YMMV) and would refer to the same C function defined by the ICD (unless you link directly against an OpenGL implementation, in which case you resolution of function names would either be unnecessary when linking statically, or handled automatically during program load).


问:
Buttons won't go side by side
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

```<code><div class="navbar navbar-default navbar-fixed-top">
                    <div class="navbar-header">
                        <button type="button" id="searchbuttonmobile" ><img src="~/Images/SearchBtn.png" /></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">
                            <img src="~/Images/MobileMenuBtn.png" />
                        </button>
</div>
</code>```

CSS:

```<code>/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}
</code>```

答:
.navbar-header button{
      float:right;
    }```

Add the above code in your CSS.

Here is Working Demo

Hope this helps.

Title: Buttons won't go side by side

Body:
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

                        <button type="button" id="searchbuttonmobile" ></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">

                        </button>

CSS:

/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}

Body:
.navbar-header button{
      float:right;
    }

Add the above code in your CSS.

Here is Working Demo

Hope this helps.


问:
Error while using h264_cuvid decoder with ffmpeg
I am trying to decode a video using the NVIDIA cuvid hardware acceleration with ffmpeg.

I am using a NVIDIA GeForce GT 745M Graphics card (GPU:GK107), which is compatible with cuvid as specified by NVIDIA here

I compiled ffmpeg with the following flags:

```<code>./configure --enable-cuda --enable-nvenc --enable-cuvid
</code>```

Then, I used ffmpeg with the following command line:

```<code>ffmpeg.exe -hwaccel cuvid -c:v h264_cuvid -i video.mkv video.mkv
</code>```

ffmpeg finishes and seems to be unable to open cuvid functions:

```<code>Cannot load cuvidGetDecoderCaps
[h264_cuvid @ 07047b80] Failed loading nvcuvid.
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (h264_cuvid) -> h264 (libx264))
  Stream #0:1 -> #0:1 (ac3 (native) -> vorbis (libvorbis))
  Stream #0:3 -> #0:2 (subrip (srt) -> ass (ssa))
Error while opening decoder for input stream #0:0 : Unknown error occurred
</code>```

In ffmpeg source code, I can find out that this error message is printed by the following macro:

```<code>#define LOAD_SYMBOL(fun, tp, symbol)                                \
    do {                                                            \
        if (!((f->fun) = (tp*)dlsym(f->lib, symbol))) {             \
            av_log(NULL, AV_LOG_ERROR, "Cannot load %s\n", symbol); \
            ret = AVERROR_UNKNOWN;                                  \
            goto error;                                             \
        }                                                           \
        av_log(NULL, AV_LOG_TRACE, "Loaded sym: %s\n", symbol);     \
    } while (0)
</code>```

Which is called by:

```<code>static inline int cuvid_load_functions(CuvidFunctions **functions)
{
    GENERIC_LOAD_FUNC_PREAMBLE(CuvidFunctions, cuvid, NVCUVID_LIBNAME);

    LOAD_SYMBOL(cuvidGetDecoderCaps, tcuvidGetDecoderCaps, "cuvidGetDecoderCaps");
    LOAD_SYMBOL(cuvidCreateDecoder, tcuvidCreateDecoder, "cuvidCreateDecoder");
    LOAD_SYMBOL(cuvidDestroyDecoder, tcuvidDestroyDecoder, "cuvidDestroyDecoder");
    LOAD_SYMBOL(cuvidDecodePicture, tcuvidDecodePicture, "cuvidDecodePicture");
#ifdef __CUVID_DEVPTR64
    LOAD_SYMBOL(cuvidMapVideoFrame, tcuvidMapVideoFrame, "cuvidMapVideoFrame64");
    LOAD_SYMBOL(cuvidUnmapVideoFrame, tcuvidUnmapVideoFrame, "cuvidUnmapVideoFrame64");
#else
    LOAD_SYMBOL(cuvidMapVideoFrame, tcuvidMapVideoFrame, "cuvidMapVideoFrame");
    LOAD_SYMBOL(cuvidUnmapVideoFrame, tcuvidUnmapVideoFrame, "cuvidUnmapVideoFrame");
#endif
    LOAD_SYMBOL(cuvidCtxLockCreate, tcuvidCtxLockCreate, "cuvidCtxLockCreate");
    LOAD_SYMBOL(cuvidCtxLockDestroy, tcuvidCtxLockDestroy, "cuvidCtxLockDestroy");
    LOAD_SYMBOL(cuvidCtxLock, tcuvidCtxLock, "cuvidCtxLock");
    LOAD_SYMBOL(cuvidCtxUnlock, tcuvidCtxUnlock, "cuvidCtxUnlock");

    LOAD_SYMBOL(cuvidCreateVideoSource, tcuvidCreateVideoSource, "cuvidCreateVideoSource");
    LOAD_SYMBOL(cuvidCreateVideoSourceW, tcuvidCreateVideoSourceW, "cuvidCreateVideoSourceW");
    LOAD_SYMBOL(cuvidDestroyVideoSource, tcuvidDestroyVideoSource, "cuvidDestroyVideoSource");
    LOAD_SYMBOL(cuvidSetVideoSourceState, tcuvidSetVideoSourceState, "cuvidSetVideoSourceState");
    LOAD_SYMBOL(cuvidGetVideoSourceState, tcuvidGetVideoSourceState, "cuvidGetVideoSourceState");
    LOAD_SYMBOL(cuvidGetSourceVideoFormat, tcuvidGetSourceVideoFormat, "cuvidGetSourceVideoFormat");
    LOAD_SYMBOL(cuvidGetSourceAudioFormat, tcuvidGetSourceAudioFormat, "cuvidGetSourceAudioFormat");
    LOAD_SYMBOL(cuvidCreateVideoParser, tcuvidCreateVideoParser, "cuvidCreateVideoParser");
    LOAD_SYMBOL(cuvidParseVideoData, tcuvidParseVideoData, "cuvidParseVideoData");
    LOAD_SYMBOL(cuvidDestroyVideoParser, tcuvidDestroyVideoParser, "cuvidDestroyVideoParser");

    GENERIC_LOAD_FUNC_FINALE(cuvid);
}
</code>```

Does anybody know if a specific file is needed by cuvid to load its functions?
Any clue to what is wrong here?

答:
I don't have the problem anymore.

I forgot to use libnpp during ffmpeg compilation.

My current configuration is :

```<code>./configure --enable-cuda --enable-nvenc --enable-cuvid --enable-libnpp --extra-cflags=-I<path_to_libnpp_headers> --extra-ldflags=-L<path_to_libnpp_libraries>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to decode a video using the NVIDIA cuvid hardware acceleration with ffmpeg.

I am using a NVIDIA GeForce GT 745M Graphics card (GPU:GK107), which is compatible with cuvid as specified by NVIDIA here

I compiled ffmpeg with the following flags:

./configure --enable-cuda --enable-nvenc --enable-cuvid

Then, I used ffmpeg with the following command line:

ffmpeg.exe -hwaccel cuvid -c:v h264_cuvid -i video.mkv video.mkv

ffmpeg finishes and seems to be unable to open cuvid functions:

Cannot load cuvidGetDecoderCaps
[h264_cuvid @ 07047b80] Failed loading nvcuvid.
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (h264_cuvid) -> h264 (libx264))
  Stream #0:1 -> #0:1 (ac3 (native) -> vorbis (libvorbis))
  Stream #0:3 -> #0:2 (subrip (srt) -> ass (ssa))
Error while opening decoder for input stream #0:0 : Unknown error occurred

In ffmpeg source code, I can find out that this error message is printed by the following macro:

#define LOAD_SYMBOL(fun, tp, symbol)                                \
    do {                                                            \
        if (!((f->fun) = (tp*)dlsym(f->lib, symbol))) {             \
            av_log(NULL, AV_LOG_ERROR, "Cannot load %s\n", symbol); \
            ret = AVERROR_UNKNOWN;                                  \
            goto error;                                             \
        }                                                           \
        av_log(NULL, AV_LOG_TRACE, "Loaded sym: %s\n", symbol);     \
    } while (0)

Which is called by:

static inline int cuvid_load_functions(CuvidFunctions **functions)
{
    GENERIC_LOAD_FUNC_PREAMBLE(CuvidFunctions, cuvid, NVCUVID_LIBNAME);

    LOAD_SYMBOL(cuvidGetDecoderCaps, tcuvidGetDecoderCaps, "cuvidGetDecoderCaps");
    LOAD_SYMBOL(cuvidCreateDecoder, tcuvidCreateDecoder, "cuvidCreateDecoder");
    LOAD_SYMBOL(cuvidDestroyDecoder, tcuvidDestroyDecoder, "cuvidDestroyDecoder");
    LOAD_SYMBOL(cuvidDecodePicture, tcuvidDecodePicture, "cuvidDecodePicture");
#ifdef __CUVID_DEVPTR64
    LOAD_SYMBOL(cuvidMapVideoFrame, tcuvidMapVideoFrame, "cuvidMapVideoFrame64");
    LOAD_SYMBOL(cuvidUnmapVideoFrame, tcuvidUnmapVideoFrame, "cuvidUnmapVideoFrame64");
#else
    LOAD_SYMBOL(cuvidMapVideoFrame, tcuvidMapVideoFrame, "cuvidMapVideoFrame");
    LOAD_SYMBOL(cuvidUnmapVideoFrame, tcuvidUnmapVideoFrame, "cuvidUnmapVideoFrame");
#endif
    LOAD_SYMBOL(cuvidCtxLockCreate, tcuvidCtxLockCreate, "cuvidCtxLockCreate");
    LOAD_SYMBOL(cuvidCtxLockDestroy, tcuvidCtxLockDestroy, "cuvidCtxLockDestroy");
    LOAD_SYMBOL(cuvidCtxLock, tcuvidCtxLock, "cuvidCtxLock");
    LOAD_SYMBOL(cuvidCtxUnlock, tcuvidCtxUnlock, "cuvidCtxUnlock");

    LOAD_SYMBOL(cuvidCreateVideoSource, tcuvidCreateVideoSource, "cuvidCreateVideoSource");
    LOAD_SYMBOL(cuvidCreateVideoSourceW, tcuvidCreateVideoSourceW, "cuvidCreateVideoSourceW");
    LOAD_SYMBOL(cuvidDestroyVideoSource, tcuvidDestroyVideoSource, "cuvidDestroyVideoSource");
    LOAD_SYMBOL(cuvidSetVideoSourceState, tcuvidSetVideoSourceState, "cuvidSetVideoSourceState");
    LOAD_SYMBOL(cuvidGetVideoSourceState, tcuvidGetVideoSourceState, "cuvidGetVideoSourceState");
    LOAD_SYMBOL(cuvidGetSourceVideoFormat, tcuvidGetSourceVideoFormat, "cuvidGetSourceVideoFormat");
    LOAD_SYMBOL(cuvidGetSourceAudioFormat, tcuvidGetSourceAudioFormat, "cuvidGetSourceAudioFormat");
    LOAD_SYMBOL(cuvidCreateVideoParser, tcuvidCreateVideoParser, "cuvidCreateVideoParser");
    LOAD_SYMBOL(cuvidParseVideoData, tcuvidParseVideoData, "cuvidParseVideoData");
    LOAD_SYMBOL(cuvidDestroyVideoParser, tcuvidDestroyVideoParser, "cuvidDestroyVideoParser");

    GENERIC_LOAD_FUNC_FINALE(cuvid);
}

Does anybody know if a specific file is needed by cuvid to load its functions?
Any clue to what is wrong here?

Body:
I don't have the problem anymore.

I forgot to use libnpp during ffmpeg compilation.

My current configuration is :

./configure --enable-cuda --enable-nvenc --enable-cuvid --enable-libnpp --extra-cflags=-I<path_to_libnpp_headers> --extra-ldflags=-L<path_to_libnpp_libraries>


问:
How to define choice element in json schema when elements are optional?
------------Josn schema-----------

```<code>{
    "type": "object",
    "properties": {
        "street_address": {
            "type": "string"
        },
        "city": {
            "type": "string"
        },
        "state": {
            "type": "string"
        }
    },
    "required": [
        "street_address"
    ],
    "additionalProperties": false
}
</code>```

In above schema i want to create a choice between city and state. That is either city or state can come in json. So that below json would be invalid

```<code>{
    "street_address": "abc",
    "city": "anv",
    "state": "opi"
}
</code>```

and below one should be valid one

```<code>{
    "street_address": "abc"
}
</code>```

or

```<code>{
    "street_address": "abc",
    "city": "anv"
}
</code>```

or

```<code>{
    "street_address": "abc",
    "state": "opi"
}
</code>```

Can some one please help me to modify above schema to accomplish the goal.

答:
Here is a schema that satisfies all four conditions:</p>

```<code>    {
        "type": "object",
        "properties": {
            "street_address": {
                "type": "string"
            },
            "city": {
                "type": "string"
            },
            "state": {
                "type": "string"
            }
        },
        "required": [
            "street_address"
        ],
        "anyOf": [{}, {
            "required": ["city"]
        }, {
            "required": ["state"]
        }],
        "not": {
            "required": ["city", "state"]
        },
        "additionalProperties": false
    }
</code>```

Body:
------------Josn schema-----------

{
    "type": "object",
    "properties": {
        "street_address": {
            "type": "string"
        },
        "city": {
            "type": "string"
        },
        "state": {
            "type": "string"
        }
    },
    "required": [
        "street_address"
    ],
    "additionalProperties": false
}

In above schema i want to create a choice between city and state. That is either city or state can come in json. So that below json would be invalid

{
    "street_address": "abc",
    "city": "anv",
    "state": "opi"
}

and below one should be valid one

{
    "street_address": "abc"
}

or

{
    "street_address": "abc",
    "city": "anv"
}

or

{
    "street_address": "abc",
    "state": "opi"
}

Can some one please help me to modify above schema to accomplish the goal.

Body:
Here is a schema that satisfies all four conditions:

    {
        "type": "object",
        "properties": {
            "street_address": {
                "type": "string"
            },
            "city": {
                "type": "string"
            },
            "state": {
                "type": "string"
            }
        },
        "required": [
            "street_address"
        ],
        "anyOf": [{}, {
            "required": ["city"]
        }, {
            "required": ["state"]
        }],
        "not": {
            "required": ["city", "state"]
        },
        "additionalProperties": false
    }


问:
Get Title and Description when Title item is clicked on Listview android
I use JSON to get data items Title and Description from a web server. I know how to parse it, use a custom Adapter and populate a listview with the Title only.. I want it to open a new activity and display the Title and Description of the clicked Item. Do I have to create a new custom adapter to populate this listview?  What should I pass from this side of the activity and how do I receive it on the other side?  Thanks in advance.

```<code> displayTitleAdapter = new DisplayTitleAdapter(this, R.layout.rowlayout);
    listView = (ListView)findViewById(R.id.listviewfinal);
    listView.setAdapter(displayTitleAdapter);
    listView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
</code>```

This is my  Adapter class' getView method

```<code>public View getView(int position,  View convertView,  ViewGroup parent) {
    View row;
    row = convertView;
    ReqHolder reqHolder;
    if(row == null){
        LayoutInflater layoutInflate = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflate.inflate(R.layout.rowlayout, parent, false);
        reqHolder = new ReqHolder();

        reqHolder.Title = (TextView)row.findViewById(R.id.title_title);
        reqHolder.Requirement = (TextView)row.findViewById(R.id.req_req);

        row.setTag(reqHolder);
    }
    else{
        reqHolder = (ReqHolder)row.getTag();
    }
    //Requirements is the model class with getter and setter methods for Fields Title and Requirement.
    Requirements requirements = (Requirements) this.getItem(position);
    reqHolder.Title.setText(requirements.getTitle());
    reqHolder.Requirement.setText(requirements.getRequirement());
    return row;
}

static class ReqHolder{
    TextView Title;
     TextView Requirement;
}
</code>```

}

答:
Here is how i did it for me, please make sure your modal class implements Serializable.

MainActivity:

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getApplicationContext(),Main2Activity.class);
            i.putExtra("Question",questionArrayList.get(position));
            startActivity(i);
        }
    });
</code>```

In my main activity i set an on item click listener on my listview and then start an activity using the intent class.

In my next class i get the object i put into the intent (question) ans display the text that i want to using getters and setters from my modal class

Acitvity 2:

```<code>public class Main2Activity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activitiy_main2);
    Question q = (Question) getIntent().getSerializableExtra("Question");

    TextView yourAnswer= (TextView)findViewById(R.id.title);
    TextView correctAnswer = (TextView)findViewById(R.id.description);

    yourAnswer.setText(q.getYourAnswer());
    correctAnswer.setText(q.getCorrectAnswer());
}
}
</code>```

Hope this helped you out!

Body:
I use JSON to get data items Title and Description from a web server. I know how to parse it, use a custom Adapter and populate a listview with the Title only.. I want it to open a new activity and display the Title and Description of the clicked Item. Do I have to create a new custom adapter to populate this listview?  What should I pass from this side of the activity and how do I receive it on the other side?  Thanks in advance.

 displayTitleAdapter = new DisplayTitleAdapter(this, R.layout.rowlayout);
    listView = (ListView)findViewById(R.id.listviewfinal);
    listView.setAdapter(displayTitleAdapter);
    listView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

This is my  Adapter class' getView method

public View getView(int position,  View convertView,  ViewGroup parent) {
    View row;
    row = convertView;
    ReqHolder reqHolder;
    if(row == null){
        LayoutInflater layoutInflate = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflate.inflate(R.layout.rowlayout, parent, false);
        reqHolder = new ReqHolder();

        reqHolder.Title = (TextView)row.findViewById(R.id.title_title);
        reqHolder.Requirement = (TextView)row.findViewById(R.id.req_req);

        row.setTag(reqHolder);
    }
    else{
        reqHolder = (ReqHolder)row.getTag();
    }
    //Requirements is the model class with getter and setter methods for Fields Title and Requirement.
    Requirements requirements = (Requirements) this.getItem(position);
    reqHolder.Title.setText(requirements.getTitle());
    reqHolder.Requirement.setText(requirements.getRequirement());
    return row;
}

static class ReqHolder{
    TextView Title;
     TextView Requirement;
}

}

Body:
Here is how i did it for me, please make sure your modal class implements Serializable.

MainActivity:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getApplicationContext(),Main2Activity.class);
            i.putExtra("Question",questionArrayList.get(position));
            startActivity(i);
        }
    });

In my main activity i set an on item click listener on my listview and then start an activity using the intent class.

In my next class i get the object i put into the intent (question) ans display the text that i want to using getters and setters from my modal class

Acitvity 2:

public class Main2Activity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activitiy_main2);
    Question q = (Question) getIntent().getSerializableExtra("Question");

    TextView yourAnswer= (TextView)findViewById(R.id.title);
    TextView correctAnswer = (TextView)findViewById(R.id.description);

    yourAnswer.setText(q.getYourAnswer());
    correctAnswer.setText(q.getCorrectAnswer());
}
}

Hope this helped you out!


问:
How to find repeating sequence of Integers in an array of Integers in java?
For example if input is:

2 0 6 3 1 6 3 1 6 3 1

then output should be 6 3 1.Need to find the first repetition cycle.

```<code>class FindDuplicate
{
void printRepeating(int arr[], int size)
{
    int i;
    System.out.println("The repeating elements are : ");

    for (i = 0; i < size; i++)
    {
        if (arr[Math.abs(arr[i])] >= 0)
            arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
        else
            System.out.print(Math.abs(arr[i]) + " ");
    }
}

public static void main(String[] args)
{
    FindDuplicate duplicate = new FindDuplicate();
    int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
    int arr_size = arr.length;
    duplicate.printRepeating(arr, arr_size);
}
}
</code>```

答:
https://pastebin.com/12bnjzfw
Have used java 8 streams for collection creation.</p>

```<code>for (int seqSize = ints.size() / 2; seqSize > 0; seqSize--) { //It should be first cycle. Main priority is biggest sequence
  for (int i = 0; i < ints.size() / seqSize; i++) { //Start position of the first block
    for (int j = i + seqSize; j < ints.size() - seqSize + 1; j++) {
      if (ints.subList(i, i + seqSize).equals(ints.subList(j, j + seqSize))) {
        System.out.println("Answer is: " + ints.subList(i, i + seqSize));
        return;
      }
    }
  }
}
</code>```

Body:
For example if input is:

2 0 6 3 1 6 3 1 6 3 1

then output should be 6 3 1.Need to find the first repetition cycle.

class FindDuplicate
{
void printRepeating(int arr[], int size)
{
    int i;
    System.out.println("The repeating elements are : ");

    for (i = 0; i < size; i++)
    {
        if (arr[Math.abs(arr[i])] >= 0)
            arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
        else
            System.out.print(Math.abs(arr[i]) + " ");
    }
}

public static void main(String[] args)
{
    FindDuplicate duplicate = new FindDuplicate();
    int arr[] = {1, 2, 3, 1, 2, 3, 1, 2, 3 };
    int arr_size = arr.length;
    duplicate.printRepeating(arr, arr_size);
}
}

Body:
https://pastebin.com/12bnjzfw
Have used java 8 streams for collection creation.

for (int seqSize = ints.size() / 2; seqSize > 0; seqSize--) { //It should be first cycle. Main priority is biggest sequence
  for (int i = 0; i < ints.size() / seqSize; i++) { //Start position of the first block
    for (int j = i + seqSize; j < ints.size() - seqSize + 1; j++) {
      if (ints.subList(i, i + seqSize).equals(ints.subList(j, j + seqSize))) {
        System.out.println("Answer is: " + ints.subList(i, i + seqSize));
        return;
      }
    }
  }
}


问:
Why we cannot mark the visibility of a class as "protected" in kotlin?
I am new to kotlin I have been learning about inheritance in kotlin recently, and then I realised that we cannot mark the visibility of a class as "protected". Correct me if i am wrong, or is there any other way to make a class protected ?</p>

答:
You can mark protected only parts of classes, so that they become accessible only from the derived classes. You can mark protected a member property, a member function or a nested class:

```<code>open class X {
    protected val v: SomeType = someValue
    protected fun f() { }
    protected class Y { ... }
}
</code>```

But you cannot mark protected anything that does not belong to a class (e.g. a top-level class or function), because the modifier would make no sense: a top-level entity is not subject to inheritance, thus there can be no derived class that would access it.

Body:
You can mark protected only parts of classes, so that they become accessible only from the derived classes. You can mark protected a member property, a member function or a nested class:

open class X {
    protected val v: SomeType = someValue
    protected fun f() { }
    protected class Y { ... }
}

But you cannot mark protected anything that does not belong to a class (e.g. a top-level class or function), because the modifier would make no sense: a top-level entity is not subject to inheritance, thus there can be no derived class that would access it.


问:
Why am I getting an "End of Statement" compile error in my Excel VBA code?
Below is my code in VBA:

```<code>Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

If Hamza_Variable = 7 Then

MsgBox Hamza_Variable & " Is da bomb"

Elself Hamza_Variable > 7 Then

MsgBox Hamza_Variable & " Is da bigger bomb"

Else

MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End If
</code>```

It is continuously giving the compile error "End of Statement" on the following line:

```<code>Elself Hamza_Variable > 7 Then
</code>```

It highlights Then and gives this error.

答:
In your original code, you wrote Elself instead of ElseIf (note the typo confusing l and I) in the line where you are getting your error. This likely confused VBA, which in turn gave you that misleading error message.

(Don't feel too bad. Other people have also had problems distinguishing these two letters in some monospace fonts before.)

Body:
Below is my code in VBA:

Sub Hamza_Starting_to_Learn()

Dim Hamza_Variable As Long

Hamza_Variable = 7

If Hamza_Variable = 7 Then

MsgBox Hamza_Variable & " Is da bomb"

Elself Hamza_Variable > 7 Then

MsgBox Hamza_Variable & " Is da bigger bomb"

Else

MsgBox Hamza_Variable & "We got ourselves a problem here bro"

End If

It is continuously giving the compile error "End of Statement" on the following line:

Elself Hamza_Variable > 7 Then

It highlights Then and gives this error.


问:
Rails 5: Associated relation triggers create instead of update on edit view
I started with the guide on http://guides.rubyonrails.org/getting_started.html. I successfully get it up and running. So far I made a few adjustments (like naming of the controller, etc.). This tutorial didn't cover how to update the relations of a model and this is the point I'm currently struggling.

models/game.rb

```<code>class Game < ApplicationRecord
    has_many :achievements, dependent: :destroy
    validates :title, presence: true,
                    length: { minimum: 5 }
end
</code>```

models/achievement.rb

```<code>class Achievement < ApplicationRecord
  belongs_to :game
end
</code>```

The update of my games, work like a charm.

controller/game_controller.rb

```<code>def edit
    @game = Game.find(params[:id])
end

    def update
            @game = Game.find(params[:id])

            if @game.update(game_params)
                redirect_to @game
            else
                render 'edit'
            end

        end

    private
            def game_params
                params.require(:game).permit(:title, :total_gs_points)
            end
</code>```

So I tried to transfer it to my achievements

controller/achievements_controller.rb

```<code>def edit
        @game = Game.find(params[:game_id])
        @achievement = @game.achievements.find(params[:id])
end

def update
        @game = Game.find(params[:game_id])
        @achievement = @game.achievements.find(params[:id])
        # @achievement = Achievement.find(params[:id])

        if @achievement.update(achievement_params)
            redirect_to game_achievements_path(@game)
        else
            render 'edit'
        end

end

private
        def achievement_params
            params.require(:achievement).permit(:id, :title, :description, :status, :hint, :pinned, :gs_points)
        end
</code>```

But there, every time I call my edit route, it fires a create event.

```<code>Started GET "/games/1/achievements/3/edit" for 127.0.0.1 at 2017-06-06 15:57:45 +0200
Processing by AchievementsController#edit as HTML
  Parameters: {"game_id"=>"1", "id"=>"3"}
  Game Load (0.3ms)  SELECT  `games`.* FROM `games` WHERE `games`.`id` = 1 LIMIT 1
  Achievement Load (0.3ms)  SELECT  `achievements`.* FROM `achievements` WHERE `achievements`.`game_id` = 1 AND `achievements`.`id` = 3 LIMIT 1
  Rendering achievements/edit.html.erb within layouts/application
  Rendered achievements/_form.html.erb (3.2ms) [cache miss]
  Rendered achievements/edit.html.erb within layouts/application (8.2ms)
Completed 200 OK in 28ms (Views: 23.9ms | ActiveRecord: 0.6ms)
</code>```

My included form _form.html.erb in views/achievements/edit.html.erb looks like:

```<code><%= form_for([@game, @game.achievements.build]) do |f| %>
    <p>
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :description %><br>
        <%= f.text_field :description %>
    </p>
    <p>
        <%= f.label :status %><br>
        <%= f.select :status, options_for_select([ 'open', 'claimed' ], 'open') %>
    </p>
    <p>
        <%= f.label :hint %><br>
        <%= f.text_area :hint %>
    </p>
    <p>
        <%= f.label :pinned %><br>
        <%= f.check_box :hint %>
    </p>
    <p>
        <%= f.label :gs_points %><br>
        <%= f.select :gs_points, options_for_select([ 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 ], 50) %>
    </p>

    <p>
        <%= f.submit %>
    </p>
<% end %>
</code>```

On my edit.html.erb, I get the correct achievement information, but don't know why the fields are not getting prefilled. The Submit buttons text is every time "Create achievement"

edit.html.erb

```<code><h1>Edit Achievement: <%= @achievement.title %></h1>

<%= render 'form' %>

<%= link_to 'Back', game_achievements_path(@game) %>
</code>```

Thanks & Regards,
mybecks

答:
What does your routes file look like? You may be able to just do something like this:

```<code><%= form_for @achievement do |f| %>
< your form code >
</code>```

Based on your update method Rails should be able to find the achievement associated with the specific game. I'm not 100% sure though, let me know if this works for you.
Edit:
You can probably do something in routes like this:

```<code>resources :games do
    resources  :achievements
end
</code>```

Body:
I started with the guide on http://guides.rubyonrails.org/getting_started.html. I successfully get it up and running. So far I made a few adjustments (like naming of the controller, etc.). This tutorial didn't cover how to update the relations of a model and this is the point I'm currently struggling.

models/game.rb

class Game < ApplicationRecord
    has_many :achievements, dependent: :destroy
    validates :title, presence: true,
                    length: { minimum: 5 }
end

models/achievement.rb

class Achievement < ApplicationRecord
  belongs_to :game
end

The update of my games, work like a charm.

controller/game_controller.rb

def edit
    @game = Game.find(params[:id])
end

    def update
            @game = Game.find(params[:id])

            if @game.update(game_params)
                redirect_to @game
            else
                render 'edit'
            end

        end

    private
            def game_params
                params.require(:game).permit(:title, :total_gs_points)
            end

So I tried to transfer it to my achievements

controller/achievements_controller.rb

def edit
        @game = Game.find(params[:game_id])
        @achievement = @game.achievements.find(params[:id])
end

def update
        @game = Game.find(params[:game_id])
        @achievement = @game.achievements.find(params[:id])
        # @achievement = Achievement.find(params[:id])

        if @achievement.update(achievement_params)
            redirect_to game_achievements_path(@game)
        else
            render 'edit'
        end

end

private
        def achievement_params
            params.require(:achievement).permit(:id, :title, :description, :status, :hint, :pinned, :gs_points)
        end

But there, every time I call my edit route, it fires a create event.

Started GET "/games/1/achievements/3/edit" for 127.0.0.1 at 2017-06-06 15:57:45 +0200
Processing by AchievementsController#edit as HTML
  Parameters: {"game_id"=>"1", "id"=>"3"}
  Game Load (0.3ms)  SELECT  `games`.* FROM `games` WHERE `games`.`id` = 1 LIMIT 1
  Achievement Load (0.3ms)  SELECT  `achievements`.* FROM `achievements` WHERE `achievements`.`game_id` = 1 AND `achievements`.`id` = 3 LIMIT 1
  Rendering achievements/edit.html.erb within layouts/application
  Rendered achievements/_form.html.erb (3.2ms) [cache miss]
  Rendered achievements/edit.html.erb within layouts/application (8.2ms)
Completed 200 OK in 28ms (Views: 23.9ms | ActiveRecord: 0.6ms)

My included form _form.html.erb in views/achievements/edit.html.erb looks like:

<%= form_for([@game, @game.achievements.build]) do |f| %>

        <%= f.label :title %>

        <%= f.text_field :title %>

        <%= f.label :description %>

        <%= f.text_field :description %>

        <%= f.label :status %>

        <%= f.select :status, options_for_select([ 'open', 'claimed' ], 'open') %>

        <%= f.label :hint %>

        <%= f.text_area :hint %>

        <%= f.label :pinned %>

        <%= f.check_box :hint %>

        <%= f.label :gs_points %>

        <%= f.select :gs_points, options_for_select([ 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 ], 50) %>

        <%= f.submit %>

<% end %>

On my edit.html.erb, I get the correct achievement information, but don't know why the fields are not getting prefilled. The Submit buttons text is every time "Create achievement"

edit.html.erb

Edit Achievement: <%= @achievement.title %>

<%= render 'form' %>

<%= link_to 'Back', game_achievements_path(@game) %>

Thanks & Regards,
mybecks

Body:
What does your routes file look like? You may be able to just do something like this:

<%= form_for @achievement do |f| %>
< your form code >

Based on your update method Rails should be able to find the achievement associated with the specific game. I'm not 100% sure though, let me know if this works for you.
Edit:
You can probably do something in routes like this:

resources :games do
    resources  :achievements
end


问:
React production rendering blank with Laravel
I didn't want to post this question but it seems like I have tried everything possible.

My index_bundle.js is created for production through webpack.

```<code>new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('production')
  }
}),
new webpack.optimize.UglifyJsPlugin({
  compress:{
    // warnings: true
  }
})
</code>```

I have Laravel routes set to use wildcards to make way for the react router aswell.

React is rendering the actual website in development mode but the production mode won't render anything but "react-empty".

There are no errors in the console, other than development build error, prior to making webpack production-ready.

答:
I have finally found the answer, I will post it in case someone else needs help in the future.

Using React (w/ React-router) requires the domain to be a virtual host and not just localhost/{slug}. It turns out react-router was trying to display the page "pie-test/public".

Body:
I didn't want to post this question but it seems like I have tried everything possible.

My index_bundle.js is created for production through webpack.

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('production')
  }
}),
new webpack.optimize.UglifyJsPlugin({
  compress:{
    // warnings: true
  }
})

I have Laravel routes set to use wildcards to make way for the react router aswell.

React is rendering the actual website in development mode but the production mode won't render anything but "react-empty".

There are no errors in the console, other than development build error, prior to making webpack production-ready.


问:
`docker run` using Golang API (Docker docs)
I am trying to use Docker's tutorial in recreating a docker run. Here is the following code from online tutorial

```<code> package main

 import (
 "io"
 "os"

"github.com/docker/docker/client"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"golang.org/x/net/context"
 )

 func main() {
ctx := context.Background()
cli, err := client.NewEnvClient()
if err != nil {
    panic(err)
}

_, err = cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
if err != nil {
    panic(err)
}

resp, err := cli.ContainerCreate(ctx, &container.Config{
    Image: "alpine",
    Cmd:   []string{"echo", "hello world"},
}, nil, nil, "")
if err != nil {
    panic(err)
}

if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{});     err != nil {
    panic(err)
}

if _, err = cli.ContainerWait(ctx, resp.ID); err != nil {
    panic(err)
}

out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
if err != nil {
    panic(err)
}

io.Copy(os.Stdout, out)
}
</code>```

The problem I see with this is, if 'alpine' docker, is not available locally, it doesn't pull the latest and ends up throwing an error.
  e.g
        XXXXX$ go run go_docker.go
        panic: Error: No such image: alpine

```<code>    goroutine 1 [running]:
      panic(0x27ffa0, 0xc4202afa50)
    /usr/local/go/src/runtime/panic.go:500 +0x1a1
    main.main()
    /Users/rvenkatesh/go_coding/raghu_test_code/go_docker.go:30 +0x592
    exit status 2
</code>```

But when I run the commandline equivalent, I see

```<code>    XXXX$ docker run alpine echo hello world
    Unable to find image 'alpine:latest' locally
    latest: Pulling from library/alpine
    627beaf3eaaf: Pull complete

        Digest:sha256:58e1a1bb75db1b5a24a462dd5e2915277ea06438c3f105138f97eb53149673c4
    Status: Downloaded newer image for alpine:latest
    hello world
</code>```

I tried looking through Go client, do I need to tweak anything with ImagePull function? Any help here would be appreciated!

Here is the link to the docs https://docs.docker.com/engine/api/getting-started/

Update: I had tested the same tutorial for python version, and it worked just fine. I wonder if the Golang page needs update.

答:
Was having the same issue, the "Pull" didn't seem to be working. Found a Fix though.

1) Modify your pull line to

```<code>pullstat, err = cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
</code>```

and add

```<code>io.Copy(os.StdOut,pullstat)
</code>```

after the ImagePull

I haven't tried doing an

```<code>io.Copy(nil,pullstat)
</code>```

but that's on my list of things to try next.

Body:
I am trying to use Docker's tutorial in recreating a docker run. Here is the following code from online tutorial

 package main

 import (
 "io"
 "os"

"github.com/docker/docker/client"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"golang.org/x/net/context"
 )

 func main() {
ctx := context.Background()
cli, err := client.NewEnvClient()
if err != nil {
    panic(err)
}

_, err = cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})
if err != nil {
    panic(err)
}

resp, err := cli.ContainerCreate(ctx, &container.Config{
    Image: "alpine",
    Cmd:   []string{"echo", "hello world"},
}, nil, nil, "")
if err != nil {
    panic(err)
}

if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{});     err != nil {
    panic(err)
}

if _, err = cli.ContainerWait(ctx, resp.ID); err != nil {
    panic(err)
}

out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
if err != nil {
    panic(err)
}

io.Copy(os.Stdout, out)
}

The problem I see with this is, if 'alpine' docker, is not available locally, it doesn't pull the latest and ends up throwing an error.
  e.g
        XXXXX$ go run go_docker.go
        panic: Error: No such image: alpine

    goroutine 1 [running]:
      panic(0x27ffa0, 0xc4202afa50)
    /usr/local/go/src/runtime/panic.go:500 +0x1a1
    main.main()
    /Users/rvenkatesh/go_coding/raghu_test_code/go_docker.go:30 +0x592
    exit status 2

But when I run the commandline equivalent, I see

    XXXX$ docker run alpine echo hello world
    Unable to find image 'alpine:latest' locally
    latest: Pulling from library/alpine
    627beaf3eaaf: Pull complete

        Digest:sha256:58e1a1bb75db1b5a24a462dd5e2915277ea06438c3f105138f97eb53149673c4
    Status: Downloaded newer image for alpine:latest
    hello world

I tried looking through Go client, do I need to tweak anything with ImagePull function? Any help here would be appreciated!

Here is the link to the docs https://docs.docker.com/engine/api/getting-started/

Update: I had tested the same tutorial for python version, and it worked just fine. I wonder if the Golang page needs update.

Body:
Was having the same issue, the "Pull" didn't seem to be working. Found a Fix though.

1) Modify your pull line to

pullstat, err = cli.ImagePull(ctx, "alpine", types.ImagePullOptions{})

and add

io.Copy(os.StdOut,pullstat)

after the ImagePull

I haven't tried doing an

io.Copy(nil,pullstat)

but that's on my list of things to try next.


问:
Optimize output when using counter?
I'm trying to optimize my output after I counted all the signs in a file. For example I want to print only signs which appear more often than once.

```<code>from codecs import open as co
from collections import Counter

with co('test.txt', 'r', 'utf-8', 'strict') as fp:
  text = fp.read()

for char, count in Counter(text).most_common():
  if not char.isspace():

    print(char, count)
</code>```

My Output so far:

c 102
a 1
b 1
```

I'm happy for any tips or solution, especially if it is easy to folow.

答:
The simple solution would be:</p>

```<code>for char, count in Counter(text).most_common():
  if not char.isspace() and count > 1:
     print(char, count)
</code>```

Title: Optimize output when using counter?

Body:
I'm trying to optimize my output after I counted all the signs in a file. For example I want to print only signs which appear more often than once.

from codecs import open as co
from collections import Counter

with co('test.txt', 'r', 'utf-8', 'strict') as fp:
  text = fp.read()

for char, count in Counter(text).most_common():
  if not char.isspace():

    print(char, count)

My Output so far:

c 102
a 1
b 1

I'm happy for any tips or solution, especially if it is easy to folow.

Body:
The simple solution would be:

for char, count in Counter(text).most_common():
  if not char.isspace() and count > 1:
     print(char, count)


问:
MS Access VBA Stored Procedure return value to text box
I'm having one of those moments and have forgot how to return a value from a SQL SP to a textbox?

I'm calling a SQL SP from MS Access 2013 using the below code and this returns the value to a listbox no problem - what property do I use to return the SP value to a text box?

Working Code:

```<code>With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSKUSearch
     Set Me.List38.Recordset = .OpenRecordset
End With
</code>```

Non-working code - what should be where the ? are:

```<code>With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Set Me.Text7.?????? = .OpenRecordset
End With
</code>```

Thanks

答:
Final working code:</p>

```<code>With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Me.Text7.Value = .OpenRecordset.Fields(0).Value
End With
</code>```

Body:
I'm having one of those moments and have forgot how to return a value from a SQL SP to a textbox?

I'm calling a SQL SP from MS Access 2013 using the below code and this returns the value to a listbox no problem - what property do I use to return the SP value to a text box?

Working Code:

With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSKUSearch
     Set Me.List38.Recordset = .OpenRecordset
End With

Non-working code - what should be where the ? are:

With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Set Me.Text7.?????? = .OpenRecordset
End With

Thanks

Body:
Final working code:

With CurrentDb.QueryDefs("qMasterPass")
     .SQL = "exec SKULookup " & txtSearch
     Me.Text7.Value = .OpenRecordset.Fields(0).Value
End With


问:
hidesBarsOnSwipe does not show navigationBar when scrolling up to the top slowly
I am trying to use a command in iOS8 to enable behaviour to hide navigation bar when scrolling.

Here is the code

```<code>-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.hidesBarsOnSwipe = YES;
}
</code>```

And when scrolling up quick, there is no problem because the navigation bar will be dragged down and visible automatically. But in the even if I scroll up to the top slowly. The navigation bar does not show.

I tried to correct this behavior by using scrollView delegate. But that does not work well also. Because the animation does not look nice.

```<code>-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{

if(floor(NSFoundationVersionNumber) >= NSFoundationVersionNumber_iOS_8_0)
{
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset < 10)
    {
        self.navigationController.navigationBarHidden = NO;
    }
}

}
</code>```

Please help. I would like to do this as simple as possible. Thanks in advance

答:
I had a UIScrollView with the right constraints on the top, but still its behavior was weird.

I solved in this way:

```<code>-(void)scrollViewDidScroll: (UIScrollView*)scrollView
{
    float scrollViewHeight = scrollView.frame.size.height;
    float scrollContentSizeHeight = scrollView.contentSize.height;
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset < 0)
    {
        self.navigationController.hidesBarsOnSwipe = NO;
        [self.navigationController setNavigationBarHidden:NO animated: YES];
    }
    else
    {
        self.navigationController.hidesBarsOnSwipe = YES;
    }
}
</code>```

Body:
I am trying to use a command in iOS8 to enable behaviour to hide navigation bar when scrolling.

Here is the code

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.hidesBarsOnSwipe = YES;
}

And when scrolling up quick, there is no problem because the navigation bar will be dragged down and visible automatically. But in the even if I scroll up to the top slowly. The navigation bar does not show.

I tried to correct this behavior by using scrollView delegate. But that does not work well also. Because the animation does not look nice.

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{

if(floor(NSFoundationVersionNumber) >= NSFoundationVersionNumber_iOS_8_0)
{
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset < 10)
    {
        self.navigationController.navigationBarHidden = NO;
    }
}

}

Please help. I would like to do this as simple as possible. Thanks in advance

Body:
I had a UIScrollView with the right constraints on the top, but still its behavior was weird.

I solved in this way:

-(void)scrollViewDidScroll: (UIScrollView*)scrollView
{
    float scrollViewHeight = scrollView.frame.size.height;
    float scrollContentSizeHeight = scrollView.contentSize.height;
    float scrollOffset = scrollView.contentOffset.y;

    if (scrollOffset < 0)
    {
        self.navigationController.hidesBarsOnSwipe = NO;
        [self.navigationController setNavigationBarHidden:NO animated: YES];
    }
    else
    {
        self.navigationController.hidesBarsOnSwipe = YES;
    }
}


答:
Only float:right; could make it work.

Follow this fiddle link.

Title: Buttons won't go side by side

Body:
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

                        <button type="button" id="searchbuttonmobile" ></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">

                        </button>

CSS:

/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}


问:
Unable to Keep my config and controller in different files in angularJs
I have a config for my RouteProvider and a controller in a single Js file as shown below

```<code>    var empApp = angular.module('employee', ['ngRoute']);
empApp.config(function ($routeProvider) {
    debugger;
    $routeProvider.when('/', {
        templateUrl: '/ShowAll.html',
        controller: 'mainCtrlr1'
    }).when('/AddEmployee', {
        templateUrl: '/AddEmployee.html',

    }).when('/EditEmployee', {
        templateUrl: '/EditEmployee.html',

    }).when('/deleteEmployee', {
        templateUrl: '/deleteEmployee.html',

    });
})
.controller('mainCtrlr1', ['$scope', '$location', function ($scope, $location) {
    $location.path('/');
    alert('Hi');
}]);
</code>```

I want keep my config and Controller in two different files
1. Configs.js

```<code>var empApp = angular.module('employee', ['ngRoute']);
empApp.config(function ($routeProvider) {
    debugger;
    $routeProvider.when('/', {
        templateUrl: '/ShowAll.html',
        controller: 'mainCtrlr1'
    }).when('/AddEmployee', {
        templateUrl: '/AddEmployee.html',

    }).when('/EditEmployee', {
        templateUrl: '/EditEmployee.html',

    }).when('/deleteEmployee', {
        templateUrl: '/deleteEmployee.html',

    });
});
</code>```

And my controller in Controller1.js as given below.

```<code>var empApp=angular.module('employee', ['ngRoute']);
empApp.controller('mainCtrlr1', ['$scope', '$location', function ($scope, $location) {
    //$location.path('/');
    alert('Hi');
}]);
</code>```

Now i have given reference of these two files in my html as given below

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="Lib/angular.js"></script>
    <!--<script src="Scripts/Services.js"></script>-->

    <script src="Scripts/Controller1.js"></script>
    <script src="Scripts/conifgs.js"></script>
    <script src="Lib/angular-route.js"></script>

</head>
<body ng-app="employee">

    <div ng-view></div>

</body>
</html>
</code>```

And my ShowAll.html code is as shown below

```<code><div ng-controller="mainCtrlr1">
    <table>
        <thead>
            <th>Employee ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Age</th>
            <th>Telephone</th>
        </thead>
        <tbody ng-repeat="emp in GetAllEmployees()">
            <tr>
                <td>{{emp.EmployeeID}}</td>
                <td>{{emp.FirstName}}</td>
                <td>{{emp.LastName}}</td>
                <td>{{emp.Email}}</td>
                <td>{{emp.Age}}</td>
                <td>{{emp.telephone}}</td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

now when i execute with above changes, my controller is failing to register. However when my controller and config is in same js file, my application works fine.

Any suggestions are much appreciated :)

答:
This code snippet angular.module('employee', ['ngRoute']) creates a new angular module.

Since you have this snippet twice (one in each new file), you will create two different angular modules.

Solution:

Keep the var empApp = angular.module('employee', ['ngRoute']); in the first js file that is imported in your html file.

In the second js file, replace the first line with var empApp = angular.module('employee');

To further clarify, angular.module('employee', ['ngRoute']) will create a new module and therefore needs to be executed first. angular.module('employee') will get a reference to the module that was already created and hence should be used in all subsequent js files that need a reference to the module.

Body:
I have a config for my RouteProvider and a controller in a single Js file as shown below

    var empApp = angular.module('employee', ['ngRoute']);
empApp.config(function ($routeProvider) {
    debugger;
    $routeProvider.when('/', {
        templateUrl: '/ShowAll.html',
        controller: 'mainCtrlr1'
    }).when('/AddEmployee', {
        templateUrl: '/AddEmployee.html',

    }).when('/EditEmployee', {
        templateUrl: '/EditEmployee.html',

    }).when('/deleteEmployee', {
        templateUrl: '/deleteEmployee.html',

    });
})
.controller('mainCtrlr1', ['$scope', '$location', function ($scope, $location) {
    $location.path('/');
    alert('Hi');
}]);

I want keep my config and Controller in two different files
1. Configs.js

var empApp = angular.module('employee', ['ngRoute']);
empApp.config(function ($routeProvider) {
    debugger;
    $routeProvider.when('/', {
        templateUrl: '/ShowAll.html',
        controller: 'mainCtrlr1'
    }).when('/AddEmployee', {
        templateUrl: '/AddEmployee.html',

    }).when('/EditEmployee', {
        templateUrl: '/EditEmployee.html',

    }).when('/deleteEmployee', {
        templateUrl: '/deleteEmployee.html',

    });
});

And my controller in Controller1.js as given below.

var empApp=angular.module('employee', ['ngRoute']);
empApp.controller('mainCtrlr1', ['$scope', '$location', function ($scope, $location) {
    //$location.path('/');
    alert('Hi');
}]);

Now i have given reference of these two files in my html as given below

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

And my ShowAll.html code is as shown below

            Employee ID
            First Name
            Last Name
            Email
            Age
            Telephone

                {{emp.EmployeeID}}
                {{emp.FirstName}}
                {{emp.LastName}}
                {{emp.Email}}
                {{emp.Age}}
                {{emp.telephone}}

now when i execute with above changes, my controller is failing to register. However when my controller and config is in same js file, my application works fine.

Any suggestions are much appreciated :)


问:
Automatically add build phases in Cordova based Xcode project
I have a Cordova based iOS project in which I need to add a custom script to the build phases. I have one set up and it works fine, however I need to be able to add the build phase automatically somehow, as I need the project to be able to install and build automatically on a CI server, without having to manually add the phase in Xcode.

To clarify, when cordova platform add ios is run the project is created without build phases, I need to add a build phase in programmatically, before (or during) cordova build ios.

I can add custom build settings in the .xcconfig file, is there somewhere I can define build phases? I see that the build phase is present in my .pbxproj file, however this is automatically generated and contains some random IDs so I am not sure its something I can just parse and insert arbitrary stuff into?

答: The solution I have found is to use an Xcode project parser, there are a few around. I have used cordova-node-xcode. I couldn't find any API documentation but the unit tests were helpful in figuring out what I needed. I needed to use the proj.addBuildPhase method, an example of using this to add a run script can be seen here: https://github.com/apache/cordova-node-xcode/blob/master/test/addBuildPhase.js#L113


问:
Locking a MySQL database so only one person at once can run a query?
I am having a few issues when people are trying to access a MySQL database and they are trying to update tables with the same information.

I have a webpage written using PHP. In this webpage is a query to check if certain data has been entered into the database. If the data hasn't, then i proceed to insert it. The trouble is that if two people try at the same time, the check might say the data has not been entered yet but when the insert takes place it has been by the other person.

What is the best way to handle this scenario? Can i lock the database to only process my queries first then anothers?

答: Read up on database transactions. That's probably a better way to handle what you need than running LOCK TABLES.</p>

OwnerDisplayName: Gary Willoughby

LastEditorDisplayName: Jason S

OwnerDisplayName: Jason S


问:
Is Window Workflow Foundation AOP?
I am new in Window Workflow Foundation and AOP. I found that they are quite similar. So I am wondering that WWF is AOP... I know the concept of WWF is different from AOP. However, I think they are going to achieve the similar idea.

If this is a silly question, I am so sorry. Thanks!

Alex

答:
I think no - those ideas are different.

AOP idea is to develop cleaner code, better encapsulate it, make systems less coupled and easier to maintain. It is an idea targeted mainly on developers.

WWF idea is to assemble enterprise applications from pre-built blocks. Targeted somewhere in between developers and business analytics. With WWF you can possibly re-use some modules in new contexts, but generally WWF tries to resemble concepts of business process modeling.

Of course, you can imagine a lot of situations where you can use WWF as the tool to achieve better encapsulation and loose coupling or otherwise - to use AOP to re-use modules and organise it in a workflow. But the intersection of their general ideas is rather small.

Title: Is Window Workflow Foundation AOP?


问:
How to view syslog in ubuntu?
Follow up from this question, LogBack Syslog not working java

I use command below to view syslog in ubuntu 16.04 but get below result. Is it the correct way to view?

user@xxx:~$ tail -f /var/log/syslog Jun  6 23:08:50 xxx systemd[1]:
Starting Hostname Service... Jun  6 23:08:50 xxx dbus[889]: [system]
Successfully activated service 'org.freedesktop.hostname1' Jun  6
23:08:50 xxx systemd[1]: Started Hostname Service. Jun  6 23:09:41 xxx
gnome-session[2645]: (nautilus:2860): Gtk-WARNING **: Attempting to
read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:41 xxx org.gtk.vfs.Daemon[2508]:
(gvfsd-recent:15282): Gtk-WARNING **: Attempting to read the recently
used resources file at '/home/xxx/.local/share/recently-used.xbel',
but the parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:41 xxx gnome-session[2645]: (zeitgeist-datahub:3069):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/seng/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(nautilus:2860): Gtk-WARNING **: Attempting to read the recently used
resources file at '/home/xxx/.local/share/recently-used.xbel', but the
parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:49 xxx org.gtk.vfs.Daemon[2508]: (gvfsd-recent:15282):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(zeitgeist-datahub:3069): Gtk-WARNING **: Attempting to read the
recently used resources file at
'/home/seng/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:17:01 xxx CRON[18877]: (root) CMD (   cd
/ && run-parts --report /etc/cron.hourly)
```

<p>Try <code>cat /var/log/syslog</code> (small part of the output)</p>

```Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$
```

<p>Try  <code>cat /var/log/syslog | tail -f</code></p>

```user@xxx:/$ cat /var/log/syslog | tail -f
Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$
```

答:
Looks like you are trying to read syslog from Java, not from an interactive terminal. The text looks like a correct output, but with smashed formatting.

tail -f is good for interactive terminals.

Try cat /var/log/syslog, or just open /var/log/syslog as a file (if your process has enough permissions).

Title: How to view syslog in ubuntu?

Body:
Follow up from this question, LogBack Syslog not working java

I use command below to view syslog in ubuntu 16.04 but get below result. Is it the correct way to view?

user@xxx:~$ tail -f /var/log/syslog Jun  6 23:08:50 xxx systemd[1]:
Starting Hostname Service... Jun  6 23:08:50 xxx dbus[889]: [system]
Successfully activated service 'org.freedesktop.hostname1' Jun  6
23:08:50 xxx systemd[1]: Started Hostname Service. Jun  6 23:09:41 xxx
gnome-session[2645]: (nautilus:2860): Gtk-WARNING **: Attempting to
read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:41 xxx org.gtk.vfs.Daemon[2508]:
(gvfsd-recent:15282): Gtk-WARNING **: Attempting to read the recently
used resources file at '/home/xxx/.local/share/recently-used.xbel',
but the parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:41 xxx gnome-session[2645]: (zeitgeist-datahub:3069):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/seng/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(nautilus:2860): Gtk-WARNING **: Attempting to read the recently used
resources file at '/home/xxx/.local/share/recently-used.xbel', but the
parser failed: Failed to open file
'/home/xxx/.local/share/recently-used.xbel': Permission denied. Jun  6
23:09:49 xxx org.gtk.vfs.Daemon[2508]: (gvfsd-recent:15282):
Gtk-WARNING **: Attempting to read the recently used resources file at
'/home/xxx/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:09:49 xxx gnome-session[2645]:
(zeitgeist-datahub:3069): Gtk-WARNING **: Attempting to read the
recently used resources file at
'/home/seng/.local/share/recently-used.xbel', but the parser failed:
Failed to open file '/home/xxx/.local/share/recently-used.xbel':
Permission denied. Jun  6 23:17:01 xxx CRON[18877]: (root) CMD (   cd
/ && run-parts --report /etc/cron.hourly)

Try cat /var/log/syslog (small part of the output)

Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$

Try  cat /var/log/syslog | tail -f

user@xxx:/$ cat /var/log/syslog | tail -f
Jun  6 23:37:26 xxx whoopsie[1040]: [23:37:26] online
Jun  6 23:37:26 xxx avahi-daemon[1023]: Registering new address record for 2001:e68:4424:afab:c31f:c843:2351:c58 on wlp6s0.*.
Jun  6 23:37:28 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 4340ms.
Jun  6 23:37:32 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 9080ms.
Jun  6 23:37:41 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 17540ms.
Jun  6 23:37:59 xxx dhclient[19397]: XMT: Solicit on wlp6s0, interval 34190ms.
Jun  6 23:38:09 xxx NetworkManager[1013]: <warn>  [1496763489.9447] dhcp6 (wlp6s0): request timed out
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9448] dhcp6 (wlp6s0): state changed unknown -> timeout
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): canceled DHCP transaction, DHCP client pid 19397
Jun  6 23:38:09 xxx NetworkManager[1013]: <info>  [1496763489.9456] dhcp6 (wlp6s0): state changed timeout -> done
user@xxx:/$


问:
Search nearby hospital via google map intent (Android)
I need to search nearby child hospital and find the root from button click using intent,

```<code>Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("http://maps.google.com/maps?&saddr="
                                + x
                                + ","
                                + y
                                + "&daddr=nearby child hospitals"

                                ));
                        startActivity(intent);
</code>```

x,y as current lat and long.

It will show the hospitals are not in my current location(Shows different country hospitals)
Then, I click back button, then click Get Directions button means (From text box contains my source lat and long, Destinations text box contains nearby child hospitals), it shows my nearer child hospitals.

Is there any way do to this in first (i.e., intent call)?

答:
you can use this code, intent open a map and automatic search hospital near me</p>

```<code>String uri = "geo:"+ x + "," + y +"?q=hospitals+near+me";
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));
</code>```

Body:
I need to search nearby child hospital and find the root from button click using intent,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("http://maps.google.com/maps?&saddr="
                                + x
                                + ","
                                + y
                                + "&daddr=nearby child hospitals"

                                ));
                        startActivity(intent);

x,y as current lat and long.

It will show the hospitals are not in my current location(Shows different country hospitals)
Then, I click back button, then click Get Directions button means (From text box contains my source lat and long, Destinations text box contains nearby child hospitals), it shows my nearer child hospitals.

Is there any way do to this in first (i.e., intent call)?

Body:
you can use this code, intent open a map and automatic search hospital near me

String uri = "geo:"+ x + "," + y +"?q=hospitals+near+me";
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));


问:
jQuery - Hide DIV which has a span element with certain text inside
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target

I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div

```<code><div id="rn_FieldDisplay_155" class="rn_FieldDisplay rn_Output">
   <span class="rn_DataLabel">Telephone Call </span>
   <div class="rn_DataValue">No</div>
</div>
</code>```

I have tried the following to no avail

```<code><script>
$(document).ready(function() {
  $(".rn_FieldDisplay > span:contains('Telephone Call')").hide ();
});
</script>
</code>```

答:
If your code is hiding the span, but not the parent div, you can target the div to be hidden using mostly the same code you already wrote.</p>

```<code><script>
$(document).ready(function() {
    $(".rn_FieldDisplay > span:contains('Telephone Call')").parent().hide();
});
</script>
</code>```

Body:
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target

I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div

   Telephone Call

No

I have tried the following to no avail

Body:
If your code is hiding the span, but not the parent div, you can target the div to be hidden using mostly the same code you already wrote.

<script>
$(document).ready(function() {
    $(".rn_FieldDisplay > span:contains('Telephone Call')").parent().hide();
});
</script>


问:
docker-compose not setting environment variables with flask
running flask container and when I try to read environment variables, they are not set by docker compose. I am Using docker-compose file version 2

```<code>compose file:
    services:
        test
             build: ./test
             image: test:1.0
             container_name: test_flask
             ports:
                  - "80:80"
             env_file: .env
             environment:
                  - COUCHDB=http://192.168.99.100:5984
             depends_on:
                  - couchdb
</code>```

I have tried both with env_file and environment directives ?
I have also tried to put the values in double quotes, single quotes, no quotes, none worked.
the .env file contains:

```<code>  COUCHDB="http://192.168.99.100:5984", also tried without quotes
</code>```

then I read the variables from python code like this:

```<code>COUCH_SERVER = os.environ["COUCHDB"]
</code>```

I also tried
    os.environ.get('COUCHDB')

none worked.

The server is started from Dockerfile as this:

CMD service apache2 restart

I start the container with the command:

docker-compose up test

I am using Docker for Windows toolbox with version:

```<code>Client:
 Version:      1.13.1
 API version:  1.26
 Go version:   go1.7.5
 Git commit:   092cba3
 Built:        Wed Feb  8 08:47:51 2017
 OS/Arch:      windows/amd64

Server:
 Version:      17.04.0-ce
 API version:  1.28 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   4845c56
 Built:        Wed Apr  5 18:45:47 2017
 OS/Arch:      linux/amd64
 Experimental: false
</code>```

Thank you for your help

答:
I leave you an example of how to do to get the environment variables from the application.

docker-compose.yml

```<code>version: '2'

services:
  app:
      image: python:2.7
      environment:
        - BAR=FOO
      volumes:
        - ./app.py:/app.py
      command: python app.py
</code>```

app.py

```<code>import os

print(os.environ["BAR"])
</code>```

Body:
running flask container and when I try to read environment variables, they are not set by docker compose. I am Using docker-compose file version 2

compose file:
    services:
        test
             build: ./test
             image: test:1.0
             container_name: test_flask
             ports:
                  - "80:80"
             env_file: .env
             environment:
                  - COUCHDB=http://192.168.99.100:5984
             depends_on:
                  - couchdb

I have tried both with env_file and environment directives ?
I have also tried to put the values in double quotes, single quotes, no quotes, none worked.
the .env file contains:

  COUCHDB="http://192.168.99.100:5984", also tried without quotes

then I read the variables from python code like this:

COUCH_SERVER = os.environ["COUCHDB"]

I also tried
    os.environ.get('COUCHDB')

none worked.

The server is started from Dockerfile as this:

CMD service apache2 restart

I start the container with the command:

docker-compose up test

I am using Docker for Windows toolbox with version:

Client:
 Version:      1.13.1
 API version:  1.26
 Go version:   go1.7.5
 Git commit:   092cba3
 Built:        Wed Feb  8 08:47:51 2017
 OS/Arch:      windows/amd64

Server:
 Version:      17.04.0-ce
 API version:  1.28 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   4845c56
 Built:        Wed Apr  5 18:45:47 2017
 OS/Arch:      linux/amd64
 Experimental: false

Thank you for your help

Body:
I leave you an example of how to do to get the environment variables from the application.

docker-compose.yml

version: '2'

services:
  app:
      image: python:2.7
      environment:
        - BAR=FOO
      volumes:
        - ./app.py:/app.py
      command: python app.py

app.py

import os

print(os.environ["BAR"])


问:
Reading a table from database
I having a problem to run below Java code. I couldn't find the DB.java class.

ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
    System.out.print(rs.getString("pid"));
    System.out.print(rs.getString("name"));
    System.out.print(rs.getString("price"));
    System.out.print(rs.getString("ava_qty"));
}
```

I'm using Glassfish server. Can someone help me to write the DB.java class?

答:
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:

https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm

Example code for future reference:

```<code>import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      } catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      System.out.println("JDBC Class found");
      int no_of_rows = 0;

      try {
         Connection con = DriverManager.getConnection (
            "jdbc:derby://localhost:1527/testDb","username", "password");
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
         while (rs.next()) {
            no_of_rows++;
         }
         System.out.println("There are "+ no_of_rows + " record in the table");
      } catch(SQLException e){
         System.out.println("SQL exception occured" + e);
      }
   }
}
</code>```

Title: Reading a table from database

Body:
I having a problem to run below Java code. I couldn't find the DB.java class.

ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
    System.out.print(rs.getString("pid"));
    System.out.print(rs.getString("name"));
    System.out.print(rs.getString("price"));
    System.out.print(rs.getString("ava_qty"));
}

I'm using Glassfish server. Can someone help me to write the DB.java class?

Body:
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:

https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm

Example code for future reference:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) {
      try {
         Class.forName("org.apache.derby.jdbc.ClientDriver");
      } catch(ClassNotFoundException e) {
         System.out.println("Class not found "+ e);
      }
      System.out.println("JDBC Class found");
      int no_of_rows = 0;

      try {
         Connection con = DriverManager.getConnection (
            "jdbc:derby://localhost:1527/testDb","username", "password");
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
         while (rs.next()) {
            no_of_rows++;
         }
         System.out.println("There are "+ no_of_rows + " record in the table");
      } catch(SQLException e){
         System.out.println("SQL exception occured" + e);
      }
   }
}