问:
Explicitly setting active member in union in C++
The following code is the classical, infamous type-punning union. Similar code is legal in C99/C11 but illegal in C++, because one has to read from the inactive member.

To activate the inactive member one has to write to it (that is not appropriate here) or to construct it via placement-new.

The code below does exactly this: it initializes member a and then activates member b by placement-new. In case of an array of primitive types, the construction is actually a noop, and the bitvalues remain the same.

I never saw this solution in the numerous other questions / answers to this topix, so I wonder if the code below in fact circumvents UB really.

```<code>#include <cstdint>
#include <cstddef>
#include <utility>
#include <array>
#include <tuple>
#include <cassert>

union ByteUnion32 {
public:
    explicit ByteUnion32(uint32_t v) : a{v}{
        new (&b) std::byte[sizeof(uint32_t)]; // set b active, but prevents constexpr, actually a noop
    }
    std::byte operator[](uint8_t i) const {
            return b[i];
    }
private:
    uint32_t a;
    std::byte b[sizeof(uint32_t)];
};
int main(){
    ByteUnion32 u10{0x01020304}; // initialise and activate byte-memebers
    auto v10 = std::to_integer<uint8_t>(u10[0]);
    assert(v10 == 4);

}
</code>```

答:
Instead of using a union to provide both conversion direction, the following maybe a solution in C++ using two specializations for the conversion directions std::byte to larger integer-type or integer-type to std::byte.

```<code>#include <cstdint>
#include <cstddef>
#include <utility>
#include <array>
#include <tuple>
#include <cassert>
#include <cstring>

namespace std {
    enum class endian { // since c++20
#ifdef _WIN32
        little = 0,
        big    = 1,
        native = little
#else
        little = __ORDER_LITTLE_ENDIAN__,
        big    = __ORDER_BIG_ENDIAN__,
        native = __BYTE_ORDER__
#endif
    };
    namespace literals {
        constexpr byte operator"" _byte(unsigned long long v) { // <> Literal-Operator for suffix `_byte`
            return byte{static_cast<uint8_t>(v)};
        }
    }
}

template<typename T>
requires (std::is_same<uint64_t, T>::value || std::is_same<uint32_t, T>::value || std::is_same<uint16_t, T>::value) && (sizeof(T) > 1)
struct ByteUnion<ByteToIntegral, T> {
public:
    template<typename... B>
    requires (std::is_same<B, std::byte>::value || ...) && (sizeof...(B) == sizeof(T))
    explicit ByteUnion(B... vv) : ByteUnion{endian_type{}, std::index_sequence_for<B...>{}, vv...} {}

    const T& value() const {return a;}
private:
    template<size_t... II, typename... B>
    explicit ByteUnion(LittleEndian, std::index_sequence<II...>, B&&... vv) {
        uint8_t* p = reinterpret_cast<uint8_t*>(&a);
        ((p[sizeof...(II) - 1 - II] = static_cast<uint8_t>(vv)),...);
    }
    template<size_t... II, typename... B>
    explicit ByteUnion(BigEndian, std::index_sequence<II...>, B&&... vv) {
        uint8_t* p = reinterpret_cast<uint8_t*>(&a);
        ((p[II] = static_cast<uint8_t>(vv)),...);
    }
    T a;
};

using namespace std::literals;

int main(){
    ByteUnion<IntegralToByte, uint64_t> u1{0x01020304}; // initialise and activate byte-memebers
//    ByteUnion<ByteToIntegral, uint64_t> u1x{0x01020304}; // not possible
    auto v1 = std::to_integer<uint8_t>(u1[0]);
//    u1.value(); // not possible, who access inactive member
    assert(v1 == 4);

    ByteUnion<ByteToIntegral, uint32_t> u2{0x01_byte, 0x02_byte, 0x03_byte, 0x04_byte}; // initialise and activate integral value member
//    ByteUnion<IntegralToByte, uint32_t> u2x{0x01_byte, 0x02_byte, 0x03_byte, 0x04_byte}; // not possible
    auto v2 = u2.value();
    assert(v2 == 0x01020304);
//    u2[0];

}
</code>```

Body:
The following code is the classical, infamous type-punning union. Similar code is legal in C99/C11 but illegal in C++, because one has to read from the inactive member.

To activate the inactive member one has to write to it (that is not appropriate here) or to construct it via placement-new.

The code below does exactly this: it initializes member a and then activates member b by placement-new. In case of an array of primitive types, the construction is actually a noop, and the bitvalues remain the same.

I never saw this solution in the numerous other questions / answers to this topix, so I wonder if the code below in fact circumvents UB really.

#include <cstdint>
#include <cstddef>
#include <utility>
#include <array>
#include <tuple>
#include <cassert>

union ByteUnion32 {
public:
    explicit ByteUnion32(uint32_t v) : a{v}{
        new (&b) std::byte[sizeof(uint32_t)]; // set b active, but prevents constexpr, actually a noop
    }
    std::byte operator[](uint8_t i) const {
            return b[i];
    }
private:
    uint32_t a;
    std::byte b[sizeof(uint32_t)];
};
int main(){
    ByteUnion32 u10{0x01020304}; // initialise and activate byte-memebers
    auto v10 = std::to_integer<uint8_t>(u10[0]);
    assert(v10 == 4);

}

Body:
Instead of using a union to provide both conversion direction, the following maybe a solution in C++ using two specializations for the conversion directions std::byte to larger integer-type or integer-type to std::byte.

#include <cstdint>
#include <cstddef>
#include <utility>
#include <array>
#include <tuple>
#include <cassert>
#include <cstring>

namespace std {
    enum class endian { // since c++20
#ifdef _WIN32
        little = 0,
        big    = 1,
        native = little
#else
        little = __ORDER_LITTLE_ENDIAN__,
        big    = __ORDER_BIG_ENDIAN__,
        native = __BYTE_ORDER__
#endif
    };
    namespace literals {
        constexpr byte operator"" _byte(unsigned long long v) { // <> Literal-Operator for suffix `_byte`
            return byte{static_cast<uint8_t>(v)};
        }
    }
}

template<typename T>
requires (std::is_same<uint64_t, T>::value || std::is_same<uint32_t, T>::value || std::is_same<uint16_t, T>::value) && (sizeof(T) > 1)
struct ByteUnion<ByteToIntegral, T> {
public:
    template<typename... B>
    requires (std::is_same<B, std::byte>::value || ...) && (sizeof...(B) == sizeof(T))
    explicit ByteUnion(B... vv) : ByteUnion{endian_type{}, std::index_sequence_for<B...>{}, vv...} {}

    const T& value() const {return a;}
private:
    template<size_t... II, typename... B>
    explicit ByteUnion(LittleEndian, std::index_sequence<II...>, B&&... vv) {
        uint8_t* p = reinterpret_cast<uint8_t*>(&a);
        ((p[sizeof...(II) - 1 - II] = static_cast<uint8_t>(vv)),...);
    }
    template<size_t... II, typename... B>
    explicit ByteUnion(BigEndian, std::index_sequence<II...>, B&&... vv) {
        uint8_t* p = reinterpret_cast<uint8_t*>(&a);
        ((p[II] = static_cast<uint8_t>(vv)),...);
    }
    T a;
};

using namespace std::literals;

int main(){
    ByteUnion<IntegralToByte, uint64_t> u1{0x01020304}; // initialise and activate byte-memebers
//    ByteUnion<ByteToIntegral, uint64_t> u1x{0x01020304}; // not possible
    auto v1 = std::to_integer<uint8_t>(u1[0]);
//    u1.value(); // not possible, who access inactive member
    assert(v1 == 4);

    ByteUnion<ByteToIntegral, uint32_t> u2{0x01_byte, 0x02_byte, 0x03_byte, 0x04_byte}; // initialise and activate integral value member
//    ByteUnion<IntegralToByte, uint32_t> u2x{0x01_byte, 0x02_byte, 0x03_byte, 0x04_byte}; // not possible
    auto v2 = u2.value();
    assert(v2 == 0x01020304);
//    u2[0];

}


来源: stackexchange

问:
Vulkan: Why does the 1080 Ti have a maxMemoryAllocationCount of 4294967296 on arch but only 4096 on Windows?
I am currently building a game engine in C++ which uses vulkan for rendering. While implementing a terrain renderer I reached a hardware limit, the maxMemoryAllocationCount which limits the amount of allocated memory blocks. I checked https://vulkan.gpuinfo.org/ to see how high that value on different GPUs is. When looking at the "GeForce GTX 1080 Ti", the value is 4096 for windows but 4294967296 for arch/manjaro. Why is there a difference between those OSes, when this really should be a hardware limitation?

答:
Why "should" it be a hardware limitation?

With 4 exceptions, every Windows implementation is limited to 4096 allocations. And those exceptions are either open-source RADV hacked to run on Windows or early drivers that returned bogus values.

So clearly, Windows as an OS is imposing this limitation. After all, the OS owns the GPU and must be involved in any memory allocations.

