问:
Typescript: Accessing a parent property from child object in a constant
In this Typescript/Javascript code:

```<code>var v= {
  x: 1,
  y: {
    z: v.x,
  }
}

const c = {
  x: 1,
  y: {
    z: c.x,
  }
}
</code>```

v is ok because var is JavaScript and it doesn't complain, but when assigning z in c there is an error because of the use of z before its declaration.

My question: is there a way to get it?
(I know I could declare another x out of c and assign its value inside, but I mean something more direct)

答:
Both examples will throw an error as v does not yet exist at the time when the expression v.x is evaluated:

var

var v= {
  x: 1,
  y: {
    z: v.x, // TypeError
  }
}```
</div>
</div>
</p>

<p><strong>const</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const c = {
  x: 1,
  y: {
    z: c.x, // TypeError
  }
}</code>```

You'll have to resort to adding the object after c is initialized:

const c = {
  x: 1
}

c.y = { z: c.x };

console.log(c.y.z);```

Body:
In this Typescript/Javascript code:

var v= {
  x: 1,
  y: {
    z: v.x,
  }
}

const c = {
  x: 1,
  y: {
    z: c.x,
  }
}

v is ok because var is JavaScript and it doesn't complain, but when assigning z in c there is an error because of the use of z before its declaration.

My question: is there a way to get it?
(I know I could declare another x out of c and assign its value inside, but I mean something more direct)

Body:
Both examples will throw an error as v does not yet exist at the time when the expression v.x is evaluated:

var

var v= {
  x: 1,
  y: {
    z: v.x, // TypeError
  }
}

const

const c = {
  x: 1,
  y: {
    z: c.x, // TypeError
  }
}

You'll have to resort to adding the object after c is initialized:

const c = {
  x: 1
}

c.y = { z: c.x };

console.log(c.y.z);


来源: stackexchange

问:
How to repeat a function on every Ajax request
So I have this transform code as an example but basically I have 3 buttons on my page that load different html files. When I click the first button the function in the .ajaxSend works properly. After I click the next button to load a different html file the .ajaxSend function doesn't work but the html file loads fine.

Am i missing something or is there a way to basically set the function so that it resets everytime I load an html file.

```<code>$('a').click(function(){
  var page = $(this).attr('href');
  $("#content").hide().load(page).fadeIn('500');

  return false;
});

