问:
Segmentation Fault - Difficulty with assigning a class
I am trying to assign my class DictObj to create a new instance of the class. What it wants to do, is to have a pointer to the class created, rather than the actual Object.

If I am to do what it likes, and have:
DictObj * d;, and then say something like, "d->load();", it gives me difficulty when assigning a string to a string. Such as with, assuming word is of type string, word = a;, where a is also a string passed as a parameter of the same type (no pointers or references). It gives me a segmentation fault when I do this.

Any suggestions as to how to fix this problem? Below, I will show a sample of the code:

P.S. I know I am  adding "Dicts.cpp", even though I am not supposed to. It is giving me an error of

/tmp/ccEFPwDS.o: In function 'main':
  /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW/main.cpp:60: undefined reference to DictObj::load()

ACTUAL CODE:

```<code>#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<thread>
#include<cassert>
#include<exception>
#include"Directory.hpp"
#include"Dicts.cpp"
#include"Tests.hpp"

int main() {
  cout << "Hello\n\n";
  DictObj * d;
  d->load();
  return 0;
}
</code>```

Here is Dicts.cpp

```<code>void DictObj::setW(string a)
{
    word = a;
}
</code>```

This gives me a segmentation fault when it runs the method:

```<code>void DictObj::load()
{
    string temp;
    cout <<"Type New Word: ";
    getline(cin, temp);
    cin >> temp;

    setW(temp);
</code>```

the code goes on, but the error is at "setW(temp)"

IF I try to make a new DictObj in the main class, as expected, then it gives me an error

Code:

```<code>int main() {
    cout << "Hello\n\n";
    DictObj d = new DictObj();
    d.load();
    return 0;
}
</code>```

Error:

```<code>g++ -std=c++14 -Wall -c "main.cpp" (in directory:         /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW)
main.cpp: In function ‘int main()’:
main.cpp:59:26: error: conversion from ‘DictObj*’ to non-scalar type     ‘DictObj’ requested
  DictObj d = new DictObj();
                      ^
Compilation failed.
</code>```

ALSO: My compilation code is as follows (I am using Geany)

g++ -std=c++14 -Wall -c "%f"

My Build code is as follows:

g++ -g -std=c++14 -Wall -Wextra -pedantic -lpthread  -o "%e"  "%f"

DEFINITION of DictObj class:

```<code>class DictObj
{
    public:
       DictObj();
       DictObj(const DictObj&);
       void load();
       void setW(string);
   private:
       string word;
};
</code>```

答:
USELESS QUSTION, AFTERALL.

I have found that the most possible problem with the code is that I am using Class Definitions to create Class Definitions of the same Class Definition. I.E.
in the class DictObj, I am defining a variable of type DictObj in the constructor. I will have to rewrite the class to separate the vectors (which is most of it) and the base DictObj nodes (the non-vectors).

Boo hoo.

Stupidity on my part.

I guess the lesson to be learned is NEVER EVER EVER DEFINE YOUR CLASS WITHIN A CLASS IN THE CONSTRUCTOR WHEN MAKING A NEW OBJECT.

At least I learned a valuable lesson!

Body:
I am trying to assign my class DictObj to create a new instance of the class. What it wants to do, is to have a pointer to the class created, rather than the actual Object.

If I am to do what it likes, and have:
DictObj * d;, and then say something like, "d->load();", it gives me difficulty when assigning a string to a string. Such as with, assuming word is of type string, word = a;, where a is also a string passed as a parameter of the same type (no pointers or references). It gives me a segmentation fault when I do this.

Any suggestions as to how to fix this problem? Below, I will show a sample of the code:

P.S. I know I am  adding "Dicts.cpp", even though I am not supposed to. It is giving me an error of

/tmp/ccEFPwDS.o: In function 'main':
  /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW/main.cpp:60: undefined reference to DictObj::load()

ACTUAL CODE:

#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<thread>
#include<cassert>
#include<exception>
#include"Directory.hpp"
#include"Dicts.cpp"
#include"Tests.hpp"

int main() {
  cout << "Hello\n\n";
  DictObj * d;
  d->load();
  return 0;
}

Here is Dicts.cpp

void DictObj::setW(string a)
{
    word = a;
}

This gives me a segmentation fault when it runs the method:

void DictObj::load()
{
    string temp;
    cout <<"Type New Word: ";
    getline(cin, temp);
    cin >> temp;

    setW(temp);

the code goes on, but the error is at "setW(temp)"

IF I try to make a new DictObj in the main class, as expected, then it gives me an error

Code:

int main() {
    cout << "Hello\n\n";
    DictObj d = new DictObj();
    d.load();
    return 0;
}

Error:

g++ -std=c++14 -Wall -c "main.cpp" (in directory:         /home/courtneymaroney/Desktop/Courtney/Documents/AI/NEW)
main.cpp: In function ‘int main()’:
main.cpp:59:26: error: conversion from ‘DictObj*’ to non-scalar type     ‘DictObj’ requested
  DictObj d = new DictObj();
                      ^
Compilation failed.

ALSO: My compilation code is as follows (I am using Geany)

g++ -std=c++14 -Wall -c "%f"

My Build code is as follows:

g++ -g -std=c++14 -Wall -Wextra -pedantic -lpthread  -o "%e"  "%f"

DEFINITION of DictObj class:

class DictObj
{
    public:
       DictObj();
       DictObj(const DictObj&);
       void load();
       void setW(string);
   private:
       string word;
};


来源: stackexchange

问:
How to get automatic table creation working in spring / hibernate / jpa?
I can't get automatic table creation working in spring when using hibernate / jpa.

Here are my config files:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence
   xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">

    <persistence-unit name="naveroTest">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <class>xxx</class>
        ...

        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
   <property name="hibernate.connection.url" value="jdbc:hsqldb:file:/tmp/naveroTestDB"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

context.xml

```<code>   <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

     <!-- For auto creation of tables -->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
      <property name="url" value="jdbc:hsqldb:file:/tmp/naveroTestDB" />
      <property name="username" value="sa" />
      <property name="password" value="" />
     </bean>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="loadTimeWeaver">
       <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
      </property>
      <property name="jpaVendorAdapter">
       <bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="generateDdl" value="true" />
        <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
        <property name="showSql" value="true" />
       </bean>
      </property>
     </bean>

     <bean id="PictureBean" class="de.navero.server.bl.PictureBean">
      <property name="entityManagerFactory"><ref local="entityManagerFactory" /></property>
     </bean>

    </beans>
</code>```

Any ideas what may be wrong?
Thanks for any help :).

答:
sadly both solutions didn't work for me :(. "hibernate.hbm2ddl.auto=update" would be also ok, as it should create the tables if they're not present.

It seems that all property settings from the persistence.xml are recognized as username and database provider are set correctly. Sadly the tables aren't created at startup which causes my testcase to fail as the SELECT statement throws an error ...

As you can see, I've set the connection url to use a local file database, which allows me to review the database log after the test run. But the log file is still empty after the test run, even no error is written to it :(.

ContentLicense: CC BY-SA 2.5

Body:
I can't get automatic table creation working in spring when using hibernate / jpa.

Here are my config files:

<?xml version="1.0" encoding="UTF-8"?>
<persistence
   xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">

    <persistence-unit name="naveroTest">
     <provider>org.hibernate.ejb.HibernatePersistence</provider>
     <class>xxx</class>
        ...

        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
   <property name="hibernate.connection.url" value="jdbc:hsqldb:file:/tmp/naveroTestDB"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
        </properties>
    </persistence-unit>
</persistence>

context.xml

   <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
                           http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
      <property name="url" value="jdbc:hsqldb:file:/tmp/naveroTestDB" />
      <property name="username" value="sa" />
      <property name="password" value="" />
     </bean>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="loadTimeWeaver">
       <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
      </property>
      <property name="jpaVendorAdapter">
       <bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="generateDdl" value="true" />
        <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
        <property name="showSql" value="true" />
       </bean>
      </property>
     </bean>

     <bean id="PictureBean" class="de.navero.server.bl.PictureBean">
      <property name="entityManagerFactory"><ref local="entityManagerFactory" /></property>
     </bean>

    </beans>

Any ideas what may be wrong?
Thanks for any help :).


问:
How do I refresh the contents of a webview
How do I refresh the contents of a webview?
That's my code THERE IS A WAY to update it? there a way to update the page automatically? thanks a lot</p>

```<code>public class MainActivity extends Activity implements AdvancedWebView.Listener {

private static final String TEST_PAGE_URL = "";
private AdvancedWebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mWebView = (AdvancedWebView) findViewById(R.id.webview);
    mWebView.setListener(this, this);
    mWebView.setGeolocationEnabled(false);
    mWebView.setMixedContentAllowed(true);
    mWebView.setCookiesEnabled(true);
    mWebView.setThirdPartyCookiesEnabled(true);
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            Toast.makeText(MainActivity.this, "Finished loading", Toast.LENGTH_SHORT).show();
        }

    });
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Toast.makeText(MainActivity.this, title, Toast.LENGTH_SHORT).show();
        }

    });
    mWebView.addHttpHeader("X-Requested-With", "");
    mWebView.loadUrl("");
}

@SuppressLint("NewApi")
@Override
protected void onResume() {
    super.onResume();
    mWebView.onResume();
    // ...
}

@SuppressLint("NewApi")
@Override
protected void onPause() {
    mWebView.onPause();
    // ...
    super.onPause();
}

@Override
protected void onDestroy() {
    mWebView.onDestroy();
    // ...
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    mWebView.onActivityResult(requestCode, resultCode, intent);
    // ...
}

@Override
public void onBackPressed() {
    if (!mWebView.onBackPressed()) { return; }
    // ...
    super.onBackPressed();
}

@Override
public void onPageStarted(String url, Bitmap favicon) {
    mWebView.setVisibility(View.INVISIBLE);
}

@Override
public void onPageFinished(String url) {
    mWebView.setVisibility(View.VISIBLE);
}

@Override
public void onPageError(int errorCode, String description, String failingUrl) {
    Toast.makeText(MainActivity.this, "onPageError(errorCode = "+errorCode+",  description = "+description+",  failingUrl = "+failingUrl+")", Toast.LENGTH_SHORT).show();
}

@Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
    Toast.makeText(MainActivity.this, "onDownloadRequested(url = "+url+",  suggestedFilename = "+suggestedFilename+",  mimeType = "+mimeType+",  contentLength = "+contentLength+",  contentDisposition = "+contentDisposition+",  userAgent = "+userAgent+")", Toast.LENGTH_LONG).show();

    /*if (AdvancedWebView.handleDownload(this, url, suggestedFilename)) {
        // download successfully handled
    }
    else {
        // download couldn't be handled because user has disabled download manager app on the device
    }*/
}
@Override
public void onExternalPageRequest(String url) {
    Toast.makeText(MainActivity.this, "onExternalPageRequest(url = "+url+")", Toast.LENGTH_SHORT).show();
}
</code>```

