问:
Trying to debug mystery sinewave using AKMIDISampler in Audiokit
Following on from a previous issue, I stopped using AKSampler to move to the functionality used in AKMIDISampler. Got my loops working again (with help from this Google Groups post), but I have a sinewave playing (which happens when the MIDISampler can't find it's source file).

It's not an issue with the source files I'm targeting because they all play OK. The sinewave is coming from somewhere else in the process, but I can't see where...

Please help 8•)

(Simplified and edited code to show only relevant details - please get in touch for any clarification)

```<code>var MIDISamplePlayer = AKMIDISampler()
var sequencer: AKSequencer?
var mixer: AKMixer!

// initialise the mixer
mixer = AKMixer()

do  {
        audiofile = try AKAudioFile(readFileName: SoundFilename as! String,
        baseDir: .resources)
    } catch let error as NSError {
        print("There's an error: \(error)")
    }

do {
       try sprite.MIDISamplePlayer.loadAudioFile(audiofile)
    } catch let error as NSError {
       print("There's an error: \(error)")
    }

sprite.tracker = AKAmplitudeTracker(sprite.MIDISamplePlayer)
mixer.connect(to:sprite.tracker, bus: mixer.nextInput.bus)

sequencer = AKSequencer(filename: POPmidi)
sequencer?.enableLooping()

let midi = AKMIDI()

for i in 0..<popCount {
    gPOPs[i].MIDISamplePlayer.enableMIDI(midi.client, name: "MIDISample_\(i)")
    mixer.connect(gPOPs[i].MIDISamplePlayer)
    sequencer!.tracks[i].setMIDIOutput(gPOPs[i].MIDISamplePlayer.midiIn)
}

AudioKit.start()
sequencer!.play()
</code>```

答:
This is a bit of a guess, but its a very common issue to have your audio files in a location that the sampler likes.  Try putting the audiofiles in a Samples/ folder like in these examples:

http://audiokit.io/playgrounds/Playback/Sequencer/
http://audiokit.io/playgrounds/Playback/Sampler/

or I think a Sounds or "Sampler Instruments" folders work as well as in the Sampler Demo:

https://github.com/AudioKit/AudioKit/tree/master/Examples/iOS/SamplerDemo/SamplerDemo/Sounds

Body:
Following on from a previous issue, I stopped using AKSampler to move to the functionality used in AKMIDISampler. Got my loops working again (with help from this Google Groups post), but I have a sinewave playing (which happens when the MIDISampler can't find it's source file).

It's not an issue with the source files I'm targeting because they all play OK. The sinewave is coming from somewhere else in the process, but I can't see where...

Please help 8•)

(Simplified and edited code to show only relevant details - please get in touch for any clarification)

var MIDISamplePlayer = AKMIDISampler()
var sequencer: AKSequencer?
var mixer: AKMixer!

// initialise the mixer
mixer = AKMixer()

do  {
        audiofile = try AKAudioFile(readFileName: SoundFilename as! String,
        baseDir: .resources)
    } catch let error as NSError {
        print("There's an error: \(error)")
    }

do {
       try sprite.MIDISamplePlayer.loadAudioFile(audiofile)
    } catch let error as NSError {
       print("There's an error: \(error)")
    }

sprite.tracker = AKAmplitudeTracker(sprite.MIDISamplePlayer)
mixer.connect(to:sprite.tracker, bus: mixer.nextInput.bus)

sequencer = AKSequencer(filename: POPmidi)
sequencer?.enableLooping()

let midi = AKMIDI()

for i in 0..<popCount {
    gPOPs[i].MIDISamplePlayer.enableMIDI(midi.client, name: "MIDISample_\(i)")
    mixer.connect(gPOPs[i].MIDISamplePlayer)
    sequencer!.tracks[i].setMIDIOutput(gPOPs[i].MIDISamplePlayer.midiIn)
}

AudioKit.start()
sequencer!.play()


来源: stackexchange

问:
What is the meaning of ":"?
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like

```<code>for(String x : model)
</code>```

Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?

答: In this context, : literally means in.

ContentLicense: CC BY-SA 3.0

Title: What is the meaning of ":"?

Body:
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like

for(String x : model)

Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?

Body: In this context, : literally means in.


答: This is the syntax of the enhanced for loop. It marely means that you're iterating over all the elements in model, where in each iteration the String x is assigned with the current element so you can use in the loop's body.

Title: What is the meaning of ":"?


问:
How to validate the number of arguments (mandatory and optional) in a shell script?
I am having trouble validating my script arguments. I am trying to achieve 5 mandatory arguments and 2 optional arguments to my script. Here is what I have tried so far.

```<code>#!/bin/sh

if [ $# -lt 5 ] || [ $# -gt 7 ]
then
  echo "Please supply 5 or 6 or 7 parameters. Aborting."
  exit 1
fi

echo MP1 = "$1"
echo MP2 = "$2"
echo MP3 = "$3"
echo MP4 = "$4"
echo MP5 = "$5"

while getopts c:a: optionalargs
do
        case $optionalargs in
          c)copt=$OPTARG;;
          a)aopt=$OPTARG;;
          *)echo "Invalid arg";;
        esac
done

if [ ! -z "$copt" ]
then
    export CHAR_SET=$copt
fi

if [ ! -z "$aopt" ]
then
    export ADDITIONAL_FLAGS=$aopt
fi

shift $((OPTIND -1))

echo OP_C = "${CHAR_SET}"
echo OP_A = "${ADDITIONAL_FLAGS}"
</code>```

The problem is validating the total number of arguments to this script as I can have a total of 5 or 7 arguments. Providing -a additional -c character is treated as 9 arguments.

```<code>./a.sh 1 2 3 4 5 -a additional -c character
Please supply 5 or 6 or 7 parameters. Aborting.
</code>```

I am open to designs with no - as long as I am able to have both mandatory and optional parameters.

How to get this properly validated?

答:
Every space-separated string will be interpreted as a new argument by the shell. Are you allowed to have the -a flag or -c arguments without parameters? Assuming those need to have something following them, you actually need to allow 5 or 7 or 9 arguments. Getopts is separate from the initial shell argument parsing.

Other than that, the script looks good. For quality check, I'd recommend Shellcheck

Body:
I am having trouble validating my script arguments. I am trying to achieve 5 mandatory arguments and 2 optional arguments to my script. Here is what I have tried so far.

#!/bin/sh

if [ $# -lt 5 ] || [ $# -gt 7 ]
then
  echo "Please supply 5 or 6 or 7 parameters. Aborting."
  exit 1
fi

echo MP1 = "$1"
echo MP2 = "$2"
echo MP3 = "$3"
echo MP4 = "$4"
echo MP5 = "$5"

while getopts c:a: optionalargs
do
        case $optionalargs in
          c)copt=$OPTARG;;
          a)aopt=$OPTARG;;
          *)echo "Invalid arg";;
        esac
done

if [ ! -z "$copt" ]
then
    export CHAR_SET=$copt
fi

if [ ! -z "$aopt" ]
then
    export ADDITIONAL_FLAGS=$aopt
fi

shift $((OPTIND -1))

echo OP_C = "${CHAR_SET}"
echo OP_A = "${ADDITIONAL_FLAGS}"

The problem is validating the total number of arguments to this script as I can have a total of 5 or 7 arguments. Providing -a additional -c character is treated as 9 arguments.

./a.sh 1 2 3 4 5 -a additional -c character
Please supply 5 or 6 or 7 parameters. Aborting.

I am open to designs with no - as long as I am able to have both mandatory and optional parameters.

How to get this properly validated?


问:
Select Customer ID who hasnt purchased product X
I have a table of customer IDs and Products Purchased.  A customer ID can purchase multiple products over time.

customerID, productID

In BigQuery I need to find the CustomerID for those who have not purchased product A.

I've been going around in circles trying to do self joins, inner joins, but I'm clueless.

Any help appreciated.

答:
```<code>select customerID
from your_table
group by customerID
having sum(case when productID = 'A' then 1 else 0 end) = 0
</code>```

and to check if it only contains a name

```<code>sum(case when productID contains 'XYZ' then 1 else 0 end) = 0
</code>```

Body:
select customerID
from your_table
group by customerID
having sum(case when productID = 'A' then 1 else 0 end) = 0

and to check if it only contains a name

sum(case when productID contains 'XYZ' then 1 else 0 end) = 0


问:
Custom logging handler in Redhar JBoss EAP / BPM Suite 6.4.0
I would like to provide custom logging handler implementation for Redhat JBoss EAP / BPM Suite 6.4.0. I have my own customized logging mechanism based on log4j and the requirement is to publish all log messages to kafka system instead of file system.

Please suggest.

Thanks.
Aniket

答:
If you want to send all the logging information, you should develop a custom handler (java.util.logging.Handler) and add it to root logger (EAP configuration).

If you want to send more BPM specific information you should implement a Process Event Listener: look a this
example implementation.
Then you have to register it the event listener in the kie-deployment-descriptor.xml.


问:
Distributed Erlang: multicall exceeds requested timeout
We use distributed erlang cluster and now I tests it in case of net splits.

To get information from all nodes of the cluster I use gen_server:multicall/4 with defined timeout. What I need is to get information from available nodes as soon as possible. So timeout is not too big (about 3000 ms).
Here call example:

```<code>Timeout = 3000
Nodes = AllConfiguredNodes
gen_server:multi_call(Nodes, broker, get_score, Timeout)
</code>```

I expect that this call returns result in Timeout ms. But in case of net split it does not. It waits approx. 8 seconds.

What I found that multi_call request is halted for additional 5 seconds in call erlang:monitor(process, {Name, Node}) before sending request.

I really do not care that some node do not reply or busy or not available, I can use any other but with this halting I forced to wait until Erlang VM
try to establish new connection to dead/not available node.

The question is: do you know solution that can prevent this halting? Or may be another RPC that suitable for my situation.

答:
I'm not sure if I totally understand the problem you are trying to solve, but if it is to get all the answers that can be retrieved in X amount of time and ignore the rest, you might try a combination of async_call and nb_yield.

Maybe something like

```<code>somefun() ->
    SmallTimeMs = 50,
    Nodes = AllConfiguredNodes,
    Promises = [rpc:async_call(N, some_mod, some_fun, ArgList) || N <- Nodes],
    get_results([], Promises, SmallTimeMs).

get_results(Results, _Promises, _SmallTimeMs) when length(Results) > 1 ->   % Replace 1 with whatever is the minimum acceptable number of results
    lists:flatten(Results);
get_results(Results, Promises, SmallTimeMs) ->
    Rs = get_promises(Promises, SmallTimeMs)
    get_results([Results|Rs], Promises, SmallTimeMs)).

get_promise(Promises, WaitMs) ->
    [rpc:nb_yield(Key, WaitMs) || Key <- Promises].
</code>```