It is the right of the OS to prevent a process from engaging in pathological behavior. Windows seems to think that making lots of GPU allocations is pathological (and they're not wrong), so the WDDM model imposes a low-but-reasonable limit on GPU allocations.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Cannot compile PHP 5.6 with Homebrew on Mac OS 10.12
I am in trouble compiling PHP 5.6 using Brew on my Mac OS X 10.12 system.

My problem begins because even if I can install PHP 5.6 directly with brew install php56, the problem is that it is not using the correct php.ini file, witch should be taken from /usr/local/etc/php/5.6/php.ini, but it seems to be taken from /etc:

```<code>m@MacBook-Pro-4.local:~$ php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         (none)
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
</code>```

This is a problem because I cannot install any additional extension like php56-redis which I need.

So I would like to build PHP 5.6 from source to see if it will solve this problem, but when I start the build I get this error which I cannot solve even after searching on Google:

```<code>m@MacBook-Pro-4.local:~$ brew install php56 --build-from-source
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
kibana@5.6
==> Updated Formulae
kibana

==> Installing php56 from homebrew/php
==> Downloading https://php.net/get/php-5.6.32.tar.bz2/from/this/mirror
Already downloaded: /Users/mattia/Library/Caches/Homebrew/php56-5.6.32
==> ./configure --prefix=/usr/local/Cellar/php56/5.6.32_8 --localstatedir=/usr/local/var --sysconfdir=/usr/local/etc/php/5.6 --with-config-file-path=/usr/local/etc/php/5.6 --with
Last 15 lines from /Users/mattia/Library/Logs/Homebrew/php56/01.configure:
checking for DSA_get_default_method in -lssl... no
checking for X509_free in -lcrypto... yes
checking for RAND_egd... no
checking for pkg-config... no
checking for OpenSSL version... >= 0.9.6
checking for CRYPTO_free in -lcrypto... yes
checking for SSL_CTX_set_ssl_version in -lssl... yes
checking for PCRE library to use... bundled
checking whether to enable the SQLite3 extension... yes
checking bundled sqlite3 library... yes
checking for ZLIB support... yes
checking if the location of ZLIB install directory is defined... no
checking for zlib version >= 1.2.0.4... 1.2.8
checking for gzgets in -lz... no
configure: error: ZLIB extension requires gzgets in zlib
</code>```

I tried to search on Google but I didn't find anything related to the ZLIB extension requires gzgets in zlib error.

I have the latest version of XCode installed.

Could you help me please?

答:
I think you should specify to the system the PHP path by this way.

nano vim ~/.bash_profile

Then Add your current PHP path (for PHP 5.6 by this way)

export PATH=/usr/local/etc/php/5.6/bin:$PATH

Then save and compile by running this command

source ~/.bash_profile

Body:
I am in trouble compiling PHP 5.6 using Brew on my Mac OS X 10.12 system.

My problem begins because even if I can install PHP 5.6 directly with brew install php56, the problem is that it is not using the correct php.ini file, witch should be taken from /usr/local/etc/php/5.6/php.ini, but it seems to be taken from /etc:

m@MacBook-Pro-4.local:~$ php --ini
Configuration File (php.ini) Path: /etc
Loaded Configuration File:         (none)
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

This is a problem because I cannot install any additional extension like php56-redis which I need.

So I would like to build PHP 5.6 from source to see if it will solve this problem, but when I start the build I get this error which I cannot solve even after searching on Google:

m@MacBook-Pro-4.local:~$ brew install php56 --build-from-source
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
kibana@5.6
==> Updated Formulae
kibana

==> Installing php56 from homebrew/php
==> Downloading https://php.net/get/php-5.6.32.tar.bz2/from/this/mirror
Already downloaded: /Users/mattia/Library/Caches/Homebrew/php56-5.6.32
==> ./configure --prefix=/usr/local/Cellar/php56/5.6.32_8 --localstatedir=/usr/local/var --sysconfdir=/usr/local/etc/php/5.6 --with-config-file-path=/usr/local/etc/php/5.6 --with
Last 15 lines from /Users/mattia/Library/Logs/Homebrew/php56/01.configure:
checking for DSA_get_default_method in -lssl... no
checking for X509_free in -lcrypto... yes
checking for RAND_egd... no
checking for pkg-config... no
checking for OpenSSL version... >= 0.9.6
checking for CRYPTO_free in -lcrypto... yes
checking for SSL_CTX_set_ssl_version in -lssl... yes
checking for PCRE library to use... bundled
checking whether to enable the SQLite3 extension... yes
checking bundled sqlite3 library... yes
checking for ZLIB support... yes
checking if the location of ZLIB install directory is defined... no
checking for zlib version >= 1.2.0.4... 1.2.8
checking for gzgets in -lz... no
configure: error: ZLIB extension requires gzgets in zlib

I tried to search on Google but I didn't find anything related to the ZLIB extension requires gzgets in zlib error.

I have the latest version of XCode installed.

Could you help me please?


问:
Paraview create points array and set it as source array
Creating an array with p_points = vtk.vtkPoints

And then add data to it p_points.InsertNextPoint(value).

There is like 50000 points.

I want to put that point array in a source.

I tried with a programmable one with :

servermanager fetch getPoints that give me the Point Array in it (p_array)

Then with a loop p_array.InsertNextPoint(p_points.GetPoint(index_point))

But with no luck. The points array in the source  remain empty.

Thanks

答:
Use a Programmable Source with a script like:

```<code>import vtk

pts = vtk.vtkPoints()
for i in xrange(10):
  pts.InsertNextPoint(i, i, i)

output.SetPoints(pts)
</code>```

The output object is pre-defined in the Python environment executed by the Programmable Source and is the output object of the source.

Body:
Use a Programmable Source with a script like:

import vtk

pts = vtk.vtkPoints()
for i in xrange(10):
  pts.InsertNextPoint(i, i, i)

output.SetPoints(pts)

The output object is pre-defined in the Python environment executed by the Programmable Source and is the output object of the source.


问:
Hashset "value cannot be null" error
I'm trying to execute the follow code and it works fine if myObject is != null but throws a "value cannot be null" error if myObject is null. Ideally, if myObject is null then I'd like to just have the HashSet have a single value of 0.

```<code>var ids = new HashSet<int>(myObject.Select(p => p.ID));
</code>```

I've tried a couple different things. I'm not sure why I thought this would work.

```<code>var ids = new HashSet<int>(myObject.Select(p => p.ID).Where(p => p != null));
</code>```

and this which seemed like it should work.

```<code>var ids = new HashSet<int>(myObject.Select(p => (p == null) ? 0 : p.ID));
</code>```

Finally this worked but it seems like there's got to be a better way.

```<code>var ids = new HashSet<int>(myObject!= null ? myObject.Select(p => p.ID) : new int[] {0});
</code>```

Anyone have a better way to do this?

答:
Now, your answer can be cleaned up just a bit:</p>

```<code>var ids = new HashSet<int>(myObject?.Select(p => p.ID) ?? new [] {0});
</code>```

Title: Hashset "value cannot be null" error

Body:
I'm trying to execute the follow code and it works fine if myObject is != null but throws a "value cannot be null" error if myObject is null. Ideally, if myObject is null then I'd like to just have the HashSet have a single value of 0.

var ids = new HashSet<int>(myObject.Select(p => p.ID));

I've tried a couple different things. I'm not sure why I thought this would work.

var ids = new HashSet<int>(myObject.Select(p => p.ID).Where(p => p != null));

and this which seemed like it should work.

var ids = new HashSet<int>(myObject.Select(p => (p == null) ? 0 : p.ID));

Finally this worked but it seems like there's got to be a better way.

var ids = new HashSet<int>(myObject!= null ? myObject.Select(p => p.ID) : new int[] {0});

Anyone have a better way to do this?

Body:
Now, your answer can be cleaned up just a bit:

var ids = new HashSet<int>(myObject?.Select(p => p.ID) ?? new [] {0});


问:
HTML 5 VIDEO + JQUERY Swapping between 2 videos including fallbacks, and not working in firefox
html+video files at: dausign.com/clicktohearsound

Howdy, I'm working on a simple video piece where I have a button that swaps the video and the button disappears. I have 2 videos each with 2 fallbacks. Would anyone know why the video is not showing up in firefox? Also, if I wanted to go back to the first video with the button by clicking in the window, what would be the best way to achieve that? thankseeeeee

答: Looks like you've got an extra closing parenthesis on line 122.</p>

ContentLicense: CC BY-SA 2.5


问:
how to merge two array in my self Pattern?
I'm trying to combine 2 arrays in javascript into one.

```<code>var one=[11,22,33,44,55];
var two=[66,77,88,99,11];
</code>```

i want combaine 2 above arraye in below Pattern:

```<code>three=[11,66,22,77,33,88,44,99,55,11];
</code>```

how do merge 2 arrays in above Pattern?

答:
```<code> const result = [];
 for(var i = 0; i < Math.min(one.length, two.length); i++)
   result.push(one[i], two[i]);
</code>```

Body:
I'm trying to combine 2 arrays in javascript into one.

var one=[11,22,33,44,55];
var two=[66,77,88,99,11];

i want combaine 2 above arraye in below Pattern:

three=[11,66,22,77,33,88,44,99,55,11];

how do merge 2 arrays in above Pattern?


问:
Can't convert Expression<Int> to Expression<AnyObject>
I am using SQLite.swift library.

I have several Expressions,

```<code>let idColumn = Expression<Int>("id")
let nameColumn = Expression<String>("name")
</code>```

I would like to have a dictionary host them, So, I did:

```<code>let columns: [String: Expression<AnyObject>] = [
   "id": idColumn,
   "name": nameColumn
]
</code>```

But I get compiler error:

```<code>Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<AnyObject>'
</code>```

Why is this error? Why Int type can’t be AnyObject?

I also tried Any instead of AnyObject:

```<code>let columns: [String: Expression<Any>] = [
       "id" : idColumn,
       "name": nameColumn
    ]
</code>```

Similar error shows:

```<code>Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<Any>'
</code>```

I don't understand this... Could someone please explain to me?

答:
Your expectations are wrong; what you expect is not how the Swift language works. I'll just repeat the example I give in my book:

A generic type specialized to a subtype is not polymorphic with respect to the same generic type specialized to a supertype. For example, suppose we have a simple generic struct along with a class and its subclass:

```<code>struct Wrapper<T> {
}
class Cat {
}
class CalicoCat : Cat {
}
</code>```

Then you can’t assign a Wrapper specialized to CalicoCat where a Wrapper specialized to Cat is expected:

```<code>let w : Wrapper<Cat> = Wrapper<CalicoCat>() // compile error
</code>```

Technically, we say that generics are not covariant on their parameterized type. There are exceptions to that rule — Optional is the obvious one — but they have to be baked into the language itself.

Body:
I am using SQLite.swift library.

I have several Expressions,

let idColumn = Expression<Int>("id")
let nameColumn = Expression<String>("name")

I would like to have a dictionary host them, So, I did:

let columns: [String: Expression<AnyObject>] = [
   "id": idColumn,
   "name": nameColumn
]

But I get compiler error:

Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<AnyObject>'

Why is this error? Why Int type can’t be AnyObject?

I also tried Any instead of AnyObject:

let columns: [String: Expression<Any>] = [
       "id" : idColumn,
       "name": nameColumn
    ]

Similar error shows:

Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<Any>'

I don't understand this... Could someone please explain to me?

Body:
Your expectations are wrong; what you expect is not how the Swift language works. I'll just repeat the example I give in my book:

A generic type specialized to a subtype is not polymorphic with respect to the same generic type specialized to a supertype. For example, suppose we have a simple generic struct along with a class and its subclass:

struct Wrapper<T> {
}
class Cat {
}
class CalicoCat : Cat {
}

Then you can’t assign a Wrapper specialized to CalicoCat where a Wrapper specialized to Cat is expected:

let w : Wrapper<Cat> = Wrapper<CalicoCat>() // compile error

Technically, we say that generics are not covariant on their parameterized type. There are exceptions to that rule — Optional is the obvious one — but they have to be baked into the language itself.


问:
mod_rewrite causing extra slash
I'm trying to simply remove .php from the filenames on URLs. I'm implementing the solution from this StackOverflow answer so my VirtualHost looks like this,

```<code># domain: example.com
# public: /var/www/html/example.com/public_html/
<Directory /var/www/html/example.com/public_html>
    Options +FollowSymLinks
     AllowOverride All
    DirectoryIndex index.html index.htm index.php
</Directory>
<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
</VirtualHost>

<VirtualHost *:443>
        # Admin details
        ServerAdmin vanguard@example.com
        ServerName example.com
        ServerAlias www.example.com

        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
        #Index File
        DirectoryIndex index.html index.php
        DocumentRoot /var/www/html/example.com/public_html
        #Log Details
        LogLevel warn
        ErrorLog /var/www/html/example.com/log/error.log
        CustomLog /var/www/html/example.com/log/access.log combined
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME}.php -f
        RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]
</VirtualHost>
</code>```

Going to https://example.com resolves just fine, but if I try to go to https://example.com/examplefile it rewrites it to https://example.com//examplefile/

答:
```<code>RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]
</code>```

In a virtual host context this RewriteCond directive will never match because at the time the directive is processed the request has not yet been mapped to the file system, so REQUEST_FILENAME simply contains the URL-path (as opposed to the absolute filesystem path), which is the same as REQUEST_URI.

(This wouldn't work in .htaccess either, but for a different reason. In .htaccess you can't rewrite to an absolute filesystem path, so whilst the RewriteCond should match, the RewriteRule is likely to trigger a 403 Forbidden error.)

To fix this in a server/virtual host context, you can modify these directives to use a URL-based look-ahead:

```<code>RewriteCond %{LA-U:REQUEST_FILENAME}.php -f
RewriteRule !\.php$ %{LA-U:REQUEST_FILENAME}.php [L]
</code>```

However, neither your original directives nor this correction explains the double slash you are seeing in your example. Either an erroneously cached response or your web application?

Title: mod_rewrite causing extra slash

Body:
I'm trying to simply remove .php from the filenames on URLs. I'm implementing the solution from this StackOverflow answer so my VirtualHost looks like this,

# domain: example.com
# public: /var/www/html/example.com/public_html/
<Directory /var/www/html/example.com/public_html>
    Options +FollowSymLinks
     AllowOverride All
    DirectoryIndex index.html index.htm index.php
</Directory>
<VirtualHost *:80>
    ServerName example.com
    Redirect / https://example.com/
</VirtualHost>

<VirtualHost *:443>
        # Admin details
        ServerAdmin vanguard@example.com
        ServerName example.com
        ServerAlias www.example.com

        SSLEngine on
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
        #Index File
        DirectoryIndex index.html index.php
        DocumentRoot /var/www/html/example.com/public_html
        #Log Details
        LogLevel warn
        ErrorLog /var/www/html/example.com/log/error.log
        CustomLog /var/www/html/example.com/log/access.log combined
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME}.php -f
        RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]
