问:
MCMC Sampling a Maxwellian Curve Using Python's emcee
I am trying to introduce myself to MCMC sampling with emcee. I want to simply take a sample from a Maxwell Boltzmann distribution using a set of example code on github, https://github.com/dfm/emcee/blob/master/examples/quickstart.py.

The example code is really excellent, but when I change the distribution from a Gaussian to a Maxwellian, I receive the error, TypeError: lnprob() takes exactly 2 arguments (3 given)

However it is not called anywhere where it is not given the appropriate parameters? In need of some guidance as to how to define a Maxwellian Curve and have it fit into this example code.

Here is what I have;

```<code>    from __future__ import print_function
import numpy as np
import emcee

try:
    xrange
except NameError:
    xrange = range
def lnprob(x, a, icov):
    pi = np.pi
    return np.sqrt(2/pi)*x**2*np.exp(-x**2/(2.*a**2))/a**3

ndim = 2
means = np.random.rand(ndim)

cov  = 0.5-np.random.rand(ndim**2).reshape((ndim, ndim))
cov  = np.triu(cov)
cov += cov.T - np.diag(cov.diagonal())
cov  = np.dot(cov,cov)

icov = np.linalg.inv(cov)

nwalkers = 50

p0 = [np.random.rand(ndim) for i in xrange(nwalkers)]

sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[means, icov])

pos, prob, state = sampler.run_mcmc(p0, 5000)

sampler.reset()

sampler.run_mcmc(pos, 100000, rstate0=state)
</code>```

Thanks

答:
I think there are a couple of problems that I see. The main one is that emcee wants you to give it the natural logarithm of the probability distribution function that you want to sample. So, rather than having:

```<code>def lnprob(x, a, icov):
    pi = np.pi
    return np.sqrt(2/pi)*x**2*np.exp(-x**2/(2.*a**2))/a**3
</code>```

you would instead want, e.g.

```<code>def lnprob(x, a):
    pi = np.pi
    if x < 0:
        return -np.inf
    else:
        return 0.5*np.log(2./pi) + 2.*np.log(x) - (x**2/(2.*a**2)) - 3.*np.log(a)
</code>```

where the if...else... statement is to explicitly say that negative values of x have zero probability (or -infinity in log-space).

You also shouldn't have to calculate icov and pass it to lnprob as that's only needed for the Gaussian case in the example you link to.

When you call:

```<code>sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[means, icov])
</code>```

the args value should just be any additional arguments that your lnprob function requires, so in your case this would be the value of a that you want to set your Maxwell-Boltxmann distribution up with. This should be a single value rather than the two randomly initialised values you have set when creating mean.

Overall, the following should work for you:

```<code>from __future__ import print_function

import emcee
import numpy as np
from numpy import pi as pi

# define the natural log of the Maxwell-Boltzmann distribution
def lnprob(x, a):
    if x < 0:
        return -np.inf
    else:
        return 0.5*np.log(2./pi) + 2.*np.log(x) - (x**2/(2.*a**2)) - 3.*np.log(a)

# choose a value of 'a' for the distributions
a = 5. # I'm choosing 5!

# choose the number of walkers
nwalkers = 50

# set some initial points at which to calculate the lnprob
p0 = [np.random.rand(1) for i in xrange(nwalkers)]

# initialise the sampler
sampler = emcee.EnsembleSampler(nwalkers, 1, lnprob, args=[a])

# Run 5000 steps as a burn-in.
pos, prob, state = sampler.run_mcmc(p0, 5000)

# Reset the chain to remove the burn-in samples.
sampler.reset()

# Starting from the final position in the burn-in chain, sample for 100000 steps.
sampler.run_mcmc(pos, 100000, rstate0=state)

# lets check the samples look right
mbmean = 2.*a*np.sqrt(2./pi) # mean of Maxwell-Boltzmann distribution
print("Sample mean = {}, analytical mean = {}".format(np.mean(sampler.flatchain[:,0]), mbmean))
mbstd = np.sqrt(a**2*(3*np.pi-8.)/np.pi) # std. dev. of M-B distribution
print("Sample standard deviation = {}, analytical = {}".format(np.std(sampler.flatchain[:,0]), mbstd))
</code>```

Body:
I am trying to introduce myself to MCMC sampling with emcee. I want to simply take a sample from a Maxwell Boltzmann distribution using a set of example code on github, https://github.com/dfm/emcee/blob/master/examples/quickstart.py.

The example code is really excellent, but when I change the distribution from a Gaussian to a Maxwellian, I receive the error, TypeError: lnprob() takes exactly 2 arguments (3 given)

However it is not called anywhere where it is not given the appropriate parameters? In need of some guidance as to how to define a Maxwellian Curve and have it fit into this example code.

Here is what I have;

    from __future__ import print_function
import numpy as np
import emcee

try:
    xrange
except NameError:
    xrange = range
def lnprob(x, a, icov):
    pi = np.pi
    return np.sqrt(2/pi)*x**2*np.exp(-x**2/(2.*a**2))/a**3

ndim = 2
means = np.random.rand(ndim)

cov  = 0.5-np.random.rand(ndim**2).reshape((ndim, ndim))
cov  = np.triu(cov)
cov += cov.T - np.diag(cov.diagonal())
cov  = np.dot(cov,cov)

icov = np.linalg.inv(cov)

nwalkers = 50

p0 = [np.random.rand(ndim) for i in xrange(nwalkers)]

sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[means, icov])

pos, prob, state = sampler.run_mcmc(p0, 5000)

sampler.reset()

sampler.run_mcmc(pos, 100000, rstate0=state)

Thanks

Body:
I think there are a couple of problems that I see. The main one is that emcee wants you to give it the natural logarithm of the probability distribution function that you want to sample. So, rather than having:

def lnprob(x, a, icov):
    pi = np.pi
    return np.sqrt(2/pi)*x**2*np.exp(-x**2/(2.*a**2))/a**3

you would instead want, e.g.

def lnprob(x, a):
    pi = np.pi
    if x < 0:
        return -np.inf
    else:
        return 0.5*np.log(2./pi) + 2.*np.log(x) - (x**2/(2.*a**2)) - 3.*np.log(a)

where the if...else... statement is to explicitly say that negative values of x have zero probability (or -infinity in log-space).

You also shouldn't have to calculate icov and pass it to lnprob as that's only needed for the Gaussian case in the example you link to.

When you call:

sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[means, icov])

the args value should just be any additional arguments that your lnprob function requires, so in your case this would be the value of a that you want to set your Maxwell-Boltxmann distribution up with. This should be a single value rather than the two randomly initialised values you have set when creating mean.

Overall, the following should work for you:

from __future__ import print_function

import emcee
import numpy as np
from numpy import pi as pi

# define the natural log of the Maxwell-Boltzmann distribution
def lnprob(x, a):
    if x < 0:
        return -np.inf
    else:
        return 0.5*np.log(2./pi) + 2.*np.log(x) - (x**2/(2.*a**2)) - 3.*np.log(a)

# choose a value of 'a' for the distributions
a = 5. # I'm choosing 5!

# choose the number of walkers
nwalkers = 50

# set some initial points at which to calculate the lnprob
p0 = [np.random.rand(1) for i in xrange(nwalkers)]

# initialise the sampler
sampler = emcee.EnsembleSampler(nwalkers, 1, lnprob, args=[a])

# Run 5000 steps as a burn-in.
pos, prob, state = sampler.run_mcmc(p0, 5000)

# Reset the chain to remove the burn-in samples.
sampler.reset()

# Starting from the final position in the burn-in chain, sample for 100000 steps.
sampler.run_mcmc(pos, 100000, rstate0=state)

# lets check the samples look right
mbmean = 2.*a*np.sqrt(2./pi) # mean of Maxwell-Boltzmann distribution
print("Sample mean = {}, analytical mean = {}".format(np.mean(sampler.flatchain[:,0]), mbmean))
mbstd = np.sqrt(a**2*(3*np.pi-8.)/np.pi) # std. dev. of M-B distribution
print("Sample standard deviation = {}, analytical = {}".format(np.std(sampler.flatchain[:,0]), mbstd))


