问:
C++ templating for vector math generating GLSL
I'm trying to come up with a C++ templating design pattern that would allow me to write C++ looking code like this the example below, that is able to both generate a string representation of the operations (like GLSL), and compute the actual results.

```<code>template<typename T>
vec3<T> make_effect(const vec3<T> &color, const mat3<T> &fx_matrix) {
    return sin(fx_matrix * color);
}

// I should of course define a sin function using this style of templating.
</code>```

(This math in this example makes little sense, but it gives a hint of what I'm after.)

Note that there is a template parameter T. The thing is that I would like to be able to with this single instance of code, produce the GLSL code, AND perform actual calculations on CPU, depending on the template parameter.

For example, in case of GLSL as a target:

```<code>vec3<GLSL> expression = make_effect(vec3<GLSL>(1.0f, 0.4f, 0.1f), some_matrix);
std::string glsl_code = expression.to_string();
// would be:
assert(glsl_code == "sin(some_matrix * vec3(1.0, 0.4, 0.1))");
</code>```

Or, in case of CPU-side calculations:

```<code>vec3<CPU> result = make_effect(vec3<CPU>(1.0f, 0.4f, 0.1f), some_matrix);
// now: result.x(), result.y(), result.z() contain the
// actual values of the calculation
</code>```

How should I approach such a thing? Does this have a name? Do similar solutions already exist?

Also note that I don't want to calculate anything in case of the GLSL variant. I only need the code, to be able to generate a shader for the GPU.
Extensibility to new implementations, for example Direct X shaders is a plus.

答:
I figured out a way to do it.

For all datatypes define a struct supporting operations like in GLSL. Note that it inherits from the template parameter B (which stands for "backend"). Also note that all functions are by default deleted. Example below is the interface for a float (shortened to fl to avoid C++ keyword collision):

```<code>template <typename B>
struct fl : public B {
    fl(B b) : B(b) {}
    fl(float x) = delete;

    operator float() const = delete;

    fl<B> operator+(const fl<B> &rhs) const = delete;
    fl<B> operator*(const fl<B> &rhs) const = delete;
    fl<B> operator-(const fl<B> &rhs) const = delete;
    fl<B> operator/(const fl<B> &rhs) const = delete;

    fl<B> operator-() const = delete;

    vec2<B> operator*(const vec2<B> &rhs) const = delete;
    vec3<B> operator*(const vec3<B> &rhs) const = delete;
};
</code>```

Now we will define a backend to use as B, for GLSL:

```<code>class GLSL {
    std::string expr;

  public:
    operator std::string() const { return expr; }
    operator const char *() const { return expr.c_str(); }

    const std::string &str() const { return expr; }

    GLSL(const std::string &str) : expr(str) {}
    GLSL(const char *str) : expr(str) {}
};
</code>```

Then, we will implement the GLSL backend template specialisation. For example the fl + fl operation in GLSL:

```<code>template <>
inline fl<GLSL> fl<GLSL>::operator +(const fl<GLSL> &rhs) const {
    return fl<GLSL>("(" + str() + "+" + rhs.str() + ")");
}
</code>```

And many more implementations come here as well.

Now we do something similar for the CPU backend (using Eigen):

```<code>class CPU {
  public:
    union {
        float _fl;
        Eigen::Vector2f _vec2;
        Eigen::Vector3f _vec3;
        struct {
            float _x, _y, _z;
        };
    };

    CPU(float x) { _fl = x; }
    CPU(Eigen::Vector2f x) { _vec2 = x; }
    CPU(Eigen::Vector3f x) { _vec3 = x; }

    CPU(const CPU &orig) { _vec3 = orig._vec3; }
};
</code>```

And the fl + fl implementation:

```<code>template <>
inline fl<CPU> fl<CPU>::operator +(const fl<CPU> &rhs) const {
    return fl<CPU>(_fl + rhs._fl);
}
</code>```

And this for all possible operators (binary and unary), functions, etc... Note that I used a lot of C preprocessor macros to save a lot of typing work. Also swizzling for vector types is completely implemented using these functions like xxx().

Now as a demo:

```<code>using namespace vecmath;

template <typename B>
vec3<B> make_effect(vec3<B> a, vec3<B> b) {
    return pow(a, b).yzx() + sin(a);
}

TEST(vecmath_demo, demo_01) {
    // GLSL
    vec3<GLSL> g_a("a");
    vec3<GLSL> g_b("b");
    vec3<GLSL> expr = make_effect(g_a, g_b);

    std::cout << "GLSL: " << expr.str() << std::endl;

    // CPU
    vec3<CPU> c_a(2.0f, 4.0f, 3.0f);
    vec3<CPU> c_b(0.0f, 1.0f, 2.0f);
    vec3<CPU> result = make_effect(c_a, c_b);

    std::cout << "CPU: " << ((Eigen::Vector3f)result).transpose() << std::endl;

    SUCCEED();
}
</code>```

Prints:

```<code>GLSL: (pow(a, b).yzx+sin(a))
CPU:  4.9093  8.2432 1.14112
</code>```

Body:
I'm trying to come up with a C++ templating design pattern that would allow me to write C++ looking code like this the example below, that is able to both generate a string representation of the operations (like GLSL), and compute the actual results.

template<typename T>
vec3<T> make_effect(const vec3<T> &color, const mat3<T> &fx_matrix) {
    return sin(fx_matrix * color);
}

// I should of course define a sin function using this style of templating.

(This math in this example makes little sense, but it gives a hint of what I'm after.)

Note that there is a template parameter T. The thing is that I would like to be able to with this single instance of code, produce the GLSL code, AND perform actual calculations on CPU, depending on the template parameter.

For example, in case of GLSL as a target:

vec3<GLSL> expression = make_effect(vec3<GLSL>(1.0f, 0.4f, 0.1f), some_matrix);
std::string glsl_code = expression.to_string();
// would be:
assert(glsl_code == "sin(some_matrix * vec3(1.0, 0.4, 0.1))");

Or, in case of CPU-side calculations:

vec3<CPU> result = make_effect(vec3<CPU>(1.0f, 0.4f, 0.1f), some_matrix);
// now: result.x(), result.y(), result.z() contain the
// actual values of the calculation

How should I approach such a thing? Does this have a name? Do similar solutions already exist?

Also note that I don't want to calculate anything in case of the GLSL variant. I only need the code, to be able to generate a shader for the GPU.
Extensibility to new implementations, for example Direct X shaders is a plus.

Body:
I figured out a way to do it.

For all datatypes define a struct supporting operations like in GLSL. Note that it inherits from the template parameter B (which stands for "backend"). Also note that all functions are by default deleted. Example below is the interface for a float (shortened to fl to avoid C++ keyword collision):

template <typename B>
struct fl : public B {
    fl(B b) : B(b) {}
    fl(float x) = delete;

    operator float() const = delete;

    fl<B> operator+(const fl<B> &rhs) const = delete;
    fl<B> operator*(const fl<B> &rhs) const = delete;
    fl<B> operator-(const fl<B> &rhs) const = delete;
    fl<B> operator/(const fl<B> &rhs) const = delete;

    fl<B> operator-() const = delete;

    vec2<B> operator*(const vec2<B> &rhs) const = delete;
    vec3<B> operator*(const vec3<B> &rhs) const = delete;
};

Now we will define a backend to use as B, for GLSL:

class GLSL {
    std::string expr;

  public:
    operator std::string() const { return expr; }
    operator const char *() const { return expr.c_str(); }

    const std::string &str() const { return expr; }

    GLSL(const std::string &str) : expr(str) {}
    GLSL(const char *str) : expr(str) {}
};

Then, we will implement the GLSL backend template specialisation. For example the fl + fl operation in GLSL:

template <>
inline fl<GLSL> fl<GLSL>::operator +(const fl<GLSL> &rhs) const {
    return fl<GLSL>("(" + str() + "+" + rhs.str() + ")");
}

And many more implementations come here as well.

Now we do something similar for the CPU backend (using Eigen):

class CPU {
  public:
    union {
        float _fl;
        Eigen::Vector2f _vec2;
        Eigen::Vector3f _vec3;
        struct {
            float _x, _y, _z;
        };
    };

    CPU(float x) { _fl = x; }
    CPU(Eigen::Vector2f x) { _vec2 = x; }
    CPU(Eigen::Vector3f x) { _vec3 = x; }

    CPU(const CPU &orig) { _vec3 = orig._vec3; }
};

And the fl + fl implementation:

template <>
inline fl<CPU> fl<CPU>::operator +(const fl<CPU> &rhs) const {
    return fl<CPU>(_fl + rhs._fl);
}

And this for all possible operators (binary and unary), functions, etc... Note that I used a lot of C preprocessor macros to save a lot of typing work. Also swizzling for vector types is completely implemented using these functions like xxx().

Now as a demo:

using namespace vecmath;

template <typename B>
vec3<B> make_effect(vec3<B> a, vec3<B> b) {
    return pow(a, b).yzx() + sin(a);
}

TEST(vecmath_demo, demo_01) {
    // GLSL
    vec3<GLSL> g_a("a");
    vec3<GLSL> g_b("b");
    vec3<GLSL> expr = make_effect(g_a, g_b);

    std::cout << "GLSL: " << expr.str() << std::endl;

    // CPU
    vec3<CPU> c_a(2.0f, 4.0f, 3.0f);
    vec3<CPU> c_b(0.0f, 1.0f, 2.0f);
    vec3<CPU> result = make_effect(c_a, c_b);

    std::cout << "CPU: " << ((Eigen::Vector3f)result).transpose() << std::endl;

    SUCCEED();
}

Prints:

GLSL: (pow(a, b).yzx+sin(a))
CPU:  4.9093  8.2432 1.14112


来源: stackexchange

问:
VSTS deploy: Unable to replace variables in appsettings.json
I have a fairly standard setup for an ASP.NET Core application - source control on GitHub with the live application hosted on Azure, with master branch changes triggering CI builds on VSTS.
The DB connection string is in appsettings.json, normally pointing at a localdb instance. For deploying to Azure, I want it to point to an Azure SQL DB (which I had neglected to set up during the first publish).
The app service itself was set up on Azure as an app service without a DB - in other words, I shouldn't have done this just after waking up. However, both the app service and DB are linked to the same resource group.

The problem I am facing is that whenever I trigger a CI build via VSTS, the build works but the release falls over at the point at which it tries to replace the connection string with the one defined in the CI build variables.

2017-07-09T08:47:02.7205410Z ##[section]Starting: Deploy Azure App Service
  2017-07-09T08:47:02.7415413Z ==============================================================================
  2017-07-09T08:47:02.7415413Z Task         : Azure App Service Deploy
  2017-07-09T08:47:02.7415413Z Description  : Update Azure App Service using Web Deploy / Kudu REST APIs
  2017-07-09T08:47:02.7415413Z Version      : 3.3.9
  2017-07-09T08:47:02.7415413Z Author       : Microsoft Corporation
  2017-07-09T08:47:02.7415413Z Help         :
  2017-07-09T08:47:02.7415413Z ==============================================================================
  2017-07-09T08:47:06.5658468Z Got connection details for Azure App Service:'BlackscarsSheetsSwtor'
  2017-07-09T08:47:07.6978989Z ##[error]Error: NO JSON file matched with specific pattern: appsettings,json.

I've tried the solution here, only to be met with exactly the same error, though with the log showing **/appsettings.json instead of appsettings.json.

Deploy definition

This is the appsettings.json file

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=Telvee32.BlackscarsSheetsSwtor.Db;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}```

This is my first time working with build and release definitions so it's entirely possible I've fessed something up, but the actual definitions were created automatically by Azure and were working fine until I started doing this, which, given that the application is dependent upon a DB, definitely needs to be working properly.

答:
My initial thoughts are that you've misspelt the JSON config name

```<code>Service:'BlackscarsSheetsSwtor' 2017-07-09T08:47:07.6978989Z ##[error]Error: NO JSON file matched with specific pattern: appsettings,json.
</code>```

Here you have a comma , instead of a ..

Have you checked to see if that's the cause of the problem?

ContentLicense: CC BY-SA 3.0

Body:
I have a fairly standard setup for an ASP.NET Core application - source control on GitHub with the live application hosted on Azure, with master branch changes triggering CI builds on VSTS.
The DB connection string is in appsettings.json, normally pointing at a localdb instance. For deploying to Azure, I want it to point to an Azure SQL DB (which I had neglected to set up during the first publish).
The app service itself was set up on Azure as an app service without a DB - in other words, I shouldn't have done this just after waking up. However, both the app service and DB are linked to the same resource group.

The problem I am facing is that whenever I trigger a CI build via VSTS, the build works but the release falls over at the point at which it tries to replace the connection string with the one defined in the CI build variables.

2017-07-09T08:47:02.7205410Z ##[section]Starting: Deploy Azure App Service
  2017-07-09T08:47:02.7415413Z ==============================================================================
  2017-07-09T08:47:02.7415413Z Task         : Azure App Service Deploy
  2017-07-09T08:47:02.7415413Z Description  : Update Azure App Service using Web Deploy / Kudu REST APIs
  2017-07-09T08:47:02.7415413Z Version      : 3.3.9
  2017-07-09T08:47:02.7415413Z Author       : Microsoft Corporation
  2017-07-09T08:47:02.7415413Z Help         :
  2017-07-09T08:47:02.7415413Z ==============================================================================
  2017-07-09T08:47:06.5658468Z Got connection details for Azure App Service:'BlackscarsSheetsSwtor'
  2017-07-09T08:47:07.6978989Z ##[error]Error: NO JSON file matched with specific pattern: appsettings,json.

I've tried the solution here, only to be met with exactly the same error, though with the log showing **/appsettings.json instead of appsettings.json.

Deploy definition

This is the appsettings.json file

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=Telvee32.BlackscarsSheetsSwtor.Db;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

This is my first time working with build and release definitions so it's entirely possible I've fessed something up, but the actual definitions were created automatically by Azure and were working fine until I started doing this, which, given that the application is dependent upon a DB, definitely needs to be working properly.

Body:
My initial thoughts are that you've misspelt the JSON config name

Service:'BlackscarsSheetsSwtor' 2017-07-09T08:47:07.6978989Z ##[error]Error: NO JSON file matched with specific pattern: appsettings,json.

Here you have a comma , instead of a ..

Have you checked to see if that's the cause of the problem?


问:
How to download source code with Pacman on Arch Linux?
I am using Arch Linux. I want to do the same thing like apt-get source coreutils; is it possible to download sources with Pacman? I didn't find a solution in the man pages.

How can I get the source code of a package?

答:
Edit: This answer is outdated due to changes on ABS.

You get the package sources from the Arch Linux SVN repository, called ABS.

First find the package online:
http://www.archlinux.org/packages/?q=coreutils

Then, on the package details page, on the right side use the SVN links, e.g.:
http://repos.archlinux.org/wsvn/packages/coreutils/trunk/

And there, you have a sweet "Download" button, in this case it leads to:
http://repos.archlinux.org/wsvn/packages/coreutils/trunk/?op=dl&isdir=1

It is a little bit more complicated than apt-get source. But perhaps you find a tool on AUR that does the job for you, for example yaourt supports building from sources and exporting them.


问:
How to define template or templateUrl (HTML) for a state with named views?
I was referring to multiple named views doc and found this statement in one of their examples:

Since the state "contacts.detail" has named views, its template or templateUrl will be ignored (as per the docs). So from where will contacts.detail.html be loaded/defined and how the 'info' view be targeted in that?

答:
They are using the following example in the documentation link you provided :

```<code>$stateProvider
.state('contacts', {
// This will get automatically plugged into the unnamed ui-view
// of the parent state template. Since this is a top level state,
// its parent state template is index.html.
templateUrl: 'contacts.html'
})
.state('contacts.detail', {
views: {
    ////////////////////////////////////
    // Relative Targeting             //
    // Targets parent state ui-view's //
    ////////////////////////////////////

    // Relatively targets the 'detail' view in this state's parent state, 'contacts'.
    // <div ui-view='detail'/> within contacts.html
    "detail" : { },

    // Relatively targets the unnamed view in this state's parent state, 'contacts'.
    // <div ui-view/> within contacts.html
    "" : { },

    ///////////////////////////////////////////////////////
    // Absolute Targeting using '@'                      //
    // Targets any view within this state or an ancestor //
    ///////////////////////////////////////////////////////

    // Absolutely targets the 'info' view in this state, 'contacts.detail'.
    // <div ui-view='info'/> within contacts.detail.html
    "info@contacts.detail" : { }

    // Absolutely targets the 'detail' view in the 'contacts' state.
    // <div ui-view='detail'/> within contacts.html
    "detail@contacts" : { }

    // Absolutely targets the unnamed view in parent 'contacts' state.
    // <div ui-view/> within contacts.html
    "@contacts" : { }

    // absolutely targets the 'status' view in root unnamed state.
    // <div ui-view='status'/> within index.html
    "status@" : { }

    // absolutely targets the unnamed view in root unnamed state.
    // <div ui-view/> within index.html
    "@" : { }
});
</code>```

Well detail is a child state of contact.

When you define that state, you can define it normally with tempalte url, or you can use nested views. If you use nested views, you shall have a parent state (here contact) and you have the choice to define the the detail child state with two ways :

```<code>    // Relatively targets the 'detail' view in this state's parent state, 'contacts'.
// <div ui-view='detail'/> within contacts.html
"detail" : {templateUrl: 'contacts.detail.html' ...}
</code>```

Which is the relative way (relative to its parent state, here 'contacts')

```<code> // Absolutely targets the 'detail' view in the 'contacts' state.
// <div ui-view='detail'/> within contacts.html
"detail@contacts" : {templateUrl: 'contacts.details.html' }
</code>```

Which is the absolute way, defining the detail child state.

This fiddle is an example of all of this.

Body:
They are using the following example in the documentation link you provided :

$stateProvider
.state('contacts', {
// This will get automatically plugged into the unnamed ui-view
// of the parent state template. Since this is a top level state,
// its parent state template is index.html.
templateUrl: 'contacts.html'
})
.state('contacts.detail', {
views: {
    ////////////////////////////////////
    // Relative Targeting             //
    // Targets parent state ui-view's //
    ////////////////////////////////////

    // Relatively targets the 'detail' view in this state's parent state, 'contacts'.
    // <div ui-view='detail'/> within contacts.html
    "detail" : { },

    // Relatively targets the unnamed view in this state's parent state, 'contacts'.
    // <div ui-view/> within contacts.html
    "" : { },

    ///////////////////////////////////////////////////////
    // Absolute Targeting using '@'                      //
    // Targets any view within this state or an ancestor //
    ///////////////////////////////////////////////////////

    // Absolutely targets the 'info' view in this state, 'contacts.detail'.
    // <div ui-view='info'/> within contacts.detail.html
    "info@contacts.detail" : { }

    // Absolutely targets the 'detail' view in the 'contacts' state.
    // <div ui-view='detail'/> within contacts.html
    "detail@contacts" : { }

    // Absolutely targets the unnamed view in parent 'contacts' state.
    // <div ui-view/> within contacts.html
    "@contacts" : { }

    // absolutely targets the 'status' view in root unnamed state.
    // <div ui-view='status'/> within index.html
    "status@" : { }

    // absolutely targets the unnamed view in root unnamed state.
    // <div ui-view/> within index.html
    "@" : { }
});

Well detail is a child state of contact.

When you define that state, you can define it normally with tempalte url, or you can use nested views. If you use nested views, you shall have a parent state (here contact) and you have the choice to define the the detail child state with two ways :

    // Relatively targets the 'detail' view in this state's parent state, 'contacts'.
// <div ui-view='detail'/> within contacts.html
"detail" : {templateUrl: 'contacts.detail.html' ...}

Which is the relative way (relative to its parent state, here 'contacts')

 // Absolutely targets the 'detail' view in the 'contacts' state.
// <div ui-view='detail'/> within contacts.html
"detail@contacts" : {templateUrl: 'contacts.details.html' }

Which is the absolute way, defining the detail child state.

This fiddle is an example of all of this.


问:
Download excel file in javascript from Rest API response content-disposition outputs [Object, Object]
I want to download a excel file from my angularJs code. Where i made a http post request to Java Rest API and returned the file with header
"Content-Disposition" : "attachment; filename=\"new_excel_file.xlsx\""

Java Code

```<code>@Post
@Path("/excel/trekResult")
@Produces("application/vnd.ms-excel")
public Response getResultsReport(@HeaderParam(Constants.ID) Long userId, @QueryParam(Constants.COMPANY_TREK_ID) Integer companyTrekId) {
String CONTENT_DESPOSITION = "Content-Disposition";
String CONTENT_ATTACHEMENT = "attachment; filename=\"new_excel_file.xlsx\"";

//Generates a excel file in local file system
File excelFile = misHelper.writeToFile(workBook, mis, userId, "trek-results");

return Response.ok().entity((Object)excelFile).
    header(CONTENT_DESPOSITION, CONTENT_ATTACHEMENT).build();

}
</code>```

On Javascript Side

```<code>myService.exportResult($scope.companyTrek.id).then(function(result) {
  if(result !== undefined || result !== '') {
    var blob = new Blob([result], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    var objectUrl = URL.createObjectURL(blob);
    saveAs(blob, 'Trek-Results-'+fetchCurrentDate()+ '.xlsx');
  }
}
</code>```

Used FileSaver.js to save file.

The output file is [Object, Object]

Tested The locally generated file.

Here is a similar question for reference that didn't help me.

receive an excel file as response in javascript from a Rest service

答:
I just noticed the Mime types are different on Java server vs Angular client.

This link shows the different MIME types related to spreadsheets.

Try making them consistent and seeing if that fixed it.

There was also this way without mishelper.

ContentLicense: CC BY-SA 4.0

Body:
I want to download a excel file from my angularJs code. Where i made a http post request to Java Rest API and returned the file with header
"Content-Disposition" : "attachment; filename=\"new_excel_file.xlsx\""

Java Code

@Post
@Path("/excel/trekResult")
@Produces("application/vnd.ms-excel")
public Response getResultsReport(@HeaderParam(Constants.ID) Long userId, @QueryParam(Constants.COMPANY_TREK_ID) Integer companyTrekId) {
String CONTENT_DESPOSITION = "Content-Disposition";
String CONTENT_ATTACHEMENT = "attachment; filename=\"new_excel_file.xlsx\"";

//Generates a excel file in local file system
File excelFile = misHelper.writeToFile(workBook, mis, userId, "trek-results");

return Response.ok().entity((Object)excelFile).
    header(CONTENT_DESPOSITION, CONTENT_ATTACHEMENT).build();

}

On Javascript Side

myService.exportResult($scope.companyTrek.id).then(function(result) {
  if(result !== undefined || result !== '') {
    var blob = new Blob([result], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    var objectUrl = URL.createObjectURL(blob);
    saveAs(blob, 'Trek-Results-'+fetchCurrentDate()+ '.xlsx');
  }
}

Used FileSaver.js to save file.

The output file is [Object, Object]

Tested The locally generated file.

Here is a similar question for reference that didn't help me.

receive an excel file as response in javascript from a Rest service


问:
Turn column headers into the first row of my df
I am looking forward to turn df headers to the first row of my df:

```<code>     Air    Unnamed:1  400.65    452.21    458.22
0    Wind       NaN   3835.83   3835.83   3813.18
1    Fire       NaN    989.05    989.75    981.31
2    Water      NaN   1617.00   1623.17   1614.64
</code>```

Looking for this output:

```<code>       0         1      2        3          4
0     Air       NaN    400.65    452.21    458.22
1    Wind       NaN   3835.83   3835.83   3813.18
2    Fire       NaN    989.05    989.75    981.31
3    Water      NaN   1617.00   1623.17   1614.64
</code>```

I have tried setting the header of the read_html function to -1 to see if it could make the header into the first row such as:

```<code>pd.read_html(route, flavor='html5lib',header=-1)
</code>```

But didn't worked

Any idea on how to turn the headers into my first row of the df?

答:
I think you need header=None:

```<code>pd.read_html(route, flavor='html5lib',header=None)
</code>```

Body:
I am looking forward to turn df headers to the first row of my df:

     Air    Unnamed:1  400.65    452.21    458.22
0    Wind       NaN   3835.83   3835.83   3813.18
1    Fire       NaN    989.05    989.75    981.31
2    Water      NaN   1617.00   1623.17   1614.64

Looking for this output:

       0         1      2        3          4
0     Air       NaN    400.65    452.21    458.22
1    Wind       NaN   3835.83   3835.83   3813.18
2    Fire       NaN    989.05    989.75    981.31
3    Water      NaN   1617.00   1623.17   1614.64

I have tried setting the header of the read_html function to -1 to see if it could make the header into the first row such as:

pd.read_html(route, flavor='html5lib',header=-1)

But didn't worked

Any idea on how to turn the headers into my first row of the df?

Body:
I think you need header=None:

pd.read_html(route, flavor='html5lib',header=None)


问:
Hibernate insert cascade not inserting foreign key
I have two entities:

```<code>@Entity
public class File
.......
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@OneToMany(fetch=FetchType.LAZY, mappedBy="file", cascade=CascadeType.ALL)
private List<Tag> tags;
.......
OTHER PROPERTIES
.......

@Entity
public class Tag
.......
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn(name="file_id")
private File file;
@Column
private String tag;
.......
OTHER PROPERTIES
.......
</code>```

I am trying to insert into File (and subsequently Tag) by doing the following:

```<code>File file = new File();
Tag tag = new Tag();
tag.setTag("tag1");
Tag2 tag2 = new Tag();
tag2.setTag("tag2");
List<Tag> tags = new ArrayList<Tag>();
tags.add(tag);
tags.add(tag2);
file.setTags(tags);
---Add other file attributes here---
</code>```

I am then inserting the file in my DAO using:

```<code>sessionFactory.getCurrentSession().saveOrUpdate(file);
</code>```

In my logs I see an insert into my "file" table and 2 inserts into my tag table, however, the foreign key in my tag table that points to my file table (file_id) is NULL.

What could I possibly be doing wrong?

答:
You are not setting the File for a Tag, just the Tag's to a File. Remember that in OOP, as opposed to the Relational Model, you have to set both ends of a relationship. You can't navigate from Tag to File just because you added a set of Tags to a File. In your case, you can just navigate from File to Tag (ie: list all Tags for a File). You can't tell which File a Tag belongs to, by looking only at the Tag.

What is usually done is a helper method in one of the models, like this:

```<code>public void addTag(Tag tag) {
  this.tags.add(tag);
  tag.setFile(this);
}
</code>```

See this for an example (from Hibernate's test suite):

ContentLicense: CC BY-SA 2.5

Body:
I have two entities:

@Entity
public class File
.......
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@OneToMany(fetch=FetchType.LAZY, mappedBy="file", cascade=CascadeType.ALL)
private List<Tag> tags;
.......
OTHER PROPERTIES
.......

@Entity
public class Tag
.......
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn(name="file_id")
private File file;
@Column
private String tag;
.......
OTHER PROPERTIES
.......

I am trying to insert into File (and subsequently Tag) by doing the following:

File file = new File();
Tag tag = new Tag();
tag.setTag("tag1");
Tag2 tag2 = new Tag();
tag2.setTag("tag2");
List<Tag> tags = new ArrayList<Tag>();
tags.add(tag);
tags.add(tag2);
file.setTags(tags);
---Add other file attributes here---

I am then inserting the file in my DAO using:

sessionFactory.getCurrentSession().saveOrUpdate(file);

In my logs I see an insert into my "file" table and 2 inserts into my tag table, however, the foreign key in my tag table that points to my file table (file_id) is NULL.

What could I possibly be doing wrong?

Body:
You are not setting the File for a Tag, just the Tag's to a File. Remember that in OOP, as opposed to the Relational Model, you have to set both ends of a relationship. You can't navigate from Tag to File just because you added a set of Tags to a File. In your case, you can just navigate from File to Tag (ie: list all Tags for a File). You can't tell which File a Tag belongs to, by looking only at the Tag.

What is usually done is a helper method in one of the models, like this:

public void addTag(Tag tag) {
  this.tags.add(tag);
  tag.setFile(this);
}

See this for an example (from Hibernate's test suite):


问:
How to implement a listener to check i have read a text file and ignore it
I have written a small program to monitor a folder. I have not used the folderWatcher in .NET because multiple files can be added to the folder simultaneously and folderWatcher can sometimes miss them. Basically, I am checking the folder for a file that starts and ends with certain characters. The timer is checking the folder every 10 seconds.

My issue: my program will read the same file multiple times. I need to set a condition or have a listener check if the file has already been read to ignore it.

The problem is I'm not sure how to go about this, can anyone shed some light on the best way to maybe implement a listener that will check if I have read this file and ignore it and move onto the next file, please?

I couldn't find another thread on here that helped me with the answer I am looking for.

答:
Thanks Coskun
That is a good option and it does work.
For simplicity i went a different route, I  add the file names to a list then check the list pre-execution, if the list does not contain that file name it executes. I go on to count the file names in the list and output the total on each pass to a text field that tell me how many files i ignored.</p>


问:
Stop function after some time
I want to make a simple background which changes to the colors of the rainbow every 1400 ms, which I did like this. Here's the code:

```<code>function onload() {
        var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
        var body = document.getElementById('body');
        var i = 0;
        function rainbow() {
            if(i == color.length) {i = 0;};
            body.style.backgroundColor = color[i++];
            setTimeout(rainbow, 1400);
        };
        rainbow();
};

onload();
</code>```

But after running this function for 6049 ms, I want the background to change with intervals of 50ms instead of 1400 ms. How would I do that?

答:
You can change the interval in another timer like this.

function onload() {
    var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
    var body = document.getElementById('body');
    var i = 0;
    var interval = 1400;

    function rainbow() {
        if (i == color.length) {
            i = 0;
        };
        body.style.backgroundColor = color[i++];
        console.log("Interval is: " + interval);
        setTimeout(rainbow, interval);
    };

    var intervalTimer = setTimeout(function() {
        interval = 50;
        clearTimeout(intervalTimer);
    }, 6049);

    rainbow();
};

onload();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body id='body'>
</body></code>```

Title: Stop function after some time

Body:
I want to make a simple background which changes to the colors of the rainbow every 1400 ms, which I did like this. Here's the code:

function onload() {
        var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
        var body = document.getElementById('body');
        var i = 0;
        function rainbow() {
            if(i == color.length) {i = 0;};
            body.style.backgroundColor = color[i++];
            setTimeout(rainbow, 1400);
        };
        rainbow();
};

onload();

But after running this function for 6049 ms, I want the background to change with intervals of 50ms instead of 1400 ms. How would I do that?

Body:
You can change the interval in another timer like this.

function onload() {
    var color = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
    var body = document.getElementById('body');
    var i = 0;
    var interval = 1400;

    function rainbow() {
        if (i == color.length) {
            i = 0;
        };
        body.style.backgroundColor = color[i++];
        console.log("Interval is: " + interval);
        setTimeout(rainbow, interval);
    };

    var intervalTimer = setTimeout(function() {
        interval = 50;
        clearTimeout(intervalTimer);
    }, 6049);

    rainbow();
};

onload();

<body id='body'>
</body>


问:
How to change user in Yii2
I am using an API into a Yii2 app, and so Yii::$app->user is null.

Can I manually set Yii::$app->user?

All exmaples I have foun involved editing a user, not setting a user.

答:
You might need to configure the 'user' component in your API app config first. Like so:</p>

```<code>'components'    => [
    // ...
    'user'      => [
        'class' => 'yii\web\User',
    ],
    // ...
],
</code>```

Title: How to change user in Yii2

Body:
You might need to configure the 'user' component in your API app config first. Like so:

'components'    => [
    // ...
    'user'      => [
        'class' => 'yii\web\User',
    ],
    // ...
],


问:
How to make that git push origin master dont show output of files in repo
I'm trying that git push don't show the output.

I try with --quiet option and redirection to /dev/null like that:

```<code>git push origin master &>/dev/null
</code>```

But Git still shows all files of the repo when a make a push like that:

```<code>Username for 'https://github.com': n0zg
Password for 'https://n0zg@github.com':
test.html
888.html
9991.html
999.html
index.html
css/
css/stylesheet.css
highlight/
highlight/README.md
highlight/LICENSE
highlight/CHANGES.md
highlight/README.ru.md
highlight/styles/
highlight/styles/ir-black.css
....
</code>```

How can I make that git push don't show all files in the repo on the terminal?

答:
As I explained here, most of the git commands do their output on stderr, not stdout.

stderr is just informative messages, not to be consumed by machines.

That means, as commented, that you need to redirect stderr to /dev/null: 2>

The OP however comments that:

&> should have redirect both outputs to /dev/null

[It] was an error of mine, I didn't see a tar czvf that I have in the shell script that was generate the output.

Body:
I'm trying that git push don't show the output.

I try with --quiet option and redirection to /dev/null like that:

git push origin master &>/dev/null

But Git still shows all files of the repo when a make a push like that:

Username for 'https://github.com': n0zg
Password for 'https://n0zg@github.com':
test.html
888.html
9991.html
999.html
index.html
css/
css/stylesheet.css
highlight/
highlight/README.md
highlight/LICENSE
highlight/CHANGES.md
highlight/README.ru.md
highlight/styles/
highlight/styles/ir-black.css
....

How can I make that git push don't show all files in the repo on the terminal?


问:
Is there a C# library that allows you to query mp3 duration and bitrate
I'm looking for an open source library (BSD/MIT style license) that allows me to extract the bitrate and duration of a MP3 audio file in dot net.

Any takers?

答: There is a wrapper for mpg123 on sourceforge. I have never used it but from the description it looks like what you are looking for. Or the source can help you out.</p>


问:
How to get unicode code point(s) representation of character/string in Swift?
As a generic solution, how can we get the unicode code point/s for a character or a string in Swift?

Consider the following:

```<code>let A: Character = "A"     // "\u{0041}"
let Á: Character = "Á"     // "\u{0041}\u{0301}"

let sparklingHeart = ""  // "\u{1F496}"
let SWIFT = "SWIFT"        // "\u{0053}\u{0057}\u{0049}\u{0046}\u{0054}"
</code>```

If I am not mistaking, the desired function might return an array of strings, for instance:

```<code>extension Character {
    func getUnicodeCodePoints() -> [String] {
        //...
    }
}

A.getUnicodeCodePoints()
// the output should be: ["\u{0041}"]

Á.getUnicodeCodePoints()
// the output should be: ["\u{0041}", "\u{0301}"]

sparklingHeart.getUnicodeCodePoints()
// the output should be: ["\u{1F496}"]

SWIFT.getUnicodeCodePoints()
// the output should be: ["\u{0053}", "\u{0057}", "\u{0049}", "\u{0046}", "\u{0054}"]
</code>```

Any more suggested elegant approach would be appreciated.

答:
Generally, the unicodeScalars property of a String returns a collection
of its unicode scalar values. (A Unicode scalar value is any
Unicode code point except high-surrogate and low-surrogate code points.)

Example:

```<code>print(Array("Á".unicodeScalars))  // ["A", "\u{0301}"]
print(Array("".unicodeScalars)) // ["\u{0001F496}"]
</code>```

Up to Swift 3 there is no way to access
the unicode scalar values of a Character directly, it has to be
converted to a String first (for the Swift 4 status, see below).

If you want to see all Unicode scalar values as hexadecimal numbers
then you can access the value property (which is a UInt32 number)
and format it according to your needs.

Example (using the U+NNNN notation for Unicode values):

```<code>extension String {
    func getUnicodeCodePoints() -> [String] {
        return unicodeScalars.map { "U+" + String($0.value, radix: 16, uppercase: true) }
    }
}

extension Character {
    func getUnicodeCodePoints() -> [String] {
        return String(self).getUnicodeCodePoints()
    }
}

print("A".getUnicodeCodePoints())     // ["U+41"]
print("Á".getUnicodeCodePoints())     // ["U+41", "U+301"]
print("".getUnicodeCodePoints())    // ["U+1F496"]
print("SWIFT".getUnicodeCodePoints()) // ["U+53", "U+57", "U+49", "U+46", "U+54"]
print("".getUnicodeCodePoints())    // ["U+1F1EF", "U+1F1F4"]
</code>```

Update for Swift 4:

As of  Swift 4, the unicodeScalars of a Character can be
accessed directly,
see SE-0178 Add unicodeScalars property to Character. This makes the conversion to a String
obsolete:

```<code>let c: Character = ""
print(Array(c.unicodeScalars)) // ["\u{0001F1EF}", "\u{0001F1F4}"]
</code>```

Body:
As a generic solution, how can we get the unicode code point/s for a character or a string in Swift?

Consider the following:

let A: Character = "A"     // "\u{0041}"
let Á: Character = "Á"     // "\u{0041}\u{0301}"

let sparklingHeart = ""  // "\u{1F496}"
let SWIFT = "SWIFT"        // "\u{0053}\u{0057}\u{0049}\u{0046}\u{0054}"

If I am not mistaking, the desired function might return an array of strings, for instance:

extension Character {
    func getUnicodeCodePoints() -> [String] {
        //...
    }
}

A.getUnicodeCodePoints()
// the output should be: ["\u{0041}"]

Á.getUnicodeCodePoints()
// the output should be: ["\u{0041}", "\u{0301}"]

sparklingHeart.getUnicodeCodePoints()
// the output should be: ["\u{1F496}"]

SWIFT.getUnicodeCodePoints()
// the output should be: ["\u{0053}", "\u{0057}", "\u{0049}", "\u{0046}", "\u{0054}"]

Any more suggested elegant approach would be appreciated.

Body:
Generally, the unicodeScalars property of a String returns a collection
of its unicode scalar values. (A Unicode scalar value is any
Unicode code point except high-surrogate and low-surrogate code points.)

Example:

print(Array("Á".unicodeScalars))  // ["A", "\u{0301}"]
print(Array("".unicodeScalars)) // ["\u{0001F496}"]

Up to Swift 3 there is no way to access
the unicode scalar values of a Character directly, it has to be
converted to a String first (for the Swift 4 status, see below).

If you want to see all Unicode scalar values as hexadecimal numbers
then you can access the value property (which is a UInt32 number)
and format it according to your needs.

Example (using the U+NNNN notation for Unicode values):

extension String {
    func getUnicodeCodePoints() -> [String] {
        return unicodeScalars.map { "U+" + String($0.value, radix: 16, uppercase: true) }
    }
}

extension Character {
    func getUnicodeCodePoints() -> [String] {
        return String(self).getUnicodeCodePoints()
    }
}

print("A".getUnicodeCodePoints())     // ["U+41"]
print("Á".getUnicodeCodePoints())     // ["U+41", "U+301"]
print("".getUnicodeCodePoints())    // ["U+1F496"]
print("SWIFT".getUnicodeCodePoints()) // ["U+53", "U+57", "U+49", "U+46", "U+54"]
print("".getUnicodeCodePoints())    // ["U+1F1EF", "U+1F1F4"]

Update for Swift 4:

As of  Swift 4, the unicodeScalars of a Character can be
accessed directly,
see SE-0178 Add unicodeScalars property to Character. This makes the conversion to a String
obsolete:

let c: Character = ""
print(Array(c.unicodeScalars)) // ["\u{0001F1EF}", "\u{0001F1F4}"]


问:
Swift: show name in ViewController
I have array with names in TableViewController and I have ViewController. If I click on cell in TableViewController I want to show name from array in ViewController navigation bar title. How to do it?

答:
If you are using Storyboard, and want to navigate and pass "title" to the SecondViewController:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let name = YOUR_ARRAY[indexPath.row]

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let destinationVC = storyboard.instantiateViewController(withIdentifier: "YOUR_SECOND_VIEW_IDENTIFIER") as? SecondViewController else { return}
    destinationVC.title = name
    navigationController?.pushViewController(destinationVC, animated: true)
}
</code>```

If you use Interface Builder

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let name = YOUR_ARRAY[indexPath.row]

    let destinationVC = SecondViewController(nibName: "YOUR_SECOND_VIEW_NAME", bundle: nil)
    destinationVC.title = name
    navigationController?.pushViewController(destinationVC, animated: true)
}
</code>```

Title: Swift: show name in ViewController

Body:
If you are using Storyboard, and want to navigate and pass "title" to the SecondViewController:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let name = YOUR_ARRAY[indexPath.row]

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let destinationVC = storyboard.instantiateViewController(withIdentifier: "YOUR_SECOND_VIEW_IDENTIFIER") as? SecondViewController else { return}
    destinationVC.title = name
    navigationController?.pushViewController(destinationVC, animated: true)
}

If you use Interface Builder

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let name = YOUR_ARRAY[indexPath.row]

    let destinationVC = SecondViewController(nibName: "YOUR_SECOND_VIEW_NAME", bundle: nil)
    destinationVC.title = name
    navigationController?.pushViewController(destinationVC, animated: true)
}


问:
How to pause notifications of an observableArray?
Scenario:

I'm creating a long-running web app built on knockout.js where i need to load several times different data for my viewmodels.

To improve performace and avoid unnecessary updates, i need during the update of my viewmodels to temporarily avoid the normal dependency tracking chain for my observables and observablearrays as well.
After the loading of the new data is completed, i can safely restore the normal ko dependency tracking.

To pause observables i'm using the withPausing function of the great RP Niemeyer described here: Change observable but don't notify subscribers in knockout.js.

Is there any way to temporarily ignore the removal and insertion also in a observablearray?

答:
Inspired by implementation of pauseableComputed and observable withPausing I have created pauseableObservable and pauseableObservableArray that have abilities to stop notifications to subscribers and than resume when needed. Also it work recursively for all nested pauseable properties.

You can play with it HERE on Codepen.

PauseableObservable:

```<code>// PauseableObservable - it's observable that have functions to 'pause' and 'resume' notifications to subscribers (pause/resume work recursive for all pauseable child).

ko.isPauseableObservable = function(instance) {
    return ko.isObservable(instance) && instance.hasOwnProperty("pause");
}

ko.pauseableObservable = function(value) {
    var that = ko.observable(value);

    function getPauseableChildren() {
        var currentValue = that();
        var properties = Object.getOwnPropertyNames(currentValue);
        var pauseables = properties.filter((property) => {
            return ko.isPauseableObservable(currentValue[property]);
        });
        return pauseables.map((property) => {
            return currentValue[property];
        });
    }

    that.pauseNotifications = false;
    that.isDirty = false;

    that.notifySubscribers = function() {
        if (!that.pauseNotifications) {
            ko.subscribable.fn.notifySubscribers.apply(that, arguments);
        }
        that.isDirty = that.pauseNotifications;
    };

    that.pause = function() {
        that.pauseNotifications = true;
        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child) => { child.pause(); });
    }

    that.resume = function() {
        that.pauseNotifications = false;

        if (that.isDirty) {
            that.valueHasMutated();
        }

        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child)=> { child.resume(); });
    }

    return that;
}
</code>```

PauseableObservableArray

```<code>// PauseableObservableArray - it's observable array that have functions to 'pause' and 'resume' notifications to subscribers about add/remove items.
// In case if array items pauseable observables - run recursively run 'pause'/'resume' on them.

ko.pauseableObservableArray = function(items) {
    var that = ko.observableArray(items);

    that.pauseNotifications = false;
    that.isDirty = false;
    that.lastNotification = [];

    that.notifySubscribers = function() {
        if (!that.pauseNotifications) {
            ko.subscribable.fn.notifySubscribers.apply(that, arguments);
        } else {
            that.lastNotification = arguments;
        }
        that.isDirty = that.pauseNotifications;
    };

    that.pause = function () {
        var items = that();
        that.pauseNotifications = true;
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.pause();
            }
        });
    }

    that.resume = function () {
        var items = that();
        that.pauseNotifications = false;

        if(that.isDirty) {
            ko.subscribable.fn.notifySubscribers.apply(that, that.lastArguments);
        }
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.resume();
            }
        });
    }

    that.refresh = function () {
        that.resume();
        that.pause();
    }

    return that;
}
</code>```

Usage example:

```<code>var firstItem = ko.pauseableObservable("Hello");
var secondItem = ko.pauseableObservable("World");
var items = [
    firstItem,
    secondItem
];
var array = ko.pauseableObservable(items);

// Stop notifications from specific observable
firstItem.pause();
// Change won't raise notification to subscribers
firstItem("Hi");
// Resume notifications
firstItem.resume();

// Stop notifications from all items of array
array.pause();
// Change won't raise notification to subscribers
array.push("Hey");
array()[0]("Hi");
// Resume notifications
array.resume();
</code>```

Body:
Inspired by implementation of pauseableComputed and observable withPausing I have created pauseableObservable and pauseableObservableArray that have abilities to stop notifications to subscribers and than resume when needed. Also it work recursively for all nested pauseable properties.

You can play with it HERE on Codepen.

PauseableObservable:

// PauseableObservable - it's observable that have functions to 'pause' and 'resume' notifications to subscribers (pause/resume work recursive for all pauseable child).

ko.isPauseableObservable = function(instance) {
    return ko.isObservable(instance) && instance.hasOwnProperty("pause");
}

ko.pauseableObservable = function(value) {
    var that = ko.observable(value);

    function getPauseableChildren() {
        var currentValue = that();
        var properties = Object.getOwnPropertyNames(currentValue);
        var pauseables = properties.filter((property) => {
            return ko.isPauseableObservable(currentValue[property]);
        });
        return pauseables.map((property) => {
            return currentValue[property];
        });
    }

    that.pauseNotifications = false;
    that.isDirty = false;

    that.notifySubscribers = function() {
        if (!that.pauseNotifications) {
            ko.subscribable.fn.notifySubscribers.apply(that, arguments);
        }
        that.isDirty = that.pauseNotifications;
    };

    that.pause = function() {
        that.pauseNotifications = true;
        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child) => { child.pause(); });
    }

    that.resume = function() {
        that.pauseNotifications = false;

        if (that.isDirty) {
            that.valueHasMutated();
        }

        var pauseableChildren = getPauseableChildren();
        pauseableChildren.forEach((child)=> { child.resume(); });
    }

    return that;
}

