问:
better way to counting result and read row in php
the first, my current code is

```<code>$sql = "SELECT COUNT(id) AS total FROM mytable WHERE something = ".$likethis;
$query = mysqli_query($connection, $sql);
$result = mysqli_fetch_object($query);
</code>```

if the result give 1 or more data, then i do this query to get the data

```<code>$sql = "SELECT col1, col2, col3 FROM mytable WHERE something = ".$likethis;
</code>```

the second one, another method i found is using this code

```<code>$totalRow = mysqli_num_rows($query);
</code>```

then if give 1 or more, i do fetch the data.

in my head now is, the first one is fast on counting data then only do the rest if have result. but need connect to database twice.
the second one is slower because need to read all data but only connect to database once.

i'm not sure my opinion is accurate it just by how much php read database, and not sure actually which one is better.

or maybe there are other better way to do:

- check how much row it have

- get the rows if have

答:
You can set flag for check you can get row/rows or not. If you can't get any row from database flag is true.

For e.g.

```<code>$query = mysqli_query($connection,"select * from `test`");
$flag = true;
while($rows = mysqli_fetch_array($query)){
    $flag = false;
    // Do stuff.
}
if($flag){
    echo "No record found.";
}
</code>```

If can not get results code will print else part.

Body:
the first, my current code is

$sql = "SELECT COUNT(id) AS total FROM mytable WHERE something = ".$likethis;
$query = mysqli_query($connection, $sql);
$result = mysqli_fetch_object($query);

if the result give 1 or more data, then i do this query to get the data

$sql = "SELECT col1, col2, col3 FROM mytable WHERE something = ".$likethis;

the second one, another method i found is using this code

$totalRow = mysqli_num_rows($query);

then if give 1 or more, i do fetch the data.

in my head now is, the first one is fast on counting data then only do the rest if have result. but need connect to database twice.
the second one is slower because need to read all data but only connect to database once.

i'm not sure my opinion is accurate it just by how much php read database, and not sure actually which one is better.

or maybe there are other better way to do:

- check how much row it have

- get the rows if have

Body:
You can set flag for check you can get row/rows or not. If you can't get any row from database flag is true.

For e.g.

$query = mysqli_query($connection,"select * from `test`");
$flag = true;
while($rows = mysqli_fetch_array($query)){
    $flag = false;
    // Do stuff.
}
if($flag){
    echo "No record found.";
}

If can not get results code will print else part.


来源: stackexchange

问:
Can Firefox be forced to use ssl instead of tls
I would like to force firefox 56 to use ssl instead of tls1.2 despite that SSL 3.0 is considered unsafe.
My intend is to produce an error like ...no overlap ....  and take a screenshot of this error.

Preferences in about:config

According to my understanding of the firefox docs for security.tls.version* I have set

security.tls.version.min = 0 and

security.tls.version.max = 1

The docs for security.tls.version* also point out:

These preferences replace the deprecated security.enable_ssl3 and
security.enable_tls boolean settings. Upon upgrade, the old
preferences are not automatically migrated.

So i checked if deprecated preference might be in conflict with my settings above. But my Firefox 56 installation has no preferences that start with security.enable_. So it seems that i do not have to worry about any deprecated settings.

Additional causes might be

that Upgrade-Insecure-Requests interferes with my intent to use ssl3,

that the rc4 cipher was planned to be removed and security.tls.unrestricted_rc4_fallback was removed in Firefox 50 and can no longer be overridden.

Is the certificate the cause

The website uses a certificate that has these characteristics:

The connection to this site uses a strong protocol (TLS 1.2), an
obsolete key exchange (RSA), and an obsolete cipher (AES_256_CBC with
HMAC-SHA1).

After reading this reply i assumed that the cipher used is not part of TLSV1 but running the command below seem to prove that the cipher used is a SSL3 supported cipher.

```<code>openssl ciphers -v 'TLSv1' | grep "AES" | grep "256" | grep "CBC" | sort
// output
PSK-AES256-CBC-SHA      SSLv3 Kx=PSK      Au=PSK  Enc=AES(256)  Mac=SHA1
SRP-AES-256-CBC-SHA     SSLv3 Kx=SRP      Au=SRP  Enc=AES(256)  Mac=SHA1
SRP-DSS-AES-256-CBC-SHA SSLv3 Kx=SRP      Au=DSS  Enc=AES(256)  Mac=SHA1
SRP-RSA-AES-256-CBC-SHA SSLv3 Kx=SRP      Au=RSA  Enc=AES(256)  Mac=SHA1
</code>```

Update

HSTS - Strict-Transport-Security HTTP response header field

This question Is firefox disabling of insecure TLS fallback part of the HSTS spec might be related.

The HTTP Strict Transport Security chapter 5.1 (HSTS - rfc 6797) contains

An HTTP host declares itself an HSTS Host by issuing to UAs an HSTS

Policy, which is represented by and conveyed via the

Strict-Transport-Security HTTP response header field over secure

transport

The site in question has these header fields among others

```<code>p3p: CP="NON CUR OTPi OUR NOR UNI"
vary: Accept-Encoding
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
cache-control: max-age=315360000, public
expires: Sat, 03 Jul 2027 00:48:12 GMT
x-xss-protection: 1; mode=block
strict-transport-security: max-age=31536000; includeSubDomains
</code>```

Questions (tl;dr)

It seems that firefox from version 50 on and above can not be forced to use ssl3. Is this the case? If not how can it be achieved?

To my understanding the certificate signing request (CSR) is the first step to get a certificate. Does the CSR already contain the ciphers and protocols that must be used in a https-connection later?

See also

Firefox Error_loading_secure_sites page

答:
Answer for Question 1: Force firefox to use a weak encryption

I was unable to force a current firefox (v 54) to use a weak encryption. As this reddit thread suggested i downloaded Firefox 30.0 portable from sourceforge and after setting security.tls.version.max = 1 was able to force the desired error Firefox Secure connection failed: ssl_error_no_cypher_overlap

This is the screenshot i was after:

Question 2: Does the CSR already contain the ciphers and protocols that must be used?

This is still unclear to me.

ContentLicense: CC BY-SA 3.0

Body:
I would like to force firefox 56 to use ssl instead of tls1.2 despite that SSL 3.0 is considered unsafe.
My intend is to produce an error like ...no overlap ....  and take a screenshot of this error.

Preferences in about:config

According to my understanding of the firefox docs for security.tls.version* I have set

security.tls.version.min = 0 and

security.tls.version.max = 1

The docs for security.tls.version* also point out:

These preferences replace the deprecated security.enable_ssl3 and
security.enable_tls boolean settings. Upon upgrade, the old
preferences are not automatically migrated.

So i checked if deprecated preference might be in conflict with my settings above. But my Firefox 56 installation has no preferences that start with security.enable_. So it seems that i do not have to worry about any deprecated settings.

Additional causes might be

that Upgrade-Insecure-Requests interferes with my intent to use ssl3,

that the rc4 cipher was planned to be removed and security.tls.unrestricted_rc4_fallback was removed in Firefox 50 and can no longer be overridden.

Is the certificate the cause

The website uses a certificate that has these characteristics:

The connection to this site uses a strong protocol (TLS 1.2), an
obsolete key exchange (RSA), and an obsolete cipher (AES_256_CBC with
HMAC-SHA1).

After reading this reply i assumed that the cipher used is not part of TLSV1 but running the command below seem to prove that the cipher used is a SSL3 supported cipher.

openssl ciphers -v 'TLSv1' | grep "AES" | grep "256" | grep "CBC" | sort
// output
PSK-AES256-CBC-SHA      SSLv3 Kx=PSK      Au=PSK  Enc=AES(256)  Mac=SHA1
SRP-AES-256-CBC-SHA     SSLv3 Kx=SRP      Au=SRP  Enc=AES(256)  Mac=SHA1
SRP-DSS-AES-256-CBC-SHA SSLv3 Kx=SRP      Au=DSS  Enc=AES(256)  Mac=SHA1
SRP-RSA-AES-256-CBC-SHA SSLv3 Kx=SRP      Au=RSA  Enc=AES(256)  Mac=SHA1

Update

HSTS - Strict-Transport-Security HTTP response header field

This question Is firefox disabling of insecure TLS fallback part of the HSTS spec might be related.

The HTTP Strict Transport Security chapter 5.1 (HSTS - rfc 6797) contains

An HTTP host declares itself an HSTS Host by issuing to UAs an HSTS

Policy, which is represented by and conveyed via the

Strict-Transport-Security HTTP response header field over secure

transport

The site in question has these header fields among others

p3p: CP="NON CUR OTPi OUR NOR UNI"
vary: Accept-Encoding
x-frame-options: SAMEORIGIN
x-content-type-options: nosniff
cache-control: max-age=315360000, public
expires: Sat, 03 Jul 2027 00:48:12 GMT
x-xss-protection: 1; mode=block
strict-transport-security: max-age=31536000; includeSubDomains

Questions (tl;dr)

It seems that firefox from version 50 on and above can not be forced to use ssl3. Is this the case? If not how can it be achieved?

To my understanding the certificate signing request (CSR) is the first step to get a certificate. Does the CSR already contain the ciphers and protocols that must be used in a https-connection later?

See also

Firefox Error_loading_secure_sites page


问:
Creating a Gin Index with Trigram (gin_trgm_ops) in Django model
The new TrigramSimilarity feature of the django.contrib.postgres was great for a problem I had. I use it for a search bar to find hard to spell latin names. The problem is that there are over 2 million names, and the search takes longer then I want.

I'd like to create a index on the trigrams as descibed in the postgres documentation.

But I am not sure how to do this in a way that the Django API would make use of it. For the postgres text search there is a description on how to create an index, but not for the trigram similarity.

This is what I have right now:

class NCBI_names(models.Model):
    tax_id          =   models.ForeignKey(NCBI_nodes, on_delete=models.CASCADE, default = 0)
    name_txt        =   models.CharField(max_length=255, default = '')
    name_class      =   models.CharField(max_length=32, db_index=True, default = '')

    class Meta:
        indexes = [GinIndex(fields=['name_txt'])]