答:
A WebView has a reload method that you can call. This will reload the current url.

https://developer.android.com/reference/android/webkit/WebView.html#reload()

It is not exactly clear on when you want to refresh but you would need to put this somewhere in your code: mWebView.reload();

ContentLicense: CC BY-SA 3.0

Body:
How do I refresh the contents of a webview?
That's my code THERE IS A WAY to update it? there a way to update the page automatically? thanks a lot

public class MainActivity extends Activity implements AdvancedWebView.Listener {

private static final String TEST_PAGE_URL = "";
private AdvancedWebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mWebView = (AdvancedWebView) findViewById(R.id.webview);
    mWebView.setListener(this, this);
    mWebView.setGeolocationEnabled(false);
    mWebView.setMixedContentAllowed(true);
    mWebView.setCookiesEnabled(true);
    mWebView.setThirdPartyCookiesEnabled(true);
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            Toast.makeText(MainActivity.this, "Finished loading", Toast.LENGTH_SHORT).show();
        }

    });
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Toast.makeText(MainActivity.this, title, Toast.LENGTH_SHORT).show();
        }

    });
    mWebView.addHttpHeader("X-Requested-With", "");
    mWebView.loadUrl("");
}

@SuppressLint("NewApi")
@Override
protected void onResume() {
    super.onResume();
    mWebView.onResume();
    // ...
}

@SuppressLint("NewApi")
@Override
protected void onPause() {
    mWebView.onPause();
    // ...
    super.onPause();
}

@Override
protected void onDestroy() {
    mWebView.onDestroy();
    // ...
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    mWebView.onActivityResult(requestCode, resultCode, intent);
    // ...
}

@Override
public void onBackPressed() {
    if (!mWebView.onBackPressed()) { return; }
    // ...
    super.onBackPressed();
}

@Override
public void onPageStarted(String url, Bitmap favicon) {
    mWebView.setVisibility(View.INVISIBLE);
}

@Override
public void onPageFinished(String url) {
    mWebView.setVisibility(View.VISIBLE);
}

@Override
public void onPageError(int errorCode, String description, String failingUrl) {
    Toast.makeText(MainActivity.this, "onPageError(errorCode = "+errorCode+",  description = "+description+",  failingUrl = "+failingUrl+")", Toast.LENGTH_SHORT).show();
}

@Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
    Toast.makeText(MainActivity.this, "onDownloadRequested(url = "+url+",  suggestedFilename = "+suggestedFilename+",  mimeType = "+mimeType+",  contentLength = "+contentLength+",  contentDisposition = "+contentDisposition+",  userAgent = "+userAgent+")", Toast.LENGTH_LONG).show();

    /*if (AdvancedWebView.handleDownload(this, url, suggestedFilename)) {
        // download successfully handled
    }
    else {
        // download couldn't be handled because user has disabled download manager app on the device
    }*/
}
@Override
public void onExternalPageRequest(String url) {
    Toast.makeText(MainActivity.this, "onExternalPageRequest(url = "+url+")", Toast.LENGTH_SHORT).show();
}


问:
Inserting data into a Postgres table if data is not null
I'm using Postgres's Common Table Expressions, and would - if possible - to insert data into a table if the values in the data is not null:

```<code>WITH prod1 AS (
   INSERT INTO p1 ... RETURNING id),
     prod2 AS (
   INSERT INTO p2 (fk,foo,bar) VALUES (prod1.id,@Foo,@Bar)
     RETURNING id)
</code>```

If the values @Foo and @Bar equate to null, is it possible for postgres to skip the insertion of data into p2 otherwise it'll create a blank reference? Or, do I have to manually check and insert as required via code?

答:
```<code>insert into p2 (fk, foo, bar)
select prod1.id, @foo, @bar
from prod1
where @foo is not null or @bar is not null
</code>```

Body:
I'm using Postgres's Common Table Expressions, and would - if possible - to insert data into a table if the values in the data is not null:

WITH prod1 AS (
   INSERT INTO p1 ... RETURNING id),
     prod2 AS (
   INSERT INTO p2 (fk,foo,bar) VALUES (prod1.id,@Foo,@Bar)
     RETURNING id)

If the values @Foo and @Bar equate to null, is it possible for postgres to skip the insertion of data into p2 otherwise it'll create a blank reference? Or, do I have to manually check and insert as required via code?


问:
Dynamic memory allocation for char***
I was trying to dynamically allocate memory for a char***.

```<code>char*** tas;
</code>```

With char*** i want to describe a table of strings with 2 columns only.

Main problem i had trying to achieve that is not to compile the program but make it run without a segmentation fault.

The issue i think is the not proper use of realloc.
Checking man page of realloc/calloc/malloc

```<code>void *realloc(void *ptr, size_t size);
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
</code>```

I found out that i have to generate the proper size_t vars to send to allocate functions.

The crucial lines of code for this are the following:

```<code>tas         = (char ***)realloc(tas,sizeof(char **)*(i+1));
tas[i]      = (char **)calloc(2,sizeof(char *));
tas[i][0]   = (char *)calloc(lenKey+1,sizeof(char));
tas[i][1]   = (char *)calloc(lenValue+1,sizeof(char));
++i;
</code>```

With tas beeing the char***.

--------EDIT-------

Piece by piece I compiled an answer and i am posting the solution i found to the problem here.

答:
A char*** is like a table of strings.

```<code>      R\C  ||---1-----|----2----|
   |---1---||string11 |string12 |
   |---2---||string21 |string22 |
   |---3---||string31 |string32 |
   | ....  ||  .....     ...... |
   |-(N-1)-||str N-1.1|str N-1.2|
   |---N---||stringN1 |stringN2 |
</code>```

Here is a demo source code with comments in order to understand how to achieve something like that:

```<code>#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void rellocateFunction(size_t lenKey, size_t lenValue);
void firstAllocateFunction(size_t lenKey, size_t lenValue);
int i=0;
char*** tas;

int main(){
    int j=0;
    size_t length1, length2;
    char* stringN1=(char *)malloc(10*sizeof(char));
    char* stringN2=(char *)malloc(10*sizeof(char));
    while(1){
        printf("dragons\n");
        printf("MAIN: Enter string[%d][0]:",j); scanf("%s", stringN1);
        printf("MAIN: Enter string[%d][1]:",j); scanf("%s", stringN2);
        length1 = strlen(stringN1); // You need the length of the string to pass it as an argumnet to allocation functions
        length2 = strlen(stringN2); // Same as above comment
        if(j==0) firstAllocateFunction(length1,length2); // We cant start with the use of realloc. So here you are initiliazing the allocation with calloc only.
        else rellocateFunction(length1,length2); // When we already have entries in the table, we are going to use this function to allocate more memory for the new entries.
        strcpy(tas[j][0],stringN1);  // Population of char*** at row j and col 0
        strcpy(tas[j][1],stringN2);  // Population of char*** at row j and col 1
        j++;
        for (int c=0; c<j; c++) // Print the results
        {
            printf("tas[%d][0]:<%s>\n",c, tas[c][0]);
            printf("tas[%d][1]:<%s>\n",c, tas[c][1]);
        }
    } // Notice the forever ongoing loop... That's to test if the code works. Cancel the execution with ctrl+c
    return 0;
}

void firstAllocateFunction(size_t len1, size_t len2){
tas         = (char ***)calloc(1,sizeof(char **)); //One char*** pointer
tas[i]      = (char **)calloc(2,sizeof(char *));   //pointin to 2 char**
tas[i][0]   = (char *)calloc(len1+1,sizeof(char)); //containing len1+1
tas[i][1]   = (char *)calloc(len2+1,sizeof(char)); //and len2+1 elements of sizeof(char) bytes.
++i;
}

void rellocateFunction(size_t len1, size_t len2){
tas         = (char ***)realloc(tas,sizeof(char **)*(i+1)); //One more char***
tas[i]      = (char **)calloc(2,sizeof(char *));   ////////////////////
tas[i][0]   = (char *)calloc(len1+1,sizeof(char)); // Same as above //
tas[i][1]   = (char *)calloc(len2+1,sizeof(char)); ///////////////////
++i;
}
</code>```

I used calloc, because i wanted to avoid using memset to init the strings. The rest are explained with comments.

Note that you have to allocate your memory for char*** the first time using a different function() than the rest of the times that you will basically reallocating the memory of char***.

Warning. The code above does not implement the free() function (which is highly recommended to. So be careful not to full your memory with dead data.

ContentLicense: CC BY-SA 4.0

Title: Dynamic memory allocation for char***

Body:
I was trying to dynamically allocate memory for a char***.

char*** tas;

With char*** i want to describe a table of strings with 2 columns only.

Main problem i had trying to achieve that is not to compile the program but make it run without a segmentation fault.

The issue i think is the not proper use of realloc.
Checking man page of realloc/calloc/malloc

void *realloc(void *ptr, size_t size);
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);

I found out that i have to generate the proper size_t vars to send to allocate functions.

The crucial lines of code for this are the following:

tas         = (char ***)realloc(tas,sizeof(char **)*(i+1));
tas[i]      = (char **)calloc(2,sizeof(char *));
tas[i][0]   = (char *)calloc(lenKey+1,sizeof(char));
tas[i][1]   = (char *)calloc(lenValue+1,sizeof(char));
++i;

