问:
XML parser Unsuccessful
D2L_XML4 parser is unsuccessfully trying to update a user with
the following XML. Assuming the  value is correct,it keeps failing. Can anybody explain this please...</p>

```<code><?xml version='1.0'?>
<enterprise>
<person recstatus="1">
<sourcedid>
<id>D2L0001</id>
</sourcedid>

<userid password="MyPassword">Johnny.Test</userid>
<name>

<n>
<family>Test, Jr.</family>
<given>Johnny</given>
</n>

</name>
<email>Johnny.Test@d2l.ca</email>
<extension>

<role roletype="Sample Role">
<status>1<status>
</role>
</extension>
</person>
</enterprise>
</code>```

答:
The problem is here:</p>

```<code><status>1<status>
          ^
          |
      Missing /
</code>```

Title: XML parser Unsuccessful

Body:
D2L_XML4 parser is unsuccessfully trying to update a user with
the following XML. Assuming the  value is correct,it keeps failing. Can anybody explain this please...

<?xml version='1.0'?>
<enterprise>
<person recstatus="1">
<sourcedid>
<id>D2L0001</id>
</sourcedid>

<userid password="MyPassword">Johnny.Test</userid>
<name>

<n>
<family>Test, Jr.</family>
<given>Johnny</given>
</n>

</name>
<email>Johnny.Test@d2l.ca</email>
<extension>

<role roletype="Sample Role">
<status>1<status>
</role>
</extension>
</person>
</enterprise>

Body:
The problem is here:

<status>1<status>
          ^
          |
      Missing /


来源: stackexchange

问:
Transforming a nested data frame with varying number of elements
I have a data frame with a column of nested data frames with 1 or 2 columns and n rows. It looks like df in the sample below:

```<code>'data.frame':   3 obs. of  2 variables:
 $ vector:List of 3
  ..$ : chr "p1"
  ..$ : chr "p2"
  ..$ : chr "p3"
 $ lists :List of 3
  ..$ :'data.frame':    2 obs. of  2 variables:
  .. ..$ n1: Factor w/ 2 levels "a","b": 1 2
  .. ..$ n2: Factor w/ 2 levels "1","2": 1 2
  ..$ :'data.frame':    1 obs. of  1 variable:
  .. ..$ n1: Factor w/ 1 level "d": 1
  ..$ :'data.frame':    1 obs. of  2 variables:
  .. ..$ n1: Factor w/ 1 level "e": 1
  .. ..$ n2: Factor w/ 1 level "3": 1
</code>```

df can be recreated like this :

```<code>v <- c("p1", "p2", "p3")
l <- list(data.frame(n1 = c("a", "b"), n2 = c("1", "2")), data.frame(n1 = "d"), data.frame(n1 = "e", n2 = "3"))
df <- as.data.frame(cbind(v, l))
</code>```

I'd like to transform it to a data frame that looks like that:

```<code>[v] [n1] [n2]

p1  a  1

p1  b  2

p2  d  NA

p3  e  3
</code>```

n1 and n2 are in seperate columns

if the data frame in row i has n rows, the vector element of row i should be repeated n times

if there is no content in n1 or n2, there should be a NA

I've tried using tidyr::unnest but got the following error

```<code> unnest(df)
Error: All nested columns must have the same number of elements.
</code>```

Does anyone has a better idea how to transform the dataframe in the desired format?

答:
This will avoid by-row operations, which will be important if you have a lot of rows.</p>

```<code>library(data.table)

rbindlist(df$l, fill = T, id = 'row')[, v := df$v[row]][]
#   row n1 n2  v
#1:   1  a  1 p1
#2:   1  b  2 p1
#3:   2  d NA p2
#4:   3  e  3 p3
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame with a column of nested data frames with 1 or 2 columns and n rows. It looks like df in the sample below:

'data.frame':   3 obs. of  2 variables:
 $ vector:List of 3
  ..$ : chr "p1"
  ..$ : chr "p2"
  ..$ : chr "p3"
 $ lists :List of 3
  ..$ :'data.frame':    2 obs. of  2 variables:
  .. ..$ n1: Factor w/ 2 levels "a","b": 1 2
  .. ..$ n2: Factor w/ 2 levels "1","2": 1 2
  ..$ :'data.frame':    1 obs. of  1 variable:
  .. ..$ n1: Factor w/ 1 level "d": 1
  ..$ :'data.frame':    1 obs. of  2 variables:
  .. ..$ n1: Factor w/ 1 level "e": 1
  .. ..$ n2: Factor w/ 1 level "3": 1

df can be recreated like this :

v <- c("p1", "p2", "p3")
l <- list(data.frame(n1 = c("a", "b"), n2 = c("1", "2")), data.frame(n1 = "d"), data.frame(n1 = "e", n2 = "3"))
df <- as.data.frame(cbind(v, l))

I'd like to transform it to a data frame that looks like that:

[v] [n1] [n2]

p1  a  1

p1  b  2

p2  d  NA

p3  e  3

n1 and n2 are in seperate columns

if the data frame in row i has n rows, the vector element of row i should be repeated n times

if there is no content in n1 or n2, there should be a NA

I've tried using tidyr::unnest but got the following error

 unnest(df)
Error: All nested columns must have the same number of elements.

Does anyone has a better idea how to transform the dataframe in the desired format?

Body:
This will avoid by-row operations, which will be important if you have a lot of rows.

library(data.table)

rbindlist(df$l, fill = T, id = 'row')[, v := df$v[row]][]
#   row n1 n2  v
#1:   1  a  1 p1
#2:   1  b  2 p1
#3:   2  d NA p2
#4:   3  e  3 p3


问:
MySQL sum and grouping extra row
If I run the following MySQL query:

```<code>SELECT username, sum(value) as value
FROM ztemp
GROUP BY username
</code>```

I get results with each username and the sum value. However, if do the following query:

```<code>SELECT username, sum(value) as value
FROM ztemp
</code>```

Then it gives me the overal sum instead of user by user.

Rather than running two SQL queries to display the result. Is there a way to get both in one SQL query? Or is it better to run the two queries?

答:
Yes, there's a way to do this ... using the ROLLUP modifier.

```<code>GROUP BY username WITH ROLLUP
</code>```

gives the extra row.

Nice, huh?

Title: MySQL sum and grouping extra row

Body:
If I run the following MySQL query:

SELECT username, sum(value) as value
FROM ztemp
GROUP BY username

I get results with each username and the sum value. However, if do the following query:

SELECT username, sum(value) as value
FROM ztemp

Then it gives me the overal sum instead of user by user.

Rather than running two SQL queries to display the result. Is there a way to get both in one SQL query? Or is it better to run the two queries?

Body:
Yes, there's a way to do this ... using the ROLLUP modifier.

GROUP BY username WITH ROLLUP

gives the extra row.

Nice, huh?


问:
ms access sql - if y = a, update field to x , elseif elseif
I am trying to populate a field in MS Access. The string I'd like to populate the field with depends on the string in another column. Is there a way to update the same field with different values depending on the value of another field?

I tried selecting the field to be populated multiple times in Query Designer, but it returns a message saying the output field was duplicated.

i.e.

```<code>Col1 Populated
x       1
x       1
y       2
j       10
y       2
j       10
x       1
</code>```

答:
This may help as a start: </p>

```<code>DECLARE @Temp TABLE (
Col1 NVARCHAR(1)
,Populated  INT
)

INSERT INTO @Temp
VALUES
 ('x',1)
,('x',1)
,('y',2)
,('j',10)
,('y',2)
,('j',10)
,('x',1)

DECLARE @InputA INT
SET @InputA =  2

DECLARE @Y INT
SELECT @Y = (SELECT Top 1 Populated FROM @Temp WHERE Col1 = 'Y')

DECLARE @x INT
SELECT @x = (SELECT Top 1 Populated FROM @Temp WHERE Col1 = 'x')

SELECT
    Col1
    ,Populated
    ,CASE WHEN Populated = @InputA THEN @X
          ELSE Populated
          END