</VirtualHost>

Going to https://example.com resolves just fine, but if I try to go to https://example.com/examplefile it rewrites it to https://example.com//examplefile/

Body:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]

In a virtual host context this RewriteCond directive will never match because at the time the directive is processed the request has not yet been mapped to the file system, so REQUEST_FILENAME simply contains the URL-path (as opposed to the absolute filesystem path), which is the same as REQUEST_URI.

(This wouldn't work in .htaccess either, but for a different reason. In .htaccess you can't rewrite to an absolute filesystem path, so whilst the RewriteCond should match, the RewriteRule is likely to trigger a 403 Forbidden error.)

To fix this in a server/virtual host context, you can modify these directives to use a URL-based look-ahead:

RewriteCond %{LA-U:REQUEST_FILENAME}.php -f
RewriteRule !\.php$ %{LA-U:REQUEST_FILENAME}.php [L]

However, neither your original directives nor this correction explains the double slash you are seeing in your example. Either an erroneously cached response or your web application?


问:
Reading a text file line by line in c
I try to read the file that I wrote the first three line, line by line. However, it enters infinity loop. How can I stop it at the end of the file?</p>

```<code>while(fscanf(infile, "%[^\n]", ch) != EOF)
   printf("%s", ch);

Tiffany;Evans Smith;F;22/01/1989;
Alex;Williams;M;23/06/1988;
Clay;Bristol;F;30/12/1989;
</code>```

答:
if you want to use fscanf, you can use this code :

```<code>int ret;
while(ret = fscanf(infile,"%s",str))
{
    if (ret == EOF)
        break;
    if(ret >0 )
    {
        cout << str <<endl;
    }
    else
    {
        break;
    }
}
</code>```

here, int ret is:

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input

Title: Reading a text file line by line in c

Body:
I try to read the file that I wrote the first three line, line by line. However, it enters infinity loop. How can I stop it at the end of the file?

while(fscanf(infile, "%[^\n]", ch) != EOF)
   printf("%s", ch);

Tiffany;Evans Smith;F;22/01/1989;
Alex;Williams;M;23/06/1988;
Clay;Bristol;F;30/12/1989;

Body:
if you want to use fscanf, you can use this code :

int ret;
while(ret = fscanf(infile,"%s",str))
{
    if (ret == EOF)
        break;
    if(ret >0 )
    {
        cout << str <<endl;
    }
    else
    {
        break;
    }
}

here, int ret is:

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input


问:
Ruby: Convert an array or hash to an activerecord relation
I am trying to convert a hash to an activerecord relation but am not able to do so. I intend to use the activerecord relation to sort and then filter the Category table. The end goal is to  create an instance method to filter the top 5 visited categories, which i can then use/call in the controller. This is what i have in mind:

Category model:

```<code>def top_5_visited
        Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5
end
</code>```

Category controller:

```<code>@categories = Category.top_5 visited
</code>```

