问:
I want to create a log file where I can get INFO, DEBUG, ERROR, CRITICAL, WARNING details int that file. But My code is not giving me the exact output
```<code>import logging.handlers

LOG_FILENAME = 'logger.log'

logging.basicConfig(filename=LOG_FILENAME,
                    level=logging.DEBUG,
                    )

logging.info('In Log File...')
f = open(LOG_FILENAME, 'rt')

try:
    body = f.read()
finally:
    f.close()
print 'FILE:'
print body
def syslog (debug,info,warning,error,critical = "LEVELS"):
    str = "Debug: "+ debug+" Info: "+ info+" Waring: "+ warning+" Error: "+ error+" Critical: " +critical
    return str
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)
my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')
my_logger.info('this is info')
my_logger.warn('this is critical')
</code>```

答:
You could establish a central log server and send all log messages from all machines to it via HTTP (or sockets).

logging module has many features, including so-called handlers. Simply put, a logging handler is a class whose emit method takes the log record to input and does something with it, for example, writing the record to a given file is default behavior (FileHandler). There is a lot of handlers already included in logging module which could be useful. In your case, you could use HTTPHandler. SocketHandler is described on the same page, you can use it if you prefer sockets.

Or you could write your own custom handler

```<code>class CustomHandler(logging.StreamHandler):
    def emit(self, record):
        msg = self.format(record)
        # msg is the record string to, em, record (sorry for much of a muchness)
        # Do whatever you want with it
</code>```

HTTPHandler and your custom handler are added to a logger just as in your code

```<code>handler = logging.handlers.HTTPHandler(...)
</code>```

or

```<code>handler = CustomHandler(...)
</code>```

```<code>my_logger.addHandler(handler)
</code>```

Body:
You could establish a central log server and send all log messages from all machines to it via HTTP (or sockets).

logging module has many features, including so-called handlers. Simply put, a logging handler is a class whose emit method takes the log record to input and does something with it, for example, writing the record to a given file is default behavior (FileHandler). There is a lot of handlers already included in logging module which could be useful. In your case, you could use HTTPHandler. SocketHandler is described on the same page, you can use it if you prefer sockets.

Or you could write your own custom handler

class CustomHandler(logging.StreamHandler):
    def emit(self, record):
        msg = self.format(record)
        # msg is the record string to, em, record (sorry for much of a muchness)
        # Do whatever you want with it

HTTPHandler and your custom handler are added to a logger just as in your code

handler = logging.handlers.HTTPHandler(...)

or

handler = CustomHandler(...)

my_logger.addHandler(handler)


来源: stackexchange

问:
How to import a private key into a Java keystore without knowning the password
I have a private key in PEM format, protected by a password (there is also a certificate for the key). Is it possible to import this key into a Java keystore without knowing it's password?

Knowing the password I would do the following:

```<code>openssl pkcs12 -export -in cert.pem -inkey key.pem > server.p12
keytool -importkeystore -srckeystore server.p12 -destkeystore server.jks -srcstoretype pkcs12
</code>```

But I'd like to skip password input and re-use the existing password.

答:
Not Possible.

The whole point of having the PrivateKey protected is to not let anyone gain access to it unless they know the password that unlocks it.

ContentLicense: CC BY-SA 3.0

Body:
I have a private key in PEM format, protected by a password (there is also a certificate for the key). Is it possible to import this key into a Java keystore without knowing it's password?

Knowing the password I would do the following:

openssl pkcs12 -export -in cert.pem -inkey key.pem > server.p12
keytool -importkeystore -srckeystore server.p12 -destkeystore server.jks -srcstoretype pkcs12

But I'd like to skip password input and re-use the existing password.


问:
Function of function(functional) in Maxima
I want to define a function of a function ( maybe functional) in Maxima. For example, I want to define T in the code:

```<code>f(r,GN,M)::=(2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2);
X(r,GN,M) ::= 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r));
T(r,GN,M) ::= diff(f(r,GN,M),r)+X(r,GN,M);
</code>```

But I don't know the code.

答:
In maxima it is convenient to use expressions.

Define two expressions

```<code>(%i1) display2d: false $
(%i2) f: (2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2) $
(%i3) X: 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r)) $
</code>```

Define a function which operates on two expressions

```<code>(%i4) T(f, X) := diff(f, r) + X $
</code>```

Call it. Result is an expression

```<code>(%i5) dfpX: T(f, X);
(%o5) (2*GN*M*(1-(GN*M)/(2*r)))/r+(GN*M)/r+2*GN*M^2
                                            *((2*GN^2*M^2)/r^3-(2*GN*M)/r^2)
</code>```

You can create a function based on dfpX

```<code>(%i6) define(f(r, GN, M), dfpX);
(%o6) f(r,GN,M):=(2*GN*M*(1-(GN*M)/(2*r)))/r+(GN*M)/r
        +2*GN*M^2*((2*GN^2*M^2)/r^3-(2*GN*M)/r^2)
</code>```

and call it

```<code>(%i7) f(1, 2, 3);
(%o7) 2142
</code>```

but you can stay with expressions

```<code>(%i8) subst([r=1, GN=2, M=3], dfpX);
(%o8) 2142
</code>```

Body:
I want to define a function of a function ( maybe functional) in Maxima. For example, I want to define T in the code:

f(r,GN,M)::=(2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2);
X(r,GN,M) ::= 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r));
T(r,GN,M) ::= diff(f(r,GN,M),r)+X(r,GN,M);

But I don't know the code.

Body:
In maxima it is convenient to use expressions.

Define two expressions

(%i1) display2d: false $
(%i2) f: (2*GN*M^2)*(2*GN*M/r-(2*GN*M/(2*r))^2) $
(%i3) X: 2*GN*M/(2*r)+2*GN*M/r*(1-2*GN*M/(4*r)) $

Define a function which operates on two expressions

(%i4) T(f, X) := diff(f, r) + X $

Call it. Result is an expression

(%i5) dfpX: T(f, X);
(%o5) (2*GN*M*(1-(GN*M)/(2*r)))/r+(GN*M)/r+2*GN*M^2
                                            *((2*GN^2*M^2)/r^3-(2*GN*M)/r^2)

You can create a function based on dfpX

(%i6) define(f(r, GN, M), dfpX);
(%o6) f(r,GN,M):=(2*GN*M*(1-(GN*M)/(2*r)))/r+(GN*M)/r
        +2*GN*M^2*((2*GN^2*M^2)/r^3-(2*GN*M)/r^2)

and call it

(%i7) f(1, 2, 3);
(%o7) 2142

but you can stay with expressions

(%i8) subst([r=1, GN=2, M=3], dfpX);
(%o8) 2142


问:
Manufacturing an array - why is it different?
consider I declare two variables like this (done within REPL, with node v7.7.2), which I expect to be arrays:

```<code>var x = Array(4)
var y = Array.from({length: 4})
</code>```

then the following should work identically, but it doesn't:

```<code>x.map(Math.random)
[ , , ,  ]
y.map(Math.random)
[ 0.46597917021676816,
  0.3348459056304458,
  0.2913995519428412,
  0.8683430009997699 ]
</code>```

in looking, it seems x and y are both identical:

```<code>> typeof x
'object'
> typeof y
'object'
> Array.isArray(x)
true
> Array.isArray(y)
true
> x.length
4
> y.length
4
> typeof x[0]
'undefined'
> typeof y[0]
'undefined'
</code>```

so why the difference?

答:
The Array created with Array(4) is not iterated over with .map(), whereas the Array.from({ length: 4 }) is iterated over. A fuller explanation can be found at JavaScript "new Array(n)" and "Array.prototype.map" weirdness, you can test this with..</p>

```<code>x.map((f,i) => console.log(i)) vs. y.map((f,i) => console.log(i))
</code>```

Body:
consider I declare two variables like this (done within REPL, with node v7.7.2), which I expect to be arrays:

var x = Array(4)
var y = Array.from({length: 4})

then the following should work identically, but it doesn't:

x.map(Math.random)
[ , , ,  ]
y.map(Math.random)
[ 0.46597917021676816,
  0.3348459056304458,
  0.2913995519428412,
  0.8683430009997699 ]

in looking, it seems x and y are both identical:

> typeof x
'object'
> typeof y
'object'
> Array.isArray(x)
true
> Array.isArray(y)
true
> x.length
4
> y.length
4
> typeof x[0]
'undefined'
> typeof y[0]
'undefined'

so why the difference?

Body:
The Array created with Array(4) is not iterated over with .map(), whereas the Array.from({ length: 4 }) is iterated over. A fuller explanation can be found at JavaScript "new Array(n)" and "Array.prototype.map" weirdness, you can test this with..

x.map((f,i) => console.log(i)) vs. y.map((f,i) => console.log(i))


问:
How do I run that database backup and restore scripts from my winform application?
I am developing a small business application which uses Sqlserver 2005 database.

Platform: .Net framework 3.5;
Application type: windows application;
Language: C#

Question:

I need to take and restore the backup from my application. I have the required script generated from SSME.

How do I run that particular script (or scripts) from my winform application?

答: You can run these scripts the same way you run a query, only you don't connect to the database you want to restore, you connect to master instead.</p>

OwnerDisplayName: Asad Malik

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: edg


问:
Web Scraping in R (Getting piece of Information from a table)
Trying to study web scraping in R alone...

This feels really difficult without HTML knowledge.

```<code>crime_wiki <- read_html("https://en.wikipedia.org/wiki/List_of_United_States_cities_by_crime_rate")
crime_wiki %>%
  html_nodes(".firstHeading") %>% html_text()

crime_wiki %>%
  html_nodes("dl+ h2 .mw-headline") %>% html_text()
</code>```

Above codes worked fine. I got what I wanted to get.

When I tried to get city names (from Albuquerque to Wichita), it didn't work.
I wrote

```<code>crime_wiki %>%
  html_nodes(".jquery-tablesorter a") %>% html_text()
</code>```

What did I do wrong?

Ultimately I want to do... When I click each city name, their linked pages seem to have the same format. So get the same piece of information from each page such as name of Mayor of all the cities in the table...

答:
The following code allowed me to get the city names:

```<code>    library(rvest)
    crime_wiki <- read_html("https://en.wikipedia.org/wiki/List_of_United_States_cities_by_crime_rate")
    crime_wiki %>%
      html_nodes("td a") %>%
      html_text()
</code>```

I'm not familiar with your use of ".jquery-tablesorter a". I used SelectorGadget to get the name of the nodes, i.e., "td a". Note that with the code that I've shared, I would need to remove the last 4 elements if I wanted only the city names.

ContentLicense: CC BY-SA 4.0

Body:
Trying to study web scraping in R alone...

This feels really difficult without HTML knowledge.

crime_wiki <- read_html("https://en.wikipedia.org/wiki/List_of_United_States_cities_by_crime_rate")
crime_wiki %>%
  html_nodes(".firstHeading") %>% html_text()

crime_wiki %>%
  html_nodes("dl+ h2 .mw-headline") %>% html_text()

Above codes worked fine. I got what I wanted to get.

When I tried to get city names (from Albuquerque to Wichita), it didn't work.
I wrote