来源: stackexchange

问:
c program to find average
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

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

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}
</code>```

output

```<code>3
1
-2
0
0.000000
0.000000
0.000000
</code>```

the last three numbers should be .3,.3,.3 but it is giving zeros.

答:
Since both sum1 and n are integers, the result of sum1/n is also an integer.  This means that if sum1 is less than n, then the result of sum1 / n is 0.

To get a floating point result, at least one of the operands has be be float or double.  I suggest you declare your sum variables to be double instead of int.

ContentLicense: CC BY-SA 3.0

Title: c program to find average

Body:
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

#include <math.h>
#include <stdio.h>

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}

output

3
1
-2
0
0.000000
0.000000
0.000000

the last three numbers should be .3,.3,.3 but it is giving zeros.


问:
How to return the getText() values in array using protractor
I'm trying to return the options present in the list using the below function.

HTML

```<code><select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>
</code>```

Function

```<code>getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });
</code>```

}

When I print the values in console using console.log(getValues()), the console displays theManagedPromise{.....} function instead of options.

But I'm expecting the options as ["one","two","three"] array. Can anyone help me?

答:
The most elegant way is to use .map().
See the documentation.

The only thing you need to remember is that .map() returns A promise that resolves to an array of values returned by the map function.

Body:
I'm trying to return the options present in the list using the below function.

HTML

<select>
  <option>one</option>
  <option>two</option>
  <option>three</option>
<select>

Function

getValues(){
  var ele = element(by.xpath("......../select"));
  return ele.all(by.tagName('option')).getAttribute('value').getText().then(function (text){
  for (var i = 0; i < text.length; i++) {
    text[i] = text[i].trim();
  }
  return text;
 });

}

When I print the values in console using console.log(getValues()), the console displays theManagedPromise{.....} function instead of options.

But I'm expecting the options as ["one","two","three"] array. Can anyone help me?


问:
How to update the Node.js in windows
After I upgraded the ionic CLI, I have error when I do a ionic serve.

The error is

```<code>ERR: Your Node.js version is v5.11.1. Please update to the latest Node 6 LTS version (or latest Node).
</code>```

What is the command that I can upgrade to Node 6 LTS without redownload the Node.js installer?

答:
Use NVM Windows Version (Node Version Manager) - be aware its a separate version from Mac / Linux

https://github.com/coreybutler/nvm-windows

More info you can check out this one :

How do I update Node.js?

```<code>nvm install node
</code>```

Title: How to update the Node.js in windows

Body:
After I upgraded the ionic CLI, I have error when I do a ionic serve.

The error is

ERR: Your Node.js version is v5.11.1. Please update to the latest Node 6 LTS version (or latest Node).

What is the command that I can upgrade to Node 6 LTS without redownload the Node.js installer?

Body:
Use NVM Windows Version (Node Version Manager) - be aware its a separate version from Mac / Linux

https://github.com/coreybutler/nvm-windows

More info you can check out this one :

How do I update Node.js?

nvm install node


问:
Ajax acting weirdly
so I have this simple ajax request to see if a combination of username or password exists or not.

```<code><script>
  $("form").submit(function(e){
    e.preventDefault();
    //send data to ajax file now
    $.ajax({
            type: 'POST',
            url: 'ajax_handler.php',
            data: $(this).serialize(),
            success: function (result) {
              alert(result);
            }
           });

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

ajax_handler.php file

```<code>$email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    echo "check";
</code>```

After hitting submit, the ajax request runs and alert(result) alerts the entire HTML/CSS coding of the page where my

答:
You need to stop the PHP script from executing the rest of the page loaded.

You can do this by using exit() or die().

```<code>$email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    echo "check";
    die();
</code>```

Title: Ajax acting weirdly

Body:
so I have this simple ajax request to see if a combination of username or password exists or not.

ajax_handler.php file

$email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    echo "check";

After hitting submit, the ajax request runs and alert(result) alerts the entire HTML/CSS coding of the page where my

Body:
You need to stop the PHP script from executing the rest of the page loaded.

You can do this by using exit() or die().

$email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    echo "check";
    die();


问:
Loading Mongo Driver 1.6.x driver on WAMP 64bit architecture
So I've installed 64bit Apache/PHP locally. Both Apache and PHP were compiled against the VC11 C++ redistributable.

https://www.apachelounge.com/download/VC11/ and

http://windows.php.net/download/ PHP5.6 (Yes... ) x64 Thread Safe (respectively)

Both work fine! (screenshots with version and architecture info inc.)

I've downloaded multiple varaities of the 1.6.x driver from both PECL and an repo' at Amazon.

https://pecl.php.net/package/mongo/1.6.14/windows

https://s3.amazonaws.com/drivers.mongodb.org/php/index.html

I've made sure they're the x64 Thread Safe variety and added to my ~/php/ext folder.

I've made sure the extension is loaded in php.ini (and that the write .ini file is called):
extension=php_mongo-1.6.8-5.6-vc11-x86_64.dll

But everytime I restart Apache I get this in my PHP error log:

[07-Jun-2017 20:21:20 UTC] PHP Warning:  PHP Startup: Unable to load dynamic library 'E:\PHP5.6\ext\php_mongo-1.6.8-5.6-vc11-x86_64.dll' - %1 is not a valid Win32 application.

(Apache comes up clean. Error.log clean)

Why is it protesting that this is not a Win32 Application. I don't want it to be. My entire architecture is 64bit and so is the Mongo Driver.

答:
It is possible that a dependency is missing. Where I suspect that to be libsasl as alluded to in the comment at http://php.net/manual/en/mongodb.requirements.php

The libsasl.dll can be found in the PHP distribution.


问:
Do I use NgFor or NgForOf?
In the angular API documentation it says to use NgForOf instead of NgFor with version 4.0 onwards. But the Fundamentals, and Heroes tutorial, documentation demonstrateNgFor, and make no mention of NgForOf.

Is there anyone who can clarify  this for me? Thank you in advance.

答: ngForOf is the name of the class that implements the *ngFor directive. Its was the class type that changed (from ngFor to ngForOf) not the directive itself. So in our templates we still use *ngFor.</p>

Title: Do I use NgFor or NgForOf?


问:
How to create C# string object inside .ps1 file
The below C# snippet is embedded in a powershell (.ps1) file and generated an System.Management.Automation.RuntimeException. Removing "string s" and the exception goes away. Tried to use uppercase "String" and tried to add namespace "System.String" and various other approaches but still get the exception. This is driving me nuts, please help me understand why this is happening.

```<code>$code = @"
public static class foo
{
  public static bool check()
  {
    string s;
    return false;
  }
}
</code>```

Code is invoked like this;

```<code>try
{
  Add-Type -TypeDefinition $code -Language CSharp
}
catch{} // ignore TYPE_ALREADY_EXISTS exception
$res = [foo]::check();
</code>```

Here is exception details;

```<code>Exception: System.Management.Automation.RuntimeException: unable to find type [foo].
TargetObject: foo
CategoryInfo: InvalidOperation (foo:Typename) [], RuntimeException
FullyQualifiedErrorId: TypeNotFound
InvocationInfo: System.Management.Automation.InvocationInfo
</code>```

答:
```<code>$code = @"
public static class foo {
  public static bool check() {
    string s;
    return false;
  }
}
"@

Add-Type -TypeDefinition $code -Language CSharp
</code>```

produces

Warning as Error: The variable 's' is declared but never used

It will not allow you to declare unused variables.

Body:
The below C# snippet is embedded in a powershell (.ps1) file and generated an System.Management.Automation.RuntimeException. Removing "string s" and the exception goes away. Tried to use uppercase "String" and tried to add namespace "System.String" and various other approaches but still get the exception. This is driving me nuts, please help me understand why this is happening.

$code = @"
public static class foo
{
  public static bool check()
  {
    string s;
    return false;
  }
}

Code is invoked like this;

try
{
  Add-Type -TypeDefinition $code -Language CSharp
}
catch{} // ignore TYPE_ALREADY_EXISTS exception
$res = [foo]::check();

Here is exception details;

Exception: System.Management.Automation.RuntimeException: unable to find type [foo].
TargetObject: foo
CategoryInfo: InvalidOperation (foo:Typename) [], RuntimeException
FullyQualifiedErrorId: TypeNotFound
InvocationInfo: System.Management.Automation.InvocationInfo

Body:
$code = @"
public static class foo {
  public static bool check() {
    string s;
    return false;
  }
}
"@

Add-Type -TypeDefinition $code -Language CSharp

produces

Warning as Error: The variable 's' is declared but never used

It will not allow you to declare unused variables.


问:
unwanted keys in JSON object
hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object

```<code> var bankdata = data;
    var updatebankdata = {}
    for (var key in bankdata) {
        var id = +key.substr(key.length - 1);

        if (isNaN(id)) {
            updatebankdata[0] = updatebankdata[0] || {};
            updatebankdata[0][key] = bankdata[key];
        } else {
            var uniqid=$("#bankaccount"+id).attr("uniq_id");
            updatebankdata[id] = updatebankdata[id] || {};
            var field = key.substring(0, key.length - 1);
            updatebankdata[id][field] = bankdata[key];
            updatebankdata[id]["uniquid"] = uniquid;
        }
    }
    return updatebankdata;
}
</code>```

my bank data is like

{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}

i want to change it into  like this way

[{bankname1: "new", micrcode1: "mkkk", comments1:
  "commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]

but still it getting like this .its not good

{"0":{bankname1: "new", micrcode1: "mkkk", comments1:

"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}

what is the mistake in my code?

答:
assign

var updatebankdata = [];

then push your object to array like this

updatebankdata.push(yourObject)

Title: unwanted keys in JSON object

Body:
hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object

 var bankdata = data;
    var updatebankdata = {}
    for (var key in bankdata) {
        var id = +key.substr(key.length - 1);

        if (isNaN(id)) {
            updatebankdata[0] = updatebankdata[0] || {};
            updatebankdata[0][key] = bankdata[key];
        } else {
            var uniqid=$("#bankaccount"+id).attr("uniq_id");
            updatebankdata[id] = updatebankdata[id] || {};
            var field = key.substring(0, key.length - 1);
            updatebankdata[id][field] = bankdata[key];
            updatebankdata[id]["uniquid"] = uniquid;
        }
    }
    return updatebankdata;
}

my bank data is like

{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}

i want to change it into  like this way

[{bankname1: "new", micrcode1: "mkkk", comments1:
  "commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]

but still it getting like this .its not good

{"0":{bankname1: "new", micrcode1: "mkkk", comments1:

"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}

what is the mistake in my code?


问:
Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
I have some bash scripts I have been running on Ubuntu 14.04 and 16.04 for well over a year now. Some recent Ubuntu update has broken bash and I cannot figure out how to sort this out.

Example:

```<code>#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"

cat $INPUT | while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done
</code>```

my script then loops through the file doing the printf statement as follows but this is the output produced

```<code>"~jetmo" 0;
"~spamme" 0;
"~baidu" 0;
</code>```

example contents of myinput.txt

```<code>jetmon
spammen
baidu
</code>```

Input lines containing a lowercase n character gets stripped out ??
Am I missing some major change in bash that occured, this started happening a week ago and is driving me insane now.

I have tried changing #!/bin/bash to #!/bin/sh with same results.

Also tried this method of looping through the input file and still get the same results.

```<code>#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"
while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done < $INPUT
</code>```

Tried suggestion from comments using echo

```<code>echo -e -n "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
</code>```

and now I get this output

```<code>-e -n "~jetmo" 0;
-e -n "~spamme" 0;
-e -n "~baidu" 0;
</code>```

Running hexdump -C myinput.txt gives this output

```<code>00000000  6a 65 74 6d 6f 6e 0a 73  70 61 6d 6d 65 6e 0a 62  |jetmon.spammen.b|
00000010  61 69 64 75 0a 0a                                 |aidu..|
00000016
</code>```

Also changed all variable names to lowercase as suggested by Michael but still getting the same results.

```<code>#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"

cat $input | while read line
do
printf "\t\"~${line}\"\t\t$action1\n" >> $output
done
</code>```

THE SOLUTION
The Mystery is Solved

thanks to everyone, but https://stackoverflow.com/users/96588/l0b0 nailed it on the head. I had an IFS=$'\n' hiding earlier on in my script.

I now have this final, better and safer formatting of printf thanks to the recommendations of Nahuel and Charles and it is working 100% ... cannot thank you all enough.

```<code>#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"
while IFS= read -r LINE
do
printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$output"
done < $input1
</code>```

Body:
I have some bash scripts I have been running on Ubuntu 14.04 and 16.04 for well over a year now. Some recent Ubuntu update has broken bash and I cannot figure out how to sort this out.

Example:

#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"

cat $INPUT | while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done

my script then loops through the file doing the printf statement as follows but this is the output produced

"~jetmo" 0;
"~spamme" 0;
"~baidu" 0;

example contents of myinput.txt

jetmon
spammen
baidu

Input lines containing a lowercase n character gets stripped out ??
Am I missing some major change in bash that occured, this started happening a week ago and is driving me insane now.

I have tried changing #!/bin/bash to #!/bin/sh with same results.

Also tried this method of looping through the input file and still get the same results.

#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"
while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done < $INPUT

Tried suggestion from comments using echo

echo -e -n "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT

and now I get this output

-e -n "~jetmo" 0;
-e -n "~spamme" 0;
-e -n "~baidu" 0;

Running hexdump -C myinput.txt gives this output

00000000  6a 65 74 6d 6f 6e 0a 73  70 61 6d 6d 65 6e 0a 62  |jetmon.spammen.b|
00000010  61 69 64 75 0a 0a                                 |aidu..|
00000016

Also changed all variable names to lowercase as suggested by Michael but still getting the same results.

#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"

cat $input | while read line
do
printf "\t\"~${line}\"\t\t$action1\n" >> $output
done

THE SOLUTION
The Mystery is Solved

thanks to everyone, but https://stackoverflow.com/users/96588/l0b0 nailed it on the head. I had an IFS=$'\n' hiding earlier on in my script.

I now have this final, better and safer formatting of printf thanks to the recommendations of Nahuel and Charles and it is working 100% ... cannot thank you all enough.

#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"
while IFS= read -r LINE
do
printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$output"
done < $input1


问:
Convert method to Delegate?
I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

```<code>using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}
</code>```

答:
Your code calls MessageBox.Show, then tries to pass the result to TryDo.

Since MessageBox.Show doesn't return a Delegate, that won't work.

Instead, you should pass the Show method itself, along with a parameter:

```<code>TryDo.Do(new Func<string, DialogResult>(MessageBox.Show), "");
</code>```

Alternatively, you can pass an anonymous method that calls the function:

```<code>TryDo.Do(new Action(() => MessageBox.Show("")));
</code>```

Note that your function will perform faster if you make generic overloads that take Funcs and Actions instead of taking a Delegate and calling DynamicInvoke.

ContentLicense: CC BY-SA 2.5

Title: Convert method to Delegate?

Body:
I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}

Body:
Your code calls MessageBox.Show, then tries to pass the result to TryDo.

Since MessageBox.Show doesn't return a Delegate, that won't work.

Instead, you should pass the Show method itself, along with a parameter:

TryDo.Do(new Func<string, DialogResult>(MessageBox.Show), "");

Alternatively, you can pass an anonymous method that calls the function:

TryDo.Do(new Action(() => MessageBox.Show("")));

Note that your function will perform faster if you make generic overloads that take Funcs and Actions instead of taking a Delegate and calling DynamicInvoke.


问:
Flask-restful API Authorization. Access current_identity inside decorator
I use flask-restful to create my APIs. I have used flask-jwt for enabling authentication based on JWT. Now I need to do authorization.

I have tried putting my authorization decorator.

test.py (/test api)

```<code>from flask_restful import Resource
from flask_jwt import jwt_required

from authorization_helper import authorized_api_user_type

class Test(Resource):

    decorators = [jwt_required(), authorized_api_user_type()]

    def get(self):
        return 'GET OK'

    def post(self):
        return 'POST OK'
</code>```

Basically to handle the basic authorization, I need to access current_identity and check it's type. Then based on it's type I am gonna decide whether the user is authorized to access the api / resources.

But current_identity appears to be empty in that decorator. So to get it indirectly, I had to see the code of jwt_handler and do the things done there.

authorization_helper.py

```<code>from functools import wraps
from flask_jwt import _jwt, JWTError
import jwt
from models import Teacher, Student

def authorized_api_user_type(realm=None, user_type='teacher'):
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            token = _jwt.request_callback()

            if token is None:
                raise JWTError('Authorization Required', 'Request does not contain an access token',
                               headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})

            try:
                payload = _jwt.jwt_decode_callback(token)
            except jwt.InvalidTokenError as e:
                raise JWTError('Invalid token', str(e))

            identity = _jwt.identity_callback(payload)
            if user_type == 'student' and isinstance(identity, Student):
                return fn(*args, **kwargs)
            elif user_type == 'teacher' and isinstance(identity, Teacher):
                return fn(*args, **kwargs)
            # NOTE - By default JWTError throws 401. We needed 404. Hence status_code=404
            raise JWTError('Unauthorized',
                           'You are unauthorized to request the api or access the resource',
                           status_code=404)
        return decorator
    return wrapper
</code>```

Why can't I just access current_identity in my authorized_api_user_type decorator? What is the RIGHT way of doing authorization in flask-restful?

答:
Use this:</p>

```<code>from flask_jwt import current_identity
@jwt_required()
def get(self):
    return {'current_identity': current_identity.json()}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I use flask-restful to create my APIs. I have used flask-jwt for enabling authentication based on JWT. Now I need to do authorization.

I have tried putting my authorization decorator.

test.py (/test api)

from flask_restful import Resource
from flask_jwt import jwt_required

from authorization_helper import authorized_api_user_type

class Test(Resource):

    decorators = [jwt_required(), authorized_api_user_type()]

    def get(self):
        return 'GET OK'

    def post(self):
        return 'POST OK'

Basically to handle the basic authorization, I need to access current_identity and check it's type. Then based on it's type I am gonna decide whether the user is authorized to access the api / resources.

But current_identity appears to be empty in that decorator. So to get it indirectly, I had to see the code of jwt_handler and do the things done there.

authorization_helper.py

from functools import wraps
from flask_jwt import _jwt, JWTError
import jwt
from models import Teacher, Student

def authorized_api_user_type(realm=None, user_type='teacher'):
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            token = _jwt.request_callback()

            if token is None:
                raise JWTError('Authorization Required', 'Request does not contain an access token',
                               headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})

            try:
                payload = _jwt.jwt_decode_callback(token)
            except jwt.InvalidTokenError as e:
                raise JWTError('Invalid token', str(e))

            identity = _jwt.identity_callback(payload)
            if user_type == 'student' and isinstance(identity, Student):
                return fn(*args, **kwargs)
            elif user_type == 'teacher' and isinstance(identity, Teacher):
                return fn(*args, **kwargs)
            # NOTE - By default JWTError throws 401. We needed 404. Hence status_code=404
            raise JWTError('Unauthorized',
                           'You are unauthorized to request the api or access the resource',
                           status_code=404)
        return decorator
    return wrapper

Why can't I just access current_identity in my authorized_api_user_type decorator? What is the RIGHT way of doing authorization in flask-restful?

Body:
Use this:

from flask_jwt import current_identity
@jwt_required()
def get(self):
    return {'current_identity': current_identity.json()}


问:
Flexbox: Header, centered body and sticky footer overflow
Update This has been solved thanks to LGSon's comment below Updated codepen

I am trying to setup a layout much like the Holy grail. The difference here is that I am looking for a dynamically sized "Content" section to be vertically and horizontally centered.

I have been able to get this working (for large displays) with flexbox: Codepen here

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

.header {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  height: calc(100% - 120px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 0, 0.5);
}
.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="footer">
    Footer
</div></code>```

The problem is that if the "Content" section is too large, or the view is too small, the overflow wont kick in until the div is more than 100% vertical not (100% height - the header and footer heights)

I am trying to make it so that when there is overlap, that the whole page will scroll and not only have a scrollbar within the "Content section".

答:
If you change your html, body rule to this

```<code>html, body {
  margin: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
}
</code>```

and then add this new rule

```<code>body {
  min-height: 100vh;
}
</code>```

and then change from height: calc(100% - 120px); to flex-grow: 1; in your content rule it will work as you asked for.

The trick here is to make your body a flex container, and then, by setting the content to flex-grow: 1 it will fill the remaining space when the content is smaller, and the min-height: 100vh will allow it to properly grow higher than the viewport when the content is bigger.

Updated codepen

Stack snippet

html, body {
  margin: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
}

body {
  min-height: 100vh;
}

.header {
  height: 60px;
  line-height: 60px;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 0, 0.5);
}

.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 </p>
</div>

<div class="footer">
    Footer
</div></code>```

And if someone want to enable the content to scroll instead of the whole page, change the body rule to height: 100vh and  add overflow: auto to the content rule

Updated codepen

Stack snippet

html, body {
  margin: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
}

body {
  height: 100vh;
}

.header {
  height: 60px;
  line-height: 60px;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(0, 255, 0, 0.5);
  overflow: auto;
}

.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 </p>
</div>

<div class="footer">
    Footer
</div></code>```

Body:
Update This has been solved thanks to LGSon's comment below Updated codepen

I am trying to setup a layout much like the Holy grail. The difference here is that I am looking for a dynamically sized "Content" section to be vertically and horizontally centered.

I have been able to get this working (for large displays) with flexbox: Codepen here

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
}

.header {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  height: calc(100% - 120px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 0, 0.5);
}
.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  width: 100%;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}

    Header

I am the content

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    Footer

The problem is that if the "Content" section is too large, or the view is too small, the overflow wont kick in until the div is more than 100% vertical not (100% height - the header and footer heights)

I am trying to make it so that when there is overlap, that the whole page will scroll and not only have a scrollbar within the "Content section".

Body:
If you change your html, body rule to this

html, body {
  margin: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
}

and then add this new rule

body {
  min-height: 100vh;
}

and then change from height: calc(100% - 120px); to flex-grow: 1; in your content rule it will work as you asked for.

The trick here is to make your body a flex container, and then, by setting the content to flex-grow: 1 it will fill the remaining space when the content is smaller, and the min-height: 100vh will allow it to properly grow higher than the viewport when the content is bigger.

Updated codepen

Stack snippet

html, body {
  margin: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
}

body {
  min-height: 100vh;
}

.header {
  height: 60px;
  line-height: 60px;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 255, 0, 0.5);
}

.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}

<div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 </p>
</div>

<div class="footer">
    Footer
</div>

And if someone want to enable the content to scroll instead of the whole page, change the body rule to height: 100vh and  add overflow: auto to the content rule

Updated codepen

Stack snippet

html, body {
  margin: 0;
  text-align: center;
  display: flex;
  flex-direction: column;
}

body {
  height: 100vh;
}

.header {
  height: 60px;
  line-height: 60px;
  background: rgba(255, 0, 0, 0.5);
}

.content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(0, 255, 0, 0.5);
  overflow: auto;
}

.content p {
  width: 50%;
}

.footer {
  height: 60px;
  line-height: 60px;
  background: rgba(0, 0, 255, 0.5);
}

.header, .footer {
  font-weight: bold;
}

<div class="header">
    Header
</div>

<div class="content">
    <h1>I am the content</h1>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
 </p>
</div>

<div class="footer">
    Footer
</div>


问:
Saving memory address content in C Array
I'm implementing a delay in C code for audio.
I have a memory address where I receive the audio sample. And another memory address which indicates where a new sample appears.

What I am trying to do is record the first audio second (48000 samples). In order to do so I'm declaring an array where I save the audio samples.

In the main loop I make a sum of the actual sample and the delayed (1 second ago) sample, it's quite similar to an echo what I want to achieve.

The problem is that my code reproduces the actual sound, but not the delayed, in fact, I can heard a little noise every second, so I guess it only reads the first sample of the array, and the rest is empty.

I have analyzed my code, but I don't know where my failure is. I think it may be related with memory allocation, but I'm not very familiarized with C language. Could you please help me?

```<code>#define au_in (volatile short *) 0x0081050  //Input memory address
#define au_out (volatile short *) 0x0081040
#define samp_rdy (volatile int *) 0x0081030 //Indicates if a new sample is ready

/* REPLAY */
void main(){
    short *buff[48000];
    int i=0;
    while(i<48000){
        if((*(samp_rdy + 0x3)==0x1)){ //If there's a new sample
            *buff[i]= *au_in;
            i++;
            *(samp_rdy + 0x3)=0x0;
        }
    }

    while (1){
        i=0;
        while(i<48000){
            if((*(samp_rdy + 0x3)==0x1)){
                *au_out = *buff[i]+(*au_in); //Reproduces actual sample + delayed sample
                *buff[i]=*au_in; //replaces the sample in the array for the new one
                i++;
                *(samp_rdy + 0x3)=0x0;
            }
        }
    }
}
</code>```

Thanks.

答:
Try to run with C99 mode:</p>

```<code>#define au_in (volatile short *) 0x0081050  //Input memory address
#define au_out (volatile short *) 0x0081040
#define samp_rdy (volatile int *) 0x0081030 //Indicates if a new sample is ready
#define SAMPLE_BUF_SIZE     (48000)

void main()
{
    static short buff[SAMPLE_BUF_SIZE];
    for(int i = 0; i < SAMPLE_BUF_SIZE; )
    {
        if(*(samp_rdy + 0x3)) //If there's a new sample
        {
            buff[i]= *au_in;
            *(samp_rdy + 0x3)= 0;
            i++;
        }
    }

    while (1)
    {
        for(int i = 0; i < SAMPLE_BUF_SIZE; )
        {
            if(*(samp_rdy + 0x3)) //If there's a new sample
            {
                *au_out = buff[i] + (*au_in);   //Reproduces actual sample + delayed sample
                buff[i] = *au_in;               //replaces the sample in the array for the new one
                *(samp_rdy + 0x3)= 0;
                i++;
            }
        }
    }
}
</code>```

Body:
I'm implementing a delay in C code for audio.
I have a memory address where I receive the audio sample. And another memory address which indicates where a new sample appears.

What I am trying to do is record the first audio second (48000 samples). In order to do so I'm declaring an array where I save the audio samples.

In the main loop I make a sum of the actual sample and the delayed (1 second ago) sample, it's quite similar to an echo what I want to achieve.

The problem is that my code reproduces the actual sound, but not the delayed, in fact, I can heard a little noise every second, so I guess it only reads the first sample of the array, and the rest is empty.

I have analyzed my code, but I don't know where my failure is. I think it may be related with memory allocation, but I'm not very familiarized with C language. Could you please help me?

#define au_in (volatile short *) 0x0081050  //Input memory address
#define au_out (volatile short *) 0x0081040
#define samp_rdy (volatile int *) 0x0081030 //Indicates if a new sample is ready

/* REPLAY */
void main(){
    short *buff[48000];
    int i=0;
    while(i<48000){
        if((*(samp_rdy + 0x3)==0x1)){ //If there's a new sample
            *buff[i]= *au_in;
            i++;
            *(samp_rdy + 0x3)=0x0;
        }
    }

    while (1){
        i=0;
        while(i<48000){
            if((*(samp_rdy + 0x3)==0x1)){
                *au_out = *buff[i]+(*au_in); //Reproduces actual sample + delayed sample
                *buff[i]=*au_in; //replaces the sample in the array for the new one
                i++;
                *(samp_rdy + 0x3)=0x0;
            }
        }
    }
}

Thanks.

Body:
Try to run with C99 mode:

#define au_in (volatile short *) 0x0081050  //Input memory address
#define au_out (volatile short *) 0x0081040
#define samp_rdy (volatile int *) 0x0081030 //Indicates if a new sample is ready
#define SAMPLE_BUF_SIZE     (48000)

void main()
{
    static short buff[SAMPLE_BUF_SIZE];
    for(int i = 0; i < SAMPLE_BUF_SIZE; )
    {
        if(*(samp_rdy + 0x3)) //If there's a new sample
        {
            buff[i]= *au_in;
            *(samp_rdy + 0x3)= 0;
            i++;
        }
    }

    while (1)
    {
        for(int i = 0; i < SAMPLE_BUF_SIZE; )
        {
            if(*(samp_rdy + 0x3)) //If there's a new sample
            {
                *au_out = buff[i] + (*au_in);   //Reproduces actual sample + delayed sample
                buff[i] = *au_in;               //replaces the sample in the array for the new one
                *(samp_rdy + 0x3)= 0;
                i++;
            }
        }
    }
}


问:
How to pass prop to eventhandler?
I have 4 span with onClick={this.clickhandler}. Inside the clickhandler there is an audio which i'd like to play when clicked. The problem is, i want 4 different audio-urls inside the same clickhandler. How can i associate each span with an audio-string and pass it to the same eventhandler?

clickhander(e) {
    const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

                <Heart fill="#555"/>

                <Heart fill="#402" />

                <Heart fill="#f39" />

                <Heart fill="#29f" />

    )
}```
</div>
</div>
</p>

<p>EDIT: i tried the solutions below but i get this error:  The error you provided does not contain a stack trace.</p>

<p>this is my code now: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Home extends Component {

    constructor(props){
        super(props)
    }
    clickhander(e, url) {
        const str = url
        const audio = new Audio(String(str));
        audio.play()

    }
    render() {
        return(
            <div className="container">
                <h1 className="header">Simon Game</h1>
                <span  onClick={this.clickhander.bind(this, "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3")}>
                    <Heart fill="#555"/>
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#402" />
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#f39" />
                </span>
                <span onClick={this.clickhander}>
                    <Heart fill="#29f" />
                </span>
            </div>
        )
    }
}

export default Home</code>```

答:
You can use bind() to attach to the handler what you want

    clickhander(val, e) {
        console.log("value passed " + val)
    }
    render() {
        return(

Simon Game

                    <Heart fill="#555"/>

                    <Heart fill="#402" />

                    <Heart fill="#f39" />

                    <Heart fill="#29f" />

        )
    }```

Title: How to pass prop to eventhandler?

Body:
I have 4 span with onClick={this.clickhandler}. Inside the clickhandler there is an audio which i'd like to play when clicked. The problem is, i want 4 different audio-urls inside the same clickhandler. How can i associate each span with an audio-string and pass it to the same eventhandler?

clickhander(e) {
    const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
    audio.play()
    console.dir(e.target)
}
render() {
    return(

Simon Game

                <Heart fill="#555"/>

                <Heart fill="#402" />

                <Heart fill="#f39" />

                <Heart fill="#29f" />

    )
}

EDIT: i tried the solutions below but i get this error:  The error you provided does not contain a stack trace.

this is my code now:

class Home extends Component {

    constructor(props){
        super(props)
    }
    clickhander(e, url) {
        const str = url
        const audio = new Audio(String(str));
        audio.play()

    }
    render() {
        return(

Simon Game

                    <Heart fill="#555"/>

                    <Heart fill="#402" />

                    <Heart fill="#f39" />

                    <Heart fill="#29f" />

        )
    }
}

export default Home

Body:
You can use bind() to attach to the handler what you want

    clickhander(val, e) {
        console.log("value passed " + val)
    }
    render() {
        return(
            <div className="container">
                <h1 className="header">Simon Game</h1>
                <span  onClick={this.clickhander.bind(this, "val1")}>
                    <Heart fill="#555"/>
                </span>
                <span onClick={this.clickhander.bind(this, "val2")}>
                    <Heart fill="#402" />
                </span>
                <span onClick={this.clickhander.bind(this, "val3")}>
                    <Heart fill="#f39" />
                </span>
                <span onClick={this.clickhander.bind(this, "val4")}>
                    <Heart fill="#29f" />
                </span>
            </div>
        )
    }


答:
The difference I see

[NgForOf] is used to assign a source value into a target within any tag. ngForOf is a prop of NgFor class. In ngForOf we assign our array to iterate. ngForOf : NgIterable

[ngFor] doesn't require a type. Using this will mean the prop NgForOf is ngForOf : any

Title: Do I use NgFor or NgForOf?

Body:
In the angular API documentation it says to use NgForOf instead of NgFor with version 4.0 onwards. But the Fundamentals, and Heroes tutorial, documentation demonstrateNgFor, and make no mention of NgForOf.

Is there anyone who can clarify  this for me? Thank you in advance.


答:
They just renamed the class. NgForOf is the new class, NgFor is now only an alias and will go away eventually.
  https://github.com/angular/angular/blob/09d9f5fe54e7108c47de61393e10712f8239d824/packages/common/src/directives/ng_for_of.ts#L205

This only affects you if you are using a reference to the NgFor class in your code. The directive is imported using the CommonModule.
The selector is unchanged, therefore if you are only using ngFor in your template, nothing will change.

Title: Do I use NgFor or NgForOf?


问:
Mongodb BI Connector & Tableau: Error while trying to run mongosqld
I'm trying to connect Tableau to MongoDB using MongoDB BI Connector and this instruction (version 2.1 (current)):

https://docs.mongodb.com/bi-connector/v2.1/installation/

but I get an error in step 5:

```<code>mongosqld --schema=schema.drdl --mongo-uri=mongodb://localhost:27017

2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] mongosqld version: v2.1.0
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] git version: 518180ba2c547d2cc6071f955d98ec6de730c0c9
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] arguments: --mongo-uri mongodb://localhost:27017 --schema schema.drdl
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] ** WARNING: Access control is not enabled for mongosqld.
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten]
2017-07-04T15:19:44.038+0200 I NETWORK    [initandlisten] connecting to mongodb at mongodb://localhost:27017
error starting server: listen unix /tmp/mysql.sock: bind: address already in use
</code>```

mongosqld is installed properly:

```<code>mongosqld --version

