问:
I need to do the piglatin exercise in ruby
I need to check if a word starts with a vowel or consonant. For words starting with a vowel I need to ad "ay" to the end of the word. This part was easy. I managed it like this:

```<code>def translate string
  vowels = ["a", "e", "i", "o", "u"]
   if vowels.include? (string[0])
   string +'ay'
  else
   *the consonant part goes here*
  end
end
</code>```

I need help with the syntax for the consonant part. If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.
Here's what I'm trying to do in the else part of my if statement:

```<code>consonant = string(0)
new_word = string - string(0)
pig_latin_word = new_word << consonant << "ay"
</code>```

Thank you.

答:
I guess what you want to do with string(0) is to get the first character in the string, in such case you'd need to do it with square brackets string[0].

When you do string - string[0] to take out the first character from the string, and assign this to a variable called new_word then you get an undefined method-'error, that's because you can't use-` for such operation, you could take a certain number of characters from the string when there's no the first one and assign it to that variable like:

```<code>p 'the'[1..-1]
# => "he"
</code>```

So that gives you the characters from the string in a range from 1 up to the last element (-1).

I could say when you do pig_latin_word = new_word << consonant << "ay", it'd be easier if you just return the last evaluated expression, this way and as you're not using the pig_latin_word variable, you can interpolate your variables with the "ay" ending and this will be what the methods return in the case the the first character of the string isn't a lowercase vowel, so, something like this would make your code work:

```<code>vowels = ["a", "e", "i", "o", "u"]
if vowels.include? (string[0])
  string +'ay'
else
  consonant = string[0]
  new_word = string[1..-1]
  "#{new_word}#{consonant}ay"
end
</code>```

But still I'm not sure, do you have to validate for every word within a sentence being passed?. In such case that would add "ay" just to the last word of the string, if a single word is passed then it works, but with a sentence like 'the quick brown fox' then it'd return "he quick brown foxtay".

And/or in the case you check if the first character of the string is a vowel, you check just for lowercase vowel, in the case it'd be an uppercase vowel, that would make it look like:

```<code>p translate('apple')
# => "appleay"
p translate('Apple')
# => "ppleAay"
</code>```

It moves your A first character to the end of the string and the adds ay.

What you could do is to split your string being passed as argument - this way if it's a sentence, you get every word, and if is a single word, then it'd work too - and check if every of the first character of them match with a vowel, uppercase and lowercase, and if so then you return just the word plus "ay", and if it's not, then you get every character from the word, make from this an array, and rotate them one character, this way if the string being passed is 'the quick brown fox' you get "het uickq rownb oxf", then as it's an array, you join them and add the ay ending, and then over your "mapped" string, you use join to join each word with a whitespace, something like:

```<code>def translate(string)
  string.split.map do |word|
    if /\A[aeiou]/i.match(word)
      "#{word}ay"
    else
      "#{word.chars.rotate(1).join}ay"
    end
  end.join(' ')
end
</code>```

Body:
I need to check if a word starts with a vowel or consonant. For words starting with a vowel I need to ad "ay" to the end of the word. This part was easy. I managed it like this:

def translate string
  vowels = ["a", "e", "i", "o", "u"]
   if vowels.include? (string[0])
   string +'ay'
  else
   *the consonant part goes here*
  end
end

I need help with the syntax for the consonant part. If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.
Here's what I'm trying to do in the else part of my if statement:

consonant = string(0)
new_word = string - string(0)
pig_latin_word = new_word << consonant << "ay"

Thank you.

Body:
I guess what you want to do with string(0) is to get the first character in the string, in such case you'd need to do it with square brackets string[0].

When you do string - string[0] to take out the first character from the string, and assign this to a variable called new_word then you get an undefined method-'error, that's because you can't use-` for such operation, you could take a certain number of characters from the string when there's no the first one and assign it to that variable like:

p 'the'[1..-1]
# => "he"

So that gives you the characters from the string in a range from 1 up to the last element (-1).

I could say when you do pig_latin_word = new_word << consonant << "ay", it'd be easier if you just return the last evaluated expression, this way and as you're not using the pig_latin_word variable, you can interpolate your variables with the "ay" ending and this will be what the methods return in the case the the first character of the string isn't a lowercase vowel, so, something like this would make your code work:

vowels = ["a", "e", "i", "o", "u"]
if vowels.include? (string[0])
  string +'ay'
else
  consonant = string[0]
  new_word = string[1..-1]
  "#{new_word}#{consonant}ay"
end

But still I'm not sure, do you have to validate for every word within a sentence being passed?. In such case that would add "ay" just to the last word of the string, if a single word is passed then it works, but with a sentence like 'the quick brown fox' then it'd return "he quick brown foxtay".

And/or in the case you check if the first character of the string is a vowel, you check just for lowercase vowel, in the case it'd be an uppercase vowel, that would make it look like:

p translate('apple')
# => "appleay"
p translate('Apple')
# => "ppleAay"

It moves your A first character to the end of the string and the adds ay.

What you could do is to split your string being passed as argument - this way if it's a sentence, you get every word, and if is a single word, then it'd work too - and check if every of the first character of them match with a vowel, uppercase and lowercase, and if so then you return just the word plus "ay", and if it's not, then you get every character from the word, make from this an array, and rotate them one character, this way if the string being passed is 'the quick brown fox' you get "het uickq rownb oxf", then as it's an array, you join them and add the ay ending, and then over your "mapped" string, you use join to join each word with a whitespace, something like:

def translate(string)
  string.split.map do |word|
    if /\A[aeiou]/i.match(word)
      "#{word}ay"
    else
      "#{word.chars.rotate(1).join}ay"
    end
  end.join(' ')
end


来源: stackexchange

问:
Kubernetes application running on master - DaemonSet
is there any way to avoid execution of an application deployed as DaemonSet on master?

I have seen that this is the expected behavior, but I would like to avoid execution in some way.

Regular pods will not schedule on master but DaemonSet pods do.

If yes, is it possible to set this information in the yml file (parameter..etc??)?

```<code> kubectl create -f mydaemon.yml

logspri-4zwl4              1/1       Running           0          <invalid>   X.X.X.X   k8s-master-e7c355e2-0
logspri-kld2w              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-0
logspri-lksrh              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-1
</code>```

I would like to avoid my pod is running on k8s-master-e7c355e2-0

I have tried :

```<code>annotations:
          scheduler.alpha.kubernetes.io/affinity: >
            {
              "nodeAffinity": {
                "requiredDuringSchedulingRequiredDuringExecution": {
                  "nodeSelectorTerms": [
                    {
                      "matchExpressions": [
                        {
                          "key": "kubernetes.io/role",
                          "operator": "NotIn",
                          "values": ["master"]
                        }
                      ]
                    }
                  ]
                }
              }
            }
</code>```

Trying also to apply the following role  (as suggested) but it doesn't work :

```<code>kubectl get nodes
NAME                    STATUS                     AGE       VERSION
k8s-agent-e7c355e2-0    Ready                      49d       v1.5.3
k8s-agent-e7c355e2-1    Ready                      49d       v1.5.3
k8s-master-e7c355e2-0   Ready,SchedulingDisabled   49d       v1.5.3
</code>```

Shall I perform:

```<code>VirtualBox:~/elk/logspout$ kubectl taint node k8s-master-e7c355e2-0 k8s-master-e7c355e2-0/ismaster=:NoSchedule
node "k8s-master-e7c355e2-0" tainted
</code>```

Even if it seems that the master is tainted I see that the application is always on master.

```<code>Role:
Labels:         beta.kubernetes.io/arch=amd64
            beta.kubernetes.io/instance-type=Standard_D2
            beta.kubernetes.io/os=linux
            failure-domain.beta.kubernetes.io/region=northeurope
            failure-domain.beta.kubernetes.io/zone=0
            kubernetes.io/hostname=k8s-master-e7c355e2-0
Annotations:        volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:         <none>
CreationTimestamp:  Wed, 17 May 2017 14:38:06 +0200
Phase:
Conditions:
</code>```

What is wrong?
Could you give me the right command to perform?

same problem reported here without an apparent solution by :

```<code>kubectl taint nodes nameofmaster dedicated=master:NoSchedule
</code>```

Thanks
Prisco

答:
By Even if it seems that the master is tainted I see that the application is always on master., I'm not certain if the DaemonSet was created before or after the taint.

If you tainted first and then created the DaemonSet, the pod should be repelled by the tainted node without further config. Otherwise, the pod from the DaemonSet will not automatically terminate. To evict existing pods immediately, the NoExecute taint is needed.

From here:

Normally, if a taint with effect NoExecute is added to a node, then
  any pods that do not tolerate the taint will be evicted immediately,
  and any pods that do tolerate the taint will never be evicted.
  However, a toleration with NoExecute effect can specify an optional
  tolerationSeconds field that dictates how long the pod will stay bound
  to the node after the taint is added.

ContentLicense: CC BY-SA 3.0

Body:
is there any way to avoid execution of an application deployed as DaemonSet on master?

I have seen that this is the expected behavior, but I would like to avoid execution in some way.

Regular pods will not schedule on master but DaemonSet pods do.

If yes, is it possible to set this information in the yml file (parameter..etc??)?

 kubectl create -f mydaemon.yml

logspri-4zwl4              1/1       Running           0          <invalid>   X.X.X.X   k8s-master-e7c355e2-0
logspri-kld2w              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-0
logspri-lksrh              1/1       Running           0          <invalid>   X.X.X.X     k8s-agent-e7c355e2-1

I would like to avoid my pod is running on k8s-master-e7c355e2-0

I have tried :

annotations:
          scheduler.alpha.kubernetes.io/affinity: >
            {
              "nodeAffinity": {
                "requiredDuringSchedulingRequiredDuringExecution": {
                  "nodeSelectorTerms": [
                    {
                      "matchExpressions": [
                        {
                          "key": "kubernetes.io/role",
                          "operator": "NotIn",
                          "values": ["master"]
                        }
                      ]
                    }
                  ]
                }
              }
            }

Trying also to apply the following role  (as suggested) but it doesn't work :

kubectl get nodes
NAME                    STATUS                     AGE       VERSION
k8s-agent-e7c355e2-0    Ready                      49d       v1.5.3
k8s-agent-e7c355e2-1    Ready                      49d       v1.5.3
k8s-master-e7c355e2-0   Ready,SchedulingDisabled   49d       v1.5.3

Shall I perform:

VirtualBox:~/elk/logspout$ kubectl taint node k8s-master-e7c355e2-0 k8s-master-e7c355e2-0/ismaster=:NoSchedule
node "k8s-master-e7c355e2-0" tainted

Even if it seems that the master is tainted I see that the application is always on master.

Role:
Labels:         beta.kubernetes.io/arch=amd64
            beta.kubernetes.io/instance-type=Standard_D2
            beta.kubernetes.io/os=linux
            failure-domain.beta.kubernetes.io/region=northeurope
            failure-domain.beta.kubernetes.io/zone=0
            kubernetes.io/hostname=k8s-master-e7c355e2-0
Annotations:        volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:         <none>
CreationTimestamp:  Wed, 17 May 2017 14:38:06 +0200
Phase:
Conditions:

What is wrong?
Could you give me the right command to perform?

same problem reported here without an apparent solution by :

kubectl taint nodes nameofmaster dedicated=master:NoSchedule

Thanks
Prisco


问:
How to run a .ps1 file in PowerShell_ISE.exe through Java
So I am creating a GUI in java that launches a variety of different scripts through powershell. I have been able to write a command that opens the .ps1 file in powershellISE, but the script doesn't actually run. My code is as follows:

```<code>String [] str = {"cmd", "/c" "start", "powershell_ise.exe", "-file", "myPath"};
try{
    Runtime.getRuntime().exec(str);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

I found this question to be helpful:

Powershell open window (from Java.Runtime.exec)

But it did not solve my issue of actually running the script

Thanks so much!

答:
Windows PowerShell Integrated Scripting Environment (ISE) is a graphical host application that enables you to read, write, run, debug, and test scripts.

If you want to run scripts you know work, you might try replacing powershell_ise.exe with powershell.exe. How to run powershell in cmd should help.

Body:
So I am creating a GUI in java that launches a variety of different scripts through powershell. I have been able to write a command that opens the .ps1 file in powershellISE, but the script doesn't actually run. My code is as follows:

String [] str = {"cmd", "/c" "start", "powershell_ise.exe", "-file", "myPath"};
try{
    Runtime.getRuntime().exec(str);
} catch (IOException e) {
    e.printStackTrace();
}

I found this question to be helpful:

Powershell open window (from Java.Runtime.exec)

But it did not solve my issue of actually running the script

Thanks so much!


问:
Set Silverstripe website as Live version outside of CMS
We have a number of clients who get confused when they use the Silverstripe CMS and then their live website displays the Draft version.

We've setup "Better Navigator" that displays whether a site is in Draft or Live but the clients still get confused (and in some view the Better Navigator button is obscured).

Ideally if the live website is being viewed outside of the CMS we want it to only display the "Live" version.

Is that possible?

答:
Instead of forcing the site to always display the published version, we can add some draft only CSS to make it much more obvious to the user that they are viewing the draft version.

Create a draft.css file, which will alter the site styling on the draft version. In this example I am changing the background of the body tag to display a tiled image with the words "Draft" on it.

mysite/css/draft.css

body {
    background-image: url(../images/draft-background.png);
}
```

<p><strong>mysite/images/draft-background.png</strong></p>

<p><img src="https://i.stack.imgur.com/qktoX.png" alt="draft background image"> </p>

<p>In our <code>Page_Controller</code> <code>init</code> function we load the <code>draft.css</code> file when the current stage is set to <code>Stage</code>:</p>

<p><strong>Page_Controller</strong></p>

```class Page_Controller extends ContentController
{

    public function init()
    {
        parent::init();

        // ...
        if ($this->current_stage() == 'Stage') {
            Requirements::css('mysite/css/draft.css');
        }
    }
    // ...
}
```

<p>The end result looks something like this:</p>

<p><img src="https://i.stack.imgur.com/mwyZJ.png" alt="Draft background example screenshot"></p>

<p>This is just one of example of what we can do with the draft only css. Alternatively we could replace the site logo, or display a warning bar at the top of page content.</p>

<p>Here is some alternate css to display the above <code>draft-background.png</code> above all the site content instead of a background image of the <code>body</code> tag:</p>

<pre class="lang-css prettyprint-override"><code>body:after {
    background-image: url(../images/draft-background.png);
    content: "";
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 1000;
    pointer-events: none;
    opacity: 0.25;
}
</code>```

Here is some example css to display a warning bar at the top of each page:

body:after {
    content: "You are currently viewing a draft version of this page";
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10000;
    pointer-events: none;
    opacity: 0.75;
    text-align: center;
    background: #F7CA18;
    color: #000000;
    padding: 20px;
}

body {
    margin-top: 60px;
}
```

Body:
Instead of forcing the site to always display the published version, we can add some draft only CSS to make it much more obvious to the user that they are viewing the draft version.

Create a draft.css file, which will alter the site styling on the draft version. In this example I am changing the background of the body tag to display a tiled image with the words "Draft" on it.

mysite/css/draft.css

body {
    background-image: url(../images/draft-background.png);
}

mysite/images/draft-background.png

In our Page_Controller init function we load the draft.css file when the current stage is set to Stage:

Page_Controller

class Page_Controller extends ContentController
{

    public function init()
    {
        parent::init();

        // ...
        if ($this->current_stage() == 'Stage') {
            Requirements::css('mysite/css/draft.css');
        }
    }
    // ...
}

The end result looks something like this:

This is just one of example of what we can do with the draft only css. Alternatively we could replace the site logo, or display a warning bar at the top of page content.

Here is some alternate css to display the above draft-background.png above all the site content instead of a background image of the body tag:

body:after {
    background-image: url(../images/draft-background.png);
    content: "";
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 1000;
    pointer-events: none;
    opacity: 0.25;
}

Here is some example css to display a warning bar at the top of each page:

body:after {
    content: "You are currently viewing a draft version of this page";
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10000;
    pointer-events: none;
    opacity: 0.75;
    text-align: center;
    background: #F7CA18;
    color: #000000;
    padding: 20px;
}

body {
    margin-top: 60px;
}


问:
How to let people collaborate on my open source project?
A while ago I started an open-source project, which for me meant (until now) I simply pushed my source code to a public repository (Mercurial on Google Code). Recently though, I've received requests from other people to collaborate on my project. Having never collaborated on an open-source project before, I'm not sure how to proceed:

Do I just give them access to the repository so they can push changes? If they push something I don't like I can always roll back and if they get on my nerves I can always revoke their access to the repository.

Do I tell them to send in patches (via the issue tracker) and then apply the ones I like and revoke the ones I don't?

Now:

I don't want to lose ownership of my project. It's a pretty nice project and it's good resume material. I think this is what I am most afraid of. However, I want to give proper credit to my collaborators.

I know this is the whole point of open-source: collaboration, so I don't want to be an idiot and say no to these people who want to help.

Lately I haven't had much time to code on my project, so it could use some help.

Also, I'm a bit reluctant to let just anyone work on my project. What if they're, pardon the expression, noobs? I suppose I can just rollback they're changes and tell them to, pardon the expression, gtfo, but that wouldn't be particularly nice.

How is this usually done?

答:
There are as many styles of doing OSS as there are projects. The guidelines below have worked so far for me. YMMV.

Don't give write access to your repository to everyone. One of the biggest benefits of DVCS is that you don't have to, everyone gets their own repository, in principle equal to yours. Only give write access to people you really trust and that you know has similar views about the project.

Always encourage patches and pull requests. Sometimes you will have to reject some patch, however make sure you really justify your rejection to the contributor; people don't like being rejected without good reason and it would discourage them (and other people too, because other people will see the issue history in the tracker) from further contributing. Also, by pointing out what's wrong with the patch, both you and the contributor will learn from the experience.

Ownership is a very relative thing. If someone contributes 10 times more than you have throughout the whole history of the project, then who really owns the project? Don't worry too much about ownership, concentrate on the project itself. Make sure you always do what's best for the project. Everything else will follow naturally.

ContentLicense: CC BY-SA 2.5


问:
React.Children.only expected to receive a single React element child error
I'm getting 'React.Children.only expected to receive a single React element child.' from the following code.

I have created a new react app using create-react-app and installed redux and react-redux, and created a simple reducer and creating store with that.

```<code>import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";

import logo from './logo.svg';
import './App.css';

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

function productReducer(state = [], action) {
  return state;
}

const store = createStore(
  productReducer
);

ReactDOM.render((<Provider store={store}><App /> </Provider>), document.getElementById('root'));
</code>```

答:
You have a space here:

```<code>                               ↓
<Provider store={store}><App /> </Provider>
</code>```

JSX is kinda picky about spacing on single lines. The above essentially gets interpreted as:

```<code><Provider store={store}><App />{' '}</Provider>
</code>```

(In fact, Prettier will produce pretty much this exact output)

You can either remove the space:

```<code><Provider store={store}><App /></Provider>
</code>```

Or break it up on to multiple lines:

```<code><Provider store={store}>
    <App />
</Provider>
</code>```

Body:
I'm getting 'React.Children.only expected to receive a single React element child.' from the following code.

I have created a new react app using create-react-app and installed redux and react-redux, and created a simple reducer and creating store with that.

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider } from "react-redux";

import logo from './logo.svg';
import './App.css';

class App extends React.Component {
  render() {
    return (

Welcome to React

          To get started, edit src/App.js and save to reload.

    );
  }
}

function productReducer(state = [], action) {
  return state;
}

const store = createStore(
  productReducer
);

ReactDOM.render((<Provider store={store}><App /> </Provider>), document.getElementById('root'));

Body:
You have a space here:

                               ↓
<Provider store={store}><App /> </Provider>

JSX is kinda picky about spacing on single lines. The above essentially gets interpreted as:

<Provider store={store}><App />{' '}</Provider>

(In fact, Prettier will produce pretty much this exact output)

You can either remove the space:

<Provider store={store}><App /></Provider>

Or break it up on to multiple lines:

<Provider store={store}>
    <App />
</Provider>

ContentLicense: CC BY-SA 4.0


问:
Wikipedia Layout: Text is too short for pictures in picture tutorial
I would like to create a picture tutorial,like suggested here.

My current layout looks like the first picture.

, but I want each subsection to have its own photo, like shown in the second picture, but I don't have much text in each section and don't want to manually fill the correct number of new lines to fill each section. Is there a better way?

答:
Use {{clear}} at the end of each section.

See https://en.wikipedia.org/wiki/Template:Clear/doc


问:
SQL give new column based on group
I have the following table:

```<code>ID | Group |  Miles
1  |    1  |   23
2  |    1  |   38
3  |    1  |   42
1  |    2  |   33
2  |    2  |   42
1  |    3  |   35
2  |    3  |   43
3  |    3  |   47
</code>```

And would like to get

```<code>id  miles1  miles2   miles3
1 | 23     | 33    | 35
2 | 38     | 42    | 43
3 | 42     | Null  | 47
</code>```

Thanks

答:
```<code>select id,
       sum(case when group = 1 then miles end) as miles1,
       sum(case when group = 2 then miles end) as miles2,
       sum(case when group = 3 then miles end) as miles3
from your_table
group by id
</code>```

Title: SQL give new column based on group

Body:
I have the following table:

ID | Group |  Miles
1  |    1  |   23
2  |    1  |   38
3  |    1  |   42
1  |    2  |   33
2  |    2  |   42
1  |    3  |   35
2  |    3  |   43
3  |    3  |   47

And would like to get

id  miles1  miles2   miles3
1 | 23     | 33    | 35
2 | 38     | 42    | 43
3 | 42     | Null  | 47

Thanks


问:
How do I create a variable length dropdown list on a ViewModel without repeating code in c#?
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

```<code>Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .
</code>```

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

```<code>[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}
</code>```

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

```<code>                      *******QUESTION EDIT***********
</code>```

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

```<code>        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }
</code>```

My Html View

```<code>        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")
</code>```

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

答:
this is a console app

```<code>   var startDate = DateTime.Now.Date;

    var days = new List<Tuple<string, string>>();

    int totalMonths = 12;

    for (int i = 1; i < totalMonths; i++)
    {
        var tempDay = startDate.AddMonths(-i);
        days.Add(new Tuple<string, string>($"{tempDay.ToString("MMM")} {tempDay.ToString("yyyy")}", tempDay.ToString("MMM")));
    }

    foreach (var d in days)
    {
        Console.WriteLine(d.Item1);
    }
</code>```

output
Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
Nov 2016
Oct 2016
Sep 2016
Aug 2016

for test purpose I have used tuple. Use the listitem class. for the item selection use either a separate loop to or use if condition in the generation method.

Body:
I'm a newbie developer and I need to populate a dropdown list with dates so they can be selected by a website visitor to retrieve certain data.

The list is unusual because it must populate backward from last month up until a year ago. Thus, last month will be the first entry in the list and each previous month will follow. For example, if today is July 5, 2017, the dropdown list will look like this:

Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
and so on . . .

Each month the list gets longer, so I can’t code a fixed length to the list. I came up with the following code, but it won’t build:

[RequireLogin]
public ActionResult Index()
{
    bool firstItem = true;
    int x = -1;
    int y = 1;
    int daysFromStartDate = beginDate.Date.Subtract(currentDate).Days;
    List<SelectListItem> items = new List<SelectListItem>();

    while (daysFromStartDate >= 30)
    {
        DateTime previousMonth = DateTime.Now.Date.AddMonths(x);
        string pMonth = previousMonth.ToString("MMM");
        string pYear = previousMonth.ToString("YYYY");
        Int32.TryParse(pMonth, out thisMonth);
        Int32.TryParse(pYear, out thisYear);
        if (firstItem)
            firstItem = false;
            SelectListItem item[y] = new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = true };  //<- #1
        else
            SelectListItem item[y]= new SelectListItem() { Text = pMonth + " " + pYear, Value = pMonth, Selected = false };  //<- #2
        items.Add(item[y]);                                                                                //<- #3
        x = x--;
        y = y++;
    }
    ViewBag.MonthList = items;
    return View();
}

I’m getting several build errors on the “item” variable and I don’t know how to fix them:

1 - Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

2 – A local variable named ‘item’ is already defined in this scope (I know I need to get rid of the dup, but that's just a symptom of my overall logic problem).

3 – Cannot apply indexing with [] to an expression of the type SelectListItem

Apparently, c# doesn't like me trying to use an index on my list items, as in "item[y]". I thought I was being clever, but this approach totally bombs.

I scoured this site as well as the Internet and read all of the examples I found, but couldn’t find a solution that matched my needs. Can anyone offer some guidance on how to fix this logic?

I believe I've thoroughly explained the problem, but if I'm lacking in precision or clarity, please accept my apology in advance. I'll be happy to respond to requests for more information.

                      *******QUESTION EDIT***********

This was a sticky one (for me anyway). However, Vlad Stryapko put me on the right track, and with a few tweeks, I got his solution (which I accepted) working. There's still another issue, but unrelated to my original post, so I'll post a separate question for that. Here's my final code:

My ViewModel

        public SelectList MonthList { get; set; }

        public SelectList ReverseMonthsLists()
        {
            var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();

            var list = new List<SelectListItem>();
            list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

            for (int i = 1; i < stringViewOfDates.Count(); i++)
            {
                list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
            }
            var selectList = new SelectList(list);
            return selectList;
        }

        public static IEnumerable<DateTime> GetDates()
        {
            DateTime startDate = new DateTime(2017, 6, 1).Date;
            var currentDate = DateTime.Now.Date;

            int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;
            if (numberOfMonthsToShow == 0)
                numberOfMonthsToShow = 1;

            var dates = new List<DateTime>(numberOfMonthsToShow);
            for (int i = 0; i < numberOfMonthsToShow; i++)
            {
                dates.Add(currentDate);
                currentDate = currentDate.AddMonths(-1);
            }
            return dates;
        }

My Html View

        @Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month Selector")

The code compiles now, but all I get is "System.Web.Mvc.SelectListItem" in my dropdown list. I'll pose that as a question in another thread, because I don't believe I'm allowed to ask a second question here.

Body:
this is a console app

   var startDate = DateTime.Now.Date;

    var days = new List<Tuple<string, string>>();

    int totalMonths = 12;

    for (int i = 1; i < totalMonths; i++)
    {
        var tempDay = startDate.AddMonths(-i);
        days.Add(new Tuple<string, string>($"{tempDay.ToString("MMM")} {tempDay.ToString("yyyy")}", tempDay.ToString("MMM")));
    }

    foreach (var d in days)
    {
        Console.WriteLine(d.Item1);
    }

output
Jun 2017
May 2017
Apr 2017
Mar 2017
Feb 2017
Jan 2017
Dec 2016
Nov 2016
Oct 2016
Sep 2016
Aug 2016

for test purpose I have used tuple. Use the listitem class. for the item selection use either a separate loop to or use if condition in the generation method.


问:
JavaScript RegExp Differences
What is the difference between

```<code>var regEx = /\d/;
</code>```

and

```<code>var regEx = new RegEx("\d");
</code>```

Bob

答:
Both evaluate to be the same exact regex, but the first is a literal, meaning you cannot use any variables inside it, you cannot dynamically generate a regex.

The second uses the constructor explicitly and can be used to create dynamic regular expressions.

```<code>var x = '3', r = ( new RegExp( x + '\d' ) ); r.test('3d')
</code>```

The above is an example of dynamically constructing the regex with the constructor, which you can not do in literal form.

In 99% of cases you will just rely on the first version ( literal ) for all your regexpes in JS. In an advanced scenario where you need say, user input to dynamically construct a regex then that's when you'll need the second form.

EDIT #1: The first matches a digit, the second just matches the letter d. You have to double-escape the second one in order for it to equal the first one, which I assume you meant to do. Just remember the advice I typed above is accurate if the second example is new RegExp('\\d').

```<code>/\d/.test('3') // true
( new RegExp('\d') ).test('3') // false
( new RegExp('\\d') ).test('3') // true
</code>```

Title: JavaScript RegExp Differences

Body:
What is the difference between

var regEx = /\d/;

and

var regEx = new RegEx("\d");

Bob

Body:
Both evaluate to be the same exact regex, but the first is a literal, meaning you cannot use any variables inside it, you cannot dynamically generate a regex.

The second uses the constructor explicitly and can be used to create dynamic regular expressions.

var x = '3', r = ( new RegExp( x + '\d' ) ); r.test('3d')

The above is an example of dynamically constructing the regex with the constructor, which you can not do in literal form.

In 99% of cases you will just rely on the first version ( literal ) for all your regexpes in JS. In an advanced scenario where you need say, user input to dynamically construct a regex then that's when you'll need the second form.

EDIT #1: The first matches a digit, the second just matches the letter d. You have to double-escape the second one in order for it to equal the first one, which I assume you meant to do. Just remember the advice I typed above is accurate if the second example is new RegExp('\\d').

/\d/.test('3') // true
( new RegExp('\d') ).test('3') // false
( new RegExp('\\d') ).test('3') // true


问:
How to create dynamic views programmatically with a good OO-design
I am facing a problem with creation of dynamic view in Swift. However, the problem is not directly related to Swift itself, it is rather a Object-Oriented programming problem.

The problem is that I need to be able to add additional view elements to a view dynamically. And I am not sure if I'm doing it correctly. My solutions seems as overkill to me.

To solve the problem I thought Decorator pattern would be a good candidate. Additionally to have more control of the flow, I have introduced Template Method pattern.

I have a number of classes that define default look and feel on certain view controls like Labels, TextFields and Buttons. Here below you can see an approximate idea of how it is.

Here is my code:

```<code>class ViewElement{
// this class inherits from default UIKit elemnts and provides default UI view
}
// default cell is the cell that implements default elements layout and margings, etc
class DefaultCell: UITableViewCell {
    let mainStack: UIViewStack
    func addElement(ViewElement)
}

class BlueCell: DefaultCell {

    let textField1: TextField
    let label : Label
    let button: Button

    init(){
        textField = TextField()
        label = Label()
        button = Button()

        addElement(textField)
        addElement(label)
        addElement(button)
    }
}
</code>```

Here is the tableViewDataSource implementation

```<code>class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }
    return cell
    }

}
</code>```

As you can see, the greater the number of conditions, the bigger my switch statement.

Additional problem arises from the fact that I will need to access the additional elements that I assign in the condition, like callbacks, tap events etc. Also the fact that those elements in conditional are added via addElement method, means that those elements will be added at the bottom of the mainStack.

In order to have control over the way elements are added to the stack I decided to go with the following solution: Template Method pattern

```<code>protocol OrderableElements {
    func top()
    func middle()
    func bottom()
}

extension OrderableElements {
    func render() {
        top()
        middle()
        bottom()
    }
}
</code>```

Now the BlueCell implements the protocol and looks like this

```<code>class BlueCell: DefaultCell, OrderableElements {

    init(){
        textField = TextField()
        label = Label()
        button = Button()
    }

    func top() {
        addElement(textField)
    }

    func middle() {
        addElement(label)
    }

    func bottom(){
        addElement(button)
    }
}
</code>```

The tabledatasource class will then look as follows:

```<code>class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }

    ...
    **cell.render()**
    return cell

    }
}
</code>```

Now because I need to add the new view elements in certain location or better said, at certain moments in during the scope of BlueCell, I introduced Decorators for the cell, like this:

```<code>class CellDecorator: OrderableElements {
    var cell: BlueCell
    init(cell: BlueCell){
        self.cell = cell
    }

    func top() {
        self.cell.top()
    }

    func middle(){
        self.cell.middle()
    }

    func bottom(){
        self.cell.bottom()
    }

    func getCell() {
        return self.cell
    }

}
</code>```

Here is the concrete implementation

```<code>class GoodWeatherDecorator: CellDecorator {

    let goodLabel
    let goodTextField
    let goodButton

    override top() {
        super.top()
        addElement(goodLabel)
    }

    override middle(){
        super.middle()
        addElement(goodTextfield)
    }

    override bottom(){
        super.bottom()
        addElement(goodButton)
    }

}
</code>```

The final implementation of the cellForRowAt method looks like below:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    var decoratedCell = CellDecorator(cell: cell)

    switch weather {

        case good:
            decoratedCell = GoodWeatherDecorator(cell: cell)
        case bad:
            decoratedCell = BadWeatherDecorator(cell: cell)

    }

    decoratedCell.configure() // <------------ here is the configure call
    cell = decoratedCell.getCell() // <------- here I get cell from the decorator

    return cell

    }

}
</code>```

Now I do understand that my implementation of the decorator pattern is not 100% valid, because I don't inherit from the BlueCell class, for example. But that does not bother me that much. The things that bothers me is that I think that this solution to the problem is kind of overkill.

All works the right way, but I can help the feeling of having done too much to solve this trivial problem.

What do you think? How would you solve this kind of problem?

Thanks in advace

答:
Given that you only show two types of cells and your solution doesn't actually get rid of the switch statement, I'd say that your solution counts as "overkill."

You don't show it, but it seems that you have a Weather enum. I'll assume that...

```<code>enum Weather: String {
    case good
    case bad
}
</code>```

In the table view datasource, my goal would be to have something like this:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let weather = weathers[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: weather.rawValue, for: indexPath) as! ConfigurableCell
    cell.configure(with: weather)
    return cell as! UITableViewCell
}
</code>```

In order to achieve the above, I would have several cells laid out in the storyboard file with different identifiers. I would have a subclass for each type of cell in my code where all of them conform to the ConfigurableCell protocol.

```<code>protocol ConfigurableCell {
    func configure(with weather: Weather)
}
</code>```

If you can't conform your Weather enum to the String type, you will need a switch statement to convert a weather object to a string identifier, but otherwise, no switch statements necessary.

Body:
I am facing a problem with creation of dynamic view in Swift. However, the problem is not directly related to Swift itself, it is rather a Object-Oriented programming problem.

The problem is that I need to be able to add additional view elements to a view dynamically. And I am not sure if I'm doing it correctly. My solutions seems as overkill to me.

To solve the problem I thought Decorator pattern would be a good candidate. Additionally to have more control of the flow, I have introduced Template Method pattern.

I have a number of classes that define default look and feel on certain view controls like Labels, TextFields and Buttons. Here below you can see an approximate idea of how it is.

Here is my code:

class ViewElement{
// this class inherits from default UIKit elemnts and provides default UI view
}
// default cell is the cell that implements default elements layout and margings, etc
class DefaultCell: UITableViewCell {
    let mainStack: UIViewStack
    func addElement(ViewElement)
}

class BlueCell: DefaultCell {

    let textField1: TextField
    let label : Label
    let button: Button

    init(){
        textField = TextField()
        label = Label()
        button = Button()

        addElement(textField)
        addElement(label)
        addElement(button)
    }
}

Here is the tableViewDataSource implementation

class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }
    return cell
    }

}

As you can see, the greater the number of conditions, the bigger my switch statement.

Additional problem arises from the fact that I will need to access the additional elements that I assign in the condition, like callbacks, tap events etc. Also the fact that those elements in conditional are added via addElement method, means that those elements will be added at the bottom of the mainStack.

In order to have control over the way elements are added to the stack I decided to go with the following solution: Template Method pattern

protocol OrderableElements {
    func top()
    func middle()
    func bottom()
}

extension OrderableElements {
    func render() {
        top()
        middle()
        bottom()
    }
}

Now the BlueCell implements the protocol and looks like this

class BlueCell: DefaultCell, OrderableElements {

    init(){
        textField = TextField()
        label = Label()
        button = Button()
    }

    func top() {
        addElement(textField)
    }

    func middle() {
        addElement(label)
    }

    func bottom(){
        addElement(button)
    }
}

The tabledatasource class will then look as follows:

class BlueTable: UITableViewDataSource {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    switch weather {
        case good:

            labelOne
            labelTwo
            buttonOne

            cell.addElement(labelOne)
            cell.addElement(labelTwo)
            cell.addElement(buttonOne)

        case bad:
            // idem
            cell.addView(badWeatherView)
    }

    ...
    **cell.render()**
    return cell

    }
}

Now because I need to add the new view elements in certain location or better said, at certain moments in during the scope of BlueCell, I introduced Decorators for the cell, like this:

class CellDecorator: OrderableElements {
    var cell: BlueCell
    init(cell: BlueCell){
        self.cell = cell
    }

    func top() {
        self.cell.top()
    }

    func middle(){
        self.cell.middle()
    }

    func bottom(){
        self.cell.bottom()
    }

    func getCell() {
        return self.cell
    }

}

Here is the concrete implementation

class GoodWeatherDecorator: CellDecorator {

    let goodLabel
    let goodTextField
    let goodButton

    override top() {
        super.top()
        addElement(goodLabel)
    }

    override middle(){
        super.middle()
        addElement(goodTextfield)
    }

    override bottom(){
        super.bottom()
        addElement(goodButton)
    }

}

The final implementation of the cellForRowAt method looks like below:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: = dequeue the cell

    if cell == nil {
        cell = BlueCell(with everything I want to pass to the constructor)
    }

    // then I check for the condition

    var decoratedCell = CellDecorator(cell: cell)

    switch weather {

        case good:
            decoratedCell = GoodWeatherDecorator(cell: cell)
        case bad:
            decoratedCell = BadWeatherDecorator(cell: cell)

    }

    decoratedCell.configure() // <------------ here is the configure call
    cell = decoratedCell.getCell() // <------- here I get cell from the decorator

    return cell

    }

}

Now I do understand that my implementation of the decorator pattern is not 100% valid, because I don't inherit from the BlueCell class, for example. But that does not bother me that much. The things that bothers me is that I think that this solution to the problem is kind of overkill.

All works the right way, but I can help the feeling of having done too much to solve this trivial problem.

What do you think? How would you solve this kind of problem?

Thanks in advace

Body:
Given that you only show two types of cells and your solution doesn't actually get rid of the switch statement, I'd say that your solution counts as "overkill."

You don't show it, but it seems that you have a Weather enum. I'll assume that...

enum Weather: String {
    case good
    case bad
}

In the table view datasource, my goal would be to have something like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let weather = weathers[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: weather.rawValue, for: indexPath) as! ConfigurableCell
    cell.configure(with: weather)
    return cell as! UITableViewCell
}

In order to achieve the above, I would have several cells laid out in the storyboard file with different identifiers. I would have a subclass for each type of cell in my code where all of them conform to the ConfigurableCell protocol.

protocol ConfigurableCell {
    func configure(with weather: Weather)
}

If you can't conform your Weather enum to the String type, you will need a switch statement to convert a weather object to a string identifier, but otherwise, no switch statements necessary.


问:
How to take R.string value instead of hardcoded value, if it's a class field?
For instance I want to take this

```<code>public class SomeClass {
    public static final String GREET_STRING = "Hello!";
    //...
</code>```

and change it to something like:

```<code>public class SomeClass {
    public static final String GREET_STRING = getString(R.string.greet_string);
    //...
</code>```

Can this be done or do I need some kind of Context instantiation to get the resources for the string loading?

答:
Try this:

```<code>public abstract class SomeClass extends AppCompatActivity {

    public static String GREET_STRING(Context context) {
        if (context == null) {
            return null;
        }
        return context.getResources().getString(R.string.greet_string);
    }
}
</code>```

Res/Value/String:

```<code><resources>
    <string name="greet_string">Hello!</string>
</resources>
</code>```

Call SomeClass from MainClass

```<code>public class MainClass extends SomeClass {
    private final static String TAG = MainClass.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // call SomeClass from MainClass
        Log.i(TAG, SomeClass.GREET_STRING(this));
    }
}
</code>```

Body:
For instance I want to take this

public class SomeClass {
    public static final String GREET_STRING = "Hello!";
    //...

and change it to something like:

public class SomeClass {
    public static final String GREET_STRING = getString(R.string.greet_string);
    //...

Can this be done or do I need some kind of Context instantiation to get the resources for the string loading?

Body:
Try this:

public abstract class SomeClass extends AppCompatActivity {

    public static String GREET_STRING(Context context) {
        if (context == null) {
            return null;
        }
        return context.getResources().getString(R.string.greet_string);
    }
}

Res/Value/String:

<resources>
    <string name="greet_string">Hello!</string>
</resources>

Call SomeClass from MainClass

public class MainClass extends SomeClass {
    private final static String TAG = MainClass.class.getName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // call SomeClass from MainClass
        Log.i(TAG, SomeClass.GREET_STRING(this));
    }
}


问:
Datadog-agent spun up within docker container outputs JMX RMI connection error
I’m getting a connection refused from my datadog-agent that is trying to collect JMX (via RMI) metrics from an in-house application that exists in its own docker container. However, jconsole is able to collect the metrics from the application that exists within its own docker container. The datadog-agent exists within a container of its own. Both containers exist within the same network on the same host. Any ideas? I have looked at the other stack overflow questions.

The IP address 0.0.0.0 and also specific host address have been tried within the custom jmx.yaml file /etc/dd-agent/conf.d/jmx.yaml

Docker Container 0:

* Runs the my_streams_app that outputs kafka streams metrics

* Executed via:

```<code>`docker run -d --name my_streams_app
      -v /var/run/docker.sock:/var/run/docker.sock:ro
      -v /proc/:/host/proc/:ro
      -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro
      -e API_KEY=someapikeyhere
      -e SD_JMX_ENABLE=yes -p 9998:9998 --network=my_streams_default quay.io/temp/my_streams`
</code>```

jconsole is able to pick up the metrics emmitted.

Docker Container 1:

* Runs datadog-agent within container
* Datadog-agent uses JMX default (RMI) to fetch the metrics from my_streams_app that exists in container 0, above.

* both containers run on the same network within the same host (my laptop MAC OSX)

* able to netcat from within datadog-agent in docker container to the my_streams_app ip and port in the other container. Using 0.0.0.0 and 9998, can also use specific IP addresses

* command to run the datadog agent from within a container

```<code>docker run -v /var/run/docker.sock:/var/run/docker.sock:ro  -v /proc/:/host/proc/:ro -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro -e LOG_LEVEL=DEBUG -e SD_BACKEND=docker --network=mystreams_default 4b1488e74733
</code>```

jmx configuration for collecting metrics by datadog jmx from within the container:

instances:

host: 0.0.0.0
   port: 9998
   tags:
        newTag: my_streams
   jmx_url: "service:jmx:rmi:///jndi/rmi://0.0.0.0:9998/jmxrmi"
   name: jmx_instance

docker_images:
        - my_streams_app

init_config:
    is_jmx: true
    conf:
        - include:
            domain: '"kafka.streams"'
            bean: '"kafka.streams":type="stream-metrics",client-id=“my_test-1-StreamThread-1"'
            attribute:
                commit-calls-rate:
                    metric_type: gauge
                commit-time-avg:
                    metric_type: gauge
                commit-time-max:
                    metric_type: gauge
                poll-calls-rate:
                    metric_type: gauge

JConsole:

* collects metrics from my_streams_app within the docker container 0, above via:

```<code>jconsole 0.0.0.0:9998
</code>```

Error output:

```<code>2017-07-05 20:48:20,236 | ERROR | App | Cannot connect to instance service:jmx:rmi:///jndi/rmi://0.0.0.0:9998/jmxrmi. java.io.IOException:

Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
java.io.IOException: java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
    at org.datadog.jmxfetch.Connection.connectWithTimeout(Connection.java:117)
    at org.datadog.jmxfetch.Connection.createConnection(Connection.java:61)
    at org.datadog.jmxfetch.RemoteConnection.<init>(RemoteConnection.java:56)
    at org.datadog.jmxfetch.ConnectionFactory.createConnection(ConnectionFactory.java:29)
    at org.datadog.jmxfetch.Instance.getConnection(Instance.java:162)
    at org.datadog.jmxfetch.Instance.init(Instance.java:173)
    at org.datadog.jmxfetch.App.init(App.java:511)
    at org.datadog.jmxfetch.App.main(App.java:115)
Caused by: java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
    at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:370)
    at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:268)
    at org.datadog.jmxfetch.Connection$1.run(Connection.java:86)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:473)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
    at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:142)
    at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:204)
    at javax.naming.InitialContext.lookup(InitialContext.java:415)
    at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1928)
    at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1895)
    at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:287)
    ... 7 more
Caused by: java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:341)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:138)
    ... 12 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:580)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.<init>(Socket.java:429)
    at java.net.Socket.<init>(Socket.java:209)
    at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
    at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
</code>```

rmiregistry has been started as per Failed to retrieve RMIServer stub

答:
The solution:

docker container 0

running the application that is outputting the metrics

create a bash script within the application that is outputting the metrics.

within the script use the set the value of the docker container $HOSTNAME environment variable to the jmxremote.host and the rmi.server.hostname.

#!/bin/sh

    java -Djava.util.logging.config.file=logging.properties -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.rmi.port=9998 -Dcom.sun.management.jmxremote.port=9998 -Djava.rmi.server.hostname=$HOSTNAME -Dcom.sun.management.jmxremote.host=$HOSTNAME -Dcom.sun.management.jmxremote.local.only=false -jar /app/my-streams.jar

remember to set chmod +x

set the dockerfile CMD to run the script above like so:

CMD["./"]

docker container 1

the container running the datadog agent

configure the jmx.yaml file as mentioned above in the question. just set the host to the application name

way more stuff was done that is available from from stack overflow posts. but the above fixes the metrics finding error from datadog-agent.

Here is how to run each component:

docker container 0

* my-streams

* spin up dependent services in tab

** mvn clean package docker:build

** docker-compose up

another tab spin up my-streams-app

** docker kill my-streams-app

** docker rm my-streams-app

** docker run -d --name my-streams-app -p 9998:9998 --
network=mystreams_default quay.io/myimage/my-streams

docker container 1

* docker build -t dd-agent-my-streams .

* docker run -v /var/run/docker.sock:/var/run/docker.sock:ro   -v /proc/:/host/proc/:ro   -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro -e LOG_LEVEL=DEBUG -e SD_BACKEND=docker --network=mystreams_default

ssh into docker container 1 to verify if metrics work

* docker ps // to find the name of the container to log into

* docker exec -it  /bin/bash

root@904e6561cc97:/# service datadog-agent configcheck

root@904e6561cc97:/# service datadog-agent jmx list_everything

root@904e6561cc97:/# service datadog-agent jmx collect

Body:
I’m getting a connection refused from my datadog-agent that is trying to collect JMX (via RMI) metrics from an in-house application that exists in its own docker container. However, jconsole is able to collect the metrics from the application that exists within its own docker container. The datadog-agent exists within a container of its own. Both containers exist within the same network on the same host. Any ideas? I have looked at the other stack overflow questions.

The IP address 0.0.0.0 and also specific host address have been tried within the custom jmx.yaml file /etc/dd-agent/conf.d/jmx.yaml

Docker Container 0:

* Runs the my_streams_app that outputs kafka streams metrics

* Executed via:

`docker run -d --name my_streams_app
      -v /var/run/docker.sock:/var/run/docker.sock:ro
      -v /proc/:/host/proc/:ro
      -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro
      -e API_KEY=someapikeyhere
      -e SD_JMX_ENABLE=yes -p 9998:9998 --network=my_streams_default quay.io/temp/my_streams`

jconsole is able to pick up the metrics emmitted.

Docker Container 1:

* Runs datadog-agent within container
* Datadog-agent uses JMX default (RMI) to fetch the metrics from my_streams_app that exists in container 0, above.

* both containers run on the same network within the same host (my laptop MAC OSX)

* able to netcat from within datadog-agent in docker container to the my_streams_app ip and port in the other container. Using 0.0.0.0 and 9998, can also use specific IP addresses

* command to run the datadog agent from within a container

docker run -v /var/run/docker.sock:/var/run/docker.sock:ro  -v /proc/:/host/proc/:ro -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro -e LOG_LEVEL=DEBUG -e SD_BACKEND=docker --network=mystreams_default 4b1488e74733

jmx configuration for collecting metrics by datadog jmx from within the container:

instances:

host: 0.0.0.0
   port: 9998
   tags:
        newTag: my_streams
   jmx_url: "service:jmx:rmi:///jndi/rmi://0.0.0.0:9998/jmxrmi"
   name: jmx_instance

docker_images:
        - my_streams_app

init_config:
    is_jmx: true
    conf:
        - include:
            domain: '"kafka.streams"'
            bean: '"kafka.streams":type="stream-metrics",client-id=“my_test-1-StreamThread-1"'
            attribute:
                commit-calls-rate:
                    metric_type: gauge
                commit-time-avg:
                    metric_type: gauge
                commit-time-max:
                    metric_type: gauge
                poll-calls-rate:
                    metric_type: gauge

JConsole:

* collects metrics from my_streams_app within the docker container 0, above via:

jconsole 0.0.0.0:9998

Error output:

2017-07-05 20:48:20,236 | ERROR | App | Cannot connect to instance service:jmx:rmi:///jndi/rmi://0.0.0.0:9998/jmxrmi. java.io.IOException:

Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
java.io.IOException: java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
    at org.datadog.jmxfetch.Connection.connectWithTimeout(Connection.java:117)
    at org.datadog.jmxfetch.Connection.createConnection(Connection.java:61)
    at org.datadog.jmxfetch.RemoteConnection.<init>(RemoteConnection.java:56)
    at org.datadog.jmxfetch.ConnectionFactory.createConnection(ConnectionFactory.java:29)
    at org.datadog.jmxfetch.Instance.getConnection(Instance.java:162)
    at org.datadog.jmxfetch.Instance.init(Instance.java:173)
    at org.datadog.jmxfetch.App.init(App.java:511)
    at org.datadog.jmxfetch.App.main(App.java:115)
Caused by: java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
    at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:370)
    at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:268)
    at org.datadog.jmxfetch.Connection$1.run(Connection.java:86)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:473)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)]
    at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:142)
    at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:204)
    at javax.naming.InitialContext.lookup(InitialContext.java:415)
    at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1928)
    at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1895)
    at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:287)
    ... 7 more
Caused by: java.rmi.ConnectException: Connection refused to host: 0.0.0.0; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:341)
    at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
    at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:138)
    ... 12 more
Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:580)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.<init>(Socket.java:429)
    at java.net.Socket.<init>(Socket.java:209)
    at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
    at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)

rmiregistry has been started as per Failed to retrieve RMIServer stub


问:
is this regular grammar- S -> 0S0/00?
Let L denotes the language generated by the grammar S -> 0S0/00. Which of the following is true?
(A) L = 0+
(B) L is regular but not 0+
(C) L is context free but not regular
(D) L is not context free

HI can anyone explain me how the language represented by the grammar S -> 0S0/00 is regular? I know very well the grammar is context free but not sure how can that be regular?

答:
Consider first the definition of a regular grammar here
https://www.cs.montana.edu/ross/theory/contents/chapter02/green/section05/page04.xhtml

So first we need a set N of non terminal symbols (symbols that can be rewritten as a combination of terminal and non-terminal symbols), for our example N={S}

Next we need a set T of terminal symbols (symbols that cannot be replaced), for our example T={0}

Now a set P of grammer rules that fit a very specific form (see link), for L we see that P={S->0S0,S->00}. Both of these rules are of regular form (meaning each non-terminal can be replaced with a terminal, a terminal then a non-terminal, or the empty string, see link for more info). So we have our rules.

Now we just need a starting symbol X, we can trivally say that our starting symbol is S.

Therefore the tuple (N={S},T={0},P={S->0S0,S->00},X=S) fits the requirements to be defined a regular grammar.

Title: is this regular grammar- S -> 0S0/00?


问:
Regression not possible for same y value
I want to run a regression analysis on below data, here x1 and x2 produce y value. But in that case, y value is fixed in all time. So regression will not happen. But why? Need explanation.

答:
Your training set shows that the coefficients are all ~0 and the constant is 5. There's no more information in that dataset, you don't need regression to show that.

You did not specify what kind of regression you are running. Depending on the type of regression you are using, you will need the matrices to be invertible and not be related linearly.

It seems to work using normal equation (with expected results):

```<code>import numpy as np
import matplotlib.pyplot as plt
input = np.array([
    [2,3,5],
    [1,2,5],
    [4,2,5],
    [1,7,5],
    [1,9,5]
])
m = len(input)
X = np.array([np.ones(m), input[:, 0],input[:, 1]]).T # Add Constant to X
y = np.array(input[:, 2]).reshape(-1, 1) # Get the dependant values
betaHat = np.linalg.solve(X.T.dot(X), X.T.dot(y)) # Calculate coefficients
print(betaHat) # Show Constant and coefficients (in that order)
[[  5.00000000e+00]
[  5.29208238e-16]
[  4.32685981e-17]]
</code>```

Body:
Your training set shows that the coefficients are all ~0 and the constant is 5. There's no more information in that dataset, you don't need regression to show that.

You did not specify what kind of regression you are running. Depending on the type of regression you are using, you will need the matrices to be invertible and not be related linearly.

It seems to work using normal equation (with expected results):

import numpy as np
import matplotlib.pyplot as plt
input = np.array([
    [2,3,5],
    [1,2,5],
    [4,2,5],
    [1,7,5],
    [1,9,5]
])
m = len(input)
X = np.array([np.ones(m), input[:, 0],input[:, 1]]).T # Add Constant to X
y = np.array(input[:, 2]).reshape(-1, 1) # Get the dependant values
betaHat = np.linalg.solve(X.T.dot(X), X.T.dot(y)) # Calculate coefficients
print(betaHat) # Show Constant and coefficients (in that order)
[[  5.00000000e+00]
[  5.29208238e-16]
[  4.32685981e-17]]


问:
preprocess angular2 upload file
I am building an import tool in angular2. The process is to allow the user to provide a csv file and then fill in how they want the data mapped to the system. So the steps would be
1. Select a local file (using file upload)
2. Instead of sending the file to the server it will be loaded into an array inside angular2 and then displayed on the screen.

Are there any examples of this.

答:
You'll have a lot of trouble accessing a file in the local file system using JavaScript, mainly because browsers won't let you do that for security reasons (imagine the viruses). Your JavaScript code runs on an isolated sandbox so by design there's no way to do this (check https://stackoverflow.com/a/33803293/165606 for references on the topic).

The only way you can load local text files is by renaming them into ".js" files (manually), adding them to your project folder and includying them in your HTML header, or using some kind of middleware like Cordova (if you're making a mobile app), or doing some advanced browser-specific configurations to deactivate the file system security rules (not trivial to do for a non-technical user, on purpose).

In case you may decide to work with uploaded files, here's some libraries and demos to upload and open CSV files with Angular 2.

File upload:

https://github.com/valor-software/ng2-file-upload

Demo: http://valor-software.com/ng2-file-upload/

Read CSV:

http://blog.sodhanalibrary.com/2016/10/read-csv-data-using-angular-2.html#.WV1-cXXyuHs

Demo: http://demo.sodhanalibrary.com/angular2/readCsvData.html

Title: preprocess angular2 upload file


问:
Explain polymorphism
What is polymorphism? I'm not sure I am understanding it correctly.

In the Python scope, what I am getting out of it is that I can define parameters as followed:

```<code>def blah (x, y)
</code>```

without having to specify the type, as opposed to another language like Java, where it'd look more along the lines of:

```<code>public void blah (int x, string y)
</code>```

Am I getting that right?

答: Polymorphism - The same object acting differently based on the scenario it is in. For example, if a 12-year old kid was in a room with a bunch of kids, the type of music they would listen to would be different than if a 12 year old kid was in a room full of adults. The 12 year old kid is the same, however the kid acting differently based on the scenario it is in (the different music). </p>

Title: Explain polymorphism

Body:
What is polymorphism? I'm not sure I am understanding it correctly.

In the Python scope, what I am getting out of it is that I can define parameters as followed:

def blah (x, y)

without having to specify the type, as opposed to another language like Java, where it'd look more along the lines of:

public void blah (int x, string y)

Am I getting that right?


问:
suggestions for unit testing exceptions
Consider a method which might throw an exception with some descriptive text:

```<code>if ($someCondition) {
    throw new \Whatever\Exception('dilithium exhausted');
}
</code>```

And elsewhere in the method is another block that might throw the same exception, but with different text:

```<code>if ($anotherCondition) {
    throw new \Whatever\Exception('differentialator exploded');
}
</code>```

While writing unit tests for this class, you create failure cases so that you can verify that these two exceptions get thrown properly. In these failure cases, do you prefer to:

A) Use @exceptionExpected in the test method's docblock to trap the generic \Whatever\Exception class and subsequently ignore the getMessage() text, assuming you got the right one? (Seems like a bad idea.)

or:

B) Use try/catch and then assert that the caught exception's getMessage() text equals the exact descriptive string you're expecting? (More resilient but it means changing your tests whenever you change your error wording.)

or:

C) Create a separate exception for each error case (e.g., \Whatever\DilithiumException and \Whatever\DifferentialatorException) and then use @exceptionExpected for each one.

I'm currently using B but tending toward C. I'm curious what others are doing in this same scenario. Do you have any guidelines that help you determine, "At what point does an error deserve its own exception class versus a more generic shared one?"

答:
All of the above.

A is great, and I use as much as possible because it is simplest. There is another case when A does not work:

```<code>/**
 * @exceptionExpected FooException
 */
test() {
  // code that could throw FooException
  ...
  // purpose of the test that throws of FooException
}
</code>```

In this case, the test could pass when it should have failed because it didn't even get to what I was testing. A good way to deal with this is to use $this->setExpectedException()

B is great when you might actually use information from the exception. Rather than using the text of the exception message I would prefer to use the code. I have a form validation exception that packages up all the problems encountered in the data into one exception. By extending the exception class it becomes easy to transmit a good deal of information from the internal error state to the external handling code.

C accomplishes the same thing as B, but allows for simplifying the code by relying on more classes. The difference between these two is subtle and I tend to rely on design aesthetic to make the decision.

TL; DR: Use exception codes rather than messages, and design to the use case rather than the unit tests.

Title: suggestions for unit testing exceptions

Body:
Consider a method which might throw an exception with some descriptive text:

if ($someCondition) {
    throw new \Whatever\Exception('dilithium exhausted');
}

And elsewhere in the method is another block that might throw the same exception, but with different text:

if ($anotherCondition) {
    throw new \Whatever\Exception('differentialator exploded');
}

While writing unit tests for this class, you create failure cases so that you can verify that these two exceptions get thrown properly. In these failure cases, do you prefer to:

A) Use @exceptionExpected in the test method's docblock to trap the generic \Whatever\Exception class and subsequently ignore the getMessage() text, assuming you got the right one? (Seems like a bad idea.)

or:

B) Use try/catch and then assert that the caught exception's getMessage() text equals the exact descriptive string you're expecting? (More resilient but it means changing your tests whenever you change your error wording.)

or:

C) Create a separate exception for each error case (e.g., \Whatever\DilithiumException and \Whatever\DifferentialatorException) and then use @exceptionExpected for each one.

I'm currently using B but tending toward C. I'm curious what others are doing in this same scenario. Do you have any guidelines that help you determine, "At what point does an error deserve its own exception class versus a more generic shared one?"

Body:
All of the above.

A is great, and I use as much as possible because it is simplest. There is another case when A does not work:

/**
 * @exceptionExpected FooException
 */
test() {
  // code that could throw FooException
  ...
  // purpose of the test that throws of FooException
}

In this case, the test could pass when it should have failed because it didn't even get to what I was testing. A good way to deal with this is to use $this->setExpectedException()

B is great when you might actually use information from the exception. Rather than using the text of the exception message I would prefer to use the code. I have a form validation exception that packages up all the problems encountered in the data into one exception. By extending the exception class it becomes easy to transmit a good deal of information from the internal error state to the external handling code.

C accomplishes the same thing as B, but allows for simplifying the code by relying on more classes. The difference between these two is subtle and I tend to rely on design aesthetic to make the decision.

TL; DR: Use exception codes rather than messages, and design to the use case rather than the unit tests.


问:
Retrieving YouTube video URL in JavaScript
I am currently trying to build a audio visualizer in HTML/JS using WebGL. I'm so far using an Audio Element for this, which I spawn, create the analyser, connect to output, etc. I can already drag and drop files and enter a url, but I'd like more... for example YouTube integration (enter a link and it just plays it).

Here comes the difficult part however:
Despite YouTube constantly updating I've found this method: How to get direct url for youtube videos

so I am loading an Iframe with the embedded video (because YT doesnt allow their Desktop side loaded in iframes....) and accessing frame.contentWindow - which doesnt work due to the same-origin policy ...    -__-

I was just trying to improve my site a little and all the "security" features are starting to get on my nerves.
Is there at current a way to do this in plain javascript & html? Additionally php for some backend-stuff WOULD be ok if not avoidable.

Thanks in advance.

答:
Try putting https://cors-anywhere.herokuapp.com/ in front of the url.  Type the entire URL afterwards, including the http://www..  This is a heroku web app that makes the request for you and should avoid the cross-origin request error.

Are you getting the cross-origin error when your code is hosted on a server?  In my experience, this error usually happens when code is being executed on the desktop but disappears when the file is hosted on a server.

Looking at all of the answers for this question may also be beneficial.

Here's a github respository that looks very similar to what you want to make.  Might be worth taking a look at.


问:
Spring Boot builds fine but throws javax.naming.NameNotFoundException: remaining name: env/jmx/runtime when running
I have an existing application that is building fine via gradle but when I run it through the embedded tomcat server, I get the following Exception.  Any idea on how to resolve?

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'mbeanExporter' defined in class path resource
  [org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate
  [org.springframework.jmx.export.annotation.AnnotationMBeanExporter]:
  Factory method 'mbeanExporter' threw exception; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'mbeanServer' defined in class path resource
  [org/springframework/boot/autoconfigure/jmx/JmxAutoConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [javax.management.MBeanServer]: Factory method
  'mbeanServer' threw exception; nested exception is
  org.springframework.jmx.MBeanServerNotFoundException: Failed to
  retrieve WebLogic MBeanServer from JNDI; nested exception is
  javax.naming.NameNotFoundException: remaining name: env/jmx/runtime
    at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at
  org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:687)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:967)
    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:956)
    at com.avada.main.Application.main(Application.java:15)

答:
You can skip loaded configuration of Spring Boot by adding the following line:

```<code>@EnableAutoConfiguration(exclude = { JmxAutoConfiguration.class, EndpointMBeanExportAutoConfiguration.class})
</code>```

The container in new version of Spring Boot (current: 1.5.4) try to load other beans inside application server jar so you need to add the exclusion (like: EndpointMBeanExportAutoConfiguration) of this setup.

Body:
You can skip loaded configuration of Spring Boot by adding the following line:

@EnableAutoConfiguration(exclude = { JmxAutoConfiguration.class, EndpointMBeanExportAutoConfiguration.class})

The container in new version of Spring Boot (current: 1.5.4) try to load other beans inside application server jar so you need to add the exclusion (like: EndpointMBeanExportAutoConfiguration) of this setup.


问:
Why is Django not loading my CSS?
I am creating a website with Django and for some reason my CSS file is having no effect on the page. I have checked to make sure my STATIC_URL is defined but still no luck.

My settings.py:

```<code># Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
</code>```

Inside of my blog app I have a static directory

```<code>blog
  |
  static
     |
     css
       |
       blog.css
</code>```

My HTML doc:

```<code>{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Medicare Supplemental info</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
        <!-- This is where I'm loading the CSS file -->
        <link rel="stylesheet" href="{% static 'css/blog.css' %}">
    </head>
</code>```

I checked to make sure that I have the required app installed in the settings.py:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]
</code>```

I have also tried changing the way I load static files from:

```<code>{% load staticfiles %}
</code>```

to:

```<code>{% load static %}
</code>```

Still no luck. What is it I'm doing wrong?

答:
I think you miss this in urls.py:

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

This work in dev, in production you must collectstatic with manage.py and serve statics with nginx(or apache).

Title: Why is Django not loading my CSS?

Body:
I am creating a website with Django and for some reason my CSS file is having no effect on the page. I have checked to make sure my STATIC_URL is defined but still no luck.

My settings.py:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Inside of my blog app I have a static directory

blog
  |
  static
     |
     css
       |
       blog.css

My HTML doc:

{% load staticfiles %}
<!DOCTYPE html>

        <title>Medicare Supplemental info</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

        <link rel="stylesheet" href="{% static 'css/blog.css' %}">

I checked to make sure that I have the required app installed in the settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

I have also tried changing the way I load static files from:

{% load staticfiles %}

to:

{% load static %}

Still no luck. What is it I'm doing wrong?

Body:
I think you miss this in urls.py:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

This work in dev, in production you must collectstatic with manage.py and serve statics with nginx(or apache).