crime_wiki %>%
  html_nodes(".jquery-tablesorter a") %>% html_text()

What did I do wrong?

Ultimately I want to do... When I click each city name, their linked pages seem to have the same format. So get the same piece of information from each page such as name of Mayor of all the cities in the table...

Body:
The following code allowed me to get the city names:

    library(rvest)
    crime_wiki <- read_html("https://en.wikipedia.org/wiki/List_of_United_States_cities_by_crime_rate")
    crime_wiki %>%
      html_nodes("td a") %>%
      html_text()

I'm not familiar with your use of ".jquery-tablesorter a". I used SelectorGadget to get the name of the nodes, i.e., "td a". Note that with the code that I've shared, I would need to remove the last 4 elements if I wanted only the city names.


问:
Python - Remove white space using only loops
I want to remove extra spaces in a string using only for/while loops, and if statements; NO split/replace/join.

like this:

```<code>mystring = 'Here is  some   text   I      wrote   '

while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

print(mystring)
</code>```

output:

```<code>Here is some text I wrote
</code>```

Here's what I tried.  Unfortunately, it doesn't quite work.

```<code>def cleanupstring(S):
    lasti = ""
    result = ""

    for i in S:
        if lasti == " " and i == " ":
            i = ""

        lasti = i
        result += i

    print(result)

cleanupstring("Hello      my name    is    joe")
</code>```

output:

```<code>Hello   my name  is  joe
</code>```

My attempt doesn't remove all the extra spaces.

答:
Uses the end of result in place of lasti:

```<code>def cleanupstring(S):
    result = S[0]

    for i in S[1:]:
        if not (result[-1] == " " and i == " "):
            result += i

    print(result)

cleanupstring("Hello      my name    is    joe")
</code>```

Body:
I want to remove extra spaces in a string using only for/while loops, and if statements; NO split/replace/join.

like this:

mystring = 'Here is  some   text   I      wrote   '

while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

print(mystring)

output:

Here is some text I wrote

Here's what I tried.  Unfortunately, it doesn't quite work.

def cleanupstring(S):
    lasti = ""
    result = ""

    for i in S:
        if lasti == " " and i == " ":
            i = ""

        lasti = i
        result += i

    print(result)

cleanupstring("Hello      my name    is    joe")

output:

Hello   my name  is  joe

My attempt doesn't remove all the extra spaces.

Body:
Uses the end of result in place of lasti:

def cleanupstring(S):
    result = S[0]

    for i in S[1:]:
        if not (result[-1] == " " and i == " "):
            result += i

    print(result)

cleanupstring("Hello      my name    is    joe")


问:
how to use Apache Commons Math Optimization in Jython?
I want to transfer Matlab code to Jython version, and find that the fminsearch in Matlab might be replaced by Apache-Common-Math-Optimization.
I'm coding on the Mango Medical Image script manager, which uses Jython 2.5.3  as coding language. And the Math version is 3.6.1.
Here is my code:

def f(x,y):
 return x^2+y^2

sys.path.append('/home/shujian/APPs/Mango/lib/commons-math3-3.6.1.jar')
sys.add_package('org.apache.commons.math3.analysis')
from org.apache.commons.math3.analysis import MultivariateFunction
sys.add_package('org.apache.commons.math3.optim.nonlinear.scalar.noderiv')
from org.apache.commons.math3.optim.nonlinear.scalar.noderiv import NelderMeadSimplex,SimplexOptimizer
sys.add_package('org.apache.commons.math3.optim.nonlinear.scalar')
from org.apache.commons.math3.optim.nonlinear.scalar import ObjectiveFunction
sys.add_package('org.apache.commons.math3.optim')
from org.apache.commons.math3.optim import MaxEval,InitialGuess
sys.add_package('org.apache.commons.math3.optimization')
from org.apache.commons.math3.optimization import GoalType

initialSolution=[2.0,2.0]
simplex=NelderMeadSimplex([2.0,2.0])
opt=SimplexOptimizer(2**(-6), 2**(-10))
solution=opt.optimize(MaxEval(300),ObjectiveFunction(f),simplex,GoalType.MINIMIZE,InitialGuess([2.0,2.0]))

skewParameters2 = solution.getPointRef()
print skewParameters2;```
</div>
</div>
</p>

<p>And I got the error below：</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-html lang-html prettyprint-override"><code>TypeError: optimize(): 1st arg can't be coerced to </code>```

I'm quite confused about how to use the optimization in Jython and the examples are all Java version.

答:
I've given up this plan and find another method to perform the fminsearch in Jython. Below is the Jython version code:

import sys
sys.path.append('.../jnumeric-2.5.1_ra0.1.jar')   #add the jnumeric path
import Numeric as np
def nelder_mead(f, x_start,
                step=0.1, no_improve_thr=10e-6,
                no_improv_break=10, max_iter=0,
                alpha=1., gamma=2., rho=-0.5, sigma=0.5):
    '''
        @param f (function): function to optimize, must return a scalar score
            and operate over a numpy array of the same dimensions as x_start
        @param x_start (float list): initial position
        @param step (float): look-around radius in initial step
        @no_improv_thr,  no_improv_break (float, int): break after no_improv_break iterations with
            an improvement lower than no_improv_thr
        @max_iter (int): always break after this number of iterations.
            Set it to 0 to loop indefinitely.
        @alpha, gamma, rho, sigma (floats): parameters of the algorithm
            (see Wikipedia page for reference)

        return: tuple (best parameter array, best score)
    '''

    # init
    dim = len(x_start)
    prev_best = f(x_start)
    no_improv = 0
    res = [[np.array(x_start), prev_best]]

    for i in range(dim):
        x=np.array(x_start)
        x[i]=x[i]+step
        score = f(x)
        res.append([x, score])

    # simplex iter
    iters = 0
    while 1:
        # order
        res.sort(key=lambda x: x[1])
        best = res[0][1]

        # break after max_iter
        if max_iter and iters >= max_iter:
            return res[0]
        iters += 1

        # break after no_improv_break iterations with no improvement
        print '...best so far:', best

        if best < prev_best - no_improve_thr:
            no_improv = 0
            prev_best = best
        else:
            no_improv += 1

        if no_improv >= no_improv_break:
            return res[0]

        # centroid
        x0 = [0.] * dim
        for tup in res[:-1]:
            for i, c in enumerate(tup[0]):
                x0[i] += c / (len(res)-1)

        # reflection
        xr = x0 + alpha*(x0 - res[-1][0])
        rscore = f(xr)
        if res[0][1] <= rscore < res[-2][1]:
            del res[-1]
            res.append([xr, rscore])
            continue

        # expansion
        if rscore < res[0][1]:
            xe = x0 + gamma*(x0 - res[-1][0])
            escore = f(xe)
            if escore < rscore:
                del res[-1]
                res.append([xe, escore])
                continue
            else:
                del res[-1]
                res.append([xr, rscore])
                continue

        # contraction
        xc = x0 + rho*(x0 - res[-1][0])
        cscore = f(xc)
        if cscore < res[-1][1]:
            del res[-1]
            res.append([xc, cscore])
            continue

        # reduction
        x1 = res[0][0]
        nres = []
        for tup in res:
            redx = x1 + sigma*(tup[0] - x1)
            score = f(redx)
            nres.append([redx, score])
        res = nres```
</div>
</div>
</p>

<p>And the test example is as below:</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-html lang-html prettyprint-override"><code>def f(x):
        return x[0]**2+x[1]**2+x[2]**2

print nelder_mead(f,[3.4,2.3,2.2])</code>```

Actually, the original version is for python, and the link below is the source:
https://github.com/fchollet/nelder-mead

Body:
I want to transfer Matlab code to Jython version, and find that the fminsearch in Matlab might be replaced by Apache-Common-Math-Optimization.
I'm coding on the Mango Medical Image script manager, which uses Jython 2.5.3  as coding language. And the Math version is 3.6.1.
Here is my code:

def f(x,y):
 return x^2+y^2

sys.path.append('/home/shujian/APPs/Mango/lib/commons-math3-3.6.1.jar')
sys.add_package('org.apache.commons.math3.analysis')
from org.apache.commons.math3.analysis import MultivariateFunction
sys.add_package('org.apache.commons.math3.optim.nonlinear.scalar.noderiv')
from org.apache.commons.math3.optim.nonlinear.scalar.noderiv import NelderMeadSimplex,SimplexOptimizer
sys.add_package('org.apache.commons.math3.optim.nonlinear.scalar')
from org.apache.commons.math3.optim.nonlinear.scalar import ObjectiveFunction
sys.add_package('org.apache.commons.math3.optim')
from org.apache.commons.math3.optim import MaxEval,InitialGuess
sys.add_package('org.apache.commons.math3.optimization')
from org.apache.commons.math3.optimization import GoalType

initialSolution=[2.0,2.0]
simplex=NelderMeadSimplex([2.0,2.0])
opt=SimplexOptimizer(2**(-6), 2**(-10))
solution=opt.optimize(MaxEval(300),ObjectiveFunction(f),simplex,GoalType.MINIMIZE,InitialGuess([2.0,2.0]))

skewParameters2 = solution.getPointRef()
print skewParameters2;

And I got the error below：

TypeError: optimize(): 1st arg can't be coerced to

I'm quite confused about how to use the optimization in Jython and the examples are all Java version.

Body:
I've given up this plan and find another method to perform the fminsearch in Jython. Below is the Jython version code:

import sys
sys.path.append('.../jnumeric-2.5.1_ra0.1.jar')   #add the jnumeric path
import Numeric as np
def nelder_mead(f, x_start,
                step=0.1, no_improve_thr=10e-6,
                no_improv_break=10, max_iter=0,
                alpha=1., gamma=2., rho=-0.5, sigma=0.5):
    '''
        @param f (function): function to optimize, must return a scalar score
            and operate over a numpy array of the same dimensions as x_start
        @param x_start (float list): initial position
        @param step (float): look-around radius in initial step
        @no_improv_thr,  no_improv_break (float, int): break after no_improv_break iterations with
            an improvement lower than no_improv_thr
        @max_iter (int): always break after this number of iterations.
            Set it to 0 to loop indefinitely.
        @alpha, gamma, rho, sigma (floats): parameters of the algorithm
            (see Wikipedia page for reference)

        return: tuple (best parameter array, best score)
    '''

    # init
    dim = len(x_start)
    prev_best = f(x_start)
    no_improv = 0
    res = [[np.array(x_start), prev_best]]

    for i in range(dim):
        x=np.array(x_start)
        x[i]=x[i]+step
        score = f(x)
        res.append([x, score])

    # simplex iter
    iters = 0
    while 1:
        # order
        res.sort(key=lambda x: x[1])
        best = res[0][1]

        # break after max_iter
        if max_iter and iters >= max_iter:
            return res[0]
        iters += 1

        # break after no_improv_break iterations with no improvement
        print '...best so far:', best

        if best < prev_best - no_improve_thr:
            no_improv = 0
            prev_best = best
        else:
            no_improv += 1

        if no_improv >= no_improv_break:
            return res[0]

        # centroid
        x0 = [0.] * dim
        for tup in res[:-1]:
            for i, c in enumerate(tup[0]):
                x0[i] += c / (len(res)-1)

        # reflection
        xr = x0 + alpha*(x0 - res[-1][0])
        rscore = f(xr)
        if res[0][1] <= rscore < res[-2][1]:
            del res[-1]
            res.append([xr, rscore])
            continue

        # expansion
        if rscore < res[0][1]:
            xe = x0 + gamma*(x0 - res[-1][0])
            escore = f(xe)
            if escore < rscore:
                del res[-1]
                res.append([xe, escore])
                continue
            else:
                del res[-1]
                res.append([xr, rscore])
                continue

        # contraction
        xc = x0 + rho*(x0 - res[-1][0])
        cscore = f(xc)
        if cscore < res[-1][1]:
            del res[-1]
            res.append([xc, cscore])
            continue

        # reduction
        x1 = res[0][0]
        nres = []
        for tup in res:
            redx = x1 + sigma*(tup[0] - x1)
            score = f(redx)
            nres.append([redx, score])
        res = nres