mongosqld version v2.1.0
git version: 518180ba2c547d2cc6071f955d98ec6de730c0c9
</code>```

also, my mongod is running and working with the default port (27017) by running this command:

```<code>sudo mongod --dbpath /mnt/PROJET-CIRMAR-1T/
</code>```

Do you have any idea that what's the problem with running mongosqld?

答: I don't know why but the problem was with the mysql.sock file. So, you can remove it or move it somewhere else and try executing the command again. At least in my case, the problem is solved and mongosqld is running! Maybe it helps someone in the future and maybe someone let us know what's the exact reason!

Body:
I'm trying to connect Tableau to MongoDB using MongoDB BI Connector and this instruction (version 2.1 (current)):

https://docs.mongodb.com/bi-connector/v2.1/installation/

but I get an error in step 5:

mongosqld --schema=schema.drdl --mongo-uri=mongodb://localhost:27017

2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] mongosqld version: v2.1.0
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] git version: 518180ba2c547d2cc6071f955d98ec6de730c0c9
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] arguments: --mongo-uri mongodb://localhost:27017 --schema schema.drdl
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten] ** WARNING: Access control is not enabled for mongosqld.
2017-07-04T15:19:44.032+0200 I CONTROL    [initandlisten]
2017-07-04T15:19:44.038+0200 I NETWORK    [initandlisten] connecting to mongodb at mongodb://localhost:27017
error starting server: listen unix /tmp/mysql.sock: bind: address already in use

mongosqld is installed properly:

mongosqld --version

mongosqld version v2.1.0
git version: 518180ba2c547d2cc6071f955d98ec6de730c0c9

also, my mongod is running and working with the default port (27017) by running this command:

sudo mongod --dbpath /mnt/PROJET-CIRMAR-1T/

Do you have any idea that what's the problem with running mongosqld?


问:
"Method does not override method from its superclass" - When creating ContextMenu in Android
I'm trying to show contextmenu on longpress in MainActivity.java. But I'm getting error "Method does not override method from its superclass" on @Override and "Cannot resolve symbol ... " for both ContextMenu and ContextMenuInfo in the onCreateContextMenu method.

My code is:

```<code>package com.syver.adhper;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.*;
import android.view.View;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        createpnl();
        //more codes here
   }
   @Override
   public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
   {
       //some codes here
       //error is only in this section at @Override, ContextMenu and ContextMenuInfo
   }
   public void createpnl()
   {
       registerForContextMenu(...); //... means a layout
       //more codes here
   }
}
</code>```

Why am I getting this error? What should I do to avoid this error? Please give me corrected complete code as I'm new in android developing. I have searched here and also google, but proper ans I did't find and also didn't understand.

My API is 19 (kitkat)

答:
try this, it work in my android studio

```<code> @Override
    public void onCreateContextMenu (ContextMenu menu,
                              View v,
                              ContextMenu.ContextMenuInfo menuInfo)
    {

    }