$( document ).ajaxSend(function() {
  setInterval(function () {
       $('body').css('transform', 'rotate(360deg)');
   },300);
});
</code>```

答:
The rotation of 360 degree is the rotation from the original position (0deg). So once it's rotated, it won't do anything else. You need to add the additional rotation yourself. For that, you could store a variable holding the rotation and increment that by 360 each time ajaxSend is called.

```<code>let rotation = 0;
$( document ).ajaxSend(function() {
       rotation += 360;
       $('body').css('transform', 'rotate(' + rotation + 'deg)');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have this transform code as an example but basically I have 3 buttons on my page that load different html files. When I click the first button the function in the .ajaxSend works properly. After I click the next button to load a different html file the .ajaxSend function doesn't work but the html file loads fine.

Am i missing something or is there a way to basically set the function so that it resets everytime I load an html file.

$('a').click(function(){
  var page = $(this).attr('href');
  $("#content").hide().load(page).fadeIn('500');

  return false;
});

$( document ).ajaxSend(function() {
  setInterval(function () {
       $('body').css('transform', 'rotate(360deg)');
   },300);
});

Body:
The rotation of 360 degree is the rotation from the original position (0deg). So once it's rotated, it won't do anything else. You need to add the additional rotation yourself. For that, you could store a variable holding the rotation and increment that by 360 each time ajaxSend is called.

let rotation = 0;
$( document ).ajaxSend(function() {
       rotation += 360;
       $('body').css('transform', 'rotate(' + rotation + 'deg)');
});


问:
To what degree do i have the worry about security (XSS) when handling user input in Angular?

To systematically block XSS bugs, Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

Angular templates are the same as executable code: HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe. This means that applications must prevent values that an attacker can control from ever making it into the source code of a template. Never generate template source code by concatenating user input and templates. To prevent these vulnerabilities, use the offline template compiler, also known as template injection.

This is what Angular says about XSS. However it kinda seems that the first paragraph contradicts the second one (please correct me if i'm wrong). So my question is: Do i need to escape and sanitize my user input?

答:
Code is trusted but values aren't. If you insert values using the normal Angular data binding, then they are encoded as appropriate, because Angular can recognize what is a value and what is code.

For example, this doesn't require any additional escaping:

```<code><h1>Hello {{yourName}}!</h1>
</code>```

But if you tried to create a template using string concatenation. For example:

```<code>'<h1>Hello ' + yourName + '!</h1>'
</code>```

or with a server-side language like PHP:

```<code><h1>Hello <?= $_GET['name'] ?> !</h1>
</code>```

Then Angular can't tell the difference between the literal html and the inserted value. Data inserted like this can now inject Javascript as well as Angular syntax.

As long as you stick to the normal Angular mechanisms for inserting values, then you don't need additional encoding. The vulnerabilities come from bypassing angular and inserting values directly some other way.

Body:
Code is trusted but values aren't. If you insert values using the normal Angular data binding, then they are encoded as appropriate, because Angular can recognize what is a value and what is code.

For example, this doesn't require any additional escaping:

<h1>Hello {{yourName}}!</h1>

But if you tried to create a template using string concatenation. For example:

'<h1>Hello ' + yourName + '!</h1>'

or with a server-side language like PHP:

<h1>Hello <?= $_GET['name'] ?> !</h1>

Then Angular can't tell the difference between the literal html and the inserted value. Data inserted like this can now inject Javascript as well as Angular syntax.

As long as you stick to the normal Angular mechanisms for inserting values, then you don't need additional encoding. The vulnerabilities come from bypassing angular and inserting values directly some other way.


问:
Smoothly change the images in the transitions
I'm using the KenBurnsView in the login screen of my App to show several images in the background. The thing is that this images change too abruptly. Isn't a way to implement a fadein/fadeout effect when changing the transitions from one image to another, hooking somewhere in the view API?

This is the code that I'm using to implement the transitions.

```<code>private void setupAnimationBackground() {
    mBackgroundImageView.setTransitionListener(new KenBurnsView.TransitionListener() {
        @DrawableRes int[] mResources = new int[]{
                R.drawable.splash1, R.drawable.splash2, R.drawable.splash3,
                R.drawable.splash4, R.drawable.splash5, R.drawable.splash6
        };

        int mIndex = 0;

        @Override
        public void onTransitionStart(Transition transition) {
            mIndex = (mIndex == mResources.length - 1) ? 0 : mIndex + 1;
        }

        @Override
        public void onTransitionEnd(Transition transition) {
            mBackgroundImageView.setImageDrawable(ContextCompat.getDrawable(getContext(), mResources[mIndex]));
        }
    });
}
</code>```

mBackgroundImageView is a KenBurnsView. I have the images resources in my drawable folder. As you can see I store the references in a resource int array.

答: Sorry, nope. You need to have two KenBurnsViews one overlapping on top of the other and you handle the crossfading yourself.</p>

Body:
I'm using the KenBurnsView in the login screen of my App to show several images in the background. The thing is that this images change too abruptly. Isn't a way to implement a fadein/fadeout effect when changing the transitions from one image to another, hooking somewhere in the view API?

This is the code that I'm using to implement the transitions.

private void setupAnimationBackground() {
    mBackgroundImageView.setTransitionListener(new KenBurnsView.TransitionListener() {
        @DrawableRes int[] mResources = new int[]{
                R.drawable.splash1, R.drawable.splash2, R.drawable.splash3,
                R.drawable.splash4, R.drawable.splash5, R.drawable.splash6
        };

        int mIndex = 0;

        @Override
        public void onTransitionStart(Transition transition) {
            mIndex = (mIndex == mResources.length - 1) ? 0 : mIndex + 1;
        }

        @Override
        public void onTransitionEnd(Transition transition) {
            mBackgroundImageView.setImageDrawable(ContextCompat.getDrawable(getContext(), mResources[mIndex]));
        }
    });
}

mBackgroundImageView is a KenBurnsView. I have the images resources in my drawable folder. As you can see I store the references in a resource int array.


问:
Loops and "i" - Correctly inputting "i"
I have no idea how to add in the "i" to the following code.  I've gone through previous questions, but I can't get this to run properly.  Ideas?  Starting after "ELSE", I have no idea how to add in the "i".  Any help would be appreciated.</p>

```<code>For i = 2 To myLastRow

Set mycell = myWorksheet.Range("AK" & i)
Set mycell2 = myWorksheet.Range("AD" & i)

Else
    **mycell.Offset(, 2).Formula = "==IF(ABS(AJ" & i & " - AL" & i & ") <= AL" & i & "*0.1, TRUE, FALSE) "**
</code>```

答:
```<code>Dim i As Integer
Dim mylastrow As Integer
Dim myworksheet As Worksheet
Dim mycell As Range
Dim mycell2 As Range

Set myworksheet = Sheet1
mylastrow = 10

For i = 2 To mylastrow
    Cells(i, "AK").Offset(, 2).Formula = "=IF(ABS(AJ" & i & " - AL" & i & ") <= AL" & i & "*0.1, TRUE, FALSE) "
 '   Cells(i, "AD").Value
Next i
</code>```

Are you trying to do something like this? The cells property works perfect for thse types of loops.

Title: Loops and "i" - Correctly inputting "i"

Body:
I have no idea how to add in the "i" to the following code.  I've gone through previous questions, but I can't get this to run properly.  Ideas?  Starting after "ELSE", I have no idea how to add in the "i".  Any help would be appreciated.

For i = 2 To myLastRow

Set mycell = myWorksheet.Range("AK" & i)
Set mycell2 = myWorksheet.Range("AD" & i)

Else
    **mycell.Offset(, 2).Formula = "==IF(ABS(AJ" & i & " - AL" & i & ") <= AL" & i & "*0.1, TRUE, FALSE) "**

Body:
Dim i As Integer
Dim mylastrow As Integer
Dim myworksheet As Worksheet
Dim mycell As Range
Dim mycell2 As Range

Set myworksheet = Sheet1
mylastrow = 10

For i = 2 To mylastrow
    Cells(i, "AK").Offset(, 2).Formula = "=IF(ABS(AJ" & i & " - AL" & i & ") <= AL" & i & "*0.1, TRUE, FALSE) "
 '   Cells(i, "AD").Value
Next i

Are you trying to do something like this? The cells property works perfect for thse types of loops.


问:
Vectorizing `numpy.random.choice` for given 2D array of probabilities along an axis
Numpy has the random.choice function, which allows you to sample from a categorical distribution. How would you repeat this over an axis? To illustrate what I mean, here is my current code:

```<code>categorical_distributions = np.array([
    [.1, .3, .6],
    [.2, .4, .4],
])
_, n = categorical_distributions.shape
np.array([np.random.choice(n, p=row)
          for row in categorical_distributions])
</code>```

Ideally, I would like to eliminate the for loop.

答:
Here's one vectorized way to get the random indices per row, with a as the 2D array of probabilities -

```<code>(a.cumsum(1) > np.random.rand(a.shape[0])[:,None]).argmax(1)
</code>```

Generalizing to cover both along the rows and columns for 2D array -

```<code>def random_choice_prob_index(a, axis=1):
    r = np.expand_dims(np.random.rand(a.shape[1-axis]), axis=axis)
    return (a.cumsum(axis=axis) > r).argmax(axis=axis)
</code>```

Let's verify with the given sample by running it over a million times -

```<code>In [589]: a = np.array([
     ...:     [.1, .3, .6],
     ...:     [.2, .4, .4],
     ...: ])

In [590]: choices = [random_choice_prob_index(a)[0] for i in range(1000000)]

# This should be close to first row of given sample
In [591]: np.bincount(choices)/float(len(choices))
Out[591]: array([ 0.099781,  0.299436,  0.600783])
</code>```

Runtime test

Original loopy way -

```<code>def loopy_app(categorical_distributions):
    m, n = categorical_distributions.shape
    out = np.empty(m, dtype=int)
    for i,row in enumerate(categorical_distributions):
        out[i] = np.random.choice(n, p=row)
    return out
</code>```

Timings on bigger array -

```<code>In [593]: a = np.array([
     ...:     [.1, .3, .6],
     ...:     [.2, .4, .4],
     ...: ])

In [594]: a_big = np.repeat(a,100000,axis=0)

In [595]: %timeit loopy_app(a_big)
1 loop, best of 3: 2.54 s per loop

In [596]: %timeit random_choice_prob_index(a_big)
100 loops, best of 3: 6.44 ms per loop
</code>```

Body:
Numpy has the random.choice function, which allows you to sample from a categorical distribution. How would you repeat this over an axis? To illustrate what I mean, here is my current code:

categorical_distributions = np.array([
    [.1, .3, .6],
    [.2, .4, .4],
])
_, n = categorical_distributions.shape
np.array([np.random.choice(n, p=row)
          for row in categorical_distributions])

Ideally, I would like to eliminate the for loop.

Body:
Here's one vectorized way to get the random indices per row, with a as the 2D array of probabilities -

(a.cumsum(1) > np.random.rand(a.shape[0])[:,None]).argmax(1)

Generalizing to cover both along the rows and columns for 2D array -

def random_choice_prob_index(a, axis=1):
    r = np.expand_dims(np.random.rand(a.shape[1-axis]), axis=axis)
    return (a.cumsum(axis=axis) > r).argmax(axis=axis)

Let's verify with the given sample by running it over a million times -

In [589]: a = np.array([
     ...:     [.1, .3, .6],
     ...:     [.2, .4, .4],
     ...: ])

In [590]: choices = [random_choice_prob_index(a)[0] for i in range(1000000)]

# This should be close to first row of given sample
In [591]: np.bincount(choices)/float(len(choices))
Out[591]: array([ 0.099781,  0.299436,  0.600783])

Runtime test

Original loopy way -

def loopy_app(categorical_distributions):
    m, n = categorical_distributions.shape
    out = np.empty(m, dtype=int)
    for i,row in enumerate(categorical_distributions):
        out[i] = np.random.choice(n, p=row)
    return out

Timings on bigger array -

In [593]: a = np.array([
     ...:     [.1, .3, .6],
     ...:     [.2, .4, .4],
     ...: ])

In [594]: a_big = np.repeat(a,100000,axis=0)

In [595]: %timeit loopy_app(a_big)
1 loop, best of 3: 2.54 s per loop

In [596]: %timeit random_choice_prob_index(a_big)
100 loops, best of 3: 6.44 ms per loop


问:
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 can use EXISTS to find the debt numbers that have more than one date. See the simplified example below.</p>

```<code>CREATE TABLE #Test(TagDate date, DebtNumber int)

INSERT INTO #Test(TagDate, DebtNumber) VALUES
('01/01/2017', 1089484),
('01/02/2017', 1089484),
('01/01/2017', 1089485),
('01/01/2017', 1089486),
('01/01/2017', 1089487),
('01/01/2017', 1089488)

SELECT *
FROM #Test AS O
WHERE EXISTS (SELECT 1 FROM #Test WHERE DebtNumber = O.DebtNumber HAVING COUNT(TagDate) > 1)

DROP TABLE #Test
</code>```

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 can use EXISTS to find the debt numbers that have more than one date. See the simplified example below.

CREATE TABLE #Test(TagDate date, DebtNumber int)

INSERT INTO #Test(TagDate, DebtNumber) VALUES
('01/01/2017', 1089484),
('01/02/2017', 1089484),
('01/01/2017', 1089485),
('01/01/2017', 1089486),
('01/01/2017', 1089487),
('01/01/2017', 1089488)

SELECT *
FROM #Test AS O
WHERE EXISTS (SELECT 1 FROM #Test WHERE DebtNumber = O.DebtNumber HAVING COUNT(TagDate) > 1)

DROP TABLE #Test


问:
REST and HATEOS definitions self-violating?
QUESTION: Can HATEOAS in REST be considered a valid proposition when it is self-evidently internally contradictory : If an interface is said to not be RESTful (according to Fielding), when a Client cannot utilize the in-band data (URI's) from the Response Hypertext (Hypermedia) without reference to an external (out-of-band) document, and therefore tightly coupling Client and Server according to Fielding, how can we do anything but fail Roy Fielding's prima facie assertion?

It seems to me that Fielding's exposition makes HATEOAS and REST an internally contradictory proposition that cannot be fulfilled with the current technology - unless someone knows how to it without referring to out-of-band data?

(EDIT) I suspect no-one is reading/has read Fielding's rant, so here's the most relevant piece:

"A REST API should be entered with no prior knowledge beyond the initial URI (bookmark) and set of standardized media types that are appropriate for the intended audience (i.e., expected to be understood by any client that might use the API). From that point on, all application state transitions must be driven by client selection of server-provided choices that are present in the received representations or implied by the user’s manipulation of those representations. The transitions may be determined (or limited by) the client’s knowledge of media types and resource communication mechanisms, both of which may be improved on-the-fly (e.g., code-on-demand). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]"

We all keep asserting that we must have out-of-band knowledge of the URI's available methods beyond the initial data stream. Note how Fielding very stridently tells us that this is failure. Yet, it's how we're all dong it, me included. But Fielding screams No back at us.

(EDIT: because no-one's reading ithe explanation).

答:
There are three pieces of prior knowledge that REST allows: the home page of the API (in browsers, this is supplied by the user typing into the address bar); an understanding of common media types, such as HTML (provided by browser developers); and link relations that inform a client application can look at when deciding what to do (e.g. rel=stylesheet links get automatically downloaded and parsed by graphical browsers to make the documents they render look pretty).

What REST prohibits is a client knowing it can do things like read an ID from a certain place on your webpage and then append it onto the end of youtube.com/watch?v= to get to a YouTube video. In stead, you should define a "video-clip" link relation and use your media type's hyperlinking mechanism to provide the full URL, not just the ID.


问:
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?

答:
A solution using dplyr and tidyr. suppressWarnings is not required. Because when you created data frames, there are factor columns, suppressWarnings is to suppress the warning message when combining factors.

```<code>library(dplyr)
library(tidyr)

df1 <- suppressWarnings(df %>%
  mutate(v = unlist(.$v)) %>%
  unnest())
df1
#    v n1   n2
# 1 p1  a    1
# 2 p1  b    2
# 3 p2  d <NA>
# 4 p3  e    3
</code>```

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:
A solution using dplyr and tidyr. suppressWarnings is not required. Because when you created data frames, there are factor columns, suppressWarnings is to suppress the warning message when combining factors.

library(dplyr)
library(tidyr)

df1 <- suppressWarnings(df %>%
  mutate(v = unlist(.$v)) %>%
  unnest())
df1
#    v n1   n2
# 1 p1  a    1
# 2 p1  b    2
# 3 p2  d <NA>
# 4 p3  e    3


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
If you are looking for confidence, the alternative to proving programs is testing them. This is easier to understand and can be automated. It also allows for the class of programs for which proofs are mathematically not possible, as described above.

Above all, no proof is a substitute for passing acceptance tests:*

Just because a program really does do what it says it does, doesn't mean it does what the user wants it to do.

Unless you can prove that what it says it does is what the user says they want.

Which you then have to prove is what they really want, because, being a user, they almost certainly don't know what they want. etc. Reductio ad absurdum.

*not to mention unit, coverage, functional, integration and all the other kinds of tests.

Hope this helps you on your path.

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?


问:
About CGRectMake
This will sound extremely silly and stupid, but I have touched a couple languages and they kind of messed up my sense of.... orientation or something:

In Objective-C, you can use CGRectMake(x,y,w,h) to make a rect. Cool.

So x,y set the... top left corner of the rect, or.... the center of the rect?

答: Cocoa uses the Cartesian coordinate plane as its coordinate system (so (x, y) is set to the bottom-left corner). You can read more about the coordinate system in the Cocoa Drawing Guide.</p>

Title: About CGRectMake


问:
the way of writing constructor, deconstructor and copy constructor for matrix class
I am trying to create a constructor, destructor, and copy constructor for  a matrix class, and I am not so sure if I am doing it well.

In particular, I am not sure about 2 things:

Is the destructor suppose to free memory also for the memory that is allocated in the copy-constructor?

As to the line Mat[i][j]=other[i][j] (see in the code below), I wonder if I should write Mat[i][j]=other.Mat[i][j] instead?

```<code>class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (const int &rows,const int &cols);
    Matrix (const Matrix &other);
    ~Matrix ();
};

Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
    rows=n_rows;
    cols=n_cols;
    Mat=new int* [cols];

    for(int i =0;i<rows;i++)
       Mat[i]=new int[cols];

    for(int i=0;i<rows;i++)
      for(int j=0;j<cols;j++)
        Mat[i][j]=0;
}

Matrix::~Matrix () //destructor
{
    for(int i =0;i<rows;i++)
        delete Mat[i];

    delete[] Mat;
}

Matrix::Matrix(const Matrix &other)  //copy constructor
{
    cols=other.cols;
    rows=other.rows;
    Mat=new int* [other.rows];

    for(int i =0;i<other.rows;i++)
       Mat[i]=new int[other.cols];

    for(int i=0;i<other.rows;i++)
      for(int j=0;j<other.cols;j++)
            Mat[i][j]=other[i][j];
}
</code>```

答:
1) I think deconstructor erases only object that belongs to, because copy-constructed objects have their own destructor.

2) Yes, Mat[i][j] = other.Mat[i][j] is right, but if you want your program to be bit faster, try using pointers (it isn't easy at first time, I know, but when you get used to it isn't that hard ^^)

Body:
I am trying to create a constructor, destructor, and copy constructor for  a matrix class, and I am not so sure if I am doing it well.

In particular, I am not sure about 2 things:

Is the destructor suppose to free memory also for the memory that is allocated in the copy-constructor?

As to the line Mat[i][j]=other[i][j] (see in the code below), I wonder if I should write Mat[i][j]=other.Mat[i][j] instead?

class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (const int &rows,const int &cols);
    Matrix (const Matrix &other);
    ~Matrix ();
};

Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
    rows=n_rows;
    cols=n_cols;
    Mat=new int* [cols];

    for(int i =0;i<rows;i++)
       Mat[i]=new int[cols];

    for(int i=0;i<rows;i++)
      for(int j=0;j<cols;j++)
        Mat[i][j]=0;
}

Matrix::~Matrix () //destructor
{
    for(int i =0;i<rows;i++)
        delete Mat[i];

    delete[] Mat;
}

Matrix::Matrix(const Matrix &other)  //copy constructor
{
    cols=other.cols;
    rows=other.rows;
    Mat=new int* [other.rows];

    for(int i =0;i<other.rows;i++)
       Mat[i]=new int[other.cols];

    for(int i=0;i<other.rows;i++)
      for(int j=0;j<other.cols;j++)
            Mat[i][j]=other[i][j];
}


问:
Having difficulties printing out my board in my Snake Game
I am not an expert on java and have run into an issue on my Snake Game. I have created a class called GameManager:

```<code>public class GameManager {

  private GameObject board[][];
  private int xR;
  private int yR;
  public Snake snk;
  private Food food;

  public GameManager (String fileName) {
      BufferedReader fileInput = null;

      try {
          fileInput = new BufferedReader(new FileReader(fileName));
          Scanner fileScanner = new Scanner(fileInput);
          int rows = fileScanner.nextInt();
          int cols = fileScanner.nextInt();

          board = new GameObject[rows][cols];
          for (int row = 0; row < rows; row++) {
              for (int col = 0; col < cols; col++) {
                  board[row][col] = new Empty();
              }
          }

          while(fileScanner.hasNext()) {
              fileScanner.nextLine();
              int xStart = fileScanner.nextInt();
              int yStart = fileScanner.nextInt();
              int xEnd = fileScanner.nextInt();
              int yEnd = fileScanner.nextInt();

            addWall(xStart, yStart, xEnd, yEnd);
        }

        addGameObject(snk);
        addGameObject(food);

        fileScanner.close();

    } catch(IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(fileInput != null) {fileInput.close();}
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

public void newRandomXY() {
    Random r = new Random(0);
    this.xR = r.nextInt(board.length);
    this.yR = r.nextInt(board.length);
}

public void addGameObject(GameObject s) {
    newRandomXY();
    while(board[xR][yR].isOccupied()) {
        newRandomXY();
    }

    if(s instanceof Snake) {
        s = new Snake(xR, yR);
        board[xR][yR] = s;
    } else if(s instanceof Food) {
        s = new Food(xR, yR);
        board[xR][yR] = s;
    }
}

public void addWall(int xStart, int yStart, int xEnd, int yEnd) {
    for(int x = xStart; x <= xEnd; x++) {
        for(int y = yStart; y <= yEnd; y++) {
            board[x][y] = new Wall();
        }
    }
}

@Override
public String toString() {

    String ret = "";
    for (int row = 0; row < board.length; row++) {
        for (int col = 0; col < board[row].length; col++) {
            ret += board[row][col].toString();
        }
        ret += "\n";
    }
    return ret;
}
</code>```

}

Now the issue I'm having is that whenever I try to print a string version of this board on my cmd, the program just hangs and I have to hard close the cmd. I have been messing around with some of the code and I have been able to fix the program just crashing, but I haven't been able to figure why its all not printing out.

Here is my Snake Class (Note: I also have some other methods in this class that I am not using at the moment, so I don't think they are the issue):

```<code>public class Snake extends GameObject {
    private Point head;
    private Deque<Point> snakeBody;
    private int lenght = 0;
    private String direction = "UP";

    public Snake(int x, int y) {
        this.head = super.newCell(x, y);
        this.snakeBody = new ArrayDeque<Point>();
        this.snakeBody.push(head);
    }
</code>```

and my toString of Snake:

```<code> public String toString(Deque<Point> s) {
        String str = "";
        for(Point p : s) {
            String snk = p.toString();
            snk = "S";
            str += snk;
        }
        return str;
    }
</code>```

Here's my Food Class:

```<code>public class Food extends GameObject {
    private Point foodLoc;

    public Food(int x, int y) {
        this.foodLoc = new Point(x, y);
    }

    public Point getLocation() {
        return foodLoc.getLocation();
    }

    public String toString() {
        return "F";
    }
}
</code>```

and here is my GameObject Class:

```<code>import java.awt.Point;

public class GameObject {

    public final int CELL_SIZE = 1;

    public Point newCell(int x, int y) {
        return new Point(x, y);
    }

    public boolean isOccupied() {
        return true;
    }

    public boolean isOccupied(Point p, Point o) {
        boolean flag = false;
        if(p.getLocation().equals(o.getLocation())) {
            flag = true;
        } else {
            flag = false;
        }

        return flag;
    }

}
</code>```

I have a good feeling that my toString method in Snake is completely wrong, but I don't necessarily understand how to fix it and why my other toString methods don't work. I have looked around the forums to see if I could find and answer, but I couldn't find anything for this.

答:
The problem is that you're trying to print an array of type gameObject, but that object does not have a .toString operator, so it's always going to return null.

I'm guessing that you want to represent the cells as either empty or occupied, or perhaps even further by having food, but you'd need a .toString in that class to define what you want returned in whatever given scenario.

Body:
I am not an expert on java and have run into an issue on my Snake Game. I have created a class called GameManager:

public class GameManager {

  private GameObject board[][];
  private int xR;
  private int yR;
  public Snake snk;
  private Food food;

  public GameManager (String fileName) {
      BufferedReader fileInput = null;

      try {
          fileInput = new BufferedReader(new FileReader(fileName));
          Scanner fileScanner = new Scanner(fileInput);
          int rows = fileScanner.nextInt();
          int cols = fileScanner.nextInt();

          board = new GameObject[rows][cols];
          for (int row = 0; row < rows; row++) {
              for (int col = 0; col < cols; col++) {
                  board[row][col] = new Empty();
              }
          }

          while(fileScanner.hasNext()) {
              fileScanner.nextLine();
              int xStart = fileScanner.nextInt();
              int yStart = fileScanner.nextInt();
              int xEnd = fileScanner.nextInt();
              int yEnd = fileScanner.nextInt();

            addWall(xStart, yStart, xEnd, yEnd);
        }

        addGameObject(snk);
        addGameObject(food);

        fileScanner.close();

    } catch(IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(fileInput != null) {fileInput.close();}
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

public void newRandomXY() {
    Random r = new Random(0);
    this.xR = r.nextInt(board.length);
    this.yR = r.nextInt(board.length);
}

public void addGameObject(GameObject s) {
    newRandomXY();
    while(board[xR][yR].isOccupied()) {
        newRandomXY();
    }

    if(s instanceof Snake) {
        s = new Snake(xR, yR);
        board[xR][yR] = s;
    } else if(s instanceof Food) {
        s = new Food(xR, yR);
        board[xR][yR] = s;
    }
}

public void addWall(int xStart, int yStart, int xEnd, int yEnd) {
    for(int x = xStart; x <= xEnd; x++) {
        for(int y = yStart; y <= yEnd; y++) {
            board[x][y] = new Wall();
        }
    }
}

@Override
public String toString() {

    String ret = "";
    for (int row = 0; row < board.length; row++) {
        for (int col = 0; col < board[row].length; col++) {
            ret += board[row][col].toString();
        }
        ret += "\n";
    }
    return ret;
}

}

Now the issue I'm having is that whenever I try to print a string version of this board on my cmd, the program just hangs and I have to hard close the cmd. I have been messing around with some of the code and I have been able to fix the program just crashing, but I haven't been able to figure why its all not printing out.

Here is my Snake Class (Note: I also have some other methods in this class that I am not using at the moment, so I don't think they are the issue):

public class Snake extends GameObject {
    private Point head;
    private Deque<Point> snakeBody;
    private int lenght = 0;
    private String direction = "UP";

    public Snake(int x, int y) {
        this.head = super.newCell(x, y);
        this.snakeBody = new ArrayDeque<Point>();
        this.snakeBody.push(head);
    }

and my toString of Snake:

 public String toString(Deque<Point> s) {
        String str = "";
        for(Point p : s) {
            String snk = p.toString();
            snk = "S";
            str += snk;
        }
        return str;
    }

Here's my Food Class:

public class Food extends GameObject {
    private Point foodLoc;

    public Food(int x, int y) {
        this.foodLoc = new Point(x, y);
    }

    public Point getLocation() {
        return foodLoc.getLocation();
    }

    public String toString() {
        return "F";
    }
}

and here is my GameObject Class:

import java.awt.Point;

public class GameObject {

    public final int CELL_SIZE = 1;

    public Point newCell(int x, int y) {
        return new Point(x, y);
    }

    public boolean isOccupied() {
        return true;
    }

    public boolean isOccupied(Point p, Point o) {
        boolean flag = false;
        if(p.getLocation().equals(o.getLocation())) {
            flag = true;
        } else {
            flag = false;
        }

        return flag;
    }

}

I have a good feeling that my toString method in Snake is completely wrong, but I don't necessarily understand how to fix it and why my other toString methods don't work. I have looked around the forums to see if I could find and answer, but I couldn't find anything for this.


问:
How to install 'warnings' package in Python?
I've seen Python programs using

```<code>import warnings
</code>```

How to install that package? I tried

```<code>pip install --upgrade warnings
</code>```

and got an error

```<code>Collecting warnings
  Could not find a version that satisfies the requirement warnings (from versions: )
No matching distribution found for warnings
</code>```

答: warnings is builtin. No need to install it.

Body:
I've seen Python programs using

import warnings

How to install that package? I tried

pip install --upgrade warnings

and got an error

Collecting warnings
  Could not find a version that satisfies the requirement warnings (from versions: )
No matching distribution found for warnings


问:
Issues writing doubles to files, writing nothing
I seem to be missing something when it comes to writing doubles to text files, when I check the file, just blank space is present. When I read from the file and print with System.out.println(); it just prints nothing... What's going wrong here? Do I need to do some converting?</p>

```<code>import java.io.*;
import javax.swing.JOptionPane;

public class ReadCalcAveragePrint  {

    double firstNum;
    double secondNum;
    double average;

    public void readFile() {

        try {
            File f = new File("numbers.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            String two = br.readLine();
            firstNum = Double.parseDouble(one);
            secondNum = Double.parseDouble(two);

            average = (firstNum + secondNum) / 2;
            JOptionPane.showMessageDialog(null, average, "title", JOptionPane.PLAIN_MESSAGE);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public void writeFile() {
        try {
            File f = new File("result.txt");
            FileOutputStream fos = new FileOutputStream(f);
            DataOutputStream dos = new DataOutputStream(fos);
            dos.writeDouble(average);
            dos.flush();
            fos.close();
            System.out.println("Printed.");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);

        }
    }

    public void readResult() {

        try {
            File f = new File("result.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            System.out.println(one);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public static void main(String[] args) {

        new ReadCalcAveragePrint().readFile();
        new ReadCalcAveragePrint().writeFile();
        new ReadCalcAveragePrint().readResult();
    }
}
</code>```

答:
see the javadoc of writeDouble:

Converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.

you write 8 bytes that may not be assigned to any alphanumeric character. Then you read it a line as a String (characters up to the next 'new line' char).
In this case, the 'new line' char can be anywhere, or nowhere (depending on the result).

8 bytes in file means almost 4 chars, very likely, no one is a "visible character".

Try to read a byte[8] from the InputStream (not from a Buffered one), and then put those 8 bytes into DoubleBuffer, then you can get the double value represented by those bytes and writen to the file before.

Body:
I seem to be missing something when it comes to writing doubles to text files, when I check the file, just blank space is present. When I read from the file and print with System.out.println(); it just prints nothing... What's going wrong here? Do I need to do some converting?

import java.io.*;
import javax.swing.JOptionPane;

public class ReadCalcAveragePrint  {

    double firstNum;
    double secondNum;
    double average;

    public void readFile() {

        try {
            File f = new File("numbers.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            String two = br.readLine();
            firstNum = Double.parseDouble(one);
            secondNum = Double.parseDouble(two);

            average = (firstNum + secondNum) / 2;
            JOptionPane.showMessageDialog(null, average, "title", JOptionPane.PLAIN_MESSAGE);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public void writeFile() {
        try {
            File f = new File("result.txt");
            FileOutputStream fos = new FileOutputStream(f);
            DataOutputStream dos = new DataOutputStream(fos);
            dos.writeDouble(average);
            dos.flush();
            fos.close();
            System.out.println("Printed.");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);

        }
    }

    public void readResult() {

        try {
            File f = new File("result.txt");
            BufferedReader br = new BufferedReader(new FileReader(f));
            String one = br.readLine();
            System.out.println(one);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }

    public static void main(String[] args) {

        new ReadCalcAveragePrint().readFile();
        new ReadCalcAveragePrint().writeFile();
        new ReadCalcAveragePrint().readResult();
    }
}


问:
Best practices to deal with the lack of inheritance in Go
I am about to start writing a new application and I was thinking about programming it in Go, which I have no experience with. As Go doesn't support inheritance how would I faithfully translate a domain like this into Go, while still being in accordance with the philosophy of Go?:

A person has 2 legs and 2 arms and can walk.

A musician is a person, has an instrument and can play it, has partitions and can read them. But nobody can be only a musician, as a musicien has and plays a specific instrument.

A violonist is a musician that has a violon and can play the violon

A pianist is a musician that has a piano and can play the piano.

When a violonist/pianist is walking in the streets, everybody only sees him as a person.

Maybe we could reformulate the domain like this to remove any 'is a' relationships so that it would be translatable into Go:

A violinist has a person part, a musician part, a violin and can play the violin

The musician part of a violinist/pianist has partitions and can read them

When a violinist/pianist is walking in the streets, everybody can only see his person part

Etc

Would it be the best practice to model such a domain like this before translating into Go? Is it the way of thinking that the authors of Go want their users to have, when they decided to exclude inheritance in Go?

答:
Go has just another point of view. You can think of objects and interfaces they match. It's closer to you second sentences:

A violinist has a person part, a musician part, a violin and can play the violin

This is interface Musician - it describes any person which have method Play()

```<code>type Musician interface {
    Play()
}
</code>```

For exapmple structure Violinist can have such a method:

```<code>type Violinist struct {}
func (v Violinist) Play() {}
</code>```

Also Pianist can play:

```<code>type Pianist struct {}
func (v Pianist) Play() {}
</code>```

They both match interface Musician. So you can have a musician variable and assign different musicians to it:

```<code>var musician Musician
musician = Violinist{}
musician.Play()
musician = Pianist{}
musician.Play()
</code>```

Look how the same variable changes it's bahaviour. It's the same like Polyformism and not in OOP-way, but  Go-way.

When a violinist/pianist is walking in the streets, everybody can only see his person part

The same way we may define a Walker interface - person who can walk a street and have appropriate method Walk for it:

```<code>type Walker interface {
    Walk()
}
</code>```

It's a sort of duck-typing: in our life if a person can play, it can be taken to the ensemble. In Go terms if a person has method Play() it can be assigned to a musician type variable.

Etc

Next you can make a combined interface embedding these both:

```<code>type WalkingMusician interface {
    Musician
    Walker
}
</code>```

This describes a person which can play and walk at a moment.

```<code>var walkingMusician WalkingMusician
walkingMusician = walkingViolinist
walkingMusician.Walk()
walkingMusician.Play()
</code>```

https://play.golang.org/p/ai-h4VDUpj

Body:
Go has just another point of view. You can think of objects and interfaces they match. It's closer to you second sentences:

A violinist has a person part, a musician part, a violin and can play the violin

This is interface Musician - it describes any person which have method Play()

type Musician interface {
    Play()
}

For exapmple structure Violinist can have such a method:

type Violinist struct {}
func (v Violinist) Play() {}

Also Pianist can play:

type Pianist struct {}
func (v Pianist) Play() {}

They both match interface Musician. So you can have a musician variable and assign different musicians to it:

var musician Musician
musician = Violinist{}
musician.Play()
musician = Pianist{}
musician.Play()

Look how the same variable changes it's bahaviour. It's the same like Polyformism and not in OOP-way, but  Go-way.

When a violinist/pianist is walking in the streets, everybody can only see his person part

The same way we may define a Walker interface - person who can walk a street and have appropriate method Walk for it:

type Walker interface {
    Walk()
}

It's a sort of duck-typing: in our life if a person can play, it can be taken to the ensemble. In Go terms if a person has method Play() it can be assigned to a musician type variable.

Etc

Next you can make a combined interface embedding these both:

type WalkingMusician interface {
    Musician
    Walker
}

This describes a person which can play and walk at a moment.

var walkingMusician WalkingMusician
walkingMusician = walkingViolinist
walkingMusician.Walk()
walkingMusician.Play()

https://play.golang.org/p/ai-h4VDUpj


问:
I need to define __setattr__ for assignment of fields without properties, but use the setter/getter functions for fields with a property defined
Defining __setattr__ overrides all setter methods / properties I define in a class.  I want to use the defined setter methods in the property, if a property exists for a field and use  self.__dict__[name] = value otherwise.

Help!  I found one solution that used __setitem__, but this does not work for me

Where are properties stored in a python class?  How do I access them?

How do I define __setattr__ so that it uses the properties for fields with setter methods defined?

```<code>class test(object):

def _get_gx(self):
    print "get!"
    return self.__dict__['gx']

def _set_gx(self, gx):
    print "set!"
    self.__dict__['gx'] = gx
    gx = property(_get_gx, _set_gx)

def __setattr__(self, name, value):
    self.__dict__[name] = value

def __init__(self):
    pass
</code>```

also,

Why is "get!" printed twice when I do,

```<code>x = test()
x.gx = 4
x.gx

prints:

   "gets!"
   "gets!"
   4
</code>```

答:
You need to rewrite your __setattr__ function. As per the docs, new style classes should use baseclass.__setattr__(self, attr, value) instead of self.__dict__[attr] = value. The former will lookup any descriptors whereas the latter will assign directly to the dict.

So rewrite your method as

```<code>def __setattr__(self, name, value):
    object.__setattr__(self, name, value)
</code>```

or

```<code>def __setattr__(self, name, value):
    super(Test, self).__setattr__(name, value)
</code>```

and you'll be fine. The code

```<code>class Test(object):
    @property
    def gx(self):
        print "getting gx"
        return self.__dict__['gx']

    @gx.setter
    def gx(self, value):
        print "setting gx"
        self.__dict__['gx'] = value

    def __setattr__(self, attr, value):
        print "using setattr"
        object.__setattr__(self, attr, value)

t = Test()
t.gx = 4
t.dummy = 5
print t.gx
print t.dummy

print dir(Test)
</code>```

outputs

```<code>using setattr
setting gx
getting gx
using setattr
4
5
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'gx']
</code>```

I don't know why your version is calling the getter twice. This one doesn't. Also, to answer your question about where descriptors live, you can plainly see it as the last entry in the class dict.

It's worth noting that you don't need __setattr__ to do what you want in your example. Python will always write an assignment foo.bar = x to foo.__dict__['bar'] = x regardless of if there's an entry in foo.__dict__ or not. __setattr__ is for when you want to transform the value or log the assignment or something like that.

Body:
Defining __setattr__ overrides all setter methods / properties I define in a class.  I want to use the defined setter methods in the property, if a property exists for a field and use  self.__dict__[name] = value otherwise.

Help!  I found one solution that used __setitem__, but this does not work for me

Where are properties stored in a python class?  How do I access them?

How do I define __setattr__ so that it uses the properties for fields with setter methods defined?

class test(object):

def _get_gx(self):
    print "get!"
    return self.__dict__['gx']

def _set_gx(self, gx):
    print "set!"
    self.__dict__['gx'] = gx
    gx = property(_get_gx, _set_gx)

def __setattr__(self, name, value):
    self.__dict__[name] = value

def __init__(self):
    pass

also,

Why is "get!" printed twice when I do,

x = test()
x.gx = 4
x.gx

prints:

   "gets!"
   "gets!"
   4

Body:
You need to rewrite your __setattr__ function. As per the docs, new style classes should use baseclass.__setattr__(self, attr, value) instead of self.__dict__[attr] = value. The former will lookup any descriptors whereas the latter will assign directly to the dict.

So rewrite your method as

def __setattr__(self, name, value):
    object.__setattr__(self, name, value)

or

def __setattr__(self, name, value):
    super(Test, self).__setattr__(name, value)

and you'll be fine. The code

class Test(object):
    @property
    def gx(self):
        print "getting gx"
        return self.__dict__['gx']

    @gx.setter
    def gx(self, value):
        print "setting gx"
        self.__dict__['gx'] = value

    def __setattr__(self, attr, value):
        print "using setattr"
        object.__setattr__(self, attr, value)

t = Test()
t.gx = 4
t.dummy = 5
print t.gx
print t.dummy

print dir(Test)

outputs

using setattr
setting gx
getting gx
using setattr
4
5
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'gx']

I don't know why your version is calling the getter twice. This one doesn't. Also, to answer your question about where descriptors live, you can plainly see it as the last entry in the class dict.

It's worth noting that you don't need __setattr__ to do what you want in your example. Python will always write an assignment foo.bar = x to foo.__dict__['bar'] = x regardless of if there's an entry in foo.__dict__ or not. __setattr__ is for when you want to transform the value or log the assignment or something like that.


问:
How to Load External JS and URL in Joomla Protostar Template
I am looking to add a hamburger menu to my joomla protostar template similar to the one found on the following URL:

```<code>['https://codepen.io/PaulVanO/pen/GgGeyE']
</code>```

This will allow me to have a fullscreen hamburger menu for my desktop and mobile screen. The problem I am having is that within the files from the above link there are 3 links, 2 to external JS files and 1 CSS file and I am not sure how I can write this into a Protostar Template. The following are the three links:

```<code><link rel='stylesheet prefetch' href='http://daneden.github.io/animate.css/animate.min.css'>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/wow/0.1.12/wow.min.js'></script>
<script  src="js/index.js"></script>
</code>```

I would really appreciate it if somebody could advise on how I can add the above scripts to my file in order for me to build this within Joomla.

Currently I am using Joomla version 3.8.2.

Thanks in advance.

答:
here is an example from the manual</p>

```<code><?php
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js');
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
?>
</code>```

Body:
I am looking to add a hamburger menu to my joomla protostar template similar to the one found on the following URL:

['https://codepen.io/PaulVanO/pen/GgGeyE']

This will allow me to have a fullscreen hamburger menu for my desktop and mobile screen. The problem I am having is that within the files from the above link there are 3 links, 2 to external JS files and 1 CSS file and I am not sure how I can write this into a Protostar Template. The following are the three links:

<link rel='stylesheet prefetch' href='http://daneden.github.io/animate.css/animate.min.css'>

I would really appreciate it if somebody could advise on how I can add the above scripts to my file in order for me to build this within Joomla.

Currently I am using Joomla version 3.8.2.

Thanks in advance.

Body:
here is an example from the manual

<?php
$document = JFactory::getDocument();
$document->addScript('/media/system/js/sample.js');
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
?>


问:
Match and replace misspelled words in a string in R
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

```<code>library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"
</code>```

everything works perfectly, until it finds a similar string, and replaces it with another word

if I have a pattern like the following:

"plea", the correct one is "please", but when I execute it removes it and replaces it with "pleased".

What I am looking for is that if a string is already correct, it is no longer modified, in case it finds a similar pattern.

答:
str_replace_all takes regex as the pattern, so you can paste0 word boundaries \\b around each badwords so that a replacement will only be made if the whole word is matched:

```<code>library(stringr)
string <- c("tre", "tree", "teeasing", "tesing")
goodwords <- c("tree", "three", "teasing", "testing")
badwords <- c("tre", "thre", "teeasing", "tesing")

# Paste word boundaries around badwords
badwords <- paste0("\\b", badwords, "\\b")

vect.corpus <- goodwords
names(vect.corpus) <- badwords

str_replace_all(string, vect.corpus)
[1] "tree"    "tree"    "teasing" "testing"
</code>```

The advantage of this is that you don't have to keep track of which strings are the longer strings.

This is what badwords looks like after pasting:

```<code>> badwords
[1] "\\btre\\b"      "\\bthre\\b"     "\\bteeasing\\b" "\\btesing\\b"
</code>```

Body:
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"

everything works perfectly, until it finds a similar string, and replaces it with another word

if I have a pattern like the following:

"plea", the correct one is "please", but when I execute it removes it and replaces it with "pleased".

What I am looking for is that if a string is already correct, it is no longer modified, in case it finds a similar pattern.

Body:
str_replace_all takes regex as the pattern, so you can paste0 word boundaries \\b around each badwords so that a replacement will only be made if the whole word is matched:

library(stringr)
string <- c("tre", "tree", "teeasing", "tesing")
goodwords <- c("tree", "three", "teasing", "testing")
badwords <- c("tre", "thre", "teeasing", "tesing")

# Paste word boundaries around badwords
badwords <- paste0("\\b", badwords, "\\b")

vect.corpus <- goodwords
names(vect.corpus) <- badwords

str_replace_all(string, vect.corpus)
[1] "tree"    "tree"    "teasing" "testing"

The advantage of this is that you don't have to keep track of which strings are the longer strings.

This is what badwords looks like after pasting:

> badwords
[1] "\\btre\\b"      "\\bthre\\b"     "\\bteeasing\\b" "\\btesing\\b"


问:
Query columns with a particular data type from a table (postgreSQL)
I have a table with 100+ columns with char, int, and numeric datatypes
but I don't know how they are placed within the table. Is it possible
to query columns with only one of those datatypes?  </p>

<p>I have tried for 'numeric' type where I find the column names from
information_schema. I then used 'with' and tried to use that to
extract the columns that matches with the query contained in 'with'.
It didn't work because the 'column_name' in the last line is not
valid. Any suggestion how to get it right?  </p>

```<code>WITH numeric_columns AS
    (SELECT column_name from information_schema.columns
    WHERE table_schema='table_admin' and
    table_name='my_table'
    AND data_type='numeric')
SELECT * from table_admin.my_table
WHERE column_name (????) IN (SELECT * FROM numeric_columns);
</code>```

答:
You need a dynamic SQL in a plpgsql function. Because the number of columns is unknown you have to merge them in some way into a single column. One of suitable ways is to use jsonb.

Example function:

```<code>create or replace function numeric_cols(sname text, tname text)
returns setof jsonb language plpgsql as $$
declare
    select_list text;
begin
    select string_agg(column_name, ',')
    into select_list
    from information_schema.columns
    where table_schema = sname
    and table_name = tname
    and data_type = 'numeric';

    return query
    execute format($fmt$
        select to_jsonb(t)
        from (
            select %s
            from %I.%I
            ) t
        $fmt$, select_list, sname, tname);
end $$;
</code>```

Example usage:

```<code>create schema if not exists table_admin;
create table table_admin.my_table(id serial primary key, n1 numeric, n2 numeric, t1 text);
insert into table_admin.my_table (n1, n2, t1) values
(100, 200, 'first'),
(200, 300, 'second');

select *
from numeric_cols('table_admin', 'my_table');

      numeric_cols
------------------------
 {"n1": 100, "n2": 200}
 {"n1": 200, "n2": 300}
(2 rows)
</code>```

Body:
I have a table with 100+ columns with char, int, and numeric datatypes
but I don't know how they are placed within the table. Is it possible
to query columns with only one of those datatypes?

I have tried for 'numeric' type where I find the column names from
information_schema. I then used 'with' and tried to use that to
extract the columns that matches with the query contained in 'with'.
It didn't work because the 'column_name' in the last line is not
valid. Any suggestion how to get it right?

WITH numeric_columns AS
    (SELECT column_name from information_schema.columns
    WHERE table_schema='table_admin' and
    table_name='my_table'
    AND data_type='numeric')
SELECT * from table_admin.my_table
WHERE column_name (????) IN (SELECT * FROM numeric_columns);

Body:
You need a dynamic SQL in a plpgsql function. Because the number of columns is unknown you have to merge them in some way into a single column. One of suitable ways is to use jsonb.

Example function:

create or replace function numeric_cols(sname text, tname text)
returns setof jsonb language plpgsql as $$
declare
    select_list text;
begin
    select string_agg(column_name, ',')
    into select_list
    from information_schema.columns
    where table_schema = sname
    and table_name = tname
    and data_type = 'numeric';

    return query
    execute format($fmt$
        select to_jsonb(t)
        from (
            select %s
            from %I.%I
            ) t
        $fmt$, select_list, sname, tname);
end $$;

Example usage:

create schema if not exists table_admin;
create table table_admin.my_table(id serial primary key, n1 numeric, n2 numeric, t1 text);
insert into table_admin.my_table (n1, n2, t1) values
(100, 200, 'first'),
(200, 300, 'second');

select *
from numeric_cols('table_admin', 'my_table');

      numeric_cols
------------------------
 {"n1": 100, "n2": 200}
 {"n1": 200, "n2": 300}
(2 rows)


问:
How array of uibutton to apply different colors each
I would like to apply different color (by the code) at different uiButton.
I thinked to create 2 arrays. The first with my uiButtons, and the other with differents colors.
After that, to make a first loop with my buttons, and inside this loop, to make an other loop with the colors (random result). The last step, apply the colors at the button.
Can this way work?</p>

答:
You can do that by making use of this answer.</p>

```<code>let numberOfButton = 10
var buttons = [UIButton]()

for _ in 0..<numberOfButton {
    let button = UIButton()
    button.setTitleColor(.random(), for: .normal)
    buttons.append(button)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can do that by making use of this answer.

let numberOfButton = 10
var buttons = [UIButton]()

for _ in 0..<numberOfButton {
    let button = UIButton()
    button.setTitleColor(.random(), for: .normal)
    buttons.append(button)
}


问:
What's the correct way to get a list of users in this bash script?
I have a script that checks each user's home directory for the existence of a maildir and archives old emails accordingly. The way I was doing this is basically this:

```<code>for USER in $(ls /home)
do
<function to check for maildir and remove old files>
</code>```

I ran my script through shellcheck and it gave the the warning

SC2045 - Iterating over ls output is fragile. Use globs.

If I change my script to use for USER in /home/*, it changes the value of $USER:

```<code>for USER in $(ls /home); do echo $USER ; done;
</code>```

gives:

```<code>user1
user2
user3
</code>```

But

```<code>for USER in /home/*; do echo $USER ; done;
</code>```

gives:

```<code>/home/user1
/home/user2
/home/user3
</code>```

and breaks my script in later places.

If I start doing things like parsing /etc/passwd for usernames I'd then need to check if they have home directories etc so it would make the script more complicated for the sake of following best practice. I couldn't work out a way to grep -v out the "/home/" part of the variable values from the second example. What's the correct way to do this?

答:
You can use grep's Perl mode grep -P such as:

```<code>for USER in /home/*; do
    echo $USER | grep -Po "(?<=/home/).*"
done
</code>```

The (?<=/home/) represents a lookbehind, which will not be considered part of the match, and won't be printed because of the -o. This has the advantage of not requiring you to cd to the home directory and back, and besides, grep -Po is incredibly useful to know about.

Alternatively using find (which is also a very useful program), you can do:

```<code>find /home -mindepth 1 -maxdepth 1 -type d -printf '%f\n'
</code>```

Body:
I have a script that checks each user's home directory for the existence of a maildir and archives old emails accordingly. The way I was doing this is basically this:

for USER in $(ls /home)
do
<function to check for maildir and remove old files>

I ran my script through shellcheck and it gave the the warning

SC2045 - Iterating over ls output is fragile. Use globs.

If I change my script to use for USER in /home/*, it changes the value of $USER:

for USER in $(ls /home); do echo $USER ; done;

gives:

user1
user2
user3

But

for USER in /home/*; do echo $USER ; done;

gives:

/home/user1
/home/user2
/home/user3

and breaks my script in later places.

If I start doing things like parsing /etc/passwd for usernames I'd then need to check if they have home directories etc so it would make the script more complicated for the sake of following best practice. I couldn't work out a way to grep -v out the "/home/" part of the variable values from the second example. What's the correct way to do this?

Body:
You can use grep's Perl mode grep -P such as:

for USER in /home/*; do
    echo $USER | grep -Po "(?<=/home/).*"
done

The (?<=/home/) represents a lookbehind, which will not be considered part of the match, and won't be printed because of the -o. This has the advantage of not requiring you to cd to the home directory and back, and besides, grep -Po is incredibly useful to know about.

Alternatively using find (which is also a very useful program), you can do:

find /home -mindepth 1 -maxdepth 1 -type d -printf '%f\n'


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答:
Have you profiled your code to show that the sort is a bottleneck?  If it isn't a bottleneck, then speeding it up won't buy you much.  Sorting eight short integers is pretty fast.

In general, std::sort() will be faster than anything you can write, unless you are a real sorting guru.


问:
for loop in while (building matrix)
It builts each number[i][j] of matrix and after every number it checks by comparing the number[i][j] with the numbers[k][l] before it.

At first it passes because of not having numbers before.

Real goal is to make a matrix with all different numbers.
I'm trying to return start of checking the numbers of matrix so that at any encounter of beeing same it will restart checking.

(it changes numbers if any are same. After changing, the number which is changed can be same with anyone at start of matrix too so i want check again at any change)

```<code>int matris[10][10];

int counter = 0;

bool control = true;

for (int i = 0; i<10; i++) {

    for (int j = 0; j<10; j++) {

        matris[i][j] = rand() % 99;
        do {
            for (int k = 0; k <= i; k++) {

                for (int l = 0; l <= j; l++) {
                    if (matris[i][j] == matris[k][l])
                    {
                        matris[i][j] = rand() % 99;
                        counter++;
                       if(k==i&&l==j)break;
                        control = false;
                    }
                     else control=true;

                }

            }

        } while (control == false);

    }

}
</code>```

It is not important if values it writes is 99-0 or 100-1.My teacher asked us for numbers between 100-1.

The real problem is it doesn't control back with while.It sometimes gives same numbers.It should't.

counter = how many times do numbers changed.

Here results..

counter:124
Matrix:
  54  68  83  55  12  30  97  96  63  91
  52  55   8   6  96  46  55  14  65  93
  52  94  39   6  92  40  12  86  66  61
  11  33  77  46  97   6  16  28  28  46
  17  72  16  75  93  81  61  82  34  19
  93  72  96  34  48  49  29  54  81  94
  72  27  13   8  22  52  12  96  35  66
  87  84  79  10  52  24  45  49  82  48
  32  64  34  32  82  85  70  72  97  55
  44  93   9  86  10   4  33  25  32  99

You can see if there are same numbers, there it's ranked.
  99  97  97  97  96  96  96  96  94  94
  93  93  93  93  92  91  87  86  86  85
  84  83  82  82  82  81  81  79  77  75
  72  72  72  72  70  68  66  66  65  64
  63  61  61  55  55  55  55  54  54  52
  52  52  52  49  49  48  48  46  46  46
  45  44  40  39  35  34  34  34  33  33
  32  32  32  30  29  28  28  27  25  24
  22  19  17  16  16  14  13  12  12  12
  11  10  10   9   8   8   6   6   6   4
Press any key to continue . . .

答:
Actually do-while works well but inside it you are using for (int k = 0; k < i; k++) which iterates up to i-1 and say if you put your 6th element in your matrix you are only checking up to 5th element and skipping the 6th one. you may try (int k = 0; k < i+1; k++) instead.

Another approach is if you want all numbers 0-99 in your matrix put them in first then scramble the matrix by randomly swapping locations... this should do the trick.

```<code>#include <iostream>

using namespace std;

int main() {
    int matris[10][10];
    int sayac = 0;

    // put all of them in first
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            matris[i][j] = sayac;
            sayac++;
        }
    }

    // then scramble
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            int tmp,k ,l;
            k = rand()%9;
            l = rand()%9;
            tmp = matris[i][j];
            matris[i][j] = matris[k][l];
            matris[k][l] = tmp;
        }
    }

    // check the result
    for (int i = 0; i<10; i++) {
        for (int j = 0; j < 10; j++) {
            cout << matris[i][j] << "\t";
        }
        cout << endl;
    }
    return 0;
}
</code>```

to see different results each time you need to use rand()  function with a seed which is usually the system clock.

Title: for loop in while (building matrix)

Body:
It builts each number[i][j] of matrix and after every number it checks by comparing the number[i][j] with the numbers[k][l] before it.

At first it passes because of not having numbers before.

Real goal is to make a matrix with all different numbers.
I'm trying to return start of checking the numbers of matrix so that at any encounter of beeing same it will restart checking.

(it changes numbers if any are same. After changing, the number which is changed can be same with anyone at start of matrix too so i want check again at any change)

int matris[10][10];

int counter = 0;

bool control = true;

for (int i = 0; i<10; i++) {

    for (int j = 0; j<10; j++) {

        matris[i][j] = rand() % 99;
        do {
            for (int k = 0; k <= i; k++) {

                for (int l = 0; l <= j; l++) {
                    if (matris[i][j] == matris[k][l])
                    {
                        matris[i][j] = rand() % 99;
                        counter++;
                       if(k==i&&l==j)break;
                        control = false;
                    }
                     else control=true;

                }

            }

        } while (control == false);

    }

}

It is not important if values it writes is 99-0 or 100-1.My teacher asked us for numbers between 100-1.

The real problem is it doesn't control back with while.It sometimes gives same numbers.It should't.

counter = how many times do numbers changed.

Here results..

counter:124
Matrix:
  54  68  83  55  12  30  97  96  63  91
  52  55   8   6  96  46  55  14  65  93
  52  94  39   6  92  40  12  86  66  61
  11  33  77  46  97   6  16  28  28  46
  17  72  16  75  93  81  61  82  34  19
  93  72  96  34  48  49  29  54  81  94
  72  27  13   8  22  52  12  96  35  66
  87  84  79  10  52  24  45  49  82  48
  32  64  34  32  82  85  70  72  97  55
  44  93   9  86  10   4  33  25  32  99

You can see if there are same numbers, there it's ranked.
  99  97  97  97  96  96  96  96  94  94
  93  93  93  93  92  91  87  86  86  85
  84  83  82  82  82  81  81  79  77  75
  72  72  72  72  70  68  66  66  65  64
  63  61  61  55  55  55  55  54  54  52
  52  52  52  49  49  48  48  46  46  46
  45  44  40  39  35  34  34  34  33  33
  32  32  32  30  29  28  28  27  25  24
  22  19  17  16  16  14  13  12  12  12
  11  10  10   9   8   8   6   6   6   4
Press any key to continue . . .

Body:
Actually do-while works well but inside it you are using for (int k = 0; k < i; k++) which iterates up to i-1 and say if you put your 6th element in your matrix you are only checking up to 5th element and skipping the 6th one. you may try (int k = 0; k < i+1; k++) instead.

Another approach is if you want all numbers 0-99 in your matrix put them in first then scramble the matrix by randomly swapping locations... this should do the trick.

#include <iostream>

using namespace std;

int main() {
    int matris[10][10];
    int sayac = 0;

    // put all of them in first
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            matris[i][j] = sayac;
            sayac++;
        }
    }

    // then scramble
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            int tmp,k ,l;
            k = rand()%9;
            l = rand()%9;
            tmp = matris[i][j];
            matris[i][j] = matris[k][l];
            matris[k][l] = tmp;
        }
    }

    // check the result
    for (int i = 0; i<10; i++) {
        for (int j = 0; j < 10; j++) {
            cout << matris[i][j] << "\t";
        }
        cout << endl;
    }
    return 0;
}

to see different results each time you need to use rand()  function with a seed which is usually the system clock.


问:
In Microsoft Access, what are the relationships between CodeData, CodeProject, and DAO..?
What are the differences between the following sets of Microsoft Access VBA collections..? Some of them seem to point to the same data & child objects, but through different conduits. I'm thinking the DAO objects are DBMS-specific, but Access.⃰ Code.⃰  and Access.⃰ Project.⃰  are not, and get connected through Access. There is ADODB, which is another beast entirely. Also, it seems some of the collections may not exist if there no child objects of that type.

Given the mentions of SQL features, there seem to be three scenarios to be concerned with, but it's difficult to grasp:

A standalone ACCDB file.

A split database with two or more ACCDB
files.

An Access frontend to an SQL server.

Object set #1:

Access.CodeData.AllTables

Access.CodeData.AllQueries

Access.CodeData.AllFunctions

Access.CodeData.AllDatabaseDiagrams

Access.CodeData.AllStoredProcedures

Access.CodeData.AllViews

Access.CodeProject.AllForms

Access.CodeProject.AllMacros

Access.CodeProject.AllModules

Access.CodeProject.AllReports

And of course CodeData vs. CurrentData and CodeProject vs. CurrentProject.

Object set #2:

Access.Application.CodeData.*

Access.Application.CodeProject.*

Object set #3:

Access.Application.CurrentDb.QueryDefs (DAO.QueryDefs)

Access.Application.CurrentDb.Relations (DAO.Relations)

Access.Application.CurrentDb.TableDefs (DAO.TableDefs)

答:
The biggest difference is in the type of database you are working with. A standard Microsoft Access database (*.accdb) will primarily use the CurrentDB/CodeDB object to reference the database objects.

An ADP Project, on the other hand, is kind of a hybrid with some data on the SQL server (tables, queries, etc...) accessed through CurrentData/CodeData and other objects like forms and reports residing in the *.adp file and accessed through CurrentProject/CodeProject.

The difference between CurrentDB and CodeDB comes into play when you have multiple database files involved, such as other Access databases referenced as library databases. Those library databases might have functions to interact with the parent application, and others that reference the library.


问:
Emacs Orgmode, what does the `/` mean in a repeating task
I am using Emacs Orgmode 9.1.3 to track habit and I saw a very useful habit template below. However I was not sure what the forward slash / meant in the date.

```<code>* NEXT HABIT
[2017-12-07 Thu 10:26]

SCHEDULED: <2017-12-07 Thu .+1d/3d>
:PROPERTIES:
:STYLE: habit
:REPEAT_TO_STATE: NEXT
:END:
</code>```

I read through the org documentation but there is no mention of the forward slash in setting a repeated task.

There is a reference to some sort of reminder like this:

```<code>DEADLINE: <2005-10-01 Sat +1m -3d>.
</code>```

which will provide a reminder three days in advance of a task due date.

Does anyone know what the forward slash does?

答:
You looked in the wrong section of the documentation: this notation applies to habits where you find:

The TODO may also have minimum and maximum ranges specified by using the syntax ‘.+2d/3d’, which says that you want to do the task at least every three days, but at most every two days.

Body:
I am using Emacs Orgmode 9.1.3 to track habit and I saw a very useful habit template below. However I was not sure what the forward slash / meant in the date.

* NEXT HABIT
[2017-12-07 Thu 10:26]

SCHEDULED: <2017-12-07 Thu .+1d/3d>
:PROPERTIES:
:STYLE: habit
:REPEAT_TO_STATE: NEXT
:END:

I read through the org documentation but there is no mention of the forward slash in setting a repeated task.

There is a reference to some sort of reminder like this:

DEADLINE: <2005-10-01 Sat +1m -3d>.

which will provide a reminder three days in advance of a task due date.

Does anyone know what the forward slash does?


问:
Unable to declare Interface " async Task<myObject> MyMethod(Object myObj); "
I'm unable to declare

```<code>interface IMyInterface
{
   async Task<myObject> MyMethod(Object myObj);
}
</code>```

The compiler tells me:

The modifier async isn't valid for this item

The async modifier can only be used for methods that have a body

Is this something that should be implemented, or does the nature of async & await prohibit this from ever occurring?

答:
If you have an interface with two implementations (one that is truly async and the other that is synchronous) this is what it would look like for each implementation - with both returning a Task<bool>.

```<code>public interface IUserManager
{
    Task<bool> IsUserInRole(string roleName);
}

public class UserManager1 : IUserManager
{
    public async Task<bool> IsUserInRole(string roleName)
    {
        return await _userManager.IsInRoleAsync(_profile.Id, roleName);
    }
}

public class UserManager2 : IUserManager
{
    public Task<bool> IsUserInRole(string roleName)
    {
        return Task.FromResult(Roles.IsUserInRole(roleName));
    }
}
</code>```

If it is a void method you need to return Task.CompletedTask; from the non async method
(I think .NET 4.5 and later)

See also : Return Task<bool> instantly

Body:
I'm unable to declare

interface IMyInterface
{
   async Task<myObject> MyMethod(Object myObj);
}

The compiler tells me:

The modifier async isn't valid for this item

The async modifier can only be used for methods that have a body

Is this something that should be implemented, or does the nature of async & await prohibit this from ever occurring?

Body:
If you have an interface with two implementations (one that is truly async and the other that is synchronous) this is what it would look like for each implementation - with both returning a Task<bool>.

public interface IUserManager
{
    Task<bool> IsUserInRole(string roleName);
}

public class UserManager1 : IUserManager
{
    public async Task<bool> IsUserInRole(string roleName)
    {
        return await _userManager.IsInRoleAsync(_profile.Id, roleName);
    }
}

public class UserManager2 : IUserManager
{
    public Task<bool> IsUserInRole(string roleName)
    {
        return Task.FromResult(Roles.IsUserInRole(roleName));
    }
}

If it is a void method you need to return Task.CompletedTask; from the non async method
(I think .NET 4.5 and later)

See also : Return Task<bool> instantly


答:
As you should already know (since I told you here), you can store code in external databases, and refer to that code from another database.

The code in this external database might rely on certain tables, queries and forms to be present. But since it's ran on another database, they might not be.

That's where CodeDb, CodeProject and CodeData come in. They're fully equivalent to the variants starting with Current, only refer to the database where the code is stored, instead of the database which is currently open.

Differences between CurrentDb, CurrentProject and CurrentData is really asking for differences between apples, pears and oranges. They're all objects, but fulfill different functions. As ThunderFrame noted, CurrentDb is mostly DAO, and CurrentProject contains some ADO functionality (mostly just the connection), but also functions to influence the VBA part of the database, the database path, and many other functions. And CurrentData is something else entirely.

Title: In Microsoft Access, what are the relationships between CodeData, CodeProject, and DAO..?

Body:
What are the differences between the following sets of Microsoft Access VBA collections..? Some of them seem to point to the same data & child objects, but through different conduits. I'm thinking the DAO objects are DBMS-specific, but Access.⃰ Code.⃰  and Access.⃰ Project.⃰  are not, and get connected through Access. There is ADODB, which is another beast entirely. Also, it seems some of the collections may not exist if there no child objects of that type.

Given the mentions of SQL features, there seem to be three scenarios to be concerned with, but it's difficult to grasp:

A standalone ACCDB file.

A split database with two or more ACCDB
files.

An Access frontend to an SQL server.

Object set #1:

Access.CodeData.AllTables

Access.CodeData.AllQueries

Access.CodeData.AllFunctions

Access.CodeData.AllDatabaseDiagrams

Access.CodeData.AllStoredProcedures

Access.CodeData.AllViews

Access.CodeProject.AllForms

Access.CodeProject.AllMacros

Access.CodeProject.AllModules

Access.CodeProject.AllReports

And of course CodeData vs. CurrentData and CodeProject vs. CurrentProject.

Object set #2:

Access.Application.CodeData.*

Access.Application.CodeProject.*

Object set #3:

Access.Application.CurrentDb.QueryDefs (DAO.QueryDefs)

Access.Application.CurrentDb.Relations (DAO.Relations)

Access.Application.CurrentDb.TableDefs (DAO.TableDefs)


问:
How to do if statement with jquery
I'm trying to do an if statement in jQuery, but it doesn't really work.

```<code>$("#button2").hide()
var score = 0;

//some code with button that is adding the score with score++ (working)

if(score >= 100) {
    $("#button2").show()
}
</code>```

The if statement is not properly working.

```<code>        $("#grandmabutton1").hide()
        $("#farmbutton1").hide()
        $("#minebutton1").hide()
        $("#factorybutton1").hide()

        $(function(){
            var score = 0;

            $("#p1").html("Your score is: " + score)

            $("#headbutton1").mousedown(function(){
                score++

                $("#p1").html("Your score is: " + score)
            })

            if(score >= 100) {
                $("#grandmabutton1").show()
            }

        })
</code>```

答:
The problem here is that the if statement only checks once, before the button has been clicked. Because the score starts at 0, nothing happens. Javascript has no way of knowing that you want the if statement to run all the time unless you tell it when to run it.

To solve this, you can put the if statement in the click function of the button so that it will check every time.

```<code>$("#headbutton1").mousedown(function () {
    score++
    if (score >= 100) { // Every time you click the button, it should check if your score is more than 100
        $("#grandmabutton1").show()
    }
    $("#p1").html("Your score is: " + score)
})
</code>```

This way, every time you click the button it will check if it's score is >= 100

Title: How to do if statement with jquery

Body:
I'm trying to do an if statement in jQuery, but it doesn't really work.

$("#button2").hide()
var score = 0;

//some code with button that is adding the score with score++ (working)

if(score >= 100) {
    $("#button2").show()
}

The if statement is not properly working.

        $("#grandmabutton1").hide()
        $("#farmbutton1").hide()
        $("#minebutton1").hide()
        $("#factorybutton1").hide()

        $(function(){
            var score = 0;

            $("#p1").html("Your score is: " + score)

            $("#headbutton1").mousedown(function(){
                score++

                $("#p1").html("Your score is: " + score)
            })

            if(score >= 100) {
                $("#grandmabutton1").show()
            }

        })

Body:
The problem here is that the if statement only checks once, before the button has been clicked. Because the score starts at 0, nothing happens. Javascript has no way of knowing that you want the if statement to run all the time unless you tell it when to run it.

To solve this, you can put the if statement in the click function of the button so that it will check every time.

$("#headbutton1").mousedown(function () {
    score++
    if (score >= 100) { // Every time you click the button, it should check if your score is more than 100
        $("#grandmabutton1").show()
    }
    $("#p1").html("Your score is: " + score)
})

This way, every time you click the button it will check if it's score is >= 100


问:
window is undefined when used as useValue provider with Angular 4 AoT
When Angular 4.0.2 application is compiled ahead-of-time, and the provider is defined as useValue

```<code>import { OpaqueToken, Provider } from '@angular/core';

export const windowToken = new OpaqueToken('window');
export const windowProvider = { provide: windowToken, useValue: window };
</code>```

and used like

```<code>@NgModule({ providers: [windowProvider], ... })
export class AppModule {}
</code>```

it compiles ok but results in window being undefined when injected as

```<code>constructor(@Inject(windowToken) window) {
   window.navigator...
}
</code>```

The error is thrown on bootstrapping:

TypeError: Cannot read property 'navigator' of undefined

On a closer look at auto-generated app.module.ngfactory.js it appears that it is indeed undefined:

```<code>...
import * as import39 from './window';
var AppModuleInjector = (function (_super) {
    ...
    AppModuleInjector.prototype.createInternal = function () {
        ...
        this._windowToken_26 = undefined;
        this._SomeService_27 = new import16.SomeService(this._windowToken_26);
    }
    AppModuleInjector.prototype.getInternal = function (token, notFoundResult) {
        ...
        if ((token === import39.windowToken)) {
            return this._windowToken_26;
        }
        ...
</code>```

When the same service is used as useFactory, everything is ok:

```<code>export function windowFactory() {
  return window;
}
export const windowProvider = { provide: windowToken, useFactory: windowFactory };
</code>```

What exactly is wrong with using window as useValue provider here? Is it a known pitfall? Does this limitation apply to all globals or all useValue providers?

答:
During AoT compilation, angular CLI statically analyses code too generate ngmodule.factory file. It sees "useValue" and check if static value is available and puts it into ngmodule.factory. During compile time, this value is not available, so it leaves that provider value and hence, it is returned as "undefined" when injected into constuctor.

However, "useFactory" is provided for very same purpose where you don't know your value until runtime.

Due to this, useValue is not working in your scenario, but "useFactory" will work.

Bottom line: When AOT compilation, Use "useValue" only if you have static value like constant string or number. Else use "useFactory" to return run-time calculated object/values.

Body:
When Angular 4.0.2 application is compiled ahead-of-time, and the provider is defined as useValue

import { OpaqueToken, Provider } from '@angular/core';

export const windowToken = new OpaqueToken('window');
export const windowProvider = { provide: windowToken, useValue: window };

and used like

@NgModule({ providers: [windowProvider], ... })
export class AppModule {}

it compiles ok but results in window being undefined when injected as

constructor(@Inject(windowToken) window) {
   window.navigator...
}

The error is thrown on bootstrapping:

TypeError: Cannot read property 'navigator' of undefined

On a closer look at auto-generated app.module.ngfactory.js it appears that it is indeed undefined:

...
import * as import39 from './window';
var AppModuleInjector = (function (_super) {
    ...
    AppModuleInjector.prototype.createInternal = function () {
        ...
        this._windowToken_26 = undefined;
        this._SomeService_27 = new import16.SomeService(this._windowToken_26);
    }
    AppModuleInjector.prototype.getInternal = function (token, notFoundResult) {
        ...
        if ((token === import39.windowToken)) {
            return this._windowToken_26;
        }
        ...

When the same service is used as useFactory, everything is ok:

export function windowFactory() {
  return window;
}
export const windowProvider = { provide: windowToken, useFactory: windowFactory };

What exactly is wrong with using window as useValue provider here? Is it a known pitfall? Does this limitation apply to all globals or all useValue providers?


问:
Styling the asp.net charting controls
Using the ASP.Net Chart Controls, which are a subset of the Dundas Chart Controls,

How can I make charts that look like this:

Instead of this:

EDIT: I've made some progress, since asking this question. The styling elements that improve the default graph in both Dundas and MSChart are:

Round Corners on the chart container

Background colours and gradients on chart container

Transparency on column colours

Alignment of columns in the x axis (bizarely, MSChart defaults to z axis alignment)

Area 3D wall width

答:
I know it's a bit late, but I was playing with the chart for a project I'm working on.

```<code>Color="#960080ff"
</code>```

The first set of two digits in the color are for the alpha channel. I've got it set for 96 which is semi transparent.

enjoy

Title: Styling the asp.net charting controls

Body:
I know it's a bit late, but I was playing with the chart for a project I'm working on.

Color="#960080ff"

The first set of two digits in the color are for the alpha channel. I've got it set for 96 which is semi transparent.

enjoy


问:
What is the correct way to instantiate StandardQueryParser in Lucene 7.1.0?
I'm trying to create a StandardQueryParser in order to Query and Index, I've already created. I do so in the following line of code:

StandardQueryParser queryParserHelper = new StandardQueryParser();

Which causes the following exception to occur at runtime:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/lucene/search/LegacyNumericRangeQuery
    at org.apache.lucene.queryparser.flexible.standard.builders.StandardQueryTreeBuilder.<init>(StandardQueryTreeBuilder.java:63)
    at org.apache.lucene.queryparser.flexible.standard.StandardQueryParser.<init>(StandardQueryParser.java:110)
    at analysis.Main.main(Main.java:67)
</code>```

Note the line 67 is the line of code included above.

I'm using Maven and IntelliJ.

I specify Lucene as a dependency through the following, in my pom:

```<code>    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-core</artifactId>
        <version>7.1.0</version>
    </dependency>
</code>```

答:
You need to add the lucene-queryparser jar, as well, to get StandardQueryParser.</p>

```<code><dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-queryparser</artifactId>
    <version>7.1.0</version>
</dependency>
</code>```

Body:
I'm trying to create a StandardQueryParser in order to Query and Index, I've already created. I do so in the following line of code:

StandardQueryParser queryParserHelper = new StandardQueryParser();

Which causes the following exception to occur at runtime:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/lucene/search/LegacyNumericRangeQuery
    at org.apache.lucene.queryparser.flexible.standard.builders.StandardQueryTreeBuilder.<init>(StandardQueryTreeBuilder.java:63)
    at org.apache.lucene.queryparser.flexible.standard.StandardQueryParser.<init>(StandardQueryParser.java:110)
    at analysis.Main.main(Main.java:67)

Note the line 67 is the line of code included above.

I'm using Maven and IntelliJ.

I specify Lucene as a dependency through the following, in my pom:

    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-core</artifactId>
        <version>7.1.0</version>
    </dependency>

Body:
You need to add the lucene-queryparser jar, as well, to get StandardQueryParser.

<dependency>
    <groupId>org.apache.lucene</groupId>
    <artifactId>lucene-queryparser</artifactId>
    <version>7.1.0</version>
</dependency>