问:
How to get all Unicode characters from specific categories?
How to get, for example..., a code point pattern like x-y\uxxxx\Uxxxxxxxxx from the Connector Punctuation (Pc) category, for scanning ECMAScript 3/JavaScript identifiers?

Original question

I need help for verifying a valid character (code point) of a ECMA-262 (3º edition, 7.6) identifier for a lexical scanner.

Syntax quote

Identifier ::

IdentifierName but not ReservedWord

IdentifierName ::

IdentifierStart

IdentifierName IdentifierPart

IdentifierStart ::

UnicodeLetter

$

_

<s>\ UnicodeEscapeSequence</s> # no need to check this

IdentifierPart ::

IdentifierStart

UnicodeCombiningMark

UnicodeDigit

UnicodeConnectorPunctuation

UnicodeLetter ::

any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase > letter (Ll)”, “Titlecase letter (Lt)”,
  “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number
  (Nl)”.

UnicodeCombiningMark ::

any character in the Unicode categories “Non-spacing mark (Mn)” or “Combining spacing mark (Mc)”

UnicodeDigit ::

any character in the Unicode category “Decimal number (Nd)”

UnicodeConnectorPunctuation ::

any character in the Unicode category “Connector punctuation (Pc)”

As you can see, it takes any character of certain categories.

I need to have all these possible characters, so my first step was to locate "Connector punctuation" on this Unicode 5.0 chart, but 0 matches and I believe I'm doing it the wrong way. So could someone help me?

答:
Unicode offers this tool for determining sets of characters. It uses regular expressions with property-value pairs enclosed in [::].

For all characters in Unicode 5 you want to do [:age=5.0:].

The rest are "general categories" (gc). So for example [:age=5.0:]&[:gc=Lu:] will find all uppercase letters in Unicode 5 (gc=L will find all letters in general).

For IdentifierStart you need [:age=5.0:]&[[:gc=L:][:gc=Nl:]\$_]. For IdentifierPart you need [:age=5.0:]&[[:gc=L:][:gc=Nl:][:gc=Mn:][:gc=Mc:][:gc=Nd:][:gc=Pc:]\$_].

Unicode also has properties called ID_Start and ID_Continue but they don't include the same characters as your specifications.

Here is also an overview of all Unicode character properties.


来源: stackexchange

问:
Reset Wordpress 'next User ID' number
I've been setting up a WordPress-based website with a membership system that uses the User ID as a membership number.

During testing I've made many users then deleted them. Now that testing is complete, when I make a new user, they get an ID of 25, 26, 27, etc…

How I can reset the 'next User ID' number back down to 2 (or whatever) so the new users become 2 then 3 then 4 etc.

Is it something I need to do in CPanel in phpMyAdmin / SQL?

答:
Yes you can do it with phpMyAdmin or SQL.

First go into the wp_users table and delete any users you need to.

Then go into the wp_usermeta table and delete any meta entries that correspond do the IDs of those deleted users.

Then you need to alter the wp_users table to reset its auto increment value. So you can do that in phpMyAdmin, or use SQL like this:

```<code>ALTER TABLE `wp_users` AUTO_INCREMENT={ID you want to be used next}
</code>```

So if you want the next created user to have the id number 4 it would look like this:

```<code>ALTER TABLE `wp_users` AUTO_INCREMENT=4
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reset Wordpress 'next User ID' number

Body:
Yes you can do it with phpMyAdmin or SQL.

First go into the wp_users table and delete any users you need to.

Then go into the wp_usermeta table and delete any meta entries that correspond do the IDs of those deleted users.

Then you need to alter the wp_users table to reset its auto increment value. So you can do that in phpMyAdmin, or use SQL like this:

ALTER TABLE `wp_users` AUTO_INCREMENT={ID you want to be used next}

So if you want the next created user to have the id number 4 it would look like this:

ALTER TABLE `wp_users` AUTO_INCREMENT=4


问:
Divide the RDD into partitions with fixed number of elements in each partition
In Apache Spark,

repartition(n) - allows partitioning the RDD into exactly n partitions.

But how to partition the given RDD into partitions such that all partitions (exception for the last partition) have specified number of elements. Given that number of elements in RDD is not known and doing .count() is expensive.

```<code>C = sc.parallelize([x for x in range(10)],2)
Let's say internally,  C = [[0,1,2,3,4,5], [6,7,8,9]]
C = someCode(3)
</code>```

Expected:

```<code>C = [[0,1,2], [3,4,5], [6, 7, 8], [9]]
</code>```

答:
Quite easy in pyspark:

```<code>    C = sc.parallelize([x for x in range(10)],2)
    rdd = C.map(lambda x : (x, x))
    C_repartitioned = rdd.partitionBy(4,lambda x: int( x *4/11)).map(lambda x: x[0]).glom().collect()
    C_repartitioned

    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
</code>```

It is called custom partitioning.
More on that: http://sparkdatasourceapi.blogspot.ru/2016/10/patitioning-in-spark-writing-custom.html

http://baahu.in/spark-custom-partitioner-java-example/

Body:
In Apache Spark,

repartition(n) - allows partitioning the RDD into exactly n partitions.

But how to partition the given RDD into partitions such that all partitions (exception for the last partition) have specified number of elements. Given that number of elements in RDD is not known and doing .count() is expensive.

C = sc.parallelize([x for x in range(10)],2)
Let's say internally,  C = [[0,1,2,3,4,5], [6,7,8,9]]
C = someCode(3)

Expected:

C = [[0,1,2], [3,4,5], [6, 7, 8], [9]]

Body:
Quite easy in pyspark:

    C = sc.parallelize([x for x in range(10)],2)
    rdd = C.map(lambda x : (x, x))
    C_repartitioned = rdd.partitionBy(4,lambda x: int( x *4/11)).map(lambda x: x[0]).glom().collect()
    C_repartitioned

    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

It is called custom partitioning.
More on that: http://sparkdatasourceapi.blogspot.ru/2016/10/patitioning-in-spark-writing-custom.html

http://baahu.in/spark-custom-partitioner-java-example/


问:
Excel VBA If Statement to Find Cells That Contain A String
I'm looking to create an IF/Else statment in VBA that when run will return a True or False value based on if a cell contains a certain string of text.  So basically I want a True value returned if the cell contains the specified string or a False value if it does not contain the specified string.  This formula needs to run down a range of cells not just one if that makes a difference.  I'm thinking I need to use the InStr function, but I'm not 100% sure if that is correct or how to implement it.  I am fairly new to VBA so any help I can get would be greatly appreciated as I have been stuck on this for several hours.

Thank You

答:
Well this is a very badly asked question but I think everyone has needed some help at some point in life. That being said, here is the code you are asking for

```<code>Sub FindString()
'Declare the range
Dim rng As Range
'Assign the range to find
Set rng = ActiveSheet.Range("A1:A100")
'Loop though each cell
For Each cell In rng.Cells
    'Check if cell has the string and set text
    'of the next column to True or False
    cell.Offset(0, 1).Value = IIf(InStr(1, cell, "stringToFind"), "True", "False")
Next
End Sub
</code>```

Give it a try and let me know your comments

Body:
Well this is a very badly asked question but I think everyone has needed some help at some point in life. That being said, here is the code you are asking for

Sub FindString()
'Declare the range
Dim rng As Range
'Assign the range to find
Set rng = ActiveSheet.Range("A1:A100")
'Loop though each cell
For Each cell In rng.Cells
    'Check if cell has the string and set text
    'of the next column to True or False
    cell.Offset(0, 1).Value = IIf(InStr(1, cell, "stringToFind"), "True", "False")
Next
End Sub

Give it a try and let me know your comments


问:
Serializing and Deserializing Raw Json String using Jackson
I am using Jackson Fasterxml version 2.8.0 to serialize and deserialize json as follows:

```<code>public static byte[] serializeData(Object object){
   final ObjectMapper mapper = new ObjectMapper();
   return mapper.writeValueAsBytes(object);
}

public static void main(String [] args) {
  String json = "{ \"id\" : \"user1\" }"; // need to escape or else compiler complains

  byte[] result = serializeData(json);

  final ObjectMapper mapper = new ObjectMapper();
  final JsonNode jsonNode = mapper.readTree(result);

  System.out.println(json);
  System.out.println(jsonNode.toString());
  System.out.println(jsonNode.getNodeType());

  Iterator<String> fields = jsonNode.fieldNames();
  while(fields.hasNext()){
    System.out.println("field - " + fields.next());
  }
}
</code>```

The output was:

```<code>{ "id" : "user1" }
"{ \"id\" : \"user1\" }"
STRING
</code>```

Notice there is no output lines for printing the field names. So, it seems like the JsonNode does not have any properties and for some reason the toString() has escape chars in them. Am I using this library in the wrong manner? Why is that when deserializing the byte array results in a behavior where I can't find the fields I initially added?

Updates

Providing some more context of the application. The app receives the Json as a String input. The code that deserializes the Json is not aware of the model of the Json. It just expects it to be valid Json object so that it can iterate through the various fields in it.

答:
It's because you are calling toString() inside writeValueAsBytes method which converts object into string. Following should work fine:

```<code>final ObjectMapper mapper = new ObjectMapper();
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("id", "user1");
byte[] result = mapper.writeValueAsBytes(node);
final JsonNode json = mapper.readTree(result);
System.out.println(json);
Iterator<String> fieldNames = json.fieldNames();
while(fieldNames.hasNext()){
    System.out.println(fieldNames.next());
}
if(json.has("id")){
  System.out.println("No id");
}
</code>```

Update

If you do not know the type of the object you want your json to be deserialized into, then you can just deserialize it into a Map, e.g.:

```<code>Map<String, Object> result = mapper.readValue(result, new TypeReference<Map<String,Object>>() {});
</code>```

Body:
I am using Jackson Fasterxml version 2.8.0 to serialize and deserialize json as follows:

public static byte[] serializeData(Object object){
   final ObjectMapper mapper = new ObjectMapper();
   return mapper.writeValueAsBytes(object);
}

public static void main(String [] args) {
  String json = "{ \"id\" : \"user1\" }"; // need to escape or else compiler complains

  byte[] result = serializeData(json);

  final ObjectMapper mapper = new ObjectMapper();
  final JsonNode jsonNode = mapper.readTree(result);

  System.out.println(json);
  System.out.println(jsonNode.toString());
  System.out.println(jsonNode.getNodeType());

  Iterator<String> fields = jsonNode.fieldNames();
  while(fields.hasNext()){
    System.out.println("field - " + fields.next());
  }
}

The output was:

{ "id" : "user1" }
"{ \"id\" : \"user1\" }"
STRING

Notice there is no output lines for printing the field names. So, it seems like the JsonNode does not have any properties and for some reason the toString() has escape chars in them. Am I using this library in the wrong manner? Why is that when deserializing the byte array results in a behavior where I can't find the fields I initially added?

Updates

Providing some more context of the application. The app receives the Json as a String input. The code that deserializes the Json is not aware of the model of the Json. It just expects it to be valid Json object so that it can iterate through the various fields in it.

Body:
It's because you are calling toString() inside writeValueAsBytes method which converts object into string. Following should work fine:

final ObjectMapper mapper = new ObjectMapper();
ObjectNode node = JsonNodeFactory.instance.objectNode();
node.put("id", "user1");
byte[] result = mapper.writeValueAsBytes(node);
final JsonNode json = mapper.readTree(result);
System.out.println(json);
Iterator<String> fieldNames = json.fieldNames();
while(fieldNames.hasNext()){
    System.out.println(fieldNames.next());
}
if(json.has("id")){
  System.out.println("No id");
}

Update

If you do not know the type of the object you want your json to be deserialized into, then you can just deserialize it into a Map, e.g.:

Map<String, Object> result = mapper.readValue(result, new TypeReference<Map<String,Object>>() {});


问:
Box plot with bands with standard deviation and range
I am new to R and ggplot2. Any help is much appreciated! I have here a data set, I am trying to graph

```<code>   weight band  mean_1     mean_2  SD_1       SD_2   min_1  min_2   max_1  max_2
    1            5         .           3        .    0.17       .    27   .
    2            6         .         3.7        .     1.1       .    23   .
    3            8         8         4.3        4.1     1   1.749    27   27
    4            8         9         3.3        6     2.3   1.402    13   42