</code>```

reference:https://developer.android.com/reference/android/app/Activity.html
also import the class by click the red, and press alt+enter, choose import the class, I think this would solve your problem

Body:
I'm trying to show contextmenu on longpress in MainActivity.java. But I'm getting error "Method does not override method from its superclass" on @Override and "Cannot resolve symbol ... " for both ContextMenu and ContextMenuInfo in the onCreateContextMenu method.

My code is:

package com.syver.adhper;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.*;
import android.view.View;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        createpnl();
        //more codes here
   }
   @Override
   public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
   {
       //some codes here
       //error is only in this section at @Override, ContextMenu and ContextMenuInfo
   }
   public void createpnl()
   {
       registerForContextMenu(...); //... means a layout
       //more codes here
   }
}

Why am I getting this error? What should I do to avoid this error? Please give me corrected complete code as I'm new in android developing. I have searched here and also google, but proper ans I did't find and also didn't understand.

My API is 19 (kitkat)

Body:
try this, it work in my android studio

 @Override
    public void onCreateContextMenu (ContextMenu menu,
                              View v,
                              ContextMenu.ContextMenuInfo menuInfo)
    {

    }

reference:https://developer.android.com/reference/android/app/Activity.html
also import the class by click the red, and press alt+enter, choose import the class, I think this would solve your problem


问:
Use Paperclip validations without storing the attachment
I am building a Rails endpoint that proxies a different service and maps the responses from said service. The main problem is to pass along a file attachment's byte data to that service.

A constraint is that I must do some sanity checks on the file before I pass it along.

I have no need to persist the file in my Rails app, it is merely used as input to the other service.

In a very simple implementation I simply just read the bytes from the appropriate request parameter which is wrapped in a Tempfile, but this of course entails no sanity checks, and therefore is not good enough.

I am interested in doing the kinds of validation that Paperclip supports, in particular size and content type, but I would prefer to not store the actual file anywhere.

Is it possible to use only the validation parts of Paperclip and not store the attachment anywhere?

答:
You can verify the file mime-type with the gem ruby-filemagic :

```<code>FileMagic.new(FileMagic::MAGIC_MIME).file(your_tempfile.path) #=> "image/png; charset=binary"
</code>```

For the size you could just check with your_tempfile.size

Body:
You can verify the file mime-type with the gem ruby-filemagic :

FileMagic.new(FileMagic::MAGIC_MIME).file(your_tempfile.path) #=> "image/png; charset=binary"

For the size you could just check with your_tempfile.size


问:
Embedded Solr server - how to use a different core name
I have a spring boot application where I am embedding a solr server. I seem to be forced right now to name my solr core as "collection1" so that my code indeed finds the core to load

anyone know how I can make this arbitrary ?

```<code>@Configuration
@EnableSolrRepositories(basePackages = ["uk.xxx"], multicoreSupport = true)
class SolrContext {