PauseableObservableArray

// PauseableObservableArray - it's observable array that have functions to 'pause' and 'resume' notifications to subscribers about add/remove items.
// In case if array items pauseable observables - run recursively run 'pause'/'resume' on them.

ko.pauseableObservableArray = function(items) {
    var that = ko.observableArray(items);

    that.pauseNotifications = false;
    that.isDirty = false;
    that.lastNotification = [];

    that.notifySubscribers = function() {
        if (!that.pauseNotifications) {
            ko.subscribable.fn.notifySubscribers.apply(that, arguments);
        } else {
            that.lastNotification = arguments;
        }
        that.isDirty = that.pauseNotifications;
    };

    that.pause = function () {
        var items = that();
        that.pauseNotifications = true;
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.pause();
            }
        });
    }

    that.resume = function () {
        var items = that();
        that.pauseNotifications = false;

        if(that.isDirty) {
            ko.subscribable.fn.notifySubscribers.apply(that, that.lastArguments);
        }
        items.forEach(function(item) {
            if(ko.isPauseableObservable(item)) {
                item.resume();
            }
        });
    }

    that.refresh = function () {
        that.resume();
        that.pause();
    }

    return that;
}

Usage example:

var firstItem = ko.pauseableObservable("Hello");
var secondItem = ko.pauseableObservable("World");
var items = [
    firstItem,
    secondItem
];
var array = ko.pauseableObservable(items);