And the test example is as below:

def f(x):
        return x[0]**2+x[1]**2+x[2]**2

print nelder_mead(f,[3.4,2.3,2.2])

Actually, the original version is for python, and the link below is the source:
https://github.com/fchollet/nelder-mead


问:
Qt tool window resizable on Mac
I have a Qt window with the following flags:

```<code>Qt::CustomizeWindowHint
|Qt::Tool
|Qt::WindowCloseButtonHint
|Qt::WindowTitleHint
|Qt::MSWindowsFixedSizeDialogHint
</code>```

On Mac, it has a resizable corner. How can I get rid of it? Specifying

```<code>setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
</code>```

does not help. In fact, with the fixed-size policy the window acts weird when I try to resize - it disappears from foreground and becomes disabled for some reason.

I don't mind dropping to the native API level.

答: This is in the Qt FAQ.</p>

Title: Qt tool window resizable on Mac

Body:
I have a Qt window with the following flags:

Qt::CustomizeWindowHint
|Qt::Tool
|Qt::WindowCloseButtonHint
|Qt::WindowTitleHint
|Qt::MSWindowsFixedSizeDialogHint

On Mac, it has a resizable corner. How can I get rid of it? Specifying

setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

does not help. In fact, with the fixed-size policy the window acts weird when I try to resize - it disappears from foreground and becomes disabled for some reason.

I don't mind dropping to the native API level.

Body: This is in the Qt FAQ.


答:
For the first three outputs, Array#map works.

It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

The ECMA 262 standard to Array.from describes a construction with length for a new array (point 7 ff).

var x = Array(4),
    y = Array.from({ length: 4 }),
    arrayX = x.map(Math.random),
    arrayY = y.map(Math.random),
    z = Array.from({ length: 4 }, Math.random);

console.log(x);
console.log(y);
console.log(arrayX);
console.log(arrayY);
console.log(z);```

Title: Manufacturing an array - why is it different?


问:
Is there a Java equivalent to C#'s 'yield' keyword?
I know there is no direct equivalent in Java itself, but perhaps a third party?

It is really convenient. Currently I'd like to implement an iterator that yields all nodes in a tree, which is about five lines of code with yield.

答:
Stream.iterate(seed, seedOperator).limit(n).foreach(action) is not the same as yield operator, but it may be usefull to write your own generators this way:

```<code>import java.util.stream.Stream;
public class Test01 {
    private static void myFoo(int someVar){
        //do some work
        System.out.println(someVar);
    }
    private static void myFoo2(){
        //do some work
        System.out.println("some work");
    }
    public static void main(String[] args) {
        Stream.iterate(1, x -> x + 1).limit(15).forEach(Test01::myFoo);     //var1
        Stream.iterate(1, x -> x + 1).limit(10).forEach(item -> myFoo2());  //var2
    }
}
</code>```

Body:
Stream.iterate(seed, seedOperator).limit(n).foreach(action) is not the same as yield operator, but it may be usefull to write your own generators this way:

import java.util.stream.Stream;
public class Test01 {
    private static void myFoo(int someVar){
        //do some work
        System.out.println(someVar);
    }
    private static void myFoo2(){
        //do some work
        System.out.println("some work");
    }
    public static void main(String[] args) {
        Stream.iterate(1, x -> x + 1).limit(15).forEach(Test01::myFoo);     //var1
        Stream.iterate(1, x -> x + 1).limit(10).forEach(item -> myFoo2());  //var2
    }
}


问:
Affects variables in php with popen
I have this php code :

<?php
while (@ ob_end_flush()); // end all output buffers if any

$proc = popen("test.o", 'r');
echo '```';
while (!feof($proc))
{
    $a = fread($proc, 1);;
 echo $a;
    @ flush();
}
echo '```';
?>```
</div>
</div>
</p>

<p>and test.o which comes from test.c :</p>

<p>test.c : </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-css lang-css prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>

void main()
{
 int a=0;
  int b=1;
 printf("%d\n",a);
 printf("%d\n",b);
}</code>```

When I run the php code it give me 0 and 1, but how do you affect this two numbers in each new variables ?

I mean, I would like to put each line in a variable and after I made echo of one variable for example.

The fact is that after this exemple I will use it for reading data from another C file which the output will be not only 2 lines but an undefined lines.

Thanks.

答:
Use fgets() to read a line. Do it in a loop that adds to an array.

```<code>$proc = popen("test.o", 'r');
$lines = array();
while ($line = fgets($proc)) {
    $lines[] = trim($line);
}
pclose($proc);
var_dump($lines);
</code>```

trim() will remove the newlines after each line.

See also PHP - while loop (!feof()) isn't outputting/showing everything

Title: Affects variables in php with popen

Body:
I have this php code :

<?php
while (@ ob_end_flush()); // end all output buffers if any

$proc = popen("test.o", 'r');
echo '
';
while (!feof($proc))
{
    $a = fread($proc, 1);;
 echo $a;
    @ flush();
}
echo '
';
?>

and test.o which comes from test.c :

test.c :

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

void main()
{
 int a=0;
  int b=1;
 printf("%d\n",a);
 printf("%d\n",b);
}

When I run the php code it give me 0 and 1, but how do you affect this two numbers in each new variables ?

I mean, I would like to put each line in a variable and after I made echo of one variable for example.

The fact is that after this exemple I will use it for reading data from another C file which the output will be not only 2 lines but an undefined lines.

Thanks.

Body:
Use fgets() to read a line. Do it in a loop that adds to an array.

$proc = popen("test.o", 'r');
$lines = array();
while ($line = fgets($proc)) {
    $lines[] = trim($line);
}
pclose($proc);
var_dump($lines);

trim() will remove the newlines after each line.

See also PHP - while loop (!feof()) isn't outputting/showing everything


问:
Application deployed via windows store
I am considering deploying my application via the windows store apart from the traditional website download (via an msi).

I created the appx package with the Desktop App Converter tool.

The application does some updates checks, and when being deployed via the windows store I would like to disable such checks.

The question is how to detect if the application was deployed via normal msi or via the windows store.

答:
To add to nikos' comment, GetCurrentPackageFamilyName will return an error APPMODEL_ERROR_NO_PACKAGE if it's run outside the UWP context (i.e. the MSI scenario you mention).

Note that this API is dependent on Windows 8 or greater, which will preclude the app from running on Windows 7. Your can work around this by dynamically loading the API. More info here.

Title: Application deployed via windows store


问:
Java regex - alphanumeric, at most one hyphen, period or underscore, seven characters long
I'm new to the regex tool in Java, and despite their great potential I'm having a hard time accomplishing this task. I want to write a regex to validate an input string which respects the following syntax:

any combination of lowercase letters and digits

only one underscore, one dash or one period (no other special characters)

minimum length of 5

I came up with the following solution:

([/./-_]{0,1}[a-z0-9]){5,}

but in some cases it still doesn't work, for example it does not match a string where one of the special characters allowed is in the middle (such as he-llo). Where did I go wrong? Is there any other pattern better than this for my purpose?

答:
You could do it all in one regex:

```<code>^                        # start string
(?=[^-_.]*[-_.][^-_.]*$) # lookahead fulfilling condition 2
([-_.\w]{5,})            # all allowed characters at least 5
$                        # end of string
</code>```

See a demo on regex101.com and note that you'll need double backslashes in Java, so that your expression becomes:

```<code>^(?=[^-_.]*[-_.][^-_.]*$)([-_.\\w]{5,})$
</code>```

Body:
You could do it all in one regex:

^                        # start string
(?=[^-_.]*[-_.][^-_.]*$) # lookahead fulfilling condition 2
([-_.\w]{5,})            # all allowed characters at least 5
$                        # end of string

See a demo on regex101.com and note that you'll need double backslashes in Java, so that your expression becomes:

^(?=[^-_.]*[-_.][^-_.]*$)([-_.\\w]{5,})$


问:
JAVA- Returning an Array to main
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main.  When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.

In main:

```<code>// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);
</code>```

In getAnswers():

```<code>// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}
</code>```

答:
try

```<code>array2[index] = input.charAt(0);
</code>```

after you obtain the value into the input variable instead of assigning it a new char array every time through the loop.

Title: JAVA- Returning an Array to main

Body:
In the program I'm working on, I created a loop to receive 20 individual characters as user input, convert to char, store in array2, and return array2 to main.  When I ran the program I wrote, it seems that the code I wrote didn't store the chars in array2 properly.

In main:

// Create array to hold user's answers, and pass answers to the array.
char array2[ ] = new char[20];
getAnswers(array2);

In getAnswers():

// getAnswers method requests user input and passes to array2.
public static char[ ] getAnswers(char array2[ ])
{
   String input;  // Holds user input.

   Scanner keyboard = new Scanner(System.in);

   // Request user input.
   System.out.println("Enter the answers for the the multiple choice exam.");

   // Loop to receive input into array.
   for (int index = 0; index < 20; index++)
   {
      System.out.print("Enter number " + (index + 1) +": ");
      input = keyboard.nextLine();
      array2 = input.toCharArray();
   }
   return array2;
}

Body:
try

array2[index] = input.charAt(0);

after you obtain the value into the input variable instead of assigning it a new char array every time through the loop.


问:
Mockito: Trying to spy on method is calling the original method
I'm using Mockito 1.9.0.  I want mock the behaviour for a single method of a class in a JUnit test, so I have

```<code>final MyClass myClassSpy = Mockito.spy(myInstance);
Mockito.when(myClassSpy.method1()).thenReturn(myResults);
</code>```

The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception.  The only reason I'm using mocks is so that later, whenever myClassSpy.method1() is called, the real method won't be called and the myResults object will be returned.

MyClass is an interface and myInstance is an implementation of that, if that matters.

What do I need to do to correct this spying behaviour?

答: In my case, using Mockito 2.0, I had to change all the any() parameters to nullable() in order to stub the real call.

Body:
I'm using Mockito 1.9.0.  I want mock the behaviour for a single method of a class in a JUnit test, so I have

final MyClass myClassSpy = Mockito.spy(myInstance);
Mockito.when(myClassSpy.method1()).thenReturn(myResults);