</code>```

In this set of data, I am trying to plot a bar graph of mean 1 and mean 2 side by side under the given weight_band (1-4) and applying error bars for min (1&2 respectively) and max (1&2 respectively). The "." notates that no data.

I have browsed through stackoverflow and other website, but haven't find the solution I am looking for.

the code I have is as follows:

```<code>sk1 <- read.csv(file="analysis.csv")

library(reshape2)

sk2 <- melt(sk1,id.vars = "Weight_band")
c <- ggplot(sk2, aes(x = Weight_band, y = value, fill = variable))
c + geom_bar(stat = "identity",  position="dodge")
</code>```

However, using this method, it does not limit the graph to only plotting the mean only. Is there a set of code to do so? Furthermore, is there a method to apply min and max as error bars to their respective mean? I thank everyone in advance. This would help me greatly in advancing my understanding of R's ggplot2 function

答:
This should get you close, we need to do a little more data cleaning and reshaping to make ggplot happy :)

```<code>library(reshape2)

df <- read.table(text = "weight_band  mean_1     mean_2  SD_1       SD_2   min_1  min_2   max_1  max_2
                 1            5         .           3        .    0.17       .    27   .
                 2            6         .         3.7        .     1.1       .    23   .
                 3            8         8         4.3        4.1     1   1.749    27   27
                 4            8         9         3.3        6     2.3   1.402    13   42", header = T)
sk2 <- melt(df,id.vars = "weight_band")

## Clean

sk2$group <- gsub(".*_(\\d)", "\\1", sk2$variable)
# new column used for color or fill aes and position dodging
sk2$variable <- gsub("_.*", "", sk2$variable)
# make these variables universal not group specific

## Reshape again

sk3 <- dcast(sk2, weight_band + group ~ variable)
# spread it back to kinda wide format
sk3 <- dplyr::mutate_if(sk3, is.character, as.numeric)
# convert every column to numeric if character now

# plot values seem a little wonky but the plot is coming together
ggplot(sk3, aes(x = as.factor(weight_band), y = mean, color = as.factor(group))) +
    geom_bar(position = "dodge", stat = "identity") +
    geom_errorbar(aes(ymax = max, ymin = min), position = "dodge")
</code>```

Body:
I am new to R and ggplot2. Any help is much appreciated! I have here a data set, I am trying to graph

   weight band  mean_1     mean_2  SD_1       SD_2   min_1  min_2   max_1  max_2
    1            5         .           3        .    0.17       .    27   .
    2            6         .         3.7        .     1.1       .    23   .
    3            8         8         4.3        4.1     1   1.749    27   27
    4            8         9         3.3        6     2.3   1.402    13   42

In this set of data, I am trying to plot a bar graph of mean 1 and mean 2 side by side under the given weight_band (1-4) and applying error bars for min (1&2 respectively) and max (1&2 respectively). The "." notates that no data.

I have browsed through stackoverflow and other website, but haven't find the solution I am looking for.

the code I have is as follows:

sk1 <- read.csv(file="analysis.csv")

library(reshape2)

sk2 <- melt(sk1,id.vars = "Weight_band")
c <- ggplot(sk2, aes(x = Weight_band, y = value, fill = variable))
c + geom_bar(stat = "identity",  position="dodge")

However, using this method, it does not limit the graph to only plotting the mean only. Is there a set of code to do so? Furthermore, is there a method to apply min and max as error bars to their respective mean? I thank everyone in advance. This would help me greatly in advancing my understanding of R's ggplot2 function

Body:
This should get you close, we need to do a little more data cleaning and reshaping to make ggplot happy :)

library(reshape2)

df <- read.table(text = "weight_band  mean_1     mean_2  SD_1       SD_2   min_1  min_2   max_1  max_2
                 1            5         .           3        .    0.17       .    27   .
                 2            6         .         3.7        .     1.1       .    23   .
                 3            8         8         4.3        4.1     1   1.749    27   27
                 4            8         9         3.3        6     2.3   1.402    13   42", header = T)
sk2 <- melt(df,id.vars = "weight_band")

## Clean

sk2$group <- gsub(".*_(\\d)", "\\1", sk2$variable)
# new column used for color or fill aes and position dodging
sk2$variable <- gsub("_.*", "", sk2$variable)
# make these variables universal not group specific

## Reshape again

sk3 <- dcast(sk2, weight_band + group ~ variable)
# spread it back to kinda wide format
sk3 <- dplyr::mutate_if(sk3, is.character, as.numeric)
# convert every column to numeric if character now

# plot values seem a little wonky but the plot is coming together
ggplot(sk3, aes(x = as.factor(weight_band), y = mean, color = as.factor(group))) +
    geom_bar(position = "dodge", stat = "identity") +
    geom_errorbar(aes(ymax = max, ymin = min), position = "dodge")


问:
What is needed to generate kerberos keytab file on windows?
I was looking for answer to above question on different web sites but in the every case there was how to generate keytab file. I need keytab to get hbase connection which contains kerberos authentication.</p>

答:
In order to generate a keytab on Windows, you need to be running some version of Kerberos which talks back to a Directory server.  On Windows, by far the most prevalent example of this is Active Directory, which has Kerberos support built-in.  You'll need to create the keytab on a Windows server joined to the Active Directory domain, using the ktpass command to actually create the keytab.

Keytab generation syntax example:

```<code>ktpass -out centos1-dev-local.keytab -mapUser krbCentos@DEV.LOCAL +rndPass -mapOp set +DumpSalt -crypto AES256-SHA1 -ptype KRB5_NT_PRINCIPAL -princ HTTP/centos1.dev.local@DEV.LOCAL
</code>```

The above command example successfully creats a keytab for use in an AD domain named DEV.LOCAL.  Note: notice the use of the randomize password syntax (+rndPass).  In my opinion, there is no need to specify a password in the keytab creation command syntax.   Instead, it's better to allow the password to be randomized - that provides much better security since it prevents anyone from being able to manually logon as the AD account surreptitiously and bypass the keytab.

For additional reference, I highly suggest you read my article on Kerberos keytab creation on the Windows platform on Microsoft Technet which greatly expands on what I said here:  Kerberos Keytabs – Explained.  I frequently go back and edit it based on questions I see here in this forum.

Body:
In order to generate a keytab on Windows, you need to be running some version of Kerberos which talks back to a Directory server.  On Windows, by far the most prevalent example of this is Active Directory, which has Kerberos support built-in.  You'll need to create the keytab on a Windows server joined to the Active Directory domain, using the ktpass command to actually create the keytab.

Keytab generation syntax example:

ktpass -out centos1-dev-local.keytab -mapUser krbCentos@DEV.LOCAL +rndPass -mapOp set +DumpSalt -crypto AES256-SHA1 -ptype KRB5_NT_PRINCIPAL -princ HTTP/centos1.dev.local@DEV.LOCAL

The above command example successfully creats a keytab for use in an AD domain named DEV.LOCAL.  Note: notice the use of the randomize password syntax (+rndPass).  In my opinion, there is no need to specify a password in the keytab creation command syntax.   Instead, it's better to allow the password to be randomized - that provides much better security since it prevents anyone from being able to manually logon as the AD account surreptitiously and bypass the keytab.

For additional reference, I highly suggest you read my article on Kerberos keytab creation on the Windows platform on Microsoft Technet which greatly expands on what I said here:  Kerberos Keytabs – Explained.  I frequently go back and edit it based on questions I see here in this forum.


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答: For anything you're concatenating manually in code, performance probably doesn't matter, so readability is king. For me, this often means using heredoc syntax. I don't like the way it breaks my indentation structure, but it's especially nice when you want line breaks and/or tabs inserted correctly into your strings.</p>

OwnerDisplayName: Darryl Hein

ContentLicense: CC BY-SA 2.5

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon


问:
Pass struct by reference in C
Is this code correct? It runs as expected, but is this code correctly using the pointers and dot notation for the struct?</p>

```<code>struct someStruct {
 unsigned int total;
};

int test(struct someStruct* state) {
 state->total = 4;
}

int main () {
 struct someStruct s;
 s.total = 5;
 test(&s);
 printf("\ns.total = %d\n", s.total);
}
</code>```

答: Yep. It's correct. If it wasn't (from the . / -> point of view), your compiler would yell.</p>

Title: Pass struct by reference in C

Body:
Is this code correct? It runs as expected, but is this code correctly using the pointers and dot notation for the struct?

struct someStruct {
 unsigned int total;
};

int test(struct someStruct* state) {
 state->total = 4;
}

int main () {
 struct someStruct s;
 s.total = 5;
 test(&s);
 printf("\ns.total = %d\n", s.total);
}


问:
Object property returning undefined when using ternary operator
I'm building an object literal and using the if-else shorthand to set the value of one of my properties, but it keeps returning undefined and I don't understand why:

```<code>var cca = cca || {};

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        site_title: (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle,
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
};
</code>```

When I evaluate with a break-point the evaluation returns the proper value but it's not getting saved to the property. However, I'm setting another property in a similar way (cca.language) and that's working fine.

答:
At the time the ternary expression is evaluated, the assignment to cca inside the initialization function hasn't happened yet. Thus, cca.englishTitle and cca.frenchTitle don't yet exist. One solution is to delay that particular property assignment until afterwards:

```<code>var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
    cca.site_title: (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle;
    site_setup();
};
</code>```

As to why the debugger is evaluating the expression to "ENGLISH SITE", that's because the assignment has already completed (you're on to the next statement).

Body:
I'm building an object literal and using the if-else shorthand to set the value of one of my properties, but it keeps returning undefined and I don't understand why:

var cca = cca || {};

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        site_title: (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle,
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
};

When I evaluate with a break-point the evaluation returns the proper value but it's not getting saved to the property. However, I'm setting another property in a similar way (cca.language) and that's working fine.

Body:
At the time the ternary expression is evaluated, the assignment to cca inside the initialization function hasn't happened yet. Thus, cca.englishTitle and cca.frenchTitle don't yet exist. One solution is to delay that particular property assignment until afterwards:

var initialization = function () {
    cca = {
        languageCode: _spPageContextInfo.currentLanguage,
        language: (_spPageContextInfo.currentLanguage == 1033) ? "english" : "french",
        englishTitle: "ENGLISH SITE",
        frenchTitle: "FRENCH SITE",
        page: _spPageContextInfo,
        path: _spPageContextInfo.webAbsoluteUrl,
        isGrantSite: function () {
            return _.includes(cca.path, "grants");
        }
    };
    cca.site_title: (_spPageContextInfo.currentLanguage == 1033) ? cca.englishTitle : cca.frenchTitle;
    site_setup();
};

As to why the debugger is evaluating the expression to "ENGLISH SITE", that's because the assignment has already completed (you're on to the next statement).


问:
Moga gamepad not working with A-Frame
I have a Moga Pro gamepad that I am trying to use with A-Frame.  According to the A-Frame 0.5.0 docs on tracked-controls, I should be able to add something like:

```<code><a-entity tracked-controls="controller: 0; idPrefix: Moga"></a-entity>
</code>```

and I would be able to use my gamepad.  But the above code doesn't work.

Also, I am running a gamepad test on a local server that identifies my controller as

```<code>gamepad: Moga Pro 2 HID (STANDARD GAMEPAD Vendor: 20d6 Product: 6271)
</code>```

Do I need to do something else in the A-Frame code to make the gamepad work?

答: The tracked-controls component is for 6DOF tracked controllers, and won't support arbitrary gamepads. You probably want to try universal-controls or gamepad-controls instead.

Title: Moga gamepad not working with A-Frame

Body:
I have a Moga Pro gamepad that I am trying to use with A-Frame.  According to the A-Frame 0.5.0 docs on tracked-controls, I should be able to add something like:

and I would be able to use my gamepad.  But the above code doesn't work.

Also, I am running a gamepad test on a local server that identifies my controller as

gamepad: Moga Pro 2 HID (STANDARD GAMEPAD Vendor: 20d6 Product: 6271)

Do I need to do something else in the A-Frame code to make the gamepad work?


答:
Yes, that's right. It makes a struct s, sets its total to 5, passes a pointer to it to a function that uses the pointer to set the total to 4, then prints it out. -> is for members of pointers to structs and . is for members of structs. Just like you used them.

The return values are different though. test should probably be void, and main needs a return 0 at its end.

Title: Pass struct by reference in C


问:
Interact with CalDav Server from asp.net MVC
I am struggling to find any documentation on using a caldav server to store events in an asp.net mvc application.

I have had no problem so far getting a local server up and running using Radicale. I have also set up iCal events internally using Ical.Net. Retrieving and updating information stored on the server is the main concern.

I want to write something like:

```<code>var calDavServer = getServer("localhost:5232");
var calendar = calDavServer.getCalendar();

// Do operations on calendar...

calDavServer.updateCalendar(calendar);
</code>```

Thank you for any help and/or advice.

答:
I don't know much about ASP.NET and I think that C# support for CalDAV may be a bit weak, but after all CalDAV is just some HTTP+XML+iCalendar. You do not really need a 'library' for that.

Building a CalDAV client is a great introduction to the protocol.

It looks like you may be able to use iCal.NET to handle the iCalendar processing part.

Body:
I am struggling to find any documentation on using a caldav server to store events in an asp.net mvc application.

I have had no problem so far getting a local server up and running using Radicale. I have also set up iCal events internally using Ical.Net. Retrieving and updating information stored on the server is the main concern.

I want to write something like:

var calDavServer = getServer("localhost:5232");
var calendar = calDavServer.getCalendar();

// Do operations on calendar...

calDavServer.updateCalendar(calendar);

Thank you for any help and/or advice.


问:
Minimum files to run MySQL or MariaDB server on Windows - (Portable MySQL/MariaDB)
I am looking for minimum files required by MariaDB or MySQL to run without installing it like a portable server. I prefer MariaDB instead of MySQL. I want to embed it in my software written in Delphi. My software will able to start and stop the server as required. I have googled around but no success.

I have read an article https://rawgit.com/pts/portable-mariadb/master/portable_mariadb.html and http://www.bluecrownsoftware.com/article/271/Installing-MySQL-without-Root-Access-on-Linux but it is for Linux and I have no experience with it.

I have also read the article MySql portable version but this article mentioned MySQL Essential version and I am unable to find it.
It will be an extra value if I have some configuration file hints for successful running the server.

Thanks in advance.

答:
Speaking of MariaDB, it is 2 files and 3 directories.

Layout is like this:

bin\mysqld.exe

share\errmsg.sys # you can take it from share\english in normal installation or ZIP

data # an empty directory

you can start with

```<code>bin\mysqld.exe --console --skip-grant-tables
</code>```

(last parameter is essential, as you do not have system tables).

It is missing system tables, if you need to create them, this will be a couple of more files.

this tool helps https://mariadb.com/kb/en/mariadb/mysql_install_dbexe/ . mysqld_install_db.exe needs to be placed  next to mysqld.exe and then you can create system tables with

```<code>mysqld_install_db.exe --datadir=path-to-datadir
</code>```

UPDATE MariaDB 10.5.3 and later

bin\mysqld.exe

bin\server.dll

bin\mysql_install_db.exe (optional, run once to create data directory, can be removed afterwards)

data

Changes compared to the previous versions : server.dll is new (mysqld.exe needs it), errmsg.sys is no more needed

Body:
Speaking of MariaDB, it is 2 files and 3 directories.

Layout is like this:

bin\mysqld.exe

share\errmsg.sys # you can take it from share\english in normal installation or ZIP

data # an empty directory

you can start with

bin\mysqld.exe --console --skip-grant-tables

(last parameter is essential, as you do not have system tables).

It is missing system tables, if you need to create them, this will be a couple of more files.

this tool helps https://mariadb.com/kb/en/mariadb/mysql_install_dbexe/ . mysqld_install_db.exe needs to be placed  next to mysqld.exe and then you can create system tables with

mysqld_install_db.exe --datadir=path-to-datadir

UPDATE MariaDB 10.5.3 and later

bin\mysqld.exe

bin\server.dll

bin\mysql_install_db.exe (optional, run once to create data directory, can be removed afterwards)

data

Changes compared to the previous versions : server.dll is new (mysqld.exe needs it), errmsg.sys is no more needed

ContentLicense: CC BY-SA 4.0


问:
How to force Sphinx to use Python 3.x interpreter
I try to create documentation for a project written with Python 3.x. Sphinx is the tool I want to use and, according to the official site, its last version 1.1.2 is compatible with Python 3.1+. My OS is Archlinux, a Linux distribution which uses Python 3.2+ as the default Python package.

The installation and configuration is straight forward (easy_install -U Sphinx then sphinx-quickinstall) and I was never asked to choose between the 2.x or 3.x Python interpreter. But when I ask Sphinx to create the documentation of my project, my code is analyzed as if I wrote it for Python 2.x.

Is Sphinx ready for Python 3.x? Did I make a mistake?

答:
When I searched for an answer, this is the site that came up over and over. I'm thinking the answer is not easy to find because everyone else understands sphinx better than I can figure out. But if any is still searching for an answer, this is what eventually I ended up with:

sudo apt-get update

sudo apt-get install python3

sudo apt-get install sqlite3

sudo apt-get install idle3

sudo apt-get install python3-pip

sudo apt-get install python3-docutils

sudo apt-get install python3-jinja2

sudo apt-get install python3-pygments

sudo pip3 install Sphinx

The key was I was missing the fact that there was a pip3. I also update the system before adding a package as habit.


问:
Performing synchronus Requests using $.ajax
we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails  or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently  i mean using call back  and error handling .It is said that (we can never have error and success call back with a request)

```<code>function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }
</code>```

答:
Rather than using async: false, you'd be better off doing something like this:

```<code>function begin_ajax() {
    // Set your UI states here
}