    static final String SOLR_HOST = 'solr.host'
    static final String SOLR_EMBEDDED_PATH = 'solr.embedded.path'

    @Resource
    Environment environment

    @Bean
    public SolrServer solrServer() {
        EmbeddedSolrServerFactory factory = new EmbeddedSolrServerFactory(environment.getRequiredProperty(SOLR_EMBEDDED_PATH))
        return factory.getSolrServer()
    }

    @Bean
    public SolrOperations solrTemplate() {
        return new SolrTemplate(solrServer())
    }

}
</code>```

tried like you said, still no good, I named my core 'coursefinder', and passed that in like you said but its still looking for colelction1 :

```<code>@Bean
public SolrServer solrServer() {
        println "starting embedded solr index"
        EmbeddedSolrServerFactory factory = new EmbeddedSolrServerFactory(grailsApplication.config.getProperty('solr.embedded.path'))
        return factory.getSolrServer("coursefinder")

    }
}
</code>```

output

```<code>starting embedded solr index
ERROR org.apache.solr.core.CoreContainer - Error creating core [collection1]: Could not load conf for core collection1: Error loading solr config from /Developer/dev/LSE/coursefinder-grails-angular/embeddedsolr/collection1/conf/solrconfig.xml
org.apache.solr.common.SolrException: Could not load conf for core collection1: Error loading solr config from /Developer/dev/LSE/coursefinder-grails-angular/embeddedsolr/collection1/conf/solrconfig.xml
    at org.apache.solr.core.ConfigSetService.getConfig(ConfigSetService.java:66)
    at org.apache.solr.core.CoreContainer.create(CoreContainer.java:489)
    at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:255)
    at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:249)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)`
</code>```