FROM @Temp
</code>```

Body:
I am trying to populate a field in MS Access. The string I'd like to populate the field with depends on the string in another column. Is there a way to update the same field with different values depending on the value of another field?

I tried selecting the field to be populated multiple times in Query Designer, but it returns a message saying the output field was duplicated.

i.e.

Col1 Populated
x       1
x       1
y       2
j       10
y       2
j       10
x       1

Body:
This may help as a start:

DECLARE @Temp TABLE (
Col1 NVARCHAR(1)
,Populated  INT
)

INSERT INTO @Temp
VALUES
 ('x',1)
,('x',1)
,('y',2)
,('j',10)
,('y',2)
,('j',10)
,('x',1)

DECLARE @InputA INT
SET @InputA =  2

DECLARE @Y INT
SELECT @Y = (SELECT Top 1 Populated FROM @Temp WHERE Col1 = 'Y')

DECLARE @x INT
SELECT @x = (SELECT Top 1 Populated FROM @Temp WHERE Col1 = 'x')

SELECT
    Col1
    ,Populated
    ,CASE WHEN Populated = @InputA THEN @X
          ELSE Populated
          END
FROM @Temp


问:
Azure Logic Apps - Dropbox Connector Filesize Limit
I have a very simple Logic App which lists files in a Dropbox folder, then copies them to an Azure Blob container.  Works great!  However, when a file is larger than 50MB (like 100MB in this example), I get the following error:

```<code>{
  "status": 413,
  "message": "The file contains 100.514 megabytes which exceeds the maximum 50 megabytes.\r\nclientRequestId: <someid>",
  "source": "dropbox-cus.azconn-cus.p.azurewebsites.net"
}
</code>```

That limit does not appear to exist on either Dropbox or Blob Storage.  Is there a way to make that connector limit larger?

答:
The team confirms that 50 MB is the default file size limit for the Dropbox connector and can't be changed at the your end. However, your question is great feedback as a feature, so please provide more details about your use case at the Logic Apps - Connectors User Voice site.

That way, others can vote, which helps the team prioritize. Thanks!

Body:
I have a very simple Logic App which lists files in a Dropbox folder, then copies them to an Azure Blob container.  Works great!  However, when a file is larger than 50MB (like 100MB in this example), I get the following error:

{
  "status": 413,
  "message": "The file contains 100.514 megabytes which exceeds the maximum 50 megabytes.\r\nclientRequestId: <someid>",
  "source": "dropbox-cus.azconn-cus.p.azurewebsites.net"
}

That limit does not appear to exist on either Dropbox or Blob Storage.  Is there a way to make that connector limit larger?


问:
Disable Touch Gestures in Android Browser via JavaScript
Does anyone know how to disable touch gestures using JavaScript while running content in the browser on Android?

For example, I want to disable the pinch to zoom gesture via JavaScript.

答:
That can be done with the meta tag, viewport.

```<code><meta name="viewport" content="width=device-width, user-scalable=no" />
</code>```

I'm not sure if it's possible with JavaScript.

ContentLicense: CC BY-SA 2.5

Body:
That can be done with the meta tag, viewport.

<meta name="viewport" content="width=device-width, user-scalable=no" />

I'm not sure if it's possible with JavaScript.


问:
ClassLoader.getResources returning an empty Enumeration on a Weblogic/Spring application
I've an EAR application deployed on Weblogic 12.2 using Spring 4.0.4 and facing a strange behaviour:

Spring can´t find the base package due to Weblogic's classloader which return an empty Enumeration for Spring's code: cl.getResources("my/base/pkg")

It's under a context which injects some @Autowired beans on my MDB. (so, due to it, the beans aren´t injected)

but if I put the below code into a sample MDB into the same application, it works:

```<code>Thread.currentThread().getContextClassLoader().getResources("my/base/pkg");
</code>```

and seems that Spring use the same code to create its cl variable.

Another thing I noticed is: if I configure Spring to have a base package as a concrete one (with classes into it) it works.

What could it be?

答:
I had a similar issue when upgrading an application that ran on java 7 in Weblogic 12.1 using Spring 2.5.6 over to java 8 in Weblogic 12.2 using Spring 4.1.9 (for full java 8 support). Technically, Spring 4.1.9 contains all of the same classes as 2.5.6 (albeit deprecated).

Suddenly, Spring would not load the beans via context files in an external directory on the filesystem that was given on the CLASSPATH. We were using the following in an interceptor that extends SpringBeanAutowiringInterceptor:

```<code>private static final String[] CONTEXT_FILES = {"classpath*:context*.xml"};
</code>```

This stopped working. To get it working again, I had to pass in the parent folder name explicitly (we call it "spring_context") and modify our CLASSPATH to be one folder up.   Like this:

```<code>private static final String[] CONTEXT_FILES = {"classpath*:spring_context/context*.xml"}
</code>```

Something about that change allowed spring to get the list of external context files via the ClassLoader in WLS 12.2.  I assume this is related to a note found in the Spring documentation:

https://docs.spring.io/spring/docs/4.0.0.RELEASE/javadoc-api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html

WARNING: Note that "classpath*:" when combined with Ant-style patterns
  will only work reliably with at least one root directory before the
  pattern starts, unless the actual target files reside in the file
  system. This means that a pattern like "classpath*:*.xml" will not
  retrieve files from the root of jar files but rather only from the
  root of expanded directories. This originates from a limitation in the
  JDK's ClassLoader.getResources() method which only returns file system
  locations for a passed-in empty String (indicating potential roots to
  search).

This seems to say that the issue only applies to loading spring context files from a jar file. But my experience with Weblogic Server 12.2 suggests that it might have the same issue as well when using an expanded directory on the filesystem.

Body:
I've an EAR application deployed on Weblogic 12.2 using Spring 4.0.4 and facing a strange behaviour:

Spring can´t find the base package due to Weblogic's classloader which return an empty Enumeration for Spring's code: cl.getResources("my/base/pkg")

It's under a context which injects some @Autowired beans on my MDB. (so, due to it, the beans aren´t injected)

but if I put the below code into a sample MDB into the same application, it works:

Thread.currentThread().getContextClassLoader().getResources("my/base/pkg");

and seems that Spring use the same code to create its cl variable.

Another thing I noticed is: if I configure Spring to have a base package as a concrete one (with classes into it) it works.

What could it be?

Body:
I had a similar issue when upgrading an application that ran on java 7 in Weblogic 12.1 using Spring 2.5.6 over to java 8 in Weblogic 12.2 using Spring 4.1.9 (for full java 8 support). Technically, Spring 4.1.9 contains all of the same classes as 2.5.6 (albeit deprecated).

Suddenly, Spring would not load the beans via context files in an external directory on the filesystem that was given on the CLASSPATH. We were using the following in an interceptor that extends SpringBeanAutowiringInterceptor:

private static final String[] CONTEXT_FILES = {"classpath*:context*.xml"};

This stopped working. To get it working again, I had to pass in the parent folder name explicitly (we call it "spring_context") and modify our CLASSPATH to be one folder up.   Like this:

private static final String[] CONTEXT_FILES = {"classpath*:spring_context/context*.xml"}

Something about that change allowed spring to get the list of external context files via the ClassLoader in WLS 12.2.  I assume this is related to a note found in the Spring documentation:

https://docs.spring.io/spring/docs/4.0.0.RELEASE/javadoc-api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html

WARNING: Note that "classpath*:" when combined with Ant-style patterns
  will only work reliably with at least one root directory before the
  pattern starts, unless the actual target files reside in the file
  system. This means that a pattern like "classpath*:*.xml" will not
  retrieve files from the root of jar files but rather only from the
  root of expanded directories. This originates from a limitation in the
  JDK's ClassLoader.getResources() method which only returns file system
  locations for a passed-in empty String (indicating potential roots to
  search).

This seems to say that the issue only applies to loading spring context files from a jar file. But my experience with Weblogic Server 12.2 suggests that it might have the same issue as well when using an expanded directory on the filesystem.


问:
How do I specify a Primary Key in an INSERT INTO statement?
I have looked at others but not finding out how to solve this in the framework of the following query. The others on here are vastly more complex. I get the error message below. I am trying to essentially copy the wage column from dbo.something and place it in dbo.sizeclassreportgov.

I do not want to auto increment. In this case, the PK is State which always has a value of 32. How would I specify a PK value of 32 in the framework of the below query?

```<code>Insert into dbo.sizeclassreportgov(wage)
select wage from dbo.something;

Msg 515, Level 16, State 2, Line 617
Cannot insert the value NULL into column 'state', table
'wid27.dbo.sizeclassreportgov'; column does not allow nulls. INSERT fails.
</code>```

答:
```<code>INSERT INTO dbo.sizeclassreportgov(wage)
SELECT 32 FROM dbo.something
</code>```

Note this will insert the value, 32, for each row in dbo.something.

Body:
I have looked at others but not finding out how to solve this in the framework of the following query. The others on here are vastly more complex. I get the error message below. I am trying to essentially copy the wage column from dbo.something and place it in dbo.sizeclassreportgov.

I do not want to auto increment. In this case, the PK is State which always has a value of 32. How would I specify a PK value of 32 in the framework of the below query?

Insert into dbo.sizeclassreportgov(wage)
select wage from dbo.something;

Msg 515, Level 16, State 2, Line 617
Cannot insert the value NULL into column 'state', table
'wid27.dbo.sizeclassreportgov'; column does not allow nulls. INSERT fails.

Body:
INSERT INTO dbo.sizeclassreportgov(wage)
SELECT 32 FROM dbo.something

Note this will insert the value, 32, for each row in dbo.something.


问:
Distinguishing between same exception by where it was called
I have an unavoidable situation that looks like this (simplified):

```<code>FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
  FUNCTION_TO_CALL(args, kargs)

def y(foo, bar=None):
  if foo == bar: # actually not this stupid
    raise TypeError()
  else:
    pass

def z(foo, bar, baz=None):
  pass
</code>```

Horribly ugly, I know. :(

But, at any rate, I need to be able to distinguish between a TypeError being raised in y because *args doesn't have anything in it or having too much in it (thus not having enough arguments or too many)/bad kwargs or because foo == bar.

In the actually setting, there are many more functions that can be called than two, not all of which have the code open to them.

Thanks so much!

答:
You could always make your own exceptions subclassing TypeError, and use them individually.</p>

```<code>class TooManyArgumentsError(TypeError):
    pass
class EqualityError(TypeError):
    pass