```
<p>In the view's <code>get_queryset</code> method:</p>
<pre class="lang-python prettyprint-override"><code>class TaxonSearchListView(ListView):
    #form_class=TaxonSearchForm
    template_name='collectie/taxon_list.html'
    paginate_by=20
    model=NCBI_names
    context_object_name = 'taxon_list'

    def dispatch(self, request, *args, **kwargs):
        query = request.GET.get('q')
        if query:
            try:
                tax_id = self.model.objects.get(name_txt__iexact=query).tax_id.tax_id
                return redirect('collectie:taxon_detail', tax_id)
            except (self.model.DoesNotExist, self.model.MultipleObjectsReturned) as e:
                return super(TaxonSearchListView, self).dispatch(request, *args, **kwargs)
        else:
            return super(TaxonSearchListView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        result = super(TaxonSearchListView, self).get_queryset()
        #
        query = self.request.GET.get('q')
        if query:
            result = result.exclude(name_txt__icontains = 'sp.')
            result = result.annotate(similarity=TrigramSimilarity('name_txt', query)).filter(similarity__gt=0.3).order_by('-similarity')
        return result
</code>```

答:
I had a similar problem, trying to use the pg_tgrm extension to support efficient contains and icontains Django field lookups.

There may be a more elegant way, but defining a new index type like this worked for me:

```<code>from django.contrib.postgres.indexes import GinIndex

class TrigramIndex(GinIndex):
    def get_sql_create_template_values(self, model, schema_editor, using):
        fields = [model._meta.get_field(field_name) for field_name, order in self.fields_orders]
        tablespace_sql = schema_editor._get_index_tablespace_sql(model, fields)
        quote_name = schema_editor.quote_name
        columns = [
            ('%s %s' % (quote_name(field.column), order)).strip() + ' gin_trgm_ops'
            for field, (field_name, order) in zip(fields, self.fields_orders)
        ]
        return {
            'table': quote_name(model._meta.db_table),
            'name': quote_name(self.name),
            'columns': ', '.join(columns),
            'using': using,
            'extra': tablespace_sql,
        }
</code>```

The method get_sql_create_template_values is copied from Index.get_sql_create_template_values(), with just one modification: the addition of + ' gin_trgm_ops'.

For your use case, you would then define the index on name_txt using this TrigramIndex instead of a GinIndex. Then run makemigrations, which will produce a migration that generates the required CREATE INDEX SQL.

UPDATE:

I see you're also doing a query using icontains:

```<code>result.exclude(name_txt__icontains = 'sp.')
</code>```

The Postgresql backend will turn that into something like this:

```<code>UPPER("NCBI_names"."name_txt"::text) LIKE UPPER('sp.')
</code>```

and then the trigram index won't be used because of the UPPER().

I had the same problem, and ended up subclassing the database backend to work around it:

```<code>from django.db.backends.postgresql import base, operations

class DatabaseFeatures(base.DatabaseFeatures):
    pass

class DatabaseOperations(operations.DatabaseOperations):
    def lookup_cast(self, lookup_type, internal_type=None):
        lookup = '%s'

        # Cast text lookups to text to allow things like filter(x__contains=4)
        if lookup_type in ('iexact', 'contains', 'icontains', 'startswith',
                           'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'):
            if internal_type in ('IPAddressField', 'GenericIPAddressField'):
                lookup = "HOST(%s)"
            else:
                lookup = "%s::text"

        return lookup

class DatabaseWrapper(base.DatabaseWrapper):
    """
        Override the defaults where needed to allow use of trigram index
    """
    ops_class = DatabaseOperations

    def __init__(self, *args, **kwargs):
        self.operators.update({
            'icontains': 'ILIKE %s',
            'istartswith': 'ILIKE %s',
            'iendswith': 'ILIKE %s',
        })
        self.pattern_ops.update({
            'icontains': "ILIKE '%%' || {} || '%%'",
            'istartswith': "ILIKE {} || '%%'",
            'iendswith': "ILIKE '%%' || {}",
        })
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The new TrigramSimilarity feature of the django.contrib.postgres was great for a problem I had. I use it for a search bar to find hard to spell latin names. The problem is that there are over 2 million names, and the search takes longer then I want.

I'd like to create a index on the trigrams as descibed in the postgres documentation.

But I am not sure how to do this in a way that the Django API would make use of it. For the postgres text search there is a description on how to create an index, but not for the trigram similarity.

This is what I have right now:

class NCBI_names(models.Model):
    tax_id          =   models.ForeignKey(NCBI_nodes, on_delete=models.CASCADE, default = 0)
    name_txt        =   models.CharField(max_length=255, default = '')
    name_class      =   models.CharField(max_length=32, db_index=True, default = '')

    class Meta:
        indexes = [GinIndex(fields=['name_txt'])]

In the view's get_queryset method:

class TaxonSearchListView(ListView):
    #form_class=TaxonSearchForm
    template_name='collectie/taxon_list.html'
    paginate_by=20
    model=NCBI_names
    context_object_name = 'taxon_list'

    def dispatch(self, request, *args, **kwargs):
        query = request.GET.get('q')
        if query:
            try:
                tax_id = self.model.objects.get(name_txt__iexact=query).tax_id.tax_id
                return redirect('collectie:taxon_detail', tax_id)
            except (self.model.DoesNotExist, self.model.MultipleObjectsReturned) as e:
                return super(TaxonSearchListView, self).dispatch(request, *args, **kwargs)
        else:
            return super(TaxonSearchListView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        result = super(TaxonSearchListView, self).get_queryset()
        #
        query = self.request.GET.get('q')
        if query:
            result = result.exclude(name_txt__icontains = 'sp.')
            result = result.annotate(similarity=TrigramSimilarity('name_txt', query)).filter(similarity__gt=0.3).order_by('-similarity')
        return result

Body:
I had a similar problem, trying to use the pg_tgrm extension to support efficient contains and icontains Django field lookups.

There may be a more elegant way, but defining a new index type like this worked for me:

from django.contrib.postgres.indexes import GinIndex

class TrigramIndex(GinIndex):
    def get_sql_create_template_values(self, model, schema_editor, using):
        fields = [model._meta.get_field(field_name) for field_name, order in self.fields_orders]
        tablespace_sql = schema_editor._get_index_tablespace_sql(model, fields)
        quote_name = schema_editor.quote_name
        columns = [
            ('%s %s' % (quote_name(field.column), order)).strip() + ' gin_trgm_ops'
            for field, (field_name, order) in zip(fields, self.fields_orders)
        ]
        return {
            'table': quote_name(model._meta.db_table),
            'name': quote_name(self.name),
            'columns': ', '.join(columns),
            'using': using,
            'extra': tablespace_sql,
        }

The method get_sql_create_template_values is copied from Index.get_sql_create_template_values(), with just one modification: the addition of + ' gin_trgm_ops'.

For your use case, you would then define the index on name_txt using this TrigramIndex instead of a GinIndex. Then run makemigrations, which will produce a migration that generates the required CREATE INDEX SQL.

UPDATE:

I see you're also doing a query using icontains:

result.exclude(name_txt__icontains = 'sp.')

The Postgresql backend will turn that into something like this:

UPPER("NCBI_names"."name_txt"::text) LIKE UPPER('sp.')

and then the trigram index won't be used because of the UPPER().

I had the same problem, and ended up subclassing the database backend to work around it:

from django.db.backends.postgresql import base, operations

class DatabaseFeatures(base.DatabaseFeatures):
    pass

class DatabaseOperations(operations.DatabaseOperations):
    def lookup_cast(self, lookup_type, internal_type=None):
        lookup = '%s'

        # Cast text lookups to text to allow things like filter(x__contains=4)
        if lookup_type in ('iexact', 'contains', 'icontains', 'startswith',
                           'istartswith', 'endswith', 'iendswith', 'regex', 'iregex'):
            if internal_type in ('IPAddressField', 'GenericIPAddressField'):
                lookup = "HOST(%s)"
            else:
                lookup = "%s::text"

        return lookup

class DatabaseWrapper(base.DatabaseWrapper):
    """
        Override the defaults where needed to allow use of trigram index
    """
    ops_class = DatabaseOperations

    def __init__(self, *args, **kwargs):
        self.operators.update({
            'icontains': 'ILIKE %s',
            'istartswith': 'ILIKE %s',
            'iendswith': 'ILIKE %s',
        })
        self.pattern_ops.update({
            'icontains': "ILIKE '%%' || {} || '%%'",
            'istartswith': "ILIKE {} || '%%'",
            'iendswith': "ILIKE '%%' || {}",
        })
        super(DatabaseWrapper, self).__init__(*args, **kwargs)


问:
Spring Environment Variable
I was planning to use @Value annotation to my service implementation class.

```<code> @Value("${some_property:default_value}")
 private String key;
</code>```

To use above annotation, I can use @Autowiredannotation.

```<code> @Autowird
 Private Environment environment;
</code>```

But, I am planning to use those setting in my applicationContext.xml file, which is something like following below.

```<code><context: something missing here = "ENVIRONMENT"/>
</code>```

答: Yes. You can do it  in applicationContext.xml beans tag itself there is a property called profile So you can do  profile="ENVIRONMENT" in latest spring version.

Title: Spring Environment Variable

Body:
I was planning to use @Value annotation to my service implementation class.

 @Value("${some_property:default_value}")
 private String key;

To use above annotation, I can use @Autowiredannotation.

 @Autowird
 Private Environment environment;

But, I am planning to use those setting in my applicationContext.xml file, which is something like following below.

<context: something missing here = "ENVIRONMENT"/>


问:
Is there any way to get numbers separated by comma?
I have

```<code>line = "abcde:abc/abcd=(12, 20)"
</code>```

and I want to get 12 and 20 in an array. My solution is:

```<code>array_line = line[/\(.*?\)/].delete('()').delete(' ').split(",")
</code>```

Is there any better way to solve it using ruby?

答:
This if you want an array of strings

```<code>line.scan(/\d+/) #=> ["12", "20"]
</code>```

or an array of numbers

```<code>line.scan(/\d+/).map(&:to_i) #=> [12, 20]
</code>```

As per comments another example and method:

```<code>line = "abcde:123, type/onetwothree = (12, 20)"
line[/(?<=\()[0-9,\s]+(?=\))/].split(', ') #=> ["12", "20"]
</code>```

Here we use a lookahead and a lookbehind to match only the numbers in between the brackets.

Body:
I have

line = "abcde:abc/abcd=(12, 20)"

and I want to get 12 and 20 in an array. My solution is:

array_line = line[/\(.*?\)/].delete('()').delete(' ').split(",")

Is there any better way to solve it using ruby?

Body:
This if you want an array of strings

line.scan(/\d+/) #=> ["12", "20"]

or an array of numbers

line.scan(/\d+/).map(&:to_i) #=> [12, 20]

As per comments another example and method:

line = "abcde:123, type/onetwothree = (12, 20)"
line[/(?<=\()[0-9,\s]+(?=\))/].split(', ') #=> ["12", "20"]

Here we use a lookahead and a lookbehind to match only the numbers in between the brackets.


问:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

```<code>>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true
</code>```

答:
These looks like a duplicate question but I've always just used something like this

```<code>var x = new Array(10);
for (var i = 0; i < 10; i++) {
  x[i] = new Array(10).fill(false);
}
x[5][5] = true
</code>```

Credit: How can I create a two dimensional array in JavaScript?

Body:
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Body:
These looks like a duplicate question but I've always just used something like this

var x = new Array(10);
for (var i = 0; i < 10; i++) {
  x[i] = new Array(10).fill(false);
}
x[5][5] = true

Credit: How can I create a two dimensional array in JavaScript?


问:
Simulating click event inside JavaScript OnClick results in error
I am building a context menu with some options using
 tags as shown below. I need to simulate click event on another ID (image), When i choose and click on this option from context menu.. I can only have the function instantaneous execution inside onclick as shown in below code-

Edited the code to give more clarity

```<code>var functionMain = function ContextMenu$functionMain(items, targetId) {
    $(menu).html(buildItems(items, targetId));
};