The problem is, in the second line, myClassSpy.method1() is actually getting called, resulting in an exception.  The only reason I'm using mocks is so that later, whenever myClassSpy.method1() is called, the real method won't be called and the myResults object will be returned.

MyClass is an interface and myInstance is an implementation of that, if that matters.

What do I need to do to correct this spying behaviour?


问:
PowerShell - comparing large fixed width file to large SQL table
I'm a software guy, but in my second week of PowerShell knowledge.

We have a set of 12 fixed-width format files containing lists of people (records can possibly be duplicated).  These files are about 800MB each  with a total combined row count of about 14 million.  Looking at the first file, it contains 1,201,940 rows.

Additionally, we have a SQL table that should contain all that data (distinct records).  I've been tasked to use PowerShell to ensure the data is fully loaded by comparing a few select fields in the source files against the SQL table, and then writing any missing records to a CSV log.

Let's assume my fields of interest are ID, FirstName, LastName, and for all situations I am limiting my objects/queries to only consider those fields.

What would be the most ideal methodology in PowerShell to compare the data?  Do you bundle the data out to SQL, make it do the work, then retrieve results, or bundle all the data to PowerShell and work on it there?

I've thought of the following Ideas, but have not tested them:

Create a SQL table variable (@fileInfo).  Create a DataTable from the file ($dtFile). Using $dtFile, for every X number of rows, load @fileInfo.  Perform a LEFT JOIN between @fileInfo and the SQL table and shove the results into a DataTable ($dtResults).  Write $dtResults to the log.  Empty the contents of @fileInfo to prepare for the next iteration of the loop.  This seems like my best idea.

Create a DataTable from the file ($dtFile). Using $dtFile, for every X number of rows, construct a SQL select statement that has a terrible looking WHERE clause that limits the rows the database returns.  Shove that in another DataTable ($dtSQL).  Compare the two and log any entries in $dtFile that don't appear in $dtSQL.  Looks gross, but works.

Load all 1.2m records from the file into a DataTable. Bulk insert them to a SQL temporary table, LEFT JOIN against the SQL table, retrieve results and write results to the log.  I assume I would get bogged due to shoving a bunch of data over the network

Load all records from the SQL table to a DataTable, Load all records from the file into a second DataTable, compare the results in PowerShell and write results to the log.  I assume that I would run out of memory...?

I would create scripts for each solution and do a test myself, but I'm under a time crunch and don't have the luxury.  Isn't that always the situation?

Edit:  I posted a solution that worked for me below

答:
Sorry all for not being timely on replying, but I have a solution!  There's most likely room for improvement, but the solution is reasonably quick.  I didn't have access to my database to run PowerShell directly against it, so I'm making use of the SQL Import and Export Wizard at the end.

Summary of process:

Create a CSV file of data points, which will be consumed as an object array in PowerShell.

Find the files of interest and store them into a string array (possibly not necessary, but it seemed to be speedier)

Cycle through each file found in your string array.  For each file, open a .NET StreamReader, and for each line, parse the file against your object array of data points to create substrings that you write to a single, consolidated, delimited, output file.  I recommend the pipe character (looks like this: |, typically above Enter) because it typically isn't found in data, whereas a rogue comma or tab character may trip you up.

Once the script is complete, use the import wizard in SQL to create a table from your output file

Detail

Create a CSV file that lists your data points in column A, the starting position in column B, and the widths in column C.  It would look something like this:

Import your data points in your script by utilizing an object array.

```<code>$dataPoints = Import-Csv "c:\temp\datapoints.csv"
$objDataCols = @()
foreach($objCol in $dataPoints){
    objColumn = New-Object psobject
    $objColumn | Add-Member -Type NoteProperty -Name Name -Value $objCol.Name
    $objColumn | Add-Member -Type NoteProperty -Name Position -Value ([int] $objCol.Position)
    $objColumn | Add-Member -Type NoteProperty -Name ColumnLength -Value ([int] $objCol.ColumnLength)
    $objSourceCols += $objColumn
}
</code>```

Find the files and assemble the names to an array (optional).  I used a regular expression to filter for my files.

```<code>$files = @()
Get-ChildItem -Path $sourceFilePath | Where-Object { $_.FullName -match $regExpression } | ForEach-Object{
    $files += $_.FullName
}
</code>```

Loop through each file and parse them to an output file.  In production code, you would want try/catch blocks, but I left them out in the example.

```<code>$writer = New-Object System.IO.StreamWriter "c:\temp\outputFile.txt"
ForEach($sourceFileName in $files){
    $reader = [System.IO.File]::OpenText($sourceFileName)
    while($reader.Peek() -gt -1){
        $line = $reader.ReadLine()

        # Write each data point in the line, pipe delimited
        for($i = 0; $j -le ($objDataCols).Length; $i++){
            # Write to a pipe-delimited file
            $writer.Write("{0}|", $line.Substring($objDataCols[$i].Position, $objDataCols[$i].ColumnLength))
        }

        # Write a new line, along with any additional reference columns not defined in the source file, such as adding in the source file name and line number
        $writer.WriteLine($sourceFileName)
    }
    $reader.Close()
    $reader.Dispose()
}
$writer.Close()
$writer.Dispose()
</code>```

Import the pipe-delimited output file into SQL.

Body:
Sorry all for not being timely on replying, but I have a solution!  There's most likely room for improvement, but the solution is reasonably quick.  I didn't have access to my database to run PowerShell directly against it, so I'm making use of the SQL Import and Export Wizard at the end.

Summary of process:

Create a CSV file of data points, which will be consumed as an object array in PowerShell.

Find the files of interest and store them into a string array (possibly not necessary, but it seemed to be speedier)

Cycle through each file found in your string array.  For each file, open a .NET StreamReader, and for each line, parse the file against your object array of data points to create substrings that you write to a single, consolidated, delimited, output file.  I recommend the pipe character (looks like this: |, typically above Enter) because it typically isn't found in data, whereas a rogue comma or tab character may trip you up.

Once the script is complete, use the import wizard in SQL to create a table from your output file

Detail

Create a CSV file that lists your data points in column A, the starting position in column B, and the widths in column C.  It would look something like this:

Import your data points in your script by utilizing an object array.

$dataPoints = Import-Csv "c:\temp\datapoints.csv"
$objDataCols = @()
foreach($objCol in $dataPoints){
    objColumn = New-Object psobject
    $objColumn | Add-Member -Type NoteProperty -Name Name -Value $objCol.Name
    $objColumn | Add-Member -Type NoteProperty -Name Position -Value ([int] $objCol.Position)
    $objColumn | Add-Member -Type NoteProperty -Name ColumnLength -Value ([int] $objCol.ColumnLength)
    $objSourceCols += $objColumn
}

Find the files and assemble the names to an array (optional).  I used a regular expression to filter for my files.

$files = @()
Get-ChildItem -Path $sourceFilePath | Where-Object { $_.FullName -match $regExpression } | ForEach-Object{
    $files += $_.FullName
}

Loop through each file and parse them to an output file.  In production code, you would want try/catch blocks, but I left them out in the example.

$writer = New-Object System.IO.StreamWriter "c:\temp\outputFile.txt"
ForEach($sourceFileName in $files){
    $reader = [System.IO.File]::OpenText($sourceFileName)
    while($reader.Peek() -gt -1){
        $line = $reader.ReadLine()

        # Write each data point in the line, pipe delimited
        for($i = 0; $j -le ($objDataCols).Length; $i++){
            # Write to a pipe-delimited file
            $writer.Write("{0}|", $line.Substring($objDataCols[$i].Position, $objDataCols[$i].ColumnLength))
        }

        # Write a new line, along with any additional reference columns not defined in the source file, such as adding in the source file name and line number
        $writer.WriteLine($sourceFileName)
    }
    $reader.Close()
    $reader.Dispose()
}
$writer.Close()
$writer.Dispose()

Import the pipe-delimited output file into SQL.


问:
Section information from a JSON Object in a section
I find this quite hard to explain as you can see in the title but let's say this is how my object looks like,

```<code>{
   "success":true,
   "objects":[
      {
         "name":"Stick",
         "value":"wood",
         "size":"large"
      }...
    ]
}
</code>```

Now I'm trying to get all the data where the objects name is Stick, so basically if it's "name" is stick it should return, name, value and size.

答:
Thanks to ES5 you can use map and filter as this:</p>

```<code>var obj = {
     "success":true,
     "objects":[
        {
           "name":"Stick",
           "value":"wood",
           "size":"large"
        }
     ]
}.objects
 .filter(function(object) {return object.name === "Stick"})
 .map(function(object) {return {value: object.value, size: object.size}})
</code>```

Body:
I find this quite hard to explain as you can see in the title but let's say this is how my object looks like,

{
   "success":true,
   "objects":[
      {
         "name":"Stick",
         "value":"wood",
         "size":"large"
      }...
    ]
}

Now I'm trying to get all the data where the objects name is Stick, so basically if it's "name" is stick it should return, name, value and size.

Body:
Thanks to ES5 you can use map and filter as this:

var obj = {
     "success":true,
     "objects":[
        {
           "name":"Stick",
           "value":"wood",
           "size":"large"
        }
     ]
}.objects
 .filter(function(object) {return object.name === "Stick"})
 .map(function(object) {return {value: object.value, size: object.size}})


问:
On click get input value using jQuery
I have the following:

```<code>$('.checkbox').click(function () {
      console.log(this);
      $.ajax({
        type:'POST',
        url: '/loadProducts',
        data: {},
        success: function(response) {
               console.log(response);
               $('.js-products').html(response);
        }});
    return false;
});
</code>```

Now where I do the console.log(this), it returns:

```<code><div class="ui checkbox checked">
    <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
    <label>Women</label>
</div>
</code>```

How do I get the input name (gender)? And whether the checkbox is checked out or not?

答:
If I interpret the question correctly, you can pass an HTML string response to jQuery() to create a jQuery object from the HTML string, then call .attr("name") and .prop("checked"):

```<code>var input = $(response).find("input");
console.log(input.attr("name"), input.prop("checked"));
</code>```

How do I get the input name (gender)? And whether the checkbox is
  checked out not?

If you are trying to get the .name and .checked property values of clicked element you can call .querySelector() chained to this: .checkbox element, with selector "input[type=checkbox]"; .getAttribute() with "name" as parameter, .replace() with RegExp /^\w+\[|\]/g to get word within "[", "]"; and .checked property of the matched element returned by .querySelector()

```<code>   $(".checkbox").click(function () {
      var input = this.querySelector("input[type=checkbox]");
      var _name = input.getAttribute("name").replace(/^\w+\[|\]/g, "");
      var checked = input.checked;
      console.log(_name, checked);
      $.ajax(/* settings */);
   });
</code>```

Title: On click get input value using jQuery

Body:
I have the following:

$('.checkbox').click(function () {
      console.log(this);
      $.ajax({
        type:'POST',
        url: '/loadProducts',
        data: {},
        success: function(response) {
               console.log(response);
               $('.js-products').html(response);
        }});
    return false;
});

Now where I do the console.log(this), it returns:

    <input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
    Women

How do I get the input name (gender)? And whether the checkbox is checked out or not?

