问:
How to access parent widget pointer in QT
I have a code something like this

```<code>Window::Window()
{
   QStackedWidget *centralApp = new QStackedWidget;
   QWidget1 *wgt1 = QWidget1;
   QWidget2 *wgt2 = QWidget2;
   QWidget3 *wgt3 = QWidget3;

   centralApp->addWidget(wgt1);
   centralApp->addWidget(wgt2);
   centralApp->addWidget(wgt3);
}
</code>```

The classes QWidget1,QWidget2 and QWidget3 are inherited from QWidget and each contains two buttons btn1 and btn2. These buttons I want to use the two buttons in each widget to navigate to other two widgets added to stacked widget. So to navigate to other page in stacked widget I have to use the setCurrentIndex() and for this I need the parent QStackedWidget pointer. Can anybody suggest me how I can access the QStackedWidget pointer inside on of its page widgets to navigate to another page?

Please let me know if I am not clear in explaining the problem.

答:
http://doc.qt.io/archives/4.6/qwidget.html#parentWidget</p>

```<code>(centralApp==wgt1->parentWidget()) //true
</code>```

Body:
I have a code something like this

Window::Window()
{
   QStackedWidget *centralApp = new QStackedWidget;
   QWidget1 *wgt1 = QWidget1;
   QWidget2 *wgt2 = QWidget2;
   QWidget3 *wgt3 = QWidget3;

   centralApp->addWidget(wgt1);
   centralApp->addWidget(wgt2);
   centralApp->addWidget(wgt3);
}

The classes QWidget1,QWidget2 and QWidget3 are inherited from QWidget and each contains two buttons btn1 and btn2. These buttons I want to use the two buttons in each widget to navigate to other two widgets added to stacked widget. So to navigate to other page in stacked widget I have to use the setCurrentIndex() and for this I need the parent QStackedWidget pointer. Can anybody suggest me how I can access the QStackedWidget pointer inside on of its page widgets to navigate to another page?

Please let me know if I am not clear in explaining the problem.

Body:
http://doc.qt.io/archives/4.6/qwidget.html#parentWidget

(centralApp==wgt1->parentWidget()) //true


来源: stackexchange

问:
Eloquent eager load Order by
I have problem with eloquent query. I am using eager loading (one to one Relationship) to get 'student' With the 'exam', Using the code below.

```<code>Student::with('exam')->orderBy('exam.result', 'DESC')->get()
</code>```

And i want to order received rows by the 'result' column in 'exam'. I am using

```<code>->orderBy('exam.result', 'DESC')
</code>```

But it is not working. Any ideas how to do it ?

答:
This worked for me: </p>

```<code>$query = Student::select(['id','name']);

    $query->has('exam')->with(['exam' => function ($query) {
        return $query->orderBy('result','ASC');
    }]);

    return $query->get();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Eloquent eager load Order by

Body:
I have problem with eloquent query. I am using eager loading (one to one Relationship) to get 'student' With the 'exam', Using the code below.

Student::with('exam')->orderBy('exam.result', 'DESC')->get()

And i want to order received rows by the 'result' column in 'exam'. I am using

->orderBy('exam.result', 'DESC')

But it is not working. Any ideas how to do it ?

Body:
This worked for me:

$query = Student::select(['id','name']);

    $query->has('exam')->with(['exam' => function ($query) {
        return $query->orderBy('result','ASC');
    }]);

    return $query->get();


问:
Symbol not found when static linking on MacOSX
I am trying to create a static library and link it on MacOS X (several versions):
File foo.c:

```<code>char foo[111];
</code>```

File bar.c:

```<code>#include <string.h>

extern char foo[];

int bar(char *src) {
  strcpy(foo, src);
  return strlen(foo);
}
</code>```

Create a library:

```<code>$ cc -c foo.c bar.c
$ ar r libfoobar.a foo.o bar.o
ar: creating archive libfoobar.a
$ ranlib libfoobar.a
$ nm libfoobar.a

libfoobar.a(foo.o):
000000000000006f C _foo

libfoobar.a(bar.o):
                 U ___strcpy_chk
0000000000000000 T _bar
                 U _foo
                 U _strlen
</code>```

Create a small test program:

File main.c:

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

int bar(char *);

int main(void) {
  printf("foobarbar = %i\n", bar("123"));
  return 0;
}
</code>```

Compile and link:

```<code>$ cc -c main.c
$ cc -o m main.o -L. -lfoobar
Undefined symbols for architecture x86_64:
  "_foo", referenced from:
      _bar in libfoobar.a(bar.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Why is the symbol not found? It is defined in foo.c? Shouldn't at least ranlib create an index in the library that allows a random order of the files there?

The same code works well under Linux (gcc), and also when the symbol in foo.c is not a char array, but an int.

答:
There is a similar question: Object files not properly added to archive on mac which has this answer:

```<code>Option 1:

ar -rs my_archive.a foo.o bar.o other_object_files.o
ranlib -c my_archive.a

Option 2:

libtool -c -static -o my_archive.a foo.o bar.o other_object_files.o
</code>```

It is -c flag that makes a difference for both options on ranlib and libtool respectively:

-c

Include  common symbols as definitions with respect to the table
                of contents.  This is seldom the intended behavior  for  linking
                from  a  library,  as  it forces the linking of a library member
                just because it uses an uninitialized global that  is  undefined
                at  that  point  in  the  linking.  This option is included only
                because this was the original behavior of ranlib.   This  option
                is not the default.

Body:
I am trying to create a static library and link it on MacOS X (several versions):
File foo.c:

char foo[111];

File bar.c:

#include <string.h>

extern char foo[];

int bar(char *src) {
  strcpy(foo, src);
  return strlen(foo);
}

Create a library:

$ cc -c foo.c bar.c
$ ar r libfoobar.a foo.o bar.o
ar: creating archive libfoobar.a
$ ranlib libfoobar.a
$ nm libfoobar.a

libfoobar.a(foo.o):
000000000000006f C _foo

libfoobar.a(bar.o):
                 U ___strcpy_chk
0000000000000000 T _bar
                 U _foo
                 U _strlen

Create a small test program:

File main.c:

#include <stdio.h>

int bar(char *);

int main(void) {
  printf("foobarbar = %i\n", bar("123"));
  return 0;
}

Compile and link:

$ cc -c main.c
$ cc -o m main.o -L. -lfoobar
Undefined symbols for architecture x86_64:
  "_foo", referenced from:
      _bar in libfoobar.a(bar.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Why is the symbol not found? It is defined in foo.c? Shouldn't at least ranlib create an index in the library that allows a random order of the files there?

The same code works well under Linux (gcc), and also when the symbol in foo.c is not a char array, but an int.

Body:
There is a similar question: Object files not properly added to archive on mac which has this answer:

Option 1:

ar -rs my_archive.a foo.o bar.o other_object_files.o
ranlib -c my_archive.a

Option 2:

libtool -c -static -o my_archive.a foo.o bar.o other_object_files.o

It is -c flag that makes a difference for both options on ranlib and libtool respectively:

-c

Include  common symbols as definitions with respect to the table
                of contents.  This is seldom the intended behavior  for  linking
                from  a  library,  as  it forces the linking of a library member
                just because it uses an uninitialized global that  is  undefined
                at  that  point  in  the  linking.  This option is included only
                because this was the original behavior of ranlib.   This  option
                is not the default.


问:
Express, Passportjs persistent login not working
I'm using Express and Passport to sign in but there is a problem: the persistent login session doesn't work.

If I log req.isAuthenticated() It's alway false.

I'm using Custom Callback from Passport
and fetch to make the call. The data received from fetch is working: { success: true, user }.

When I'm not using the custom callback (see below) it's working.

Works

```<code>app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                    failureRedirect: '/login' }));
</code>```

Not working

app.js

```<code>app.use(morgan('tiny'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(assetPath))
app.use(cookieParser())
app.use(
  session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true },
  })
)
app.use(passport.initialize())
app.use(passport.session())
</code>```

routes.js

```<code>router.post('/login', (req, res, next) => {
  passport.authenticate('local', ({ user, err, message }) => {
    if (err) {
      return res.send({ user, err, message })
    }

    if (!user) {
      return res.send({ user, err, message })
    }

    req.login(user, function(err) {
      if (err) {
        return next(err)
      }
      return res.send({ success: true, user })
    })
  })(req, res, next)
})
</code>```

Client:

```<code>    fetch(url, {
      method: 'POST',
      credentials: 'include',
      body: JSON.stringify(values),
      headers: { 'Content-Type': 'application/json' },
    })