// Stop notifications from specific observable
firstItem.pause();
// Change won't raise notification to subscribers
firstItem("Hi");
// Resume notifications
firstItem.resume();

// Stop notifications from all items of array
array.pause();
// Change won't raise notification to subscribers
array.push("Hey");
array()[0]("Hi");
// Resume notifications
array.resume();


问:
SecurityException Running on Android with S8 Phone
I get the following exception when running on the new Samsung Galaxy 8 phones. The exception doesn't give me any information about what's causing it (as far as I can tell). I don't have an S8 phone to try to pinpoint the line of offending code.

Does anybody have any idea what the problem is or how to figure it out?

TIA

```<code>java.lang.SecurityException:
at android.app.ContextImpl.checkMode(ContextImpl.java:2323)
at android.app.ContextImpl.openFileOutput(ContextImpl.java:534)
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:192)
at com.yandex.metrica.impl.o.c(SourceFile:178)
at com.yandex.metrica.impl.o.a(SourceFile:44)
at com.yandex.metrica.impl.o$a.a(SourceFile:310)
at com.yandex.metrica.impl.o.b(SourceFile:164)
at com.yandex.metrica.impl.bh.c(SourceFile:139)
at com.yandex.metrica.impl.ag.c(SourceFile:145)
at com.yandex.metrica.impl.ag$a.run(SourceFile:295)
at com.yandex.metrica.impl.ob.bh.execute(SourceFile:10)
at com.yandex.metrica.impl.ob.bj.execute(SourceFile:7)
at com.yandex.metrica.impl.ag.run(SourceFile:86)
</code>```