See: http://erlang.org/doc/man/rpc.html#async_call-4 for more details.

Body:
We use distributed erlang cluster and now I tests it in case of net splits.

To get information from all nodes of the cluster I use gen_server:multicall/4 with defined timeout. What I need is to get information from available nodes as soon as possible. So timeout is not too big (about 3000 ms).
Here call example:

Timeout = 3000
Nodes = AllConfiguredNodes
gen_server:multi_call(Nodes, broker, get_score, Timeout)

I expect that this call returns result in Timeout ms. But in case of net split it does not. It waits approx. 8 seconds.

What I found that multi_call request is halted for additional 5 seconds in call erlang:monitor(process, {Name, Node}) before sending request.

I really do not care that some node do not reply or busy or not available, I can use any other but with this halting I forced to wait until Erlang VM
try to establish new connection to dead/not available node.

The question is: do you know solution that can prevent this halting? Or may be another RPC that suitable for my situation.

Body:
I'm not sure if I totally understand the problem you are trying to solve, but if it is to get all the answers that can be retrieved in X amount of time and ignore the rest, you might try a combination of async_call and nb_yield.

Maybe something like

somefun() ->
    SmallTimeMs = 50,
    Nodes = AllConfiguredNodes,
    Promises = [rpc:async_call(N, some_mod, some_fun, ArgList) || N <- Nodes],
    get_results([], Promises, SmallTimeMs).

get_results(Results, _Promises, _SmallTimeMs) when length(Results) > 1 ->   % Replace 1 with whatever is the minimum acceptable number of results
    lists:flatten(Results);
get_results(Results, Promises, SmallTimeMs) ->
    Rs = get_promises(Promises, SmallTimeMs)
    get_results([Results|Rs], Promises, SmallTimeMs)).

get_promise(Promises, WaitMs) ->
    [rpc:nb_yield(Key, WaitMs) || Key <- Promises].

See: http://erlang.org/doc/man/rpc.html#async_call-4 for more details.


问:
Why am I getting this bit-wise operation error when using a custom QFlags implementation?
I created my own custom QFlags enumeration...

```<code>class A
{
  ...

  enum class PrimitiveTypeFlag : unsigned int {
    Unknown = 0x0,
    Bool = 0x1,
    Float = 0x2,
    Double = 0x4,
    Int8 = 0x8,
    UInt8 = 0x10,
    Int16 = 0x20,
    UInt16 = 0x40,
    Int32 = 0x80,
    UInt32 = 0x100,
    Int64 = 0x200,
    UInt64 = 0x400,
    StatsDataArray = 0x800,
    NeighborList = 0x1000,
    StringArray = 0x2000,
    NumericalPrimitives = 0x07FE,
    Any = 0x3FFF
  };
  Q_DECLARE_FLAGS(PrimitiveTypeFlags, PrimitiveTypeFlag)
  ...
  ...
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::PrimitiveTypeFlags)
</code>```

When I instantiate an instance of PrimitiveTypeFlags, all flags are turned on.

```<code>A::PrimitiveTypeFlags pFlags;
pFlags.setFlag(A::PrimitiveTypeFlag::StringArray, false);
</code>```

When I execute the block of code above to turn off the StringArray flag, I get this error:

```<code>invalid argument type 'A::PrimitiveTypeFlag' to unary expression.
</code>```

If I simply execute ~A::PrimitiveTypeFlag::StringArray, I also get the same error.

Why do I get this error, and how do I fix it?

Thanks in advance.

答:
enum classes are meant to be used as pure enums, which makes them safer to use by forbidding implicit conversions to their underlying type. This is hitting you here, because the QT macros expect to be able to perform bit operations on the values passed in.

You should be able to fix this by using pre-C++11 enum declarations:

```<code>class A
{
  ...

  enum PrimitiveTypeFlag : unsigned int {
    Unknown = 0x0,
    Bool = 0x1,
    Float = 0x2,
    Double = 0x4,
    Int8 = 0x8,
    UInt8 = 0x10,
    Int16 = 0x20,
    UInt16 = 0x40,
    Int32 = 0x80,
    UInt32 = 0x100,
    Int64 = 0x200,
    UInt64 = 0x400,
    StatsDataArray = 0x800,
    NeighborList = 0x1000,
    StringArray = 0x2000,
    NumericalPrimitives = 0x07FE,
    Any = 0x3FFF
  };
  Q_DECLARE_FLAGS(PrimitiveTypeFlags, PrimitiveTypeFlag)
  ...
  ...
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::PrimitiveTypeFlags)
</code>```

Body:
I created my own custom QFlags enumeration...

class A
{
  ...

  enum class PrimitiveTypeFlag : unsigned int {
    Unknown = 0x0,
    Bool = 0x1,
    Float = 0x2,
    Double = 0x4,
    Int8 = 0x8,
    UInt8 = 0x10,
    Int16 = 0x20,
    UInt16 = 0x40,
    Int32 = 0x80,
    UInt32 = 0x100,
    Int64 = 0x200,
    UInt64 = 0x400,
    StatsDataArray = 0x800,
    NeighborList = 0x1000,
    StringArray = 0x2000,
    NumericalPrimitives = 0x07FE,
    Any = 0x3FFF
  };
  Q_DECLARE_FLAGS(PrimitiveTypeFlags, PrimitiveTypeFlag)
  ...
  ...
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::PrimitiveTypeFlags)

When I instantiate an instance of PrimitiveTypeFlags, all flags are turned on.

A::PrimitiveTypeFlags pFlags;
pFlags.setFlag(A::PrimitiveTypeFlag::StringArray, false);

When I execute the block of code above to turn off the StringArray flag, I get this error:

invalid argument type 'A::PrimitiveTypeFlag' to unary expression.

If I simply execute ~A::PrimitiveTypeFlag::StringArray, I also get the same error.

Why do I get this error, and how do I fix it?

Thanks in advance.

Body:
enum classes are meant to be used as pure enums, which makes them safer to use by forbidding implicit conversions to their underlying type. This is hitting you here, because the QT macros expect to be able to perform bit operations on the values passed in.

You should be able to fix this by using pre-C++11 enum declarations:

class A
{
  ...

  enum PrimitiveTypeFlag : unsigned int {
    Unknown = 0x0,
    Bool = 0x1,
    Float = 0x2,
    Double = 0x4,
    Int8 = 0x8,
    UInt8 = 0x10,
    Int16 = 0x20,
    UInt16 = 0x40,
    Int32 = 0x80,
    UInt32 = 0x100,
    Int64 = 0x200,
    UInt64 = 0x400,
    StatsDataArray = 0x800,
    NeighborList = 0x1000,
    StringArray = 0x2000,
    NumericalPrimitives = 0x07FE,
    Any = 0x3FFF
  };
  Q_DECLARE_FLAGS(PrimitiveTypeFlags, PrimitiveTypeFlag)
  ...
  ...
};
Q_DECLARE_OPERATORS_FOR_FLAGS(A::PrimitiveTypeFlags)


问:
Disable Validation on a single (disabled) @Html.EditorFor
I've read around that the given way of doing this seems to be having different view models (which is a bit overkill imo) for different actions/controllers.

I thought

```<code>@Html.EditorFor(model => model.Ingredient.Name, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", data_val = "false"} })
</code>```

might work but unfortunately not.

Does anyone have any ideas?

答:
All unobtrusive validation (the kind used by ASP.NET MVC) is predicated on finding and parsing data attributes on each object.  Those carry all the information that the validation engine needs to run and only elements that have data-val="true" are included.

Any HTML attributes you pass will override any of the default attributes, so the easiest way is to just force data-val="false" and the form element won't be included in the validation engine and none of the other dependent tags will be parsed.

Here's an example from ASP .NET MVC Disable Client Side Validation at Per-Field Level:

@Html.TextBoxFor(m => m.BatchId, new { data_val = "false" })
```

Body:
I've read around that the given way of doing this seems to be having different view models (which is a bit overkill imo) for different actions/controllers.

I thought

@Html.EditorFor(model => model.Ingredient.Name, new { htmlAttributes = new { @class = "form-control", disabled = "disabled", data_val = "false"} })

might work but unfortunately not.

Does anyone have any ideas?


问:
Comparing 40 million lines in a file with 6 million list items in Python
I have a file with 40 million entries in the form of:

```<code>#No Username
</code>```

And I have a list with 6 million items, where each item is a username.

I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far:

```<code>import os
usernames=[]
common=open('/path/to/filf','w')
f=open('/path/to/6 million','r')
for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)
#noOfUsers=len(usernames)
for l in f:
    l=l.split(' ')
    if(l[1] in usernames):
        common.write(l[1]+'\n')