function success_ajax(data) {
    // Run whatever needs to run if the request is successful.
}

function error_ajax(xhr, error_type, msg) {
    // Display error messages
}

function complete_ajax() {
    // Clean up UI
}
$.ajax({
    beforeSend: begin_ajax,
    success: success_ajax,
    error: error_ajax,
    complete: complete_ajax
    // Your parameters here
});
</code>```

Body:
we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails  or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently  i mean using call back  and error handling .It is said that (we can never have error and success call back with a request)

function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }

Body:
Rather than using async: false, you'd be better off doing something like this:

function begin_ajax() {
    // Set your UI states here
}

function success_ajax(data) {
    // Run whatever needs to run if the request is successful.
}

function error_ajax(xhr, error_type, msg) {
    // Display error messages
}

function complete_ajax() {
    // Clean up UI
}
$.ajax({
    beforeSend: begin_ajax,
    success: success_ajax,
    error: error_ajax,
    complete: complete_ajax
    // Your parameters here
});


问:
Perl CGI redirect after cancelling on a 401
I've currently got a small script running that sends a 401 to the client, upon cancelling and not providing user details the script will return nothing.

I'd like to send a redirect to the page they have come from instead.

The main subroutine looks like this;

```<code>#!usr/bin/perl
use strict;
use CGI;