With tas beeing the char***.

--------EDIT-------

Piece by piece I compiled an answer and i am posting the solution i found to the problem here.

Body:
A char*** is like a table of strings.

      R\C  ||---1-----|----2----|
   |---1---||string11 |string12 |
   |---2---||string21 |string22 |
   |---3---||string31 |string32 |
   | ....  ||  .....     ...... |
   |-(N-1)-||str N-1.1|str N-1.2|
   |---N---||stringN1 |stringN2 |

Here is a demo source code with comments in order to understand how to achieve something like that:

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void rellocateFunction(size_t lenKey, size_t lenValue);
void firstAllocateFunction(size_t lenKey, size_t lenValue);
int i=0;
char*** tas;

int main(){
    int j=0;
    size_t length1, length2;
    char* stringN1=(char *)malloc(10*sizeof(char));
    char* stringN2=(char *)malloc(10*sizeof(char));
    while(1){
        printf("dragons\n");
        printf("MAIN: Enter string[%d][0]:",j); scanf("%s", stringN1);
        printf("MAIN: Enter string[%d][1]:",j); scanf("%s", stringN2);
        length1 = strlen(stringN1); // You need the length of the string to pass it as an argumnet to allocation functions
        length2 = strlen(stringN2); // Same as above comment
        if(j==0) firstAllocateFunction(length1,length2); // We cant start with the use of realloc. So here you are initiliazing the allocation with calloc only.
        else rellocateFunction(length1,length2); // When we already have entries in the table, we are going to use this function to allocate more memory for the new entries.
        strcpy(tas[j][0],stringN1);  // Population of char*** at row j and col 0
        strcpy(tas[j][1],stringN2);  // Population of char*** at row j and col 1
        j++;
        for (int c=0; c<j; c++) // Print the results
        {
            printf("tas[%d][0]:<%s>\n",c, tas[c][0]);
            printf("tas[%d][1]:<%s>\n",c, tas[c][1]);
        }
    } // Notice the forever ongoing loop... That's to test if the code works. Cancel the execution with ctrl+c
    return 0;
}

void firstAllocateFunction(size_t len1, size_t len2){
tas         = (char ***)calloc(1,sizeof(char **)); //One char*** pointer
tas[i]      = (char **)calloc(2,sizeof(char *));   //pointin to 2 char**
tas[i][0]   = (char *)calloc(len1+1,sizeof(char)); //containing len1+1
tas[i][1]   = (char *)calloc(len2+1,sizeof(char)); //and len2+1 elements of sizeof(char) bytes.
++i;
}

void rellocateFunction(size_t len1, size_t len2){
tas         = (char ***)realloc(tas,sizeof(char **)*(i+1)); //One more char***
tas[i]      = (char **)calloc(2,sizeof(char *));   ////////////////////
tas[i][0]   = (char *)calloc(len1+1,sizeof(char)); // Same as above //
tas[i][1]   = (char *)calloc(len2+1,sizeof(char)); ///////////////////
++i;
}

I used calloc, because i wanted to avoid using memset to init the strings. The rest are explained with comments.

Note that you have to allocate your memory for char*** the first time using a different function() than the rest of the times that you will basically reallocating the memory of char***.

Warning. The code above does not implement the free() function (which is highly recommended to. So be careful not to full your memory with dead data.


问:
want to hide image when image is not found at the src location?
```<code>jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });
</code>
```

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

答:
The example on the .error() docs show this:

```<code>$("img").error(function(){
  $(this).hide();
});
</code>```

... which is essentially the same as what you're doing. Can you verify that jQuery is loaded and available on the page? Also, if you're using FireFox, Chrome or Safari, try checking your javascript console for errors.

EDIT: Note this also, from the docs:

This event may not be correctly fired when the page is served locally. Since error relies on normal HTTP status codes, it will generally not be triggered if the URL uses the file: protocol.

Are you testing this locally?

Body:
jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

Body:
The example on the .error() docs show this:

$("img").error(function(){
  $(this).hide();
});

... which is essentially the same as what you're doing. Can you verify that jQuery is loaded and available on the page? Also, if you're using FireFox, Chrome or Safari, try checking your javascript console for errors.

EDIT: Note this also, from the docs:

This event may not be correctly fired when the page is served locally. Since error relies on normal HTTP status codes, it will generally not be triggered if the URL uses the file: protocol.

Are you testing this locally?


问:
Modify object in container without pointer: vector vs set
I have access to a factory which produces objects in the following way:

```<code>A a = factory.build();
</code>```

I want to store objects of type A in a container, access them, modify their inner state and the next I access the object via the container I'd like to access the same as object as before (with the modified state).
My first thought was to store pointers to A in a container. However, as given above, the factory does not give me a pointer to an object but the object itself.

Class A:

```<code>class A
{
  private:
    int id;

  public:
    A(int id)
    {
      this->id = id;
    }

    int getId() const
    {
      return id;
    }

    void setId(int id)
    {
      this->id = id;
    }
};
</code>```

I figured out that the following works using vector:

```<code>A obj1(1);

std::vector<A> vec;
vec.push_back(obj1);

A & obj = vec[0];
obj.setId(4);

for(std::vector<A>::iterator itr = vec.begin();itr!=vec.end();itr++)
{
    std::cout << (*itr).getId() << endl;
}
</code>```

This prints the modified id: 4.

Is something similar possible using std::set? I tried the following:

```<code>struct AComp
{
  bool operator()(const A lhs, const A rhs) const
  {
    return (lhs.getId() < rhs.getId());
  }
};
</code>```

and

```<code>A obj2(1);

std::set<A, AComp> mySet;
mySet.insert(obj2);

int id = 1;
auto result = std::find_if(mySet.begin(), mySet.end(), [id](A a) {return a.getId() == id;});

A tmp = *result;
tmp.setId(4);
std::cout << tmp.getId() << endl;

for(std::set<A>::iterator itr = mySet.begin(); itr!=mySet.end();itr++)
{
    std::cout << (*itr).getId() << endl;
}
</code>```

Of course this does not change the state of the object in the set. But here I can't say

```<code>A & tmp = *result;
</code>```

This gives me:

```<code>binding ‘const hallo2::A’ to reference of type ‘hallo2::A&’ discards qualifiers
</code>```

How would I achieve this with a std::set?

答:
You did not provide the the factory class or build method so I have to assume you are referring to the standard patterns.

But, if all you need is a pointer to the object, something like this should do:

Aptr *A;

Aptr aptr = &(factory.build());

Body:
I have access to a factory which produces objects in the following way:

A a = factory.build();

I want to store objects of type A in a container, access them, modify their inner state and the next I access the object via the container I'd like to access the same as object as before (with the modified state).
My first thought was to store pointers to A in a container. However, as given above, the factory does not give me a pointer to an object but the object itself.

Class A:

class A
{
  private:
    int id;

  public:
    A(int id)
    {
      this->id = id;
    }

    int getId() const
    {
      return id;
    }

    void setId(int id)
    {
      this->id = id;
    }
};

I figured out that the following works using vector:

A obj1(1);

std::vector vec;
vec.push_back(obj1);

A & obj = vec[0];
obj.setId(4);

for(std::vector::iterator itr = vec.begin();itr!=vec.end();itr++)
{
    std::cout << (*itr).getId() << endl;
}

This prints the modified id: 4.

Is something similar possible using std::set? I tried the following:

struct AComp
{
  bool operator()(const A lhs, const A rhs) const
  {
    return (lhs.getId() < rhs.getId());
  }
};

and

A obj2(1);

std::set mySet;
mySet.insert(obj2);

int id = 1;
auto result = std::find_if(mySet.begin(), mySet.end(), [id](A a) {return a.getId() == id;});

A tmp = *result;
tmp.setId(4);
std::cout << tmp.getId() << endl;

for(std::set::iterator itr = mySet.begin(); itr!=mySet.end();itr++)
{
    std::cout << (*itr).getId() << endl;
}

Of course this does not change the state of the object in the set. But here I can't say

A & tmp = *result;

This gives me:

binding ‘const hallo2::A’ to reference of type ‘hallo2::A&’ discards qualifiers

How would I achieve this with a std::set?


问:
Incomplete Node HTTP.Response
My application builds a custom array of integers that need to be concatenated in order to create a dynamic request for economic data.

Once my variable options gets created, I push it through an http request and try to parse the response, where I'm getting an error -

```<code>SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
</code>```

When I use my code to read the body, the response cuts off early and I don't get the full response in the console.log().

I've tested the request values and placed the results in my search bar and have yielded positive results.

Any Ideas on why the body on the response gets cut short? I need to read all of the data from this request and when parsing I get errors.

Here is the code -

```<code>var options = {
host: 'api.eve-central.com',
port: 80,
path: '/api/marketstat/json?typeid=18&typeid=19&typeid=20&typeid=21&typeid=22&typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=41&typeid=42&typeid=43&typeid=44&typeid=45&typeid=49&typeid=50&typeid=51&typeid=52&typeid=164&typeid=165&typeid=166&typeid=178&typeid=179&typeid=180&typeid=181&typeid=182&typeid=183&typeid=184&typeid=185&typeid=186&typeid=187&typeid=188&typeid=189&typeid=190&typeid=191&typeid=192&typeid=193&typeid=194&typeid=195&typeid=196&typeid=197&typeid=198&typeid=199&typeid=200&typeid=201&typeid=202&typeid=203&typeid=204&typeid=205&typeid=206&typeid=207&typeid=208&typeid=209&typeid=210&typeid=211&typeid=212&typeid=213&typeid=215&typeid=216&typeid=217&typeid=218&typeid=219&typeid=220&typeid=221&typeid=222&typeid=223&typeid=224&typeid=225&typeid=226&typeid=227&typeid=228&typeid=229&typeid=230&typeid=231&typeid=232&typeid=233&typeid=234&typeid=235&typeid=236&typeid=237&typeid=238&typeid=239&typeid=240&typeid=241&typeid=242&typeid=243&typeid=244&typeid=245&typeid=246&typeid=247&typeid=248&typeid=249&typeid=250&typeid=251&typeid=252&typeid=253&typeid=254&usesystem=30000142',
method: 'GET'
}

function requester(options) {
http.request(options, function (res) {
    //console.log('STATUS: ' + res.statusCode);
    //console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        var payload = JSON.parse(chunk);
        //console.log('After Parse: ' + payload);
        //Separating the payload into three pieces.
        buy = payload[0]["buy"];
        all = payload[0]["all"];
        sell = payload[0]["sell"];
    });
  }).end();
};
</code>```

Edit: Removed variables from the code that would interfere with testing.

答:
You need to accumulate the the data that is streamed before performing a parse since what consitutes a data chunk is determined by the io rate.

Instead store all of the chunked data and then parse it

```<code>var options = {
  host: 'api.eve-central.com',
  port: 80,
  path: '/api/marketstat/json?typeid=18&typeid=19&typeid=20&typeid=21&typeid=22&typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=41&typeid=42&typeid=43&typeid=44&typeid=45&typeid=49&typeid=50&typeid=51&typeid=52&typeid=164&typeid=165&typeid=166&typeid=178&typeid=179&typeid=180&typeid=181&typeid=182&typeid=183&typeid=184&typeid=185&typeid=186&typeid=187&typeid=188&typeid=189&typeid=190&typeid=191&typeid=192&typeid=193&typeid=194&typeid=195&typeid=196&typeid=197&typeid=198&typeid=199&typeid=200&typeid=201&typeid=202&typeid=203&typeid=204&typeid=205&typeid=206&typeid=207&typeid=208&typeid=209&typeid=210&typeid=211&typeid=212&typeid=213&typeid=215&typeid=216&typeid=217&typeid=218&typeid=219&typeid=220&typeid=221&typeid=222&typeid=223&typeid=224&typeid=225&typeid=226&typeid=227&typeid=228&typeid=229&typeid=230&typeid=231&typeid=232&typeid=233&typeid=234&typeid=235&typeid=236&typeid=237&typeid=238&typeid=239&typeid=240&typeid=241&typeid=242&typeid=243&typeid=244&typeid=245&typeid=246&typeid=247&typeid=248&typeid=249&typeid=250&typeid=251&typeid=252&typeid=253&typeid=254&usesystem=30000142',
  method: 'GET'
}

function requester(options) {
    http.request(options, function (res) {
        res.setEncoding('utf8');

        // Build response body in a string
        var resBody = '';

        // Listen for data and add
        res.on('data', function (chunk) {
            resBody += chunk
        });

        res.on('end', function () {
            // Now that the response is done streaming, parse resBody
            var payload = JSON.parse(resBody);

            //Separating the payload into three pieces.
            buy = payload[0]["buy"];
            all = payload[0]["all"];
            sell = payload[0]["sell"];

            itemStats.hiBuy = buy["max"];
            itemStats.loSel = sell["min"];
            itemStats.iskSpread = itemStats.loSel - itemStats.hiBuy; //Adjusted the spread calculation for station trading.
            itemStats.perSpread = itemStats.iskSpread / itemStats.loSel;
            itemStats.buyVol = buy["volume"];
            itemStats.selVol = sell["volume"];
            itemStats.allVol = all["volume"];
            itemStats.buyPerHR = itemStats.buyVol / 24;
            itemStats.selPerHR = itemStats.selVol / 24;

            console.log("Transferred Values" + JSON.stringify(itemStats));
        });
    });
};
</code>```

Title: Incomplete Node HTTP.Response

Body:
My application builds a custom array of integers that need to be concatenated in order to create a dynamic request for economic data.

Once my variable options gets created, I push it through an http request and try to parse the response, where I'm getting an error -

SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)