A hash {"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112} will be created through the following query:

```<code>total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)
</code>```

I have also tried to convert it to an array using sort_by method:

```<code>total_count_sorted = total_count.sort_by {|_key, value| value}
</code>```

I have googled "convert array to activerecord relation" and referenced this post, but testing this:

```<code>Category.where(id: total_count_sort.map(&:id))
</code>```

in the rails console, brings up this error:

NoMethodError: undefined method id for ["Simula", 7]:Array

答:
Change the code to: </p>

```<code>Category.where(id: total_count_sort.map(&:last))
</code>```

Body:
I am trying to convert a hash to an activerecord relation but am not able to do so. I intend to use the activerecord relation to sort and then filter the Category table. The end goal is to  create an instance method to filter the top 5 visited categories, which i can then use/call in the controller. This is what i have in mind:

Category model:

def top_5_visited
        Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5
end

Category controller:

@categories = Category.top_5 visited

A hash {"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112} will be created through the following query:

total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)

I have also tried to convert it to an array using sort_by method:

total_count_sorted = total_count.sort_by {|_key, value| value}

I have googled "convert array to activerecord relation" and referenced this post, but testing this:

Category.where(id: total_count_sort.map(&:id))

in the rails console, brings up this error:

NoMethodError: undefined method id for ["Simula", 7]:Array

Body:
Change the code to:

Category.where(id: total_count_sort.map(&:last))


问:
Laravel is not parsing a JSON Object in Blade as expected - Error Undefined property: stdClass
I have a JSON Object like so:

```<code>{
  "statusCode": 0,
  "statusMessage": "OK",
  "content": {
    "templateId": "5a00775807105e735085c65d",
    "authorId": "fabio.peddis@bsc.it",
    "title": "Primo Template",
    "description": "Descrizione del Primo Template",
    "status": 0,
    "saveDate": 1509979998738,
    "publishDate": null,
    "keywords": [
      "keyDue",
      "keySecondo"
    ],
    "icon": null,
    "questions": [
      {
        "questionId": 1,
        "questionText": "Domanda 01?",
        "responses": [
          {
            "keywords": [
              "Sì",
              "Yes",
              "Oui"
            ],
            "nextQuestionId": 11
          },
          {
            "keywords": [
              "No",
              "Not",
              "Non"
            ],
            "nextQuestionId": 12
          }
        ]
      },
      {
        "questionId": 11,
        "questionText": "Domanda 11?",
        "responses": [
          {
            "keywords": [
</code>```

I pass it to a view after doing this:

```<code>$objResp=json_decode($response);
</code>```

Then on the view I simply access it like so:

```<code>@foreach($template->content->questions as $question)
    ...
    {{$question->questionText}}
    ...
    @foreach($question->responses as $res )
        ....
    @endforeach

@endforeach
</code>```

"Responses" is a different structure but at the same level as "questionText" that I can easily access it.

So the problem is in the second/internal loop, it crashes without hope..., but if I do a dd() of $question->responses, I can see the correct contents of an array size2.

Laravel gives me back this error with the loop:

Undefined property: stdClass::$responses

What is causing this error?

答:
Pass true as the second argument to json_decode.

$objResp=json_decode($response, true);

Body:
I have a JSON Object like so:

{
  "statusCode": 0,
  "statusMessage": "OK",
  "content": {
    "templateId": "5a00775807105e735085c65d",
    "authorId": "fabio.peddis@bsc.it",
    "title": "Primo Template",
    "description": "Descrizione del Primo Template",
    "status": 0,
    "saveDate": 1509979998738,
    "publishDate": null,
    "keywords": [
      "keyDue",
      "keySecondo"
    ],
    "icon": null,
    "questions": [
      {
        "questionId": 1,
        "questionText": "Domanda 01?",
        "responses": [
          {
            "keywords": [
              "Sì",
              "Yes",
              "Oui"
            ],
            "nextQuestionId": 11
          },
          {
            "keywords": [
              "No",
              "Not",
              "Non"
            ],
            "nextQuestionId": 12
          }
        ]
      },
      {
        "questionId": 11,
        "questionText": "Domanda 11?",
        "responses": [
          {
            "keywords": [

I pass it to a view after doing this:

$objResp=json_decode($response);

Then on the view I simply access it like so:

@foreach($template->content->questions as $question)
    ...
    {{$question->questionText}}
    ...
    @foreach($question->responses as $res )
        ....
    @endforeach

@endforeach

"Responses" is a different structure but at the same level as "questionText" that I can easily access it.

So the problem is in the second/internal loop, it crashes without hope..., but if I do a dd() of $question->responses, I can see the correct contents of an array size2.

Laravel gives me back this error with the loop:

Undefined property: stdClass::$responses

What is causing this error?


问:
iOS - Onboarding setup causing JWPlayer fullScreen button to load initial view controller
I have a tab bar application (Swift 3, Xcode 8.3) with three tabs. When the app is first launched, the code checks UserDefaults to see if a user is logged in. If there is a user, the initial view controller (the first tab) is loaded. Otherwise, an onboarding screen is loaded for the user to log in, after which he/she will get to the first tab.

This is the code I used in AppDelegate:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Set up onboarding screen
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var vc: UIViewController

    let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
    if !isUserLoggedIn {
        vc = storyboard.instantiateViewController(withIdentifier: "onboarding")
    } else {
        vc = storyboard.instantiateInitialViewController()!
    }

    self.window?.rootViewController = vc
    self.window?.makeKeyAndVisible()

    return true
}
</code>```

On itself, this works perfectly. The problem occurs later. Any of the tabs can segue to a screen where I have an instance of the JWPlayer for iOS which takes about the top third of the screen. If a video starts playing and I rotate the phone to landscape mode, the video goes fullScreen (this also happens if the user clicks on the fullScreen button). However, when the device is rotated back to portrait, instead of getting back the screen with the video player on the top third, I immediately see the initial view (that is, the contents of the first tab). The video keeps playing in the background but I can't see it. I can't get back to the video unless I rotate the device to landscape mode again. So, landscape I see my original video, portrait I get the initial view (first tab).

I tried many things, such as deleting chunks of code one at a time, monitoring viewDidDisappear, viewWillDisappear (for the video screen), none of which were triggered when the phone was rotated to portrait. I also monitored if the initial tab was somehow being selected, but this wasn't the case either.

Only when I deleted the onboarding code from app delegate did the video player work normally.

Is there anything in the onboarding code that could be making the video player display the initialViewController upon exiting fullScreen? Is there a different way I could write the onboarding code?

Thanks.

答:
This is what I did. I had to treat the onboarding screen as any other, with its own ViewController. Then inside the ViewController I wrote:

```<code>override func viewDidAppear(_ animated: Bool) {
    // Check to see if user is logged in
    let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
    if isUserLoggedIn {
        performSegue(withIdentifier: "toMainSegue", sender: self)
        return
    }
}
</code>```

No other way to fix it, unfortunately.

Body:
I have a tab bar application (Swift 3, Xcode 8.3) with three tabs. When the app is first launched, the code checks UserDefaults to see if a user is logged in. If there is a user, the initial view controller (the first tab) is loaded. Otherwise, an onboarding screen is loaded for the user to log in, after which he/she will get to the first tab.

This is the code I used in AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Set up onboarding screen
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var vc: UIViewController

    let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
    if !isUserLoggedIn {
        vc = storyboard.instantiateViewController(withIdentifier: "onboarding")
    } else {
        vc = storyboard.instantiateInitialViewController()!
    }

    self.window?.rootViewController = vc
    self.window?.makeKeyAndVisible()

    return true
}

On itself, this works perfectly. The problem occurs later. Any of the tabs can segue to a screen where I have an instance of the JWPlayer for iOS which takes about the top third of the screen. If a video starts playing and I rotate the phone to landscape mode, the video goes fullScreen (this also happens if the user clicks on the fullScreen button). However, when the device is rotated back to portrait, instead of getting back the screen with the video player on the top third, I immediately see the initial view (that is, the contents of the first tab). The video keeps playing in the background but I can't see it. I can't get back to the video unless I rotate the device to landscape mode again. So, landscape I see my original video, portrait I get the initial view (first tab).

I tried many things, such as deleting chunks of code one at a time, monitoring viewDidDisappear, viewWillDisappear (for the video screen), none of which were triggered when the phone was rotated to portrait. I also monitored if the initial tab was somehow being selected, but this wasn't the case either.

Only when I deleted the onboarding code from app delegate did the video player work normally.

Is there anything in the onboarding code that could be making the video player display the initialViewController upon exiting fullScreen? Is there a different way I could write the onboarding code?

Thanks.

Body:
This is what I did. I had to treat the onboarding screen as any other, with its own ViewController. Then inside the ViewController I wrote:

override func viewDidAppear(_ animated: Bool) {
    // Check to see if user is logged in
    let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
    if isUserLoggedIn {
        performSegue(withIdentifier: "toMainSegue", sender: self)
        return
    }
}

No other way to fix it, unfortunately.


问:
I want to pass in constructor mode of file
I created child class of ofstream. I want to pass in constructor mode of file. For example ios::app. How can i do it ? What should i write in my_file constructor to put it in ofstream class constructor? I know that it's int type but how to understand what is value of ios::app?

```<code>#include <string>
#include <fstream>
#include <iostream>
using namespace std;

class my_file : public ofstream {
    string name;
public:
    my_file(string name, const char* filename) : ofstream(filename) { this->name = name; }
    inline const string get() { return this->name; }
};

int main(void) {
    my_file file("Name","new.txt"  /* , ios::app  */   );

    return 0;
}
</code>```

答:
I know that it's int type but how to understand what is value of ios::app?

Wrong, that's not a int!

Go to ofstream doc http://www.cplusplus.com/reference/fstream/ofstream/, then click (constructor) to see what the parameters are and then you can see that mode is of type std::ios_base::openmode (as described here)

So simply do:

```<code>class my_file : public ofstream {
    string name;
public:
    my_file(string name, const char* filename, std::ios_base::openmode mode ) : ofstream(filename,mode) { this->name = name; }
    inline const string get() { return this->name; }
};
</code>```

Then:

```<code>my_file file("Name","new.txt", ios::app);
</code>```

Body:
I created child class of ofstream. I want to pass in constructor mode of file. For example ios::app. How can i do it ? What should i write in my_file constructor to put it in ofstream class constructor? I know that it's int type but how to understand what is value of ios::app?

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

class my_file : public ofstream {
    string name;
public:
    my_file(string name, const char* filename) : ofstream(filename) { this->name = name; }
    inline const string get() { return this->name; }
};

int main(void) {
    my_file file("Name","new.txt"  /* , ios::app  */   );

    return 0;
}

Body:
I know that it's int type but how to understand what is value of ios::app?

Wrong, that's not a int!

Go to ofstream doc http://www.cplusplus.com/reference/fstream/ofstream/, then click (constructor) to see what the parameters are and then you can see that mode is of type std::ios_base::openmode (as described here)

So simply do:

class my_file : public ofstream {
    string name;
public:
    my_file(string name, const char* filename, std::ios_base::openmode mode ) : ofstream(filename,mode) { this->name = name; }
    inline const string get() { return this->name; }
};

Then:

my_file file("Name","new.txt", ios::app);


问:
How to open generated pdf using jspdf in new window
I am using jspdf to generate a pdf file. Every thing is working fine. But how to open generated
pdf in new tab or new window.

I am using

```<code>doc.output('datauri');
</code>```

Which is opening the pdf in same tab.

答:
This solution working for me</p>

```<code>window.open(doc.output('bloburl'))
</code>```

Body:
I am using jspdf to generate a pdf file. Every thing is working fine. But how to open generated
pdf in new tab or new window.

I am using

doc.output('datauri');

Which is opening the pdf in same tab.

Body:
This solution working for me

window.open(doc.output('bloburl'))


问:
Can't generate signed APK in Android Studio, 'java.io.IOException'
I have a problem with generating signed APK in Android Studio. It was working fine few days ago, I dont know what went wrong. I'm getting this error for any project I try to fgenerate signed APK of:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/proguard/release/jars/3/1f/main.jar] (Can't read [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/RealmTransformer/release/folders/1/1/realm(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))

Here is my buildTypes Task:

```<code>buildTypes {
    debug {
        shrinkResources false // This must be first
        minifyEnabled false   // This must be after shrinkResources
        multiDexEnabled true
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules-debug.pro"
    }
    release {
        shrinkResources true
        minifyEnabled true
        useProguard true
        multiDexEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
    }
}
</code>```

Here is the code I've written in proguard file:

```<code>-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-keepattributes Signature
-keepattributes Exceptions
-repackageclasses ''

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.
-keep public class com.android.vending.licensing.ILicensingService

-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry
-keep class com.google.common.cache.LocalCache$ReferenceEntry

-dontnote com.android.vending.licensing.ILicensingService

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class **.R$* {
  public static <fields>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.* { *; }
-keepattributes *Annotation,Signature
-dontwarn in.mylo.pregnancy.baby.app.**
-keep class in.mylo.pregnancy.baby.app.shapeimageview.**{ *; }

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keep class butterknife.*
-keepclasseswithmembernames class * {
 @butterknife.* <methods>; }
-keepclasseswithmembernames class * {
 @butterknife.* <fields>; }

-dontwarn javax.annotation.**
-dontwarn javax.inject.**
-dontwarn sun.misc.Unsafe

-dontwarn java.lang.ClassValue
-dontwarn com.google.j2objc.annotations.Weak
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-dontwarn com.clevertap.android.sdk.**

-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
    public static <fields>;
}

-dontwarn android.support.**

-dontwarn com.google.android.gms.**

-dontwarn com.fasterxml.**
-dontwarn okio.**
-dontwarn com.caverock.**
-dontwarn com.github.siyamed.shapeimageview.**

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-dontwarn sun.misc.Unsafe
-dontwarn com.octo.android.robospice.retrofit.RetrofitJackson**
-dontwarn retrofit.appengine.UrlFetchClient
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keep class com.google.gson.** { *; }
-keep class com.google.inject.** { *; }
-keep class org.apache.http.** { *; }
-keep class org.apache.james.mime4j.** { *; }
-keep class javax.inject.** { *; }
-keep class retrofit.** { *; }
-keep class retrofit2.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn retrofit.**
-dontwarn retrofit2.**

-dontwarn sun.misc.**

-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}

-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   long producerNode;
   long consumerNode;
}

-keep class in.mylo.pregnancy.baby.app.retrofit.** { *; }

-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }

-keepnames public class * extends io.realm.RealmObject
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.** { *; }
-dontwarn javax.**
-dontwarn io.realm.**

-keepnames public class * extends io.realm.RealmObject

-dontwarn com.google.android.gms.location.**
-dontwarn com.google.android.gms.gcm.**
-dontwarn com.google.android.gms.iid.**

-keep class com.google.android.gms.gcm.** { *; }
-keep class com.google.android.gms.iid.** { *; }
-keep class com.google.android.gms.location.** { *; }

-keep class com.moe.pushlibrary.activities.** { *; }
-keep class com.moengage.locationlibrary.GeofenceIntentService
-keep class com.moe.pushlibrary.InstallReceiver
-keep class com.moengage.push.MoEPushWorker
-keep class com.moe.pushlibrary.providers.MoEProvider
-keep class com.moengage.receiver.MoEInstanceIDListener
-keep class com.moengage.worker.MoEGCMListenerService
-keep class com.moe.pushlibrary.models.** { *;}
-keep class com.moengage.core.GeoTask
-keep class com.moengage.location.GeoManager
-keep class com.moengage.inapp.InAppManager
-keep class com.moengage.push.PushManager
-keep class com.moengage.inapp.InAppController

-dontwarn com.moengage.location.GeoManager
-dontwarn com.moengage.core.GeoTask
-dontwarn com.moengage.receiver.*
-dontwarn com.moengage.worker.*
-dontwarn com.moengage.inapp.ViewEngine

-keep class com.delight.**  { *; }

-dontwarn com.google.android.gms.location.**
-keep class com.moe.** { *; }
-keep class com.moengage.** { *; }
-keep class com.delight.** { *; }

-keep class com.google.android.gms.ads.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn android.databinding.**
-keep class android.databinding.** { *; }
</code>```

Any help appreciated, thanks in advance.

答:
Problem

The same problem occurred to me after I :

Upgraded to Android Studio 3, then

in my dependency library, changed inline classes to lambdas and method references.

I thought I could freely utilize lambdas and method references as stated in Android Studio 3 release notes, I may have forgot or missed it.

Solution:

Anyway, I'm not 100% sure, but I think we still can't use lambdas and/or method references in project libraries, because as soon as I reverted all lambdas and method references in my library, I successfully re-generated my APK.

Body:
I have a problem with generating signed APK in Android Studio. It was working fine few days ago, I dont know what went wrong. I'm getting this error for any project I try to fgenerate signed APK of:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/proguard/release/jars/3/1f/main.jar] (Can't read [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/RealmTransformer/release/folders/1/1/realm(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))

Here is my buildTypes Task:

buildTypes {
    debug {
        shrinkResources false // This must be first
        minifyEnabled false   // This must be after shrinkResources
        multiDexEnabled true
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules-debug.pro"
    }
    release {
        shrinkResources true
        minifyEnabled true
        useProguard true
        multiDexEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
    }
}

Here is the code I've written in proguard file:

-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-keepattributes Signature
-keepattributes Exceptions
-repackageclasses ''

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.
-keep public class com.android.vending.licensing.ILicensingService

-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry
-keep class com.google.common.cache.LocalCache$ReferenceEntry

-dontnote com.android.vending.licensing.ILicensingService

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class **.R$* {
  public static <fields>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.* { *; }
-keepattributes *Annotation,Signature
-dontwarn in.mylo.pregnancy.baby.app.**
-keep class in.mylo.pregnancy.baby.app.shapeimageview.**{ *; }

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keep class butterknife.*
-keepclasseswithmembernames class * {
 @butterknife.* <methods>; }
-keepclasseswithmembernames class * {
 @butterknife.* <fields>; }

-dontwarn javax.annotation.**
-dontwarn javax.inject.**
-dontwarn sun.misc.Unsafe

-dontwarn java.lang.ClassValue
-dontwarn com.google.j2objc.annotations.Weak
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-dontwarn com.clevertap.android.sdk.**

-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
    public static <fields>;
}

-dontwarn android.support.**

-dontwarn com.google.android.gms.**

-dontwarn com.fasterxml.**
-dontwarn okio.**
-dontwarn com.caverock.**
-dontwarn com.github.siyamed.shapeimageview.**

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-dontwarn sun.misc.Unsafe
-dontwarn com.octo.android.robospice.retrofit.RetrofitJackson**
-dontwarn retrofit.appengine.UrlFetchClient
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keep class com.google.gson.** { *; }
-keep class com.google.inject.** { *; }
-keep class org.apache.http.** { *; }
-keep class org.apache.james.mime4j.** { *; }
-keep class javax.inject.** { *; }
-keep class retrofit.** { *; }
-keep class retrofit2.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn retrofit.**
-dontwarn retrofit2.**

-dontwarn sun.misc.**

-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}

-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   long producerNode;
   long consumerNode;
}

-keep class in.mylo.pregnancy.baby.app.retrofit.** { *; }

-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }

-keepnames public class * extends io.realm.RealmObject
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.** { *; }
-dontwarn javax.**
-dontwarn io.realm.**

-keepnames public class * extends io.realm.RealmObject

-dontwarn com.google.android.gms.location.**
-dontwarn com.google.android.gms.gcm.**
-dontwarn com.google.android.gms.iid.**

-keep class com.google.android.gms.gcm.** { *; }
-keep class com.google.android.gms.iid.** { *; }
-keep class com.google.android.gms.location.** { *; }

-keep class com.moe.pushlibrary.activities.** { *; }
-keep class com.moengage.locationlibrary.GeofenceIntentService
-keep class com.moe.pushlibrary.InstallReceiver
-keep class com.moengage.push.MoEPushWorker
-keep class com.moe.pushlibrary.providers.MoEProvider
-keep class com.moengage.receiver.MoEInstanceIDListener
-keep class com.moengage.worker.MoEGCMListenerService
-keep class com.moe.pushlibrary.models.** { *;}
-keep class com.moengage.core.GeoTask
-keep class com.moengage.location.GeoManager
-keep class com.moengage.inapp.InAppManager
-keep class com.moengage.push.PushManager
-keep class com.moengage.inapp.InAppController

-dontwarn com.moengage.location.GeoManager
-dontwarn com.moengage.core.GeoTask
-dontwarn com.moengage.receiver.*
-dontwarn com.moengage.worker.*
-dontwarn com.moengage.inapp.ViewEngine

-keep class com.delight.**  { *; }

-dontwarn com.google.android.gms.location.**
-keep class com.moe.** { *; }
-keep class com.moengage.** { *; }
-keep class com.delight.** { *; }

-keep class com.google.android.gms.ads.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn android.databinding.**
-keep class android.databinding.** { *; }

Any help appreciated, thanks in advance.


问:
Inserting object that should be mapped into different DB table depending on scenario
I have an object with properties names that exactly name the field names inside the DB table but I'm not sure how to insert it.
The only thing different is the DB table name. So it's an object with a name of different model/mapped table but I want it to be inserted into a table with a different name than the model.
I tried this:

```<code>var val = info.FooBarObj;
conn.Execute("insert DBInformation(val) values(@val)", new { val = val });
</code>```

Where e.g.

Object is FooBarObj and properties are int Id, string Foo, string Bar

and the DBInformation has the field names: Id, Foo, and Bar but the table isn't called FooBarObj, it's called DBInformation.

How can I insert something like this? I'm using Dapper

EDIT:

Can I have two table attributes for FooBar model?

E.g. [Table("DBInformation")] and [Table("FooBar")].

I have a weird edge case where I want to insert into FooBar if this scenario occurs, if another scenario occurs, insert into DBInformation. That's the problem I'm currently facing and thus that's why I can't just add the attribute and be done with for this problem.

答:
You can use EF or PetaPoco

My suggestion is PetaPoco because very simple and affective.

if you are dealing with big data then my suggestion

EntityFramework

Your object

```<code>[TableName("Administrators")]
[PrimaryKey("dbid", autoIncrement = true)]
class Administrators
{
    public int dbid { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}
</code>```

Insert statement

```<code>var Administrators= new Administrators{
Name = "Mami",
Surname= "Dora"
};

object getObj= db.Insert(Administrators);
</code>```

Basic Example (Get&Set)

App.config

```<code> <connectionStrings>
    <add name="PetaExample" connectionString="Data Source=MDORA17\SQLEXPRESS;Initial Catalog=mdblog;Integrated Security=True;Connect Timeout=300;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</code>```

GET

```<code> static void Main(string[] args)
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var result = db.Query<Administrators>("select * from mdpub.Administrators").ToList();

                    result.ForEach(ShowPerson);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }

        private static void ShowPerson(Administrators admin)
        {
            Console.WriteLine("{0} {1} ", admin.Name, admin.SurName);
        }
</code>```

SET

```<code>static void Main(string[] args)
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var Administrators = new Administrators
                    {
                        Name = "Mami",
                        SurName = "Dora",
                    };

                    db.Insert("mdpub.Administrators", "dbid", true, Administrators);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }

    }
    public class Administrators
    {
        public int dbid { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

    }
</code>```

Body:
I have an object with properties names that exactly name the field names inside the DB table but I'm not sure how to insert it.
The only thing different is the DB table name. So it's an object with a name of different model/mapped table but I want it to be inserted into a table with a different name than the model.
I tried this:

var val = info.FooBarObj;
conn.Execute("insert DBInformation(val) values(@val)", new { val = val });

Where e.g.

Object is FooBarObj and properties are int Id, string Foo, string Bar

and the DBInformation has the field names: Id, Foo, and Bar but the table isn't called FooBarObj, it's called DBInformation.

How can I insert something like this? I'm using Dapper

EDIT:

Can I have two table attributes for FooBar model?

E.g. [Table("DBInformation")] and [Table("FooBar")].

I have a weird edge case where I want to insert into FooBar if this scenario occurs, if another scenario occurs, insert into DBInformation. That's the problem I'm currently facing and thus that's why I can't just add the attribute and be done with for this problem.

Body:
You can use EF or PetaPoco

My suggestion is PetaPoco because very simple and affective.

if you are dealing with big data then my suggestion

EntityFramework

Your object

[TableName("Administrators")]
[PrimaryKey("dbid", autoIncrement = true)]
class Administrators
{
    public int dbid { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

Insert statement

var Administrators= new Administrators{
Name = "Mami",
Surname= "Dora"
};

object getObj= db.Insert(Administrators);

Basic Example (Get&Set)

App.config

 <connectionStrings>
    <add name="PetaExample" connectionString="Data Source=MDORA17\SQLEXPRESS;Initial Catalog=mdblog;Integrated Security=True;Connect Timeout=300;" providerName="System.Data.SqlClient" />
  </connectionStrings>

GET

 static void Main(string[] args)
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var result = db.Query<Administrators>("select * from mdpub.Administrators").ToList();

                    result.ForEach(ShowPerson);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }

        private static void ShowPerson(Administrators admin)
        {
            Console.WriteLine("{0} {1} ", admin.Name, admin.SurName);
        }

SET

static void Main(string[] args)
        {
            using (var db = new Database("PetaExample"))
            {
                try
                {
                    var Administrators = new Administrators
                    {
                        Name = "Mami",
                        SurName = "Dora",
                    };

                    db.Insert("mdpub.Administrators", "dbid", true, Administrators);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            Console.ReadKey();
        }

    }
    public class Administrators
    {
        public int dbid { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

    }


问:
Send message from content script to another
I am developing a Google chrome extension. My purpose is to send messages from my script1.js to script2.js. Here is what I wrote in my manifest.json:

```<code>  {
    "matches": ["https://www.google.fr/"],
    "css": ["styles.css"],
    "js": ["script1.js"]

  },
  {
    "matches": ["my_website.html"],
    "css": ["styles.css"],
    "js": ["script2.js"]

  },
</code>```

Here is what I wrote in script1.js:

chrome.runtime.sendMessage('hello world!!!!!!');

and in script2.js:

chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){

alert(response);

} );

I don't think I'm doing it the right way, I think I've to use the background.js but I don't know how.

Thanks very much in advance.

答:
As you say, you have to use background script. For example:

script1:

```<code>chrome.runtime.sendMessage({from:"script1",message:"hello!"});
</code>```

background.js

```<code>var tab2id;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.from == "script2") {
        tab2id = sender.tab.id;
    }
    if (message.from == "script1"){
        chrome.tabs.sendMessage(tab2id,message);
    }
});
</code>```

script2.js

```<code>chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    alert("Script1 says: " + message.message);
});
chrome.runtime.sendMessage({from:"script2"});
</code>```

Remember to include your background script in manifest:

```<code>"background": {
    "scripts": ["background.js"]
}
</code>```

Body:
I am developing a Google chrome extension. My purpose is to send messages from my script1.js to script2.js. Here is what I wrote in my manifest.json:

  {
    "matches": ["https://www.google.fr/"],
    "css": ["styles.css"],
    "js": ["script1.js"]

  },
  {
    "matches": ["my_website.html"],
    "css": ["styles.css"],
    "js": ["script2.js"]

  },

Here is what I wrote in script1.js:

chrome.runtime.sendMessage('hello world!!!!!!');

and in script2.js:

chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){

alert(response);

} );

I don't think I'm doing it the right way, I think I've to use the background.js but I don't know how.

Thanks very much in advance.

Body:
As you say, you have to use background script. For example:

script1:

chrome.runtime.sendMessage({from:"script1",message:"hello!"});

background.js

var tab2id;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.from == "script2") {
        tab2id = sender.tab.id;
    }
    if (message.from == "script1"){
        chrome.tabs.sendMessage(tab2id,message);
    }
});

script2.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    alert("Script1 says: " + message.message);
});
chrome.runtime.sendMessage({from:"script2"});