var buildItems = function ContextMenu$buildItems(items, targetId) {
    var i, result;
    result = '';
    for (i = 0; i < items.length; ++i) {
        var reportId = targetId.substring(targetId.indexOf(':') + 1);
        var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);
        result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){'+ reportIdFormed+'.trigger(\'click\'); })();"> Run HTML </a></li>';
    }
    return result;
};
</code>```

Above code is resulting in Uncaught SyntaxError: Unexpected identifier

Resultant HTML --> Run HTML

How to get rid of this issue?

答:
Try this</p>

```<code>var reportId = targetId.substring(targetId.indexOf(':') + 1); //e.g. rpt1234
var reportIdFormed = reportId + 'run' + runReportLinkName; //e.g. rpt1234runHTML
result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){document.getElementById(\''+ reportIdFormed+'\').trigger(\'click\'); })();"> Run HTML </a></li>';
</code>```

Body:
I am building a context menu with some options using
 tags as shown below. I need to simulate click event on another ID (image), When i choose and click on this option from context menu.. I can only have the function instantaneous execution inside onclick as shown in below code-

Edited the code to give more clarity

var functionMain = function ContextMenu$functionMain(items, targetId) {
    $(menu).html(buildItems(items, targetId));
};

var buildItems = function ContextMenu$buildItems(items, targetId) {
    var i, result;
    result = '';
    for (i = 0; i < items.length; ++i) {
        var reportId = targetId.substring(targetId.indexOf(':') + 1);
        var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);
        result += '
 Run HTML
';
    }
    return result;
};

Above code is resulting in Uncaught SyntaxError: Unexpected identifier

Resultant HTML --> Run HTML

How to get rid of this issue?

Body:
Try this

var reportId = targetId.substring(targetId.indexOf(':') + 1); //e.g. rpt1234
var reportIdFormed = reportId + 'run' + runReportLinkName; //e.g. rpt1234runHTML
result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){document.getElementById(\''+ reportIdFormed+'\').trigger(\'click\'); })();"> Run HTML </a></li>';


问:
Link two tables with Order: MySQL and PHP
I have this table called user_friends:

```<code>accid  |  user1  |  user2
1       mark_12     john_24
2       john_24     jim_01
3       mark_12     jim_01
4       nico_7      mark_12
</code>```

And this table called users_students:

```<code>studentuniqueid  |  firstname  |  lastname  |  age
mark_12           Mark Anthony   Sierra       20
john_24           Johhny         Powers       21
jim_01            James          Sanders      21
nico_7            Nicolai        Renade       19
janice_53         Janice         Allaine      24
peter_41          Peter          Allan        21
</code>```

Now, here's what I wanted to do:

1.Select all entry/data in the user_friends table that has mark_12 (Mark's ID). Mark's ID could either be on user1 or user2 right? So I can just use SELECT * FROM user_friends WHERE user1 = 'mark_12' OR user2 = 'mark_12' and echo its accid, it will then display:

1, 3, 4 since mark_12 appears on those entries on the table.

2.Now I want to select and link the user_friends and users_student so that I could alphabetically arrange Mark's friends based on the user_friends table ORDERING them based on the lastname on the users_student table. I know this is possible, I just don't know how to do it yet.

I tried:

```<code>$user_id = $_SESSION['id'];
$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN IN (user_friends.user1,user_friends.user2)=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";
</code>```

And also:

```<code>$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN user_friends.user1,user_friends.user2=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";
</code>```

But somehow didn't work.
I want to achieve something like:

```<code>Mark's Friends:

Johnny Powers
Nicolai Renade
James Sanders
</code>```

答:
you should use inner join on the result for the select for filter the accid</p>

```<code>  select
      t.accid
    , users_student.studentuniqueid
    , users_student.firstname,
    , users_student.lastname
  from (
  select accid
  from user_friends
  where user1 = 'mark_12'
  or user2 = 'mark_12'
  ) t on. t.accid = users_student.studentuniqueid
  order by users_student.lastname ASC
</code>```

Body:
I have this table called user_friends:

accid  |  user1  |  user2
1       mark_12     john_24
2       john_24     jim_01
3       mark_12     jim_01
4       nico_7      mark_12

And this table called users_students:

studentuniqueid  |  firstname  |  lastname  |  age
mark_12           Mark Anthony   Sierra       20
john_24           Johhny         Powers       21
jim_01            James          Sanders      21
nico_7            Nicolai        Renade       19
janice_53         Janice         Allaine      24
peter_41          Peter          Allan        21

Now, here's what I wanted to do:

1.Select all entry/data in the user_friends table that has mark_12 (Mark's ID). Mark's ID could either be on user1 or user2 right? So I can just use SELECT * FROM user_friends WHERE user1 = 'mark_12' OR user2 = 'mark_12' and echo its accid, it will then display:

1, 3, 4 since mark_12 appears on those entries on the table.

2.Now I want to select and link the user_friends and users_student so that I could alphabetically arrange Mark's friends based on the user_friends table ORDERING them based on the lastname on the users_student table. I know this is possible, I just don't know how to do it yet.

I tried:

$user_id = $_SESSION['id'];
$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN IN (user_friends.user1,user_friends.user2)=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";

And also:

$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN user_friends.user1,user_friends.user2=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";

But somehow didn't work.
I want to achieve something like:

Mark's Friends:

Johnny Powers
Nicolai Renade
James Sanders

Body:
you should use inner join on the result for the select for filter the accid

  select
      t.accid
    , users_student.studentuniqueid
    , users_student.firstname,
    , users_student.lastname
  from (
  select accid
  from user_friends
  where user1 = 'mark_12'
  or user2 = 'mark_12'
  ) t on. t.accid = users_student.studentuniqueid
  order by users_student.lastname ASC


问:
How to Create a Multiple Question?
I need to retrieve 6 questions from a plist and check the answer if is correct from the plist itself??

i will use a QR code scanner api to scan for answer, the api will covert to a string and read from the plist to check if the answer is correct... is there any tutorial or references for me to look @ ??

In my plist there is:
question ~ Dictionary with the following strings:

NumberOfOption ~ which define if the question is a multiple choice or a QR code question
Question ~ question itself
Answer ~ Answer itself
Option 1 ~ 4 ~ if it is a multiple choice question

Thanks in advance for answering my questions, i appreciated it

cheers

Desmond

答: Depending on how your plists are structured, you can read them in to memory using [NSArray arrayWithContentsOfFile:...]; or [NSDictionary dictionaryWithContentsOfFile:...];.  Beyond that, it really depends on how your plist is structured, how your input is coming in, etc.

ContentLicense: CC BY-SA 2.5

Title: How to Create a Multiple Question?


答:
you can use </p>

```<code>select * from user_students where StudentUniqueId in (select user1 from user_friends where user2='mark_12' union select user2 from user_friends where user1 ='mark_12');
</code>```

Title: Link two tables with Order: MySQL and PHP

Body:
you can use

select * from user_students where StudentUniqueId in (select user1 from user_friends where user2='mark_12' union select user2 from user_friends where user1 ='mark_12');


问:
How to set image1 overlap image2 android
How to set image1 overlap image2

I want to set image1(by Drawable) overlap image2(by bitmap)

example

In the example above

icon play is image1 and picture is image2

I found slove is only image1 and image2 is by drawable

and If image2 is by bitmap ,I have no idea to set it

ps. sorry my english is not good.

答:
ImageView having extra properties to set extra bitmap or icon or drawable other than normal Background in View properties,

So for your case, you can set Play icon as src(which will come on top of background and center) and Bitmap you can set as Background

```<code><ImageView
            android:id="@+id/video"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/msg_media_play_small_icon" >
        </ImageView>
</code>```

and to set the Background Image, don't use imageView.setImageBitmap
use imageView.setBackground

```<code>imageview.setBackground(new BitmapDrawable(context.getResources(), bitmap));
</code>```

Body:
ImageView having extra properties to set extra bitmap or icon or drawable other than normal Background in View properties,

So for your case, you can set Play icon as src(which will come on top of background and center) and Bitmap you can set as Background

<ImageView
            android:id="@+id/video"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/msg_media_play_small_icon" >
        </ImageView>

and to set the Background Image, don't use imageView.setImageBitmap
use imageView.setBackground

imageview.setBackground(new BitmapDrawable(context.getResources(), bitmap));


问:
DataGridView retrieve entire row
I'm using CellClick to open a message box and show the row contents of a single row from a DataGridView in a form. I was stumped in trying to find something more elegant than what I've got so far. I was searching for a way to display the contents of the column header, and the row value, possibly using foreach or a for loop, but no avail. Any recommendations?</p>

```<code>private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (authorDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show("Author Number: " + authorDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()
                + "\nAuthor First Name: " + authorDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()
                + "\nAuthor Last Name: " + authorDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString());
        }
    }
</code>```

答:
You can get a reference to the row, which simplifies it a bit.

```<code>DataGridViewRow authorRow = authorDataGridView.Rows[e.RowIndex];
if (authorRow.Cells[e.ColumnIndex].Value != null)
{
    MessageBox.Show("Author Number: " + authorRow.Cells[0].Value.ToString()
            + "\nAuthor First Name: " + authorRow.Cells[1].Value.ToString()
            + "\nAuthor Last Name: " + authorRow.Cells[2].Value.ToString());
}
</code>```

If you want the Column Header text, I think its:

```<code>DataGridViewColumn col = authorDataGridView.Column[e.ColumnIndex]
</code>```

and then you can get the header text from:

```<code>col.HeaderText;
</code>```

If you're going to do something like this a lot, you could encapsulate what you want in a function:

```<code>    public string ParseRowText(DataGridView grid, DataGridViewCellEventArgs e)
    {
        DataGridViewRow row = grid.Rows[e.RowIndex];
        string output = "";
        for (int col = 0; col < grid.Columns.Count; col++)
        {
            //Get column header and cell contents
            output = output + grid.Columns[col].HeaderText + ": " + row.Cells[col].Value.ToString() + Environment.NewLine;
        }
        return output;
    }
</code>```

Is that the sort of thing you're after, where the Column Headers are "Author Number", "Author First Name", "Author Last Name" etc?

You'd then call it via:

```<code>private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show(ParseRowText(this, e));
}
</code>```

Title: DataGridView retrieve entire row

Body:
I'm using CellClick to open a message box and show the row contents of a single row from a DataGridView in a form. I was stumped in trying to find something more elegant than what I've got so far. I was searching for a way to display the contents of the column header, and the row value, possibly using foreach or a for loop, but no avail. Any recommendations?

private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (authorDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
        {
            MessageBox.Show("Author Number: " + authorDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()
                + "\nAuthor First Name: " + authorDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()
                + "\nAuthor Last Name: " + authorDataGridView.Rows[e.RowIndex].Cells[2].Value.ToString());
        }
    }

Body:
You can get a reference to the row, which simplifies it a bit.

DataGridViewRow authorRow = authorDataGridView.Rows[e.RowIndex];
if (authorRow.Cells[e.ColumnIndex].Value != null)
{
    MessageBox.Show("Author Number: " + authorRow.Cells[0].Value.ToString()
            + "\nAuthor First Name: " + authorRow.Cells[1].Value.ToString()
            + "\nAuthor Last Name: " + authorRow.Cells[2].Value.ToString());
}

If you want the Column Header text, I think its:

DataGridViewColumn col = authorDataGridView.Column[e.ColumnIndex]

and then you can get the header text from:

col.HeaderText;

If you're going to do something like this a lot, you could encapsulate what you want in a function:

    public string ParseRowText(DataGridView grid, DataGridViewCellEventArgs e)
    {
        DataGridViewRow row = grid.Rows[e.RowIndex];
        string output = "";
        for (int col = 0; col < grid.Columns.Count; col++)
        {
            //Get column header and cell contents
            output = output + grid.Columns[col].HeaderText + ": " + row.Cells[col].Value.ToString() + Environment.NewLine;
        }
        return output;
    }

Is that the sort of thing you're after, where the Column Headers are "Author Number", "Author First Name", "Author Last Name" etc?

You'd then call it via:

private void authorDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show(ParseRowText(this, e));
}


问:
Magento 1 CE - How to create a diferent category for each Multistore
Thank you for reading..

I have created a multistore site based on 4 diferents subdomains domain1.site.com domain2.site.com and so on, everything works, i have diferent logo and design for each site, but i need to enable and disable categories already created for each site, is this possible?, i dont mean root category, i need to show a category for one site, and other category for other site, is this possible via admin panel or at least via code?

I have tried to create root category and disable category by category for each store view.

答:
Yes. Its possible but quite complicated. let me explain you how you reach that.

You need to create one custom category attribute and just set the value in which you want to display that category.

In category page (coding side) you just need to check this attribute value and write your condition according to that.


问:
how do I add and commit a png screenshot image to a local repo?
I see repos in github that just have a screenshot added. Not a screenshot inside an md file, the png is it's own file in the repo. I want to know how to get the screenshot png into the local repo and commit it to be pushed to github without using the gui. </p>

答: Presuming that "screenshot" here refers to a .png file. I am pretty sure you can add the png in the directory you want to and then stage-->commit-->push. AFAIK this should work.</p>


问:
Msys2 autocomplete doesn't work for current directory
I installed msys2-x86_64-20161025.exe following these steps.

When I try autocompletion for programs on the PATH, e.g. by typing g and then pressing TAB key twice, Msys2 console shows me a lot of options (.exe , .dll , and others).

However, when I type ./ and then press TAB key twice, it shows me only subdirectories of the current directory, but not .sh or .bat files in the current directory.

ls -al command shows that Msys2 doesn't see "executable" file permission on the .bat and .sh files. chmod +x * doesn't seem to work on Windows.

So how to get autocomplete to work in Msys2 for current directory script files?

I am on Windows 10 x64. Let me know if some additional info about the environment is needed.

答:
If your script contains a shebang line, msys2 will recognize the file as a script. That's has been my experience at least.

Particularly for Bash scripts the first line of each script can be #!/bin/bash, if Bash is installed in /bin/. See more on Shebang line here.


问:
PHP Fatal error: Call to a member function result_array() on a non-object
I am working on php using codeigniter framework as a beginner. My program is running perfectly on my localhost. But after uploading to the web server, it is showing an error for some pages. I have searched about this problem and most of the solutions show that my program is right. But for the live server, it is showing PHP fatal error. First one is, whenever I want to see data in datatable it is showing HTTP 500 error. My server administrator told me this is because of my model whenever I am returning data as result_array(). Here is my model,

```<code> public function get_pages()
    {
        $this->db->select('*');
        $this->db->from('page');
        $this->db->join('NavigationMenu', 'NavigationMenu.MenuID = page.MenuID', 'left');
        $this->db->join('SubMenu', 'SubMenu.SubMenuID = Page.SubMenuID', 'left');
        $query = $this->db->get();
        return $query->result_array();
    }