</code>```

答:
By default, the persistent login is stored in session, which uses a signed cookie to identify future requests as part of the same session.

Also by default, fetch doesn't send cookies.

You can send cookies by including them:

```<code>fetch(url, {
  credentials: 'include'
});
</code>```

Or you can use a more modern mechanism for authentication like JWTs.  Up to you.

UPDATE

Also, you are setting secure:true on your session, which is the default and also means the requests must happen over https, or else the cookies will be stripped out.  If you're not using https, then set secure:false.  For best results, make that a configuration setting you can change for production or development, since you always want to use https in production.

Body:
I'm using Express and Passport to sign in but there is a problem: the persistent login session doesn't work.

If I log req.isAuthenticated() It's alway false.

I'm using Custom Callback from Passport
and fetch to make the call. The data received from fetch is working: { success: true, user }.

When I'm not using the custom callback (see below) it's working.

Works

app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                    failureRedirect: '/login' }));

Not working

app.js

app.use(morgan('tiny'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(assetPath))
app.use(cookieParser())
app.use(
  session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true },
  })
)
app.use(passport.initialize())
app.use(passport.session())

routes.js

router.post('/login', (req, res, next) => {
  passport.authenticate('local', ({ user, err, message }) => {
    if (err) {
      return res.send({ user, err, message })
    }

    if (!user) {
      return res.send({ user, err, message })
    }

    req.login(user, function(err) {
      if (err) {
        return next(err)
      }
      return res.send({ success: true, user })
    })
  })(req, res, next)
})

Client:

    fetch(url, {
      method: 'POST',
      credentials: 'include',
      body: JSON.stringify(values),
      headers: { 'Content-Type': 'application/json' },
    })

Body:
By default, the persistent login is stored in session, which uses a signed cookie to identify future requests as part of the same session.

Also by default, fetch doesn't send cookies.

You can send cookies by including them:

fetch(url, {
  credentials: 'include'
});

Or you can use a more modern mechanism for authentication like JWTs.  Up to you.

UPDATE

Also, you are setting secure:true on your session, which is the default and also means the requests must happen over https, or else the cookies will be stripped out.  If you're not using https, then set secure:false.  For best results, make that a configuration setting you can change for production or development, since you always want to use https in production.


问:
How do I get http headers in React.js
I've made a request to a React page, and I need to get the headers from the request.

I call the page via the URL:

http://localhost/dashboard

and I set headers, for example authcode=1234.

I then load the page with this route:

```<code><Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requireAuth}></Route>
</code>```

is there something like this.props.header, I can call in the page constructor?

答:
You cant get current page headers without sending a http request via javascript.
See this answer for more info.

Add a dummy api url on your server and hit it after your page loadn then you can get the headers.

```<code>class App extends React.Component{
    //some code
    componentDidMount(){
       fetch(Some_API).then(response=>{
           console.log(response.headers)
       })
    }
    //some code
}
</code>```

Title: How do I get http headers in React.js

Body:
I've made a request to a React page, and I need to get the headers from the request.

I call the page via the URL:

http://localhost/dashboard

and I set headers, for example authcode=1234.

I then load the page with this route:

<Route path="dashboard" name="dashboard" component={Dashboard} onEnter={requireAuth}></Route>

is there something like this.props.header, I can call in the page constructor?

Body:
You cant get current page headers without sending a http request via javascript.
See this answer for more info.

Add a dummy api url on your server and hit it after your page loadn then you can get the headers.

class App extends React.Component{
    //some code
    componentDidMount(){
       fetch(Some_API).then(response=>{
           console.log(response.headers)
       })
    }
    //some code
}


问:
Cleaner/shorter way to update nested state in Redux?
Sometimes reducers get kind of messy:

```<code>const initialState = {
    notificationBar: {
        open: false,
    },
};

export default function (state = initialState, action) {
  switch (action.type) {
    case actions.LAYOUT_NOTIFICATIONBAR_OPEN:
      return Object.assign({}, state, {
        // TODO: Find a cleaner way to do this!
        notificationBar: Object.assign({}, state.notificationBar, {
          open: true,
        }),
      });
    default:
      return state;
  }
}
</code>```

Is there a more terse way to do this?

答:
All advice here are great and valid, but I would like to offer another solution. The problem which appears here is definitely a common pattern, so I think it is much better just to write your own interface for such updates and stick with it inside reducers, and use one function to update deeply inside all your reducers.

For example, I have created a library, where I tried to address this issue the next way: I get the type of the module (so-called "tile"), function to perform operations (both async and sync) and desired nesting based on passed params. So, for your case it will be something like:

```<code>import { createSyncTile } from 'redux-tiles';
const uiTile = createSyncTile({
  type: ['ui', 'elements'],
  fn: ({ params }) => params,
  // type will be `notificationBar`
  nesting: ({ type }) => [type],
});
</code>```

And that's it -- it will be update correctly on arbitrary nesting. Also, tile provides selectors, so you don't have to worry personally where precisely data is located, you can just use them.
So, I don't want to say it is the best solution, but the idea is pretty simple -- don't be afraid to write your own implementation, and then just use factory to solve this issue.

Body:
Sometimes reducers get kind of messy:

const initialState = {
    notificationBar: {
        open: false,
    },
};

export default function (state = initialState, action) {
  switch (action.type) {
    case actions.LAYOUT_NOTIFICATIONBAR_OPEN:
      return Object.assign({}, state, {
        // TODO: Find a cleaner way to do this!
        notificationBar: Object.assign({}, state.notificationBar, {
          open: true,
        }),
      });
    default:
      return state;
  }
}

Is there a more terse way to do this?

Body:
All advice here are great and valid, but I would like to offer another solution. The problem which appears here is definitely a common pattern, so I think it is much better just to write your own interface for such updates and stick with it inside reducers, and use one function to update deeply inside all your reducers.

For example, I have created a library, where I tried to address this issue the next way: I get the type of the module (so-called "tile"), function to perform operations (both async and sync) and desired nesting based on passed params. So, for your case it will be something like:

import { createSyncTile } from 'redux-tiles';
const uiTile = createSyncTile({
  type: ['ui', 'elements'],
  fn: ({ params }) => params,
  // type will be `notificationBar`
  nesting: ({ type }) => [type],
});

And that's it -- it will be update correctly on arbitrary nesting. Also, tile provides selectors, so you don't have to worry personally where precisely data is located, you can just use them.
So, I don't want to say it is the best solution, but the idea is pretty simple -- don't be afraid to write your own implementation, and then just use factory to solve this issue.


问:
Printing word by word from a sentence
I have a sentence "Computer Science" as my input and I want to print Computer and Science seperately. I wrote a program in c++ but it is printing only "Computer". Could anyone help me find out why it is not printing both the words seperately?</p>

```<code>int main()
{
    char string[]="Computer Science";
    int l;
    l=strlen(string);
    char begin[l];
    int i=0,ind=0;

        while(string[i]!='\0')
        {
            begin[ind]=string[i];
            if(string[i]==' ')
                {
                    begin[ind]=NULL;
                    cout<<begin<<"\n";

                    ind=0;
                    //ind++;
                    i++;
                }
            else
            {

                ind++;
                i++;
            }
        }

    return 0;
}
</code>```

答:
You are looking only for space which printing output. Science has null after it not space.
Change while to

```<code>while(i <= l)
</code>```

Change your if condition to

```<code>if(string[i]==' ' || string[i] == '\0')
</code>```

Title: Printing word by word from a sentence

Body:
I have a sentence "Computer Science" as my input and I want to print Computer and Science seperately. I wrote a program in c++ but it is printing only "Computer". Could anyone help me find out why it is not printing both the words seperately?

int main()
{
    char string[]="Computer Science";
    int l;
    l=strlen(string);
    char begin[l];
    int i=0,ind=0;

        while(string[i]!='\0')
        {
            begin[ind]=string[i];
            if(string[i]==' ')
                {
                    begin[ind]=NULL;
                    cout<<begin<<"\n";

                    ind=0;
                    //ind++;
                    i++;
                }
            else
            {

                ind++;
                i++;
            }
        }

    return 0;
}

Body:
You are looking only for space which printing output. Science has null after it not space.
Change while to

while(i <= l)

Change your if condition to

if(string[i]==' ' || string[i] == '\0')


问:
How can I determine the class of an XML serialized object in C# before I deserialize it?
I have a server that accepts requests as XML serialized objects which could be any of 10 or so different Classes.  Of course in order for the server to process the request, it must first de-serialize the XML string back into an object.  To do that, it needs to know what class the object came from to choose the correct de-serializer and re-construct the object.  So it would be good to be able to just quickly inspect the XML string before attempting to de-serialize it to get the object type and then select the appropriate de-serializer.

I have been using the following code, but, like the song goes, "I know there's got to be a better way..."  Any suggestions or insight would be appreciated.

```<code> private void button1_Click(object sender, EventArgs e)
    {
        //any class - does not matter - create an object
        SomeClass tc = new SomeClass();
        //populate it
        tc.i = 5;
        tc.s = "Hello World";
        tc.d = 123.456;

        //Serialize it to XML
        StringWriter xml = new StringWriter();
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(SomeClass));
        x.Serialize(xml, tc);

        //Extract the Class name and show the XML to the user without de-serializing it
        textBox1.Text = GetClassNameFromXMLSerializedString(xml.ToString());
    }

    private string GetClassNameFromXMLSerializedString(string xml)
    {
        //The class name is somewhere in the xml
        string classname = xml;
        //get the start of class name
        classname = xml.Substring(classname.IndexOf('>') + 4);
        //get the class name which is terminated by a space
        classname = classname.Substring(0, classname.IndexOf(' '));
        //return it
        return classname;
    }