sub checkAuth {
  my ($user, $pass) = &getAuthUsers(); # Get the user and pass of already authenticated users.
  unless ($user) {
    &sendAuthenticationHeader(); # Send 401
  }

  # Check user against DB and return 1 for success.
  if ( &checkUser($user, $pass) eq 'Y') { return 1 };
  else { # This is the redirect I'm trying to issue.
    my $cgi = CGI->new();
    print $cgi->redirect($ENV{HTTP_REFERER}); # Redirect to the referer url
    exit;
  }
}
</code>```

Unfortunately whenever I try to send new headers it's just received as plain text.

Any help is appreciated, thanks in advance.

答:
sendAuthenticationHeader() emits a header with a 401 status code.

print $cgi->redirect($ENV{HTTP_REFERER}); emits a header with a 302 status code. Of course, since you've already emitted a header, this gets treated as the body.

There's no point to return a 401 if you want to redirect. Change your code to

```<code>sub checkAuth {
  my ($user, $pass) = getAuthUsers();

  if (!$user || !checkUser($user, $pass)) {
    print CGI::redirect($ENV{HTTP_REFERER});
    exit;
  }
}
</code>```

Notes:

Removed incorrect &. Don't tell Perl to ignore the prototype of subs. Address the underlying issue instead if required.

The return value of checkUser is boolean, so it should return either a true or a false value (e.g. 0 or 1), not two true values (e.g. N or Y). The above code assumed you fixed this.

Body:
I've currently got a small script running that sends a 401 to the client, upon cancelling and not providing user details the script will return nothing.

I'd like to send a redirect to the page they have come from instead.

The main subroutine looks like this;

#!usr/bin/perl
use strict;
use CGI;

sub checkAuth {
  my ($user, $pass) = &getAuthUsers(); # Get the user and pass of already authenticated users.
  unless ($user) {
    &sendAuthenticationHeader(); # Send 401
  }

  # Check user against DB and return 1 for success.
  if ( &checkUser($user, $pass) eq 'Y') { return 1 };
  else { # This is the redirect I'm trying to issue.
    my $cgi = CGI->new();
    print $cgi->redirect($ENV{HTTP_REFERER}); # Redirect to the referer url
    exit;
  }
}

Unfortunately whenever I try to send new headers it's just received as plain text.

Any help is appreciated, thanks in advance.

Body:
sendAuthenticationHeader() emits a header with a 401 status code.

print $cgi->redirect($ENV{HTTP_REFERER}); emits a header with a 302 status code. Of course, since you've already emitted a header, this gets treated as the body.

There's no point to return a 401 if you want to redirect. Change your code to

sub checkAuth {
  my ($user, $pass) = getAuthUsers();

  if (!$user || !checkUser($user, $pass)) {
    print CGI::redirect($ENV{HTTP_REFERER});
    exit;
  }
}

Notes:

Removed incorrect &. Don't tell Perl to ignore the prototype of subs. Address the underlying issue instead if required.

The return value of checkUser is boolean, so it should return either a true or a false value (e.g. 0 or 1), not two true values (e.g. N or Y). The above code assumed you fixed this.


问:
Is there any way to make these link inside another link work
I have the following markup:

```<code><a class="list-group-item hola" id="competition-card-<%= competition.id %>" href="a_url_to_a_site">
    <div class='row'>
          <div class='col-xs-11'>
            Some text
          </div>

        <div class='col-xs-1 shows-submenu'>
           Some text
        </div>
    </div>