</code>```

Here is my controller for that,

```<code>public function pages()
{
        $data['page'] = $this->Pages_Model->get_pages();
        $tempString =  $this->load->view('admin_panel/content/pages', $data, true);
        $page_data = array(
            'fileHere' => $tempString
        );
        $this->load->view('admin_panel/shared/admin_layout',$page_data);
}
</code>```

And this is my View page,

Page Lists

                  Title
                  Main Menu
                  Sub-Menu
                  Edit/Remove

                <?php foreach ($page as $page_item): ?>

                        <?php echo $page_item['PageTitle']; ?>
                        <?php echo $page_item['MenuName']; ?>
                        <?php echo $page_item['SubMenuName']; ?>
                        <button type="submit" class="btn btn-primary" onClick="javascipt:window.location.href='<?php echo base_url('content/edit_page_content')?>/<?php echo $page_item['PageID']; ?>'">Edit</button>
                            <button type="submit" class="btn btn-danger delete_page" id="<?php echo $page_item['PageID']; ?>">Remove</button>

                <?php endforeach; ?>

```

This is one of my problem. I beleive if I get a solution I can solve others. The result_array() function is working perfectly in other places like where I need to fetch data. Thank you in advance.

答:
Try This as controller,<p>
    ```<code>public function pages()
        {
                $data['page'] = $this->Pages_Model->get_pages();
                $this->load->view('admin_panel/content/pages',$data);
                $this->load->view('admin_panel/shared/admin_layout',$data);
        }</code></p>

<code>```
</code>```

Body:
I am working on php using codeigniter framework as a beginner. My program is running perfectly on my localhost. But after uploading to the web server, it is showing an error for some pages. I have searched about this problem and most of the solutions show that my program is right. But for the live server, it is showing PHP fatal error. First one is, whenever I want to see data in datatable it is showing HTTP 500 error. My server administrator told me this is because of my model whenever I am returning data as result_array(). Here is my model,

 public function get_pages()
    {
        $this->db->select('*');
        $this->db->from('page');
        $this->db->join('NavigationMenu', 'NavigationMenu.MenuID = page.MenuID', 'left');
        $this->db->join('SubMenu', 'SubMenu.SubMenuID = Page.SubMenuID', 'left');
        $query = $this->db->get();
        return $query->result_array();
    }

Here is my controller for that,

public function pages()
{
        $data['page'] = $this->Pages_Model->get_pages();
        $tempString =  $this->load->view('admin_panel/content/pages', $data, true);
        $page_data = array(
            'fileHere' => $tempString
        );
        $this->load->view('admin_panel/shared/admin_layout',$page_data);
}

And this is my View page,

Page Lists

                  Title
                  Main Menu
                  Sub-Menu
                  Edit/Remove

                <?php foreach ($page as $page_item): ?>

                        <?php echo $page_item['PageTitle']; ?>
                        <?php echo $page_item['MenuName']; ?>
                        <?php echo $page_item['SubMenuName']; ?>
                        <button type="submit" class="btn btn-primary" onClick="javascipt:window.location.href='<?php echo base_url('content/edit_page_content')?>/<?php echo $page_item['PageID']; ?>'">Edit</button>
                            <button type="submit" class="btn btn-danger delete_page" id="<?php echo $page_item['PageID']; ?>">Remove</button>

                <?php endforeach; ?>

This is one of my problem. I beleive if I get a solution I can solve others. The result_array() function is working perfectly in other places like where I need to fetch data. Thank you in advance.

Body:
Try This as controller,

public function pages()
        {
                $data['page'] = $this->Pages_Model->get_pages();
                $this->load->view('admin_panel/content/pages',$data);
                $this->load->view('admin_panel/shared/admin_layout',$data);
        }

</pre>


问:
Updating android app not listed on play store?
For a customer of mine, we have developed an app which is provided with a tablet as a default launcher. Now every so often we want to update the app - preferably without access to the tablet - so pretty much remotely. The app is not listed on play store, it's being installed as a .apk file by us in-house on the tablet and then sent to the customer.

How do I go about being able to force updates to it? App has internet connectivity, it's written in Cordova or Android native (we have 2 apps).

答:
You can use the cordova File plugin to gain access and permission to write files to disk, then include a function that checks a value on your server to determine if the app is up to date or not. If the app is not running the current version... then your app can call a function that downloads the updated app pages/scripts and saves them locally.

To be safe, i would recommend implementing a dynamic splash screen (of your own) that checks to see if there are any downloaded update-files to be transferred to the active app directory.

So the next time the app starts, the splash screen will just stay up a little longer and let the user know that an update is in progress... whilst your update function copy, edit and replace the files in the background.

This is something you should test thoroughly before shipping as it can sometimes break your application if the app is suspended during a file write.

You can read more about the cordova file plugin here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/


问:
Android layouts for different screen sizes
I am struggling for layouts for an Android app. I have defined different layouts for different screen sizes and the current layout directory structure is something like this:

layout

layout-land

layout-small

layout-xlarge

layout-xlarge-land

Problem

The main layout directory files are being displayed for 3.7 to 7.0 which is a very broad range. And text overlap on small screens and if I adjust on small; it becomes very tiny on the large screen.

According to me, the layout small files should be rendered for smaller screens but those files are only rendered for android wear devices.

layout-xlarge seems to work for Nexus 9 to Nexus 10

I want to know, how can I define the different layout for 3.7-5.0 and 5.0-7.0 screen sizes.

答:
Create folders like the following

```<code>layout-sw300dp
layout-sw330dp
layout-sw480dp
layout-sw600dp
layout-sw720dp
</code>```

Create also values-folders like

```<code>values-sw300dp
values-sw330dp
values-sw480dp
values-sw600dp
values-sw720dp
</code>```

Body:
Create folders like the following

layout-sw300dp
layout-sw330dp
layout-sw480dp
layout-sw600dp
layout-sw720dp

Create also values-folders like

values-sw300dp
values-sw330dp
values-sw480dp
values-sw600dp
values-sw720dp


问:
Angular JS data binding not working for HTML5 reset button
I my angular application, I'm using a reset button to clear the data in a text box. But the binding is not working properly with the reset button.

```<code><form>
  <input type="text" name="email" ng-model="ch.email"><br>
  <input type="reset" value="Reset">