When I use my code to read the body, the response cuts off early and I don't get the full response in the console.log().

I've tested the request values and placed the results in my search bar and have yielded positive results.

Any Ideas on why the body on the response gets cut short? I need to read all of the data from this request and when parsing I get errors.

Here is the code -

var options = {
host: 'api.eve-central.com',
port: 80,
path: '/api/marketstat/json?typeid=18&typeid=19&typeid=20&typeid=21&typeid=22&typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=41&typeid=42&typeid=43&typeid=44&typeid=45&typeid=49&typeid=50&typeid=51&typeid=52&typeid=164&typeid=165&typeid=166&typeid=178&typeid=179&typeid=180&typeid=181&typeid=182&typeid=183&typeid=184&typeid=185&typeid=186&typeid=187&typeid=188&typeid=189&typeid=190&typeid=191&typeid=192&typeid=193&typeid=194&typeid=195&typeid=196&typeid=197&typeid=198&typeid=199&typeid=200&typeid=201&typeid=202&typeid=203&typeid=204&typeid=205&typeid=206&typeid=207&typeid=208&typeid=209&typeid=210&typeid=211&typeid=212&typeid=213&typeid=215&typeid=216&typeid=217&typeid=218&typeid=219&typeid=220&typeid=221&typeid=222&typeid=223&typeid=224&typeid=225&typeid=226&typeid=227&typeid=228&typeid=229&typeid=230&typeid=231&typeid=232&typeid=233&typeid=234&typeid=235&typeid=236&typeid=237&typeid=238&typeid=239&typeid=240&typeid=241&typeid=242&typeid=243&typeid=244&typeid=245&typeid=246&typeid=247&typeid=248&typeid=249&typeid=250&typeid=251&typeid=252&typeid=253&typeid=254&usesystem=30000142',
method: 'GET'
}

function requester(options) {
http.request(options, function (res) {
    //console.log('STATUS: ' + res.statusCode);
    //console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        var payload = JSON.parse(chunk);
        //console.log('After Parse: ' + payload);
        //Separating the payload into three pieces.
        buy = payload[0]["buy"];
        all = payload[0]["all"];
        sell = payload[0]["sell"];
    });
  }).end();
};

Edit: Removed variables from the code that would interfere with testing.

Body:
You need to accumulate the the data that is streamed before performing a parse since what consitutes a data chunk is determined by the io rate.

Instead store all of the chunked data and then parse it

var options = {
  host: 'api.eve-central.com',
  port: 80,
  path: '/api/marketstat/json?typeid=18&typeid=19&typeid=20&typeid=21&typeid=22&typeid=34&typeid=35&typeid=36&typeid=37&typeid=38&typeid=39&typeid=40&typeid=41&typeid=42&typeid=43&typeid=44&typeid=45&typeid=49&typeid=50&typeid=51&typeid=52&typeid=164&typeid=165&typeid=166&typeid=178&typeid=179&typeid=180&typeid=181&typeid=182&typeid=183&typeid=184&typeid=185&typeid=186&typeid=187&typeid=188&typeid=189&typeid=190&typeid=191&typeid=192&typeid=193&typeid=194&typeid=195&typeid=196&typeid=197&typeid=198&typeid=199&typeid=200&typeid=201&typeid=202&typeid=203&typeid=204&typeid=205&typeid=206&typeid=207&typeid=208&typeid=209&typeid=210&typeid=211&typeid=212&typeid=213&typeid=215&typeid=216&typeid=217&typeid=218&typeid=219&typeid=220&typeid=221&typeid=222&typeid=223&typeid=224&typeid=225&typeid=226&typeid=227&typeid=228&typeid=229&typeid=230&typeid=231&typeid=232&typeid=233&typeid=234&typeid=235&typeid=236&typeid=237&typeid=238&typeid=239&typeid=240&typeid=241&typeid=242&typeid=243&typeid=244&typeid=245&typeid=246&typeid=247&typeid=248&typeid=249&typeid=250&typeid=251&typeid=252&typeid=253&typeid=254&usesystem=30000142',
  method: 'GET'
}

function requester(options) {
    http.request(options, function (res) {
        res.setEncoding('utf8');

        // Build response body in a string
        var resBody = '';

        // Listen for data and add
        res.on('data', function (chunk) {
            resBody += chunk
        });

        res.on('end', function () {
            // Now that the response is done streaming, parse resBody
            var payload = JSON.parse(resBody);

            //Separating the payload into three pieces.
            buy = payload[0]["buy"];
            all = payload[0]["all"];
            sell = payload[0]["sell"];

            itemStats.hiBuy = buy["max"];
            itemStats.loSel = sell["min"];
            itemStats.iskSpread = itemStats.loSel - itemStats.hiBuy; //Adjusted the spread calculation for station trading.
            itemStats.perSpread = itemStats.iskSpread / itemStats.loSel;
            itemStats.buyVol = buy["volume"];
            itemStats.selVol = sell["volume"];
            itemStats.allVol = all["volume"];
            itemStats.buyPerHR = itemStats.buyVol / 24;
            itemStats.selPerHR = itemStats.selVol / 24;

            console.log("Transferred Values" + JSON.stringify(itemStats));
        });
    });
};


答:
You are parsing a single chunk, you need to read all chunks before parsing the data:</p>

```<code>let data = '';
res.on('data', function (chunk) {
  data += chunk;
});
res.on('end', function() {
  let payload = JSON.parse(data);
});
</code>```

Title: Incomplete Node HTTP.Response

Body:
You are parsing a single chunk, you need to read all chunks before parsing the data:

let data = '';
res.on('data', function (chunk) {
  data += chunk;
});
res.on('end', function() {
  let payload = JSON.parse(data);
});


问:
Navigation Title is not well aligned and the navbar is a bit too thick?
For some reason the title is not properly aligned and the navbar is too thick?
How will I be able to let it show properly aligned and smaller size?

I am sure it can be done using Bootstrap itself, without additional css, right?

Sorry, I can't post the image directly here, need higher reputation.

Screenshot of the navbar

{% load static %}

<!DOCTYPE html>

    <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">

    <link href="http://157.97.56.42:8000/static/css/bootstrap.css" rel="stylesheet"/>

    {% block base.head %}
    {% endblock %}

    {% block base.header %}

            Developity

Home

Projects

    {% endblock %}

    {% block base.body %}
    {% endblock %}

    {% block base.footer %}
    {% endblock %}