Body:
If I interpret the question correctly, you can pass an HTML string response to jQuery() to create a jQuery object from the HTML string, then call .attr("name") and .prop("checked"):

var input = $(response).find("input");
console.log(input.attr("name"), input.prop("checked"));

How do I get the input name (gender)? And whether the checkbox is
  checked out not?

If you are trying to get the .name and .checked property values of clicked element you can call .querySelector() chained to this: .checkbox element, with selector "input[type=checkbox]"; .getAttribute() with "name" as parameter, .replace() with RegExp /^\w+\[|\]/g to get word within "[", "]"; and .checked property of the matched element returned by .querySelector()

   $(".checkbox").click(function () {
      var input = this.querySelector("input[type=checkbox]");
      var _name = input.getAttribute("name").replace(/^\w+\[|\]/g, "");
      var checked = input.checked;
      console.log(_name, checked);
      $.ajax(/* settings */);
   });


问:
MINIX 2 - syscall to kernel
I want to make 2 syscalls to kernel (getlot and setlot). They have to read and set some value in struct proc, which is in kernel. What is the problem? What is missing?

In /usr/include/minix/callnr.h I increased NCALLS and add 2 define

```<code> #define NCALLS       80    /* number of system calls allowed */

 #define SETLOT       78
 #define GETLOT       79
</code>```

In usr/src/mm/main.c

```<code>PUBLIC void do_setlot()
{
    message msg;
    msg = mm_in;
   _taskcall(SYSTASK, SYS_SETLOT), &msg);
}

PUBLIC void do_getlot()
{
    message msg;
    msg = mm_in;
   _taskcall(SYSTASK, SYS_GETLOT, &msg);
}
</code>```

In /usr/src/mm/proto.h I added two prototypes

```<code>_PROTOTYPE( void do_setlot, (void));
_PROTOTYPE( void do_getlot, (void));
</code>```

In /usr/src/mm/table.c I added to the end of _PROTOTYPE (int (*call_vec[NCALLS]), (void) )

```<code>do_setlot,
do_getlot,
</code>```

In /usr/src/fs/table.c I added to the end of_PROTOTYPE (int (*call_vec[]), (void) )

```<code>no_sys,
no_sys,
</code>```

In /usr/include/minix/com.h I created 2 SYS_xxx define

```<code>#   define SYS_SETLOT    22
#   define SYS_GETLOT    23
</code>```

In /usr/src/kernel/system.c I wrote

```<code>FORWARD _PROTOTYPE( int do_procsetlot, (message *m_ptr) );
FORWARD _PROTOTYPE( int do_procgetlot, (message *m_ptr) );
</code>```

Then added SYS_xxx to switch in PUBLIC void sys_task()

```<code>case SYS_SETLOT:    r = do_procsetlot(&m);  break;
case SYS_GETLOT:    r = do_procgetlot(&m);  break;
</code>```

And at the bottom I wrote 2 definions

```<code>PRIVATE int do_procsetlot(m_ptr)
register message *m_ptr;
{
  pid_t prid;
  int i;
  int tickets;
  prid = m_ptr->m1_i1;
  tickets = m_ptr->m1_i2;

  if(tickets > LOT_MAX)
    return EINVAL;
  if(tickets < LOT_MIN)
    return EINVAL;
  for(i = 0 ; i <NR_PROCS; i++)
  {
     if(proc[i].p_pid == prid)
     {
       proc[i].tickets_number = tickets;
       return 0;
     }
  {
  return EINVAL;
 }

PRIVATE int do_procgetlot(m_ptr)
register message *m_ptr;
{
  int i;
  pid_t prid;
  prid = m_ptr->m1_i1;

  for(i = 0 ; i< NR_PROCS; i++)
  {
    if(proc[i].p_pid == prid)
        return proc[i].tickets_number;
  }
 return EINVAL;
}
</code>```

Finally after make hdboot I got error:

```<code>exec cc -c -I/usr/include main.c
exec cc -c -I/usr/include proc.c
exec cc -c -I/usr/include system.c
"system.c", line 1260: static not expected
make in /usr/src/kernel: Exit code 1
</code>```

Line 1260 is

```<code>PRIVATE int do_procgetlot(m_ptr)
</code>```

答:
I know this message is years old, but...

You have a syntax error at the bottom of do_procsetlot:

```<code>  {
  return EINVAL;
 }
</code>```

...should be:

```<code>  }
  return EINVAL;
 }
</code>```

I hope you figured it out yourself some time in 2014!

BTW, the Minix 2 compiler totally supports ANSI C, so you shouldn't need all the K&Risms.

Title: MINIX 2 - syscall to kernel

Body:
I want to make 2 syscalls to kernel (getlot and setlot). They have to read and set some value in struct proc, which is in kernel. What is the problem? What is missing?

In /usr/include/minix/callnr.h I increased NCALLS and add 2 define

 #define NCALLS       80    /* number of system calls allowed */

 #define SETLOT       78
 #define GETLOT       79

In usr/src/mm/main.c

PUBLIC void do_setlot()
{
    message msg;
    msg = mm_in;
   _taskcall(SYSTASK, SYS_SETLOT), &msg);
}

PUBLIC void do_getlot()
{
    message msg;
    msg = mm_in;
   _taskcall(SYSTASK, SYS_GETLOT, &msg);
}

In /usr/src/mm/proto.h I added two prototypes

_PROTOTYPE( void do_setlot, (void));
_PROTOTYPE( void do_getlot, (void));

In /usr/src/mm/table.c I added to the end of _PROTOTYPE (int (*call_vec[NCALLS]), (void) )

do_setlot,
do_getlot,

In /usr/src/fs/table.c I added to the end of_PROTOTYPE (int (*call_vec[]), (void) )

no_sys,
no_sys,

In /usr/include/minix/com.h I created 2 SYS_xxx define

#   define SYS_SETLOT    22
#   define SYS_GETLOT    23

In /usr/src/kernel/system.c I wrote

FORWARD _PROTOTYPE( int do_procsetlot, (message *m_ptr) );
FORWARD _PROTOTYPE( int do_procgetlot, (message *m_ptr) );

Then added SYS_xxx to switch in PUBLIC void sys_task()

case SYS_SETLOT:    r = do_procsetlot(&m);  break;
case SYS_GETLOT:    r = do_procgetlot(&m);  break;

And at the bottom I wrote 2 definions

PRIVATE int do_procsetlot(m_ptr)
register message *m_ptr;
{
  pid_t prid;
  int i;
  int tickets;
  prid = m_ptr->m1_i1;
  tickets = m_ptr->m1_i2;

  if(tickets > LOT_MAX)
    return EINVAL;
  if(tickets < LOT_MIN)
    return EINVAL;
  for(i = 0 ; i <NR_PROCS; i++)
  {
     if(proc[i].p_pid == prid)
     {
       proc[i].tickets_number = tickets;
       return 0;
     }
  {
  return EINVAL;
 }

PRIVATE int do_procgetlot(m_ptr)
register message *m_ptr;
{
  int i;
  pid_t prid;
  prid = m_ptr->m1_i1;

  for(i = 0 ; i< NR_PROCS; i++)
  {
    if(proc[i].p_pid == prid)
        return proc[i].tickets_number;
  }
 return EINVAL;
}

Finally after make hdboot I got error:

exec cc -c -I/usr/include main.c
exec cc -c -I/usr/include proc.c
exec cc -c -I/usr/include system.c
"system.c", line 1260: static not expected
make in /usr/src/kernel: Exit code 1

Line 1260 is

PRIVATE int do_procgetlot(m_ptr)

Body:
I know this message is years old, but...

You have a syntax error at the bottom of do_procsetlot:

  {
  return EINVAL;
 }

...should be:

  }
  return EINVAL;
 }

I hope you figured it out yourself some time in 2014!

BTW, the Minix 2 compiler totally supports ANSI C, so you shouldn't need all the K&Risms.


问:
Xcode trying to match frameworks bundle ID when uploading iOS app to App Store
After 4 months developing my first iOS app, it's time to submit it to the App Store. I created the app in iTunes Connect, filled in all the details, set up the correct Bundle ID in both Connect and Xcode. However, I've struggled the last 3 days trying to solve this weird problem. It seems like xcode is trying to upload Cocoapods frameworks, not my main app.

After archiving, I went to Window > Organizer > Validate.... I see the following screen:

The error:

(For googlers: No suitable application records were found. Verify your bundle identifier 'org.cocoapods.Alamofire' is correct).

The error message indicates that it's trying to match a Bundle ID according to a framework's name, not my own bundle (e.g com.organization.AppName). I can't find answers anywhere. I tried doing the following in my Podfile (which has use_frameworks!), as well as my different conf combinations but had no success.

```<code>post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|

      config.build_settings['EXPANDED_CODE_SIGN_IDENTITY'] = ""
      config.build_settings['CODE_SIGNING_REQUIRED'] = "NO"
      config.build_settings['CODE_SIGNING_ALLOWED'] = "NO"
    end
  end
end
</code>```

Questions:

Are the steps I'm making correct?

Why is Xcode trying to match a framework's bundle id instead of just my main application?

How can I get past this problem to finally submit my app?

EDIT 1: I was able to get past this problem, but that caused another problem later, so I still don't have a solution. Basically, Alamofire Pod (from Cocoapods) has a bundle id com.xxx.Alamofire. I changed it to com.xxx.myAppName. With that, I was able to send it to the App Store, however I can't install the app in my iPhone from TestFlight due to the following error:

```<code>4/22/16, 12:50:29 AM itunesstored[124]: [ApplicationWorkspace]: Failed to install application: com.xxx.myAppName; /var/mobile/Media/Downloads/5927832272594571027/-6969961974973998640; Error Domain=LaunchServicesError Code=0 "(null)" UserInfo={Error=DuplicateIdentifier, ErrorDescription=The parent bundle has the same identifier (com.xxx.myAppName) as sub-bundle at /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.IVHCuO/extracted/Payload/MyApp.app/Frameworks/Alamofire.framework}
</code>```

答: In my case I had to remove Provisioning profile setting from Pods sub-project

Body:
After 4 months developing my first iOS app, it's time to submit it to the App Store. I created the app in iTunes Connect, filled in all the details, set up the correct Bundle ID in both Connect and Xcode. However, I've struggled the last 3 days trying to solve this weird problem. It seems like xcode is trying to upload Cocoapods frameworks, not my main app.

After archiving, I went to Window > Organizer > Validate.... I see the following screen:

The error:

(For googlers: No suitable application records were found. Verify your bundle identifier 'org.cocoapods.Alamofire' is correct).

The error message indicates that it's trying to match a Bundle ID according to a framework's name, not my own bundle (e.g com.organization.AppName). I can't find answers anywhere. I tried doing the following in my Podfile (which has use_frameworks!), as well as my different conf combinations but had no success.

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|

      config.build_settings['EXPANDED_CODE_SIGN_IDENTITY'] = ""
      config.build_settings['CODE_SIGNING_REQUIRED'] = "NO"
      config.build_settings['CODE_SIGNING_ALLOWED'] = "NO"
    end
  end
end

Questions:

Are the steps I'm making correct?

Why is Xcode trying to match a framework's bundle id instead of just my main application?