Remember to include your background script in manifest:

"background": {
    "scripts": ["background.js"]
}


问:
How to make enum accessible from other classes in XNA when enum is defined in main game class?
So I have my main game class and have created an enum for game state.
How do I make this enum accessible to other classes? I know you have to make it public but I cant seem to make it accessible to other classes.
What I'm trying to do is have a bunch of different classes to be able to check the current game state via enum and do different things depending on the current game state.</p>

答:
There are two main ways to do this.

Make the game state globally accessible, either through a global variable or a singleton.

Pass a game state supplier object to the objects needing to know the game state.

I prefer option 2 as it makes your dependencies more explicit.

```<code>public enum GameState
{
   Running,
   Paused
}

public interface IGame
{
   GameState State { get; }
}

public class SomeObject
{
   private IGame m_game;

   public SomeObject(IGame game)
   {
      m_game = game;
   }

   public void Update()
   {
      switch (m_game.State)
      {
         case GameState.Running:
            UpdateRunning();
            break;

         case GameState.Paused:
            UpdatePaused();
            break;
      }
   }
}

public class Game : IGame
{
   GameState m_state;
   SomeObject m_object;

   public Game()
   {
      m_object = new SomeObject(this);
      m_state = GameState.Running;
   }

   public GameState State
   {
      get
      {
         return m_state;
      }
   }
}
</code>```