</code>```

答:
The XML Deserializer does not need to know what type it is before deserializing. The MSDN Article about the Deserialize method has some useful information about it and of course it has a code snippet, which I've put below.

I think you might have confused yourself with the fact that the server will deserialize it to an object, but then won't know what to do with it. You can always do a switch case for the result of the ReturnedObject.GetType() method and work out what you need to do with it.

You can just serialize it to an object like this:

```<code> var ReturnedObject = XMLSerializer.Deserialize(reader);
</code>```

Then you can go ahead and do

```<code> switch (ReturnedObject.getType())
 {
     case MyClass:
         // Insert code here
     case AnotehrClass:
         //Do something else here for another class
 }
</code>```

Body:
I have a server that accepts requests as XML serialized objects which could be any of 10 or so different Classes.  Of course in order for the server to process the request, it must first de-serialize the XML string back into an object.  To do that, it needs to know what class the object came from to choose the correct de-serializer and re-construct the object.  So it would be good to be able to just quickly inspect the XML string before attempting to de-serialize it to get the object type and then select the appropriate de-serializer.

I have been using the following code, but, like the song goes, "I know there's got to be a better way..."  Any suggestions or insight would be appreciated.

 private void button1_Click(object sender, EventArgs e)
    {
        //any class - does not matter - create an object
        SomeClass tc = new SomeClass();
        //populate it
        tc.i = 5;
        tc.s = "Hello World";
        tc.d = 123.456;

        //Serialize it to XML
        StringWriter xml = new StringWriter();
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(SomeClass));
        x.Serialize(xml, tc);

        //Extract the Class name and show the XML to the user without de-serializing it
        textBox1.Text = GetClassNameFromXMLSerializedString(xml.ToString());
    }

    private string GetClassNameFromXMLSerializedString(string xml)
    {
        //The class name is somewhere in the xml
        string classname = xml;
        //get the start of class name
        classname = xml.Substring(classname.IndexOf('>') + 4);
        //get the class name which is terminated by a space
        classname = classname.Substring(0, classname.IndexOf(' '));
        //return it
        return classname;
    }

Body:
The XML Deserializer does not need to know what type it is before deserializing. The MSDN Article about the Deserialize method has some useful information about it and of course it has a code snippet, which I've put below.

I think you might have confused yourself with the fact that the server will deserialize it to an object, but then won't know what to do with it. You can always do a switch case for the result of the ReturnedObject.GetType() method and work out what you need to do with it.

You can just serialize it to an object like this:

 var ReturnedObject = XMLSerializer.Deserialize(reader);

Then you can go ahead and do

 switch (ReturnedObject.getType())
 {
     case MyClass:
         // Insert code here
     case AnotehrClass:
         //Do something else here for another class
 }


问:
send email to owner by collecting information provided by user through form?
I had designed user input form that collects user name, email address, subject and message.
I had verified all elements stored these element in variable.
Now I need to send this information to the owner via email.
How can I solve this problem in localhost(too)?

How can I send email to owner?

How can I add all information so that I can get back or differ it later in owner email.

contact.php

```<code><form action="contact_ok.php" method="post"  autocomplete="on">
<p>
    <label for="username"> Name <span class="required">*</span></label>
    <input type="text" name="username" required="TRUE"/>
</p>
<p>
    <label for="usermail"> E-mail address <span class="required">*</span></label>
    <input type="email" name="usermail"required="TRUE"/>
</p>
<p>
    <label for="subject"> Subject </label>
    <input type="text" name="subject" required="TRUE" />
</p>
<p>
    <label for="message"> Message  <span class="required">*</span></label>
    <textarea name="msg" required="TRUE" ></textarea>
</p>
<input type="submit" name="submit mail"/>
</form>
</code>```

contact_ok.php

```<code><?php
$name = addslashes($_POST['username']);
$uml = addslashes($_POST['usermail']);
$sub = addslashes($_POST['subject']);
$msg =addslashes($_POST['msg']);
//sending mail to owner
$to ='owner@gmail.com';
//enter input information in array ******
//send email
mail($to,$sub,$msg);
?>
</code>```

For sending mail I read about PHP mailer but I found hard to understand. Also I studied this thread on SO it is also not sufficient.
2.For storing all elements I tried to convert message firstly to array by using $msg=str_split($msg)
and push all other information by using push_array($msg) and change it by using print_r($msg,TRUE) but it does not work.

答:
There is different ways:

1) You can use PHP MAILER library to send Email. So this library is totally based on SMTP . You have to specify your third party SMTP services and credentials. You can send email through gmail, yahoo etc . by using this library. This library will take care about securities, headers etc and very easy to use.

2) Another way which is not recommend by me is install your own postfix. Configure all things and send an email. Its very time consuming and you have to add various level of authentication like SPF, DMARC etc.

I would like to recommend  you to go with PHP Mailer integrate yous SMTP service and start Mailing.

Body:
I had designed user input form that collects user name, email address, subject and message.
I had verified all elements stored these element in variable.
Now I need to send this information to the owner via email.
How can I solve this problem in localhost(too)?

How can I send email to owner?

How can I add all information so that I can get back or differ it later in owner email.

contact.php

<form action="contact_ok.php" method="post"  autocomplete="on">

     Name *
    <input type="text" name="username" required="TRUE"/>

     E-mail address *
    <input type="email" name="usermail"required="TRUE"/>

     Subject
    <input type="text" name="subject" required="TRUE" />

     Message  *
    <textarea name="msg" required="TRUE" ></textarea>

<input type="submit" name="submit mail"/>
</form>

contact_ok.php

<?php
$name = addslashes($_POST['username']);
$uml = addslashes($_POST['usermail']);
$sub = addslashes($_POST['subject']);
$msg =addslashes($_POST['msg']);
//sending mail to owner
$to ='owner@gmail.com';
//enter input information in array ******
//send email
mail($to,$sub,$msg);
?>

For sending mail I read about PHP mailer but I found hard to understand. Also I studied this thread on SO it is also not sufficient.
2.For storing all elements I tried to convert message firstly to array by using $msg=str_split($msg)
and push all other information by using push_array($msg) and change it by using print_r($msg,TRUE) but it does not work.


问:
Is it okay to have a very long .htaccess file?
I am giving out URLs to people on a website, that actually point to something ugly (on the same website).

http://www.mydomain.com/cool-URL

actually points to

http://www.mydomain.com/boring.php?id=478547&sessid=34734asdf7&otherboringdetails

I'm planning to achieve this by modifying the .htaccess file whenever needed. I'm going to make the PHP script write to the .htaccess file, adding a new rewrite rule whenever there is a new hand-out of a url (from an admin area a non-programmer can control [specify the URL title for this new entry, admin : it will be assigned automagically]).

Is this going to be a problem, especially after 1000 or so such URLs? What is the actual number that is acceptable? Because, I can picture this: the server receives a request for a URL, then it searches the .htaccess file for the right page for this url, and finally sends the user to the right page. If this is anything like Database searching, it might take a long time for the user to actually get to the right page...

Any pointers on this, please?

答:
I would perform a simple test: generate a large .htaccess file with random URLs, and measure the resulting performance yourself.</p>

```<code>import random,string