How can I get past this problem to finally submit my app?

EDIT 1: I was able to get past this problem, but that caused another problem later, so I still don't have a solution. Basically, Alamofire Pod (from Cocoapods) has a bundle id com.xxx.Alamofire. I changed it to com.xxx.myAppName. With that, I was able to send it to the App Store, however I can't install the app in my iPhone from TestFlight due to the following error:

4/22/16, 12:50:29 AM itunesstored[124]: [ApplicationWorkspace]: Failed to install application: com.xxx.myAppName; /var/mobile/Media/Downloads/5927832272594571027/-6969961974973998640; Error Domain=LaunchServicesError Code=0 "(null)" UserInfo={Error=DuplicateIdentifier, ErrorDescription=The parent bundle has the same identifier (com.xxx.myAppName) as sub-bundle at /private/var/installd/Library/Caches/com.apple.mobile.installd.staging/temp.IVHCuO/extracted/Payload/MyApp.app/Frameworks/Alamofire.framework}


问:
Neural Network for Recognition of Handwritten Digits in C#
I've gone through very good code project article about the Neural Network for Recognition of Handwritten Digits in C# by a code project contributor named Vietdungiitb.

Here's the link for the Project :

http://www.codeproject.com/Articles/143059/Neural-Network-for-Recognition-of-Handwritten-Digi

But, there was a code sample provided and I ran the code but, I had this error 'Format Exception was unhandled'.

In the Preferences.cs file.

```<code>private void Get(string lpAppName, string lpKeyName, out double nDefault)
{

       nDefault = Convert.ToDouble(m_Inifile.IniReadValue(lpAppName, lpKeyName));
       return;
}
</code>```

Above Code lines produced the run time exception.

```<code>System.FormatException was unhandled
  HResult=-2146233033
  Message=Input string was not in a correct format.
  Source=mscorlib
  StackTrace:
       at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
       at System.Convert.ToDouble(String value)
       at NeuralNetworkLibrary.Preferences.Get(String lpAppName, String lpKeyName, Double& nDefault) in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\NeuralNetworkLibrary\ArchiveSerialization\Preferences.cs:line 178
       at NeuralNetworkLibrary.Preferences.ReadIniFile() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\NeuralNetworkLibrary\ArchiveSerialization\Preferences.cs:line 109
       at NeuralNetworkLibrary.Preferences..ctor() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\NeuralNetworkLibrary\ArchiveSerialization\Preferences.cs:line 97
       at HandwrittenRecogniration.Mainform..ctor() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\HandwrittenRecognition\Mainform.cs:line 66
       at HandwrittenRecogniration.Program.Main() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\HandwrittenRecognition\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
</code>```

There's no enough answers provided for this problem. So, I was wondering if anybody had this problem when they ran this project ?

Full Preferences.cs is as follows.

```<code>using System;

namespace NeuralNetworkLibrary
{
    public class Preferences
    {
        public const int g_cImageSize = 28;
        public const int g_cVectorSize = 29;

        public int m_cNumBackpropThreads;

        public uint m_nMagicTrainingLabels;
        public uint m_nMagicTrainingImages;

        public uint m_nItemsTrainingLabels;
        public uint m_nItemsTrainingImages;

        public int m_cNumTestingThreads;

        public int m_nMagicTestingLabels;
        public int m_nMagicTestingImages;

        public uint m_nItemsTestingLabels;
        public uint m_nItemsTestingImages;

        public uint m_nRowsImages;
        public uint m_nColsImages;

        public int m_nMagWindowSize;
        public int m_nMagWindowMagnification;

        public double m_dInitialEtaLearningRate;
        public double m_dLearningRateDecay;
        public double m_dMinimumEtaLearningRate;
        public uint m_nAfterEveryNBackprops;

        // for limiting the step size in backpropagation, since we are using second order
        // "Stochastic Diagonal Levenberg-Marquardt" update algorithm.  See Yann LeCun 1998
        // "Gradianet-Based Learning Applied to Document Recognition" at page 41

        public double m_dMicronLimitParameter;
        public uint m_nNumHessianPatterns;

        // for distortions of the input image, in an attempt to improve generalization

        public double m_dMaxScaling;  // as a percentage, such as 20.0 for plus/minus 20%
        public double m_dMaxRotation;  // in degrees, such as 20.0 for plus/minus rotations of 20 degrees
        public double m_dElasticSigma;  // one sigma value for randomness in Simard's elastic distortions
        public double m_dElasticScaling;  // after-smoohting scale factor for Simard's elastic distortions
        private IniFile m_Inifile;
        ////////////
        public Preferences()
        {
            // set default values

            m_nMagicTrainingLabels = 0x00000801;
            m_nMagicTrainingImages = 0x00000803;

            m_nItemsTrainingLabels = 60000;
            m_nItemsTrainingImages = 60000;

            m_nMagicTestingLabels = 0x00000801;
            m_nMagicTestingImages = 0x00000803;

            m_nItemsTestingLabels = 10000;
            m_nItemsTestingImages = 10000;

            m_nRowsImages = g_cImageSize;
            m_nColsImages = g_cImageSize;

            m_nMagWindowSize = 5;
            m_nMagWindowMagnification = 8;

            m_dInitialEtaLearningRate = 0.001;
            m_dLearningRateDecay = 0.794328235;  // 0.794328235 = 0.001 down to 0.00001 in 20 epochs
            m_dMinimumEtaLearningRate = 0.00001;
            m_nAfterEveryNBackprops = 60000;
            m_cNumBackpropThreads = 2;

            m_cNumTestingThreads = 1;

            // parameters for controlling distortions of input image

            m_dMaxScaling = 15.0;  // like 20.0 for 20%
            m_dMaxRotation = 15.0;  // like 20.0 for 20 degrees
            m_dElasticSigma = 8.0;  // higher numbers are more smooth and less distorted; Simard uses 4.0
            m_dElasticScaling = 0.5;  // higher numbers amplify the distortions; Simard uses 34 (sic, maybe 0.34 ??)

            // for limiting the step size in backpropagation, since we are using second order
            // "Stochastic Diagonal Levenberg-Marquardt" update algorithm.  See Yann LeCun 1998
            // "Gradient-Based Learning Applied to Document Recognition" at page 41

            m_dMicronLimitParameter = 0.10;  // since we divide by this, update can never be more than 10x current eta
            m_nNumHessianPatterns = 500;  // number of patterns used to calculate the diagonal Hessian
            String path = System.IO.Directory.GetCurrentDirectory() + "\\Data\\Default-ini.ini";
            m_Inifile = new IniFile(path);
            ReadIniFile();
        }
        public void ReadIniFile()
        {
            // now read values from the ini file

            String tSection;

            // Neural Network parameters

            tSection = "Neural Network Parameters";

            Get(tSection, "Initial learning rate (eta)", out m_dInitialEtaLearningRate);
            Get(tSection, "Minimum learning rate (eta)", out m_dMinimumEtaLearningRate);
            Get(tSection, "Rate of decay for learning rate (eta)", out m_dLearningRateDecay);
            Get(tSection, "Decay rate is applied after this number of backprops", out m_nAfterEveryNBackprops);
            Get(tSection, "Number of backprop threads", out m_cNumBackpropThreads);
            Get(tSection, "Number of testing threads", out m_cNumTestingThreads);
            Get(tSection, "Number of patterns used to calculate Hessian", out m_nNumHessianPatterns);
            Get(tSection, "Limiting divisor (micron) for learning rate amplification (like 0.10 for 10x limit)", out m_dMicronLimitParameter);

            // Neural Network Viewer parameters

            tSection = "Neural Net Viewer Parameters";

            Get(tSection, "Size of magnification window", out m_nMagWindowSize);
            Get(tSection, "Magnification factor for magnification window", out m_nMagWindowMagnification);

            // MNIST data collection parameters

            tSection = "MNIST Database Parameters";

            Get(tSection, "Training images magic number", out m_nMagicTrainingImages);
            Get(tSection, "Training images item count", out m_nItemsTrainingImages);
            Get(tSection, "Training labels magic number", out m_nMagicTrainingLabels);
            Get(tSection, "Training labels item count", out m_nItemsTrainingLabels);

            Get(tSection, "Testing images magic number", out m_nMagicTestingImages);
            Get(tSection, "Testing images item count", out m_nItemsTestingImages);
            Get(tSection, "Testing labels magic number", out m_nMagicTestingLabels);
            Get(tSection, "Testing labels item count", out m_nItemsTestingLabels);

            // these two are basically ignored

            uint uiCount = g_cImageSize;
            Get(tSection, "Rows per image", out uiCount);
            m_nRowsImages = uiCount;

            uiCount = g_cImageSize;
            Get(tSection, "Columns per image", out uiCount);
            m_nColsImages = uiCount;

            // parameters for controlling pattern distortion during backpropagation

            tSection = "Parameters for Controlling Pattern Distortion During Backpropagation";

            Get(tSection, "Maximum scale factor change (percent, like 20.0 for 20%)", out m_dMaxScaling);
            Get(tSection, "Maximum rotational change (degrees, like 20.0 for 20 degrees)", out m_dMaxRotation);
            Get(tSection, "Sigma for elastic distortions (higher numbers are more smooth and less distorted; Simard uses 4.0)", out m_dElasticSigma);
            Get(tSection, "Scaling for elastic distortions (higher numbers amplify distortions; Simard uses 0.34)", out m_dElasticScaling);
        }
        private void Get(string lpAppName, string lpKeyName, out int nDefault)
        {
            nDefault = Convert.ToInt32(m_Inifile.IniReadValue(lpAppName, lpKeyName));
            return;

        }
        private void Get(string lpAppName, string lpKeyName, out uint nDefault)
        {
            nDefault = Convert.ToUInt32(m_Inifile.IniReadValue(lpAppName, lpKeyName));
            return;
        }

        private void Get(string lpAppName, string lpKeyName, out double nDefault)
        {
               nDefault = Convert.ToDouble(m_Inifile.IniReadValue(lpAppName, lpKeyName));
               return;
        }
        private void Get(string lpAppName, string lpKeyName, out byte nDefault)
        {

           nDefault = Convert.ToByte(m_Inifile.IniReadValue(lpAppName, lpKeyName));
           return ;

        }

        private void Get(string lpAppName, string lpKeyName, out string nDefault)
        {
            nDefault = m_Inifile.IniReadValue(lpAppName, lpKeyName);
            return;

        }
        private void Get(string lpAppName, string lpKeyName, out bool nDefault)
        {
            nDefault = Convert.ToBoolean(m_Inifile.IniReadValue(lpAppName, lpKeyName));
            return;
        }

    }
}
</code>```

答:
In this case, the problem is in the decimal point of the default .ini file.</p>

```<code>nDefault = Convert.ToDouble(m_Inifile.IniReadValue(lpAppName, lpKeyName), CultureInfo.InvariantCulture);
</code>```

Body:
I've gone through very good code project article about the Neural Network for Recognition of Handwritten Digits in C# by a code project contributor named Vietdungiitb.

Here's the link for the Project :

http://www.codeproject.com/Articles/143059/Neural-Network-for-Recognition-of-Handwritten-Digi