```

答:
Removing the navbar-text class will remove the margin from the links making the navbar smaller and everything aligned.

```<code><nav class="navbar navbar-inverse" role="navigation">
  <span class="navbar-brand">Developity</span>
  <ul class="nav navbar-nav">
    <li><a href="/index">Home</a></li>
    <li><a href="/projects">Projects</a></li>
  </ul>
</nav>
</code>```

Or you can add navbar-text to the navbar-brand to give it the same margins as the links.

```<code><nav class="navbar navbar-inverse" role="navigation">
  <span class="navbar-brand navbar-text">Developity</span>
  <ul class="nav navbar-nav">
    <li><a href="/index" class="navbar-text">Home</a></li>
    <li><a href="/projects" class="navbar-text">Projects</a></li>
  </ul>
</nav>
</code>```

Both shown here http://codepen.io/anon/pen/RpvYba

Body:
Removing the navbar-text class will remove the margin from the links making the navbar smaller and everything aligned.

<nav class="navbar navbar-inverse" role="navigation">
  <span class="navbar-brand">Developity</span>
  <ul class="nav navbar-nav">
    <li><a href="/index">Home</a></li>
    <li><a href="/projects">Projects</a></li>
  </ul>
</nav>

Or you can add navbar-text to the navbar-brand to give it the same margins as the links.

<nav class="navbar navbar-inverse" role="navigation">
  <span class="navbar-brand navbar-text">Developity</span>
  <ul class="nav navbar-nav">
    <li><a href="/index" class="navbar-text">Home</a></li>
    <li><a href="/projects" class="navbar-text">Projects</a></li>
  </ul>
</nav>

Both shown here http://codepen.io/anon/pen/RpvYba


问:
How do I pass an std::string to a function that expects char*?

Possible Duplicate:

  Can I get a non-const C string back from a C++ string?

Do I need to convert it first? I saw in another post that .c_str() can be used if the function expected const char*. What about for just char*?

答:
There is no way to get a char* from a string that is guaranteed to work on all platforms, for the simple fact that string is not required to use contiguous storage.

Your safest, most portable course of action is to copy the string somewhere that does use contigious storage (a vector perhaps), and use that instead.

```<code>vector<char> chars(my_string.begin(), my_string.end());
char* ptr = &chars[0];
</code>```

If you want to be hacky and non-portable and decidedly unsafe, you can confirm that your string implementation does in fact use contigious storage, and then maybe use this:

```<code>&my_str[0]
</code>```

But I would punch any developer that worked for me that did this.

EDIT:

I've been made aware that there are currently no known STL implementations that do not store the string data in a contiguous array, which would make &my_str[0] safe.  It is also true (and I was asked to state this) that in the upcoming C++0x standard, it will be required for the storage to be contiguous.

It's been suggested that because if these facts that my post is factually incorrect.

Decide for yourself, but I say no.  This is not in the current C++ standard, and so it is not required.  I will still in practice do things the way I have suggested, and in any code review I will flag any code that assumes the underlying storage is contigious.

Consider this.  Suppose there were a question about vtable pointers.  Someone wants to examing a class and get the pointer to a virtual function by looking at the vtable.  I would immediately tell them not to do this because there is no mention of how virtual methods are implemented in C++.  Every implementation I know uses vtables, and I can't think of a better way to do it.  It is likely that polymorphism will forever be implemented using vtables.  Does that make it ok to examing the vtable directly?

IMO no, because this depends on undocumented implementation details.  You have no control over this, and it could change at any time.  Even if you expect it will never change, it is still bad engineering to rely on these implementation details.

Decide for yourself.

Body:
There is no way to get a char* from a string that is guaranteed to work on all platforms, for the simple fact that string is not required to use contiguous storage.

Your safest, most portable course of action is to copy the string somewhere that does use contigious storage (a vector perhaps), and use that instead.

vector<char> chars(my_string.begin(), my_string.end());
char* ptr = &chars[0];

If you want to be hacky and non-portable and decidedly unsafe, you can confirm that your string implementation does in fact use contigious storage, and then maybe use this:

&my_str[0]

But I would punch any developer that worked for me that did this.

EDIT:

I've been made aware that there are currently no known STL implementations that do not store the string data in a contiguous array, which would make &my_str[0] safe.  It is also true (and I was asked to state this) that in the upcoming C++0x standard, it will be required for the storage to be contiguous.

It's been suggested that because if these facts that my post is factually incorrect.

Decide for yourself, but I say no.  This is not in the current C++ standard, and so it is not required.  I will still in practice do things the way I have suggested, and in any code review I will flag any code that assumes the underlying storage is contigious.

Consider this.  Suppose there were a question about vtable pointers.  Someone wants to examing a class and get the pointer to a virtual function by looking at the vtable.  I would immediately tell them not to do this because there is no mention of how virtual methods are implemented in C++.  Every implementation I know uses vtables, and I can't think of a better way to do it.  It is likely that polymorphism will forever be implemented using vtables.  Does that make it ok to examing the vtable directly?

IMO no, because this depends on undocumented implementation details.  You have no control over this, and it could change at any time.  Even if you expect it will never change, it is still bad engineering to rely on these implementation details.

Decide for yourself.


问:
What kind of numerical method does 'pdepe' (MATLAB function's) use?
I'm using the MATLAB's function 'pdepe' to solve a problem with some partial differential equations, a parabolic one.

I need to know the kind of numerical method that function uses, 'cause I have to notify this in a report.

The description of the function in MathWorks is "Solve initial-boundary value problems for systems of parabolic and elliptic PDEs in one space variable and time". Is it a finite difference method?

Thanks for helping me.

答:
Taken from the Matlab 2016b documentation for pdepe:

The time integration is done with ode15s. pdepe exploits the
  capabilities of ode15s for solving the differential-algebraic
  equations that arise when Equation 1-3 contains elliptic equations,
  and for handling Jacobians with a specified sparsity pattern.

Also, from the ode15s documentation:

ode15s is a variable-step, variable-order (VSVO) solver based on the
  numerical differentiation formulas (NDFs) of orders 1 to 5.
  Optionally, it can use the backward differentiation formulas (BDFs,
  also known as Gear's method) that are usually less efficient


问:
SHA 256 With Indy
I am trying to use the SHA-256 encryption function, but with no success.

I need to get a hash of a string and a file.
I'm using Delphi 10.1 Berlin, and Indy for Hash.

My code:

```<code>uses System.Classes, IdHashSha, System.SysUtils;

function GetHashF(_filename: string): string;
  var
   sha: TIdHashSHA256;
   fs: TFileStream;
  begin
   if TIdHashSHA256.IsAvailable then
    begin
     sha:= TIdHashSHA256.Create;
     try
      fs:= TFileStream.Create(_filename, fmOpenRead);
      try
       Result:= sha.HashStreamAsHex(fs);
      finally
       sha.Free;
      end;
     finally
      fs.Free;
     end;
    end;

 function GetHashS(_string: string): string;
  var
   sha: TIdHashSHA256;
  begin
   if TIdHashSHA256.IsAvailable then
    begin
     sha:= TIdHashSHA256.Create;
     try
      Result:= sha.HashStringAsHex(_string);
     finally
      sha.Free;
     end;
    end;
  end;