def rand_string():
    length = random.randint(4,10)
    res = []
    for i in range(length):
        res.append(random.choice(string.letters))
    return ''.join(res)

for i in range(1000):
    print "RewriteRule %s http://www.mydomain.com/boring.php?%s [R]" % \
     (rand_string(), rand_string())
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would perform a simple test: generate a large .htaccess file with random URLs, and measure the resulting performance yourself.

import random,string

def rand_string():
    length = random.randint(4,10)
    res = []
    for i in range(length):
        res.append(random.choice(string.letters))
    return ''.join(res)

for i in range(1000):
    print "RewriteRule %s http://www.mydomain.com/boring.php?%s [R]" % \
     (rand_string(), rand_string())


问:
Custom keyboard shortcuts for Google Docs (change color - background color)
I would like to change the ForegroundColor of a selected text in a Google Docs with a keyboard shortcut.

I could make the "change the ForegroundColor" part (with a menu item bound to the function setColor() ), but not the "keyboard shortcut part".

I found this code but I have trouble implementing it:

```<code>$(document).keydown(function(e){
  //CTRL + Q keydown combo
  if(e.ctrlKey && e.keyCode == 81){
    $( '#output' ).html("I've been pressed!");
  }
})
</code>```

My difficulties :

1) I am not sure where to place this code in my script editor (I tried to place it in the onOpen() function as below, but also above it without success).

2) I am not sure what the $(document) should refer to.

3) I am not sure what they mean by "having to click on / activate the sidebar first for that to happen".

```<code>function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('My Menu')
      .addItem('Color', 'setColor')
      .addToUi();

  var document = DocumentApp.getActiveDocument() // should it be here?
  $(document).keydown(function(e){
    //CTRL + Q keydown combo
    if(e.ctrlKey && e.keyCode == 81){
      SpreadsheetApp.getUi().alert('Hello, world!');
    }
  })
}

function setColor1() {
    var selection = DocumentApp.getActiveDocument().getSelection();
    if (selection) {
    var elements = selection.getRangeElements();
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];

        // Only modify elements that can be edited as text; skip images and other non-text elements.
        if (element.getElement().editAsText) {
            var text = element.getElement().editAsText();

            // Edit the selected part of the element, or the full element if it's completely selected.
            if (element.isPartial()) {
                text.setForegroundColor(element.getStartOffset(), element.getEndOffsetInclusive(), "#00FFFF");
            } else {
                text.setForegroundColor("#00FFFF");
            }
        }
    }
    }
}
</code>```

答:
Instead of using the sidebar as Anton Dementiev suggested, it's possible to use a modeless dialog box. It can be run from the function onOpen() or from a menu item.

Advantage of modeless dialog box over the sidebar: the dialog box is smaller and can be move anywhere on the screen (click on the title an drag it)

Inconvenient: it's easier to set the focus on the sidebar, because on the modeless dialog box, you have to click inside the content of the dialog (which can be quite small) to set the focus.

The .html is the same than the one Anton Dementiev gave, but the .gs is different:

```<code>function onOpen() {
  var ui = DocumentApp.getUi();

  ui.createMenu('My Menu')
      .addItem('Open Color Dialog', 'dialogBox')
      .addToUi();

      var htmlOutput = HtmlService   // alternative to the sidebar
        .createHtmlOutputFromFile('sidebar')
        .setWidth(50)
        .setHeight(50);
      DocumentApp.getUi().showModelessDialog(htmlOutput, 'Title');

}

  function dialogBox() {
      var htmlOutput = HtmlService
        .createHtmlOutputFromFile('sidebar')
        .setWidth(50)
        .setHeight(50);
      DocumentApp.getUi().showModelessDialog(htmlOutput, 'Title');
}
</code>```

Body:
I would like to change the ForegroundColor of a selected text in a Google Docs with a keyboard shortcut.

I could make the "change the ForegroundColor" part (with a menu item bound to the function setColor() ), but not the "keyboard shortcut part".

I found this code but I have trouble implementing it:

$(document).keydown(function(e){
  //CTRL + Q keydown combo
  if(e.ctrlKey && e.keyCode == 81){
    $( '#output' ).html("I've been pressed!");
  }
})

My difficulties :

1) I am not sure where to place this code in my script editor (I tried to place it in the onOpen() function as below, but also above it without success).

2) I am not sure what the $(document) should refer to.

3) I am not sure what they mean by "having to click on / activate the sidebar first for that to happen".

function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('My Menu')
      .addItem('Color', 'setColor')
      .addToUi();

  var document = DocumentApp.getActiveDocument() // should it be here?
  $(document).keydown(function(e){
    //CTRL + Q keydown combo
    if(e.ctrlKey && e.keyCode == 81){
      SpreadsheetApp.getUi().alert('Hello, world!');
    }
  })
}

function setColor1() {
    var selection = DocumentApp.getActiveDocument().getSelection();
    if (selection) {
    var elements = selection.getRangeElements();
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];

        // Only modify elements that can be edited as text; skip images and other non-text elements.
        if (element.getElement().editAsText) {
            var text = element.getElement().editAsText();

            // Edit the selected part of the element, or the full element if it's completely selected.
            if (element.isPartial()) {
                text.setForegroundColor(element.getStartOffset(), element.getEndOffsetInclusive(), "#00FFFF");
            } else {
                text.setForegroundColor("#00FFFF");
            }
        }
    }
    }
}

Body:
Instead of using the sidebar as Anton Dementiev suggested, it's possible to use a modeless dialog box. It can be run from the function onOpen() or from a menu item.

Advantage of modeless dialog box over the sidebar: the dialog box is smaller and can be move anywhere on the screen (click on the title an drag it)

Inconvenient: it's easier to set the focus on the sidebar, because on the modeless dialog box, you have to click inside the content of the dialog (which can be quite small) to set the focus.

The .html is the same than the one Anton Dementiev gave, but the .gs is different:

function onOpen() {
  var ui = DocumentApp.getUi();

  ui.createMenu('My Menu')
      .addItem('Open Color Dialog', 'dialogBox')
      .addToUi();

      var htmlOutput = HtmlService   // alternative to the sidebar
        .createHtmlOutputFromFile('sidebar')
        .setWidth(50)
        .setHeight(50);
      DocumentApp.getUi().showModelessDialog(htmlOutput, 'Title');

}

  function dialogBox() {
      var htmlOutput = HtmlService
        .createHtmlOutputFromFile('sidebar')
        .setWidth(50)
        .setHeight(50);
      DocumentApp.getUi().showModelessDialog(htmlOutput, 'Title');
}


问:
Why is the Inverse Ackermann function used to describe complexity of Kruskal's algorithm?
In a class for analysis of algorithms, we are presented with this pseudocode for Kruskal's algorithm:

He then states the following, for disjoint-set forests:

A sequence of m MAKE-SET, UNION, and FIND-SET operations, n of which
  are MAKE-SET operations, can be performed on a disjoint-set forest
  with union by rank and path compression in worst-case time O(m α(n)).

Used to compute the complexity of Step 2, and steps 5-8

For connected G: |E| ≥ |V| -1; m = O(V + E), n = O(V);

So Steps 2, 5-8: O((V + E) α(V)) = O(E α(V))

α(V) = O(lg V) = O(lg E); so we obtain O(E lg E) ----- // how is α(V) equal here?

Kruskal: Steps 3, 5-8, and step 4: O(E lg E)

Observe: |E| < |V|2 -> lg E = O(lg V)

So, Kruskal complexity: O(E lg V)

I have attempted to understand the logic behind this "alpha(n)"/"α(n)" function, and from what I've read it seems that, simplistically, the Ackermann function is one that grows exponentially incredibly fast, and the inverse is one that grows logarithmically incredibly slowly.

If my interpretation is correct, what does "α(n)" represent? Does it mean that MAKE-SET operations are at most O(lg n)? How/Why is using inverse-Ackermann necessary? I was under the impression this operation is performed V times (for each vertex). Following this, α(V) is also simplified to O(lg V) = O(lg E), does this mean that, at a maximum, α(V) may be represented by O(lg V)?