答:
I tried all many posted solution, the only thing which is working for solr 5.x is the following.

Be aware that you have a core.properties beneath the home folder which has the same name inside.

Best way is to build a core with solr create and use that structure as home folder.

Following is for Spring based jUnit testing

```<code>@Bean
public EmbeddedSolrServer solrServerFactoryBean() {
    String folder = "src/main/resources/server/solr/";
    CoreContainer container = new CoreContainer(folder);
    container.load();
    return new EmbeddedSolrServer(container, "myName");

}

@Bean
public SolrTemplate solrTemplate(EmbeddedSolrServer server) throws Exception {
    SolrTemplate solrTemplate = new SolrTemplate(server);
    return solrTemplate;
}
</code>```

Body:
I have a spring boot application where I am embedding a solr server. I seem to be forced right now to name my solr core as "collection1" so that my code indeed finds the core to load

anyone know how I can make this arbitrary ?

@Configuration
@EnableSolrRepositories(basePackages = ["uk.xxx"], multicoreSupport = true)
class SolrContext {

    static final String SOLR_HOST = 'solr.host'
    static final String SOLR_EMBEDDED_PATH = 'solr.embedded.path'

    @Resource
    Environment environment

    @Bean
    public SolrServer solrServer() {
        EmbeddedSolrServerFactory factory = new EmbeddedSolrServerFactory(environment.getRequiredProperty(SOLR_EMBEDDED_PATH))
        return factory.getSolrServer()
    }