答:
It might be due to a lack of permission.

Have you obtained storage permissions?

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Depending on the Android SDK that you are targeting, you might need to request the permission at runtime.

https://developer.android.com/training/basics/data-storage/files.html

Body:
I get the following exception when running on the new Samsung Galaxy 8 phones. The exception doesn't give me any information about what's causing it (as far as I can tell). I don't have an S8 phone to try to pinpoint the line of offending code.

Does anybody have any idea what the problem is or how to figure it out?

TIA

java.lang.SecurityException:
at android.app.ContextImpl.checkMode(ContextImpl.java:2323)
at android.app.ContextImpl.openFileOutput(ContextImpl.java:534)
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:192)
at com.yandex.metrica.impl.o.c(SourceFile:178)
at com.yandex.metrica.impl.o.a(SourceFile:44)
at com.yandex.metrica.impl.o$a.a(SourceFile:310)
at com.yandex.metrica.impl.o.b(SourceFile:164)
at com.yandex.metrica.impl.bh.c(SourceFile:139)
at com.yandex.metrica.impl.ag.c(SourceFile:145)
at com.yandex.metrica.impl.ag$a.run(SourceFile:295)
at com.yandex.metrica.impl.ob.bh.execute(SourceFile:10)
at com.yandex.metrica.impl.ob.bj.execute(SourceFile:7)
at com.yandex.metrica.impl.ag.run(SourceFile:86)