Also, why is the |E| < |V|^2 -> lg E = O(lg V) statement made, how is it known that that |E| < |V|^2?

I think my question really boils down to, why is it that a "forest" representation of disjoint sets seems to be more efficient than those implemented with linked lists when my lecturer states they are both O(E log V)? Therefore is there a point in the increased difficulty of implementing disjoint sets with forests?

答:
α(V) = O(lg V) is a common abuse of notation, really we have α(V) ∈ O(lg V) (inverse-Ackerman of V is a member of the set of functions O(lg V)). They're not equal, they're not even the same type, one is a function and the other is a set of functions.

how is it known that that |E| < |V|²?

How many edges does a complete undirected graph have? You can't have more than that. You could in a multigraph, but that's not what the algorithm operates on, and it's useless to extend it to multigraphs - just throw out all but the best edge between a pair of nodes.

why is it that a "forest" representation of disjoint sets seems to be more efficient than those implemented with linked lists when my lecturer states they are both O(E log V)?

This is a weird thing to ask for several reasons. First, you're effectively measuring the efficiency of disjoint sets through Kruskals algorithm, not by its own. The "they" is your question is two implementations of Kruskals algorithm. Secondly, as you surely realized, the derivation of an upper bound used α(V) ∈ O(lg V). So it deliberately ignores a significant difference. That makes sense, because the time complexity is asymptotically dominated by the sorting step, but just because a difference is invisible in a big O doesn't mean it isn't there.

Therefore is there a point in the increased difficulty of implementing disjoint sets with forests?

There is no increased difficulty really. It's a super easy data structure that you can write in 5 minutes, just two arrays and some simple code - linked lists may actually be harder, especially if you have to do manual memory management. Note that outside the context of Kruskals algorithm, the difference is huge in terms of both asymptotic time and actual time.

But even in the context of Kruskals algorithm, improving the second stage of the algorithm obviously makes the total time better, even if it doesn't show in the worst case asymptotic time. FWIW you can improve the first stage too, you can use a heap (or one of its fancier drop-in replacements) and only heapify the edges in linear time. Then the second stage of the algorithm will extract them one by one but, crucially, you typically don't have to extract every edge - you can keep track of how many disjoint sets are left and stop when it drops to 1, potentially leaving many (even most) edges unused. In the worst case that doesn't help, but in real life it does. And in special cases you can sort the edges faster than O(E log E), when any of the fast sorts (counting sort, bucket sort, etc) apply.


问:
How do I update a Listbox Index with a Timer output
I am fairly new to coding with Visual Basics. I am working on a project were I need to create multiple items in a list and at the end of each list have a timer count up individually for when the Start button is pressed.
Currently the problem is that I have been unable to update the index when the timer increases its count.
Form Design Picture Here
I have listed my code below. Any feedback on how to achieve this will be much help.</p>

```<code>Public Class Form1

    Dim t1, t2, t3, t4 As Object
    Dim count As Object

    Public Sub GlobalTimerTick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
        count.Text = Val(count.Text) + 1
        ListBox1.Update()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        count = New System.Windows.Forms.Label
        count.Text = 0
        t1 = TextBox1.Text
        t2 = TextBox2.Text
        t3 = TextBox3.Text
        t4 = TextBox4.Text
        ListBox1.Items.Add("P" + t1 + " - " + t2 + " - " + t3 + " - " + t4 + " - " + count.text)

        If (t1 = "") Then
            MsgBox("Please enter a P-Level number.")
        ElseIf (t1 = 0) Then
            Timer1.Start()
        ElseIf (t1 = 1) Then

        ElseIf (t1 = 2) Then

        ElseIf (t1 = 3) Then

        ElseIf (t1 = 4) Then
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ListBox1.Items.Remove(ListBox1.SelectedItem)
        Timer1.Stop()
    End Sub
End Class
</code>```

答:
Still not sure if I understand correctly...but try this to start out with:</p>

```<code>Public Class Form1

    Private Entries As New System.ComponentModel.BindingList(Of Entry)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.DataSource = Entries
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent As New Entry
        ent.T1 = TextBox1.Text
        ent.T2 = TextBox2.Text
        ent.T3 = TextBox3.Text
        ent.T4 = TextBox4.Text
        Entries.Add(ent)
    End Sub

    Private Class Entry

        Public T1 As String
        Public T2 As String
        Public T3 As String
        Public T4 As String
        Public Shared Counter As Integer

        Private Shared Delimiter As String = " - "

        Public Overrides Function ToString() As String
            Return "P" & T1 & Delimiter & T2 & Delimiter & T3 & Delimiter & T4 & Delimiter & Counter
        End Function

    End Class

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Entry.Counter = Entry.Counter + 1
        ListBox1.DataSource = Nothing
        ListBox1.DataSource = Entries
    End Sub

End Class
</code>```

Body:
I am fairly new to coding with Visual Basics. I am working on a project were I need to create multiple items in a list and at the end of each list have a timer count up individually for when the Start button is pressed.
Currently the problem is that I have been unable to update the index when the timer increases its count.
Form Design Picture Here
I have listed my code below. Any feedback on how to achieve this will be much help.

Public Class Form1

    Dim t1, t2, t3, t4 As Object
    Dim count As Object

    Public Sub GlobalTimerTick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
        count.Text = Val(count.Text) + 1
        ListBox1.Update()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        count = New System.Windows.Forms.Label
        count.Text = 0
        t1 = TextBox1.Text
        t2 = TextBox2.Text
        t3 = TextBox3.Text
        t4 = TextBox4.Text
        ListBox1.Items.Add("P" + t1 + " - " + t2 + " - " + t3 + " - " + t4 + " - " + count.text)

        If (t1 = "") Then
            MsgBox("Please enter a P-Level number.")
        ElseIf (t1 = 0) Then
            Timer1.Start()
        ElseIf (t1 = 1) Then

        ElseIf (t1 = 2) Then

        ElseIf (t1 = 3) Then

        ElseIf (t1 = 4) Then
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ListBox1.Items.Remove(ListBox1.SelectedItem)
        Timer1.Stop()
    End Sub
End Class

Body:
Still not sure if I understand correctly...but try this to start out with:

Public Class Form1

    Private Entries As New System.ComponentModel.BindingList(Of Entry)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.DataSource = Entries
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim ent As New Entry
        ent.T1 = TextBox1.Text
        ent.T2 = TextBox2.Text
        ent.T3 = TextBox3.Text
        ent.T4 = TextBox4.Text
        Entries.Add(ent)
    End Sub

    Private Class Entry

        Public T1 As String
        Public T2 As String
        Public T3 As String
        Public T4 As String
        Public Shared Counter As Integer

        Private Shared Delimiter As String = " - "

        Public Overrides Function ToString() As String
            Return "P" & T1 & Delimiter & T2 & Delimiter & T3 & Delimiter & T4 & Delimiter & Counter
        End Function

    End Class

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Entry.Counter = Entry.Counter + 1
        ListBox1.DataSource = Nothing
        ListBox1.DataSource = Entries
    End Sub

End Class


问:
Hangfire FileNotFoundException: Could not load file or assembly DynamicProxyGenAssembly,
I am having an issue with HangFire after i set a background job it get set but when i open the HangFire dashboard i see the following exception

System.IO.FileNotFoundException: Could not load file or assembly
  'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=null' or one of its dependencies. The system cannot
  find the file specified.

All interfaces are being registered using AutoFac for DI. , I am setting up the following in the startup.cs

I have the following code in the startup

```<code>  GlobalConfiguration.Configuration.UseSqlServerStorage("Hangfire");
  app.UseHangfireDashboard();
  app.UseHangfireServer();
</code>```

I have the following ocde to schule the job

```<code> public class ScheduleAppService : IScheduleAppService
  {
    private readonly IRunCommandAppService _runCommandAppService;

    public ScheduleAppService(IRepository<Schedule> repository, IAdHocTemplateRunnerAppService adHocTemplateRunner) : base(repository)
    {
      _adHocTemplateRunner = adHocTemplateRunner;
    }

    public async Task CreateSchedule(ScheduleDto schedule)
    {
      input.Schedule.JobId = BackgroundJob.Schedule(
        () => _runCommandAppService.AddTemplate(
          new Template{ RunId = Guid.NewGuid().ToString(), TemplateId = schedule.Id }), schedule.Start);
    }
}
</code>```