However, exposing your game state to an object other than the game should be avoided if possible.  It breaks the encapsulation of your game and tightly couples your objects together.  Do the objects really need to know your game state or is there a more specific thing they need to know in order to operate?  Can you have two separate objects, one corresponding to each game state that are controlled by the game class?

Body:
There are two main ways to do this.

Make the game state globally accessible, either through a global variable or a singleton.

Pass a game state supplier object to the objects needing to know the game state.

I prefer option 2 as it makes your dependencies more explicit.

public enum GameState
{
   Running,
   Paused
}

public interface IGame
{
   GameState State { get; }
}

public class SomeObject
{
   private IGame m_game;

   public SomeObject(IGame game)
   {
      m_game = game;
   }

   public void Update()
   {
      switch (m_game.State)
      {
         case GameState.Running:
            UpdateRunning();
            break;

         case GameState.Paused:
            UpdatePaused();
            break;
      }
   }
}

public class Game : IGame
{
   GameState m_state;
   SomeObject m_object;

   public Game()
   {
      m_object = new SomeObject(this);
      m_state = GameState.Running;
   }

   public GameState State
   {
      get
      {
         return m_state;
      }
   }
}

However, exposing your game state to an object other than the game should be avoided if possible.  It breaks the encapsulation of your game and tightly couples your objects together.  Do the objects really need to know your game state or is there a more specific thing they need to know in order to operate?  Can you have two separate objects, one corresponding to each game state that are controlled by the game class?