</form>

<div>{{ch.email}}</div>
</code>```

When some text is typed in the text box, it appears in the div, But after resetting, The text in the div doesn't disappears.

Please see the fiddle

答:
You can use a button instead

HTML:

```<code><form>
    <input type="text" name="email" ng-model="changestore.sample">
    <br>
    <input type="button" value="Reset" ng-click="reset()">
</form>
<div id="textdisplay">
    {{changestore.sample}}
</div>
</code>```

JS:

```<code>$scope.reset=function(){
  $scope.changestore={};
}
</code>```

Working Fiddle:http://jsfiddle.net/aks0kmwe/

HTML 5 reset button won't clear the ng-model, it clears only the value from the input box

Working Example:http://jsfiddle.net/ADukg/12591/

Body:
I my angular application, I'm using a reset button to clear the data in a text box. But the binding is not working properly with the reset button.

<form>
  <input type="text" name="email" ng-model="ch.email">

  <input type="reset" value="Reset">
</form>

{{ch.email}}

When some text is typed in the text box, it appears in the div, But after resetting, The text in the div doesn't disappears.

Please see the fiddle

Body:
You can use a button instead

HTML:

<form>
    <input type="text" name="email" ng-model="changestore.sample">
    <br>
    <input type="button" value="Reset" ng-click="reset()">
</form>
<div id="textdisplay">
    {{changestore.sample}}
</div>

JS:

$scope.reset=function(){
  $scope.changestore={};
}

Working Fiddle:http://jsfiddle.net/aks0kmwe/

HTML 5 reset button won't clear the ng-model, it clears only the value from the input box

Working Example:http://jsfiddle.net/ADukg/12591/


问:
Error while Publishing files to Azure Web App using FTP
I am following this MSDN guide to publish / upload ASP.Net Web Application files to Azure Web App (Resource Manager). But getting UploadFile error whenever the Sub Folder starts. Root folder is going fine.

Uploading to ftp://XXXXXX.ftp.azurewebsites.windows.net/site/wwwroot/bin/Antlr3.Runtime.dll
From C:\Users\SampleWebApp\bin\Antlr3.Runtime.dll

Exception calling "UploadFile" with "2" argument(s):

The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

```<code>Param(
[string] [Parameter(Mandatory=$true)] $AppDirectory,
[string] [Parameter(Mandatory=$true)] $WebAppName,
[string] [Parameter(Mandatory=$true)] $ResourceGroupName
)

$xml = [Xml](Get-AzureRmWebAppPublishingProfile -Name $webappname `
-ResourceGroupName $ResourceGroupName `
-OutputFile null)
$username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value
$password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value
$url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value

Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse | Where-Object{!($_.PSIsContainer)}

foreach ($file in $files)
{
if ($file.FullName)
$relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')
$uri = New-Object System.Uri("$url/$relativepath")
"Uploading to " + $uri.AbsoluteUri
"From " + $file.FullName
$webclient.UploadFile($uri, $file.FullName)
}
$webclient.Dispose()
</code>```

答:
as the issue starts only with first occurrence of sub directory(bin) file, it could be because of some other process is using the Antlr dll. can you close all active debug sessions and run this script again? and also make sure you're not having any whitespaces after forming relative uri path

[UPDATE]
It was failing to create sub-directory and hence the error "file not found" while uploading a file from sub directory.

made few changes in the for-loop to create sub-directory on ftp before uploading file from sub-directory and is working fine.

```<code>$appdirectory="<Replace with your app directory>"
$webappname="mywebapp$(Get-Random)"
$location="West Europe"

# Create a resource group.
New-AzureRmResourceGroup -Name myResourceGroup -Location $location

# Create an App Service plan in `Free` tier.
New-AzureRmAppServicePlan -Name $webappname -Location $location `
-ResourceGroupName myResourceGroup -Tier Free

# Create a web app.
New-AzureRmWebApp -Name $webappname -Location $location -AppServicePlan $webappname `
-ResourceGroupName myResourceGroup

# Get publishing profile for the web app
$xml = (Get-AzureRmWebAppPublishingProfile -Name $webappname `
-ResourceGroupName myResourceGroup `
-OutputFile null)

# Not in Original Script
$xml = [xml]$xml

# Extract connection information from publishing profile
$username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value
$password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value
$url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value

# Upload files recursively
Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse #Removed IsContainer condition
foreach ($file in $files)
{
    $relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')
    $uri = New-Object System.Uri("$url/$relativepath")

    if($file.PSIsContainer)
    {
        $uri.AbsolutePath + "is Directory"
        $ftprequest = [System.Net.FtpWebRequest]::Create($uri);
        $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
        $ftprequest.UseBinary = $true

        $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

        $response = $ftprequest.GetResponse();
        $response.StatusDescription
        continue
    }

    "Uploading to " + $uri.AbsoluteUri + " from "+ $file.FullName

    $webclient.UploadFile($uri, $file.FullName)
}
$webclient.Dispose()
</code>```

i also blogged about this in detail on how I troubleshooted this issue to get the fix here.

Body:
I am following this MSDN guide to publish / upload ASP.Net Web Application files to Azure Web App (Resource Manager). But getting UploadFile error whenever the Sub Folder starts. Root folder is going fine.

Uploading to ftp://XXXXXX.ftp.azurewebsites.windows.net/site/wwwroot/bin/Antlr3.Runtime.dll
From C:\Users\SampleWebApp\bin\Antlr3.Runtime.dll

Exception calling "UploadFile" with "2" argument(s):

The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

Param(
[string] [Parameter(Mandatory=$true)] $AppDirectory,
[string] [Parameter(Mandatory=$true)] $WebAppName,
[string] [Parameter(Mandatory=$true)] $ResourceGroupName
)

$xml = [Xml](Get-AzureRmWebAppPublishingProfile -Name $webappname `
-ResourceGroupName $ResourceGroupName `
-OutputFile null)
$username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value
$password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value
$url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value

Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse | Where-Object{!($_.PSIsContainer)}

foreach ($file in $files)
{
if ($file.FullName)
$relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')
$uri = New-Object System.Uri("$url/$relativepath")
"Uploading to " + $uri.AbsoluteUri
"From " + $file.FullName
$webclient.UploadFile($uri, $file.FullName)
}
$webclient.Dispose()

Body:
as the issue starts only with first occurrence of sub directory(bin) file, it could be because of some other process is using the Antlr dll. can you close all active debug sessions and run this script again? and also make sure you're not having any whitespaces after forming relative uri path

[UPDATE]
It was failing to create sub-directory and hence the error "file not found" while uploading a file from sub directory.

made few changes in the for-loop to create sub-directory on ftp before uploading file from sub-directory and is working fine.

$appdirectory="<Replace with your app directory>"
$webappname="mywebapp$(Get-Random)"
$location="West Europe"

# Create a resource group.
New-AzureRmResourceGroup -Name myResourceGroup -Location $location

# Create an App Service plan in `Free` tier.
New-AzureRmAppServicePlan -Name $webappname -Location $location `
-ResourceGroupName myResourceGroup -Tier Free

# Create a web app.
New-AzureRmWebApp -Name $webappname -Location $location -AppServicePlan $webappname `
-ResourceGroupName myResourceGroup

# Get publishing profile for the web app
$xml = (Get-AzureRmWebAppPublishingProfile -Name $webappname `
-ResourceGroupName myResourceGroup `
-OutputFile null)

# Not in Original Script
$xml = [xml]$xml

# Extract connection information from publishing profile
$username = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userName").value
$password = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@userPWD").value
$url = $xml.SelectNodes("//publishProfile[@publishMethod=`"FTP`"]/@publishUrl").value

# Upload files recursively
Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse #Removed IsContainer condition
foreach ($file in $files)
{
    $relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')
    $uri = New-Object System.Uri("$url/$relativepath")

    if($file.PSIsContainer)
    {
        $uri.AbsolutePath + "is Directory"
        $ftprequest = [System.Net.FtpWebRequest]::Create($uri);
        $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
        $ftprequest.UseBinary = $true

        $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

        $response = $ftprequest.GetResponse();
        $response.StatusDescription
        continue
    }

    "Uploading to " + $uri.AbsoluteUri + " from "+ $file.FullName

    $webclient.UploadFile($uri, $file.FullName)
}
$webclient.Dispose()

i also blogged about this in detail on how I troubleshooted this issue to get the fix here.


问:
Why am I showing up as two contributors in GitLab?
I am using SmartGit 17 and GitLab Enterprise 8.6.0-ee, on Windows 7 Enterprise.  I upgraded SmartGit not too long ago from version 7.1.  I've been working intermittently on a project (I'm the only person working on this project), and today decided to browse around GitLab a little.  I noticed on the Graphs page, Contributors tab, that it shows two contributors, both of whom are me.  One has my full first and last name, and the other has only my last name.  One has my e-mail address all in lower case and the other has it in mixed case.  Over time, there is a ramp-down from May 28 to a little after July 2 of the one contributor, and a corresponding ramp up of the other one.