common.close()
f.close()
</code>```

How can I improve the performance of this code?

答: If you create a dict with usernames as keys then the algorithm for testing the existence of a key in a dict is much faster than testing for the presence of an element in a list.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a file with 40 million entries in the form of:

#No Username

And I have a list with 6 million items, where each item is a username.

I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far:

import os
usernames=[]
common=open('/path/to/filf','w')
f=open('/path/to/6 million','r')
for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)
#noOfUsers=len(usernames)
for l in f:
    l=l.split(' ')
    if(l[1] in usernames):
        common.write(l[1]+'\n')
common.close()
f.close()

How can I improve the performance of this code?


问:
Laravel form returning errors only for some fields in log file
I've got an application form. This form has a few fields, such as "name", "email", "country", etc.

Laravel is ONLY redirecting back returning an error for the email field. Such as The email field is required.. For everything else, it just refreshes the page, and in my laravel.log file, I get the following error:

[2017-11-16 08:52:30] production.ERROR:
  Illuminate\Validation\ValidationException: The given data failed to
  pass validation. in
  C:\xampp\htdocs\series\commend-me\CommendMe\vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:89

Here is my route:

```<code>Route::post('/postapply', [
    'uses' => '\CommendMe\Http\Controllers\ApplyController@postApply',
    'as' => 'post.apply',
    'middleware' => ['auth'],
]);
</code>```

and my controller:

```<code>public function postApply(Request $request) {

    $this->validate($request, [
        'name' => 'required|alpha_num|max:40|min:2',
        'country' => 'required|alpha_num|max:100|min:2',
        'body' => 'required|string|max:2000',
        'mature' => 'required',
        'email' => 'required|email|max:255',
    ]);

    dd("test");
</code>```

dd does not return "test" in this instance. Furthermore, the validation will ONLY redirect back an error for the email field, and if the email field is renamed to something else in the controller, it'll go back to just sending the error to the log file.

Why is this happening?

EDIT:

Adding markup as requested:

```<code><form role="form" method="post" action="{{ route ('post.apply') }}">
    <div class="submitArtSection">
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div class="border-bot">
            <input class="submitArtTitle" type="text" name="name" maxlength="39"  placeholder="Name">
        </div>
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div class="border-bot">
            <input class="submitArtTitle" type="text" maxlength="255" name="email"  placeholder="Email">
        </div>
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div class="border-bot">
            <input class="submitArtTitle" type="text" maxlength="255" name="country"  placeholder="Country">
        </div>
    <div class="submitRequired submitRequiredTitle">Required</div>
        <div>
            <textarea name="body" style="height: 175px;" maxlength="1980" placeholder="Tell us about yourself..."></textarea>
        </div>
    </div>

    <div class="submitArtSection submitArtCheckers">
    <div class="submitRequired">Required</div>
        <div>
            <span class="submitArtCaption submitArtRestrictionsHeader">
                Age
            </span>
            <span>
                <label>
                  <input type="radio" name="mature" value="0">
                    Under 18
                  <span class="checkmark"></span>
                </label>

                <label>
                 <input type="radio" name="mature" value="1">
                    18+
                  <span class="checkmark"></span>
                </label>
            </span>
        </div>
    </div>

    <div class="text-center">
        <button id="saveImage" class="pointer">Submit</button>
    </div>
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</code>```

dd($request->all()); at the start of the method returns of the following

```<code>array:5 [▼
  "name" => ""
  "email" => ""
  "country" => ""
  "body" => ""
  "_token" => "HKJ51CMvteYOD0OG79SQiRjpeTup9NNWvTfw1IWB"
]
</code>```

答:
I wasn't cycling errors in my markup.

```<code>@if (count($errors) > 0)
    <div class="alert alert-info" role="alert">
        {{ $errors->first() }}
        <a href="#" class="alert-close" data-dismiss="alert" aria-label="close">×</a>
    </div>
@endif
</code>```

the reason why I didn't realize that is because my template page also has an email field named email (for login), and was cycling errors for it. So only the form's email, which had the same name, was redirecting an error.

Body:
I've got an application form. This form has a few fields, such as "name", "email", "country", etc.

Laravel is ONLY redirecting back returning an error for the email field. Such as The email field is required.. For everything else, it just refreshes the page, and in my laravel.log file, I get the following error:

[2017-11-16 08:52:30] production.ERROR:
  Illuminate\Validation\ValidationException: The given data failed to
  pass validation. in
  C:\xampp\htdocs\series\commend-me\CommendMe\vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:89

Here is my route:

Route::post('/postapply', [
    'uses' => '\CommendMe\Http\Controllers\ApplyController@postApply',
    'as' => 'post.apply',
    'middleware' => ['auth'],
]);

and my controller:

public function postApply(Request $request) {

    $this->validate($request, [
        'name' => 'required|alpha_num|max:40|min:2',
        'country' => 'required|alpha_num|max:100|min:2',
        'body' => 'required|string|max:2000',
        'mature' => 'required',
        'email' => 'required|email|max:255',
    ]);

    dd("test");

dd does not return "test" in this instance. Furthermore, the validation will ONLY redirect back an error for the email field, and if the email field is renamed to something else in the controller, it'll go back to just sending the error to the log file.

Why is this happening?

EDIT:

Adding markup as requested:

<form role="form" method="post" action="{{ route ('post.apply') }}">

Required

            <input class="submitArtTitle" type="text" name="name" maxlength="39"  placeholder="Name">

Required

            <input class="submitArtTitle" type="text" maxlength="255" name="email"  placeholder="Email">

Required

            <input class="submitArtTitle" type="text" maxlength="255" name="country"  placeholder="Country">

Required

            <textarea name="body" style="height: 175px;" maxlength="1980" placeholder="Tell us about yourself..."></textarea>

Required

                Age

                  <input type="radio" name="mature" value="0">
                    Under 18

                 <input type="radio" name="mature" value="1">
                    18+

        <button id="saveImage" class="pointer">Submit</button>

    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

dd($request->all()); at the start of the method returns of the following

array:5 [▼
  "name" => ""
  "email" => ""
  "country" => ""
  "body" => ""
  "_token" => "HKJ51CMvteYOD0OG79SQiRjpeTup9NNWvTfw1IWB"
]

Body:
I wasn't cycling errors in my markup.

@if (count($errors) > 0)
    <div class="alert alert-info" role="alert">
        {{ $errors->first() }}
        <a href="#" class="alert-close" data-dismiss="alert" aria-label="close">×</a>
    </div>
@endif

the reason why I didn't realize that is because my template page also has an email field named email (for login), and was cycling errors for it. So only the form's email, which had the same name, was redirecting an error.


问:
PHP stdClass Object with array inside
I have this array.  I have tried a few things but not getting what I want.
I tried a foreach loop but it does not seem to do it easly and the process takes a long time.

```<code>stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [display_number] => 100140
                    [client] => stdClass Object
                        (
                            [name] => TAUQIR SHEIKH ET AL
                        )

                )

            [1] => stdClass Object
                (
                    [display_number] => 100141
                    [client] => stdClass Object
                        (
                            [name] => YOLANDA SHEIKH ET AL
                        )

                )
</code>```

I want it to be one simple array

```<code>[0] => Array
        (
            [0] => 100140
            [1] => TAUQIR SHEIKH ET AL
        )

    [1] => Array
        (
            [0] => 100141
            [1] => YOLANDA SHEIKH ET AL
        )
</code>```

Ok So the old code works but now they updated the API and this made it worse.  The response is now

```<code>(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [data] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [display_number] => 100140
                                    [client] => stdClass Object
                                        (
                                            [name] => TAUQIR SHEIKH ET AL
                                        )

                                )

                            [1] => stdClass Object
                                (
                                    [display_number] => 100141
                                    [client] => stdClass Object
                                        (
                                            [name] => YOLANDA SHEIKH ET AL
                                        )

                                )
</code>```

I tried this with the new code... But the array is empty.  Where am I going wrong?

```<code>//clean and make into an array
        $matter_array = array();
        if(!empty($response_Decode->data->data) &&
         is_array($response_Decode->data->data)) {
            foreach ($response_Decode->data->data as $info) {
                $d = array();
                $d[] = $info->display_number;
                $d[] = $info->client->name;
                $matter_array[] = $d;
            }
        }

        print_r($matter_array);  //For testing
        die(); //For testing
</code>```

答:
Ok so I just simplified the array... AND THAT WORKS!    </p>

```<code>//clean and make into an array
        $response_Decode=$response_Decode->data;
        $response_Decode=$response_Decode[0];
        //print_r ($response_Decode);
        //die(); //For testing
        $matter_array = array();
        if(!empty($response_Decode->data) && is_array($response_Decode->data)) {
            foreach ($response_Decode->data as $info) {
                $d = array();
                $d[] = $info->display_number;
                $d[] = $info->client->name;
                $matter_array[] = $d;
            }
        }
</code>```

Title: PHP stdClass Object with array inside

Body:
I have this array.  I have tried a few things but not getting what I want.
I tried a foreach loop but it does not seem to do it easly and the process takes a long time.

stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [display_number] => 100140
                    [client] => stdClass Object
                        (
                            [name] => TAUQIR SHEIKH ET AL
                        )

                )

            [1] => stdClass Object
                (
                    [display_number] => 100141
                    [client] => stdClass Object
                        (
                            [name] => YOLANDA SHEIKH ET AL
                        )

                )

I want it to be one simple array

[0] => Array
        (
            [0] => 100140
            [1] => TAUQIR SHEIKH ET AL
        )

    [1] => Array
        (
            [0] => 100141
            [1] => YOLANDA SHEIKH ET AL
        )

Ok So the old code works but now they updated the API and this made it worse.  The response is now

(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [data] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [display_number] => 100140
                                    [client] => stdClass Object
                                        (
                                            [name] => TAUQIR SHEIKH ET AL
                                        )

                                )

                            [1] => stdClass Object
                                (
                                    [display_number] => 100141
                                    [client] => stdClass Object
                                        (
                                            [name] => YOLANDA SHEIKH ET AL
                                        )

                                )

I tried this with the new code... But the array is empty.  Where am I going wrong?

//clean and make into an array
        $matter_array = array();
        if(!empty($response_Decode->data->data) &&
         is_array($response_Decode->data->data)) {
            foreach ($response_Decode->data->data as $info) {
                $d = array();
                $d[] = $info->display_number;
                $d[] = $info->client->name;
                $matter_array[] = $d;
            }
        }

        print_r($matter_array);  //For testing
        die(); //For testing

Body:
Ok so I just simplified the array... AND THAT WORKS!

//clean and make into an array
        $response_Decode=$response_Decode->data;
        $response_Decode=$response_Decode[0];
        //print_r ($response_Decode);
        //die(); //For testing
        $matter_array = array();
        if(!empty($response_Decode->data) && is_array($response_Decode->data)) {
            foreach ($response_Decode->data as $info) {
                $d = array();
                $d[] = $info->display_number;
                $d[] = $info->client->name;
                $matter_array[] = $d;
            }
        }


问:
Does memoization works with active record relations?
Let's say i have a method in my model as below.

```<code>def all_users
  @users ||= User.all
end
</code>```

and I have other method in my model where i am doing all_users.where(id: 123) for multiple different ids. Will it execute a query/ hit to db everytime or it will fetch the record directly from the cached resultset.

答:
See the docs on SQL caching. If the query is exactly the same, the result will be fetched from the cache. Requests for different ID's will result in individual queries.

Be careful when using #all, however, as it will load all your records into memory. This can be slow and consume a lot of memory. Making individual User.find(X) queries will be better for you in the long run.

Body:
Let's say i have a method in my model as below.

def all_users
  @users ||= User.all
end

and I have other method in my model where i am doing all_users.where(id: 123) for multiple different ids. Will it execute a query/ hit to db everytime or it will fetch the record directly from the cached resultset.


问:
unable use columns defined in xmltable
Getting error while running the below query

```<code>  select xt.IssueDate, xt.SequenceNumber  from xml_tab x ,
          XMLTABLE('/EmployeeInfo'
                   PASSING x.xml_data COLUMNS
                   "IssueDate" varchar2(10) path '@IssueDate',
                   "SequenceNumber" integer path '@SequenceNumber'
            ) xt;