</code>```

But whenever I do this, it returns a clean string ("") for both function.

I used the breakpoint to check if it is passing from IsAvaible, and it is not.
  What is going on?

答:
At this time, Indy only implements a few hashing algorithms natively, but that does not include SHA-256 (I have created a ticket for that feature).

For algorithms not implemented natively, Indy allows you to hook in an external hashing implementation of your choosing to provide the actual hash functionality.  You are seeing IsAvailable return false because you have not done that hookup yet.

You can use any hash implementation you want, as long as you assign appropriate wrapper functions to the following callbacks in the IdFIPS unit:

```<code>IsHashingIntfAvail
UpdateHashInst
FinalHashInst
</code>```

And for SHA-256 specifically, also:

```<code>GetSHA256HashInst
IsSHA256HashIntfAvail
</code>```

By default, Indy can use OpenSSL as a hashing library:

add the IdSSLOpenSSLHeaders unit to your uses clause

call IdSSLOpenSSLHeaders.Load() at runtime

deploy the OpenSSL binaries with your app executable.

IdSSLOpenSSLHeaders.pas hooks up relevant OpenSSL functions for the IdFIPS callbacks.

Title: SHA 256 With Indy

Body:
I am trying to use the SHA-256 encryption function, but with no success.

I need to get a hash of a string and a file.
I'm using Delphi 10.1 Berlin, and Indy for Hash.

My code:

uses System.Classes, IdHashSha, System.SysUtils;

function GetHashF(_filename: string): string;
  var
   sha: TIdHashSHA256;
   fs: TFileStream;
  begin
   if TIdHashSHA256.IsAvailable then
    begin
     sha:= TIdHashSHA256.Create;
     try
      fs:= TFileStream.Create(_filename, fmOpenRead);
      try
       Result:= sha.HashStreamAsHex(fs);
      finally
       sha.Free;
      end;
     finally
      fs.Free;
     end;
    end;

 function GetHashS(_string: string): string;
  var
   sha: TIdHashSHA256;
  begin
   if TIdHashSHA256.IsAvailable then
    begin
     sha:= TIdHashSHA256.Create;
     try
      Result:= sha.HashStringAsHex(_string);
     finally
      sha.Free;
     end;
    end;
  end;

But whenever I do this, it returns a clean string ("") for both function.

I used the breakpoint to check if it is passing from IsAvaible, and it is not.
  What is going on?

Body:
At this time, Indy only implements a few hashing algorithms natively, but that does not include SHA-256 (I have created a ticket for that feature).

For algorithms not implemented natively, Indy allows you to hook in an external hashing implementation of your choosing to provide the actual hash functionality.  You are seeing IsAvailable return false because you have not done that hookup yet.

You can use any hash implementation you want, as long as you assign appropriate wrapper functions to the following callbacks in the IdFIPS unit:

IsHashingIntfAvail
UpdateHashInst
FinalHashInst

And for SHA-256 specifically, also:

GetSHA256HashInst
IsSHA256HashIntfAvail

By default, Indy can use OpenSSL as a hashing library:

add the IdSSLOpenSSLHeaders unit to your uses clause

call IdSSLOpenSSLHeaders.Load() at runtime

deploy the OpenSSL binaries with your app executable.

IdSSLOpenSSLHeaders.pas hooks up relevant OpenSSL functions for the IdFIPS callbacks.


问:
Where to add CPU Instructions Installing Tensorflow From Source?
I am trying to install Tensorflow from source because of a warning about CPU instructions (SSE, AVX...) not being installed when I installed with pip AND virtualenv:

W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.

So I'm trying to install Tensorflow from source so that these instructions can be compiled with Tensorflow.

Do I need to do anything aside from the instructions on the Tensorflow website to compile with these instructions? (./configure?)

If so, what do I need to do and how exactly do I do it?

In the installation when I have to install the pip package, the Tensorflow website says that for Linux, the command is :
sudo pip install /tmp/tensorflow_pkg/tensorflow-1.0.1-py2-none-any.whlit says that this command will differ based on the machine, what is the equivalent command for MacOS? How do I go about the Bazel wheelsteps?

Side Note: I've been told that there are a few ways I could do this with Bazel, but being unexperienced with Bazel and not too experienced on Terminal, I need clear steps on what to do?

OS Sierra (10.12.2)

答:
For your question number one (and two), the default for ./configure will provide you with the instruction set optimized for your machine. This is done through the default compiler option, -march=native. Just follow the steps here

For number three, once you have generated the whl file in /tmp/tensorflow_pkg (or where ever), then look at the name of the file in that directory. It will be similar to but different than the linux example given in the instructions. You should then be able to install it usingpip install /tmp/tensorflow_pkg/YOUR_FILENAME.whl. If you have any problems you can follow steps here but using /tmp/tensorflow_pkg/YOUR_FILENAME.whl instead of tensorflow or tensorflow-gpu

Good luck.


问:
Countdown HIIT timer Restarting timer
I am making a countdown timer in the fashion of a HIIT timer with an 'active' and 'rest' period that will repeat any number of times. I have the two timers running, but in my loop to restart the timers, when I call this.start it starts both timers.

When I click on this.start in Android studio, it highlights both .start() calls, I want to to only start the .start above 'intervals--'

How can I start only the first one again?

```<code>    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);
    minutesText = (EditText) findViewById(R.id.minutesText);
    secondsText = (EditText) findViewById(R.id.secondsText);
    startButton = (Button) findViewById(R.id.startButton);
    intervalCount = (EditText) findViewById(R.id.intervalCount);

    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (minutesText.getText().toString().equals("")) {
                minutesInt = 0;
            } else {
                minutesString = minutesText.getText().toString();
                minutesInt = Integer.parseInt(minutesString);

            }

            secondsString = secondsText.getText().toString();
            if (secondsText.getText().toString().equals("")) {
                secondsInt = 0;

            } else {
                secondsString = secondsText.getText().toString();
                secondsInt = Integer.parseInt(secondsString);

            }
            if (intervalCount.getText().toString().equals("")) {
                intervals = 0;
            } else {
                intervalsString = intervalCount.getText().toString();
                intervals = Integer.parseInt(intervalsString);
            }

            final int timerAmount = ((minutesInt * 60) + (secondsInt)) * 1000;

                Log.i("Hello, ", "intervals are " + intervals);
                new CountDownTimer(timerAmount, 1000) {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    public void onTick(long millisUntilFinished) {
                        activeRunning = true;
                        String timeLeft = String.format("%02d : %02d",
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                        );
                        textView.setText("Reamining: " + timeLeft);
                    }

                    public void onFinish() {

                        textView.setText("FINISHED1");

                        try {
                            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                            r.play();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        new CountDownTimer(5000, 1000) {
                            public void onTick(long millisUntilFinished) {
                                restRunning = true;
                                activeRunning = false;
                                String timeLeft = String.format("%02d : %02d",
                                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                                );
                                textView.setText("Rest: " + timeLeft);
                            }
                            public void onFinish() {
                                restRunning = false;

                                textView.setText("FINISHED2");
                                try {
                                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                    r.play();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }.start();

                            if (intervals > 0) {
                                intervals--;
                                this.start();
                            }
                    }
                }.start();
                    intervals--;

            }

    });

}

    }
</code>```

答: Is the second timer nested in the brackets of the first? That could be the reason...</p>

Title: Countdown HIIT timer Restarting timer

Body:
I am making a countdown timer in the fashion of a HIIT timer with an 'active' and 'rest' period that will repeat any number of times. I have the two timers running, but in my loop to restart the timers, when I call this.start it starts both timers.

When I click on this.start in Android studio, it highlights both .start() calls, I want to to only start the .start above 'intervals--'

How can I start only the first one again?

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);
    minutesText = (EditText) findViewById(R.id.minutesText);
    secondsText = (EditText) findViewById(R.id.secondsText);
    startButton = (Button) findViewById(R.id.startButton);
    intervalCount = (EditText) findViewById(R.id.intervalCount);

    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (minutesText.getText().toString().equals("")) {
                minutesInt = 0;
            } else {
                minutesString = minutesText.getText().toString();
                minutesInt = Integer.parseInt(minutesString);

            }

            secondsString = secondsText.getText().toString();
            if (secondsText.getText().toString().equals("")) {
                secondsInt = 0;

            } else {
                secondsString = secondsText.getText().toString();
                secondsInt = Integer.parseInt(secondsString);

            }
            if (intervalCount.getText().toString().equals("")) {
                intervals = 0;
            } else {
                intervalsString = intervalCount.getText().toString();
                intervals = Integer.parseInt(intervalsString);
            }

            final int timerAmount = ((minutesInt * 60) + (secondsInt)) * 1000;

                Log.i("Hello, ", "intervals are " + intervals);
                new CountDownTimer(timerAmount, 1000) {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    public void onTick(long millisUntilFinished) {
                        activeRunning = true;
                        String timeLeft = String.format("%02d : %02d",
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                        );
                        textView.setText("Reamining: " + timeLeft);
                    }

                    public void onFinish() {

                        textView.setText("FINISHED1");

                        try {
                            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                            r.play();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        new CountDownTimer(5000, 1000) {
                            public void onTick(long millisUntilFinished) {
                                restRunning = true;
                                activeRunning = false;
                                String timeLeft = String.format("%02d : %02d",
                                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                                );
                                textView.setText("Rest: " + timeLeft);
                            }
                            public void onFinish() {
                                restRunning = false;

                                textView.setText("FINISHED2");
                                try {
                                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                                    r.play();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        }.start();

                            if (intervals > 0) {
                                intervals--;
                                this.start();
                            }
                    }
                }.start();
                    intervals--;

            }

    });

}

    }


问:
How can I find out if getDate() is between 2 time(7) timestamps?
I have an application that sends alerts if the temperature exceeds limits, but I only want to send alerts if it happens at certain times of the day.  I'm using time(7) datatype to store those times.  I need it to be flexible enough to cross midnight, so I could have the following times:

```<code>time_on   time_off
08:00:00  17:00:00
00:00:00  12:00:00
21:00:00  09:00:00
</code>```

How can I figure out if CONVERT(time(7), getdate()) is between any of those combinations?

答:
You can do:

```<code>select a.*
from alerttimes a
where (time_on <= time_off and cast(getdate() as time) >= time_on and cast(getdate() as time) < time_off) or
      (time_on > time_off and cast(getdate() as time) <= time_on and cast(getdate() as time) >= time_off);
</code>```

This handles the issue with your table, which is that some period include midnight.

Body:
I have an application that sends alerts if the temperature exceeds limits, but I only want to send alerts if it happens at certain times of the day.  I'm using time(7) datatype to store those times.  I need it to be flexible enough to cross midnight, so I could have the following times:

time_on   time_off
08:00:00  17:00:00
00:00:00  12:00:00
21:00:00  09:00:00

How can I figure out if CONVERT(time(7), getdate()) is between any of those combinations?

Body:
You can do:

select a.*
from alerttimes a
where (time_on <= time_off and cast(getdate() as time) >= time_on and cast(getdate() as time) < time_off) or
      (time_on > time_off and cast(getdate() as time) <= time_on and cast(getdate() as time) >= time_off);

This handles the issue with your table, which is that some period include midnight.


问:
DDoS attack mitigation on Azure infrastructure
I have a Django based web application hosted on Azure provisioned virtual machines (Ubuntu OS). My application recently experienced a DDoS attack and we were helpless against it.

The problem is that once traffic hits the server - even if it's blocked at a firewall or throttled in my webserver - the traffic is already consuming my network bandwidth. I can do nothing about it. This needs to be blocked "upstream", in the routing gear servicing my server.

Is there any DDoS protection Azure can offer me? Or at the very least, make recommendations as to how I might deploy my application so that it's more resistant to these attacks? Please advise.

答:
First: Azure allows for IP-whitelisting (or blacklisting), so you can add malicious IP addresses to your block-list on incoming traffic (port 80/443 for instance). And you can modify IP addresses / ranges programmatically. This should prevent traffic from hitting your web app. Note: This is specific to Azure Virtual Machines, which you're using.

Second: Azure provides the Azure Security Center, which is designed to detect such things as DoS attacks, intrusion attacks, etc. Not that it solves your problem, but it can be used for alerting you to issues.


问:
nonexhaustive binding failure in sml code
I'm supposed to right a function less(e, L) int * int list -> int list that returns a list of all the elements in L that are smaller then e. I wrote this:

```<code>    fun less(_, nil) = nil
      | less(e, L) =
        let
           val x::xs = less (e, tl L)
        in
           if e > hd L then hd L::x::xs
           else nil @ x::xs
        end;
</code>```

I'm getting a binding failure, surely in the let in bit. I tried a lot of different thinfs already, and I can't figure out why this is wrong. Can anyone shed a light?

答:
```<code>val x::xs = less (e, tl L)
</code>```

This does not match the case where the result of less (e, t1 L) is the empty list.

A correct implementation of the function is this:

```<code>fun less (_, nil) = nil
  | less (y, x::xs) =
    let
       val xs' = less (y, xs)
    in
      if x < y then x::xs' else xs'