I vaguely seem to remember being prompted to enter my name and e-mail address and accepting a default (which was just my last name), and I think it is related to SmartGit, but I can't see to find where this is recorded so I can change it back globally rather than on a per-repository basis.

Can anyone tell me where to look?

Also, I don't konw whether "contributor" means committer or author, or if that matters.

答:
I believe that a contributor is identified via the email address of the user commiting.

As you mentioned vaguely having to enter that information at some point, I reckon it was probably at that point that you ended up with multiple 'identities' within gitlab.

To check what your current email address is configured to and/or modify it you can run the following from a command prompt window (as long as git is on the PATH)

```<code>git config --global user.email
</code>```

That will display the current globally configured email, to set it:

```<code>git config --global user.email "email@example.com
</code>```

More information can be found in the github pages on this here.

Body:
I believe that a contributor is identified via the email address of the user commiting.

As you mentioned vaguely having to enter that information at some point, I reckon it was probably at that point that you ended up with multiple 'identities' within gitlab.

To check what your current email address is configured to and/or modify it you can run the following from a command prompt window (as long as git is on the PATH)

git config --global user.email

That will display the current globally configured email, to set it:

git config --global user.email "email@example.com

More information can be found in the github pages on this here.


问:
Is it possible to disable jsessionid in tomcat servlet?
Is it possible to turnoff jsessionid in the url in tomcat? the jsessionid seems not too search engine friendly.</p>

答:
Also if you have Apache in front of Tomcat you can strip out the jsession with a mod_rewrite filter.

Add the following to your apache config.

```<code>#Fix up tomcat jsession appending rule issue
RewriteRule  ^/(.*);jsessionid=(.*) /$1 [R=301,L]
</code>```

This will do a 301 redirect to a page without the jsessionid.  Obviously this will completely disable url jsessionid's but this is what I needed.

Cheers,
Mark

Body:
Also if you have Apache in front of Tomcat you can strip out the jsession with a mod_rewrite filter.

Add the following to your apache config.

#Fix up tomcat jsession appending rule issue
RewriteRule  ^/(.*);jsessionid=(.*) /$1 [R=301,L]

This will do a 301 redirect to a page without the jsessionid.  Obviously this will completely disable url jsessionid's but this is what I needed.

Cheers,
Mark


问:
Rhino JavaScript Method of Replacing Character & TitleCase
I need to convert Paid Search terms into a normal sentence case string.  For example, the Google referring URL would contain the following:

q=javascript+stackoverlow+HELP

My current code escapes the value, but I'm thinking I need a simple function to remove the plus signs and set the case properly so that it looks like this:

Javascript Stackoverflow Help

Here is my current setup.

```<code>if (landing.referrer.domain.match(/google\.com/)) {
  return unescape(landing.referrer.param('q'));
} else if (landing.referrer.domain.match(/yahoo\.com/)) {
  return unescape(landing.referrer.param('p'));
} else if (landing.referrer.domain.match(/bing\.com/)) {
  return unescape(landing.referrer.param('q'));
}
</code>```

I only need to worry about English (Latin) character set.

答:
You can just use css inside JavaScript. Check this answer.

The full code can be:

```<code>function format_str(str) {
    formatted_str = str.replace(/+/g, ' ');
    return '<span style="text-transform: capitalize">'+ formatted_str +'</span>';
}
</code>```

Body:
I need to convert Paid Search terms into a normal sentence case string.  For example, the Google referring URL would contain the following:

q=javascript+stackoverlow+HELP

My current code escapes the value, but I'm thinking I need a simple function to remove the plus signs and set the case properly so that it looks like this:

Javascript Stackoverflow Help

Here is my current setup.

if (landing.referrer.domain.match(/google\.com/)) {
  return unescape(landing.referrer.param('q'));
} else if (landing.referrer.domain.match(/yahoo\.com/)) {
  return unescape(landing.referrer.param('p'));
} else if (landing.referrer.domain.match(/bing\.com/)) {
  return unescape(landing.referrer.param('q'));
}

I only need to worry about English (Latin) character set.

Body:
You can just use css inside JavaScript. Check this answer.

The full code can be:

function format_str(str) {
    formatted_str = str.replace(/+/g, ' ');
    return '<span style="text-transform: capitalize">'+ formatted_str +'</span>';
}


问:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

```<code>>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true
</code>```

答:
```<code>var a = Array(100).fill(Array(100).fill(false));
</code>```

a contains an array, each element of which references to an array. you are filling the outer array with an array which contains all false values. The inner array is being made only once and reference to the same array is passed to each element of outer array that is why if you perform an operation on one element it reflects on other elements as well.

This is actually equivalent to

```<code>var a1 = Array(100).fill(false);
var a = Array(100).fill(a1);
</code>```

here a gets 100 elements all having reference to same array a1. So if you change one element of a, all elements change since they are references to same array.

you will need to fill each element in outer array with a new array. you can do something like this:

```<code>var a = [];
for(var i=0; i<100; i++)
  a.push(Array(100).fill(false));
</code>```

Body:
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Body:
var a = Array(100).fill(Array(100).fill(false));

a contains an array, each element of which references to an array. you are filling the outer array with an array which contains all false values. The inner array is being made only once and reference to the same array is passed to each element of outer array that is why if you perform an operation on one element it reflects on other elements as well.

This is actually equivalent to

var a1 = Array(100).fill(false);
var a = Array(100).fill(a1);

here a gets 100 elements all having reference to same array a1. So if you change one element of a, all elements change since they are references to same array.

you will need to fill each element in outer array with a new array. you can do something like this:

var a = [];
for(var i=0; i<100; i++)
  a.push(Array(100).fill(false));


问:
Localizable.strings key-value pair
I want to localize "1 of 9", and 1 and 9 are int parameters, my code is as below

```<code>context = [NSString stringWithFormat:NSLocalizedString(@"%d of %d",
          "This text will be used to show page number on the screen"),
          currentPageIndex + 1, pageCount];
</code>```

And the generated Localizable.strings show like that

```<code>/* This text will be used to show page number on the screen */
"%d of %d" = "%1$d of %2$d";
</code>```

I think the thing on the left of "=" is key and the the thing on the right of "=" is value, but I want the key looks like "show_page_number" not included the format "%d", how can I do? I try to replace "%d of %d" with "show_page_number", but it does not work. Any advice?

答:
NSLocalizedString() replaced key with value at runtime .So you can use anystring as key & it will be replaced as "%1$d of %2$d" at runtime.
Add string in Localizable file :

```<code>"show_page_number" = "%1$d of %2$d";
</code>```

& in code use that key

```<code>context = [NSString stringWithFormat:NSLocalizedString(@"show_page_number", "This text will be used to show page number on the screen"), currentPageIndex + 1, pageCount];
</code>```

Add localizable.string file in xcode project.

Title: Localizable.strings key-value pair

Body:
I want to localize "1 of 9", and 1 and 9 are int parameters, my code is as below

context = [NSString stringWithFormat:NSLocalizedString(@"%d of %d",
          "This text will be used to show page number on the screen"),
          currentPageIndex + 1, pageCount];

And the generated Localizable.strings show like that

/* This text will be used to show page number on the screen */
"%d of %d" = "%1$d of %2$d";

I think the thing on the left of "=" is key and the the thing on the right of "=" is value, but I want the key looks like "show_page_number" not included the format "%d", how can I do? I try to replace "%d of %d" with "show_page_number", but it does not work. Any advice?

Body:
NSLocalizedString() replaced key with value at runtime .So you can use anystring as key & it will be replaced as "%1$d of %2$d" at runtime.
Add string in Localizable file :

"show_page_number" = "%1$d of %2$d";

& in code use that key

context = [NSString stringWithFormat:NSLocalizedString(@"show_page_number", "This text will be used to show page number on the screen"), currentPageIndex + 1, pageCount];

Add localizable.string file in xcode project.


问:
TimeSpan to UTC milliseconds
I currently have a TimeSpan variable that holds the time set from a TimePicker. I need a long similar to the one given by TimeSpan.TotalMilliseconds() but I need it in respect to UTC.

I saw some tactics like converting to a DateTime and then using DateTime.ToUniversalTime() but I haven't successfully gotten the total milliseconds from it after the conversion. I tried taking the new UTC DateTime and using DateTime.TimeOfDay() to put it back into a TimeSpan type and then use the TimeSpan.TotalMilliseconds() again but it did not work.

Any ideas?

答:
I also had the same problem. Use this to your datepicker method-

```<code>DateTime.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
DateTime.set(final_year, final_month, final_day, final_hour, final_minute,0);
private long datetime=DateTime.getTimeInMillis();
String dt= String.valueOf(datetime);
</code>```

I think this will solve your problem!

Title: TimeSpan to UTC milliseconds

Body:
I also had the same problem. Use this to your datepicker method-

DateTime.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
DateTime.set(final_year, final_month, final_day, final_hour, final_minute,0);
private long datetime=DateTime.getTimeInMillis();
String dt= String.valueOf(datetime);

I think this will solve your problem!


问:
How to validate multiple images input?
I have this function which will allow users to upload one image or more. I already create the validation rules but it keep returning false no matter what the input is.

Rules :

```<code>public function rules()
    {
        return [
            'image' => 'required|mimes:jpg,jpeg,png,gif,bmp',
        ];
    }
</code>```

Upload method :

```<code>public function addIM(PhotosReq $request) {
        $id = $request->id;
        // Upload Image
        foreach ($request->file('image') as $file) {
            $ext = $file->getClientOriginalExtension();
            $image_name = str_random(8) . ".$ext";
            $upload_path = 'image';
            $file->move($upload_path, $image_name);
            Photos::create([
                'post_id' => $id,
                'image' => $image_name,
            ]);
        }
        //Toastr notifiacation
        $notification = array(
            'message' => 'Images added successfully!',
            'alert-type' => 'success'
        );
        return back()->with($notification);
    }
</code>```

How to solve this ?
That's all and thanks!

答:
You have multiple image upload field name like and add multiple attribute to your input element

```<code><input type="file" name="image[]" multiple="multiple">
</code>```

So that, your input is like array inside which there will be images.
Since there is different method for array input validation, see docs here.

So, you have to validate something like this:

```<code>$this->validate($request,[
     'image' => 'required',
     'image.*' => 'mimes:jpg,jpeg,png,gif,bmp',
]);
</code>```

Hope,You understand

Title: How to validate multiple images input?