    @Bean
    public SolrOperations solrTemplate() {
        return new SolrTemplate(solrServer())
    }

}

tried like you said, still no good, I named my core 'coursefinder', and passed that in like you said but its still looking for colelction1 :

@Bean
public SolrServer solrServer() {
        println "starting embedded solr index"
        EmbeddedSolrServerFactory factory = new EmbeddedSolrServerFactory(grailsApplication.config.getProperty('solr.embedded.path'))
        return factory.getSolrServer("coursefinder")

    }
}

output

starting embedded solr index
ERROR org.apache.solr.core.CoreContainer - Error creating core [collection1]: Could not load conf for core collection1: Error loading solr config from /Developer/dev/LSE/coursefinder-grails-angular/embeddedsolr/collection1/conf/solrconfig.xml
org.apache.solr.common.SolrException: Could not load conf for core collection1: Error loading solr config from /Developer/dev/LSE/coursefinder-grails-angular/embeddedsolr/collection1/conf/solrconfig.xml
    at org.apache.solr.core.ConfigSetService.getConfig(ConfigSetService.java:66)
    at org.apache.solr.core.CoreContainer.create(CoreContainer.java:489)
    at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:255)
    at org.apache.solr.core.CoreContainer$1.call(CoreContainer.java:249)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)`

Body:
I tried all many posted solution, the only thing which is working for solr 5.x is the following.

Be aware that you have a core.properties beneath the home folder which has the same name inside.

Best way is to build a core with solr create and use that structure as home folder.

Following is for Spring based jUnit testing

@Bean
public EmbeddedSolrServer solrServerFactoryBean() {
    String folder = "src/main/resources/server/solr/";
    CoreContainer container = new CoreContainer(folder);
    container.load();
    return new EmbeddedSolrServer(container, "myName");

}

@Bean
public SolrTemplate solrTemplate(EmbeddedSolrServer server) throws Exception {
    SolrTemplate solrTemplate = new SolrTemplate(server);
    return solrTemplate;
}


问:
Ajax request not firing in new version of jquery
I have a small script that checks the username in the database if it is taken it will say taken if its available it will say available. currently the below code works perfectly in jQuery v1.7.2

How ever I need to update it to work with the current version of jQuery v3.2.1,
but trying to use the current jquery version it just says checking availability and nothing else.

```<code>$(document).ready(function() {
  $("#username").keyup(function() {
    var username = $("#username").val();
    var msgbox = $("#status");

    if (username.length > 3) {
      $("#status").html('');

      $.ajax({
        type: "POST",
        url: "includes/user_check.php",
        data: "username=" + username,
        success: function(msg) {
          $("#status").ajaxComplete(function(event, request) {
            if (msg == 'OK') {

              $("#username").removeClass("red");
              $("#username").addClass("green");
              msgbox.html('Available');
            } else {
              $("#username").removeClass("green");
              $("#username").addClass("red");
              msgbox.html(msg);
            }

          });
        }
      });
    } else {
      $("#username").addClass("red");
      $("#status").html('<font color="#cc0000">To Short</font>');
    }
    return false;
  });
});
</code>```

答:
Your ajaxComplete attached to the wrong place.
According to documentation for .ajaxComplete

Additional Notes:

As of jQuery 1.9, all the handlers for the jQuery global Ajax events, including those added with the .ajaxComplete() method, must be attached to document.

If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxComplete() method will not fire.

Try to change this part:  $("#status").ajaxComplete(function(event, request) {

UPD: Actually you don't even need this function in your implementation. success will do it for you

Body:
I have a small script that checks the username in the database if it is taken it will say taken if its available it will say available. currently the below code works perfectly in jQuery v1.7.2

How ever I need to update it to work with the current version of jQuery v3.2.1,
but trying to use the current jquery version it just says checking availability and nothing else.

$(document).ready(function() {
  $("#username").keyup(function() {
    var username = $("#username").val();
    var msgbox = $("#status");

    if (username.length > 3) {
      $("#status").html('');

      $.ajax({
        type: "POST",
        url: "includes/user_check.php",
        data: "username=" + username,
        success: function(msg) {
          $("#status").ajaxComplete(function(event, request) {
            if (msg == 'OK') {

              $("#username").removeClass("red");
              $("#username").addClass("green");
              msgbox.html('Available');
            } else {
              $("#username").removeClass("green");
              $("#username").addClass("red");
              msgbox.html(msg);
            }

          });
        }
      });
    } else {
      $("#username").addClass("red");
      $("#status").html('To Short');
    }
    return false;
  });
});


问:
Connection to IBM message hub using C# and Confluent
I'm trying to create producer and consumer apps using IBM message hub. For the producer i'm using the following code:

```<code>var config = new Dictionary<string, object> {
                { "bootstrap.servers", brokerList },
                { "group.id", "simple-csharp-producer" },
                { "client.id", "some string for id such as FR45fHth..." },
                {"api.version.request","true" },
                {"sasl.mechanisms","PLAIN" },
                {"sasl.username","the first 16 charachters of the client.id" },
                {"sasl.password","the other characters left" }
            };

            using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
              ....
            }