But, there was a code sample provided and I ran the code but, I had this error 'Format Exception was unhandled'.

In the Preferences.cs file.

private void Get(string lpAppName, string lpKeyName, out double nDefault)
{

       nDefault = Convert.ToDouble(m_Inifile.IniReadValue(lpAppName, lpKeyName));
       return;
}

Above Code lines produced the run time exception.

System.FormatException was unhandled
  HResult=-2146233033
  Message=Input string was not in a correct format.
  Source=mscorlib
  StackTrace:
       at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
       at System.Convert.ToDouble(String value)
       at NeuralNetworkLibrary.Preferences.Get(String lpAppName, String lpKeyName, Double&amp; nDefault) in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\NeuralNetworkLibrary\ArchiveSerialization\Preferences.cs:line 178
       at NeuralNetworkLibrary.Preferences.ReadIniFile() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\NeuralNetworkLibrary\ArchiveSerialization\Preferences.cs:line 109
       at NeuralNetworkLibrary.Preferences..ctor() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\NeuralNetworkLibrary\ArchiveSerialization\Preferences.cs:line 97
       at HandwrittenRecogniration.Mainform..ctor() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\HandwrittenRecognition\Mainform.cs:line 66
       at HandwrittenRecogniration.Program.Main() in c:\Users\PC_USER\Downloads\Example\Code Project\source\HandwrittenRecognition\HandwrittenRecognition\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

There's no enough answers provided for this problem. So, I was wondering if anybody had this problem when they ran this project ?

Full Preferences.cs is as follows.

using System;

namespace NeuralNetworkLibrary
{
    public class Preferences
    {
        public const int g_cImageSize = 28;
        public const int g_cVectorSize = 29;

        public int m_cNumBackpropThreads;

        public uint m_nMagicTrainingLabels;
        public uint m_nMagicTrainingImages;

        public uint m_nItemsTrainingLabels;
        public uint m_nItemsTrainingImages;

        public int m_cNumTestingThreads;

        public int m_nMagicTestingLabels;
        public int m_nMagicTestingImages;

        public uint m_nItemsTestingLabels;
        public uint m_nItemsTestingImages;

        public uint m_nRowsImages;
        public uint m_nColsImages;

        public int m_nMagWindowSize;
        public int m_nMagWindowMagnification;

        public double m_dInitialEtaLearningRate;
        public double m_dLearningRateDecay;
        public double m_dMinimumEtaLearningRate;
        public uint m_nAfterEveryNBackprops;

        // for limiting the step size in backpropagation, since we are using second order
        // "Stochastic Diagonal Levenberg-Marquardt" update algorithm.  See Yann LeCun 1998
        // "Gradianet-Based Learning Applied to Document Recognition" at page 41

        public double m_dMicronLimitParameter;
        public uint m_nNumHessianPatterns;

        // for distortions of the input image, in an attempt to improve generalization

        public double m_dMaxScaling;  // as a percentage, such as 20.0 for plus/minus 20%
        public double m_dMaxRotation;  // in degrees, such as 20.0 for plus/minus rotations of 20 degrees
        public double m_dElasticSigma;  // one sigma value for randomness in Simard's elastic distortions
        public double m_dElasticScaling;  // after-smoohting scale factor for Simard's elastic distortions
        private IniFile m_Inifile;
        ////////////
        public Preferences()
        {
            // set default values

            m_nMagicTrainingLabels = 0x00000801;
            m_nMagicTrainingImages = 0x00000803;

            m_nItemsTrainingLabels = 60000;
            m_nItemsTrainingImages = 60000;

            m_nMagicTestingLabels = 0x00000801;
            m_nMagicTestingImages = 0x00000803;

            m_nItemsTestingLabels = 10000;
            m_nItemsTestingImages = 10000;

            m_nRowsImages = g_cImageSize;
            m_nColsImages = g_cImageSize;

            m_nMagWindowSize = 5;
            m_nMagWindowMagnification = 8;

            m_dInitialEtaLearningRate = 0.001;
            m_dLearningRateDecay = 0.794328235;  // 0.794328235 = 0.001 down to 0.00001 in 20 epochs
            m_dMinimumEtaLearningRate = 0.00001;
            m_nAfterEveryNBackprops = 60000;
            m_cNumBackpropThreads = 2;

            m_cNumTestingThreads = 1;

            // parameters for controlling distortions of input image

            m_dMaxScaling = 15.0;  // like 20.0 for 20%
            m_dMaxRotation = 15.0;  // like 20.0 for 20 degrees
            m_dElasticSigma = 8.0;  // higher numbers are more smooth and less distorted; Simard uses 4.0
            m_dElasticScaling = 0.5;  // higher numbers amplify the distortions; Simard uses 34 (sic, maybe 0.34 ??)

            // for limiting the step size in backpropagation, since we are using second order
            // "Stochastic Diagonal Levenberg-Marquardt" update algorithm.  See Yann LeCun 1998
            // "Gradient-Based Learning Applied to Document Recognition" at page 41

            m_dMicronLimitParameter = 0.10;  // since we divide by this, update can never be more than 10x current eta
            m_nNumHessianPatterns = 500;  // number of patterns used to calculate the diagonal Hessian
            String path = System.IO.Directory.GetCurrentDirectory() + "\\Data\\Default-ini.ini";
            m_Inifile = new IniFile(path);
            ReadIniFile();
        }
        public void ReadIniFile()
        {
            // now read values from the ini file

            String tSection;

            // Neural Network parameters

            tSection = "Neural Network Parameters";

            Get(tSection, "Initial learning rate (eta)", out m_dInitialEtaLearningRate);
            Get(tSection, "Minimum learning rate (eta)", out m_dMinimumEtaLearningRate);
            Get(tSection, "Rate of decay for learning rate (eta)", out m_dLearningRateDecay);
            Get(tSection, "Decay rate is applied after this number of backprops", out m_nAfterEveryNBackprops);
            Get(tSection, "Number of backprop threads", out m_cNumBackpropThreads);
            Get(tSection, "Number of testing threads", out m_cNumTestingThreads);
            Get(tSection, "Number of patterns used to calculate Hessian", out m_nNumHessianPatterns);
            Get(tSection, "Limiting divisor (micron) for learning rate amplification (like 0.10 for 10x limit)", out m_dMicronLimitParameter);

            // Neural Network Viewer parameters

            tSection = "Neural Net Viewer Parameters";

            Get(tSection, "Size of magnification window", out m_nMagWindowSize);
            Get(tSection, "Magnification factor for magnification window", out m_nMagWindowMagnification);

            // MNIST data collection parameters

            tSection = "MNIST Database Parameters";

            Get(tSection, "Training images magic number", out m_nMagicTrainingImages);
            Get(tSection, "Training images item count", out m_nItemsTrainingImages);
            Get(tSection, "Training labels magic number", out m_nMagicTrainingLabels);
            Get(tSection, "Training labels item count", out m_nItemsTrainingLabels);

            Get(tSection, "Testing images magic number", out m_nMagicTestingImages);
            Get(tSection, "Testing images item count", out m_nItemsTestingImages);
            Get(tSection, "Testing labels magic number", out m_nMagicTestingLabels);
            Get(tSection, "Testing labels item count", out m_nItemsTestingLabels);

            // these two are basically ignored

            uint uiCount = g_cImageSize;
            Get(tSection, "Rows per image", out uiCount);
            m_nRowsImages = uiCount;

            uiCount = g_cImageSize;
            Get(tSection, "Columns per image", out uiCount);
            m_nColsImages = uiCount;

            // parameters for controlling pattern distortion during backpropagation

            tSection = "Parameters for Controlling Pattern Distortion During Backpropagation";

            Get(tSection, "Maximum scale factor change (percent, like 20.0 for 20%)", out m_dMaxScaling);
            Get(tSection, "Maximum rotational change (degrees, like 20.0 for 20 degrees)", out m_dMaxRotation);
            Get(tSection, "Sigma for elastic distortions (higher numbers are more smooth and less distorted; Simard uses 4.0)", out m_dElasticSigma);
            Get(tSection, "Scaling for elastic distortions (higher numbers amplify distortions; Simard uses 0.34)", out m_dElasticScaling);
        }
        private void Get(string lpAppName, string lpKeyName, out int nDefault)
        {
            nDefault = Convert.ToInt32(m_Inifile.IniReadValue(lpAppName, lpKeyName));
            return;

        }
        private void Get(string lpAppName, string lpKeyName, out uint nDefault)
        {
            nDefault = Convert.ToUInt32(m_Inifile.IniReadValue(lpAppName, lpKeyName));
            return;
        }

        private void Get(string lpAppName, string lpKeyName, out double nDefault)
        {
               nDefault = Convert.ToDouble(m_Inifile.IniReadValue(lpAppName, lpKeyName));
               return;
        }
        private void Get(string lpAppName, string lpKeyName, out byte nDefault)
        {

           nDefault = Convert.ToByte(m_Inifile.IniReadValue(lpAppName, lpKeyName));
           return ;

        }

        private void Get(string lpAppName, string lpKeyName, out string nDefault)
        {
            nDefault = m_Inifile.IniReadValue(lpAppName, lpKeyName);
            return;

        }
        private void Get(string lpAppName, string lpKeyName, out bool nDefault)
        {
            nDefault = Convert.ToBoolean(m_Inifile.IniReadValue(lpAppName, lpKeyName));
            return;
        }

    }
}

Body:
In this case, the problem is in the decimal point of the default .ini file.

nDefault = Convert.ToDouble(m_Inifile.IniReadValue(lpAppName, lpKeyName), CultureInfo.InvariantCulture);


问:
Java - HashMap Iteration - Exception
I want to iterate a HashMap like:

```<code>        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }
</code>```

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards

答:
You're removing items from the map as you're iterating through it. This is what's causing the exception.

To get a bit of intuition as to why this is: if your map contains three items and on the first iteration you remove the first item, should the next item be the second, or third? i.e. should the iteration continue as though the removed item was still there? And if so, how?

You can get around this by using an iterator on the map which safely goes through each element of the map.

Title: Java - HashMap Iteration - Exception

Body:
I want to iterate a HashMap like:

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards


问:
Can't find the nuget package manager in visual studio 2017?
I installed package installer from Tools->Extensions and Updates .
I tried searching in the tools menu, couldn't find install nuget package option.
Also if I right click on the project, there is an option Quick Install Package, In the box there I fill in the nuget package I want to add in my project (openBLAS in my case) and it says, Visual studio needs to restart .

Iam working in Visual C++ win32 console application and tried finding the nuget package manager for other projects as well.

I restarted my visual studio and even my PC too, but still couldn't find it.
Please help!

答:
It's not installed by default(as far as I know) you have to select It in the Visual Studio Installer manually.

First open up your Visual Studio installer (e.g., via Tools->Get Tools and Features...). Modify your currently installed product. You can find the NuGet package manager under the Individual components tab.


问:
Charts.js & Bootstrap Accordion
I have been trying to understand why Charts.js wouldn't draw a chart if it's inside a Bootstrap Accordion.