Body:
I have this function which will allow users to upload one image or more. I already create the validation rules but it keep returning false no matter what the input is.

Rules :

public function rules()
    {
        return [
            'image' => 'required|mimes:jpg,jpeg,png,gif,bmp',
        ];
    }

Upload method :

public function addIM(PhotosReq $request) {
        $id = $request->id;
        // Upload Image
        foreach ($request->file('image') as $file) {
            $ext = $file->getClientOriginalExtension();
            $image_name = str_random(8) . ".$ext";
            $upload_path = 'image';
            $file->move($upload_path, $image_name);
            Photos::create([
                'post_id' => $id,
                'image' => $image_name,
            ]);
        }
        //Toastr notifiacation
        $notification = array(
            'message' => 'Images added successfully!',
            'alert-type' => 'success'
        );
        return back()->with($notification);
    }

How to solve this ?
That's all and thanks!

Body:
You have multiple image upload field name like and add multiple attribute to your input element

<input type="file" name="image[]" multiple="multiple">

So that, your input is like array inside which there will be images.
Since there is different method for array input validation, see docs here.

So, you have to validate something like this:

$this->validate($request,[
     'image' => 'required',
     'image.*' => 'mimes:jpg,jpeg,png,gif,bmp',
]);

Hope,You understand


问:
Firebase : How to add new attribute in existing table
I am working on a project in swift and having firebase as backend for managing data.

```<code>FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
</code>```

This is what I have set in app delegate file. Now in my chat module, I have added message information in firebase database through below code.

```<code>    let messageData = ["text": text, "senderId": senderId, "senderName": senderDisplayName, "MediaType": "TEXT"]
    self.messageSentRef?.child("Messages").childByAutoId().setValue(messageData)
</code>```

Now I want to add one new attribute named TimeStamp in messages table.

Anyone can help me how to do that?

答:
If you have a MessageItem/MessageData object, you can always add more properties to that by modify your object structure. In order to add timestamp to the existing data, you can add it directly in your Firebase/Database console (which is a manual way to do it, or just do it in code like this)

```<code>let messageItem = MessageItem(text: text,
                           senderId: self.user.email,
                           senderDisplayName: false,
                           mediaType: "",
                           timestamp: "")

let messageItemRef = self.ref.child("Message")
messageItemRef.setValue(messageItem.toAnyObject())
</code>```

Edit:
The original question does not have a MessageItem object so let's put one together that makes this answer work:

In your viewController class (or whatever the top level class is) we need to implement a MessageItem class object like this

```<code>class MessageItem {
    var text = ""
    var senderId = ""
    var senderDisplayName = false
    var mediaType = ""
    var timestamp = ""

    init(text: String, senderId: String, senderDisplayName: Bool, mediaType: String, timestamp: String) {
        self.text = text
        self.senderId = senderId
        self.senderDisplayName = senderDisplayName
        self.mediaType = mediaType
        self.timestamp = timestamp
    }

    func toAnyObject() -> Any {
        return [
            "text": text,
            "senderId": senderId,
            "senderDisplayName": senderDisplayName,
            "mediaType": mediaType,
            "timestamp": timestamp
        ]
    }
}
</code>```

Body:
I am working on a project in swift and having firebase as backend for managing data.

FirebaseApp.configure()
Database.database().isPersistenceEnabled = true

This is what I have set in app delegate file. Now in my chat module, I have added message information in firebase database through below code.

    let messageData = ["text": text, "senderId": senderId, "senderName": senderDisplayName, "MediaType": "TEXT"]
    self.messageSentRef?.child("Messages").childByAutoId().setValue(messageData)

Now I want to add one new attribute named TimeStamp in messages table.

Anyone can help me how to do that?

Body:
If you have a MessageItem/MessageData object, you can always add more properties to that by modify your object structure. In order to add timestamp to the existing data, you can add it directly in your Firebase/Database console (which is a manual way to do it, or just do it in code like this)

let messageItem = MessageItem(text: text,
                           senderId: self.user.email,
                           senderDisplayName: false,
                           mediaType: "",
                           timestamp: "")

let messageItemRef = self.ref.child("Message")
messageItemRef.setValue(messageItem.toAnyObject())

Edit:
The original question does not have a MessageItem object so let's put one together that makes this answer work:

In your viewController class (or whatever the top level class is) we need to implement a MessageItem class object like this

class MessageItem {
    var text = ""
    var senderId = ""
    var senderDisplayName = false
    var mediaType = ""
    var timestamp = ""

    init(text: String, senderId: String, senderDisplayName: Bool, mediaType: String, timestamp: String) {
        self.text = text
        self.senderId = senderId
        self.senderDisplayName = senderDisplayName
        self.mediaType = mediaType
        self.timestamp = timestamp
    }

    func toAnyObject() -> Any {
        return [
            "text": text,
            "senderId": senderId,
            "senderDisplayName": senderDisplayName,
            "mediaType": mediaType,
            "timestamp": timestamp
        ]
    }
}


问:
Laravel Backpack select2_multiple not Displaying Correctly
I'm working with Backpack for Laravel, and implemented a select2_multiple field. The field works correctly, though it doesn't display properly at all. It's defined as:

```<code>    $this->crud->addField([       // Select2Multiple = n-n relationship (with pivot table)
        'label' => "Categories",
        'type' => 'select2_multiple',
        'name' => 'categories', // the method that defines the relationship in your Model
        'entity' => 'categories', // the method that defines the relationship in your Model
        'attribute' => 'title', // foreign key attribute that is shown to user
        'model' => "App\Models\Category", // foreign key model
        'pivot' => true // on create&update, do you need to add/delete pivot table entries?
    ]);
</code>```

The pivot tables exist, as do the relationships on the models. The field shows for a second, and then in quickly hidden on page load (I guess by some JS). You can see below the 'categories' label, there's just white space:

I can, however, click in the white space and it will then appear and allow me to select categories as expected (though it displays rather strangely):

This is all default functionality, I haven't edited the select2_multiple template or any of the JS. Why is this displaying so poorly?

答: I believe it was a bug that has since been fixed. A composer update should fix it for you.

Body:
I'm working with Backpack for Laravel, and implemented a select2_multiple field. The field works correctly, though it doesn't display properly at all. It's defined as:

    $this->crud->addField([       // Select2Multiple = n-n relationship (with pivot table)
        'label' => "Categories",
        'type' => 'select2_multiple',
        'name' => 'categories', // the method that defines the relationship in your Model
        'entity' => 'categories', // the method that defines the relationship in your Model
        'attribute' => 'title', // foreign key attribute that is shown to user
        'model' => "App\Models\Category", // foreign key model
        'pivot' => true // on create&update, do you need to add/delete pivot table entries?
    ]);

The pivot tables exist, as do the relationships on the models. The field shows for a second, and then in quickly hidden on page load (I guess by some JS). You can see below the 'categories' label, there's just white space:

I can, however, click in the white space and it will then appear and allow me to select categories as expected (though it displays rather strangely):

This is all default functionality, I haven't edited the select2_multiple template or any of the JS. Why is this displaying so poorly?


问:
custom structure directive in Angular2 documentation
In the custom structure directive example at following link, what does TemplateRef and ViewContainerRef point to?

https://angular.io/guide/structural-directives#unless

A Directive usually doesn't have a view. So would templateRef point to the HTML tag or Component the directive is attached to? Eg In the following code, the template is everything between
 ...
? I read that * gets converted to <ng-template> so it could be the case.

```<code><p *myUnless="condition">Show this sentence unless the condition is true.</p>
</code>```

What is ViewContainerRef in the example? Generally I would add a <ng-container> as view container? Where does it come from in the example?

答:
This example

```<code><p *myUnless="condition">Show this sentence unless the condition is true.</p>
</code>```

is transformed by the compiler into

```<code><ng-template [myUnless]="condition">
   <p>Show this sentence unless the condition is true.</p>
<ng-template>
</code>```

So you can see now that myUnless directive is placed on the ng-template element and that's why it has access to the templateRef

So would templateRef point to the HTML tag or Component the directive
  is attached to?

It "sort of" points to the contents of the ng-template element the directive is attached to. Under the hood it references the embedded view definition created for the ng-template contents.

What is ViewContainerRef in the example?

Any HTML element can act as a view container. So again, in this case the directive injects the view container that references directive host element.

The ng-template element is rendered as comment DOM node, so you will see that both ViewContaineRef and TemplateRef point to this comment node:

```<code>export class MyUnless {
  constructor(t: TemplateRef<any>, vc: ViewContainerRef) {
    console.log(t.elementRef.nativeElement.nodeName); // #comment
    console.log(t.elementRef.nativeElement === vc.element.nativeElement); // true
  }
}
</code>```

Body:
In the custom structure directive example at following link, what does TemplateRef and ViewContainerRef point to?

https://angular.io/guide/structural-directives#unless

A Directive usually doesn't have a view. So would templateRef point to the HTML tag or Component the directive is attached to? Eg In the following code, the template is everything between
 ...
? I read that * gets converted to <ng-template> so it could be the case.

Show this sentence unless the condition is true.

What is ViewContainerRef in the example? Generally I would add a <ng-container> as view container? Where does it come from in the example?

Body:
This example

<p *myUnless="condition">Show this sentence unless the condition is true.</p>

is transformed by the compiler into

<ng-template [myUnless]="condition">
   <p>Show this sentence unless the condition is true.</p>
<ng-template>

So you can see now that myUnless directive is placed on the ng-template element and that's why it has access to the templateRef

So would templateRef point to the HTML tag or Component the directive
  is attached to?

It "sort of" points to the contents of the ng-template element the directive is attached to. Under the hood it references the embedded view definition created for the ng-template contents.

What is ViewContainerRef in the example?

Any HTML element can act as a view container. So again, in this case the directive injects the view container that references directive host element.

The ng-template element is rendered as comment DOM node, so you will see that both ViewContaineRef and TemplateRef point to this comment node:

export class MyUnless {
  constructor(t: TemplateRef<any>, vc: ViewContainerRef) {
    console.log(t.elementRef.nativeElement.nodeName); // #comment
    console.log(t.elementRef.nativeElement === vc.element.nativeElement); // true
  }
}


问:
Array of two types
I have two arrays :

```<code>Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)
</code>```

How to combine both as:

```<code>Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)
</code>```

Thanks -
Haan

答:
```<code>// copy array 2 into the result array.
$combined = $arr2;

// add a new key 'day' with value from first array.
for($i=0;$i<count($combined);$i++) {
        $combined[$i]['day'] = $arr1[$i];
}
</code>```