</a>
</code>```

I'm trying to achieve:

If user clicks the 'a' tag he is directed to a site, except when...

user clicks the '.shows-submenu' div a hidden div is displayed.

My jQuery is as follows:

```<code>$('body').on('click', '.shows-submenu', function(e) {
   event.stopImmediatePropagation();
  if ($(this).closest('a.list-group-item').next('.hidden-group-item').hasClass('hide')) {
     $('.hidden-group-item').addClass('hide');
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  else {
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
});
</code>```

Currently, if I click '.shows-submenu' div the 'a' tag is still called and I'm directed to the site.
As I'm using bootcards plugin I can't change the 'a' tag to a div, for example.

Is there any way to stop 'a' only when clicking the '.shows-submenu' div. I've tried using stopPropagation in both 'a' and the 'div' without success.

答:
I think what you want is event.preventDefault().  Both event.stopPropagation() and event.stopImmediatePropagation() will affect other event handlers but not the default behavior of an anchor.   Also you should declare the argument as event if that's how you're referring to it inside the function:

$('.show-submenu').on('click', function(event) {
  event.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
this follows link
    <div class="show-submenu">this does not</div>
</code>```

Body:
I have the following markup:

<a class="list-group-item hola" id="competition-card-<%= competition.id %>" href="a_url_to_a_site">

            Some text

           Some text

I'm trying to achieve:

If user clicks the 'a' tag he is directed to a site, except when...

user clicks the '.shows-submenu' div a hidden div is displayed.

My jQuery is as follows:

$('body').on('click', '.shows-submenu', function(e) {
   event.stopImmediatePropagation();
  if ($(this).closest('a.list-group-item').next('.hidden-group-item').hasClass('hide')) {
     $('.hidden-group-item').addClass('hide');
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
  else {
     $(this).closest('a.list-group-item').next('.hidden-group-item').toggleClass('hide');
  }
});

Currently, if I click '.shows-submenu' div the 'a' tag is still called and I'm directed to the site.
As I'm using bootcards plugin I can't change the 'a' tag to a div, for example.

Is there any way to stop 'a' only when clicking the '.shows-submenu' div. I've tried using stopPropagation in both 'a' and the 'div' without success.

Body:
I think what you want is event.preventDefault().  Both event.stopPropagation() and event.stopImmediatePropagation() will affect other event handlers but not the default behavior of an anchor.   Also you should declare the argument as event if that's how you're referring to it inside the function:

$('.show-submenu').on('click', function(event) {
  event.preventDefault();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://example.com">this follows link
    <div class="show-submenu">this does not</div>
</a>


问:
Trim whitespaces from esql string
I want to Trim the white-spaces from a string which I am getting from XML file using esql.

I am using trim command but it doesn't seems to work while trimming spaces, whereas if you want to trim something else the Trim() function seems to be working fine .

example

```<code>Trim(' ' From '  Nitin  ');
</code>```

Result

Nitin

```<code>Trim('i' From 'Nitin');
</code>```

Result

Ntn

答:
```<code>DECLARE whiteSpace CONSTANT CHARACTER CAST( X'090D0A20' AS CHAR CCSID 1208);
 -- tab, cr, lf, space
DECLARE input2 CHARACTER 'smith';

SET input2 = whiteSpace || input2 || whiteSpace;
SET OutputRoot.XMLNSC.Top.Out2 = TRIM( whiteSpace FROM input2);
</code>```

<p>output: </p>

```<code><Top><Out2>smith</Out2></Top>
</code>```

Title: Trim whitespaces from esql string

Body:
I want to Trim the white-spaces from a string which I am getting from XML file using esql.

I am using trim command but it doesn't seems to work while trimming spaces, whereas if you want to trim something else the Trim() function seems to be working fine .

example

Trim(' ' From '  Nitin  ');

Result

Nitin

Trim('i' From 'Nitin');

Result

Ntn

Body:
DECLARE whiteSpace CONSTANT CHARACTER CAST( X'090D0A20' AS CHAR CCSID 1208);
 -- tab, cr, lf, space
DECLARE input2 CHARACTER 'smith';

SET input2 = whiteSpace || input2 || whiteSpace;
SET OutputRoot.XMLNSC.Top.Out2 = TRIM( whiteSpace FROM input2);

output:

<Top><Out2>smith</Out2></Top>


问:
Syntax-highlighting for PXSL?
To mitigate some of the headache of working with XML I've been experimenting with PXSL, an abbreviated syntax for any XML document with advanced macro capabilities. However, since it's so new, I haven't been able to find any text editors that know how to parse it for syntax highlighting.

Do you know of any editors or plug-ins that would enable this? Where would I start if I wanted to define syntax highlighting, say for Notepad++?

Thanks in advance.

答:
I'd recomend PSpad, suports a lot of languages syntax coloring and it's freeware.
www.pspad.com</p>

OwnerDisplayName: Jweede

Title: Syntax-highlighting for PXSL?

LastEditorDisplayName: Nerdling


问:
How to create one to many in mongoDB using java
So I'm trying to make a system that is one of many styles DB in mongo using java.I am trying to recreate a school grading database where there are: teachers, classes, periods, students and their grades attributes. But my question is how do I implement one to many in java, for example, teachers and the classes they teach.

big diagram of DB

more precise diagram of DB

答:
I think that the question that you're asking is more about the schema design itself, the fact that it's "in java" seems irrelevant to your question.

Anyhow, it's quite a broad question and a broad topic. There's rarely, if ever, one way to approach a schema design.

I'd suggest you start with broadening your knowledge of the schema design process, and the various tradeoffs of different approaches.

Here are some resources to get you started:

6 Rules of Thumb for MongoDB Schema Design: Part 1 (links to
parts 2 and 3 within)

Data Model Design (MongoDB docs)

I think that after you've gone through those you should have some ideas around various approaches to your particular model, and you can check back here for additional help if needed. :-)


问:
Netlogo, changing exported file name
**I am trying to write information to a file for some experiments. Is it possible to change the file name for each experiment without having to change the code each time?

I was trying to use a slider to change the file name but had no luck.
**

答:
you can try

```<code>file-open (word "mytrack" fileName ".txt")
</code>```

word strings together its arguments and converts numbers to strings in the process.

Title: Netlogo, changing exported file name

Body:
you can try

file-open (word "mytrack" fileName ".txt")

word strings together its arguments and converts numbers to strings in the process.


问:
Firebase Data Collection with Unique Member
I would like to show a list of toys.
ach toy as a unique name.
The name can contain any character, so it can have a dot a slash or a dollar.
This is why I would prefer to use the push method to get a generated key.

The code I end up with is troublesome.
It is not thread safe and I could end up with duplicate toys.
Is there a better way?

```<code>var child = testsRef.orderByChild("name").equalTo("Meccano");

return child.once('value').then(function(snapshot) {
  var snap = snapshot.val();
  if (snapshot.val()) {
    alert('Toy ' + value + ' already exists.');
  } else {
    var newPostKey = testsRef.push().key;
    var updates = {};
    updates[newPostKey] = {          name: value        };
    var result = testsRef.update(updates);
    alert('We can only assume that it has worked.' + result);
  }
});
</code>```

I built a complete working codepen to illustrate my question here:
http://codepen.io/paganaye/pen/EWrayY

答:
Use the toy name as the key but first run it through a firebase key sanitizer like:

```<code>function fbKeySanitizer(str) {
  return encodeURIComponent(str).replace(/[.$[\]#\/]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase();
  });
}
</code>```

You can either save the original name as a property like you would with the push() method or you can use decodeURIComponent() to reverse the encoding to get back to the exact same string.

Body:
I would like to show a list of toys.
ach toy as a unique name.
The name can contain any character, so it can have a dot a slash or a dollar.
This is why I would prefer to use the push method to get a generated key.

The code I end up with is troublesome.
It is not thread safe and I could end up with duplicate toys.
Is there a better way?

var child = testsRef.orderByChild("name").equalTo("Meccano");

return child.once('value').then(function(snapshot) {
  var snap = snapshot.val();
  if (snapshot.val()) {
    alert('Toy ' + value + ' already exists.');
  } else {
    var newPostKey = testsRef.push().key;
    var updates = {};
    updates[newPostKey] = {          name: value        };
    var result = testsRef.update(updates);
    alert('We can only assume that it has worked.' + result);
  }
});

I built a complete working codepen to illustrate my question here:
http://codepen.io/paganaye/pen/EWrayY

Body:
Use the toy name as the key but first run it through a firebase key sanitizer like:

function fbKeySanitizer(str) {
  return encodeURIComponent(str).replace(/[.$[\]#\/]/g, function (c) {
    return '%' + c.charCodeAt(0).toString(16).toUpperCase();
  });
}

You can either save the original name as a property like you would with the push() method or you can use decodeURIComponent() to reverse the encoding to get back to the exact same string.


问:
Measure the quality of audio file .WAV after encryption my project language is VB.net
what is the way to measure the quality of the audio file WAV after encryption my project language is VB.net</p>

答: After encryption the file will be indistinguishable from random bytes, there is no information about the original file without decrypting it with the encryption key.</p>


问:
How to know whether the Register Email is verified or not in Firebase?
```<code>onSubmit(formData) {
if(formData.valid) {
  console.log(formData.value);
  this.af.auth.createUser({
    email: formData.value.email,
    password: formData.value.password
  }).then(
    authState => {
    authState.auth.sendEmailVerification();
    this.router.navigate(['/login'])
  }).catch(
    (err) => {
    console.log(err);
    this.error = err;
  })
}
}
</code>```

In Firebase, I set the SendEmailVerfication like the code above, and the email could send normally.However, in my app, there is no difference between the user who does not click the verification email with those clicked, how to make a difference?

答:
According to the documentation, the User object contains an emailVerified property.

So the user to which the signInWithEmailAndPassword method's promise resolves - or the user that is passed to the onAuthStateChanged method's callback - can be inspected and the value of emailVerified can be checked.

Body:
onSubmit(formData) {
if(formData.valid) {
  console.log(formData.value);
  this.af.auth.createUser({
    email: formData.value.email,
    password: formData.value.password
  }).then(
    authState => {
    authState.auth.sendEmailVerification();
    this.router.navigate(['/login'])
  }).catch(
    (err) => {
    console.log(err);
    this.error = err;
  })
}
}

In Firebase, I set the SendEmailVerfication like the code above, and the email could send normally.However, in my app, there is no difference between the user who does not click the verification email with those clicked, how to make a difference?


问:
JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."
I have been adding logs to the console to check the status of different variables without using the Firefox debugger.

However, in many places in which I add a console.log in my main.js file, I receive the following error instead of my lovely little handwritten messages to myself:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help http://xhr.spec.whatwg.org/

What alternatives to or wrappers for console.log can I add to my code use that will not cause this error?

Am I "doing it wrong"?

答: Visual Studio 2015/2017's live debugger is injecting code that contains the deprecated call.</p>


问:
Apache 2.4 query string with regex
Ok...trying to get a leg up on the new way of writing SSI in 2.4

Any of the SSI gurus out there that can help....I would really appreciate it.

I have this code that works with SSILegacyExprParser on

```<code>http://path-to-webpage?dynContent=AboutUs

<!--#set var="dynContent" value="" -->
<!--#if expr="$QUERY_STRING = /dynContent=([a-zA-Z0-9]+)/" -->
<!--#set var="dynContent" value="$1" -->
<!--#else -->
<!--#set var="dynContent" value="default" -->
<!--#endif -->

<!--#echo var="dynContent" -->
</code>```

The expected Response is AboutUs otherwise it is default

I have tried to re-write this line to make it work in Apache 2.4 without the SSILegacyExprParser like this....

```<code><!--#set var="dynContent" value="" -->
<!--#if expr="(%{QUERY_STRING} =~ /dynContent=([a-zA-Z0-9]+)/)" -->
<!--#set var="dynContent" value="$0" -->
<!--#else -->
<!--#set var="dynContent" value="default" -->
<!--#endif -->
</code>```

This works partially.  I get a Response back as dynContent=AboutUs

I really need it to give back AboutUs otherwise fallback to default

Any idea how I can get this?

答:
Ok...this took a lot of research and some luck.....mostly luck :-)

I got this to work....I understand the old using regex PRE Apache 2.4 but I don't understand the regex after Apache 2.4.....but I did get this to work.
Here is the code I used.

```<code><!--#set var="dynContent" value="" -->
<!--#if expr="v('QUERY_STRING') =~ /(dynContent=)(.*)/ && $2 =~ /(.*)/" -->
<!--#set var="dynContent" value="$0" -->
<!--#else -->
<!--#set var="dynContent" value="default" -->
<!--#endif -->
</code>```

I can now use it in the page as well as a variable for an include web page

```<code><!--#echo var="dynContent" -->
<!--#include virtual="/path-to-page/${dynContent}.shtml" -->
</code>```

If someone can explain this to me...please do....I would like to try and understand it.

Title: Apache 2.4 query string with regex

Body:
Ok...trying to get a leg up on the new way of writing SSI in 2.4

Any of the SSI gurus out there that can help....I would really appreciate it.

I have this code that works with SSILegacyExprParser on

http://path-to-webpage?dynContent=AboutUs

The expected Response is AboutUs otherwise it is default

I have tried to re-write this line to make it work in Apache 2.4 without the SSILegacyExprParser like this....

This works partially.  I get a Response back as dynContent=AboutUs

I really need it to give back AboutUs otherwise fallback to default

Any idea how I can get this?

Body:
Ok...this took a lot of research and some luck.....mostly luck :-)

I got this to work....I understand the old using regex PRE Apache 2.4 but I don't understand the regex after Apache 2.4.....but I did get this to work.
Here is the code I used.

<!--#set var="dynContent" value="" -->
<!--#if expr="v('QUERY_STRING') =~ /(dynContent=)(.*)/ && $2 =~ /(.*)/" -->
<!--#set var="dynContent" value="$0" -->
<!--#else -->
<!--#set var="dynContent" value="default" -->
<!--#endif -->

I can now use it in the page as well as a variable for an include web page

<!--#echo var="dynContent" -->
<!--#include virtual="/path-to-page/${dynContent}.shtml" -->

If someone can explain this to me...please do....I would like to try and understand it.


问:
Pagination not working in DRF APIView
I am using APIView for get and post items.

I wanted to implement pagination for my API using Django Rest Framework, but it is not working.

I want to show 10 items per page but when I do api/v1/items?page=1, I get all the items and if I just do api/v1/items I get an empty list.

Here is what I have done:

```<code>from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        """
        Return a list of all items of this user.
        """
        reply = {}
        page = request.GET.get('page')
        print ('page is', page)
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.filter(owner=request.user)
            paginator = Paginator(items, 1)
            items_with_pagination = paginator.page(page)
            if page is not None:
                reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)
</code>```

答:
You could make your life a lot easier and just use a ListView. By overriding render_to_response you can make it output json instead of HTML. It does all the pagination for you.</p>

```<code>from django.core import serializers
from django.views.generic import ListView

class MyListView(JSONResponseMixin, ListView):
    model = models.BaseItem
    paginate_by = 10

    def render_to_response(self, context):
        return JsonResponse(
            serializers.serialize("json", context),
            **response_kwargs
        )
</code>```

Title: Pagination not working in DRF APIView

Body:
I am using APIView for get and post items.

I wanted to implement pagination for my API using Django Rest Framework, but it is not working.

I want to show 10 items per page but when I do api/v1/items?page=1, I get all the items and if I just do api/v1/items I get an empty list.

Here is what I have done:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, format=None):
        """
        Return a list of all items of this user.
        """
        reply = {}
        page = request.GET.get('page')
        print ('page is', page)
        try:
            products = BaseItem.objects.owned_items().filter(owner=request.user)
            reply['data'] = OwnedItemSerializer(products, many=True).data

            items = BaseItem.objects.filter(owner=request.user)
            paginator = Paginator(items, 1)
            items_with_pagination = paginator.page(page)
            if page is not None:
                reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data)
            reply['data'].extend(ItemSerializer(items, many=True).data)

Body:
You could make your life a lot easier and just use a ListView. By overriding render_to_response you can make it output json instead of HTML. It does all the pagination for you.

from django.core import serializers
from django.views.generic import ListView

class MyListView(JSONResponseMixin, ListView):
    model = models.BaseItem
    paginate_by = 10

    def render_to_response(self, context):
        return JsonResponse(
            serializers.serialize("json", context),
            **response_kwargs
        )


问:
How can I invoke system functions from native code on AIX?
My purpose is invoke a system call or libc functions from native code.
The native code is a executable memory block which I insert some machine code into it. In the native code I try to invoke puts() or printf() functions to output a string. Then I call the native code. This sequence model is the Mono tries to do. But when I porting the Mono into AIX, I met a segment fault when invokes system library functions such as printf() or abs(). I guess it must break calling stack somewhere. But I could not resolve such problem I am not familiar with IBM powerpc platform.
I have wrote a simple program to demonstrate the sequence, it also lead to segment fault at calling puts(). It takes so much time, please give me some advises, thank you in advance!

```<code>#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h>

typedef uint8_t        guint8;
typedef int16_t        gint16;
typedef uint16_t       guint16;
typedef int32_t        gint32;
typedef uint32_t       guint32;
typedef int64_t        gint64;
typedef uint64_t       guint64;
typedef float          gfloat;
typedef double         gdouble;
typedef int32_t        gboolean;
typedef void *         gpointer;
typedef enum {
        ppc_r0 = 0,
        ppc_r1,
        ppc_sp = ppc_r1,
        ppc_r2,
        ppc_r3,
        ppc_r4,
        ppc_r5,
        ppc_r6,
        ppc_r7,
        ppc_r8,
        ppc_r9,
        ppc_r10,
        ppc_r11,
        ppc_r12,
        ppc_r13,
        ppc_r14,
        ppc_r15,
        ppc_r16,
        ppc_r17,
        ppc_r18,
        ppc_r19,
        ppc_r20,
        ppc_r21,
        ppc_r22,
        ppc_r23,
        ppc_r24,
        ppc_r25,
        ppc_r26,
        ppc_r27,
        ppc_r28,
        ppc_r29,
        ppc_r30,
        ppc_r31
} PPCIntRegister;
typedef enum {
        ppc_lr = 256,
        ppc_ctr = 256 + 32,
        ppc_xer = 32
} PPCSpecialRegister;
#define G_STMT_START    do
#define G_STMT_END      while (0)
#define ppc_load32(c,D,v) G_STMT_START {        \
                ppc_lis ((c), (D),      (guint32)(v) >> 16);    \
                ppc_ori ((c), (D), (D), (guint32)(v) & 0xffff); \
        } G_STMT_END
#define ppc_emit32(c,x) do { *((guint32 *) (c)) = (guint32) (x); (c) = (gpointer)((guint8 *)(c) + sizeof (    guint32));} while (0)
#define ppc_stwux(c,S,A,B) ppc_emit32(c, (31 << 26) | (S << 21) | (A << 16) | (B << 11) | (183 << 1) | 0)
#define    ppc_or(c,a,s,b) ppc_emit32 (c, (31 << 26) | ((s) << 21) | ((a) << 16) | ((b) << 11) | 888)
#define    ppc_mr(c,a,s)   ppc_or     (c, a, s, s)
#define   ppc_ori(c,S,A,ui) ppc_emit32 (c, (24 << 26) | ((S) << 21) | ((A) << 16) | (guint16)(ui))
#define ppc_addis(c,D,A,i) ppc_emit32 (c, (15 << 26) | ((D) << 21) | ((A) << 16) | (guint16)(i))
#define   ppc_lis(c,D,v)   ppc_addis  (c, D, 0, (guint16)(v))
#define ppc_load_sequence(c,D,v) ppc_load32 ((c), (D), (guint32)(v))
#define ppc_load_func(c,D,V)          ppc_load_sequence ((c), (D), (V))
#define ppc_mtspr(c,spr,S) ppc_emit32 (c, (31 << 26) | ((S) << 21) | ((spr) << 11) | (467 << 1))
#define  ppc_mtlr(c,S)     ppc_mtspr  (c, ppc_lr, S)
#define  ppc_blrl(c)       ppc_emit32 (c, 0x4e800021)
#define ppc_mfspr(c,D,spr) ppc_emit32 (c, (31 << 26) | ((D) << 21) | ((spr) << 11) | (339 << 1))
#define  ppc_mflr(c,D)     ppc_mfspr  (c, D, ppc_lr)
#define   ppc_stw(c,S,d,A) ppc_emit32 (c, (36 << 26) | ((S) << 21) | ((A) << 16) | (guint16)(d))
#define  ppc_stwu(c,s,d,A) ppc_emit32 (c, (37 << 26) | ((s) << 21) | ((A) << 16) | (guint16)(d))
#define  ppc_addi(c,D,A,i) ppc_emit32 (c, (14 << 26) | ((D) << 21) | ((A) << 16) | (guint16)(i))
#define   ppc_lwz(c,D,d,A) ppc_emit32 (c, (32 << 26) | ((D) << 21) | ((A) << 16) | (guint16)(d))
#define   ppc_blr(c)       ppc_emit32 (c, 0x4e800020)
#define  ppc_bl(c,li)       ppc_emit32 (c, (18 << 26) | ((li) << 2) | 1)
#define PPC_CALL_REG ppc_r12

void foo()
{
  puts("Hello");
}

int main()
{
  unsigned char codebuf [1024];
  unsigned char* code;
  void * mem;
  unsigned char* codest;
  void *values[1];
  int rc;

  foo();
  code = codest = codebuf;
  ppc_load_func(code, PPC_CALL_REG, *((void **)foo));
  ppc_mtlr(code, PPC_CALL_REG);
  ppc_blrl(code);

  mem = mmap(NULL, code - codest, PROT_WRITE | PROT_EXEC,
    MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  memcpy(mem, codest, code - codest);
  void (*func) () = &mem;
  func();

  return 0;
}
</code>```

I must use gcc. the macros were copied from Mono. func() is good when not call system library functions.
It could step into func(), but when invokes puts, the register R2 value somehow was manipulated. I don't know why? following is debug step on my test box :

```<code>127       func();
=> 0x10000760 <main+304>:       80 1f 00 40     lwz     r0,64(r31)
   0x10000764 <main+308>:       7c 0b 03 78     mr      r11,r0
   0x10000768 <main+312>:       81 2b 00 00     lwz     r9,0(r11)
   0x1000076c <main+316>:       90 41 00 14     stw     r2,20(r1)
   0x10000770 <main+320>:       7c 0a 03 78     mr      r10,r0
   0x10000774 <main+324>:       81 6a 00 08     lwz     r11,8(r10)
   0x10000778 <main+328>:       7d 29 03 a6     mtctr   r9
   0x1000077c <main+332>:       7c 0a 03 78     mr      r10,r0
   0x10000780 <main+336>:       80 4a 00 04     lwz     r2,4(r10)
   0x10000784 <main+340>:       4e 80 04 21     bctrl
   0x10000788 <main+344>:       80 41 00 14     lwz     r2,20(r1)
</code>```

above is the point of entering func().
below is the core dump snapshot:

```<code>(gdb)
    0x10000550      90        puts("Hello");
    0x1000054c <foo+20>: 80 62 00 58     lwz     r3,88(r2)
 => 0x10000550 <foo+24>: 48 00 03 41     bl      0x10000890 <puts>
    0x10000554 <foo+28>: 80 41 00 14     lwz     r2,20(r1)
(gdb)
    0x10000890 in puts ()
 => 0x10000890 <puts+0>: 81 82 00 5c     lwz     r12,92(r2)
(gdb)
    0x10000894 in puts ()
 => 0x10000894 <puts+4>: 90 41 00 14     stw     r2,20(r1)
(gdb) info reg r12
    r12            0x0      0
(gdb) ni
    0x10000898 in puts ()
 => 0x10000898 <puts+8>: 80 0c 00 00     lwz     r0,0(r12)
(gdb)
    0x1000089c in puts ()
 => 0x1000089c <puts+12>:        80 4c 00 04     lwz     r2,4(r12)
(gdb)
    0x100008a0 in puts ()
 => 0x100008a0 <puts+16>:        7c 09 03 a6     mtctr   r0
(gdb) info reg r0
    r0             0x0      0
(gdb) ni
    0x100008a4 in puts ()
 => 0x100008a4 <puts+20>:        4e 80 04 20     bctr
(gdb)
Program received signal SIGILL, Illegal instruction.
    0x00000000 in ?? ()
 => 0x00000000:  00 00 00 00     .long 0x0
</code>```

in puts(), it jump to wrong address 0x0, at the begining of func(), compiler has modified R2(lwz     r2,4(r10)), it leads to the problem, but it is compiler generated code, I can't change it. I don't know how to handle this issue. Please help me! Thank you.

答:
You need to understand "glue code" and "glink code".

As a practical method, write just a simple program where main calls puts.  Then look at the assembly produced as well as single step (i.e. stepi) through the code.

The "function pointer" puts() does not point to the executable when it is in another module.  Instead it points to a toc entry that has three entries: the address of the function, the toc of the module, and another value that I can't recall.  The glue code / glink code (IIRC) takes a pointer in r11 to this entry and it will then correctly call the destination function.

Upon return, the next instruction after the bl will be an instruction to restore the toc.

The compiler, ld, as well as the loader all participate in the magic to make this happen.

Happy hunting...

Body:
My purpose is invoke a system call or libc functions from native code.
The native code is a executable memory block which I insert some machine code into it. In the native code I try to invoke puts() or printf() functions to output a string. Then I call the native code. This sequence model is the Mono tries to do. But when I porting the Mono into AIX, I met a segment fault when invokes system library functions such as printf() or abs(). I guess it must break calling stack somewhere. But I could not resolve such problem I am not familiar with IBM powerpc platform.
I have wrote a simple program to demonstrate the sequence, it also lead to segment fault at calling puts(). It takes so much time, please give me some advises, thank you in advance!

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h>

typedef uint8_t        guint8;
typedef int16_t        gint16;
typedef uint16_t       guint16;
typedef int32_t        gint32;
typedef uint32_t       guint32;
typedef int64_t        gint64;
typedef uint64_t       guint64;
typedef float          gfloat;
typedef double         gdouble;
typedef int32_t        gboolean;
typedef void *         gpointer;
typedef enum {
        ppc_r0 = 0,
        ppc_r1,
        ppc_sp = ppc_r1,
        ppc_r2,
        ppc_r3,
        ppc_r4,
        ppc_r5,
        ppc_r6,
        ppc_r7,
        ppc_r8,
        ppc_r9,
        ppc_r10,
        ppc_r11,
        ppc_r12,
        ppc_r13,
        ppc_r14,
        ppc_r15,
        ppc_r16,
        ppc_r17,
        ppc_r18,
        ppc_r19,
        ppc_r20,
        ppc_r21,
        ppc_r22,
        ppc_r23,
        ppc_r24,
        ppc_r25,
        ppc_r26,
        ppc_r27,
        ppc_r28,
        ppc_r29,
        ppc_r30,
        ppc_r31
} PPCIntRegister;
typedef enum {
        ppc_lr = 256,
        ppc_ctr = 256 + 32,
        ppc_xer = 32
} PPCSpecialRegister;
#define G_STMT_START    do
#define G_STMT_END      while (0)
#define ppc_load32(c,D,v) G_STMT_START {        \
                ppc_lis ((c), (D),      (guint32)(v) >> 16);    \
                ppc_ori ((c), (D), (D), (guint32)(v) & 0xffff); \
        } G_STMT_END