Body:
It might be due to a lack of permission.

Have you obtained storage permissions?

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Depending on the Android SDK that you are targeting, you might need to request the permission at runtime.

https://developer.android.com/training/basics/data-storage/files.html


问:
how to return number as float number es6
Well, im trying to return all my number in a specific format

```<code>Number(parseFloat(number).toFixed(fractionalDigits || 2))
</code>```

this  works fine but in some cases fails,  here are some result

1.111 returns "1.11" and after converting it to number it will be returned 1.11
 as float which is right,
but 2.2 returns "2.20" and after converting it to number it will be 2.2  i need it to be 2.20 as float

100 returns "100.00" because of toFixed Function and after converting it to number it back to 100 i need it 100.00 but as float

how can i do that ?

答:
For the result you want remove fractionDigits from parameter and remove the las should work

```<code>parseFloat(number).toFixed(2)
</code>```

the external Number() was not required as you already parsed number as float.Hope it helps

what was happening was the Number function was removing unnecessary 0 that the toFixed was putting in.

Body:
Well, im trying to return all my number in a specific format

Number(parseFloat(number).toFixed(fractionalDigits || 2))

this  works fine but in some cases fails,  here are some result

1.111 returns "1.11" and after converting it to number it will be returned 1.11
 as float which is right,