See it

Title: Array of two types

Body:
I have two arrays :

Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)

How to combine both as:

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)

Thanks -
Haan

Body:
// copy array 2 into the result array.
$combined = $arr2;

// add a new key 'day' with value from first array.
for($i=0;$i<count($combined);$i++) {
        $combined[$i]['day'] = $arr1[$i];
}

See it


问:
Change permission folder in Raspberry Pi to R permission
The image below contain the command that change the permission for folder:

I want to change permission folder in Raspberry Pi to r permission it is folder for radio in /var/www. It failed and said "chmod: invalid mode: '-R' try chmod :--help to more information".

答:
As already mentioned -R is not a permission, rather it's an option that sets the recursive mode on. The command you want is:

```<code>sudo chmod 777 -R PiFmRds/src
</code>```

Note: chmod 777 is a dangerous permission setting. It means that literally everyone and everything can read, write, and execute the directory and everything below it.

Body:
As already mentioned -R is not a permission, rather it's an option that sets the recursive mode on. The command you want is:

sudo chmod 777 -R PiFmRds/src

Note: chmod 777 is a dangerous permission setting. It means that literally everyone and everything can read, write, and execute the directory and everything below it.


问:
Variable reference inside SQLSyntax when constructing SQL query in ScalalikeJdbc
I have a search parameter from request which is a string like "abc". Now I want to build an sqls and use this variable reference inside the sqls. I tried below approach:

```<code>val searchValue = "abc"

sqls"column_name ILIKE '%$searchValue%'"
</code>```

But this didn't work. Then i tried with below unsafe approach.

```<code>val searchValueSqls = SQLSyntax.createUnsafely(searchValue)

sqls"column_name ILIKE '%$searchValueSqls%'"
</code>```

This worked fine but documentation says "Be aware of SQL injection vulnerability."

Is there any safe approach to achieve variable reference inside sqls?

Another approach is that we can use sqls.like to build the like operation.

But is sqls.like case insensitive? As ILIKE is case insensitive for redshift.

答:
We can use LikeConditionEscapeUtil.

```<code>val escapedValue = SQLSyntax.createUnsafely(LikeConditionEscapeUtil.escape(searchValue))
sqls"column_name ILIKE '$escapedValue'"
</code>```

Body:
I have a search parameter from request which is a string like "abc". Now I want to build an sqls and use this variable reference inside the sqls. I tried below approach:

val searchValue = "abc"

sqls"column_name ILIKE '%$searchValue%'"

But this didn't work. Then i tried with below unsafe approach.

val searchValueSqls = SQLSyntax.createUnsafely(searchValue)

sqls"column_name ILIKE '%$searchValueSqls%'"

This worked fine but documentation says "Be aware of SQL injection vulnerability."

Is there any safe approach to achieve variable reference inside sqls?

Another approach is that we can use sqls.like to build the like operation.

But is sqls.like case insensitive? As ILIKE is case insensitive for redshift.

Body:
We can use LikeConditionEscapeUtil.

val escapedValue = SQLSyntax.createUnsafely(LikeConditionEscapeUtil.escape(searchValue))
sqls"column_name ILIKE '$escapedValue'"


问:
TSQL - Display the date which exist in all Model
```<code>MODEL     DateCreated
----------------------
MODEL_1   2017-07-20
MODEL_1   2017-07-19
MODEL_1   2017-06-10
MODEL_1   2017-06-02
MODEL_2   2017-07-18
MODEL_2   2017-07-17
MODEL_2   2017-06-10
MODEL_2   2017-06-02
MODEL_3   2017-07-20
MODEL_3   2017-07-12
MODEL_3   2017-06-10
MODEL_3   2017-06-02
MODEL_3   2017-05-16
</code>```

Expected result

```<code>DateCreated_Exist_In_All_Model
------------------------------
2017-06-10
2017-06-02
</code>```

This means, only those DateCreated exist in all model will be displayed

Thanks to everyone who willing to help me.

答:
One approach would be to aggregate on the creation date and then compare the count of distinct models appearing on each date against the total number of models appearing in the table.

```<code>SELECT
    DateCreated AS DateCreated_Exist_In_All_Model
FROM [yourTable]
GROUP BY DateCreated
HAVING COUNT(DISTINCT MODEL) = (SELECT COUNT(DISTINCT MODEL) FROM yourTable)
</code>```

Note that even though there appear to be only 3 models in your data set, we can make the query more flexible by using a subquery which counts the number of distinct models in the entire table.

Body:
MODEL     DateCreated
----------------------
MODEL_1   2017-07-20
MODEL_1   2017-07-19
MODEL_1   2017-06-10
MODEL_1   2017-06-02
MODEL_2   2017-07-18
MODEL_2   2017-07-17
MODEL_2   2017-06-10
MODEL_2   2017-06-02
MODEL_3   2017-07-20
MODEL_3   2017-07-12
MODEL_3   2017-06-10
MODEL_3   2017-06-02
MODEL_3   2017-05-16

Expected result

DateCreated_Exist_In_All_Model
------------------------------
2017-06-10
2017-06-02

This means, only those DateCreated exist in all model will be displayed

Thanks to everyone who willing to help me.

Body:
One approach would be to aggregate on the creation date and then compare the count of distinct models appearing on each date against the total number of models appearing in the table.

SELECT
    DateCreated AS DateCreated_Exist_In_All_Model
FROM [yourTable]
GROUP BY DateCreated
HAVING COUNT(DISTINCT MODEL) = (SELECT COUNT(DISTINCT MODEL) FROM yourTable)

Note that even though there appear to be only 3 models in your data set, we can make the query more flexible by using a subquery which counts the number of distinct models in the entire table.


问:
Selenium on Raspberry Pi using Mono (C#)
I'have written a C# pogram using selenium. It works perfelcty fine when using it on windows, but not on the Rapsberry Pi. [It works without the selenium part].

Here is the code:

```<code>var options = new FirefoxOptions();
                options.BrowserExecutableLocation = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";

//IWebDriver driver = new FirefoxDriver(options);   // WINDOWS VERSION
IWebDriver driver = new FirefoxDriver(); // LINUX VERSION
string xpath = "html/body/div[1]/div/main/div/section/section[2]/div/div[2]/div[1]/div/div/textarea";
string xpathButton = "html/body/div[1]/div/main/div/section/section[2]/div/div[2]/div[1]/div/button";

driver.Url = myurl;
driver.FindElement(By.XPath(xpathButton)).Click();
List<IWebElement> webElems = driver.FindElements(By.XPath(xpath)).ToList();

string comparestring = "";
int comparecounter = 0;

foreach (IWebElement element in webElems)
{
    comparestring = element.Text;
}
</code>```

I keep getting the following error on the raspberry pi:

Connection refused

and:
OpenQA.Selenium.WebDriverException: Unable to find a matching set of capabilities
  at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError (OpenQA.Selenium.Remote.Response errorResponse) [0x00000] in :0
  at OpenQA.Selenium.Remote.RemoteWebDriver.Execute (System.String driverCommandToExecute, System.Collections.Generic.Dictionary`2 parameters) [0x00000] in :0
  at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession (ICapabilities desiredCapabilities) [0x00000] in :0
  at OpenQA.Selenium.Remote.RemoteWebDriver..ctor (ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) [0x00000] in :0
  at OpenQA.Selenium.Firefox.FirefoxDriver..ctor (OpenQA.Selenium.Firefox.FirefoxDriverService service, OpenQA.Selenium.Firefox.FirefoxOptions options, TimeSpan commandTimeout) [0x00000] in :0
  at OpenQA.Selenium.Firefox.FirefoxDriver..ctor (OpenQA.Selenium.Firefox.FirefoxOptions options) [0x00000] in :0
  at OpenQA.Selenium.Firefox.FirefoxDriver..ctor () [0x00000] in :0
  at Dialga.MyBot+c__async8.MoveNext () [0x00000] in :0

答:
So I got it working. The reason it did not work properly was a mismatch between Firefox and the geckodriver-versions.
I solved it by downloading Firefox 52.2-ESR and using geckdrover 1.7. [Selenium 3.4].

Sadly Firefox is way to slow on the raspberry Pi so I switched it all up for the PhantomJS webdriver.

Body:
I'have written a C# pogram using selenium. It works perfelcty fine when using it on windows, but not on the Rapsberry Pi. [It works without the selenium part].

Here is the code:

var options = new FirefoxOptions();
                options.BrowserExecutableLocation = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";

//IWebDriver driver = new FirefoxDriver(options);   // WINDOWS VERSION
IWebDriver driver = new FirefoxDriver(); // LINUX VERSION
string xpath = "html/body/div[1]/div/main/div/section/section[2]/div/div[2]/div[1]/div/div/textarea";
string xpathButton = "html/body/div[1]/div/main/div/section/section[2]/div/div[2]/div[1]/div/button";

driver.Url = myurl;
driver.FindElement(By.XPath(xpathButton)).Click();
List<IWebElement> webElems = driver.FindElements(By.XPath(xpath)).ToList();

string comparestring = "";
int comparecounter = 0;

foreach (IWebElement element in webElems)
{
    comparestring = element.Text;
}

I keep getting the following error on the raspberry pi:

Connection refused

and:
OpenQA.Selenium.WebDriverException: Unable to find a matching set of capabilities
  at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError (OpenQA.Selenium.Remote.Response errorResponse) [0x00000] in :0
  at OpenQA.Selenium.Remote.RemoteWebDriver.Execute (System.String driverCommandToExecute, System.Collections.Generic.Dictionary`2 parameters) [0x00000] in :0
  at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession (ICapabilities desiredCapabilities) [0x00000] in :0
  at OpenQA.Selenium.Remote.RemoteWebDriver..ctor (ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) [0x00000] in :0
  at OpenQA.Selenium.Firefox.FirefoxDriver..ctor (OpenQA.Selenium.Firefox.FirefoxDriverService service, OpenQA.Selenium.Firefox.FirefoxOptions options, TimeSpan commandTimeout) [0x00000] in :0
  at OpenQA.Selenium.Firefox.FirefoxDriver..ctor (OpenQA.Selenium.Firefox.FirefoxOptions options) [0x00000] in :0
  at OpenQA.Selenium.Firefox.FirefoxDriver..ctor () [0x00000] in :0
  at Dialga.MyBot+c__async8.MoveNext () [0x00000] in :0