问:
JS static files issues in AWS Production Django Application
I am having a weird issue where angular is undefined when application is deployed in AWS but locally there are no issues in my angular or javascript code.

Update:

My static files (JS, CSS, Images, etc) all live in an S3 static files bucket. There is no problem in retrieving the files, but it seems like suddenly a working commit that has been deployed for months just started raising JS issues when static files are being loaded.

Here are my JS files in my base template:

```<code>{% compress js %}
    <script src="{{STATIC_URL}}shared/stacktrace-js/dist/stacktrace.js"></script>
    <script src="{{STATIC_URL}}shared/jquery/2.1.1/jquery.min.js"></script>
    <script src="{{STATIC_URL}}shared/jquery-growl/1.2.3/jquery.growl.js"></script>
    <script src="{{STATIC_URL}}shared/jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
    <script src="{{STATIC_URL}}ckeditor/ckeditor-init.js"></script>
    <script src="{{STATIC_URL}}shared/ckeditor-custom/ckeditor-custom.js"></script>
    <script src="{{STATIC_URL}}shared/bootstrap/3.3.5/dist/js/bootstrap.min.js"></script>
    <script src="{{STATIC_URL}}shared/utils.js"></script>
    <script src="{{STATIC_URL}}shared/angular/1.3.11/angular.min.js"></script>
    <script src="{{STATIC_URL}}shared/angular/1.3.11/angular-route.min.js"></script>
    <script src="{{STATIC_URL}}shared/angular/1.3.11/angular-cookies.min.js"></script>
    <script src="{{STATIC_URL}}shared/angular-bootstrap/0.11.0/ui-bootstrap-tpls-0.11.0.min.js"></script>
    <script src="{{STATIC_URL}}shared/bootstrap-multiselect/bootstrap-multiselect.js"></script>
    <script src="{{STATIC_URL}}shared/introjs/intro.js"></script>
    <script type="text/django" src="{{STATIC_URL}}shared/ch-error-logging.js"></script>
    <script type="text/django" src="{{STATIC_URL}}shared/ch-config.js"></script>
    <script src="{{STATIC_URL}}shared/angulartics/dist/angulartics.min.js"></script>
    <script src="{{STATIC_URL}}shared/angulartics-segment/dist/angulartics-segment.min.js"></script>
    <script src="{{STATIC_URL}}shared/chart.js/dist/Chart.min.js"></script>
    <script src="{{STATIC_URL}}shared/select2/dist/js/select2.min.js"></script>
    <script src="{{STATIC_URL}}shared/angular-chart.js/dist/angular-chart.js"></script>
    <script src="{{STATIC_URL}}shared/jquery-validation/dist/jquery.validate.min.js"></script>
    <script type="text/django" src="{{STATIC_URL}}shared/ch-track.js"></script>
    <script type="text/django" src="{{STATIC_URL}}shared/ch-file.js"></script>
    <script src="{{STATIC_URL}}shared/offline.js"></script>
    {% endcompress %}
</code>```

If I change the jquery.min.js to jquery.js inside or outside the compress block, then other JS files begin raising syntax issues. Usually the error in Chrome's console says