</code>```

for the consumer i'm using similar config properties.

the rest of the code for the consumer:

```<code>using (var consumer = new Consumer<Null, string>(config, null, new StringDeserializer(Encoding.UTF8)))
            {
                consumer.Assign(new List<TopicPartitionOffset> { new TopicPartitionOffset(topics, 0, 0) });

                while (true)
                {
                    Message<Null, string> msg;
                    if (consumer.Consume(out msg, TimeSpan.FromSeconds(1)))
                    {
                        Console.WriteLine($"Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");
                    }
                }
            }
</code>```

and for the producer:

```<code>using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
                Console.WriteLine($"{producer.Name} producing on {topicName}. q to exit.");

                string text;
                while ((text = Console.ReadLine()) != "q")
                {
                    var deliveryReport = producer.ProduceAsync(topicName, null, text);
                    deliveryReport.ContinueWith(task =>
                    {
                        Console.WriteLine($"Partition: {task.Result.Partition}, Offset: {task.Result.Offset}");
                    });
                }

                // Tasks are not waited on synchronously (ContinueWith is not synchronous),
                // so it's possible they may still in progress here.
                producer.Flush(Convert.ToInt32(TimeSpan.FromSeconds(10)));
</code>```

Anyhow, it didn't work, there is no sign for sending of getting anything...
what is missing?
or what can i use for it to work?

The Logs i get:

*sasl_ssl://kafka03-prod02.messagehub.services.eu-gb.bluemix.net:9093/bootstrap:
  Failed to initialize SASL authentication: SASL mechanism "PLAIN" not
  supported on platform

*1/1 brokers are down

答:
The settings that Mickael has posted are correct.

However if you are running on Windows - to get SASL/SSL support (required for Message Hub) you need librdkafka 0.11

With librdkafka 0.9.5 you can't connect to MH from Windows

Body:
I'm trying to create producer and consumer apps using IBM message hub. For the producer i'm using the following code:

var config = new Dictionary<string, object> {
                { "bootstrap.servers", brokerList },
                { "group.id", "simple-csharp-producer" },
                { "client.id", "some string for id such as FR45fHth..." },
                {"api.version.request","true" },
                {"sasl.mechanisms","PLAIN" },
                {"sasl.username","the first 16 charachters of the client.id" },
                {"sasl.password","the other characters left" }
            };

            using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
              ....
            }

for the consumer i'm using similar config properties.

the rest of the code for the consumer:

using (var consumer = new Consumer<Null, string>(config, null, new StringDeserializer(Encoding.UTF8)))
            {
                consumer.Assign(new List<TopicPartitionOffset> { new TopicPartitionOffset(topics, 0, 0) });

                while (true)
                {
                    Message<Null, string> msg;
                    if (consumer.Consume(out msg, TimeSpan.FromSeconds(1)))
                    {
                        Console.WriteLine($"Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");
                    }
                }
            }

and for the producer:

using (var producer = new Producer<Null, string>(config, null, new StringSerializer(Encoding.UTF8)))
            {
                Console.WriteLine($"{producer.Name} producing on {topicName}. q to exit.");

                string text;
                while ((text = Console.ReadLine()) != "q")
                {
                    var deliveryReport = producer.ProduceAsync(topicName, null, text);
                    deliveryReport.ContinueWith(task =>
                    {
                        Console.WriteLine($"Partition: {task.Result.Partition}, Offset: {task.Result.Offset}");
                    });
                }

                // Tasks are not waited on synchronously (ContinueWith is not synchronous),
                // so it's possible they may still in progress here.
                producer.Flush(Convert.ToInt32(TimeSpan.FromSeconds(10)));

Anyhow, it didn't work, there is no sign for sending of getting anything...
what is missing?
or what can i use for it to work?

The Logs i get:

*sasl_ssl://kafka03-prod02.messagehub.services.eu-gb.bluemix.net:9093/bootstrap:
  Failed to initialize SASL authentication: SASL mechanism "PLAIN" not
  supported on platform

*1/1 brokers are down


问:
swagger-node - Error: Response validation failed: void does not allow a value
I'm using swagger-node library, and am trying to achieve a 302 redirect with it. But it results into the error described in the title.

My schema regarding the path looks following:

```<code>  /login:
    x-swagger-router-controller: login
    get:
      produces:
        - text/html
      description: Entry point for login
      operationId: login
      responses:
        "302":
          headers:
            Location:
              type: "string"
          description: Found
</code>```

In my api, I have express app, and I'm just redirecting like so:

```<code>res.redirect(redirect_url);
</code>```

How could I achieve redirect using swagger-node?

Stacktrace is following:

```<code>Error: Response validation failed: void does not allow a value
at throwErrorWithCode (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/lib/validators.js:121:13)
at validateTypeAndFormat (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/lib/validators.js:538:7)
at Object.module.exports.validateSchemaConstraints (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/lib/validators.js:630:7)
at validateValue (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/middleware/swagger-validator.js:117:16)
at ServerResponse.res.end (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/middleware/swagger-validator.js:252:9)
</code>```

答:
Don't know if you already figured it out, but to make 302 response work, u have to define the schema type from the response as a string</p>

```<code>responses:
  "302":
    description: "302 response"
    schema:
      type: string
</code>```

Body:
I'm using swagger-node library, and am trying to achieve a 302 redirect with it. But it results into the error described in the title.

My schema regarding the path looks following:

  /login:
    x-swagger-router-controller: login
    get:
      produces:
        - text/html
      description: Entry point for login
      operationId: login
      responses:
        "302":
          headers:
            Location:
              type: "string"
          description: Found

In my api, I have express app, and I'm just redirecting like so:

res.redirect(redirect_url);

How could I achieve redirect using swagger-node?

Stacktrace is following:

Error: Response validation failed: void does not allow a value
at throwErrorWithCode (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/lib/validators.js:121:13)
at validateTypeAndFormat (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/lib/validators.js:538:7)
at Object.module.exports.validateSchemaConstraints (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/lib/validators.js:630:7)
at validateValue (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/middleware/swagger-validator.js:117:16)
at ServerResponse.res.end (/home/coder/projects/clever-saml2/clever-saml2/node_modules/swagger-express-mw/node_modules/swagger-node-runner/node_modules/swagger-tools/middleware/swagger-validator.js:252:9)

Body:
Don't know if you already figured it out, but to make 302 response work, u have to define the schema type from the response as a string

responses:
  "302":
    description: "302 response"
    schema:
      type: string


问:
Hangman Game - Duplicate characters issue in lists
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.</p>

```<code>def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
</code>```

答:
you can try this if you want. pretty easy to understand if you don't want anything too complicated:

```<code>def findOccurences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = findOccurences(word,letter)
        for i in letterPlace:
            answer[i] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
</code>```

Nice game by the way.

Body:
I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = word.index(letter)
        answer[letterPlace] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()

Body:
you can try this if you want. pretty easy to understand if you don't want anything too complicated:

def findOccurences(s, ch):
    return [i for i, letter in enumerate(s) if letter == ch]

def guess():
    letter = input ("Please enter a letter:")
    if letter in word:
        print ("Correct!")
        letterPlace = findOccurences(word,letter)
        for i in letterPlace:
            answer[i] = letter
        print (*answer)
    else:
        print ("Wrong!")

    if answer == word :
        print ("You guessed it! Well Done!")
        #end here
    else:
        guess()

from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()

Nice game by the way.