but 2.2 returns "2.20" and after converting it to number it will be 2.2  i need it to be 2.20 as float

100 returns "100.00" because of toFixed Function and after converting it to number it back to 100 i need it 100.00 but as float

how can i do that ?

Body:
For the result you want remove fractionDigits from parameter and remove the las should work

parseFloat(number).toFixed(2)

the external Number() was not required as you already parsed number as float.Hope it helps

what was happening was the Number function was removing unnecessary 0 that the toFixed was putting in.


问:
C recursive program to find the maximum element from array
So I have a task in my training that sounds like this:
Write a subprogram that will recursively find the maximum element from an array and also write the main function to call it.
What I failed to fully understand is what recursion is. I wanted to ask you guys if my code is recursive or not. And if not what changes should I make/ what recursion really means?

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

int find_maximum(int[], int);

int main() {
  int c, array[100], size, location, maximum;

  printf("Input number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  location = find_maximum(array, size);
  maximum  = array[location];

  printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
  return 0;
}

int find_maximum(int a[], int n) {
  int c, max, index;

  max = a[0];
  index = 0;

  for (c = 1; c < n; c++) {
    if (a[c] > max) {
       index = c;
       max = a[c];
    }
  }

  return index;
}
</code>```

Thank you all for your time!

答:
No, your program is certainly not recursive. As the definition, recursive function must call itself with a terminating condition.

Please read TutorialsPoint about recursion in C.

Update on @JonathanLeffler's comment:
Please note that the output in the reference will overflow.

Body:
So I have a task in my training that sounds like this:
Write a subprogram that will recursively find the maximum element from an array and also write the main function to call it.
What I failed to fully understand is what recursion is. I wanted to ask you guys if my code is recursive or not. And if not what changes should I make/ what recursion really means?

#include <stdio.h>

int find_maximum(int[], int);

int main() {
  int c, array[100], size, location, maximum;

  printf("Input number of elements in array\n");
  scanf("%d", &size);

  printf("Enter %d integers\n", size);

  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);

  location = find_maximum(array, size);
  maximum  = array[location];

  printf("Maximum element location = %d and value = %d.\n", location + 1, maximum);
  return 0;
}

int find_maximum(int a[], int n) {
  int c, max, index;

  max = a[0];
  index = 0;

  for (c = 1; c < n; c++) {
    if (a[c] > max) {
       index = c;
       max = a[c];
    }
  }

  return index;
}

Thank you all for your time!


问:
How to fetch all news article urls?
I can easily scrape all news article from websites in which articles' urls are organized in this way: http://samplenewsagency.com/en/news/12563. Just one should generate some numbers and replace with 12563 to find another piece of news.
But what can be done for websites like http://gcaptain.com which organize their news in this way: http://gcaptain.com/chinese-aircraft-carrier-sails-hong-kong-maiden-visit/.
How can I find all news urls?

答:
After inspecting the given web site gcaptain.com, the easiest way to go seems to be creating spider based on CrawlSpider class and using rules to specify which links to follow. Here's the simplest example:

```<code># -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class GcaptainSpider(CrawlSpider):
    name = 'gcaptain'
    allowed_domains = ['gcaptain.com']
    start_urls = ['http://gcaptain.com/']

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//article//h2/a'), callback='parse_article', follow=True),
    )

    def parse_article(self, response):
        item = {}
        item['title'] = response.xpath('//article//header/h1/text()').extract_first()
        return item
</code>```

It assumes all links to news articles can be found using XPath expression //article//h2/a and extracts just titles from the articles. This example won't give you all articles as the web site is using infinite scrolling mechanism, which you would have to take into account to load all news. How to do this can be read for example in this Scrapinghub blog post.

Title: How to fetch all news article urls?

Body:
After inspecting the given web site gcaptain.com, the easiest way to go seems to be creating spider based on CrawlSpider class and using rules to specify which links to follow. Here's the simplest example:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class GcaptainSpider(CrawlSpider):
    name = 'gcaptain'
    allowed_domains = ['gcaptain.com']
    start_urls = ['http://gcaptain.com/']

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//article//h2/a'), callback='parse_article', follow=True),
    )

    def parse_article(self, response):
        item = {}
        item['title'] = response.xpath('//article//header/h1/text()').extract_first()
        return item

It assumes all links to news articles can be found using XPath expression //article//h2/a and extracts just titles from the articles. This example won't give you all articles as the web site is using infinite scrolling mechanism, which you would have to take into account to load all news. How to do this can be read for example in this Scrapinghub blog post.


问:
Is there a way I can get an Enum value by its number in the sequence?
I have this enum:

```<code>public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}
</code>```

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

```<code>if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);
</code>```

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

```<code><Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>
</code>```

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

答:
You are trying to get the index of the Enum value.

```<code>// Below code sample how to find the index of Enum.
// Sample to show how to find the index of item
PTI p = PTI.Ten;
int index = Array.IndexOf(Enum.GetValues(p.GetType()), p);
Console.WriteLine(index); // Output: 2 because of value PTI.Ten
</code>```

So, finally solution for you to replace all if statements with just one statement.

```<code>PTI pti = (PTI)(Enum.GetValues(typeof(PTI))).GetValue(selectedIndex-1); // selectedIndex-1 because the index is 0 based.
App.DB.UpdateSetting(Settings.Pti, pti);
</code>```

Body:
I have this enum:

public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

<Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

Body:
You are trying to get the index of the Enum value.

// Below code sample how to find the index of Enum.
// Sample to show how to find the index of item
PTI p = PTI.Ten;
int index = Array.IndexOf(Enum.GetValues(p.GetType()), p);
Console.WriteLine(index); // Output: 2 because of value PTI.Ten

So, finally solution for you to replace all if statements with just one statement.

PTI pti = (PTI)(Enum.GetValues(typeof(PTI))).GetValue(selectedIndex-1); // selectedIndex-1 because the index is 0 based.
App.DB.UpdateSetting(Settings.Pti, pti);


答:
No, your code does not use recursion. Recursion is when a function calls itself, or calls another function which leads to a call to itself again.

You can change your code like this to have a recursive, stateless function that can determine the maximum value of the array.

```<code>int find_maximum(int a[], int n) {
   return find_maximum_r(a, 0, n);
}

int find_maximum_r(int a[], int index, int n) {
  if (index + 1 == n) {
    return a[index];
  }

  int maxRight = find_maximum_r(a, index + 1, n);
  return a[index] > maxRight ? a[index] : maxRight;
}
</code>```

Title: C recursive program to find the maximum element from array

Body:
No, your code does not use recursion. Recursion is when a function calls itself, or calls another function which leads to a call to itself again.

You can change your code like this to have a recursive, stateless function that can determine the maximum value of the array.

int find_maximum(int a[], int n) {
   return find_maximum_r(a, 0, n);
}

int find_maximum_r(int a[], int index, int n) {
  if (index + 1 == n) {
    return a[index];
  }

  int maxRight = find_maximum_r(a, index + 1, n);
  return a[index] > maxRight ? a[index] : maxRight;
}


问:
Is it advisable to upload files as parameter of Parse Cloud Code function?
I want to upload videos to parse server. Instead of saving the video file with the Parse iOS SDK's PFFile I upload the video to Parse Cloud Code as parameter:

```<code>PFCloud.callFunction(inBackground: "uploadVideo", withParameters: ["videoData": videoData]]) { (response, error) in
    ...
}
</code>```

On the server side I save the file:

```<code>Parse.Cloud.define("uploadVideo", function(request, response) {

    var videoData = request.params.videoData;
    var videoFile = new Parse.File("video.mov", videoData, "video/mov");

    videoFile.save(null, {useMasterKey: true})
    .then(
        function() {
            response.success();
        },
        function(error) {
            response.error(error.message);
        }
    );
});
</code>```

Is that good practice or are there any risks involved?
E.g. what is the maximum data object size to be passed as Cloud Code parameter?

答:
I decided to upload the file with PFFile and send the file object to the Cloud Code function as parameter. Unlike PfObject which cannot be passed as Cloud Code function parameter, PFFile can.

The advantage is that PFFile has an upload progress callback to give an upload status feedback to the user.

Body:
I want to upload videos to parse server. Instead of saving the video file with the Parse iOS SDK's PFFile I upload the video to Parse Cloud Code as parameter:

PFCloud.callFunction(inBackground: "uploadVideo", withParameters: ["videoData": videoData]]) { (response, error) in
    ...
}

On the server side I save the file:

Parse.Cloud.define("uploadVideo", function(request, response) {

    var videoData = request.params.videoData;
    var videoFile = new Parse.File("video.mov", videoData, "video/mov");

    videoFile.save(null, {useMasterKey: true})
    .then(
        function() {
            response.success();
        },
        function(error) {
            response.error(error.message);
        }
    );
});

Is that good practice or are there any risks involved?
E.g. what is the maximum data object size to be passed as Cloud Code parameter?


问:
Why is my consumer reading all messages from the topic each time, even when auto.offset.reset=largest?
I have produced 5 messages to Kafka on topic1 and consumed them successfully. When I sent 6th message and trying to consume, I am getting all 6 messages again instead of the latest(6th) message.

Please note I am running consumer command line, rather from a database connector(access module). And the connector has the config property auto.offset.reset set to "largest".(please see all the config properties from log below)

Also please see the OffsetChecker output below:

```<code>bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker \
    --group testjob --zookeeper localhost:2181 --topic topic1