</code>```

Body:
I have an unavoidable situation that looks like this (simplified):

FUNCTION_TO_CALL = y # can be either y or z
def x(*args, **kargs):
  FUNCTION_TO_CALL(args, kargs)

def y(foo, bar=None):
  if foo == bar: # actually not this stupid
    raise TypeError()
  else:
    pass

def z(foo, bar, baz=None):
  pass

Horribly ugly, I know. :(

But, at any rate, I need to be able to distinguish between a TypeError being raised in y because *args doesn't have anything in it or having too much in it (thus not having enough arguments or too many)/bad kwargs or because foo == bar.

In the actually setting, there are many more functions that can be called than two, not all of which have the code open to them.

Thanks so much!

Body:
You could always make your own exceptions subclassing TypeError, and use them individually.

class TooManyArgumentsError(TypeError):
    pass
class EqualityError(TypeError):
    pass


问:
Command to get list of files that are edited but not "opened" in perforce
Is there a command in Perforce to get a list of files that have been edited?
It seems the only way to do that is to open them using "p4 open " and do a "p4 diff".
I come from git where the easiest way to do that would be "git status".
Sometimes I don't want to "open" files but I still want to edit them.

Thanks.

答:
p4 diff -se will specifically give you files that are modified (determined via checksum comparison) but not opened for edit.

As tkosinski said you can also use p4 reconcile or p4 status.  Look carefully at the options to these commands; they can do a bunch of different things.  For example:

p4 reconcile will automatically open files for add, edit, delete, or move depending on whether they're new, modified, missing, or moved.

p4 reconcile -e will ONLY handle modified files (opening them for edit)

p4 status or p4 reconcile -n will ONLY report the differences (you can also combine this with the -e flag).

p4 status -A will open the file(s) for the appropriate action, making it basically a synonym for p4 reconcile (much like p4 reconcile -n is basically a synonym for p4 status).


问:
How to Update/Refresh Scrolling Texts in html (as they are scrolling)
I'm working with Django, and I'm trying to create a horizontally scrolling text that is updated every few seconds. The code I got so far is (including some I gathered from other posts):

```<code>index.html

<script>
$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  var my_refresh = setInterval(function() {
    $('#updateBox').load("{% url 'updateBox' %}");
  }, 1000);
});

</script>

....
....

<div id="updateBox">
   {% include "updateBox.html" %}
</div>
</code>```

```<code>updateBox.html

<marquee behavior="scroll" direction="left">
      {{updateText_1}}  ;  {{updateText_2}}  ;  {{updateText_3}}
</marquee>
</code>```

```<code>views.py

def getNewTexts(parms):
    (updateText_1,updateText_2,updateText_3) = someAPIwrapper.(parms)
    return (updateText_1,updateText_2,updateText_3)

def index(request):
    return render(request, 'index.html' )

def updateBox(request):
    (updateText_1,updateText_2,updateText_3) = getNewTexts(parms)
    return render(request, 'updateBox.html',    {'updateText_1': updateText_1, 'updateText_2':updateText_2,'updateText_3':updateText_3})
</code>```

Now these codes so far results in this: The texts get correct values upon loading index page, starts scrolling, but right after it starts scrolling for 1 second (1000ms as specified in the script), the whole division "updateBox" gets refreshed and reloaded, and the texts starts scrolling from the very right-hand-side again. The result is that, only half of {{updateText_1}} ever gets shown.

Ideally, I would want to find a solution to only update the texts {{updateText_1}} ; {{updateText_2}} ; {{updateText_3}} without interupting the flow of the scrolling. Or if there are other elegant ways of achieving similar effects, I would also like to learn about them. Thanks in advance!

答:
with jQuery.load() you replace the complete innerHTML of a DOM element. In your case you replace the existing <marquee> with a new one. But you actually want to replace the innerHTML of the <marquee>.

Put the <marquee> in your index.html

```<code><div id="updateBox">
    <marquee behavior="scroll" direction="left">
        {% include "updateBox.html" %}
    </marquee>
</div>
</code>```

and remove it from your updateBox.html

```<code>{{updateText_1}}  ;  {{updateText_2}}  ;  {{updateText_3}}
</code>```

In your JS, load the ajax result into the marquee $('#updateBox>marquee') instead of the wrapping div:

```<code><script>
$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  var my_refresh = setInterval(function() {
    $('#updateBox>marquee').load("{% url 'updateBox' %}");
  }, 1000);
});
</script>
</code>```

Body:
I'm working with Django, and I'm trying to create a horizontally scrolling text that is updated every few seconds. The code I got so far is (including some I gathered from other posts):

index.html

....
....

   {% include "updateBox.html" %}

updateBox.html

<marquee behavior="scroll" direction="left">
      {{updateText_1}}  ;  {{updateText_2}}  ;  {{updateText_3}}
</marquee>

views.py

def getNewTexts(parms):
    (updateText_1,updateText_2,updateText_3) = someAPIwrapper.(parms)
    return (updateText_1,updateText_2,updateText_3)

def index(request):
    return render(request, 'index.html' )

def updateBox(request):
    (updateText_1,updateText_2,updateText_3) = getNewTexts(parms)
    return render(request, 'updateBox.html',    {'updateText_1': updateText_1, 'updateText_2':updateText_2,'updateText_3':updateText_3})

Now these codes so far results in this: The texts get correct values upon loading index page, starts scrolling, but right after it starts scrolling for 1 second (1000ms as specified in the script), the whole division "updateBox" gets refreshed and reloaded, and the texts starts scrolling from the very right-hand-side again. The result is that, only half of {{updateText_1}} ever gets shown.

Ideally, I would want to find a solution to only update the texts {{updateText_1}} ; {{updateText_2}} ; {{updateText_3}} without interupting the flow of the scrolling. Or if there are other elegant ways of achieving similar effects, I would also like to learn about them. Thanks in advance!

Body:
with jQuery.load() you replace the complete innerHTML of a DOM element. In your case you replace the existing <marquee> with a new one. But you actually want to replace the innerHTML of the <marquee>.

Put the <marquee> in your index.html

<div id="updateBox">
    <marquee behavior="scroll" direction="left">
        {% include "updateBox.html" %}
    </marquee>
</div>

and remove it from your updateBox.html

{{updateText_1}}  ;  {{updateText_2}}  ;  {{updateText_3}}

In your JS, load the ajax result into the marquee $('#updateBox>marquee') instead of the wrapping div:

<script>
$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  var my_refresh = setInterval(function() {
    $('#updateBox>marquee').load("{% url 'updateBox' %}");
  }, 1000);
});
</script>


问:
Strange CSP error in Firefox
I recently added the following CSP policies for https://stefan.sofa-rockers.org/

```<code>default-src 'self'; style-src 'self' https://brick.a.ssl.fastly.net; font-src 'self' https://brick.a.ssl.fastly.net
</code>```

It seems to work well on all browser, but Firefox is showing me this strange, truncated error message:

```<code>Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src https://stefan.sofa-rockers.org”). Source: (function (ERROR) {

    const V8_STACK_.... stefan.sofa-rockers.org:1
</code>```

Do I have an error in my CSP (all resources are getting loaded, so I don't think this is the case) or might this be a bug in Firefox itself?

答:
It looks like you may be hitting a known Firefox bug that’s been partially fixed in Firefox 58. See the Improved Content Security Policy (CSP) Handling section of the following blog post:

https://blog.mozilla.org/addons/2017/11/20/extensions-in-firefox-58/

The relevant existing Firefox bugs are these:

https://bugzilla.mozilla.org/show_bug.cgi?id=1406278

https://bugzilla.mozilla.org/show_bug.cgi?id=1267027

And specifically, as noted in the comments here, if you have the Privacy Badger add-on installed, you might need to consider disabling it.

See also the following related Stack Overflow answers:

Firefox content script not loading in some pages

Content Security Policy failing on line 1 (Firefox 57.0)

Title: Strange CSP error in Firefox

Body:
I recently added the following CSP policies for https://stefan.sofa-rockers.org/

default-src 'self'; style-src 'self' https://brick.a.ssl.fastly.net; font-src 'self' https://brick.a.ssl.fastly.net

It seems to work well on all browser, but Firefox is showing me this strange, truncated error message:

Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src https://stefan.sofa-rockers.org”). Source: (function (ERROR) {

    const V8_STACK_.... stefan.sofa-rockers.org:1

Do I have an error in my CSP (all resources are getting loaded, so I don't think this is the case) or might this be a bug in Firefox itself?


答:
Define a custom exception:

class yTypeError(TypeError):
       pass

then raise this in y() and only in y()

Title: Distinguishing between same exception by where it was called


问:
Comparing two strings in C in a loop
I am writing a code to see whether or not the user's input is equivalent to an already stated string. The program loops until the input is the same as the string, using the strcmp function, but for some reason the program does not compare the strings and therefore the loop malfunctions. The code is below:</p>

```<code>int main()
{
    char passcode[3]="ZZZ";
    char input[3];
    int check;
    while(check!=0)
        {
        printf("What is the password?\n");
        gets(input);
        check=strcmp(passcode, input);
        }
    printf("You crack the pass code!");
    return 0;
}
</code>```

答:
The main problem is here:

```<code>char passcode[3]="ZZZ";
char input[3];
</code>```

A string in C consists of a sequence of characters followed by a null byte.  passcode is not large enough to hold the null byte for the string it's initialized with.  So when you try to use it as a string by passing it to strcmp it reads past the end of the array.  Doing so invokes undefined behavior.

Similarly, input isn't big enough to hold a string big enough to compare against.

You're also not initializing check, so the first time you enter the loop it's value is unknown.

Another problem is the use of gets.  This function is dangerous because it does not check if the string the user entered can fit into the given buffer.  If is is too big, this again invokes undefined behavior.

Make your arrays larger to hold the user's input as well as the target string, and use fgets instead of gets.  You should also change the while loop to do..while since you need to enter the loop at least once.

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

int main()
{
    char passcode[]="ZZZ";    // array is automatically sized
    char input[50];
    int check;

    do {
        printf("What is the password?\n");
        fgets(input, sizeof(input), stdin);
        check=strcmp(passcode, input);
    } while (check!=0);
    printf("You crack the pass code!");
    return 0;
}
</code>```

Title: Comparing two strings in C in a loop

Body:
I am writing a code to see whether or not the user's input is equivalent to an already stated string. The program loops until the input is the same as the string, using the strcmp function, but for some reason the program does not compare the strings and therefore the loop malfunctions. The code is below:

int main()
{
    char passcode[3]="ZZZ";
    char input[3];
    int check;
    while(check!=0)
        {
        printf("What is the password?\n");
        gets(input);
        check=strcmp(passcode, input);
        }
    printf("You crack the pass code!");
    return 0;
}

Body:
The main problem is here:

char passcode[3]="ZZZ";
char input[3];

A string in C consists of a sequence of characters followed by a null byte.  passcode is not large enough to hold the null byte for the string it's initialized with.  So when you try to use it as a string by passing it to strcmp it reads past the end of the array.  Doing so invokes undefined behavior.

Similarly, input isn't big enough to hold a string big enough to compare against.

You're also not initializing check, so the first time you enter the loop it's value is unknown.

Another problem is the use of gets.  This function is dangerous because it does not check if the string the user entered can fit into the given buffer.  If is is too big, this again invokes undefined behavior.

Make your arrays larger to hold the user's input as well as the target string, and use fgets instead of gets.  You should also change the while loop to do..while since you need to enter the loop at least once.

#include <stdio.h>

int main()
{
    char passcode[]="ZZZ";    // array is automatically sized
    char input[50];
    int check;

    do {
        printf("What is the password?\n");
        fgets(input, sizeof(input), stdin);
        check=strcmp(passcode, input);
    } while (check!=0);
    printf("You crack the pass code!");
    return 0;
}


问:
SQL - Counting Records By Group
I would like my results to include records only where there is more than Tag Date per Debt Number.

```<code>SELECT DISTINCT
    tag.tag_shrt_nm AS [Tag]
    ,cnsmr.cnsmr_idntfr_agncy_id AS [Borrower Number]
    ,CAST(cnsmr_pymnt_tag.cnsmr_pymnt_tag_assgn_dt AS Date) AS [Tag Date]
    ,cnsmr_accnt_idntfr_agncy_id [Debt Number]
FROM
    cnsmr INNER JOIN
    cnsmr_pymnt_jrnl ON cnsmr.cnsmr_id = cnsmr_pymnt_jrnl.cnsmr_id INNER JOIN
    cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id =  cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id INNER JOIN
    tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id INNER JOIN
    cnsmr_accnt ON cnsmr.cnsmr_id = cnsmr_accnt.cnsmr_id
WHERE
    tag.tag_shrt_nm IN ('tRehab')
ORDER BY
    cnsmr_accnt_idntfr_agncy_id
</code>```

Here there is more than 1 date per debt number so this is my desired output.

```<code>Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-20      1089484
tRehab      1000020234          2012-04-07      1089484
tRehab      1000020234          2012-04-10      1089484
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089487
tRehab      1000020234          2012-04-10      1089487
</code>```

Here there is only 1 debt number per tag date so this not what I'm looking for and should not be in the results.

```<code>Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-19      1089484
tRehab      1000020234          2012-04-07      1089485
tRehab      1000020234          2012-04-10      1089486
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089488
tRehab      1000020234          2012-04-10      1089489
</code>```

答:
You could try this, as it requires only minimal modification to what you already have:

```<code>SELECT *
FROM (SELECT DISTINCT
         tag.tag_shrt_nm AS [Tag]
         ,cnsmr.cnsmr_idntfr_agncy_id AS [Borrower Number]
         ,CAST(cnsmr_pymnt_tag.cnsmr_pymnt_tag_assgn_dt AS Date) AS [Tag Date]
         ,cnsmr_accnt_idntfr_agncy_id [Debt Number]
         ,COUNT(cnsmr_accnt_idntfr_agncy_id) OVER(PARTITION BY cnsmr_accnt_idntfr_agncy_id ORDER BY cnsmr_accnt_idntfr_agncy_id) AS [Debt Number Count]
      FROM
         cnsmr INNER JOIN
         cnsmr_pymnt_jrnl ON cnsmr.cnsmr_id = cnsmr_pymnt_jrnl.cnsmr_id INNER JOIN
         cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id =
         cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id INNER JOIN
         tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id INNER JOIN
         cnsmr_accnt ON cnsmr.cnsmr_id = cnsmr_accnt.cnsmr_id
      WHERE
         tag.tag_shrt_nm IN ('tRehab')
      ORDER BY
         cnsmr_accnt_idntfr_agncy_id) tA
WHERE tA.[Debt Number Count] > 1
</code>```

I guess my only question is, are there situations where the same date will occur more than once for the same debt number? For instance, maybe two different borrower numbers?

Title: SQL - Counting Records By Group

Body:
I would like my results to include records only where there is more than Tag Date per Debt Number.

SELECT DISTINCT
    tag.tag_shrt_nm AS [Tag]
    ,cnsmr.cnsmr_idntfr_agncy_id AS [Borrower Number]
    ,CAST(cnsmr_pymnt_tag.cnsmr_pymnt_tag_assgn_dt AS Date) AS [Tag Date]
    ,cnsmr_accnt_idntfr_agncy_id [Debt Number]
FROM
    cnsmr INNER JOIN
    cnsmr_pymnt_jrnl ON cnsmr.cnsmr_id = cnsmr_pymnt_jrnl.cnsmr_id INNER JOIN
    cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id =  cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id INNER JOIN
    tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id INNER JOIN
    cnsmr_accnt ON cnsmr.cnsmr_id = cnsmr_accnt.cnsmr_id
WHERE
    tag.tag_shrt_nm IN ('tRehab')
ORDER BY
    cnsmr_accnt_idntfr_agncy_id

Here there is more than 1 date per debt number so this is my desired output.

Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-20      1089484
tRehab      1000020234          2012-04-07      1089484
tRehab      1000020234          2012-04-10      1089484
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089487
tRehab      1000020234          2012-04-10      1089487

Here there is only 1 debt number per tag date so this not what I'm looking for and should not be in the results.

Tag         Borrower Number     Tag Date        Debt Number
tRehab      1000020234          2012-02-19      1089484
tRehab      1000020234          2012-04-07      1089485
tRehab      1000020234          2012-04-10      1089486
tRehab      1000020234          2012-02-20      1089487
tRehab      1000020234          2012-04-07      1089488
tRehab      1000020234          2012-04-10      1089489

Body:
You could try this, as it requires only minimal modification to what you already have:

SELECT *
FROM (SELECT DISTINCT
         tag.tag_shrt_nm AS [Tag]
         ,cnsmr.cnsmr_idntfr_agncy_id AS [Borrower Number]
         ,CAST(cnsmr_pymnt_tag.cnsmr_pymnt_tag_assgn_dt AS Date) AS [Tag Date]
         ,cnsmr_accnt_idntfr_agncy_id [Debt Number]
         ,COUNT(cnsmr_accnt_idntfr_agncy_id) OVER(PARTITION BY cnsmr_accnt_idntfr_agncy_id ORDER BY cnsmr_accnt_idntfr_agncy_id) AS [Debt Number Count]
      FROM
         cnsmr INNER JOIN
         cnsmr_pymnt_jrnl ON cnsmr.cnsmr_id = cnsmr_pymnt_jrnl.cnsmr_id INNER JOIN
         cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id =
         cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id INNER JOIN
         tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id INNER JOIN
         cnsmr_accnt ON cnsmr.cnsmr_id = cnsmr_accnt.cnsmr_id
      WHERE
         tag.tag_shrt_nm IN ('tRehab')
      ORDER BY
         cnsmr_accnt_idntfr_agncy_id) tA
WHERE tA.[Debt Number Count] > 1

I guess my only question is, are there situations where the same date will occur more than once for the same debt number? For instance, maybe two different borrower numbers?


问:
CSS-Only Scrollable Table with fixed headers
I have a solution by which I can create scrollable tables w/fixed header/footer using minor jQuery and CSS - but I am looking for a way to make this a CSS-only solution that is cross-browser compliant.