The code which is being called is here

```<code> public class RunCommandAppService  : IRunCommandAppService
  {
    private readonly IRepository<Template> _templateRepo;

    public RunCommandAppService (IRepository<Template> templateRepo)
    {
      _templateRepo = templateRepo;
    }

    public void AddTemplate(Template input)
    {
      try
      {
        Run(input);
      }
      finally
      {
        SetRunComplate(input.RunId);
      }
    }
</code>```

答:
Might not be the same context as yours but I think it's still worth adding it here:

-Hangfire server was running as a Windows service;

-Hangfire dashboard running on top of a ASP.NET MVC 5 app;

-jobs were actually running but dashboard kept displaying a FileNotFoundException;

Solution:  added a reference to the missing assembly (ie: 'DynamicProxyGenAssembly2') in the dashboard web app.

Same problem was reported and solved in the same way by @reggieboyYEAH.

Details here: https://github.com/HangfireIO/Hangfire/issues/558

Body:
I am having an issue with HangFire after i set a background job it get set but when i open the HangFire dashboard i see the following exception

System.IO.FileNotFoundException: Could not load file or assembly
  'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral,
  PublicKeyToken=null' or one of its dependencies. The system cannot
  find the file specified.

All interfaces are being registered using AutoFac for DI. , I am setting up the following in the startup.cs

I have the following code in the startup

  GlobalConfiguration.Configuration.UseSqlServerStorage("Hangfire");
  app.UseHangfireDashboard();
  app.UseHangfireServer();

I have the following ocde to schule the job

 public class ScheduleAppService : IScheduleAppService
  {
    private readonly IRunCommandAppService _runCommandAppService;

    public ScheduleAppService(IRepository<Schedule> repository, IAdHocTemplateRunnerAppService adHocTemplateRunner) : base(repository)
    {
      _adHocTemplateRunner = adHocTemplateRunner;
    }

    public async Task CreateSchedule(ScheduleDto schedule)
    {
      input.Schedule.JobId = BackgroundJob.Schedule(
        () => _runCommandAppService.AddTemplate(
          new Template{ RunId = Guid.NewGuid().ToString(), TemplateId = schedule.Id }), schedule.Start);
    }
}