[2017-07-06 21:57:46,707] WARN WARNING: ConsumerOffsetChecker is deprecated and will be dropped in releases following 0.9.0. Use ConsumerGroupCommand instead. (kafka.tools.ConsumerOffsetChecker$)
Exiting due to: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /consumers/testjob/offsets/topic1/0.
</code>```

Could anyone please let me know where the problem is?

Here is the log that shows config properties:

```<code>***Global config Properties***
*             client.id = rdkafka
*             message.max.bytes = 1200
*             receive.message.max.bytes = 100000000
*             metadata.request.timeout.ms = 60000
*             topic.metadata.refresh.interval.ms = 600000
*             topic.metadata.refresh.fast.cnt = 10
*             topic.metadata.refresh.fast.interval.ms = 250
*             topic.metadata.refresh.sparse = false
*             socket.timeout.ms = 60000
*             socket.send.buffer.bytes = 0
*             socket.receive.buffer.bytes = 0
*             socket.keepalive.enable = false
*             socket.max.fails = 3
*             broker.address.ttl = 300000
*             broker.address.family = any
*             statistics.interval.ms = 0
*             log_cb = 0x7fecb80c6dd0
*             log_level = 6
*             socket_cb = 0x7fecb80cd2f0
*             open_cb = 0x7fecb80ddd30
*             opaque = 0x2641280
*             internal.termination.signal = 0
*             queued.min.messages = 100000
*             queued.max.messages.kbytes = 1000000
*             fetch.wait.max.ms = 100
*             fetch.message.max.bytes = 1049776
*             fetch.min.bytes = 1
*             fetch.error.backoff.ms = 500
*             group.id = testjob
*             queue.buffering.max.messages = 100000
*             queue.buffering.max.ms = 1000
*             message.send.max.retries = 2
*             retry.backoff.ms = 100
*             compression.codec = none
*             batch.num.messages = 1000
*             delivery.report.only.error = false
*             request.required.acks = 1
*             enforce.isr.cnt = 0
*             request.timeout.ms = 5000
*             message.timeout.ms = 300000
*             produce.offset.report = false
*             auto.commit.enable = true
*             auto.commit.interval.ms = 60000
*             auto.offset.reset = largest    <<<<--------
*             offset.store.path = .
*             offset.store.sync.interval.ms = 0
*             offset.store.method = file
*             consume.callback.max.messages = 0
</code>```

答:
Add this properties
AUTO_OFFSET_RESET_CONFIG="earliest" it will work</p>

Body:
I have produced 5 messages to Kafka on topic1 and consumed them successfully. When I sent 6th message and trying to consume, I am getting all 6 messages again instead of the latest(6th) message.

Please note I am running consumer command line, rather from a database connector(access module). And the connector has the config property auto.offset.reset set to "largest".(please see all the config properties from log below)

Also please see the OffsetChecker output below:

bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker \
    --group testjob --zookeeper localhost:2181 --topic topic1

[2017-07-06 21:57:46,707] WARN WARNING: ConsumerOffsetChecker is deprecated and will be dropped in releases following 0.9.0. Use ConsumerGroupCommand instead. (kafka.tools.ConsumerOffsetChecker$)
Exiting due to: org.apache.zookeeper.KeeperException$NoNodeException: KeeperErrorCode = NoNode for /consumers/testjob/offsets/topic1/0.

Could anyone please let me know where the problem is?

Here is the log that shows config properties:

***Global config Properties***
*             client.id = rdkafka
*             message.max.bytes = 1200
*             receive.message.max.bytes = 100000000
*             metadata.request.timeout.ms = 60000
*             topic.metadata.refresh.interval.ms = 600000
*             topic.metadata.refresh.fast.cnt = 10
*             topic.metadata.refresh.fast.interval.ms = 250
*             topic.metadata.refresh.sparse = false
*             socket.timeout.ms = 60000
*             socket.send.buffer.bytes = 0
*             socket.receive.buffer.bytes = 0
*             socket.keepalive.enable = false
*             socket.max.fails = 3
*             broker.address.ttl = 300000
*             broker.address.family = any
*             statistics.interval.ms = 0
*             log_cb = 0x7fecb80c6dd0
*             log_level = 6
*             socket_cb = 0x7fecb80cd2f0
*             open_cb = 0x7fecb80ddd30
*             opaque = 0x2641280
*             internal.termination.signal = 0
*             queued.min.messages = 100000
*             queued.max.messages.kbytes = 1000000
*             fetch.wait.max.ms = 100
*             fetch.message.max.bytes = 1049776
*             fetch.min.bytes = 1
*             fetch.error.backoff.ms = 500
*             group.id = testjob
*             queue.buffering.max.messages = 100000
*             queue.buffering.max.ms = 1000
*             message.send.max.retries = 2
*             retry.backoff.ms = 100
*             compression.codec = none
*             batch.num.messages = 1000
*             delivery.report.only.error = false
*             request.required.acks = 1
*             enforce.isr.cnt = 0
*             request.timeout.ms = 5000
*             message.timeout.ms = 300000
*             produce.offset.report = false
*             auto.commit.enable = true
*             auto.commit.interval.ms = 60000
*             auto.offset.reset = largest    <<<<--------
*             offset.store.path = .
*             offset.store.sync.interval.ms = 0
*             offset.store.method = file
*             consume.callback.max.messages = 0


问:
Cannot overwrite Django authentication templates in AWS
I have developped a Django application and I have been using the django-authtools module to be able to login using email. It is working great on my laptop but when I tried to deploy it in production in AWS using Beanstalk, it seems Django does not recognize the overwrite of the authentication module and is forcing redirection to the django built-in authentication module. Everything else seems to work fine (from a deployment and application point of view).
It results in a 500 error:

```<code>xxx.xxx.xxx.xxx (-) - - [04/Jul/2017:19:07:54 +1000] "GET /accounts/login/ HTTP/1.1" 500 7807 "http://<removed>.ap-southeast-2.elasticbeanstalk.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"

    Internal Server Error: /accounts/login/
    Traceback (most recent call last):
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner
        response = get_response(request)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 217, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 215, in _get_response
        response = response.render()
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 107, in render
        self.content = self.rendered_content
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 82, in rendered_content
        template = self.resolve_template(self.template_name)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 64, in resolve_template
        return select_template(template, using=self.using)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/loader.py", line 53, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: registration/login.html
</code>```

Again this is working perfectly fine on my laptop, but not on the AWS server. I cannot find any difference between the 2 and they are running same version of django and django-authools:

```<code>$ pip freeze