#define ppc_emit32(c,x) do { *((guint32 *) (c)) = (guint32) (x); (c) = (gpointer)((guint8 *)(c) + sizeof (    guint32));} while (0)
#define ppc_stwux(c,S,A,B) ppc_emit32(c, (31 << 26) | (S << 21) | (A << 16) | (B << 11) | (183 << 1) | 0)
#define    ppc_or(c,a,s,b) ppc_emit32 (c, (31 << 26) | ((s) << 21) | ((a) << 16) | ((b) << 11) | 888)
#define    ppc_mr(c,a,s)   ppc_or     (c, a, s, s)
#define   ppc_ori(c,S,A,ui) ppc_emit32 (c, (24 << 26) | ((S) << 21) | ((A) << 16) | (guint16)(ui))
#define ppc_addis(c,D,A,i) ppc_emit32 (c, (15 << 26) | ((D) << 21) | ((A) << 16) | (guint16)(i))
#define   ppc_lis(c,D,v)   ppc_addis  (c, D, 0, (guint16)(v))
#define ppc_load_sequence(c,D,v) ppc_load32 ((c), (D), (guint32)(v))
#define ppc_load_func(c,D,V)          ppc_load_sequence ((c), (D), (V))
#define ppc_mtspr(c,spr,S) ppc_emit32 (c, (31 << 26) | ((S) << 21) | ((spr) << 11) | (467 << 1))
#define  ppc_mtlr(c,S)     ppc_mtspr  (c, ppc_lr, S)
#define  ppc_blrl(c)       ppc_emit32 (c, 0x4e800021)
#define ppc_mfspr(c,D,spr) ppc_emit32 (c, (31 << 26) | ((D) << 21) | ((spr) << 11) | (339 << 1))
#define  ppc_mflr(c,D)     ppc_mfspr  (c, D, ppc_lr)
#define   ppc_stw(c,S,d,A) ppc_emit32 (c, (36 << 26) | ((S) << 21) | ((A) << 16) | (guint16)(d))
#define  ppc_stwu(c,s,d,A) ppc_emit32 (c, (37 << 26) | ((s) << 21) | ((A) << 16) | (guint16)(d))
#define  ppc_addi(c,D,A,i) ppc_emit32 (c, (14 << 26) | ((D) << 21) | ((A) << 16) | (guint16)(i))
#define   ppc_lwz(c,D,d,A) ppc_emit32 (c, (32 << 26) | ((D) << 21) | ((A) << 16) | (guint16)(d))
#define   ppc_blr(c)       ppc_emit32 (c, 0x4e800020)
#define  ppc_bl(c,li)       ppc_emit32 (c, (18 << 26) | ((li) << 2) | 1)
#define PPC_CALL_REG ppc_r12