To be clear, what I am seeking to do is use only a table tag (and it's valid sub-tags, colgroup, col, thead, tbody, tfoot, tr, th, td), but adopt a set of CSS rules which will meet the following conditions:

Must maintain column alignment between header / footer / content rows

Must allow the header/footer to remain fixed while the content scrolls vertically

Must not require any jQuery or other JavaScript in order to provide the functionality

Must only use the tags provided above

This code example: http://jsfiddle.net/TroyAlford/SNKfd/ shows my current approach. Most of the JS is just to populate the table with random values, but the last portion is what drives the left/right scrollability.

```<code>$tbody.bind('scroll', function(ev) {
    var $css = { 'left': -ev.target.scrollLeft };
    $thead.css($css);
    $tfoot.css($css);
});
</code>```

NOTE: The example provided does not render properly in IE, and requires jQuery to provide the horizontal scrolling. I don't care about horizontal scrolling anyway, so it's fine if a solution doesn't do that.

答:
if it gets rock hard where all the mentioned solutions don't work (as it got for me), try a two-tabled solutioned, as I explained in this answer

https://stackoverflow.com/a/47722456/6488361

Body:
I have a solution by which I can create scrollable tables w/fixed header/footer using minor jQuery and CSS - but I am looking for a way to make this a CSS-only solution that is cross-browser compliant.

To be clear, what I am seeking to do is use only a table tag (and it's valid sub-tags, colgroup, col, thead, tbody, tfoot, tr, th, td), but adopt a set of CSS rules which will meet the following conditions:

Must maintain column alignment between header / footer / content rows

Must allow the header/footer to remain fixed while the content scrolls vertically

Must not require any jQuery or other JavaScript in order to provide the functionality

Must only use the tags provided above

This code example: http://jsfiddle.net/TroyAlford/SNKfd/ shows my current approach. Most of the JS is just to populate the table with random values, but the last portion is what drives the left/right scrollability.

$tbody.bind('scroll', function(ev) {
    var $css = { 'left': -ev.target.scrollLeft };
    $thead.css($css);
    $tfoot.css($css);
});

NOTE: The example provided does not render properly in IE, and requires jQuery to provide the horizontal scrolling. I don't care about horizontal scrolling anyway, so it's fine if a solution doesn't do that.


问:
JSON ListView filter not working
So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class

Here is my code:

```<code>public class jobcategories extends Activity{

private TextView jobData;
private ProgressDialog myprocessingdialog;

ArrayAdapter<String> adapter;

ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;

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

    myprocessingdialog = new ProgressDialog(this);

    jobList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    sv = (SearchView) findViewById(R.id.search);

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String text) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String text) {

            adapter.getFilter().filter(text);

            return false;
        }
    });

    new JSONTask().execute("https://apidata.com");

}

public class JSONTask extends AsyncTask<String,String, String>{

    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

       //Showing Progress dialogue

        myprocessingdialog.setTitle("Please Wait..");
        myprocessingdialog.setMessage("Loading");
        myprocessingdialog.setCancelable(false);
        myprocessingdialog.setIndeterminate(false);
        myprocessingdialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try{
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";
            while((line = reader.readLine()) != null){
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONArray parentObject = new JSONArray(finalJson);

            for (int i=0; i < parentObject.length(); i++) {
                JSONObject job = parentObject.getJSONObject(i);

                String JobTitle = job.getString("title");
                String JobLocation = job.getString("location");
                String finalTitle = JobTitle + " in " + JobLocation;
                String JobCompany = "advert by "+job.getString("company");
                String JobDescription = job.getString("description");
                String JobApply = "How to Apply: " + job.getString("apply");

                HashMap<String, String> jobs = new HashMap<>();
                jobs.put("title", finalTitle);
                jobs.put("company", JobCompany);
                jobs.put("description", JobDescription);
                jobs.put("apply", JobApply);

                jobList.add(jobs);
            }

        }catch (MalformedURLException e){
            Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
            try {
                if(reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String results) {
        super.onPostExecute(results);
        myprocessingdialog.cancel();
        ListAdapter adapter = new SimpleAdapter(
                jobcategories.this, jobList,
                R.layout.list_item, new String[]{"title", "company", "description", "apply"},
                new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});

        lv.setAdapter(adapter);

    }
    }
}
</code>```

Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.

答:
Create an interface called OnJsonResultListener like so:

```<code>public interface OnJsonResultListener {
    void onResult(String result);
}
</code>```

Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there.  Then make the AsyncTask take a OnJsonResultListener in the constructor.  Then in the onPostExecute method, call listener.onResult(results);

This is a simple way of making a callback.

Title: JSON ListView filter not working

Body:
So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class

Here is my code:

public class jobcategories extends Activity{

private TextView jobData;
private ProgressDialog myprocessingdialog;

ArrayAdapter<String> adapter;

ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;

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

    myprocessingdialog = new ProgressDialog(this);

    jobList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    sv = (SearchView) findViewById(R.id.search);

    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String text) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String text) {

            adapter.getFilter().filter(text);

            return false;
        }
    });

    new JSONTask().execute("https://apidata.com");

}

public class JSONTask extends AsyncTask<String,String, String>{

    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

       //Showing Progress dialogue

        myprocessingdialog.setTitle("Please Wait..");
        myprocessingdialog.setMessage("Loading");
        myprocessingdialog.setCancelable(false);
        myprocessingdialog.setIndeterminate(false);
        myprocessingdialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try{
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";
            while((line = reader.readLine()) != null){
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONArray parentObject = new JSONArray(finalJson);

            for (int i=0; i < parentObject.length(); i++) {
                JSONObject job = parentObject.getJSONObject(i);

                String JobTitle = job.getString("title");
                String JobLocation = job.getString("location");
                String finalTitle = JobTitle + " in " + JobLocation;
                String JobCompany = "advert by "+job.getString("company");
                String JobDescription = job.getString("description");
                String JobApply = "How to Apply: " + job.getString("apply");

                HashMap<String, String> jobs = new HashMap<>();
                jobs.put("title", finalTitle);
                jobs.put("company", JobCompany);
                jobs.put("description", JobDescription);
                jobs.put("apply", JobApply);

                jobList.add(jobs);
            }

        }catch (MalformedURLException e){
            Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
        } finally {
            if(connection != null) {
                connection.disconnect();
            }
            try {
                if(reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String results) {
        super.onPostExecute(results);
        myprocessingdialog.cancel();
        ListAdapter adapter = new SimpleAdapter(
                jobcategories.this, jobList,
                R.layout.list_item, new String[]{"title", "company", "description", "apply"},
                new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});

        lv.setAdapter(adapter);

    }
    }
}

Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.

Body:
Create an interface called OnJsonResultListener like so:

public interface OnJsonResultListener {
    void onResult(String result);
}

Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there.  Then make the AsyncTask take a OnJsonResultListener in the constructor.  Then in the onPostExecute method, call listener.onResult(results);

This is a simple way of making a callback.


问:
Git: "please tell me who you are" error
I have app servers that I bootstrap together using Chef + some ad-hoc bash scripts. The problem is, when I want to run an update on one of these app servers, I get:

```<code>19:00:28: *** Please tell me who you are.

Run

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

Do I really need to set this for doing a simple git pull origin master every time I update an app server? Is there anyway to override this behavior so it doesn't error out when name and email are not set?

答: For me the issue was network connection, once I reconnected to my wifi, it could fetch the details and commit without any issues.</p>

Title: Git: "please tell me who you are" error

Body:
I have app servers that I bootstrap together using Chef + some ad-hoc bash scripts. The problem is, when I want to run an update on one of these app servers, I get:

19:00:28: *** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

Do I really need to set this for doing a simple git pull origin master every time I update an app server? Is there anyway to override this behavior so it doesn't error out when name and email are not set?


答:
I see what is going on.  Your input string is only three three bytes and you are reading using the unsafe gets.  The gets is putting the input of ZZZ into the input variable as expected but it is putting the terminating null in the first byte of passcode.

Change the size of your input buffer to 999 and things will work a lot better.

Title: Comparing two strings in C in a loop


问:
function argument type differs without any compilation or runtime error
How come the following code is running? "measure" expects an argument of type geometry, but this code passes argument of "square" type.

```<code>package main
import "fmt"

type geometry interface {
    area() int
}

type square struct {
    radius int
}
func (s square) area() int {
    return s.radius*s.radius
}

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
}

func main() {
    measure(square{radius: 3})
}
</code>```

The outpust is:

```<code>{3}
9
</code>```

Thanks

答: square implements the geometry interface because it has the method area(). This is exactly the point of interfaces. See: https://tour.golang.org/methods/9

Body:
How come the following code is running? "measure" expects an argument of type geometry, but this code passes argument of "square" type.

package main
import "fmt"

type geometry interface {
    area() int
}

type square struct {
    radius int
}
func (s square) area() int {
    return s.radius*s.radius
}

func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
}

func main() {
    measure(square{radius: 3})
}

The outpust is:

{3}
9

Thanks


问:
How to get red distance lines in storyboard Xcode?
Watching a tutorial and it looks like the guy is holding down a button to show the distance between his selected view and what's around it.

I've tried command, option, control, and every other button I can think might work.  What button needs to be held to get these lines?

答:
By pressing option key only on your keyboard.

Select an element, and move the mouse while pressing the option key, it will show the red lines with the distances.

Hovering over another element will show you the distance between the selected element and that element.


问:
Using PHP Object values in AJAX
I am working on a pet-project. I have a php class. in the HTML, I make instances of that object. So the same page can contain many instances. now, I have to make ajax calls. the ajax call is based on the instances of the object. the data sent in ajax calls is can contain names of database tables and such. I was wondering how safe that is. any thoughts?</p>

答:
An attacker would like to know:

how to slip something in,

what to slip in.

You are giving away number 2 for free.

Title: Using PHP Object values in AJAX


问:
Ajax call works on click, but not when button is submit button is pressed
I have the following HTML template in Django to POST a request when the user selects the select option.  The console shows the correct value based on what the user selects.  My problem is when I push the submit button my POST gets posted as None on the submitted view.  How can I get it to post on button click, i've aliased the button as my_select.</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <form action = "{% url 'submitted' %}" form method = "POST">
    {% csrf_token %}
          <h2>Applications:</h3></br>

            {% for app in retreivecheckbox %}
            <li><input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}
              </li>
            {% endfor %}
        </div>

      </div>

      <div class="row">
        <div class="col">
          <label for="accesslevel"><h3>Access Level</h3></label>

<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
            <option value=""> Please select your access level  </option>
            <option value="7"> Facility  </option>
            <option value="5"> Division  </option>
            <option value = "3"> Corporate  </option>
            <option value = "6"> Market  </option>
            <option value = "4"> Group  </option>
</select>

        </div>
        <div class="col">

          <label for="phi"><h3>PHI</h3></label>

          <select class="form-control my_select" id="phi" title = "phi" >
            <option value = ""> Please select if you need access to PHI data </option>
            <option value = "0"> No  </option>
            <option value = "1"> Yes  </option>

          </select>

        </div>
      </div>

        <div class="row">
  <div class="container">
    <div class="row">
      <div class="col">
 </br> </br>

  <button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>
  <script>
  $(document).ready(function () {
      $('.my_select').on('click', function () {
          var phi = $('#phi').val();
          var accesslevelid = $('#accesslevelid ').val();
          $.ajax({ url: "{% url 'submitted' %}",
                  headers: { 'X-CSRFToken': '{{ csrf_token }}' },
                  data: {
                    phi: phi,
                    accesslevelid: accesslevelid,
                  },
                  type: 'POST',
                  success: function (result) {
                    ;
                  },
                });
        });
    });
  </script>

</div>

  </form>
</code>```