After many attempts I managed to understand why it's not drawing the chart! it's because the panel is basically hiding the canvas so Charts.js doesn't draw it.

Can anyone help me come up with a solution to this?

I've also tried to draw the chart only when the Bootstrap event shown.bs.collapse is active, doesn't work.

Here's a jsfiddle I've created to illustrate the problem:

If you want to reproduce the problem simply add in to the class in line

答:
For anyone coming to this later, I had the same issue but preferred not to rely on a timer delay as offered in the accepted answer. The following is what worked for me using Bootstrap 3.3.7 with the shown event:

shown.bs.collapse

```<code>$('#accordion').on('shown.bs.collapse', function (e) {

            switch (e.target.id)
            {
                case "panel1": ShowChart1(); break;
                case "panel2": ShowChart2(); break;
                case "panel3": ShowChart3(); break;
                case "panel4": ShowChart4(); break;
                default: ShowDefault();
            }

        })
</code>```

Hopes this helps

btw - this is the above code working: greatdata.com/stats/newyork_ny

Title: Charts.js & Bootstrap Accordion

Body:
For anyone coming to this later, I had the same issue but preferred not to rely on a timer delay as offered in the accepted answer. The following is what worked for me using Bootstrap 3.3.7 with the shown event:

shown.bs.collapse

$('#accordion').on('shown.bs.collapse', function (e) {

            switch (e.target.id)
            {
                case "panel1": ShowChart1(); break;
                case "panel2": ShowChart2(); break;
                case "panel3": ShowChart3(); break;
                case "panel4": ShowChart4(); break;
                default: ShowDefault();
            }

        })

Hopes this helps

btw - this is the above code working: greatdata.com/stats/newyork_ny


问:
1 million sentences to save in DB - removing non-relevant English words
I am trying to train a Naive Bayes classifier with positive/negative words extracting from a sentiment. example:

I love this movie :))

I hate when it rains :(

The idea is I extract positive or negative sentences based on the emoctions used, but in order to train a classifier and persist it into database.

The problem is that I have more than 1 million such sentences, so if I train it word by word, the database will go for a toss. I want to remove all non-relevant word example 'I','this', 'when', 'it' so that number of times I have to make a database query is less.

Please help me in resolving this issue to suggest me better ways of doing it

Thank you

答:
You might want to check this out
http://books.google.com/books?id=CE1QzecoVf4C&lpg=PA390&ots=OHuYwLRhag&dq=sentiment%20%20mining%20for%20fortune%20500&pg=PA379#v=onepage&q=sentiment%20%20mining%20for%20fortune%20500&f=false</p>


问:
Getting ORA-00918: column ambiguously defined: running this SQL:
```<code>SELECT Name AS "Avatar Name",
       COUNT(WEAPON_ID) AS "Active Weapons Held |",
       SUM(W.COST) AS "Total Weapons Cost"
FROM   Avatar A, Weapon_Held H, Weapon W
WHERE  A.Avatar_ID=H.AVATAR_ID AND H.WEAPON_ID=W.WEAPON_ID
Group by Name;
</code>```

答:
Do you have two or more colums in  these tables named 'Name'?
Please use implicit names like: 'A.Name' or 'H.Name' like:</p>

```<code>Select A.Name....
Group by A.Name
</code>```

Body:
Do you have two or more colums in  these tables named 'Name'?
Please use implicit names like: 'A.Name' or 'H.Name' like:

Select A.Name....
Group by A.Name


问:
Pandas - Duplicate Rows at Iteration
I'm trying to create duplicate rows during a dataframe iteration. Basically, I have two for loops wherein in the first loop, I'm feeding values into an API, and in the second loop, I'm extracting values from the JSON output.

I want to duplicate the current row and create N rows based on how many items are on the list.
For example:

```<code>Name    Date      Sales
John    1/1/17    100
Bob     1/2/17    200

items = []
for row in df.sales:
    url = 'www.samplewebsite.com/values=xyz/APIKEY=MYAPIKEY'
    result = simplejson.load(urllib.urlopen(url))
    for i in range(0, len(result['column a'][0]['column b']:
        items.append(result['column a'][0]['column b'][i]['item'])
</code>```

In this particular loop, two lists are created (one for  John, the other for Bob):

```<code>items = ['Paper','Paper Clips','Pencils']
items = ['Notebook','Stapler','Highlighter','Pen']
</code>```

Desired output:

```<code>Name    Date      Sales     Item
John    1/1/17    100       Paper
John    1/1/17    100       Paper Clips
John    1/1/17    100       Pencils
Bob     1/2/17    200       Notebook
Bob     1/2/17    200       Stapler
Bob     1/2/17    200       Highlighter
Bob     1/2/17    200       Pen
</code>```

Thank you in advance!

答:
There are a handful of ways to do this. From inside your loop you could, after extracting each item push one item and one name into a main dataframe. Or, you could push a bunch of items into one df along with one name and then append that to the main df after each name. Or you could gather up all the things and then append them at the very end.

Here's how you would put all items belonging to one name into a df then append it to a master df. You'd have to do this inside the loop, once for each name:

```<code># set this up before the loop
mainDF = pd.DataFrame( columns=['Name','Items'])

## this gets populated inside the loop
name = 'John'
items = ['Paper','Paper Clips','Pencils']

# inside the loop create a df to hold one name and all the items belonging to that name
df = pd.DataFrame( columns=['Name','Items'])

#populate... do items first then fill in all the name with the one name
df.Items = items
df.Name = name

## then append the above df into the main df
mainDF = mainDF.append(df)
</code>```

Title: Pandas - Duplicate Rows at Iteration

Body:
I'm trying to create duplicate rows during a dataframe iteration. Basically, I have two for loops wherein in the first loop, I'm feeding values into an API, and in the second loop, I'm extracting values from the JSON output.

I want to duplicate the current row and create N rows based on how many items are on the list.
For example:

Name    Date      Sales
John    1/1/17    100
Bob     1/2/17    200

items = []
for row in df.sales:
    url = 'www.samplewebsite.com/values=xyz/APIKEY=MYAPIKEY'
    result = simplejson.load(urllib.urlopen(url))
    for i in range(0, len(result['column a'][0]['column b']:
        items.append(result['column a'][0]['column b'][i]['item'])

In this particular loop, two lists are created (one for  John, the other for Bob):

items = ['Paper','Paper Clips','Pencils']
items = ['Notebook','Stapler','Highlighter','Pen']

Desired output:

Name    Date      Sales     Item
John    1/1/17    100       Paper
John    1/1/17    100       Paper Clips
John    1/1/17    100       Pencils
Bob     1/2/17    200       Notebook
Bob     1/2/17    200       Stapler
Bob     1/2/17    200       Highlighter
Bob     1/2/17    200       Pen

Thank you in advance!

Body:
There are a handful of ways to do this. From inside your loop you could, after extracting each item push one item and one name into a main dataframe. Or, you could push a bunch of items into one df along with one name and then append that to the main df after each name. Or you could gather up all the things and then append them at the very end.

Here's how you would put all items belonging to one name into a df then append it to a master df. You'd have to do this inside the loop, once for each name:

# set this up before the loop
mainDF = pd.DataFrame( columns=['Name','Items'])

## this gets populated inside the loop
name = 'John'
items = ['Paper','Paper Clips','Pencils']

# inside the loop create a df to hold one name and all the items belonging to that name
df = pd.DataFrame( columns=['Name','Items'])

#populate... do items first then fill in all the name with the one name
df.Items = items
df.Name = name

## then append the above df into the main df
mainDF = mainDF.append(df)


答:
First, never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

Second, use table aliases, but use them everywhere:

```<code>SELECT Name AS "Avatar Name",
       COUNT(H.WEAPON_ID) AS "Active Weapons Held",
       SUM(W.COST) AS "Total Weapons Cost"
FROM Avatar A JOIN
     Weapon_Held H
     ON A.Avatar_ID = H.AVATAR_ID JOIN
     Weapon W
     ON H.WEAPON_ID = W.WEAPON_ID
Group by Name;
</code>```

Title: Getting ORA-00918: column ambiguously defined: running this SQL:

Body:
SELECT Name AS "Avatar Name",
       COUNT(WEAPON_ID) AS "Active Weapons Held |",
       SUM(W.COST) AS "Total Weapons Cost"
FROM   Avatar A, Weapon_Held H, Weapon W
WHERE  A.Avatar_ID=H.AVATAR_ID AND H.WEAPON_ID=W.WEAPON_ID
Group by Name;

Body:
First, never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

Second, use table aliases, but use them everywhere:

SELECT Name AS "Avatar Name",
       COUNT(H.WEAPON_ID) AS "Active Weapons Held",
       SUM(W.COST) AS "Total Weapons Cost"
FROM Avatar A JOIN
     Weapon_Held H
     ON A.Avatar_ID = H.AVATAR_ID JOIN
     Weapon W
     ON H.WEAPON_ID = W.WEAPON_ID
Group by Name;


答:
You're getting the error because you have multiple tables in your query that have the same name and it doesn't know where to pull it from.  Try changing your query to the following:</p>

```<code>SELECT  A.Name AS "Avatar Name",
        COUNT(H.WEAPON_ID) AS "Active Weapons Held |",
        SUM(W.COST) AS "Total Weapons Cost"
FROM    Avatar      A
JOIN    Weapon_Held H   ON  A.Avatar_ID=H.AVATAR_ID
JOIN    Weapon      W   ON  H.WEAPON_ID=W.WEAPON_ID
Group by A.Name;
</code>```

Body:
You're getting the error because you have multiple tables in your query that have the same name and it doesn't know where to pull it from.  Try changing your query to the following:

SELECT  A.Name AS "Avatar Name",
        COUNT(H.WEAPON_ID) AS "Active Weapons Held |",
        SUM(W.COST) AS "Total Weapons Cost"
FROM    Avatar      A
JOIN    Weapon_Held H   ON  A.Avatar_ID=H.AVATAR_ID
JOIN    Weapon      W   ON  H.WEAPON_ID=W.WEAPON_ID
Group by A.Name;


问:
Remove callback not working in Handler
I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code

```<code>handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        myFunction(position);
        handler.postDelayed(runnable,10000);
    }
};
public void myFunction(int position)
{
    if(position>10)
        handler.removeCallbacks(runnable);
}
</code>```

I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?

答:
The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one.  There are plenty of ways to refactor this.  For example:

```<code>handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        boolean reschedule = myFunction(position);
        if(reschedule) {
            handler.postDelayed(runnable,10000);
        }
    }
};
public boolean myFunction(int position)
{
    if(position>10) {
        return false;
    }
    return true;
}
</code>```

You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.

Title: Remove callback not working in Handler

Body:
I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code

handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        myFunction(position);
        handler.postDelayed(runnable,10000);
    }
};
public void myFunction(int position)
{
    if(position>10)
        handler.removeCallbacks(runnable);
}

I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?

Body:
The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one.  There are plenty of ways to refactor this.  For example:

handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        boolean reschedule = myFunction(position);
        if(reschedule) {
            handler.postDelayed(runnable,10000);
        }
    }
};
public boolean myFunction(int position)
{
    if(position>10) {
        return false;
    }
    return true;
}

You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.