void foo()
{
  puts("Hello");
}

int main()
{
  unsigned char codebuf [1024];
  unsigned char* code;
  void * mem;
  unsigned char* codest;
  void *values[1];
  int rc;

  foo();
  code = codest = codebuf;
  ppc_load_func(code, PPC_CALL_REG, *((void **)foo));
  ppc_mtlr(code, PPC_CALL_REG);
  ppc_blrl(code);

  mem = mmap(NULL, code - codest, PROT_WRITE | PROT_EXEC,
    MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  memcpy(mem, codest, code - codest);
  void (*func) () = &mem;
  func();

  return 0;
}

I must use gcc. the macros were copied from Mono. func() is good when not call system library functions.
It could step into func(), but when invokes puts, the register R2 value somehow was manipulated. I don't know why? following is debug step on my test box :

127       func();
=> 0x10000760 :       80 1f 00 40     lwz     r0,64(r31)
   0x10000764 :       7c 0b 03 78     mr      r11,r0
   0x10000768 :       81 2b 00 00     lwz     r9,0(r11)
   0x1000076c :       90 41 00 14     stw     r2,20(r1)
   0x10000770 :       7c 0a 03 78     mr      r10,r0
   0x10000774 :       81 6a 00 08     lwz     r11,8(r10)
   0x10000778 :       7d 29 03 a6     mtctr   r9
   0x1000077c :       7c 0a 03 78     mr      r10,r0
   0x10000780 :       80 4a 00 04     lwz     r2,4(r10)
   0x10000784 :       4e 80 04 21     bctrl
   0x10000788 :       80 41 00 14     lwz     r2,20(r1)

above is the point of entering func().
below is the core dump snapshot:

(gdb)
    0x10000550      90        puts("Hello");
    0x1000054c <foo+20>: 80 62 00 58     lwz     r3,88(r2)
 => 0x10000550 <foo+24>: 48 00 03 41     bl      0x10000890 <puts>
    0x10000554 <foo+28>: 80 41 00 14     lwz     r2,20(r1)
(gdb)
    0x10000890 in puts ()
 => 0x10000890 <puts+0>: 81 82 00 5c     lwz     r12,92(r2)
(gdb)
    0x10000894 in puts ()
 => 0x10000894 <puts+4>: 90 41 00 14     stw     r2,20(r1)
(gdb) info reg r12
    r12            0x0      0
(gdb) ni
    0x10000898 in puts ()
 => 0x10000898 <puts+8>: 80 0c 00 00     lwz     r0,0(r12)
(gdb)
    0x1000089c in puts ()
 => 0x1000089c <puts+12>:        80 4c 00 04     lwz     r2,4(r12)
(gdb)
    0x100008a0 in puts ()
 => 0x100008a0 <puts+16>:        7c 09 03 a6     mtctr   r0
(gdb) info reg r0
    r0             0x0      0
(gdb) ni
    0x100008a4 in puts ()
 => 0x100008a4 <puts+20>:        4e 80 04 20     bctr
(gdb)
Program received signal SIGILL, Illegal instruction.
    0x00000000 in ?? ()
 => 0x00000000:  00 00 00 00     .long 0x0

in puts(), it jump to wrong address 0x0, at the begining of func(), compiler has modified R2(lwz     r2,4(r10)), it leads to the problem, but it is compiler generated code, I can't change it. I don't know how to handle this issue. Please help me! Thank you.


问:
Closure Compiler warning with Google Analytics and Facebook Pixel
I have a function that looks like this:

```<code>function StartThirdPartyScripts() {

    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'UA-XXXXXXXXX-1', 'auto');
    ga('send', 'pageview');

    !function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');

    fbq('init', 'XXXXXXXXXXXXXXXXXXXX');
    fbq('track', 'PageView');
}
</code>```

The problem is that when I run this in Closure Compiler advanced mode, I got 3 warnings because the number of parameters don't match. Here are the warnings:

```<code>        WARNING - Function function: called with 5 argument(s).
        Function requires at least 7 argument(s) and no more than 7 argument(s).
        (function (i, s, o, g, r, a, m) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     ClosureCompiler/initialjxaz.js:512: WARNING - Suspicious code. The result of
        the 'not' operator is not being used. !function (f, b, e, v, n, t, s) {
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ClosureCompiler/initialjxaz.js:512:
        WARNING - Function function: called with 4 argument(s). Function requires at
least 7 argument(s) and no more than 7 argument(s).
        !function (f, b, e, v, n, t, s) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        ^^^^ 0 error(s), 3 warning(s)
</code>```

What can I do to fix it?

答:
You can safely ignore those warnings. The code has extra function arguments which are not used so Closure-compiler is warning. If the arguments were marked as optional or had default values, then the compiler would not warn.

I also have no idea why they are using the ! operator in front of that function. It looks like they are using it to protect against concatenated files not have a semi-colon - but I would have just expected them to use ; for that.

Body:
I have a function that looks like this:

function StartThirdPartyScripts() {

    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'UA-XXXXXXXXX-1', 'auto');
    ga('send', 'pageview');

    !function (f, b, e, v, n, t, s) {
        if (f.fbq) return; n = f.fbq = function () {
            n.callMethod ?
            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
        }; if (!f._fbq) f._fbq = n;
        n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
        t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
    }(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');

    fbq('init', 'XXXXXXXXXXXXXXXXXXXX');
    fbq('track', 'PageView');
}

The problem is that when I run this in Closure Compiler advanced mode, I got 3 warnings because the number of parameters don't match. Here are the warnings:

        WARNING - Function function: called with 5 argument(s).
        Function requires at least 7 argument(s) and no more than 7 argument(s).
        (function (i, s, o, g, r, a, m) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     ClosureCompiler/initialjxaz.js:512: WARNING - Suspicious code. The result of
        the 'not' operator is not being used. !function (f, b, e, v, n, t, s) {
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ClosureCompiler/initialjxaz.js:512:
        WARNING - Function function: called with 4 argument(s). Function requires at
least 7 argument(s) and no more than 7 argument(s).
        !function (f, b, e, v, n, t, s) { ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        ^^^^ 0 error(s), 3 warning(s)

What can I do to fix it?


问:
How do I keep a CSS container the same size?
I have 6 images next to each other in two rows. I used a CSS container to center it (couldn't use padding). However, when I shrink the screen, since the margin is set to auto, the container shrinks opposed to the blank space around the container. You can see this here . The blue is just there to show the container. The images need to stay in that order until it becomes physically impossible for them to stay there. Any help would be appreciated! Thank you in advanced!</p>

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Featured Industries</title>
</head>
<style>
.center {
    margin: auto;
    width: 66%;
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}
.img {
    float: left;
}
a:hover img {
    position: relative;
    z-index: 1;
    transition: -webkit-box-shadow 0.3s ease-in-out;
    -webkit-box-shadow: 0px 3px 31px -6px rgba(0,0,0,0.75);
    -moz-box-shadow: 0px 3px 31px -6px rgba(0,0,0,0.75);
    box-shadow: 0px 3px 31px -6px rgba(0,0,0,0.75);
}
</style>
</code>```

答:
Use this class:

```<code>.center {
    margin: auto;
    width: 933px;
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}
</code>```

If you set the width to the 66% it will depend on the father width, bit if you just set it to a number of px it will remain the same size

Body:
I have 6 images next to each other in two rows. I used a CSS container to center it (couldn't use padding). However, when I shrink the screen, since the margin is set to auto, the container shrinks opposed to the blank space around the container. You can see this here . The blue is just there to show the container. The images need to stay in that order until it becomes physically impossible for them to stay there. Any help would be appreciated! Thank you in advanced!

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Featured Industries</title>

Body:
Use this class:

.center {
    margin: auto;
    width: 933px;
    height: 625px;
    border: 3px solid #0026E3;
    padding: 0px;
}

If you set the width to the 66% it will depend on the father width, bit if you just set it to a number of px it will remain the same size


问:
Randomizing numbers in C and storing them in an integer array
I am trying to write a code which randomizes numbers between 1 and 14 (symbolizing one suit of a deck of cards). The code should store the values in an array with a limit of 52. Each number can only be stored 4 times (as there are 4 suits in a deck of cards). So, in the end, I should be displaying two randomized decks for person_a and person_b.

My problem is that the randomized decks for person_a and person_b are the same. I have no idea why. I tried seeding using srand(), and using rand() for the random number. Can someone help?

Also, I know my code is really messy and terrible. I'm sorry - this is my first time taking a C course. Below is the code:

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

#define MAX_DECK 52
#define REPETITIONS 4
#define CARDS_HIGH 14
#define CARDS_LOW 1

int
randomize_check(int value_check, int limit, int cards[])
{
    int count = 0;
    int i = 0;
    for(i=0; i<limit; i++)
    {
        if(cards[i]==value_check)
        {
            count++;
        }
    }
    if(count>REPETITIONS)
    {
        return -1;
    }
    else if (count<=REPETITIONS)
    {
        return 1;
    }
}

int
get_random(void)
{
    int random_number = 0;
    random_number = (rand()%(CARDS_HIGH-CARDS_LOW))+CARDS_LOW;

    return(random_number);
}

int * randomize_deck(void)
{

    static int cards[MAX_DECK];
    int i = 0;
    int randomize = 0;
    int check = 0;

    for (i=0; i<MAX_DECK; i++)
    {
        randomize = get_random();
        cards[i] = randomize;
        check = randomize_check(cards[i], MAX_DECK, cards);
        while((check) == -1)
        {
            randomize = get_random();
            cards[i] = randomize;
            check = randomize_check(cards[i], MAX_DECK, cards);
        }

    }
    return(cards);
}

int
main(void)
{
    srand ( time(NULL) );
    int i = 0, j = 0;

    int *person_a = randomize_deck();
    int *person_b = randomize_deck();

    for (i = 0; i < MAX_DECK; i++) //print_a
    {
        printf( "Cards[a%d]: %d\n", i, *(person_a + i));
    }

    printf("\n");

    for (j = 0; j < MAX_DECK; j++) //print_b
    {
        printf( "Cards[b%d]: %d\n", j, *(person_b + j));
    }

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

答:
Your problem stems from the fact that cards is declared as a static array in the randomize_deck() function. So, the first call to randomize_deck() fills this array with random cards, returning a pointer to cards. Then the second call to randomize_deck() fills the same static array with new random cards, and returns a pointer to the same static array. After all of this, both person_a and person_b point to the same static array.

One solution is to change the randomize_deck() function to accept an array argument, with a return type of void. Also, it would be best to pass the size of the array to randomize_deck(), instead of relying on a global constant. And note that in the code below I have changed the array index variables to type size_t, which is an unsigned integer type guaranteed to hold any array index, and the correct type for array indices.

```<code>void randomize_deck(int cards[], size_t deck_sz)
{

    size_t i = 0;
    int randomize = 0;
    int check = 0;

    for (i = 0; i < deck_sz; i++)
    {
        randomize = get_random();
        cards[i] = randomize;
        check = randomize_check(cards[i], deck_sz, cards);
        while((check) == -1)
        {
            randomize = get_random();
            cards[i] = randomize;
            check = randomize_check(cards[i], deck_sz, cards);
        }

    }
}
</code>```

Then in main(), you declare two int arrays, one for each player, and pass these to the randomize_deck() function:

```<code>int main(void)
{
    srand ( time(NULL) );
    size_t i = 0, j = 0;

    int person_a[MAX_DECK];
    int person_b[MAX_DECK];

    randomize_deck(person_a, MAX_DECK);
    randomize_deck(person_b, MAX_DECK);

    /* ... */

    return 0;
}
</code>```

Body:
I am trying to write a code which randomizes numbers between 1 and 14 (symbolizing one suit of a deck of cards). The code should store the values in an array with a limit of 52. Each number can only be stored 4 times (as there are 4 suits in a deck of cards). So, in the end, I should be displaying two randomized decks for person_a and person_b.

My problem is that the randomized decks for person_a and person_b are the same. I have no idea why. I tried seeding using srand(), and using rand() for the random number. Can someone help?

Also, I know my code is really messy and terrible. I'm sorry - this is my first time taking a C course. Below is the code:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define MAX_DECK 52
#define REPETITIONS 4
#define CARDS_HIGH 14
#define CARDS_LOW 1

int
randomize_check(int value_check, int limit, int cards[])
{
    int count = 0;
    int i = 0;
    for(i=0; i<limit; i++)
    {
        if(cards[i]==value_check)
        {
            count++;
        }
    }
    if(count>REPETITIONS)
    {
        return -1;
    }
    else if (count<=REPETITIONS)
    {
        return 1;
    }
}

int
get_random(void)
{
    int random_number = 0;
    random_number = (rand()%(CARDS_HIGH-CARDS_LOW))+CARDS_LOW;

    return(random_number);
}

int * randomize_deck(void)
{

    static int cards[MAX_DECK];
    int i = 0;
    int randomize = 0;
    int check = 0;

    for (i=0; i<MAX_DECK; i++)
    {
        randomize = get_random();
        cards[i] = randomize;
        check = randomize_check(cards[i], MAX_DECK, cards);
        while((check) == -1)
        {
            randomize = get_random();
            cards[i] = randomize;
            check = randomize_check(cards[i], MAX_DECK, cards);
        }

    }
    return(cards);
}

int
main(void)
{
    srand ( time(NULL) );
    int i = 0, j = 0;

    int *person_a = randomize_deck();
    int *person_b = randomize_deck();

    for (i = 0; i < MAX_DECK; i++) //print_a
    {
        printf( "Cards[a%d]: %d\n", i, *(person_a + i));
    }

    printf("\n");

    for (j = 0; j < MAX_DECK; j++) //print_b
    {
        printf( "Cards[b%d]: %d\n", j, *(person_b + j));
    }

    return(0);
}

Body:
Your problem stems from the fact that cards is declared as a static array in the randomize_deck() function. So, the first call to randomize_deck() fills this array with random cards, returning a pointer to cards. Then the second call to randomize_deck() fills the same static array with new random cards, and returns a pointer to the same static array. After all of this, both person_a and person_b point to the same static array.

One solution is to change the randomize_deck() function to accept an array argument, with a return type of void. Also, it would be best to pass the size of the array to randomize_deck(), instead of relying on a global constant. And note that in the code below I have changed the array index variables to type size_t, which is an unsigned integer type guaranteed to hold any array index, and the correct type for array indices.

void randomize_deck(int cards[], size_t deck_sz)
{

    size_t i = 0;
    int randomize = 0;
    int check = 0;

    for (i = 0; i < deck_sz; i++)
    {
        randomize = get_random();
        cards[i] = randomize;
        check = randomize_check(cards[i], deck_sz, cards);
        while((check) == -1)
        {
            randomize = get_random();
            cards[i] = randomize;
            check = randomize_check(cards[i], deck_sz, cards);
        }

    }
}

Then in main(), you declare two int arrays, one for each player, and pass these to the randomize_deck() function:

int main(void)
{
    srand ( time(NULL) );
    size_t i = 0, j = 0;

    int person_a[MAX_DECK];
    int person_b[MAX_DECK];

    randomize_deck(person_a, MAX_DECK);
    randomize_deck(person_b, MAX_DECK);

    /* ... */

    return 0;
}


问:
Rails method to return current "controller#action"?
Instead of checking if controller_name == 'foo' && action_name == 'bar', is there a Rails method to return the two in the same format that you'd define them in the routes.rb file (get '/buzz' => 'foo#bar')?

Is there something like get_current_route() that'll return "foo#bar"?

答:
You can get names of your current controller and action by using controller_name and action_name methods. So you can concatenate strings to get desired result.

Also you can get these values from params hash its considered as a bad practise to do so.

The params hash will always contain the :controller and :action keys,
  but you should use the methods controller_name and action_name instead
  to access these values

ActionController Parameters

Reference links:

Rails - controller action name to string

Can I get the name of the current controller in the view?


问:
Javascript hide items from dropdown
I have a dropdown list with 24 items, the user can check a radio button and this will set it to only show 12. If they de-select it, the dropdown will show the 24 items as before.

I have it working to only show 12 items using

```<code>document.getElementById('theMenu').length = 12;
</code>```

But then when I try to set it back to 24, the other 12 items are empty.

Am thinking I may need to store the values in a temp array of some sort, then just load these back into the dropdown menu? (Javascript only)

Thanks:)

答:
Why not use jQuery to make it simpler?

You can store the values in an Array

```<code>var values = {1:one,2:two,3:three};
</code>```

and then based on the checkbox value populate them

```<code>$.each(values , function(key,value) {
  alert(value);
       $('#drop').
          append($("<option></option>").
          attr("value",key).
          text(key));

});
</code>```

What is the best way to add options to a select from an array with jQuery?

Title: Javascript hide items from dropdown

Body:
I have a dropdown list with 24 items, the user can check a radio button and this will set it to only show 12. If they de-select it, the dropdown will show the 24 items as before.

I have it working to only show 12 items using

document.getElementById('theMenu').length = 12;

But then when I try to set it back to 24, the other 12 items are empty.

Am thinking I may need to store the values in a temp array of some sort, then just load these back into the dropdown menu? (Javascript only)

Thanks:)

Body:
Why not use jQuery to make it simpler?

You can store the values in an Array

var values = {1:one,2:two,3:three};

and then based on the checkbox value populate them

$.each(values , function(key,value) {
  alert(value);
       $('#drop').
          append($("<option></option>").
          attr("value",key).
          text(key));

});

What is the best way to add options to a select from an array with jQuery?


问:
UIImagePickerController takePicture Dismisses Controller
I have a custom UIImagePickerController that works nicely, only I am facing one issue that I feel should be fairly simple - I just have yet to figure out the solution.

Upon touching my custom added "photo" button, I have it targeted to the build in takePicture method of the UIIPC. Here is my code

```<code>@interface CustomCameraController ()

@end

@implementation CustomCameraController {
    CGFloat width, height;
}

- (instancetype)init {

    if (self = [super init]) {

        width = self.view.frame.size.width, height = self.view.frame.size.height;
        self.allowsEditing = YES;
        self.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.showsCameraControls = NO;
        self.toolbarHidden = YES;

        [self buildCameraOverlay];

    }
    return self;
}

- (void)buildCameraOverlay {

    UIView *customOverlay = [UIView alloc] ...
    // ... Custom overlay setup done here

    _takePhoto = [[CustomButton alloc] initWithFrame:CGRectMake(0, 0, heightBottomBar*.5, heightBottomBar*.5)];
    _takePhoto.center = CGPointMake(bottomBar.frame.size.width/2, bottomBar.frame.size.height/2);
    [_takePhoto setImage:[UIImage imageNamed:@"camera button icon"] forState:UIControlStateNormal];
    [_takePhoto addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:_takePhoto];

    // ...

    self.cameraOverlayView = customOverlay;
}
</code>```

This is done in my custom controller CustomCameraController init call.

The problem is, upon taking the picture via takePicture, the camera shutter goes off, everything works just fine, but the controller dismisses itself. I'm trying to figure out how to stop it from closing immediately after taking the picture, so  I can A)present the taken picture, and B) give the user the option to choose the image or cancel and retake another one (returning to the camera)

If anyone knows why this happens or something that I am missing / doing incorrectly please let me know. I'm sure it's a simple answer - just can't seem to figure it out. Thanks!

答: The most common reason for such a weird behaviour is usually lack of delegate methods (for UIImagePickerController in this case) or their wrong implementation.

Body:
I have a custom UIImagePickerController that works nicely, only I am facing one issue that I feel should be fairly simple - I just have yet to figure out the solution.

Upon touching my custom added "photo" button, I have it targeted to the build in takePicture method of the UIIPC. Here is my code

@interface CustomCameraController ()

@end

@implementation CustomCameraController {
    CGFloat width, height;
}

- (instancetype)init {

    if (self = [super init]) {

        width = self.view.frame.size.width, height = self.view.frame.size.height;
        self.allowsEditing = YES;
        self.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.showsCameraControls = NO;
        self.toolbarHidden = YES;

        [self buildCameraOverlay];

    }
    return self;
}

- (void)buildCameraOverlay {

    UIView *customOverlay = [UIView alloc] ...
    // ... Custom overlay setup done here

    _takePhoto = [[CustomButton alloc] initWithFrame:CGRectMake(0, 0, heightBottomBar*.5, heightBottomBar*.5)];
    _takePhoto.center = CGPointMake(bottomBar.frame.size.width/2, bottomBar.frame.size.height/2);
    [_takePhoto setImage:[UIImage imageNamed:@"camera button icon"] forState:UIControlStateNormal];
    [_takePhoto addTarget:self action:@selector(takePicture) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:_takePhoto];

    // ...

    self.cameraOverlayView = customOverlay;
}

This is done in my custom controller CustomCameraController init call.

The problem is, upon taking the picture via takePicture, the camera shutter goes off, everything works just fine, but the controller dismisses itself. I'm trying to figure out how to stop it from closing immediately after taking the picture, so  I can A)present the taken picture, and B) give the user the option to choose the image or cancel and retake another one (returning to the camera)

If anyone knows why this happens or something that I am missing / doing incorrectly please let me know. I'm sure it's a simple answer - just can't seem to figure it out. Thanks!