The code which is being called is here

 public class RunCommandAppService  : IRunCommandAppService
  {
    private readonly IRepository<Template> _templateRepo;

    public RunCommandAppService (IRepository<Template> templateRepo)
    {
      _templateRepo = templateRepo;
    }

    public void AddTemplate(Template input)
    {
      try
      {
        Run(input);
      }
      finally
      {
        SetRunComplate(input.RunId);
      }
    }


问:
Optimizing Mandelbrot fractal
This is a code that outputs in a .ppm file the mandelbrot fractal. How can I optimize this?

```<code>#include<bits/stdc++.h>
using namespace std;

int findMandelbrot(double cr, double ci, int max_iterations)
{
    int i = 0;
    double zr = 0.0, zi = 0.0;
    while (i < max_iterations && zr * zr + zi * zi < 4.0)
    {
        double temp = zr * zr - zi * zi + cr;
        zi = 2.0 * zr * zi + ci;
        zr = temp;
        ++i;
    }
    return i;
}

double mapToReal(int x, int imageWidth, double minR, double maxR)
{
    double range = maxR - minR;
    return x * (range / imageWidth) + minR;
}

double mapToImaginary(int y, int imageHeight, double minI, double maxI)
{
    double range = maxI - minI;
    return y * (range / imageHeight) + minI;
}

int main()
{
    ifstream f("input.txt");
    int imageWidth, imageHeight, maxN;
    double minR, maxR, minI, maxI;

    if (!f)
    {
        cout << "Could not open file!" << endl;
        return 1;
    }

    f >> imageWidth >> imageHeight >> maxN;
    f >> minR >> maxR >> minI >> maxI;

    ofstream g("output_image.ppm");
    g << "P3" << endl;
    g << imageWidth << " " << imageHeight << endl;
    g << "255" << endl;

    double start = clock();

    for (int i = 0; i < imageHeight; i++)
    {
        for (int j = 0; j < imageWidth; j++)
        {
            double cr = mapToReal(j, imageWidth, minR, maxR);
            double ci = mapToImaginary(i, imageHeight, minI, maxI);

            int n = findMandelbrot(cr, ci, maxN);

            int r = ((int)sqrt(n) % 256);
            int gr = (2*n % 256);
            int b = (n % 256);

            g << r << " " << gr << " " << b << " ";
        }
        g << endl;

        if(i == imageHeight / 2) break;
    }

    cout << "Finished!" << endl;

    double stop = clock();

    cout << (stop-start)/CLOCKS_PER_SEC;
    return 0;
}
</code>```

I go until imageHeight / 2 because in a photoshop I can just copy the other half.
I was thinking about loghartimic power but tried something and only works with integers...

答:
So this is the hot loop:

```<code>int i = 0;
double zr = 0.0, zi = 0.0;
while (i < max_iterations && zr * zr + zi * zi < 4.0)
{
    double temp = zr * zr - zi * zi + cr;
    zi = 2.0 * zr * zi + ci;
    zr = temp;
    ++i;
}
return i;
</code>```

I know how to implement non-integer power in fast CPU instructions but it won't get you out of a bind as it doesn't work for complex numbers at all. Nor will using std::complex help at all. You won't gain anything to pay for the non-inlining and certainly can't apply optimizations as you find them. So the best I can do is this:

```<code>int i = max_iterations;
double zr = 0.0, zi = 0.0;
do {
    double temp = zr * zr - zi * zi + cr;
    zi = 2.0 * zr * zi + ci;
    zr = temp;
} while (--i && zr * zr + zi * zi < 4.0)
return max_iterations - i;
</code>```

Yes I know taking one integer test out of the loop didn't buy much over all that. I only found one other optimizer and you'll have to check if its really faster:

```<code>int i = max_iterations;
double zr = 0.0, zi = 0.0;
do {
    double tempr = zr * zr - zi * zi + cr;
    double tempi = zr * zi;
    zi = tempi + tempi + ci;
    zr = tempr;
} while (--i && zr * zr + zi * zi < 4.0);
return max_iterations - i;
</code>```

That's all there is folks.

Title: Optimizing Mandelbrot fractal

Body:
This is a code that outputs in a .ppm file the mandelbrot fractal. How can I optimize this?

#include<bits/stdc++.h>
using namespace std;

int findMandelbrot(double cr, double ci, int max_iterations)
{
    int i = 0;
    double zr = 0.0, zi = 0.0;
    while (i < max_iterations && zr * zr + zi * zi < 4.0)
    {
        double temp = zr * zr - zi * zi + cr;
        zi = 2.0 * zr * zi + ci;
        zr = temp;
        ++i;
    }
    return i;
}

double mapToReal(int x, int imageWidth, double minR, double maxR)
{
    double range = maxR - minR;
    return x * (range / imageWidth) + minR;
}

double mapToImaginary(int y, int imageHeight, double minI, double maxI)
{
    double range = maxI - minI;
    return y * (range / imageHeight) + minI;
}

int main()
{
    ifstream f("input.txt");
    int imageWidth, imageHeight, maxN;
    double minR, maxR, minI, maxI;

    if (!f)
    {
        cout << "Could not open file!" << endl;
        return 1;
    }

    f >> imageWidth >> imageHeight >> maxN;
    f >> minR >> maxR >> minI >> maxI;

    ofstream g("output_image.ppm");
    g << "P3" << endl;
    g << imageWidth << " " << imageHeight << endl;
    g << "255" << endl;

    double start = clock();

    for (int i = 0; i < imageHeight; i++)
    {
        for (int j = 0; j < imageWidth; j++)
        {
            double cr = mapToReal(j, imageWidth, minR, maxR);
            double ci = mapToImaginary(i, imageHeight, minI, maxI);

            int n = findMandelbrot(cr, ci, maxN);

            int r = ((int)sqrt(n) % 256);
            int gr = (2*n % 256);
            int b = (n % 256);

            g << r << " " << gr << " " << b << " ";
        }
        g << endl;

        if(i == imageHeight / 2) break;
    }

    cout << "Finished!" << endl;

    double stop = clock();

    cout << (stop-start)/CLOCKS_PER_SEC;
    return 0;
}

I go until imageHeight / 2 because in a photoshop I can just copy the other half.
I was thinking about loghartimic power but tried something and only works with integers...

Body:
So this is the hot loop:

int i = 0;
double zr = 0.0, zi = 0.0;
while (i < max_iterations && zr * zr + zi * zi < 4.0)
{
    double temp = zr * zr - zi * zi + cr;
    zi = 2.0 * zr * zi + ci;
    zr = temp;
    ++i;
}
return i;

I know how to implement non-integer power in fast CPU instructions but it won't get you out of a bind as it doesn't work for complex numbers at all. Nor will using std::complex help at all. You won't gain anything to pay for the non-inlining and certainly can't apply optimizations as you find them. So the best I can do is this:

int i = max_iterations;
double zr = 0.0, zi = 0.0;
do {
    double temp = zr * zr - zi * zi + cr;
    zi = 2.0 * zr * zi + ci;
    zr = temp;
} while (--i && zr * zr + zi * zi < 4.0)
return max_iterations - i;

Yes I know taking one integer test out of the loop didn't buy much over all that. I only found one other optimizer and you'll have to check if its really faster:

int i = max_iterations;
double zr = 0.0, zi = 0.0;
do {
    double tempr = zr * zr - zi * zi + cr;
    double tempi = zr * zi;
    zi = tempi + tempi + ci;
    zr = tempr;
} while (--i && zr * zr + zi * zi < 4.0);
return max_iterations - i;

That's all there is folks.


问:
Why do some developers declare String objects in their Interfaces in Java, and how does it work?
When I was analysing a code in my project, I came accross this situation.
I have got an Interface with complete String constants declaration as below

```<code>public interface SampleInterface {
    String EXAMPLE_ONE = "exampleOne";
    String USER_ID     = "userId";

    public void setValue();
}
</code>```

If any class implements this SampleInterface interface, what happens to the variables it declares?

Does the inherited class get access to all the variables?

Does the implemented class needs to override the declarations?

What might be the purpose of declaring the String variables in an interface, when we could use an abstract class for this purpose?

Also, what is the best strategy:

A class with the final static fields and a private constructor?

An Interface with the variables as seen above?

答:
It's a Common Java Idiom

In an interface in Java, all members are implicitly public, and fields in particular are implicitly public static final. You DON'T have a choice. If you try to use any other permission level than public, the compiler would scream at you as it wouldn't make any sense.

So any implementing class will indeed inherit the members, including these static constant fields.

Why do People Use this Idiom?

There are several reasons why you would do this in an interface, and usually it is to use it as a constant store. This idiom is used to simply bundle constants together in one place, not necessarily to have the interface used as part of an inheritance tree in an OO way.

So you can call as usuall MyInterface.MY_CONST to access one of your constants.

You would do this over an interface usually when you don't need any behavior to be defined, so when you don't need any methods. It's really just a static store (often, the interface is made final itself as well). You could use an abstract class for this as well, for instance if you want to encapsulate and hide details of an implementation. But in this case, where you have both fields and methods, usually your objective is simply to provide some constants and a contract for sub-classes.

Considering in your case there's also a method signature as part of your interface, there's obviously an intent to implement this interface. In which case you can still access your data as either:

MyInterface.MY_CONST,

or MyExtendingClass.MY_CONST,

or instanceOfMyExtendingClass.MY_CONST.

More Information

For more information, have a look at:

this FAQ entry and the ones that follow it,

comments by Anon and Jeff regarding misuses of this form,

Enum type as introduced since Java 5 (which, and as mentioned by John, would in many cases definitely be a better idea: more elegant, with the added benefit of type-safety when passing it, and using fairly optimized constructs to lookup and manipulate the values).

Body:
When I was analysing a code in my project, I came accross this situation.
I have got an Interface with complete String constants declaration as below

public interface SampleInterface {
    String EXAMPLE_ONE = "exampleOne";
    String USER_ID     = "userId";

    public void setValue();
}

If any class implements this SampleInterface interface, what happens to the variables it declares?

Does the inherited class get access to all the variables?

Does the implemented class needs to override the declarations?

What might be the purpose of declaring the String variables in an interface, when we could use an abstract class for this purpose?

Also, what is the best strategy:

A class with the final static fields and a private constructor?

An Interface with the variables as seen above?


问:
How to update redux state further down the tree
For a given reducer, my redux state tree typically looks something like this:

```<code>{
  someField: 'some value',
  // ... more fields
  metadata: {
    pending: false,
    fetched: true,
  }
}
</code>```

Typically, when I do an async request, I fire a SOME_ACTION_REQUEST action, which sets the metadata.pending property to true. It's reset to false again when the matching SOME_ACTION_RESPONSE or SOME_ACTION_ERROR event trickles in later.

However, the way I update the state is a bit verbose:

```<code>case actions.SOME_ACTION_REQUEST: {
  return {
    ...state,
    metadata: { ...state.metadata, pending: true },
  };
}
</code>```

Is there a simpler way of doing this?

Object.assign({}, state, { metadata: { pending: true } }) isn't very readable either.

答:
You can go for a nested structure of reducer.

where have a function/reducer naming metadata, call this to change the fields.

Example code

```<code>const metadata = (state = [], action = {}) => {
    switch (action.type) {
        case actions.SOME_ACTION_REQUEST::
            return {...state, ...action.payload.metadata};

        default:
            return state;
    }
};
const someReducer = (state = initalState, action = {}) => {
    let metadata = {};
    switch (action.type) {
        case actions.SOME_ACTION_REQUEST: {
            metadata = metadata(state.metadata, action)
            return {
                ...state,
                ...metadata
                };
            }
    }
};
</code>```

Body:
For a given reducer, my redux state tree typically looks something like this:

{
  someField: 'some value',
  // ... more fields
  metadata: {
    pending: false,
    fetched: true,
  }
}

Typically, when I do an async request, I fire a SOME_ACTION_REQUEST action, which sets the metadata.pending property to true. It's reset to false again when the matching SOME_ACTION_RESPONSE or SOME_ACTION_ERROR event trickles in later.

However, the way I update the state is a bit verbose:

case actions.SOME_ACTION_REQUEST: {
  return {
    ...state,
    metadata: { ...state.metadata, pending: true },
  };
}

Is there a simpler way of doing this?

Object.assign({}, state, { metadata: { pending: true } }) isn't very readable either.

Body:
You can go for a nested structure of reducer.

where have a function/reducer naming metadata, call this to change the fields.

Example code

const metadata = (state = [], action = {}) => {
    switch (action.type) {
        case actions.SOME_ACTION_REQUEST::
            return {...state, ...action.payload.metadata};

        default:
            return state;
    }
};
const someReducer = (state = initalState, action = {}) => {
    let metadata = {};
    switch (action.type) {
        case actions.SOME_ACTION_REQUEST: {
            metadata = metadata(state.metadata, action)
            return {
                ...state,
                ...metadata
                };
            }
    }
};


问:
Impossible to install shared library with .so file
I'm not able to install this library on Ubuntu, or at least to compile a .cpp linking the library to it. I have finish all Google and StackOverflow answers.

So ok, first of all I run cmake and after I run make (and make install to be sure). Still, if I run g++ xxx.cpp -lcrb -o test I get this error: fatal error: CRNB.h: No such file or directory. The library doesn't like to be installed yet, so I copy the libcrn.so file  to /usr/lib and I run sudo ldconfig to load it. Now...

sudo ldconfig -n -v /usr/lib/ says it's properly installed (not before copying the .so file).

g++ -lcrn says it's properly installed because returns undefined reference to 'main' and not cannot find -lcrn (as before copying the .so file)

ldd /bin/ls doesn't list the library, which means it's not installed

Anyways, trying to compile still throws the same error. I have also tried...

... to create a .conf file and add it to the folder /etc/ld.so.conf.d/

... to creaty a symbolic link of the .so file to /usr/lib

... to repeat all this solutions also in /usr/local/lib and in /lib folders

... to add all this folders to the /etc/ld.so.conf paths

... to export LD_LIBRARY_PATH to the path of the .so file

And many more similar. As you can see all this things are the same, so it's clear that I'm losing something important. Anyone knows what it could be?

Thanks a lot!

答:
You need to specify with "-I" flag the include directories, or import it to your system.

Try:

```<code>g++ src_name.cpp -L./your/library -lcrn -I./your/headers -o out_name -std=c++11
</code>```

Or:

You can copy from libcrn include files ("*.h") to "/usr/local/include/" and the library to "/usr/local/lib/" if doesn't exist, and then:

```<code>g++ src_name.cpp -lcrn -o out_name -std=c++11
</code>```

Body:
You need to specify with "-I" flag the include directories, or import it to your system.

Try:

g++ src_name.cpp -L./your/library -lcrn -I./your/headers -o out_name -std=c++11

Or:

You can copy from libcrn include files ("*.h") to "/usr/local/include/" and the library to "/usr/local/lib/" if doesn't exist, and then:

g++ src_name.cpp -lcrn -o out_name -std=c++11


问:
bcrypt Error: data and hash arguments required
I am getting a bcrypt error stating that data and hash arguments are required, referencing line #44 in my routes.js file. From what I can tell, I am passing that information: the first parameter to bcrypt.compare is the user entered password, and the second is the hashed password retrieved from the db. What am I doing wrong?

```<code>bcrypt.compare(req.params.password, user.password, function...
</code>```

routes.js

```<code>'use strict'

var express = require('express');
var router = express.Router();
var User = require('../app/models/user');
//password hashing
var bcrypt = require('bcrypt');

var count = 0;

router.use(function(req, res, next) {
    count++;
    console.log('API hit count = %s', count);
    next();
});

// /users post(create new user) get(specific user)
router.route('/users')
    .post(function(req,res) {
        var user = new User();
        user.username = req.body.username;
        user.password = bcrypt.hashSync(req.body.password, 10);

        //save the user and checkfor errors
        user.save(function(err) {
            if (err) {
                res.send(err);
            } else {
                res.json({message: "User created!"});
            }
        });

    })

router.route('/users/:username')
    .get(function(req, res) {
        var query = {
            username: req.params.username,
        };
        User.findOne(query, function(err, user) {
            if (err) {
                res.send(err);
            } else {
                bcrypt.compare(req.params.password, user.password, function(err, res) {
                    if(err) {
                        console.log('Comparison error: ', err);
                    }
                })
                res.json(user);
            }
        });
    })
</code>```

答:
bcrypt.compare takes 3 parameters; passwordToCheck, passwordHash, and a callback, respectively. (Check the documentation for examples)

This error means one or both of the first 2 parameters are either null or undefined. Therefore, make sure both of them are passed correctly. (Not as null or undefined)

Body:
I am getting a bcrypt error stating that data and hash arguments are required, referencing line #44 in my routes.js file. From what I can tell, I am passing that information: the first parameter to bcrypt.compare is the user entered password, and the second is the hashed password retrieved from the db. What am I doing wrong?

bcrypt.compare(req.params.password, user.password, function...

routes.js

'use strict'

var express = require('express');
var router = express.Router();
var User = require('../app/models/user');
//password hashing
var bcrypt = require('bcrypt');

var count = 0;

router.use(function(req, res, next) {
    count++;
    console.log('API hit count = %s', count);
    next();
});

// /users post(create new user) get(specific user)
router.route('/users')
    .post(function(req,res) {
        var user = new User();
        user.username = req.body.username;
        user.password = bcrypt.hashSync(req.body.password, 10);

        //save the user and checkfor errors
        user.save(function(err) {
            if (err) {
                res.send(err);
            } else {
                res.json({message: "User created!"});
            }
        });

    })

router.route('/users/:username')
    .get(function(req, res) {
        var query = {
            username: req.params.username,
        };
        User.findOne(query, function(err, user) {
            if (err) {
                res.send(err);
            } else {
                bcrypt.compare(req.params.password, user.password, function(err, res) {
                    if(err) {
                        console.log('Comparison error: ', err);
                    }
                })
                res.json(user);
            }
        });
    })

ContentLicense: CC BY-SA 4.0


问:
SQLException or Execute update returns null?
I am working on a java project where I have some operations in a DB.
I am working on handling the exceptions. However I am a bit confused, if a query is wrong because the parameter used doesn't exist: try to do a SELECT query with a wrong value: wrong login name, wrong order number...), does it create an SQL exception or does it simply return 0 when executeQuery or executeUpdate? And does it variate if this parameter is a primary key or a foreign key ?</p>

答:
As pointed out, the question can be easily answered if you would have consulted the documentation: https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#executeQuery-java.lang.String-

Returns:
  a ResultSet object that contains the data produced by the given query; never null

So if you queue for e.g. a username that doesn't exist (with this password hash), it will return a ResultSet, which will be empty though.


问:
Why python does not see dist-packages when in virtualenv?
I needed to use opencv with python on my ubuntu 12.04 so I used this tutorial http://www.pyimagesearch.com/2015/06/22/install-opencv-3-0-and-python-2-7-on-ubuntu/ .

Unfortunately it came with somethin I do not quite understand - virtualenv. Now after completeing tutorial I have a problem. When I deactivate my virtualenv inside python I can see my dist-packages like numpy, matplotlib but dont see opencv (cv2), but when I use virtualenv inside python I can see opencv but no matplotlib or numpy.

To make a point: I need to make python see all of my dist-packages.

I found a way that works but is so inelegant i cannot live with it - I can create function called in init that modifies sys path.

答:
Virtualenv is specifically designed to give you a clean python development environment. i.e. a fresh copy of python and any packages you need should then be installed while in the virtual env.

You can think of it like containers if you use Docker etc.

Main point is, if you want to use a package in virtual env, just use pip install ... while inside the env.


问:
Javascript - Add an error msg when xml is unavailable
I've built an iPhone app that's working great so far.  I've had some great help here optimising the code, but wondered if I could please obtain some help to display an error msg when the following conditions are met.

When the xml file is unavailable

When one of the xml data fields is missing (eg. brisbane is currently not listed in the xml for function 1, but should be - http://www.arpansa.gov.au/uvindex/realtime/xml/uvvalues.xml)

My current code: http://pastebin.com/VgBmdXjd

At the moment I've got the error msg working when the xml data field is empty (not missing), which should be apparent in the code. Please let me know if it isn't.

Also, both functions are setup a little differently, which might affect the way the condition is formatted.  If anyone is able to explain the differences, that would be great too.

Any help is sincerely appreciated.

Kind Regards,
Glen

答: You need to set up the ajax error event handler in jQuery. Good Example</p>


问:
Error during inference: Invalid argument: No OpKernel was registered to support Op 'DecodeJpeg' with these attrs
I got this error message when I ran the app. It crash just a few seconds after app launched.</p>

```<code>05-28 09:05:29.791 15453-15472/my.xxxxx.androidtensorflowbirdexample A/native: tensorflow_jni.cc:304 Error during inference: Invalid argument: No OpKernel was registered to support Op 'DecodeJpeg' with these attrs
                                                                                [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false](DecodeJpeg/contents)]]
05-28 09:05:29.791 15453-15472/my.xxxxx.androidtensorflowbirdexample A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 15472 (InferenceThread)

                                                                                [ 05-28 09:05:29.796 15453:15503 E/         ]
                                                                                [android_ws] Format: 5, Width: 1080, Height: 1620

                                                                                [ 05-28 09:05:29.796 15453:15503 E/         ]
                                                                                [android_ws] Format: 5, Width: 1080, Height: 1620
</code>```

答: Looks like you Android version or the mobile  CPU does not support the Tensorflow JNI library. You may want to check both your Android version and your mobile CPU.</p>

Body:
I got this error message when I ran the app. It crash just a few seconds after app launched.

05-28 09:05:29.791 15453-15472/my.xxxxx.androidtensorflowbirdexample A/native: tensorflow_jni.cc:304 Error during inference: Invalid argument: No OpKernel was registered to support Op 'DecodeJpeg' with these attrs
                                                                                [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=3, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false](DecodeJpeg/contents)]]
05-28 09:05:29.791 15453-15472/my.xxxxx.androidtensorflowbirdexample A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 15472 (InferenceThread)

                                                                                [ 05-28 09:05:29.796 15453:15503 E/         ]
                                                                                [android_ws] Format: 5, Width: 1080, Height: 1620

                                                                                [ 05-28 09:05:29.796 15453:15503 E/         ]
                                                                                [android_ws] Format: 5, Width: 1080, Height: 1620