</code>```

error I am getting

ORA-00904: "XT"."SEQUENCENUMBER": invalid identifier
  00904. 00000 -  "%s: invalid identifier"
  *Cause:

  *Action: Error at Line: 114 Column: 22

答:
You are mixing quoted and non-quoted identifiers. The columns clause in the XMLTable call is defining SQL-type names, not XML-type names.

You can either quote both:

```<code>select xt."IssueDate", xt."SequenceNumber"  from xml_tab x ,
          XMLTABLE('/EmployeeInfo'
                   PASSING x.xml_data COLUMNS
                   "IssueDate" varchar2(10) path '@IssueDate',
                   "SequenceNumber" integer path '@SequenceNumber'
            ) xt;
</code>```

or preferably quote neither:

```<code>select xt.IssueDate, xt.SequenceNumber  from xml_tab x ,
          XMLTABLE('/EmployeeInfo'
                   PASSING x.xml_data COLUMNS
                   IssueDate varchar2(10) path '@IssueDate',
                   SequenceNumber integer path '@SequenceNumber'
            ) xt;
</code>```

Title: unable use columns defined in xmltable

Body:
Getting error while running the below query

  select xt.IssueDate, xt.SequenceNumber  from xml_tab x ,
          XMLTABLE('/EmployeeInfo'
                   PASSING x.xml_data COLUMNS
                   "IssueDate" varchar2(10) path '@IssueDate',
                   "SequenceNumber" integer path '@SequenceNumber'
            ) xt;

error I am getting

ORA-00904: "XT"."SEQUENCENUMBER": invalid identifier
  00904. 00000 -  "%s: invalid identifier"
  *Cause:

  *Action: Error at Line: 114 Column: 22

Body:
You are mixing quoted and non-quoted identifiers. The columns clause in the XMLTable call is defining SQL-type names, not XML-type names.

You can either quote both:

select xt."IssueDate", xt."SequenceNumber"  from xml_tab x ,
          XMLTABLE('/EmployeeInfo'
                   PASSING x.xml_data COLUMNS
                   "IssueDate" varchar2(10) path '@IssueDate',
                   "SequenceNumber" integer path '@SequenceNumber'
            ) xt;

or preferably quote neither:

select xt.IssueDate, xt.SequenceNumber  from xml_tab x ,
          XMLTABLE('/EmployeeInfo'
                   PASSING x.xml_data COLUMNS
                   IssueDate varchar2(10) path '@IssueDate',
                   SequenceNumber integer path '@SequenceNumber'
            ) xt;


问:
Android studio uses 100% CPU while just coding (no builiding)
Android Studio uses 100% CPU when I'm just coding, even if I type a single word CPU use raises to the 100% and comes to back normal, and if I keep typing it takes 100% CPU all the time.

What I have tried is :

File > Invalidate cache and Restart

Change max heap size for android studio by editing VM options

"Power Save Mode" it runs perfectly when it is turned on. but it also disables some useful features of IDE and I don't want to disable it.

removed .android and .AndroidStudio3.0 folder from c:\users\username\

Android Studio plugins are set to default. no extra plugins are added. I tried disabling a plugin that can be disabled like Git and SVN but it's still same

I'm running windows 7 64-bit OS and Android Studio 3.0 and OS which I re-installed yesterday. I did not install the JDK - Android Studio is using default OpenJDK.

I've searched on internet but it did not help. any help would be appreciated.

答:
It seems your systems config is low. as Android studio cares of itself for CPU uses so it gives its best.

Reasons being

You have Core 2 duo that is too low for Android Studio.

You have 4gb Ram, that is too low again.

If you work on some large project then 2gb of ram is necessary for Android Studio. and Java takes unexpected upto 4gb or more.

Solution

Increase ram by 8gb and processor at least intel i3

kill java or invalidate cache and restart if you get stuck of hanging your android studio.

Here is my CPU uses that goes upto 3gb for Android Studio and upto 4gb for Java.

The recommended hardware requirements for Android Studio are:

Microsoft® Windows® 8/7/Vista (64-bit Recommended)

Intel i5 4th-5th gen processor.

6 GB RAM

2 GB hard disk space + at least 1 GB for Android SDK, emulator system images, and caches

Optional for accelerated emulator: Intel® processor with support for Intel® VT-x,

As Java uses it’s own Machine known as JVM(Java Virtual Machine) for program compilation and it has some complex tasks like generate classes then verify byte code and then execute program with JIT(Just In Time)

And as Android has Natively developed in Java the slow compilation will be the issue i presume. But with new Android Studio feature known as “Instant Run” compilation and development of Android apps made more easy.

As i am developer of Android apps, I use

Intel i5 6th gen 2.70 Ghz processor

12 GB of RAM (8GB in first slot and 4 in Second Both DDR3)
1 TB of Hard Drive
Nvidia G-Force 940M 2 GB of Dedicated GPU for running Adobe After-Effects, Maya and Unity like Software which needs Dedicated GPU.
That’s all and Still Android Studio sometimes Lags with such high performance Hardware with the more complex and big apps(Complex Projects).

I think if you are going to buy a hardware and use it for at-least 3 years get the exact specs i have (or similar), However if you are frequent hardware changer use specs i mentioned first.

And for Emulator use Genymotion as it is way faster then the emulator which Android provides. Or use some other alternatives like Memu, Blustacks, Andy etc.

ContentLicense: CC BY-SA 4.0


问:
Text files vs MySQL. Which is better for storing wiki information
I have been storing my wiki information in a MySQL database. However, it seems like kind of a waste to store huge amounts of info in a relational database. I am thinking of moving the bulk of the information to text files. Does anyone have experience with which would be better?</p>

答:
Why you want do that,

if you do that, how you can perform search on your wiki?

a wiki post should be processed to build blue links and red links, how you want do that in text file?

after processing wiki post it's good to cache it in text file, we have a large wiki and store processed wiki in another table, its very fast.


问:
Django Get absolute url for static files
In Django, when I use:

```<code>{{ request.build_absolute_uri }}{% static "img/myimage.jpg" %}
</code>```

It produces: 'http://myurl.com//static/img/myimage.jpg'. This produces an error.

How can I remove the double slashes?

The STATIC URL is:

```<code>STATIC_URL = '/static/'
</code>```

But I don't think removing the first '/' would be a good idea.

答:
I just made a quick template tag for doing this. Create files /myapp/templatetags/__init__.py and /myapp/templatetags/my_tag_library.py, if you don't have them already, and add the following to my_tag_library.py:

```<code>from django import template
from django.templatetags import static

register = template.Library()

class FullStaticNode(static.StaticNode):
    def url(self, context):
        request = context['request']
        return request.build_absolute_uri(super().url(context))

@register.tag('fullstatic')
def do_static(parser, token):
    return FullStaticNode.handle_token(parser, token)