答:
Change your button and javascript to this:

```<code><button class="btn btn-primary my_select" type="submit">Submit</button>
<script>
$(document).ready(function () {
    $('form').on('submit', function (e) {
        e.preventDefault();
        var phi = $('#phi').val();
        var accesslevelid = $('#accesslevelid').val();
        $.ajax({
            url: "{% url 'submitted' %}",
            headers: { 'X-CSRFToken': '{{ csrf_token }}' },
            data: {
                phi: phi,
                accesslevelid: accesslevelid,
            },
            type: 'POST',
            success: function (result) {
                // do something with result
            },
        });
    });
});
</script>
</code>```

this is what i would normally use if you use Jquery 3.2.1

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

$('form').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        method: "POST",
        data: $(this).serialize()
    }).done(function(xhr) {
        // do something
    });
});
</code>```

also update your select elements to have

```<code><select class="form-control my_select" id="phi" name="phi">
</code>```

rather than

```<code><select class="form-control my_select" id="phi" title = "phi" >
</code>```

notice i have changed the "title" attr to "name"

Body:
I have the following HTML template in Django to POST a request when the user selects the select option.  The console shows the correct value based on what the user selects.  My problem is when I push the submit button my POST gets posted as None on the submitted view.  How can I get it to post on button click, i've aliased the button as my_select.

  <form action = "{% url 'submitted' %}" form method = "POST">
    {% csrf_token %}

Applications:

            {% for app in retreivecheckbox %}

<input type="checkbox" name="report_id" value ="{{app.report_id}}" checked> {{ app }}

            {% endfor %}

Access Level

<select title ="accesslevelid" class="form-control my_select" id="accesslevelid">
            <option value=""> Please select your access level  </option>
            <option value="7"> Facility  </option>
            <option value="5"> Division  </option>
            <option value = "3"> Corporate  </option>
            <option value = "6"> Market  </option>
            <option value = "4"> Group  </option>
</select>

PHI

          <select class="form-control my_select" id="phi" title = "phi" >
            <option value = ""> Please select if you need access to PHI data </option>
            <option value = "0"> No  </option>
            <option value = "1"> Yes  </option>

          </select>

  <button href="{% url 'submitted' %}" class="btn btn-primary my_select" type = "submit"> Submit </button>

  </form>

Body:
Change your button and javascript to this:

<button class="btn btn-primary my_select" type="submit">Submit</button>
<script>
$(document).ready(function () {
    $('form').on('submit', function (e) {
        e.preventDefault();
        var phi = $('#phi').val();
        var accesslevelid = $('#accesslevelid').val();
        $.ajax({
            url: "{% url 'submitted' %}",
            headers: { 'X-CSRFToken': '{{ csrf_token }}' },
            data: {
                phi: phi,
                accesslevelid: accesslevelid,
            },
            type: 'POST',
            success: function (result) {
                // do something with result
            },
        });
    });
});
</script>

this is what i would normally use if you use Jquery 3.2.1

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

$('form').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        method: "POST",
        data: $(this).serialize()
    }).done(function(xhr) {
        // do something
    });
});

also update your select elements to have

<select class="form-control my_select" id="phi" name="phi">

rather than

<select class="form-control my_select" id="phi" title = "phi" >

notice i have changed the "title" attr to "name"


问:
Webpack + React + TypeScript: Module not found ... in ... node_modules/react/
I'm trying to put together a very basic project with React, TypeScript and Webpack.  When I compile I get the following errors from the react folder in node_modules (I've removed the stack traces and my project's path for brevity):

```<code>ERROR in ./node_modules/react/cjs/react.production.min.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyFunction' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyFunction' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.production.min.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyObject' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyObject' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/invariant' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/warning' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.production.min.js
Module not found: Error: Can't resolve 'object-assign' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'object-assign' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'prop-types/checkPropTypes' in '.../node_modules/react/cjs'
</code>```

I tried uninstalling TypeScript and replacing it with Babel to transpile the JSX and got the same error.  Installing babel-preset-2015 fixed it.

I've tried just about every combination of target and module in tsconfig.json to get the same result in TypeScript but couldn't get anything working.  How can I get Webpack, TypeScript, and React working together?

I've worked with all three of these technologies before, is it a recent compatibility problem?  If so what are the most recent compatible versions?

I've seen a few other questions similar to this one where the solution was installing fbjs directly in the project - I've tried this too without success.

Files

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "jsx": "react",
    "module": "es2015"
  },
  "exclude": ["build"]
}
</code>```

webpack.config.js

```<code>module.exports = {
    entry: {
        dev: "./src/index.tsx",
    },
    output: {
        filename: "./build/index.js",
    },
    devtool: "source-map",
    resolve: {
        extensions: [".ts", ".tsx"],
    },
    module: {
        loaders: [
            // Typescript
            { test: /\.tsx?$/, loader: "ts-loader" },
        ],
    },
};
</code>```

package.json

```<code>{
    ...
    "scripts": {
        "build": "webpack"
    },
    "devDependencies": {
        "@types/react": "^16.0.28",
        "ts-loader": "^3.2.0",
        "typescript": "^2.6.2",
        "webpack": "^3.10.0"
    },
    "dependencies": {
        "react": "^16.2.0"
    }
}
</code>```

./src/index.tsx

```<code>import * as React from "react";

const a = <div />;
</code>```

(I'm running this with Node 9.2.1 and NPM 5.6.0 installed)

答:
Webpack is not resolving .js files. Add this to your webpack.config.js.

```<code>resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"]
},
</code>```

Here is the tsconfig.json I used to run your example.

```<code>{
  "compilerOptions": {
    "jsx": "react",
    "lib": ["es6", "dom"],
    "rootDir": "src",
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "moduleResolution": "node",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  },
  "include": [
    "./src"
  ],
  "exclude": [
    "node_modules",
    "build"
  ]
}
</code>```

Body:
I'm trying to put together a very basic project with React, TypeScript and Webpack.  When I compile I get the following errors from the react folder in node_modules (I've removed the stack traces and my project's path for brevity):

ERROR in ./node_modules/react/cjs/react.production.min.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyFunction' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyFunction' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.production.min.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyObject' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/emptyObject' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/invariant' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'fbjs/lib/warning' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.production.min.js
Module not found: Error: Can't resolve 'object-assign' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'object-assign' in '.../node_modules/react/cjs'

ERROR in ./node_modules/react/cjs/react.development.js
Module not found: Error: Can't resolve 'prop-types/checkPropTypes' in '.../node_modules/react/cjs'

I tried uninstalling TypeScript and replacing it with Babel to transpile the JSX and got the same error.  Installing babel-preset-2015 fixed it.

I've tried just about every combination of target and module in tsconfig.json to get the same result in TypeScript but couldn't get anything working.  How can I get Webpack, TypeScript, and React working together?

I've worked with all three of these technologies before, is it a recent compatibility problem?  If so what are the most recent compatible versions?

I've seen a few other questions similar to this one where the solution was installing fbjs directly in the project - I've tried this too without success.

Files

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "jsx": "react",
    "module": "es2015"
  },
  "exclude": ["build"]
}

webpack.config.js

module.exports = {
    entry: {
        dev: "./src/index.tsx",
    },
    output: {
        filename: "./build/index.js",
    },
    devtool: "source-map",
    resolve: {
        extensions: [".ts", ".tsx"],
    },
    module: {
        loaders: [
            // Typescript
            { test: /\.tsx?$/, loader: "ts-loader" },
        ],
    },
};

package.json

{
    ...
    "scripts": {
        "build": "webpack"
    },
    "devDependencies": {
        "@types/react": "^16.0.28",
        "ts-loader": "^3.2.0",
        "typescript": "^2.6.2",
        "webpack": "^3.10.0"
    },
    "dependencies": {
        "react": "^16.2.0"
    }
}

./src/index.tsx

import * as React from "react";

const a =
;

(I'm running this with Node 9.2.1 and NPM 5.6.0 installed)

Body:
Webpack is not resolving .js files. Add this to your webpack.config.js.

resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"]
},

Here is the tsconfig.json I used to run your example.

{
  "compilerOptions": {
    "jsx": "react",
    "lib": ["es6", "dom"],
    "rootDir": "src",
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "moduleResolution": "node",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  },
  "include": [
    "./src"
  ],
  "exclude": [
    "node_modules",
    "build"
  ]
}

ContentLicense: CC BY-SA 4.0


问:
Error in grouped_df_impl(data, unname(vars), drop) :
This is the first time I try to write a function with 2 pipes inside so that when I give a name x and variable name y, the results will be aggregrated, joined to the data and removed. When I run my written function, the captioned error message kept on coming up and I have no idea what the problem is.

```<code>mrr <- function(x, y){
  x <- data %>%
   group_by(y) %>%
   summarize(n=n(),
         sum=sum(unit_sales))
data <- data %>%
  left_join(x, by="y") %>%
  mutate(str_c(x,y))=(sum-unit_sales)/(n-1) %>%
  select(-one_of(n, sum)) %>%
  rm(x)
}
</code>```

I found the related results when I gave the error message in the search box, but the answers were not related to my problem. Do let me know if you have any thoughts.

答:
There's quite a few things going on here.

First, you don't need to input x into the function...because you are overwriting it immediately. I'm not sure whether you may have meant to input data.