[...]
Django==1.11.2
django-authtools==1.5.0
django-extensions==1.7.6
django-phonenumber-field==1.3.0
django-qsstats-magic==0.7.2
django-simple-captcha==0.5.5
django-storages==1.6.1
[...]
</code>```

The only difference seems to be the version of python, 3.4.3 on AWS and 3.5.2 on my laptop.

On the server, my settings.py file is the same as on my laptop:

myproject/settings.py:

```<code>INSTALLED_APPS = [
    'myapp.apps.MyappConfig',
    'authtools',
    'captcha',
    'storages',
    'phonenumber_field',
    'django_extensions',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTH_USER_MODEL = "authtools.User"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
</code>```

},
]

myapp/urls.py:

```<code>from authtools import urls
[...]
    url(r'^accounts/', include('authtools.urls')),
[...]
</code>```

authtools/url.py:

```<code>from django.conf.urls import url
from authtools import views as authools_views

urlpatterns = [
    url(r'^login/$', authools_views.LoginView.as_view(), name='login'),
    url(r'^logout/$', authools_views.LogoutView.as_view(), {'next_page': '/accounts/login'}, name='logout'),
    url(r'^password_change/$', authools_views.PasswordChangeView.as_view(), name='password_change'),
    url(r'^password_change/done/$', authools_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
    url(r'^password_reset/$', authools_views.PasswordResetView.as_view(), name='password_reset'),
    url(r'^password_reset/done/$', authools_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
    url(r'^reset/done/$', authools_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
    url(r'^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        authools_views.PasswordResetConfirmView.as_view()),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        authools_views.PasswordResetConfirmView.as_view(),
        name='password_reset_confirm'),
]
</code>```

I have also tried to pass the template in the url statement directly (LoginView.as_view(template_name='myapp/login.html')) but same result.

Extract of authtools/view.py:

```<code>class LoginView(AuthDecoratorsMixin, WithCurrentSiteMixin, WithNextUrlMixin, FormView):
    print('ENTERING LOGIN VIEW')
    form_class = AuthenticationForm
    template_name = 'myapp/login.html'
    allow_authenticated = True
    success_url = resolve_url_lazy(settings.LOGIN_REDIRECT_URL)

    # BBB: This is deprecated (See LoginView.get_allow_authenticated)
    disallow_authenticated = None
</code>```

The template showed in the error "registration/login.html" is the built-in template and not the one provided by the authtools module which should overwrite it.
Also when navigating to the /admin/ of my website, I can login correctly with my super user and when going back to the site I am then detected as being authenticated. The logout action though redirects me to the default logout page and is not using my custom template provided in the authtools module (so same behavior).

If any one would have a solution or any idea of where to investigate that would be greatly appreciated!

Thanks!

I am adding my beanstalk config file just in case it helps, even though I don't believe this is a problem related to beanstalk itself.

```<code>.ebextensions# cat 001_set_env.config
option_settings:
  "aws:elasticbeanstalk:application:environment":
    PYTHONPATH: /opt/python/current/app/myapp:/opt/python/current/app/authtools:$PYTHONPATH
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "myproject/wsgi.py"
.ebextensions# cat 002_deploy.config
commands:
  01_update_pip:
    command: "/opt/python/run/venv/bin/pip install --upgrade pip"
  02_set_time_zone:
    command: ln -f -s /usr/share/zoneinfo/Australia/Sydney /etc/localtime

container_commands:
  01_makemigration:
    command: "source /opt/python/run/venv/bin/activate && python manage.py makemigrations --noinput"
    leader_only: true
  02_migrate:
    command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput"
    leader_only: true
  03_initialize_db:
    command: "source /opt/python/run/venv/bin/activate && python manage.py initializedb"
    leader_only: true
  04_create_superuser:
    command: "source /opt/python/run/venv/bin/activate && python manage.py createsu"
    leader_only: true
</code>```

答:
I suggest you stop editing the code in authtools. It is not clear how you are doing it, and since the error is showing the missing template is registration/login.html, it is now working in production.

If you rename your template from myapp/templates/myapp/login.html to myapp/templates/registration/login.html, then the app directories loader should find your template.

Finally, as an aside, your DIRS setting looks incorrect.

```<code>'DIRS': ['templates'],
</code>```

If you want to include a myproject/templates directory, then change it to

```<code>'DIRS': [os.path.join(BASE_DIR, 'templates')]
</code>```

Body:
I have developped a Django application and I have been using the django-authtools module to be able to login using email. It is working great on my laptop but when I tried to deploy it in production in AWS using Beanstalk, it seems Django does not recognize the overwrite of the authentication module and is forcing redirection to the django built-in authentication module. Everything else seems to work fine (from a deployment and application point of view).
It results in a 500 error:

xxx.xxx.xxx.xxx (-) - - [04/Jul/2017:19:07:54 +1000] "GET /accounts/login/ HTTP/1.1" 500 7807 "http://<removed>.ap-southeast-2.elasticbeanstalk.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"

    Internal Server Error: /accounts/login/
    Traceback (most recent call last):
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner
        response = get_response(request)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 217, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 215, in _get_response
        response = response.render()
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 107, in render
        self.content = self.rendered_content
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 82, in rendered_content
        template = self.resolve_template(self.template_name)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 64, in resolve_template
        return select_template(template, using=self.using)
      File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/loader.py", line 53, in select_template
        raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
    django.template.exceptions.TemplateDoesNotExist: registration/login.html

Again this is working perfectly fine on my laptop, but not on the AWS server. I cannot find any difference between the 2 and they are running same version of django and django-authools:

$ pip freeze

[...]
Django==1.11.2
django-authtools==1.5.0
django-extensions==1.7.6
django-phonenumber-field==1.3.0
django-qsstats-magic==0.7.2
django-simple-captcha==0.5.5
django-storages==1.6.1
[...]

The only difference seems to be the version of python, 3.4.3 on AWS and 3.5.2 on my laptop.

On the server, my settings.py file is the same as on my laptop:

myproject/settings.py:

INSTALLED_APPS = [
    'myapp.apps.MyappConfig',
    'authtools',
    'captcha',
    'storages',
    'phonenumber_field',
    'django_extensions',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

AUTH_USER_MODEL = "authtools.User"

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },

},
]

myapp/urls.py:

from authtools import urls
[...]
    url(r'^accounts/', include('authtools.urls')),
[...]

authtools/url.py:

from django.conf.urls import url
from authtools import views as authools_views

urlpatterns = [
    url(r'^login/$', authools_views.LoginView.as_view(), name='login'),
    url(r'^logout/$', authools_views.LogoutView.as_view(), {'next_page': '/accounts/login'}, name='logout'),
    url(r'^password_change/$', authools_views.PasswordChangeView.as_view(), name='password_change'),
    url(r'^password_change/done/$', authools_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
    url(r'^password_reset/$', authools_views.PasswordResetView.as_view(), name='password_reset'),
    url(r'^password_reset/done/$', authools_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
    url(r'^reset/done/$', authools_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
    url(r'^reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        authools_views.PasswordResetConfirmView.as_view()),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        authools_views.PasswordResetConfirmView.as_view(),
        name='password_reset_confirm'),
]

I have also tried to pass the template in the url statement directly (LoginView.as_view(template_name='myapp/login.html')) but same result.

Extract of authtools/view.py:

class LoginView(AuthDecoratorsMixin, WithCurrentSiteMixin, WithNextUrlMixin, FormView):
    print('ENTERING LOGIN VIEW')
    form_class = AuthenticationForm
    template_name = 'myapp/login.html'
    allow_authenticated = True
    success_url = resolve_url_lazy(settings.LOGIN_REDIRECT_URL)

    # BBB: This is deprecated (See LoginView.get_allow_authenticated)
    disallow_authenticated = None

The template showed in the error "registration/login.html" is the built-in template and not the one provided by the authtools module which should overwrite it.
Also when navigating to the /admin/ of my website, I can login correctly with my super user and when going back to the site I am then detected as being authenticated. The logout action though redirects me to the default logout page and is not using my custom template provided in the authtools module (so same behavior).

If any one would have a solution or any idea of where to investigate that would be greatly appreciated!

Thanks!

I am adding my beanstalk config file just in case it helps, even though I don't believe this is a problem related to beanstalk itself.

.ebextensions# cat 001_set_env.config
option_settings:
  "aws:elasticbeanstalk:application:environment":
    PYTHONPATH: /opt/python/current/app/myapp:/opt/python/current/app/authtools:$PYTHONPATH
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "myproject/wsgi.py"
.ebextensions# cat 002_deploy.config
commands:
  01_update_pip:
    command: "/opt/python/run/venv/bin/pip install --upgrade pip"
  02_set_time_zone:
    command: ln -f -s /usr/share/zoneinfo/Australia/Sydney /etc/localtime

container_commands:
  01_makemigration:
    command: "source /opt/python/run/venv/bin/activate && python manage.py makemigrations --noinput"
    leader_only: true
  02_migrate:
    command: "source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput"
    leader_only: true
  03_initialize_db:
    command: "source /opt/python/run/venv/bin/activate && python manage.py initializedb"
    leader_only: true
  04_create_superuser:
    command: "source /opt/python/run/venv/bin/activate && python manage.py createsu"
    leader_only: true

Body:
I suggest you stop editing the code in authtools. It is not clear how you are doing it, and since the error is showing the missing template is registration/login.html, it is now working in production.

If you rename your template from myapp/templates/myapp/login.html to myapp/templates/registration/login.html, then the app directories loader should find your template.

Finally, as an aside, your DIRS setting looks incorrect.

'DIRS': ['templates'],

If you want to include a myproject/templates directory, then change it to

'DIRS': [os.path.join(BASE_DIR, 'templates')]


问:
Kademlia Implementation in Java
I want to setup a Kademlia network to connect peers and build a p2p network. I'm going to distribute processing power of nodes within the network. For network I found this Kademlia Java implemented Setup from git.   https://github.com/JoshuaKissoon/Kademlia

I want to know how to setup this and use to implement the network.
I found that

```<code>JKademliaNode kad1 = new JKademliaNode("Node1", new KademliaId("ASF45678947584567467"), 7574);

JKademliaNode kad2 = new JKademliaNode("Node2", new KademliaId("ASERTKJDHGVHERJHGFLK"), 7572);
</code>```

is used to create 2 instances of the peers and following code to connect them with each other.

```<code>kad1.bootstrap(kad2.getNode());
</code>```

But that was to connect them in the same program where it's running.

I want to connect them accordingly for different computers. Been stuck here for hours. I don't know how to use this.

答:
According to Kademlia protocol you can find in here, "To join the network,  n node U must have a contact to an already  participating node W. U then performs a node lookup for it's own node ID."

You should have two instance of the nodes.

Instance 1:

```<code>JKademliaNode kad1 = new JKademliaNode("Node1", new KademliaId("ASF45678947584567467"), 7574);
</code>```

Instance 2:

```<code>JKademliaNode kad2 = new JKademliaNode("Node2", new KademliaId("ASERTKJDHGVHERJHGFLK"), 7572);
</code>```

You can bootstrap the node2 from node 1.

```<code>KademliaId id = new KademliaId("ASERTKJDHGVHERJHGFLK");
InetAddress ip =InetAddress.getByName("Ip address of the remote node");
Node kad2 = new Node(id,ip,7572);
kad1.bootstrap(kad2);
</code>```

Title: Kademlia Implementation in Java

Body:
I want to setup a Kademlia network to connect peers and build a p2p network. I'm going to distribute processing power of nodes within the network. For network I found this Kademlia Java implemented Setup from git.   https://github.com/JoshuaKissoon/Kademlia

I want to know how to setup this and use to implement the network.
I found that

JKademliaNode kad1 = new JKademliaNode("Node1", new KademliaId("ASF45678947584567467"), 7574);

JKademliaNode kad2 = new JKademliaNode("Node2", new KademliaId("ASERTKJDHGVHERJHGFLK"), 7572);

is used to create 2 instances of the peers and following code to connect them with each other.

kad1.bootstrap(kad2.getNode());

But that was to connect them in the same program where it's running.

I want to connect them accordingly for different computers. Been stuck here for hours. I don't know how to use this.

Body:
According to Kademlia protocol you can find in here, "To join the network,  n node U must have a contact to an already  participating node W. U then performs a node lookup for it's own node ID."

You should have two instance of the nodes.

Instance 1:

JKademliaNode kad1 = new JKademliaNode("Node1", new KademliaId("ASF45678947584567467"), 7574);

Instance 2:

JKademliaNode kad2 = new JKademliaNode("Node2", new KademliaId("ASERTKJDHGVHERJHGFLK"), 7572);

You can bootstrap the node2 from node 1.

KademliaId id = new KademliaId("ASERTKJDHGVHERJHGFLK");
InetAddress ip =InetAddress.getByName("Ip address of the remote node");
Node kad2 = new Node(id,ip,7572);
kad1.bootstrap(kad2);


问:
IOS 11 XCODE 9: Archive errors Undefined symbols for architecture arm64:
I am trying to create an archive for a XCODE 9 app using NFC core and getting errors (see images) that I cant figure out having tried many settings. We are using the new NFC Core framework in the app and all works perfectly when running on devices etc - just wont create a archive so we can add to TestFight...

Here is a screen shot of me having changed the scheme for Archive to debug, but with no different results unfortunately.

 Archive changed to debug">

答:
Ok, in my opinion there might not be the release versions of this symbols, it is an option, and if it worked while testing you might have a go compiling with Debug settings the archived version too:

Click on your target scheme settings:

Click on edit scheme:

Select Archive, and then change the Build Configuration to Debug:

Then you can have a go again at archiving... The side effect might be that the executable will be bigger... Let me know if it works :-)