</code>```

Then in your templates, just {% load my_tag_library %} and use e.g. {% fullstatic my_image.jpg %}.

In response to earlier comments wondering why someone would need to do this, my particular use case was that I wanted to put a link to a static file inside of an open graph protocol meta tag, and those links need to be absolute. In development the static files get served locally, but in production they get served remotely, so I couldn't just prepend the host to get the full url.

Body:
In Django, when I use:

{{ request.build_absolute_uri }}{% static "img/myimage.jpg" %}

It produces: 'http://myurl.com//static/img/myimage.jpg'. This produces an error.

How can I remove the double slashes?

The STATIC URL is:

STATIC_URL = '/static/'

But I don't think removing the first '/' would be a good idea.

Body:
I just made a quick template tag for doing this. Create files /myapp/templatetags/__init__.py and /myapp/templatetags/my_tag_library.py, if you don't have them already, and add the following to my_tag_library.py:

from django import template
from django.templatetags import static

register = template.Library()

class FullStaticNode(static.StaticNode):
    def url(self, context):
        request = context['request']
        return request.build_absolute_uri(super().url(context))

@register.tag('fullstatic')
def do_static(parser, token):
    return FullStaticNode.handle_token(parser, token)

Then in your templates, just {% load my_tag_library %} and use e.g. {% fullstatic my_image.jpg %}.

In response to earlier comments wondering why someone would need to do this, my particular use case was that I wanted to put a link to a static file inside of an open graph protocol meta tag, and those links need to be absolute. In development the static files get served locally, but in production they get served remotely, so I couldn't just prepend the host to get the full url.


问:
Acces linked list in main class from another class java
I have this project of an Online Store. The class OnlineStore is where the main method is, that starts the program. I also have 3 classes, User, Item andPackage, with some inherited classes.

I store all users, items and Packages in linked lists.
I created instances in the class OnlineStore inside the main method but I want to be able to access to them every moment; The class Item sould be able to access this linked list and remove an item that has been sold.

```<code>public class OnlineStore{

    public static void main(String[] args) {
    LinkedList<User> users = new  LinkedList<User>();
    LinkedList<Item> itemsSold =  new  LinkedList<Item>();
    LinkedList<Item> items =  new  LinkedList<Item>(
    LinkedList<Package> packages =  new  LinkedList<Package>();
    }
}

//Then I create some instances of Items Users and call their methods of buying,
//loging in, etc..

//If a item is buyed:

public class Buyer extends User {
    //ATTRIBUTES
    private String accountNumber;
    private LinkedList<Item> boughtItems;

    //CONSTRUCTOR
    public Buyer(String n, String id, String pass, String a){
        super(n, id, pass);
        accountNumber = a;
    }

    //METHODS
    public void buy(Item i){
        boughtItems.add(i);
        //Here I need to acces the first class and remove from availableItems
        items.remove(i);
    }

}
</code>```

Thanks for your help!
John R.

答:
Try something like this:

```<code>public class OnlineStore{

    public static LinkedList<User> users = new  LinkedList<User>();
    public static LinkedList<Item> itemsSold =  new  LinkedList<Item>();
    public static LinkedList<Item> items =  new  LinkedList<Item>();
    public static LinkedList<Package> packages =  new  LinkedList<Package>();

    public static void main(String[] args) {

    }
</code>```

}

Body:
I have this project of an Online Store. The class OnlineStore is where the main method is, that starts the program. I also have 3 classes, User, Item andPackage, with some inherited classes.

I store all users, items and Packages in linked lists.
I created instances in the class OnlineStore inside the main method but I want to be able to access to them every moment; The class Item sould be able to access this linked list and remove an item that has been sold.

public class OnlineStore{

    public static void main(String[] args) {
    LinkedList<User> users = new  LinkedList<User>();
    LinkedList<Item> itemsSold =  new  LinkedList<Item>();
    LinkedList<Item> items =  new  LinkedList<Item>(
    LinkedList<Package> packages =  new  LinkedList<Package>();
    }
}

//Then I create some instances of Items Users and call their methods of buying,
//loging in, etc..

//If a item is buyed:

public class Buyer extends User {
    //ATTRIBUTES
    private String accountNumber;
    private LinkedList<Item> boughtItems;

    //CONSTRUCTOR
    public Buyer(String n, String id, String pass, String a){
        super(n, id, pass);
        accountNumber = a;
    }

    //METHODS
    public void buy(Item i){
        boughtItems.add(i);
        //Here I need to acces the first class and remove from availableItems
        items.remove(i);
    }

}

Thanks for your help!
John R.

Body:
Try something like this:

public class OnlineStore{

    public static LinkedList<User> users = new  LinkedList<User>();
    public static LinkedList<Item> itemsSold =  new  LinkedList<Item>();
    public static LinkedList<Item> items =  new  LinkedList<Item>();
    public static LinkedList<Package> packages =  new  LinkedList<Package>();

    public static void main(String[] args) {

    }

}


问:
JAVA: Do i need to rebuild an application after updating password in context.xml?
I am new to Java.

I updated the context.xml file on my web app, but it appears to still be using the old password.

Do i need to rebuild an application after updating a DB password in context.xml?

Thanks.

答: In my specific case, I ended up updating the configurations locally, doing a maven install, and then replacing the war file on the server with the new generated war from my local environment.  </p>


问:
What is the meaning of ":"?
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like

```<code>for(String x : model)
</code>```

Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?

答:
Similar to mathematical notation that represents elements in a set.

Read left to right; For all string's x that are elements in model, do .

Title: What is the meaning of ":"?

Body:
I have been watching some LinkedList videos to try and understand what it is. But I see a lot of people having code like

for(String x : model)

Can anyone help me understand what ":" does in this code besides attaching x to "model" or is that all it does?


问:
Program that finds the largest prime factor
So I wrote a code for finding the largest factor for my learning procces on Project Euler and it worked fine and I got the right answer. Tho I saw diffrent solutions and they were "longer" and looked more complicated. So my question is, is there anything my code is no taking care of for lets say different number or is there a better way to do this task? I am trying to learn different ways of solving problems to get better at programming so I wonder if I should have done that code in a different way.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prime_factor
{
  class Program
  {
    static void Main(string[] args)
    {
        long n = 600851475143;
        int largest = 0;
        for (int i = 1; i<=n; i++)
        {
            if (n%i == 0)
            {
                Console.WriteLine(i);
                n /= i;
                largest = i;

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

答:
I like it - you get around checking if i is prime, which is the most complicated part! If it were not prime, you would have already divided out it's composite factors.

However, I think there are cases where a non-prime i can sneak in - where multiples of prime factors divide your n. Try n = 36 (since 36 == 2^2 * 3^2). I think your algorithm returns 6.

You just need to add a loop to see if i can divide n multiple times and I think it will fix this issue.

Body:
So I wrote a code for finding the largest factor for my learning procces on Project Euler and it worked fine and I got the right answer. Tho I saw diffrent solutions and they were "longer" and looked more complicated. So my question is, is there anything my code is no taking care of for lets say different number or is there a better way to do this task? I am trying to learn different ways of solving problems to get better at programming so I wonder if I should have done that code in a different way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prime_factor
{
  class Program
  {
    static void Main(string[] args)
    {
        long n = 600851475143;
        int largest = 0;
        for (int i = 1; i<=n; i++)
        {
            if (n%i == 0)
            {
                Console.WriteLine(i);
                n /= i;
                largest = i;

            }
        }
        Console.WriteLine(largest);
        Console.ReadLine();
    }
  }
}


问:
The pd.Series.is_monotonic() function
In applying the is_monotonic() function I am getting an error message I can not explain. This is my code:

```<code>pd.Series([1, 1, 2, 3, 3, 4, 4, 4]).is_monotonic()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-65238a38d200> in <module>()
----> 1 pd.Series([1, 1, 2, 3, 3, 4, 4, 4]).is_monotonic()

TypeError: 'bool' object is not callable
</code>```

Since I am not passing a boolean object why I am getting this error message?

Your advice will be appreciated.

答:
is_monotonic is not method but an attribute.

Don't put the parenthesis, "()" afterwards.

```<code>s = pd.Series([1, 1, 2, 3, 3, 4, 4, 4])
s.is_monotonic

True
</code>```

Title: The pd.Series.is_monotonic() function

Body:
In applying the is_monotonic() function I am getting an error message I can not explain. This is my code:

pd.Series([1, 1, 2, 3, 3, 4, 4, 4]).is_monotonic()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-65238a38d200> in <module>()
----> 1 pd.Series([1, 1, 2, 3, 3, 4, 4, 4]).is_monotonic()

TypeError: 'bool' object is not callable

Since I am not passing a boolean object why I am getting this error message?

Your advice will be appreciated.

Body:
is_monotonic is not method but an attribute.

Don't put the parenthesis, "()" afterwards.

s = pd.Series([1, 1, 2, 3, 3, 4, 4, 4])
s.is_monotonic

True


问:
ItextSharp Add lines to PDF and convert into bytes without saving it.
I have a method that gets a pdf and adds's lines in that pdf and then creates a new pdf and saves it in a path that's given to it. Now I don't want to save that new file in a path instead I want to convert it into bytes and send in Emails how can I do that I tried a couple of methods but it all ways look for path says no path found here is the code. </p>

```<code>     protected void CreatePDF()
    {

        string Oldfile = @"C:\BlankPDFt.pdf"; // Gets the Template / The actualy agreement Letter
      //  (new FileInfo("C:/Documents/Docs.pdf")).Directory.Create(); // Go create this folder if it's not there
      string NewFile = "C:/Documents/Docs.pdf";
        PdfReader reader = new PdfReader(Oldfile);
        iTextSharp.text.Rectangle Size = reader.GetPageSizeWithRotation(1);
        Document document = new Document(Size);
        FileStream fs = new FileStream(NewFile , FileMode.Create, FileAccess.Write); // This is where it all ways look for new file path
 i dont want it to save instead convert to bytes but wont work.
        PdfWriter weiter = PdfWriter.GetInstance(document, fs);
        document.Open();
        PdfContentByte cb = weiter.DirectContent;
        PdfImportedPage page = weiter.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetColorFill(BaseColor.BLACK);
        cb.SetFontAndSize(bf, 12);
        cb.BeginText();
     //   string Signatur = "Some texts"; // adds this text to that pdf
      cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Here", 335, 90, 0); // Insert the signature
        cb.EndText();
    }
</code>```

答:
The PdfWriter.GetInstance() method accepts an InputStream as its second argument. Instead of passing a FileStream you should  pass it a MemoryStream.

```<code>MemoryStream memory_stream = new MemoryStream();
PdfWriter.GetInstance(document, memory_stream );
...
document.Close();
byte[] pdf_bytes = memory_stream.ToArray();
</code>```

Body:
I have a method that gets a pdf and adds's lines in that pdf and then creates a new pdf and saves it in a path that's given to it. Now I don't want to save that new file in a path instead I want to convert it into bytes and send in Emails how can I do that I tried a couple of methods but it all ways look for path says no path found here is the code.

     protected void CreatePDF()
    {

        string Oldfile = @"C:\BlankPDFt.pdf"; // Gets the Template / The actualy agreement Letter
      //  (new FileInfo("C:/Documents/Docs.pdf")).Directory.Create(); // Go create this folder if it's not there
      string NewFile = "C:/Documents/Docs.pdf";
        PdfReader reader = new PdfReader(Oldfile);
        iTextSharp.text.Rectangle Size = reader.GetPageSizeWithRotation(1);
        Document document = new Document(Size);
        FileStream fs = new FileStream(NewFile , FileMode.Create, FileAccess.Write); // This is where it all ways look for new file path
 i dont want it to save instead convert to bytes but wont work.
        PdfWriter weiter = PdfWriter.GetInstance(document, fs);
        document.Open();
        PdfContentByte cb = weiter.DirectContent;
        PdfImportedPage page = weiter.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetColorFill(BaseColor.BLACK);
        cb.SetFontAndSize(bf, 12);
        cb.BeginText();
     //   string Signatur = "Some texts"; // adds this text to that pdf
      cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Here", 335, 90, 0); // Insert the signature
        cb.EndText();
    }

Body:
The PdfWriter.GetInstance() method accepts an InputStream as its second argument. Instead of passing a FileStream you should  pass it a MemoryStream.

MemoryStream memory_stream = new MemoryStream();
PdfWriter.GetInstance(document, memory_stream );
...
document.Close();
byte[] pdf_bytes = memory_stream.ToArray();


问:
Replace a String containing a "
I have run into a problem trying to get this code to work:

```<code>filereader.Replace(Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000000", Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000001")
</code>```

I want it to replace a string which is !exaclty! looking like this, containing the quotation marks:

"SomeSetting"=dword:00000000

but what it does is looking for this string:

""SomeSetting""=dword:00000000

and i cant get it to work. Even if i tried this:

```<code>Dim Test As String = Chr(34)
</code>```

Test will look like this:
""
instead of "
 what am i missing here?

答:
I think I see your problem... This is a quite common, accidental thing for people to do.

Strings are immutable, which means that once you've created them they cannot be changed without creating a new string instance.

The problem is this:

```<code>filereader.Replace(Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000000", Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000001")
</code>```

The Replace() function returns the new string with the replaced value(s) (since it cannot change the original one), but you never use the instance it returns.

You should set your old string variable to the new string returned by Replace(), like this:

```<code>filereader = filereader.Replace(Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000000", Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000001")
</code>```

To avoid (or at least minimize the risk of) things like this happening, make sure you read the information that Visual Studio's IntelliSense shows you when writing the function call.

If you do bump into problems anyway, make sure to check the MSDN documentation to see if you missed anything. They usually also have examples showing how you can use the methods.

Title: Replace a String containing a "

Body:
I have run into a problem trying to get this code to work:

filereader.Replace(Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000000", Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000001")

I want it to replace a string which is !exaclty! looking like this, containing the quotation marks:

"SomeSetting"=dword:00000000

but what it does is looking for this string:

""SomeSetting""=dword:00000000

and i cant get it to work. Even if i tried this:

Dim Test As String = Chr(34)

Test will look like this:
""
instead of "
 what am i missing here?

Body:
I think I see your problem... This is a quite common, accidental thing for people to do.

Strings are immutable, which means that once you've created them they cannot be changed without creating a new string instance.

The problem is this:

filereader.Replace(Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000000", Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000001")

The Replace() function returns the new string with the replaced value(s) (since it cannot change the original one), but you never use the instance it returns.

You should set your old string variable to the new string returned by Replace(), like this:

filereader = filereader.Replace(Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000000", Chr(34) & "SomeSetting" & Chr(34) & "=dword:00000001")

To avoid (or at least minimize the risk of) things like this happening, make sure you read the information that Visual Studio's IntelliSense shows you when writing the function call.

If you do bump into problems anyway, make sure to check the MSDN documentation to see if you missed anything. They usually also have examples showing how you can use the methods.


问:
getElementByID.readOnly in array
Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?

```<code>script language="javascript" type="text/javascript">
 $(document).ready(function () {
 $(function(){
     var index, len;
        $.get('/SomeList.txt', function(data){
            var SomeList = data.split('\n');
            for (index = 0, len = SomeList.length; index < len; index++) {
           document.getElementById(SomeList[index]).readOnly = true;
}
        });

    });

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

and txt file contains name of input ID:

```<code>TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
</code>```

答:
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
           document.getElementById(id_array[i]).readOnly = true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  Email: <input type="text" id="email" value="test@mail.com"><br>
  Country: <input type="text" id="country" value="Norway" ></code>```

it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements

Title: getElementByID.readOnly in array

Body:
Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?

script language="javascript" type="text/javascript">
 $(document).ready(function () {
 $(function(){
     var index, len;
        $.get('/SomeList.txt', function(data){
            var SomeList = data.split('\n');
            for (index = 0, len = SomeList.length; index < len; index++) {
           document.getElementById(SomeList[index]).readOnly = true;
}
        });

    });

     });
     </script>

and txt file contains name of input ID:

TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice

Body:
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
           document.getElementById(id_array[i]).readOnly = true;
}

  Email: <input type="text" id="email" value="test@mail.com"><br>
  Country: <input type="text" id="country" value="Norway" >

it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements


问:
Flyway Issue with DB2
I am using flyway for a deployment and the tables built as a result of flyway are all fine.
The issue I have is with the schema_version table. I am unable to query an individual column in the table. I am only able to perform a select *.
The error message I am getting is:

10:35:49  [SELECT - 0 row(s), 0.000 secs]  1) [Error Code: -206, SQL State: 42703]  DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=SCRIPT, DRIVER=4.13.127. 2) [Error Code: -727, SQL State: 56098]  DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-206;42703;SCRIPT, DRIVER=4.13.127

答:
Try enclosing the column name in double quotes:
select "SCRIPT" from flyway.schema_version</p>

Title: Flyway Issue with DB2


问:
Get Value from local .resx file
How can i get value from local .resx file in asp.net?</p>

答:
From code-behind:

```<code>CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

// Gets the value of associated with key "MyKey" from the local resource file for a given culture ("~/MyPage.aspx.en.resx") or from the default one ("~/MyPage.aspx.resx")
object keyValue = HttpContext.GetLocalResourceObject("~/MyPage.aspx", "MyKey", culture);
</code>```

If you need the value to be populated directly on your page/user control then you can use one of these techniques to get the values from the resource files.

Title: Get Value from local .resx file

Body:
From code-behind:

CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

// Gets the value of associated with key "MyKey" from the local resource file for a given culture ("~/MyPage.aspx.en.resx") or from the default one ("~/MyPage.aspx.resx")
object keyValue = HttpContext.GetLocalResourceObject("~/MyPage.aspx", "MyKey", culture);

If you need the value to be populated directly on your page/user control then you can use one of these techniques to get the values from the resource files.


问:
Multiple Input lines java
I want to write a program that reads this input:

```<code>1
3
9
16
25
17
150312
0.5
13.8
2.4
</code>```

and it should output this:

```<code>1.00,1.00
3.00,1.73
9.00,3.00
16.00,4.00
25.00,5.00
17.00,4.12
150312.00,387.70
0.50,0.71
13.80,3.71
2.40,1.55
</code>```

My Code is this:

```<code>import java.util.Scanner;

public class SqrtTable {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        if(StdIn.isEmpty()==true) {
        }
        else {
            output(s);
        }
    }

    public static void output(Scanner s) {
        double a = StdIn.readDouble();
//
        StdOut.printf("%.2f, %.2f", a, Math.sqrt(a));
//      System.out.println(a);
        StdIn.readLine();
    }
}
</code>```

My Code only puts out the first line.
What do I have to change?

答:
Try something like this:

```<code>Scanner sc = new Scanner(System.in);
String myString = sc.nextLine();
String[] flostr = myString.split(" ");
DecimalFormat df = new DecimalFormat("#.##");

for(String s : flostr){
   System.out.println(Float.parseFloat(s) +" ," + df.format(Math.sqrt(Float.parseFloat(s))));
}
</code>```

Edit: Considering user input will be in different line, try something like:

```<code>public static void main(String args[]) {
   Scanner sc = new Scanner(System.in);
   List<String> list = new ArrayList<String>();

   System.out.println("Enter your numbers, enter 'end' when done: ");
   while(!sc.hasNext("end")){
       list.add(sc.next());
   }

   String[] flostr = list.toArray(new String[0]);
   for(String s : flostr){
       System.out.println(String.format("%.2f", Float.parseFloat(s)) +" ," + String.format("%.2f", (Math.sqrt(Float.parseFloat(s)))));
   }

}
</code>```

Title: Multiple Input lines java

Body:
I want to write a program that reads this input:

1
3
9
16
25
17
150312
0.5
13.8
2.4

and it should output this:

1.00,1.00
3.00,1.73
9.00,3.00
16.00,4.00
25.00,5.00
17.00,4.12
150312.00,387.70
0.50,0.71
13.80,3.71
2.40,1.55

My Code is this:

import java.util.Scanner;

public class SqrtTable {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        if(StdIn.isEmpty()==true) {
        }
        else {
            output(s);
        }
    }

    public static void output(Scanner s) {
        double a = StdIn.readDouble();
//
        StdOut.printf("%.2f, %.2f", a, Math.sqrt(a));
//      System.out.println(a);
        StdIn.readLine();
    }
}

My Code only puts out the first line.
What do I have to change?

Body:
Try something like this:

Scanner sc = new Scanner(System.in);
String myString = sc.nextLine();
String[] flostr = myString.split(" ");
DecimalFormat df = new DecimalFormat("#.##");

for(String s : flostr){
   System.out.println(Float.parseFloat(s) +" ," + df.format(Math.sqrt(Float.parseFloat(s))));
}

Edit: Considering user input will be in different line, try something like:

public static void main(String args[]) {
   Scanner sc = new Scanner(System.in);
   List<String> list = new ArrayList<String>();

   System.out.println("Enter your numbers, enter 'end' when done: ");
   while(!sc.hasNext("end")){
       list.add(sc.next());
   }

   String[] flostr = list.toArray(new String[0]);
   for(String s : flostr){
       System.out.println(String.format("%.2f", Float.parseFloat(s)) +" ," + String.format("%.2f", (Math.sqrt(Float.parseFloat(s)))));
   }

}


问:
Pass Fluid variable to TypoScript
I want to pass a variable (uid of category) in Fluid to a TypoScript :

```<code> <f:cObject typoscriptObjectPath="lib.testFluid" data="{setting.myvar}/>
</code>```

Then i want to use the var to get all content elements in folder with pid 942 and the category {setting.myvar}

```<code>lib.testFluid = COA
lib.testFluid = CONTENT
lib.testFluid {
table = tt_content
    select {
    pidInList = 942
    where = selected_categories = |
</code>```

}

}

This does not work, it creates an MySql syntax error. I also tried using current = 1 instead of the where clause without success. I looked at post TYPO3: pass variable to typoscript via cObject? and I can recreate it but it does not work with my script. (TYPO3 8)
If i use

```<code>...
    where = selected_categories = 13
....
</code>```

the scrip will succesfully display all CE with category 13. How do i make it work with a var?

答:
could you try this:

```<code><f:cObject typoscriptObjectPath="lib.testFluid" data="{myvar: setting.myvar}/>

lib.testFluid = CONTENT
lib.testFluid {
    table = tt_content
    select {
        pidInList = 942
        where.data = field:myvar
        where.intval = 1
        where.wrap = selected_categories=|
    }
}
</code>```

hard to test for me but it might work ...

Title: Pass Fluid variable to TypoScript

Body:
I want to pass a variable (uid of category) in Fluid to a TypoScript :

 <f:cObject typoscriptObjectPath="lib.testFluid" data="{setting.myvar}/>

Then i want to use the var to get all content elements in folder with pid 942 and the category {setting.myvar}

lib.testFluid = COA
lib.testFluid = CONTENT
lib.testFluid {
table = tt_content
    select {
    pidInList = 942
    where = selected_categories = |

}

}

This does not work, it creates an MySql syntax error. I also tried using current = 1 instead of the where clause without success. I looked at post TYPO3: pass variable to typoscript via cObject? and I can recreate it but it does not work with my script. (TYPO3 8)
If i use

...
    where = selected_categories = 13
....

the scrip will succesfully display all CE with category 13. How do i make it work with a var?

Body:
could you try this:

<f:cObject typoscriptObjectPath="lib.testFluid" data="{myvar: setting.myvar}/>

lib.testFluid = CONTENT
lib.testFluid {
    table = tt_content
    select {
        pidInList = 942
        where.data = field:myvar
        where.intval = 1
        where.wrap = selected_categories=|
    }
}

hard to test for me but it might work ...


问:
Func and List<string>
I have defined the following

```<code>Dictionary<string, Func<string, List<string>>> test1 = new Dictionary<string, Func<string, List<string>>>();
</code>```

also I have

```<code>    private string fred(List<string> Parms)
    {

        return "Test";
    }
</code>```

how do I add fred to the dictionary?
I have tried

```<code>       test1.Add("Test",fred);
</code>```

but I get an error, if I replace the List for a string everything is ok.

答:
```<code>Dictionary<string, Func<string, List<string>>> test1 = new Dictionary<string, Func<string, List<string>>>();
</code>```

should be

```<code>Dictionary<string, Func<List<string>, string>>> test1 = new Dictionary<string, Func<List<string>, string>>();
</code>```

Title: Func and List<string>

Body:
I have defined the following

Dictionary<string, Func<string, List<string>>> test1 = new Dictionary<string, Func<string, List<string>>>();

also I have

    private string fred(List<string> Parms)
    {

        return "Test";
    }

how do I add fred to the dictionary?
I have tried

       test1.Add("Test",fred);

but I get an error, if I replace the List for a string everything is ok.

Body:
Dictionary<string, Func<string, List<string>>> test1 = new Dictionary<string, Func<string, List<string>>>();

should be

Dictionary<string, Func<List<string>, string>>> test1 = new Dictionary<string, Func<List<string>, string>>();


问:
Long Numeric to Character in SAS
When I try to convert a 10 digit number which is stored as 8. into a character using put(,8.) it gives me the character value as something like 1.2345e10. I want the character string to be as 1234567890. Can someone please help ?</p>

答:
8. is the width (number of characters) you'd like to use. So of course it is 1.2345e9; that's what it can fit in 8 characters.

```<code>x_char = put(x,10.);
</code>```

That asks for it to be put in 10 characters.  Keep extending it if you want it more than 10.  Just be aware you may need to use the optional alignment option (put(x,10. -l)) if you aren't happy with the default alignment of right aligned for shorter-than-maximum-length values.

Do note that when you originally describe the number as 8., I suspect you're actually referring to length; length is not the display size but the storage size (bytes in memory set aside).  For character variables in a SBCS system they're identical, but for numeric variables length and format are entirely unrelated.

Title: Long Numeric to Character in SAS

Body:
8. is the width (number of characters) you'd like to use. So of course it is 1.2345e9; that's what it can fit in 8 characters.

x_char = put(x,10.);

That asks for it to be put in 10 characters.  Keep extending it if you want it more than 10.  Just be aware you may need to use the optional alignment option (put(x,10. -l)) if you aren't happy with the default alignment of right aligned for shorter-than-maximum-length values.

Do note that when you originally describe the number as 8., I suspect you're actually referring to length; length is not the display size but the storage size (bytes in memory set aside).  For character variables in a SBCS system they're identical, but for numeric variables length and format are entirely unrelated.


问:
What is the equivalent operator in R for matlab /
I have one program in Matlab that I want translate to a R program.

The matlab program is :

```<code>function R = cprob(N,A,B)
    R = ((A.*B)*N)/(B*N)
end
</code>```

In R, " * " becomes " %*% " and " .* " becomes " * ". And " / "?

答:
I understand that by "/" you mean a matrix right division.

You can use mrdivide frim the pracma package.  Please take a look at this.

https://www.rdocumentation.org/packages/pracma/versions/1.9.9/topics/mldivide

This would be your code:

```<code>    library("pracma")

    a1 = matrix(c(1,2,0,2,5,-1,4,10,-1),nrow=3,ncol=3)
    a2 = matrix(c(1,2,4,2,5,10,0,-1,-1),nrow=3,ncol=3)
    a3=  matrix(c(1,0,0,0,1,0,0,0,1),nrow=3,ncol=3)

    myfunction<-function (N,A,B) {
      return(round(mrdivide((A*B)%*%N,B %*% N)))
    }

    result_matrix<-myfunction(a1,a2,a3)
</code>```

Which gives you the result you stated in the comments.

Body:
I have one program in Matlab that I want translate to a R program.

The matlab program is :

function R = cprob(N,A,B)
    R = ((A.*B)*N)/(B*N)
end

In R, " * " becomes " %*% " and " .* " becomes " * ". And " / "?

Body:
I understand that by "/" you mean a matrix right division.

You can use mrdivide frim the pracma package.  Please take a look at this.

https://www.rdocumentation.org/packages/pracma/versions/1.9.9/topics/mldivide

This would be your code:

    library("pracma")

    a1 = matrix(c(1,2,0,2,5,-1,4,10,-1),nrow=3,ncol=3)
    a2 = matrix(c(1,2,4,2,5,10,0,-1,-1),nrow=3,ncol=3)
    a3=  matrix(c(1,0,0,0,1,0,0,0,1),nrow=3,ncol=3)

    myfunction<-function (N,A,B) {
      return(round(mrdivide((A*B)%*%N,B %*% N)))
    }

    result_matrix<-myfunction(a1,a2,a3)

Which gives you the result you stated in the comments.


问:
mysql and php suddenly case-sensitive?
Basically, I've changed something in my php login code and now when I log in, the MySQL requires that the case matches?!

```<code>    $match = "select * from users where username = '".$username."' and password = '".$password."';";

    echo $match;
</code>```

If my username's CaSe doesn't match the database then it doesn't return any rows.

If a user registers as ADMIN then I want them to be able to log in as "admin" or "AdMiN" etc. any ideas?

Many thanks :)

答:
The collation for that column has changed, I guess. See this MySQL page about case sensitivity in string comparison to learn more. To insulate yourself from problems like that, something like:

```<code>$match = "select * from users where UPPER(username) = '".strtoupper($username)."' and password = '".$password."';";
</code>```

is the usual trick. As others have observed, though, understanding how collation works in the database and using it appropriately is the best solution. Getting the database collation right and relying on it should allow the database to use any index on the username column, rather than scanning the table.

And also make sure that you're avoiding SQL injection attacks -- what happens in your current code if a user enters a username containing a single quote?

You may also want to consider what characters you'll allow as usernames, and what character set you're using -- is "René" a valid username? Will it successfully pass from your front-end, through the database and back out unmolested by character set problems? Joel Spolsky's excellent article on Unicode is probably worth a read at some point.

Title: mysql and php suddenly case-sensitive?

Body:
Basically, I've changed something in my php login code and now when I log in, the MySQL requires that the case matches?!

    $match = "select * from users where username = '".$username."' and password = '".$password."';";

    echo $match;

If my username's CaSe doesn't match the database then it doesn't return any rows.

If a user registers as ADMIN then I want them to be able to log in as "admin" or "AdMiN" etc. any ideas?

Many thanks :)

Body:
The collation for that column has changed, I guess. See this MySQL page about case sensitivity in string comparison to learn more. To insulate yourself from problems like that, something like:

$match = "select * from users where UPPER(username) = '".strtoupper($username)."' and password = '".$password."';";

is the usual trick. As others have observed, though, understanding how collation works in the database and using it appropriately is the best solution. Getting the database collation right and relying on it should allow the database to use any index on the username column, rather than scanning the table.

And also make sure that you're avoiding SQL injection attacks -- what happens in your current code if a user enters a username containing a single quote?

You may also want to consider what characters you'll allow as usernames, and what character set you're using -- is "René" a valid username? Will it successfully pass from your front-end, through the database and back out unmolested by character set problems? Joel Spolsky's excellent article on Unicode is probably worth a read at some point.


问:
Bootstrap Thumbnail issue
I want my caption be inside thumbnail , and that image won't overflow over the caption :

My html:

```<code> <div class="col-lg-4 col-md-4 wow fadeInLeft" data-wow-delay="1.8s">
                        <div class="thumbnail">
                          <a href="http://stoptheworld-iwannagetoff.com/"> <img src="images/stoptheworldxxx.jpg"></a>
                        </div>
                        <a href="http://loll.com/" ><p class="caption text-center">Thumbnail image</p></a>
                    </div>
</code>```

CSS:

```<code>.thumbnail{
           width:100%;
           overflow: hidden;

}

img{
    -webkit-transition:all 0.5s ease;

}

img:hover{
    transform:scale(1.3);opacity:0.6;background-color: blue;

}
</code>```

I tried putting caption above the div tag that closing the thumbnail, but then the image overflows over the caption.

答:
Try:

           Thumbnail image

Title: Bootstrap Thumbnail issue

Body:
I want my caption be inside thumbnail , and that image won't overflow over the caption :

My html:

Thumbnail image

CSS:

.thumbnail{
           width:100%;
           overflow: hidden;

}

img{
    -webkit-transition:all 0.5s ease;

}

img:hover{
    transform:scale(1.3);opacity:0.6;background-color: blue;

}

I tried putting caption above the div tag that closing the thumbnail, but then the image overflows over the caption.

Body:
Try:

<div class="col-lg-4 col-md-4 wow fadeInLeft" data-wow-delay="1.8s">
      <div class="thumbnail">
        <a href="http://stoptheworld-iwannagetoff.com/"> <img src="images/stoptheworldxxx.jpg"></a>
          <div class="caption text-center">
           <a href="http://loll.com/" >Thumbnail image</a>
          </div>
      </div>
</div>


问:
Adding enum on model shows error on initializing different class object
I have added enum on RvDate model as:

```<code>class RvDate < ApplicationRecord
 enum status: { Available: 0, Not_Available: 1 }

 # Associations
 belongs_to :rv

 # Validations
 validates_presence_of :start_date
end
</code>```

But when I run Rv.create on rails console, it shows me the following error:

I have not used enum on Rv model and I do not need one. Is there anything I have missed here?

Rv model looks like this:

```<code>class Rv < ApplicationRecord
 has_many :rv_dates, dependent: :destroy
end
</code>```

Schema for rv_dates

```<code>create_table "rv_dates", force: :cascade do |t|
 t.integer  "rv_id"
 t.date     "start_date"
 t.date     "end_date"
 t.boolean  "availability"
 t.float    "price"
 t.text     "notes"
 t.datetime "created_at",   null: false
 t.datetime "updated_at",   null: false
 t.integer  "status"
 t.index ["rv_id"], name: "index_rv_dates_on_rv_id", using: :btree
end
</code>```

答:
Try using an array instead of a hash, the enum will automatically assign the values, and should allow you to use the helper methods:

```<code>enum status: [
  :available,
  :not_available
]
</code>```

This should allow you to use the helper methods like so:

```<code>RvDate.statuses => { available: 0, not_available: 1 }
some_rv = RvDate.new
some_rv.status = :available
some_rv.available? => true
</code>```

Body:
I have added enum on RvDate model as:

class RvDate < ApplicationRecord
 enum status: { Available: 0, Not_Available: 1 }

 # Associations
 belongs_to :rv

 # Validations
 validates_presence_of :start_date
end

But when I run Rv.create on rails console, it shows me the following error:

I have not used enum on Rv model and I do not need one. Is there anything I have missed here?

Rv model looks like this:

class Rv < ApplicationRecord
 has_many :rv_dates, dependent: :destroy
end

Schema for rv_dates

create_table "rv_dates", force: :cascade do |t|
 t.integer  "rv_id"
 t.date     "start_date"
 t.date     "end_date"
 t.boolean  "availability"
 t.float    "price"
 t.text     "notes"
 t.datetime "created_at",   null: false
 t.datetime "updated_at",   null: false
 t.integer  "status"
 t.index ["rv_id"], name: "index_rv_dates_on_rv_id", using: :btree
end

Body:
Try using an array instead of a hash, the enum will automatically assign the values, and should allow you to use the helper methods:

enum status: [
  :available,
  :not_available
]

This should allow you to use the helper methods like so:

RvDate.statuses => { available: 0, not_available: 1 }
some_rv = RvDate.new
some_rv.status = :available
some_rv.available? => true


问:
grep returns "<regular expression>" No such file or directory
I have the following regular expression to match a phone number. The regular expression works (123)123-123, but I am puzzled by the last result.

```<code>user@host: grep -l -v -f *.txt -E "(\d{3})-\d{3}-\d{3}"
f2.txt
f3.txt
f4.txt
grep: (\d{3})-\d{3}-\d{3}: No such file or directory
</code>```

Why is grep searching the regular expression?

Here is the ls:

```<code>user@host:/tmp# ls
f1.txt  f2.txt  f3.txt  f4.txt
</code>```

答:
The grep usage is

```<code>grep [OPTION]... PATTERN [FILE]...
</code>```

Your command expands to

```<code>grep -l -v -f f1.txt f2.txt f3.txt f4.txt -E "(\d{3})-\d{3}-\d{3}"
</code>```

which is equivalent to

```<code>grep -f f1.txt -l -v -E f2.txt f3.txt f4.txt "(\d{3})-\d{3}-\d{3}"
</code>```

which is "use the file f1.txt as a file containing patterns, and search the files f2.txt, f3.txt, f4.txt and (\d{3})-\d{3}-\d{3}. Apply options -l, -v and -E everywhere."

Maybe you meant

```<code>grep -l -v -E "(\d{3})-\d{3}-\d{3}" *.txt
</code>```

instead?

The relevant part of the man page reads as follows:

-f FILE, --file=FILE

  Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.

Side note: if you use -E, you have to escape literal parentheses. Also, \d is not supported as far as I can tell, so you'd have to use either

```<code>grep -P '\(\d{3}\)-\d{3}-\d{3}'
</code>```

or

```<code>grep -E '\([[:digit:]]{3}\)-[[:digit:]]{3}-[[:digit:]]{3}'
</code>```

Body:
I have the following regular expression to match a phone number. The regular expression works (123)123-123, but I am puzzled by the last result.

user@host: grep -l -v -f *.txt -E "(\d{3})-\d{3}-\d{3}"
f2.txt
f3.txt
f4.txt
grep: (\d{3})-\d{3}-\d{3}: No such file or directory

Why is grep searching the regular expression?

Here is the ls:

user@host:/tmp# ls
f1.txt  f2.txt  f3.txt  f4.txt

Body:
The grep usage is

grep [OPTION]... PATTERN [FILE]...

Your command expands to

grep -l -v -f f1.txt f2.txt f3.txt f4.txt -E "(\d{3})-\d{3}-\d{3}"

which is equivalent to

grep -f f1.txt -l -v -E f2.txt f3.txt f4.txt "(\d{3})-\d{3}-\d{3}"

which is "use the file f1.txt as a file containing patterns, and search the files f2.txt, f3.txt, f4.txt and (\d{3})-\d{3}-\d{3}. Apply options -l, -v and -E everywhere."

Maybe you meant

grep -l -v -E "(\d{3})-\d{3}-\d{3}" *.txt

instead?

The relevant part of the man page reads as follows:

-f FILE, --file=FILE

  Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.

Side note: if you use -E, you have to escape literal parentheses. Also, \d is not supported as far as I can tell, so you'd have to use either

grep -P '\(\d{3}\)-\d{3}-\d{3}'

or

grep -E '\([[:digit:]]{3}\)-[[:digit:]]{3}-[[:digit:]]{3}'


问:
Laravel Dingo API - Only log 500 error, never send error details via api?
I made the below controller to demonstrate the issue of handling 500 errors I am having with dingo api in laravel. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

```<code>class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}
</code>```

This is what the client sees:

In my controllers, I handle errors manually by returning a success/error json response from within the controllers, but if an error occurs that I did not expect, the api returns it and it has too much details for the client to see. Instead, these unexpected errors should bubble up to some sort of handler to return a generic error occurred response. In Laravel, setting APP_DEBUG = false in .env works for laravel (but not for dingo api), this has no effect and the full error is returned to the client. Looking for a safety net for errors that slip through the cracks.

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

答:
If you haven't already done yet, publish dingo config file

```<code>php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
</code>```

Then, open config/api.php and edit the errorFormat value to whatever message you want.

Replace :message with a generic message

Body:
I made the below controller to demonstrate the issue of handling 500 errors I am having with dingo api in laravel. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees:

In my controllers, I handle errors manually by returning a success/error json response from within the controllers, but if an error occurs that I did not expect, the api returns it and it has too much details for the client to see. Instead, these unexpected errors should bubble up to some sort of handler to return a generic error occurred response. In Laravel, setting APP_DEBUG = false in .env works for laravel (but not for dingo api), this has no effect and the full error is returned to the client. Looking for a safety net for errors that slip through the cracks.

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'

Body:
If you haven't already done yet, publish dingo config file

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

Then, open config/api.php and edit the errorFormat value to whatever message you want.

Replace :message with a generic message


问:
nodejs 3des decrypt didn't get expected result
My nodejs 3DES decryption didn't get expected result. Is there anything wrong with my code?

```<code>let cryptojs = require('crypto-js')
var key = '551408C3D129EC64DA505CB48CD61D57551408C3D129EC64';
var ciphertext = 'C5F21F0F82038833851BA3092D613F085A60DB1E189E10F6';
var iv = cryptojs.enc.Hex.parse("0".repeat(16));

key = cryptojs.enc.Hex.parse(key);
var result = cryptojs.TripleDES.decrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
console.log ('decrypted ' + result.toString(cryptojs.enc.Hex));
</code>```

result is '90d49e1085d5251f87dbcd6292570ba30e8a6e0f84d8331c97a579ef0ba6ac867342f2f6'

however expected result should be '466F0198321458864627662057083A457601185220050000'

答:
You said you were trying to decrypt the data, but you encrypted it:</p>

```<code>var result = cryptojs.TripleDES.encrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
</code>```

Body:
My nodejs 3DES decryption didn't get expected result. Is there anything wrong with my code?

let cryptojs = require('crypto-js')
var key = '551408C3D129EC64DA505CB48CD61D57551408C3D129EC64';
var ciphertext = 'C5F21F0F82038833851BA3092D613F085A60DB1E189E10F6';
var iv = cryptojs.enc.Hex.parse("0".repeat(16));

key = cryptojs.enc.Hex.parse(key);
var result = cryptojs.TripleDES.decrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});
console.log ('decrypted ' + result.toString(cryptojs.enc.Hex));

result is '90d49e1085d5251f87dbcd6292570ba30e8a6e0f84d8331c97a579ef0ba6ac867342f2f6'

however expected result should be '466F0198321458864627662057083A457601185220050000'

Body:
You said you were trying to decrypt the data, but you encrypted it:

var result = cryptojs.TripleDES.encrypt(ciphertext, key, {iv: iv, mode: cryptojs.mode.CBC, padding: cryptojs.pad.NoPadding});


问:
Authentication method calling problem on iPhone
When I have established SSL connection with NSURLConnection, I need to change certificates in credentials to make new request. But when I make new request, canAuthenticateAgainstProtectionSpace method don't fires and request use credentials which were setted to previous request. I've already tried to add '#' to the end of the URL, clear cookies,  but nothing works.</p>

答: The thing is that those methods from protocol fires only once for the first request and for next requests not.</p>


问:
Display content only on child-page
I'm trying to change the header only on the child pages of the page id=261.
I wanna display a text above the menu only on those.

I was thinking in something like <?php if(is_page('page name')){ ?>

 <?php } ?>

But I'm not sure how to check if page is a child of page 261.

```<code>    <header class="site-header no-fixed-header">
            <div class="bnt-container">

                <?php mobile_menu(); ?>

                <?php logo(); ?>

                <div class="text-above">Menu title child pages</div>

                <?php primary_menu(); ?>

            </div>
        </header>
</code>```

答:
use $post->post_parent to check if the current page parent id is 261

```<code>if ( '261' == $post->post_parent ) {
    do some thing
 }
</code>```

for more info see this

Title: Display content only on child-page

Body:
I'm trying to change the header only on the child pages of the page id=261.
I wanna display a text above the menu only on those.

I was thinking in something like <?php if(is_page('page name')){ ?>

 <?php } ?>

But I'm not sure how to check if page is a child of page 261.

                <?php mobile_menu(); ?>

                <?php logo(); ?>

Menu title child pages

                <?php primary_menu(); ?>

Body:
use $post->post_parent to check if the current page parent id is 261

if ( '261' == $post->post_parent ) {
    do some thing
 }

for more info see this


问:
using rand() in a function in c
I have made a function that creates a random number between 0 and 9 but when i call the function in main in a for loop with index i = 0 ; i < n ; i++ it prints 1 random number n types. but i want different values to be printed n times.
here is the code which i made :-

```<code>    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
     int i;
     srand(time(NULL));
     i = rand()%10;
     printf("%d ",i);
    }
    main() {
     for(int j=0;j<10;j++) {
      random_variable();
     }
    }
</code>```

output is this :-

please click on the link to see the output :-
here instead of 8 ten times i needed 10 different values

答:
srand() seeds your random numbers. You want to do this once, not every time.

```<code>    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
       int i;
       i = rand()%10;
       printf("%d ",i);
    }
    main() {
       srand(time(NULL));
       for(int j=0;j<10;j++) {
          random_variable();
       }
    }
</code>```

Title: using rand() in a function in c

Body:
I have made a function that creates a random number between 0 and 9 but when i call the function in main in a for loop with index i = 0 ; i < n ; i++ it prints 1 random number n types. but i want different values to be printed n times.
here is the code which i made :-

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
     int i;
     srand(time(NULL));
     i = rand()%10;
     printf("%d ",i);
    }
    main() {
     for(int j=0;j<10;j++) {
      random_variable();
     }
    }

output is this :-

please click on the link to see the output :-
here instead of 8 ten times i needed 10 different values

Body:
srand() seeds your random numbers. You want to do this once, not every time.

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
       int i;
       i = rand()%10;
       printf("%d ",i);
    }
    main() {
       srand(time(NULL));
       for(int j=0;j<10;j++) {
          random_variable();
       }
    }