</code>```

Body:
I'm supposed to right a function less(e, L) int * int list -> int list that returns a list of all the elements in L that are smaller then e. I wrote this:

    fun less(_, nil) = nil
      | less(e, L) =
        let
           val x::xs = less (e, tl L)
        in
           if e > hd L then hd L::x::xs
           else nil @ x::xs
        end;

I'm getting a binding failure, surely in the let in bit. I tried a lot of different thinfs already, and I can't figure out why this is wrong. Can anyone shed a light?

Body:
val x::xs = less (e, tl L)

This does not match the case where the result of less (e, t1 L) is the empty list.

A correct implementation of the function is this:

fun less (_, nil) = nil
  | less (y, x::xs) =
    let
       val xs' = less (y, xs)
    in
      if x < y then x::xs' else xs'


问:
If the difference between 2 numbers is between 1 and 100 it should run an if statement
I'm not sure why the if statement saying the "numbers are close" is not running?

I've tested it with numbers to create a difference between 1-100.

Any ideas?

```<code>#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    double num1, num2, difference;

    while(num1 != 100 || num2 != 200)
    {
        cout << "Enter a number:" << endl ;
        cin >> num1 ;
        cout << "Enter a 2nd number: " << endl ;
        cin >> num2 ;
        if (num1 == num2)
            { cout << "the numbers are equal" << endl ;
            }
        else if (num1 > num2)
        {   cout << "The larger number is num1:" << num1 << endl ;
            cout << "The smaller number is num2:" <<num2 << endl;
            difference = num1- num2;
           if (difference <100 && difference > 1)
            {
            cout << "Numbers are almost equal\n" ;
            }
            else
            {}
        }
    else if (num2 - num1)
        {   cout << "The larger number is num2:" << num2 << endl ;
            cout << "The smaller number is num1:" <<num1 << endl;
        }

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

Kind regards,

答:
Instead of

```<code>difference = num1- num2;
</code>```

you need

```<code>difference = fabs(num1- num2);
</code>```

Otherwise, the test for "closeness" will work only when num1 is greater than num2.

Also make sure that num1 and num2 are initialized before the while loop.

```<code>double num1 = 0;
double num2 = 0;
double difference = 0;  // Just for consistency

while ( ... )
{
   ...
}
</code>```

Body:
I'm not sure why the if statement saying the "numbers are close" is not running?

I've tested it with numbers to create a difference between 1-100.

Any ideas?

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    double num1, num2, difference;

    while(num1 != 100 || num2 != 200)
    {
        cout << "Enter a number:" << endl ;
        cin >> num1 ;
        cout << "Enter a 2nd number: " << endl ;
        cin >> num2 ;
        if (num1 == num2)
            { cout << "the numbers are equal" << endl ;
            }
        else if (num1 > num2)
        {   cout << "The larger number is num1:" << num1 << endl ;
            cout << "The smaller number is num2:" <<num2 << endl;
            difference = num1- num2;
           if (difference <100 && difference > 1)
            {
            cout << "Numbers are almost equal\n" ;
            }
            else
            {}
        }
    else if (num2 - num1)
        {   cout << "The larger number is num2:" << num2 << endl ;
            cout << "The smaller number is num1:" <<num1 << endl;
        }

    }
    return 0;
}

Kind regards,

Body:
Instead of

difference = num1- num2;

you need

difference = fabs(num1- num2);

Otherwise, the test for "closeness" will work only when num1 is greater than num2.

Also make sure that num1 and num2 are initialized before the while loop.

double num1 = 0;
double num2 = 0;
double difference = 0;  // Just for consistency

while ( ... )
{
   ...
}


问:
Anonymous users in Rails -- security considerations?
I'm looking at implementing some form of anonymous user system in Rails. I need to let people do things (creating records, looking at what they've created, etc), without actually creating an account. Once they create an account, everything persists without risk of losing it by clearing cookies or something.

Right now, I'm thinking it's pretty straightforward. Have an is_anonymous field in the User model, and use something like this to access the currently logged in user:

```<code>def find_user
  session[:user_id] ||= create_new_anonymous_user.id
end
</code>```

Assuming the session persists for some reasonable period of time, and the session cookie doesn't expire, that should keep everything running smoothly.

However, there is this piece of me that is convinced that I'm missing something security-related. Has anyone done something like this before? Am I missing something super-obvious?

Thanks!

答:
Are you sure that you want to let people create objects that are tied to accounts that may not exist?  Unfortunately I don't know much about what your application is actually doing but I would think that going down this path might leave you with a bunch of orphaned objects not really "owned" by any real users.

If you really do want to do this I think what you have is decent.  You could be creating a real user, flagged as "guest" (or whatever) and once the user wants to really register they are prompted for other information and unflagged.  You should add access control for guest vs non-guest, etc.

OwnerDisplayName: Tim Sullivan

Body:
I'm looking at implementing some form of anonymous user system in Rails. I need to let people do things (creating records, looking at what they've created, etc), without actually creating an account. Once they create an account, everything persists without risk of losing it by clearing cookies or something.

Right now, I'm thinking it's pretty straightforward. Have an is_anonymous field in the User model, and use something like this to access the currently logged in user:

def find_user
  session[:user_id] ||= create_new_anonymous_user.id
end

Assuming the session persists for some reasonable period of time, and the session cookie doesn't expire, that should keep everything running smoothly.

However, there is this piece of me that is convinced that I'm missing something security-related. Has anyone done something like this before? Am I missing something super-obvious?

Thanks!

OwnerDisplayName: revolutiontrigger


问:
Java JFrame/Swing alignment
I'm new and learning JFrame currently and I'm running into a problem with the alignment of my ComboBox, checkboxes and buttons. The listeners are not hooked up yet and this is just a test to see if it's aligned properly. My question is why doesn't the alignment function seem to be working? I want the combo box to be at the top the checkboxes in the middle and the buttons on the bottom.

```<code>import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;

public class CheckBoxFrame extends JFrame
{

private final JComboBox<String> colorComboBox;
private final JCheckBox backgroundColorCheckBox;
private final JCheckBox foregroundColorCheckBox;
private final JButton okButton;
private final JButton cancelButton;

private static final String[] color =
{"Red", "Blue", "Green", "Purple"};

public CheckBoxFrame()
{
  super("ColorSelect");
  setLayout(new FlowLayout());

  colorComboBox = new JComboBox<String>(color);
  colorComboBox.setAlignmentX(SwingConstants.TOP);
  add(colorComboBox);

  backgroundColorCheckBox = new JCheckBox("Background");
  foregroundColorCheckBox = new JCheckBox("Foreground");
  foregroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  backgroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  add(backgroundColorCheckBox); // add bold checkbox to JFrame
  add(foregroundColorCheckBox); // add italic checkbox to JFrame

  okButton = new JButton("Ok");
  cancelButton = new JButton("Cancel");
  okButton.setVerticalAlignment(SwingConstants.BOTTOM);
  cancelButton.setVerticalAlignment(SwingConstants.BOTTOM);
  add(okButton);
  add(cancelButton);

  // register listeners for JCheckBoxes
  CheckBoxHandler handler = new CheckBoxHandler();
  backgroundColorCheckBox.addItemListener(handler);
  foregroundColorCheckBox.addItemListener(handler);
  }

private class CheckBoxHandler implements ItemListener
{
  // respond to checkbox events
  @Override
  public void itemStateChanged(ItemEvent event)
  {

  }
 }
} // end class CheckBoxFrame
</code>```

答:
From the JavaDocs for setVerticalAlignment

Sets the vertical alignment of the icon and text.

This changes the way in which the icon and text properties are laid out WITHIN the context of the component.

setVerticalAlignment won't affect how the component is laid out in the container.

To change the way components are laid out in the container, you will need to change the layout manager, see Lesson: Laying Out Components Within a Container

Based on your requirements, there are number of ways you might achieve it.

You could use a GridLayout, which all the components for an individual row wrapped in their own JPanel and this panel added to the primary container.

You could also use a GridBagLayout, which, while more complex, is also more flexible

Title: Java JFrame/Swing alignment

Body:
I'm new and learning JFrame currently and I'm running into a problem with the alignment of my ComboBox, checkboxes and buttons. The listeners are not hooked up yet and this is just a test to see if it's aligned properly. My question is why doesn't the alignment function seem to be working? I want the combo box to be at the top the checkboxes in the middle and the buttons on the bottom.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;

public class CheckBoxFrame extends JFrame
{

private final JComboBox<String> colorComboBox;
private final JCheckBox backgroundColorCheckBox;
private final JCheckBox foregroundColorCheckBox;
private final JButton okButton;
private final JButton cancelButton;

private static final String[] color =
{"Red", "Blue", "Green", "Purple"};

public CheckBoxFrame()
{
  super("ColorSelect");
  setLayout(new FlowLayout());

  colorComboBox = new JComboBox<String>(color);
  colorComboBox.setAlignmentX(SwingConstants.TOP);
  add(colorComboBox);

  backgroundColorCheckBox = new JCheckBox("Background");
  foregroundColorCheckBox = new JCheckBox("Foreground");
  foregroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  backgroundColorCheckBox.setVerticalAlignment(SwingConstants.CENTER);
  add(backgroundColorCheckBox); // add bold checkbox to JFrame
  add(foregroundColorCheckBox); // add italic checkbox to JFrame

  okButton = new JButton("Ok");
  cancelButton = new JButton("Cancel");
  okButton.setVerticalAlignment(SwingConstants.BOTTOM);
  cancelButton.setVerticalAlignment(SwingConstants.BOTTOM);
  add(okButton);
  add(cancelButton);

  // register listeners for JCheckBoxes
  CheckBoxHandler handler = new CheckBoxHandler();
  backgroundColorCheckBox.addItemListener(handler);
  foregroundColorCheckBox.addItemListener(handler);
  }

private class CheckBoxHandler implements ItemListener
{
  // respond to checkbox events
  @Override
  public void itemStateChanged(ItemEvent event)
  {

  }
 }
} // end class CheckBoxFrame


问:
Big O Notation - O(nlog(n)) vs O(log(n^2))
Is the notation of NLog(N) the same as Log(N^2)? If so, why is it not written like that?