Next, your group_by isn't working because y doesn't exist in your data set...the contents of y are the name of the header. We can use group_by_() to solve this problem.

After that, your mutate command is broken. mutate(str_c(x,y)) is a complete mutate statement because the () are closed. Also, str_c(x,y) is trying to take a dataframe x and concatenate with a character inside y to get a single character out...this will at best give you a dataframe out and at worse give an error. Better to just specify a column name.

In the same mutate, you may run into an error in =(sum-unit_sales)/(n-1). If n = 1 then you get a divide by zero error output of NaN. You can leave this if you want. Just understand what your equation is actually doing.

Getting close, the -one_of() command requires a vector of characters (not just column names. You can either do select(-n,-sum) or you can do select(-one_of(c("n", "sum"))).

Finally, you don't really need to use rm(x) because the variable will be removed when the function is done running anyway.

I had to guess at the name of columns...your names will be different since you didn't give me a sample data set.

```<code>data <- data.frame(d1 = runif(n=10,min=1,max=10),
           d2 = runif(n=10,min=1,max=10),
           unit_sales = runif(n=10,min=1,max=10))

mrr <- function(data, y){
  x <- data %>%
    group_by_(.dots = y) %>%
    summarize(n=n(),
     sum=sum(unit_sales))
  data <- data %>%
  left_join(x, by=y) %>%
    mutate(someCol=(sum-unit_sales)/(n)) %>%
    select(-one_of(c("n", "sum"))) #%>%
    # rm(x)
}

(mrr(data,"d2"))
</code>```

Body:
This is the first time I try to write a function with 2 pipes inside so that when I give a name x and variable name y, the results will be aggregrated, joined to the data and removed. When I run my written function, the captioned error message kept on coming up and I have no idea what the problem is.

mrr <- function(x, y){
  x <- data %>%
   group_by(y) %>%
   summarize(n=n(),
         sum=sum(unit_sales))
data <- data %>%
  left_join(x, by="y") %>%
  mutate(str_c(x,y))=(sum-unit_sales)/(n-1) %>%
  select(-one_of(n, sum)) %>%
  rm(x)
}

I found the related results when I gave the error message in the search box, but the answers were not related to my problem. Do let me know if you have any thoughts.

Body:
There's quite a few things going on here.

First, you don't need to input x into the function...because you are overwriting it immediately. I'm not sure whether you may have meant to input data.

Next, your group_by isn't working because y doesn't exist in your data set...the contents of y are the name of the header. We can use group_by_() to solve this problem.

After that, your mutate command is broken. mutate(str_c(x,y)) is a complete mutate statement because the () are closed. Also, str_c(x,y) is trying to take a dataframe x and concatenate with a character inside y to get a single character out...this will at best give you a dataframe out and at worse give an error. Better to just specify a column name.

In the same mutate, you may run into an error in =(sum-unit_sales)/(n-1). If n = 1 then you get a divide by zero error output of NaN. You can leave this if you want. Just understand what your equation is actually doing.

Getting close, the -one_of() command requires a vector of characters (not just column names. You can either do select(-n,-sum) or you can do select(-one_of(c("n", "sum"))).

Finally, you don't really need to use rm(x) because the variable will be removed when the function is done running anyway.

I had to guess at the name of columns...your names will be different since you didn't give me a sample data set.

data <- data.frame(d1 = runif(n=10,min=1,max=10),
           d2 = runif(n=10,min=1,max=10),
           unit_sales = runif(n=10,min=1,max=10))

mrr <- function(data, y){
  x <- data %>%
    group_by_(.dots = y) %>%
    summarize(n=n(),
     sum=sum(unit_sales))
  data <- data %>%
  left_join(x, by=y) %>%
    mutate(someCol=(sum-unit_sales)/(n)) %>%
    select(-one_of(c("n", "sum"))) #%>%
    # rm(x)
}

(mrr(data,"d2"))


问:
Autotools: Optionally compile and link against a third-party library
I have an executable project prog on autotools build-system. This program links against libfoo which is also an autotools project.

I want to give my users (who wish to compile prog) the freedom to choose between linking against a previously installed libfoo, or to configure, compile (static linkage) and link to the libfoo source tree which is shipped within package (in third-party directory)

libfoo uses libtool and pkg-config if it matters...

Ideally this would be done with some autoconf arguments:

```<code>./configure --with-local-libfoo
</code>```

vs

```<code>./configure --with-system-libfoo
</code>```

The question is how to tell the buildsystem to compile libfoo before prog (in second case) and how to provide correct link flags?

答:
Since libfoo is also an Autotools project, a copy of which is distributed inside the main project, it would be natural to set it up as a subproject.  The key Autoconf macro here is AC_CONFIG_SUBDIRS.  Thus, if the libfoo package were in a subdirectory libfoo/ of the directory containing the top-level configure script, the top-level configure.ac would use

```<code>AC_CONFIG_SUBDIRS([libfoo])
</code>```

In that case, the top-level configure script will run libfoo's configure script automatically, passing it all the same options it received (including any that are meaningful only to libfoo).  Moreover, the top-level script's --help option will print both its own and libfoo's options.  You can make that conditional on a --with-* argument (but just one, don't use two different ones).

On the Automake side, look into Automake conditionals and conditional subdirectories.  You can use conditionals, with the condition controlled by your --with-system-libfoo or whatever, to select the right set of link options and to determine whether make will recurse into the libfoo package.  When you're building your own copy of libfoo, it might be helpful to include the -static-libtool-libs option among the main program's link flags.

The last bits revolve around preventing the local libfoo, when you build it, from being installed on the system along side the main program.  I haven't come up with a good solution that doesn't involve tweaking libfoo's build system.  Do switch libfoo.la to be a convenience library (named in noinst_LTLIBRARIES instead of in lib_LTLIBRARIES or such) and in fact generally switch build targets in the libfoo subpackage from installed ones to noinst_ ones.

Body:
I have an executable project prog on autotools build-system. This program links against libfoo which is also an autotools project.

I want to give my users (who wish to compile prog) the freedom to choose between linking against a previously installed libfoo, or to configure, compile (static linkage) and link to the libfoo source tree which is shipped within package (in third-party directory)

libfoo uses libtool and pkg-config if it matters...

Ideally this would be done with some autoconf arguments:

./configure --with-local-libfoo

vs

./configure --with-system-libfoo

The question is how to tell the buildsystem to compile libfoo before prog (in second case) and how to provide correct link flags?

Body:
Since libfoo is also an Autotools project, a copy of which is distributed inside the main project, it would be natural to set it up as a subproject.  The key Autoconf macro here is AC_CONFIG_SUBDIRS.  Thus, if the libfoo package were in a subdirectory libfoo/ of the directory containing the top-level configure script, the top-level configure.ac would use

AC_CONFIG_SUBDIRS([libfoo])

In that case, the top-level configure script will run libfoo's configure script automatically, passing it all the same options it received (including any that are meaningful only to libfoo).  Moreover, the top-level script's --help option will print both its own and libfoo's options.  You can make that conditional on a --with-* argument (but just one, don't use two different ones).

On the Automake side, look into Automake conditionals and conditional subdirectories.  You can use conditionals, with the condition controlled by your --with-system-libfoo or whatever, to select the right set of link options and to determine whether make will recurse into the libfoo package.  When you're building your own copy of libfoo, it might be helpful to include the -static-libtool-libs option among the main program's link flags.

The last bits revolve around preventing the local libfoo, when you build it, from being installed on the system along side the main program.  I haven't come up with a good solution that doesn't involve tweaking libfoo's build system.  Do switch libfoo.la to be a convenience library (named in noinst_LTLIBRARIES instead of in lib_LTLIBRARIES or such) and in fact generally switch build targets in the libfoo subpackage from installed ones to noinst_ ones.


问:
Slack: How can I remove a message's action buttons without Slack appending "edited"
I have a Slackbot message that has action buttons (see here). When a user click's a button, we perform a bit of work on our server and then use chat.update to remove the action buttons and update the message's footer:

```<code>removeButtons(reply, convo, footer) {

  const data = reply.original_message;
  delete data.attachments[0].actions;
  data.channel = reply.channel;
  if (footer) {
    data.attachments[0].footer = footer;
  }
  this.bot.api.chat.update(data, (res) => {

  });
}
</code>```

Everything is working great but Slack appends an "(Edited)" to the message. I see a lot of other apps doing the same, but they seem to avoid the "(Edited)" text? What are they doing differently?

I've tried setting as_user and replace_original in the chat.update call but haven't had any luck.

Slack Screenshot

答:
There are two ways to "update" a message as result of an interaction.

Use the API method chat.update (as you described)

Respond directly to the slack request with a new message

With 2) the original message will be replaced by default and there will be no "edited" note.

Body:
I have a Slackbot message that has action buttons (see here). When a user click's a button, we perform a bit of work on our server and then use chat.update to remove the action buttons and update the message's footer:

removeButtons(reply, convo, footer) {

  const data = reply.original_message;
  delete data.attachments[0].actions;
  data.channel = reply.channel;
  if (footer) {
    data.attachments[0].footer = footer;
  }
  this.bot.api.chat.update(data, (res) => {

  });
}

Everything is working great but Slack appends an "(Edited)" to the message. I see a lot of other apps doing the same, but they seem to avoid the "(Edited)" text? What are they doing differently?

I've tried setting as_user and replace_original in the chat.update call but haven't had any luck.

Slack Screenshot


问:
MySQL data and Maths to get attendance
Below is a screenshot I have of a sample MySQL attendance data for users.