Unexpected token (

And in Firefox, the error says

SyntaxError: function statement requires a name

答:
This post helped me figure out which JS files are causing compressed JS errors. Basically, I had issues with directives/controllers construction and by using the ng-strict-di, I found all these issues.

From the AngularJS ngApp documentation. https://docs.angularjs.org/api/ng/directive/ngApp

ngStrictDi (optional) boolean  if this attribute is present on the app
  element, the injector will be created in "strict-di" mode. This means
  that the application will fail to invoke functions which do not use
  explicit function annotation (and are thus unsuitable for
  minification), as described in the Dependency Injection guide, and
  useful debugging info will assist in tracking down the root of these
  bugs.

Body:
I am having a weird issue where angular is undefined when application is deployed in AWS but locally there are no issues in my angular or javascript code.

Update:

My static files (JS, CSS, Images, etc) all live in an S3 static files bucket. There is no problem in retrieving the files, but it seems like suddenly a working commit that has been deployed for months just started raising JS issues when static files are being loaded.

Here are my JS files in my base template:

{% compress js %}

    {% endcompress %}

If I change the jquery.min.js to jquery.js inside or outside the compress block, then other JS files begin raising syntax issues. Usually the error in Chrome's console says

Unexpected token (

And in Firefox, the error says

SyntaxError: function statement requires a name


问:
How can I dynamically generate DOM elements using ReactJS?
I have array with thee values:

```<code>let elements = ["div", "span", "button"]
</code>```

How can I dynamically generate these elements in DOM using forEach or map  iterator in ReactJS?

So as output I want to have:

 Value1

 Value 2
<button> Click me! </button>
```

答:
If you really want to do that, it's as simple as

```<code>React.createElement('div', {attribute: 'value'}, [children])
</code>```

Just replace 'div' with your variable. Docs

Body:
I have array with thee values:

let elements = ["div", "span", "button"]

How can I dynamically generate these elements in DOM using forEach or map  iterator in ReactJS?

So as output I want to have:

 Value1

 Value 2
<button> Click me! </button>

Body:
If you really want to do that, it's as simple as

React.createElement('div', {attribute: 'value'}, [children])

Just replace 'div' with your variable. Docs


问:
Adding contents using javascript on click
Trying to add one more row onClick using javascript. But it is not adding!

Tried the below code:

    $(document).ready(function(){
        var cont = 3
        var qty = "qty"
  var item = "item"
  var what = "service"
        $(".add-row").click(function(){
            var nameqty = qty+cont
   var nameitem = item+cont
   var namewhat = service+cont
            var markup = '
<select name="' + nameitem + '" class="country"><option>Select Item</option><option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select>	<select class="country" name="' + namewhat + '"></select>	<input type="text" name="' + nameqty + '" value="" placeholder="Quantity">
';
            $(markup).insertBefore($('button[type="submit"]').closest("tr"));
            cont++;
            console.log(qty)
   console.log(item)
   console.log(what)
        });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post" action="invoice_form.php" id="item_sel">

 <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
   <tr>
    <td colspan="3">
      <input type="text" name="customer" value="" placeholder="Customer Name">
    </td>
  </tr>
  <tr>
    <th>Item</th>
 <th>Service</th>
    <th>Qty</th>

  </tr>

    <tr>
   <td>
   <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select></td>

   <td><select class="country" name="service1">
</select></td>
<td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
    </tr>
 <tr>
   <td>
   <select name='item2' class='country'>
            <option>Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select></td>

   <td><select class="country" name="service2">
</select></td>
<td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
    </tr>
 <tr>
        <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
        <span class="glyphicon glyphicon-save"></span>   Save
        </button>
        </td>
    </tr>
</table>
    <input type="button" class="add-row" value="Add Row">
</form></code>```

Trying to add one more row on-click using javascript. But it is not adding!

I am not able to find what mistake I have made in the above code!

Please have a look at the snippet, basically 'JavaScript' part.

答:
You've two problems in your code :

You're service variable isn't defined.

You've a quotes problem in you're markup variable.

If you fix the both you're snippet should work as the snippet below shows.

I suggest the use of a model div that will be used in your JS for the creation of new items like :

```<code><div id="markup_model" class="hide">
    <table>
        <tr>
            <td>
                <select name="' + nameitem + '" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>
            </td>
            <td>
                <select class="country" name="' + namewhat + '"></select>
            </td>
            <td>
                <input type="text" name="' + nameqty + '" value="" placeholder="Quantity"/>
            </td>
        </tr>
    </table>
</div>
</code>```

Then in your JS code the markup will looks like :

```<code>var markup = $('#markup_model table').html();
</code>```

Hope this helps.

$(document).ready(function() {
  var cont = 3
  var qty = "qty"
  var item = "item"
  var what = "service"

  $(".add-row").click(function() {
    var nameqty = qty + cont;
    var nameitem = item + cont;
    var namewhat = what + cont;

    var markup = $('#markup_model tbody');

    $(markup).find('.country:eq(0)').attr('name', nameitem);
    $(markup).find('.country:eq(1)').attr('name', namewhat);
    $(markup).find('input').attr('name', nameqty);

    $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));

    cont++;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post" action="invoice_form.php" id="item_sel">
  <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
    <tr>
      <td colspan="3">
        <input type="text" name="customer" value="" placeholder="Customer Name">
      </td>
    </tr>
    <tr>
      <th>Item</th>
      <th>Service</th>
      <th>Qty</th>
    </tr>
    <tr>
      <td>
        <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select></td>

      <td><select class="country" name="service1">
</select></td>
      <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
      <td>
        <select name='item2' class='country'>
            <option>Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select></td>
      <td><select class="country" name="service2">
</select></td>
      <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
      <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default hide">
        <span class="glyphicon glyphicon-save"></span>   Save
        </button>
      </td>
    </tr>
  </table>
  <input type="button" class="add-row" value="Add Row">
</form><br><br><br>

<div id="markup_model" class="hide">
  <table>
    <tr>
      <td>
        <select name="nameitem" class="country">
                    <option>Select Item</option>
                </select>
      </td>
      <td>
        <select class="country" name="namewhat"></select>
      </td>
      <td>
        <input type="text" name="nameqty" value="" placeholder="Quantity" />
      </td>
    </tr>
  </table>
</div></code>```

Body:
Trying to add one more row onClick using javascript. But it is not adding!

Tried the below code:

    $(document).ready(function(){
        var cont = 3
        var qty = "qty"
  var item = "item"
  var what = "service"
        $(".add-row").click(function(){
            var nameqty = qty+cont
   var nameitem = item+cont
   var namewhat = service+cont
            var markup = '
<select name="' + nameitem + '" class="country"><option>Select Item</option><option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select>	<select class="country" name="' + namewhat + '"></select>	<input type="text" name="' + nameqty + '" value="" placeholder="Quantity">
';
            $(markup).insertBefore($('button[type="submit"]').closest("tr"));
            cont++;
            console.log(qty)
   console.log(item)
   console.log(what)
        });
    });

<form method="post" action="invoice_form.php" id="item_sel">

      <input type="text" name="customer" value="" placeholder="Customer Name">

    Item
 Service
    Qty

   <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select>

   <select class="country" name="service1">
</select>
<input type="text" name="qty1" value="" placeholder="Quantity">

   <select name='item2' class='country'>
            <option>Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select>

   <select class="country" name="service2">
</select>
<input type="text" name="qty2" value="" placeholder="Quantity">

        <button type="submit" name="btnsave" class="btn btn-default">
           Save
        </button>

    <input type="button" class="add-row" value="Add Row">
</form>

Trying to add one more row on-click using javascript. But it is not adding!

I am not able to find what mistake I have made in the above code!

Please have a look at the snippet, basically 'JavaScript' part.

Body:
You've two problems in your code :

You're service variable isn't defined.

You've a quotes problem in you're markup variable.

If you fix the both you're snippet should work as the snippet below shows.

I suggest the use of a model div that will be used in your JS for the creation of new items like :

<div id="markup_model" class="hide">
    <table>
        <tr>
            <td>
                <select name="' + nameitem + '" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>
            </td>
            <td>
                <select class="country" name="' + namewhat + '"></select>
            </td>
            <td>
                <input type="text" name="' + nameqty + '" value="" placeholder="Quantity"/>
            </td>
        </tr>
    </table>
</div>

Then in your JS code the markup will looks like :

var markup = $('#markup_model table').html();

Hope this helps.

$(document).ready(function() {
  var cont = 3
  var qty = "qty"
  var item = "item"
  var what = "service"

  $(".add-row").click(function() {
    var nameqty = qty + cont;
    var nameitem = item + cont;
    var namewhat = what + cont;

    var markup = $('#markup_model tbody');

    $(markup).find('.country:eq(0)').attr('name', nameitem);
    $(markup).find('.country:eq(1)').attr('name', namewhat);
    $(markup).find('input').attr('name', nameqty);

    $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));

    cont++;
  });
});

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form method="post" action="invoice_form.php" id="item_sel">
  <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
    <tr>
      <td colspan="3">
        <input type="text" name="customer" value="" placeholder="Customer Name">
      </td>
    </tr>
    <tr>
      <th>Item</th>
      <th>Service</th>
      <th>Qty</th>
    </tr>
    <tr>
      <td>
        <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select></td>

      <td><select class="country" name="service1">
</select></td>
      <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
      <td>
        <select name='item2' class='country'>
            <option>Select Item</option>
   <option value='ZZ2017TF11A1'>Shirt</option><option value='ZZ2017TF11A2'>Pant</option></select></td>
      <td><select class="country" name="service2">
</select></td>
      <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
      <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default hide">
        <span class="glyphicon glyphicon-save"></span> &nbsp; Save
        </button>
      </td>
    </tr>
  </table>
  <input type="button" class="add-row" value="Add Row">
</form><br><br><br>

<div id="markup_model" class="hide">
  <table>
    <tr>
      <td>
        <select name="nameitem" class="country">
                    <option>Select Item</option>
                </select>
      </td>
      <td>
        <select class="country" name="namewhat"></select>
      </td>
      <td>
        <input type="text" name="nameqty" value="" placeholder="Quantity" />
      </td>
    </tr>
  </table>
</div>


问:
load balancing postgres instances via aws network balancer possible?
We have an application that has multiple postgres databases (that are guaranteed to be in sync) installed on AWS EC2 instances in different availability zones. I would like to abstract them behind a single DNS so that, if one of the EC2 instances crashes, the clients can still access the db. I am wondering if I can use an AWS network load balancer to load balance my databases? Why or why not? If not, is there any other standard, easy-to-implement solution that I can use? (I am aware of http://www.pgpool.net/mediawiki/index.php/Main_Page for example. However, am leery of using something that I have to setup myself, especially since I would have to replicate pgpool instances as well...)</p>

答:
Having just tried it myself, it does seem you can set up a network load balancer to load balance your databases.  My production setup uses patroni to manage failover, and patroni provides an HTTP API for health checks.  The master returns a 200 response, while the replicas return a 503.  This works fine for my use case, where the replicas are there just for failover, not for replicated reads.  I'm assuming you could come up with some code that returns a successful response for health checks based on your needs.

I configured the load balancer to listen to port 5432 and the health checks to connect on port 8008.  I modified the security group for the postgres instances to allow connections from my VPC's IP range, since the NLB doesn't have security groups. Connecting via psql to the NLB's DNS name worked as expected.

Though it works, I think I'll stick with my current setup, which has a PgBouncer running on each application instance (so no need to worry managing a pool of bouncer instances) with consul-template updating pgbouncer.ini and reloading PgBouncer when the leader key changes in consul.


问:
How to add a line number to each row of a tabularinline block
I have a ModelAdmin class with an inline of type TabularInline. What I would like is for each row of the TabularInline to have a line number displayed to the left of it. This number would increment as new records are added to the inline, and would be displayed when the form is being edited.

I prefer the line number not be a part of the model for the inlined data, but rather be generated each time a new record is added to or displayed by the inline block. I don't need to keep this number in the database. It is for reference only on another field in the ModelAdmin class.

I'm new to django, and I can't seem to figure out how to make this happen.

Any suggestions would be appreciated.

Regards,
Rick

答:
You can number existing inlines easily through the admin class with a class variable and a method to return the line number:

```<code>class MyInlineAdmin(admin.TabularInline):
    line_numbering = 0
    fields = ('line_number', 'other_field')
    readonly_fields = ('line_number',)

    def line_number(self, obj):
        self.line_numbering += 1
        return self.line_numbering

    line_number.short_description = '#'
</code>```

This will number any inlines in the order they appear, including any extra (blank) inlines that are included. If you add a single inline via the "Add another" link, it's line number will be correct (incremented by one from the last one), however if you add more than one inline via the link, subsequent ones will still have the same line number as the last one.

Not perfect, but better than nothing.

Body:
You can number existing inlines easily through the admin class with a class variable and a method to return the line number:

class MyInlineAdmin(admin.TabularInline):
    line_numbering = 0
    fields = ('line_number', 'other_field')
    readonly_fields = ('line_number',)

    def line_number(self, obj):
        self.line_numbering += 1
        return self.line_numbering

    line_number.short_description = '#'

This will number any inlines in the order they appear, including any extra (blank) inlines that are included. If you add a single inline via the "Add another" link, it's line number will be correct (incremented by one from the last one), however if you add more than one inline via the link, subsequent ones will still have the same line number as the last one.

Not perfect, but better than nothing.