Is NLog(N) the standard notation? I feel like Log(N^2) is less confusing to see.

答: Nlog(N) = log(N^N) so no and as pointed out by zerkms  above log(N^2) = 2log(N)</p>


问:
postgresql limit the number of foreign key available for a given table
Here the situation, I am setting up a database using postgresql. In my database I have a league and a number of team associated with the league how can I set a minimum number of team that can be associated with a particular league ?</p>

答:
You would not set this up as a constraint.  Instead, you could set this up as a flag at the league level.  The flag would specify if there are enough teams for the league to be active.

One way to maintain the flag is to use a trigger to update the value every time a team is inserted, deleted, or updated in a way that changes the league.


答:
Adding logarithms is the same as multiplying numbers, so log(n*n) becomes log(n) + log(n) = 2 log(n).

n log(n) is close to linear. The first n is the important part, as the rest of it grows rather slowly.

For example merge sort has n log n time complexity, because if you think of the merging as a tree, then the tree is log(n) levels tall, and on each level all n elements are processed.

Title: Big O Notation - O(nlog(n)) vs O(log(n^2))

Body:
Is the notation of NLog(N) the same as Log(N^2)? If so, why is it not written like that?

Is NLog(N) the standard notation? I feel like Log(N^2) is less confusing to see.


问:
DBSCAN Remove Noise from Plot
Using DBSCAN,

```<code>(DBSCAN(eps=epsilon, min_samples=10, algorithm='ball_tree', metric='haversine')
</code>```

I have clustered a list of latitude and longitude pairs, for which I then plotted using matplotlib. When plotting, it includes the "noise" coordinates, which are the points that are not assigned to one of the 270 clusters created. I would like to remove the noise from the plot, and just plot the clusters meeting the requirements specified, but I'm not sure how to do so. How might I go about excluding the noise (again, those points not assigned to a cluster)?

Below is the code I have used to cluster and plot:

```<code>df = pd.read_csv('xxx.csv')

# define the number of kilometers in one radiation
# which will be used to convert esp from km to radiation
kms_per_rad = 6371.0088

# define a function to calculate the geographic coordinate
# centroid of a cluster of geographic points
# it will be used later to calculate the centroids of DBSCAN cluster
# because Scikit-learn DBSCAN cluster class does not come with centroid attribute.
def get_centroid(cluster):
"""calculate the centroid of a cluster of geographic coordinate points
Args:
  cluster coordinates, nx2 array-like (array, list of lists, etc)
  n is the number of points(latitude, longitude)in the cluster.
Return:
  geometry centroid of the cluster

"""
cluster_ary = np.asarray(cluster)
centroid = cluster_ary.mean(axis=0)
return centroid

# convert eps to radians for use by haversine
epsilon = 0.1/kms_per_rad #1.5=1.5km  1=1km  0.5=500m 0.25=250m   0.1=100m

# Extract intersection coordinates (latitude, longitude)
tweet_coords = df.as_matrix(columns=['latitude','longitude'])

start_time = time.time()
dbsc = (DBSCAN(eps=epsilon, min_samples=10, algorithm='ball_tree', metric='haversine')
    .fit(np.radians(tweet_coords)))

tweet_cluster_labels = dbsc.labels_

# get the number of clusters
num_clusters = len(set(dbsc.labels_))

# print the outcome
message = 'Clustered {:,} points down to {:,} clusters, for {:.1f}% compression in {:,.2f} seconds'
print(message.format(len(df), num_clusters, 100*(1 - float(num_clusters) / len(df)), time.time()-start_time))
print('Silhouette coefficient:     {:0.03f}'.format(metrics.silhouette_score(tweet_coords, tweet_cluster_labels)))

# Turn the clusters into a pandas series,where each element is a cluster of points
dbsc_clusters = pd.Series([tweet_coords[tweet_cluster_labels==n] for n in  range(num_clusters)])

# get centroid of each cluster
cluster_centroids = dbsc_clusters.map(get_centroid)
# unzip the list of centroid points (lat, lon) tuples into separate lat and lon lists
cent_lats, cent_lons = zip(*cluster_centroids)
# from these lats/lons create a new df of one representative point for eac   cluster
centroids_df = pd.DataFrame({'longitude':cent_lons, 'latitude':cent_lats})
#print centroids_df

# Plot the clusters and cluster centroids
fig, ax = plt.subplots(figsize=[20, 12])
tweet_scatter = ax.scatter(df['longitude'], df['latitude'],   c=tweet_cluster_labels, cmap = cm.hot, edgecolor='None', alpha=0.25, s=50)
centroid_scatter = ax.scatter(centroids_df['longitude'], centroids_df['latitude'], marker='x', linewidths=2, c='k', s=50)
ax.set_title('Tweet Clusters & Cluser Centroids', fontsize = 30)
ax.set_xlabel('Longitude', fontsize=24)
ax.set_ylabel('Latitude', fontsize = 24)
ax.legend([tweet_scatter, centroid_scatter], ['Tweets', 'Tweets Cluster Centroids'], loc='upper right', fontsize = 20)
plt.show()
</code>```

Black points are the noise, those not added in a cluster as defined by DBSCAN inputs, and colored points are clusters. My goal is to visualize just the clusters.

答:
Store the labels in an additional column in the original DataFrame

```<code>df['tweet_cluster_labels'] = tweet_cluster_labels
</code>```

filter the DataFrame so that it only contains non-noise points (noisy samples are given the label -1)

```<code>df_filtered = df[df.tweet_cluster_labels>-1]
</code>```

and plot just those points

```<code>tweet_scatter = ax.scatter(df_filtered['longitude'],
                df_filtered['latitude'],
                c=df_filtered.tweet_cluster_labels,
                cmap=cm.hot, edgecolor='None', alpha=0.25, s=50)
</code>```

Title: DBSCAN Remove Noise from Plot

Body:
Using DBSCAN,

(DBSCAN(eps=epsilon, min_samples=10, algorithm='ball_tree', metric='haversine')

I have clustered a list of latitude and longitude pairs, for which I then plotted using matplotlib. When plotting, it includes the "noise" coordinates, which are the points that are not assigned to one of the 270 clusters created. I would like to remove the noise from the plot, and just plot the clusters meeting the requirements specified, but I'm not sure how to do so. How might I go about excluding the noise (again, those points not assigned to a cluster)?

Below is the code I have used to cluster and plot:

df = pd.read_csv('xxx.csv')

# define the number of kilometers in one radiation
# which will be used to convert esp from km to radiation
kms_per_rad = 6371.0088

# define a function to calculate the geographic coordinate
# centroid of a cluster of geographic points
# it will be used later to calculate the centroids of DBSCAN cluster
# because Scikit-learn DBSCAN cluster class does not come with centroid attribute.
def get_centroid(cluster):
"""calculate the centroid of a cluster of geographic coordinate points
Args:
  cluster coordinates, nx2 array-like (array, list of lists, etc)
  n is the number of points(latitude, longitude)in the cluster.
Return:
  geometry centroid of the cluster

"""
cluster_ary = np.asarray(cluster)
centroid = cluster_ary.mean(axis=0)
return centroid

# convert eps to radians for use by haversine
epsilon = 0.1/kms_per_rad #1.5=1.5km  1=1km  0.5=500m 0.25=250m   0.1=100m

# Extract intersection coordinates (latitude, longitude)
tweet_coords = df.as_matrix(columns=['latitude','longitude'])

start_time = time.time()
dbsc = (DBSCAN(eps=epsilon, min_samples=10, algorithm='ball_tree', metric='haversine')
    .fit(np.radians(tweet_coords)))

tweet_cluster_labels = dbsc.labels_

# get the number of clusters
num_clusters = len(set(dbsc.labels_))

# print the outcome
message = 'Clustered {:,} points down to {:,} clusters, for {:.1f}% compression in {:,.2f} seconds'
print(message.format(len(df), num_clusters, 100*(1 - float(num_clusters) / len(df)), time.time()-start_time))
print('Silhouette coefficient:     {:0.03f}'.format(metrics.silhouette_score(tweet_coords, tweet_cluster_labels)))

# Turn the clusters into a pandas series,where each element is a cluster of points
dbsc_clusters = pd.Series([tweet_coords[tweet_cluster_labels==n] for n in  range(num_clusters)])

# get centroid of each cluster
cluster_centroids = dbsc_clusters.map(get_centroid)
# unzip the list of centroid points (lat, lon) tuples into separate lat and lon lists
cent_lats, cent_lons = zip(*cluster_centroids)
# from these lats/lons create a new df of one representative point for eac   cluster
centroids_df = pd.DataFrame({'longitude':cent_lons, 'latitude':cent_lats})
#print centroids_df

# Plot the clusters and cluster centroids
fig, ax = plt.subplots(figsize=[20, 12])
tweet_scatter = ax.scatter(df['longitude'], df['latitude'],   c=tweet_cluster_labels, cmap = cm.hot, edgecolor='None', alpha=0.25, s=50)
centroid_scatter = ax.scatter(centroids_df['longitude'], centroids_df['latitude'], marker='x', linewidths=2, c='k', s=50)
ax.set_title('Tweet Clusters & Cluser Centroids', fontsize = 30)
ax.set_xlabel('Longitude', fontsize=24)
ax.set_ylabel('Latitude', fontsize = 24)
ax.legend([tweet_scatter, centroid_scatter], ['Tweets', 'Tweets Cluster Centroids'], loc='upper right', fontsize = 20)
plt.show()

Black points are the noise, those not added in a cluster as defined by DBSCAN inputs, and colored points are clusters. My goal is to visualize just the clusters.

Body:
Store the labels in an additional column in the original DataFrame

df['tweet_cluster_labels'] = tweet_cluster_labels

filter the DataFrame so that it only contains non-noise points (noisy samples are given the label -1)

df_filtered = df[df.tweet_cluster_labels>-1]

and plot just those points

tweet_scatter = ax.scatter(df_filtered['longitude'],
                df_filtered['latitude'],
                c=df_filtered.tweet_cluster_labels,
                cmap=cm.hot, edgecolor='None', alpha=0.25, s=50)