Each attendance for username is calculated based on column attended_sessions divide by total_sessions multiple by 100. This gives each users exact attendance. Each user has variable total number of sessions depending on when they started and ended.

This is fine. However my question is to calculate the attendance for all of those users, and this poses a maths dilemma.

If I average all 15 rows of the attendance percentage I get 87.09%. However, this is average. Whereas if I sum up both the sessions data I get attended_sessions=1494 and total_session=1648. Then if I divide that by each other and multiply by 100 I get 90.66%.

My maths skills isn't great. So which is the correct method to calculate? I would think that the average isn't accurate as it is averaging it. Whereas the other method of summing up all sessions would be the exact representation of the attendance.

答: Summing the sessions data, dividing and multiplying by 100 is going to be more accurate than just summing the attendance averages. The values for attendance are already rounded, so you've already lost some precision. Better to work with source data than derived data.</p>

Title: MySQL data and Maths to get attendance


问:
mysql only returning results with numeric values

I am creating a random alphanumeric for a public access category that can only be found by using this alphanumeric post id in the url link. Weird thing is that I am only getting results from the query when numeric values are used.

```<code> $sql = "SELECT *
 FROM $a
 WHERE access_key = $category_id
</code>```

I get an "unknown column" error containing the alphnumeric data as the column, which I find a little strange. I think this maybe something simple like escaping that needs to be done, but I am not really sure.

Any suggestions would be appriciated. Thanks in advance.

答:
As stated by tadman, never use direct $_GET or $_POST values in your SQL. Protect it with something like this:

```<code>Function protectSQL($val, $type=‘text’) {
$val = get_magic_quotes_gpc() ? stripslashes($val) : $val;
switch ($type) {
    case "text":
         $val = ($val != "") ? "'" . $val . "'" : "NULL";
         break;
    case "long":
    case "int":
         $val = ($val != "") ? intval($val) : "NULL";
         break;
      }
return $val;
}
</code>```

Since you're not wrapping within apostrophes your value, MySQL thinks its a column. So, write something like this:

```<code>$sql = sprintf("SELECT * FROM %s WHERE access_key = %s", $a, protectSQL($val)); // $val is passed in the functions above, and $a has to be guaranteed...
</code>```

And you'll get something clean like:

```<code>echo $sql; // SELECT * FROM table WHERE access_key = 'abc123'
</code>```

Remember that $a is assumed to come from your code, so there is no protection added. If it comes from the client side, a simple in_array command could ensure that it is a valid table.

Body:
I am creating a random alphanumeric for a public access category that can only be found by using this alphanumeric post id in the url link. Weird thing is that I am only getting results from the query when numeric values are used.

 $sql = "SELECT *
 FROM $a
 WHERE access_key = $category_id

I get an "unknown column" error containing the alphnumeric data as the column, which I find a little strange. I think this maybe something simple like escaping that needs to be done, but I am not really sure.

Any suggestions would be appriciated. Thanks in advance.

Body:
As stated by tadman, never use direct $_GET or $_POST values in your SQL. Protect it with something like this:

Function protectSQL($val, $type=‘text’) {
$val = get_magic_quotes_gpc() ? stripslashes($val) : $val;
switch ($type) {
    case "text":
         $val = ($val != "") ? "'" . $val . "'" : "NULL";
         break;
    case "long":
    case "int":
         $val = ($val != "") ? intval($val) : "NULL";
         break;
      }
return $val;
}

Since you're not wrapping within apostrophes your value, MySQL thinks its a column. So, write something like this:

$sql = sprintf("SELECT * FROM %s WHERE access_key = %s", $a, protectSQL($val)); // $val is passed in the functions above, and $a has to be guaranteed...

And you'll get something clean like:

echo $sql; // SELECT * FROM table WHERE access_key = 'abc123'

Remember that $a is assumed to come from your code, so there is no protection added. If it comes from the client side, a simple in_array command could ensure that it is a valid table.


问:
Running PDFTron in a separate AppDomain: "Cannot pass a GCHandle across AppDomains"
PDFTron seems not to be able to handle more than one AppDomain. When running PDFTron from a separate AppDomain, the application crashes with an unhandled exception ("Cannot pass a GCHandle across AppDomains").

```<code>   bei System.Runtime.InteropServices.GCHandle.InternalCheckDomain(IntPtr handle)
   bei System.Runtime.InteropServices.GCHandle.FromIntPtr(IntPtr value)
   bei gcroot<pdftron::PDF::PDFViewWPF ^>.->(gcroot<pdftron::PDF::PDFViewWPF ^>* )
   bei pdftron.PDF.detail.DeluxeCreateTile(Void* data, SByte* buffer, UInt32 width, UInt32 height, UInt32 stride, UInt32 page_num, UInt64 x_page_loc, UInt64 y_page_loc, UInt32 zoomed_page_width, UInt32 zoomed_page_height, UInt32 tile_id, UInt32 x_in_page, UInt32 y_in_page, Int32 canvas_id, Int32 remaining_tiles, Int32 tile_type, Int32 sequenceNum)
</code>```

While searching for a solution I found a thread in the Google Groups forum which was created in 2011. A user got the same exception in an outlook plugin he was working on. According to the topic the issue has been known to the PDFTron support and also was fixed in one of the WinForms-based controls. You can find the discussion here: https://groups.google.com/forum/#!topic/pdfnet-sdk/DGki3Fj2_FU

Do I have to consider something or is PDFTron simply not able to run in this environment?

This is the code from the example I used to reproduce the issue:

MainWindow.xaml

```<code><Window x:Class="RunningPdfTronUsingMultipleAppDomains.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RunningPdfTronUsingMultipleAppDomains"
        xmlns:pdf="clr-namespace:pdftron.PDF;assembly=PDFNet"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="LayoutRoot">
        <pdf:PDFViewWPF x:Name="PDFView"/>
        <Button Panel.ZIndex="100" Height="20" Width="110" Content="Create AppDomain" PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown"/>
    </Grid>
</Window>
</code>```

MainWindow.xaml.cs

```<code> public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
    {
        PDFDoc document = new PDFDoc("SampleDocument.pdf");
        PDFView.SetDoc(document);
    }

        private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            AppDomain appDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
            var assembly = System.Reflection.Assembly.GetAssembly(typeof(MainWindow));
            appDomain.Load(assembly.GetName());
            Proxy proxy = (Proxy)appDomain.CreateInstanceAndUnwrap(System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName, typeof(Proxy).FullName);
            Thread thread = new Thread(new ParameterizedThreadStart((o) => proxy.Invoke())) { ApartmentState = ApartmentState.STA };
            thread.Start();
        }
    }
</code>```

Proxy.cs

```<code>  public class Proxy : MarshalByRefObject
        {
            public void Invoke()
            {
                try
                {
                    App app = new App();
                    app.Run(new MainWindow());
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
</code>```

答: FYI: PDFTron WPF 6.8 (slated for January) will include support for multiple/separate AppDomains</p>

Body:
PDFTron seems not to be able to handle more than one AppDomain. When running PDFTron from a separate AppDomain, the application crashes with an unhandled exception ("Cannot pass a GCHandle across AppDomains").

   bei System.Runtime.InteropServices.GCHandle.InternalCheckDomain(IntPtr handle)
   bei System.Runtime.InteropServices.GCHandle.FromIntPtr(IntPtr value)
   bei gcroot<pdftron::PDF::PDFViewWPF ^>.->(gcroot<pdftron::PDF::PDFViewWPF ^>* )
   bei pdftron.PDF.detail.DeluxeCreateTile(Void* data, SByte* buffer, UInt32 width, UInt32 height, UInt32 stride, UInt32 page_num, UInt64 x_page_loc, UInt64 y_page_loc, UInt32 zoomed_page_width, UInt32 zoomed_page_height, UInt32 tile_id, UInt32 x_in_page, UInt32 y_in_page, Int32 canvas_id, Int32 remaining_tiles, Int32 tile_type, Int32 sequenceNum)

While searching for a solution I found a thread in the Google Groups forum which was created in 2011. A user got the same exception in an outlook plugin he was working on. According to the topic the issue has been known to the PDFTron support and also was fixed in one of the WinForms-based controls. You can find the discussion here: https://groups.google.com/forum/#!topic/pdfnet-sdk/DGki3Fj2_FU

Do I have to consider something or is PDFTron simply not able to run in this environment?

This is the code from the example I used to reproduce the issue:

MainWindow.xaml

<Window x:Class="RunningPdfTronUsingMultipleAppDomains.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:RunningPdfTronUsingMultipleAppDomains"
        xmlns:pdf="clr-namespace:pdftron.PDF;assembly=PDFNet"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="LayoutRoot">
        <pdf:PDFViewWPF x:Name="PDFView"/>
        <Button Panel.ZIndex="100" Height="20" Width="110" Content="Create AppDomain" PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown"/>
    </Grid>
</Window>

MainWindow.xaml.cs

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
    {
        PDFDoc document = new PDFDoc("SampleDocument.pdf");
        PDFView.SetDoc(document);
    }

        private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            AppDomain appDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
            var assembly = System.Reflection.Assembly.GetAssembly(typeof(MainWindow));
            appDomain.Load(assembly.GetName());
            Proxy proxy = (Proxy)appDomain.CreateInstanceAndUnwrap(System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName, typeof(Proxy).FullName);
            Thread thread = new Thread(new ParameterizedThreadStart((o) => proxy.Invoke())) { ApartmentState = ApartmentState.STA };
            thread.Start();
        }
    }

Proxy.cs

  public class Proxy : MarshalByRefObject
        {
            public void Invoke()
            {
                try
                {
                    App app = new App();
                    app.Run(new MainWindow());
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }