问:
How to change h1 tittle when clicked/make the section centered
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

```<code><Body>
<H1 title = "When this is clicked, the section changes"> Title </ h1>
<P id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </ P>
</ Body>
</code>```

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

答:
I really have no idea why you're being downvoted here. From what I gather you've tried your best on all your assigned questions and this one happened to stump you...

Anyways.. this question has a few different problems that need to be solved for you to complete the question. I'm going to try to break these down into the components, and then explain the pieces that help us get to where you want to be.

Question 1

Thinking through this a bit, here are the following steps to solve your problem.

Find a way to "listen" for a "click event" on the
 element.

Find a way to change the text within the
 element to the desired text when the
 element is clicked.

There are some substeps buried in this but this should get us started.

To solve this issue, we'll need to find a way to select elements on a page. A Google search yields a few methods to do this in vanilla JS based solely on the code you've given.

Query Selectors: document.querySelector and document.querySelectorAll

Tag selectors: document.getElementsByTagName

There are many others as well, but using only the code that you've supplied, and assuming we're not allowed to add class attributes or anything, we'll roll with the above choices.

The selectors above all return HTML "nodes" from the page. You can think of a HTML nodes as objects that make up an HTML page. They have all sorts of properties and we can perform many operations on them.

Your best bet is to use the first suggestion, document.querySelector because it returns a single HTML node based on the passed selector. Be careful though. If we had more than one of the same element, it would only return the first which isn't at all useful.

Here's some documentation you can read and a few examples to help you understand how it works.

document.querySelector documentation

So now we have a way of selecting the
 element on the page.

document.querySelector(h1);

Now, we need a way to listen for events. A search of "listening for events in vanilla JS" would bring you to the addEventListener method, which allows us to listen for events on a given HTML element.

eventListener documentation

Now we can put these two together and we have an
 element that listens for events. I'm going to skip ahead a bit and fill in the function so we have.

```<code>let title = document.querySelector('h1');

title.addEventListener('click', function() {
    alert('I just clicked the title');
});
</code>```

If you plug that in and click the title, you'll see a modal pop up indicating that you clicked the title. One step down.

Now, we have to find a way to change the "text content" of the
 element to the desired text. To do this, we first need to select the
 element and store it in a variable. You now know how to do this so I'll leave you to it.

Now that we have the reference to the node we want to modify, we need to change a property of that node related to the text. A Google search of this will return a few different properties, but I'm going to nudge you in the right direction and let you know you want the elem.textContent property.

Putting this all together, here's the code I have that works and satisfies your requirements for the first question.

```<code>let headerTxt = document.querySelector('h1');
let sectionTxt = document.querySelector('p');

headerTxt.addEventListener('click', function() {
  sectionTxt.textContent = 'First section: modified version';
});
</code>```

Question 2

Some similarities from the first question here. We need to...

Select both the
 and
 elements on the page (DONE)

add a click event listener to the
 element that centers the
 element.

We can skip the first piece since we did that in question 1. I'm also going to skip adding an event listener to the
 since we did something similar to that in the first question.

After adding the event listener, we need a way to change the text-alignment of some text in an HTML element.

A Google search brings us to the textAlign CSS property which we can modify using JS.

textAlign

Putting this all together, here's the complete solution

let headerTxt = document.querySelector('h1');
let sectionTxt = document.querySelector('p');

headerTxt.addEventListener('click', function() {
  sectionTxt.textContent = 'First section: modified version';
});

sectionTxt.addEventListener('click', function() {
  headerTxt.style.textAlign = 'center';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<h1 title = "When this is clicked, the section changes"> Title </h1>
<p id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </p>
</body></code>```

Hope this helps man. One takeaway of advice I have for you is get used to searching and get used to reading documentation. I'm a beginner too and I've figured that out quickly lol.

Good luck!

Body:
I'm working on some simple questions as practice for my exam, but most of the questions don't have any answers for me to check if I don't know. There is one I'm really unsure about, so I thaught I'd check here. The question is:

Suppose we have an HTML document that contains these two lines:

 Title

 First section: Original version.

Type the code that would change the look of this page so that:

• When you click on the h1 title, the section changes from "First section: Original Version" to "First section: modified version ".

• When you click on the section, the position of the title changes and gets centered.

Hope someone can help learn me this so I have an answer if something similar shows up on my exam:)

Body:
I really have no idea why you're being downvoted here. From what I gather you've tried your best on all your assigned questions and this one happened to stump you...

Anyways.. this question has a few different problems that need to be solved for you to complete the question. I'm going to try to break these down into the components, and then explain the pieces that help us get to where you want to be.

Question 1

Thinking through this a bit, here are the following steps to solve your problem.

Find a way to "listen" for a "click event" on the <h1> element.

Find a way to change the text within the <p> element to the desired text when the <h1> element is clicked.

There are some substeps buried in this but this should get us started.

To solve this issue, we'll need to find a way to select elements on a page. A Google search yields a few methods to do this in vanilla JS based solely on the code you've given.

Query Selectors: document.querySelector and document.querySelectorAll

Tag selectors: document.getElementsByTagName

There are many others as well, but using only the code that you've supplied, and assuming we're not allowed to add class attributes or anything, we'll roll with the above choices.

The selectors above all return HTML "nodes" from the page. You can think of a HTML nodes as objects that make up an HTML page. They have all sorts of properties and we can perform many operations on them.

Your best bet is to use the first suggestion, document.querySelector because it returns a single HTML node based on the passed selector. Be careful though. If we had more than one of the same element, it would only return the first which isn't at all useful.

Here's some documentation you can read and a few examples to help you understand how it works.

document.querySelector documentation

So now we have a way of selecting the <h1> element on the page.

document.querySelector(h1);

Now, we need a way to listen for events. A search of "listening for events in vanilla JS" would bring you to the addEventListener method, which allows us to listen for events on a given HTML element.

eventListener documentation

Now we can put these two together and we have an <h1> element that listens for events. I'm going to skip ahead a bit and fill in the function so we have.

let title = document.querySelector('h1');

title.addEventListener('click', function() {
    alert('I just clicked the title');
});

If you plug that in and click the title, you'll see a modal pop up indicating that you clicked the title. One step down.

Now, we have to find a way to change the "text content" of the <p> element to the desired text. To do this, we first need to select the <p> element and store it in a variable. You now know how to do this so I'll leave you to it.

Now that we have the reference to the node we want to modify, we need to change a property of that node related to the text. A Google search of this will return a few different properties, but I'm going to nudge you in the right direction and let you know you want the elem.textContent property.

Putting this all together, here's the code I have that works and satisfies your requirements for the first question.

let headerTxt = document.querySelector('h1');
let sectionTxt = document.querySelector('p');

headerTxt.addEventListener('click', function() {
  sectionTxt.textContent = 'First section: modified version';
});

Question 2

Some similarities from the first question here. We need to...

Select both the <h1> and <p> elements on the page (DONE)

add a click event listener to the <p> element that centers the <h1> element.

We can skip the first piece since we did that in question 1. I'm also going to skip adding an event listener to the <p> since we did something similar to that in the first question.

After adding the event listener, we need a way to change the text-alignment of some text in an HTML element.

A Google search brings us to the textAlign CSS property which we can modify using JS.

textAlign

Putting this all together, here's the complete solution

let headerTxt = document.querySelector('h1');
let sectionTxt = document.querySelector('p');

headerTxt.addEventListener('click', function() {
  sectionTxt.textContent = 'First section: modified version';
});

sectionTxt.addEventListener('click', function() {
  headerTxt.style.textAlign = 'center';
});

<body>
<h1 title = "When this is clicked, the section changes"> Title </h1>
<p id = "first" title = "When this is clicked, the title is centered"> First section: Original version. </p>
</body>

Hope this helps man. One takeaway of advice I have for you is get used to searching and get used to reading documentation. I'm a beginner too and I've figured that out quickly lol.

Good luck!


来源: stackexchange

问:
Getting parameters from Object
I really need your help. Dont be scared of a title, cause I dont really know how to describe a problem. So I have an array

```<code>public static final Server[] SERVERS = {
        new Server(0, "Test0", "localhost", "00000", "client"),
        new Server(1, "Test1", "localhost", "00001", "client"),
        new Server(2, "Test2", "localhost", "00002", "client")
};
</code>```

How can I get Test0, Test1 and Test2 from that array? I thought about SERVERS[2], but that will select whole object. I have no clue how to get that..
I will really appreciate your help. Thank you in advance :3

P.S.For example:

File f = new File("abc");

How can I call that thing, which is in brackets? I mean whats a proper name of "abc"? Parameter? Variable?

答:
Remember Servers is an array of servers, so you can do SERVERS[x] and that will give you access to the server object located at the given index x.

After that you just need to use the getters, something like:

```<code>String name = SERVERS[2].getName();
int index = SERVERS[2].getIndex();
//etc etc
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting parameters from Object

Body:
I really need your help. Dont be scared of a title, cause I dont really know how to describe a problem. So I have an array

public static final Server[] SERVERS = {
        new Server(0, "Test0", "localhost", "00000", "client"),
        new Server(1, "Test1", "localhost", "00001", "client"),
        new Server(2, "Test2", "localhost", "00002", "client")
};

How can I get Test0, Test1 and Test2 from that array? I thought about SERVERS[2], but that will select whole object. I have no clue how to get that..
I will really appreciate your help. Thank you in advance :3

P.S.For example:

File f = new File("abc");

How can I call that thing, which is in brackets? I mean whats a proper name of "abc"? Parameter? Variable?

Body:
Remember Servers is an array of servers, so you can do SERVERS[x] and that will give you access to the server object located at the given index x.

After that you just need to use the getters, something like:

String name = SERVERS[2].getName();
int index = SERVERS[2].getIndex();
//etc etc


问:
net/http: concurrency and message passing between coroutines
I am working on a REST API server and one of the features of the server is being able to notify arbitrary number of client via a websocket when a new resource is created or an existing one is modified.

I have a custom action router to bind an URL to a function and gorillas's implementation of websocket library. For IPC I have decided to rely on channels as it appears to be the idiomatic way to communicate between coroutines. Also it behaves like a pipe which is a concept I am familiar with.

A prototype for a function Create looks like this:

```<code>func Create (res http.ResponseWriter, req *http.Request, userdata interface {}) (int, string, interface {})
</code>```

As a userdata an instance of a structure PipeSet is passed. It is a map that is shared between all coroutines where a key is an address (a pointer to) of a Pipe and value the same thing. The rationale here is to speed up a lookup process when deleting.

```<code>type Pipe chan string

type PipeSet struct {
    sync.Mutex
    Pipes map [*Pipe] *Pipe
}

func NewPipe () Pipe {
    return make (Pipe)
}

func NewPipeSet () PipeSet {
    var newSet PipeSet
    newSet.Pipes = make (map[*Pipe] *Pipe)
    return newSet
}

func (o *PipeSet) AddPipe (pipe *Pipe) {
    o.Lock ()
    o.Pipes[pipe] = pipe
    o.Unlock ()
}

func (o *PipeSet) ForeachPipe (f func (pipe Pipe)) {
    o.Lock ()
    for k := range (o.Pipes) {
        f (*o.Pipes[k])
    }
    o.Unlock ()
}

func (o *PipeSet) DeletePipe (pipe *Pipe) {
    o.Lock ()
    delete (o.Pipes, pipe)
    o.Unlock ()
}
</code>```

When a client connects via websocket a new channel (a Pipe) is created and added to a shared PipeSet. Then if a new resource is created a coroutine goes through an entire PipeSet sending a message to each Pipe. The message is then forwarded to a connected clients on the other side.

A problem area

I am unable to detect whether client's websocket connection is still there. I need to know that to determine whether I should remove a Pipe from the PipeSet. I am relying on CloseNotifier in this case. It never fires.

The code looks like this (excerpt):

```<code>var upgrader = websocket.Upgrader {
    CheckOrigin: func (r *http.Request) bool { return true },
}

conn, err := upgrader.Upgrade (res, req, nil)

if err != nil {
    marker.MarkError (err)
    return http.StatusBadRequest, "", nil
}

defer conn.Close ()

exitStatus = http.StatusOK
pipe := genstore.NewPipe ()
quit := res.(http.CloseNotifier).CloseNotify ()

genStore.WSChannels.AddPipe (&pipe)

for {
    log.Printf ("waiting for a message")

    select {
        case wsMsg = <-pipe:
            log.Printf ("got a message: %s (num pipes %d)", wsMsg, len (genStore.WSChannels.Pipes))

            if err = conn.WriteMessage (websocket.TextMessage, []byte (wsMsg)); err != nil {
                marker.MarkError (err)
                goto egress
            }

        case <-quit:
            log.Printf ("quit...")
            goto egress
    }
}

egress:
genStore.WSChannels.DeletePipe (&pipe)
</code>```

答:
When you upgrade HTTP connection to a WebSocket connection using Gorilla, it hijacks that connection and net/http server stops serving it. This means, that you can't rely on a net/http events from that moment.

Check this: https://github.com/gorilla/websocket/issues/123

So, what you can do here is to start new goroutine for every new WebSocket connection, which will read data from this connection and write a message to a quit channel on a failure.

Body:
I am working on a REST API server and one of the features of the server is being able to notify arbitrary number of client via a websocket when a new resource is created or an existing one is modified.

I have a custom action router to bind an URL to a function and gorillas's implementation of websocket library. For IPC I have decided to rely on channels as it appears to be the idiomatic way to communicate between coroutines. Also it behaves like a pipe which is a concept I am familiar with.

A prototype for a function Create looks like this:

func Create (res http.ResponseWriter, req *http.Request, userdata interface {}) (int, string, interface {})

As a userdata an instance of a structure PipeSet is passed. It is a map that is shared between all coroutines where a key is an address (a pointer to) of a Pipe and value the same thing. The rationale here is to speed up a lookup process when deleting.

type Pipe chan string

type PipeSet struct {
    sync.Mutex
    Pipes map [*Pipe] *Pipe
}

func NewPipe () Pipe {
    return make (Pipe)
}

func NewPipeSet () PipeSet {
    var newSet PipeSet
    newSet.Pipes = make (map[*Pipe] *Pipe)
    return newSet
}

func (o *PipeSet) AddPipe (pipe *Pipe) {
    o.Lock ()
    o.Pipes[pipe] = pipe
    o.Unlock ()
}

func (o *PipeSet) ForeachPipe (f func (pipe Pipe)) {
    o.Lock ()
    for k := range (o.Pipes) {
        f (*o.Pipes[k])
    }
    o.Unlock ()
}

func (o *PipeSet) DeletePipe (pipe *Pipe) {
    o.Lock ()
    delete (o.Pipes, pipe)
    o.Unlock ()
}

When a client connects via websocket a new channel (a Pipe) is created and added to a shared PipeSet. Then if a new resource is created a coroutine goes through an entire PipeSet sending a message to each Pipe. The message is then forwarded to a connected clients on the other side.

A problem area

I am unable to detect whether client's websocket connection is still there. I need to know that to determine whether I should remove a Pipe from the PipeSet. I am relying on CloseNotifier in this case. It never fires.

The code looks like this (excerpt):

var upgrader = websocket.Upgrader {
    CheckOrigin: func (r *http.Request) bool { return true },
}

conn, err := upgrader.Upgrade (res, req, nil)

if err != nil {
    marker.MarkError (err)
    return http.StatusBadRequest, "", nil
}

defer conn.Close ()

exitStatus = http.StatusOK
pipe := genstore.NewPipe ()
quit := res.(http.CloseNotifier).CloseNotify ()

genStore.WSChannels.AddPipe (&pipe)

for {
    log.Printf ("waiting for a message")

    select {
        case wsMsg = <-pipe:
            log.Printf ("got a message: %s (num pipes %d)", wsMsg, len (genStore.WSChannels.Pipes))

            if err = conn.WriteMessage (websocket.TextMessage, []byte (wsMsg)); err != nil {
                marker.MarkError (err)
                goto egress
            }

        case <-quit:
            log.Printf ("quit...")
            goto egress
    }
}

egress:
genStore.WSChannels.DeletePipe (&pipe)


问:
How can I globally configure a Cargo profile option?
With Cargo, I can set a project's development settings to use parallel code generation:

```<code>[profile.dev]
codegen-units = 8
</code>```

According to the documentation, it should be possible to put this into ~/.cargo/config to apply this setting to all projects.  This doesn't work for me: it seems that the .cargo/config file isn't used at all.  Is there any way to apply such configuration to every project I compile?

答:
You can set rustflags for all builds or per target in your .cargo/config file.

```<code>[build] # or [target.$triple]
rustflags = ["-Ccodegen-units=4"]
</code>```

To be clear, this will set the codegen-units for all your projects (covered by this .cargo/config) regardless of profile.

To make sure it's actually set, you can also set verbose output in the same file. This will show each rustc command with flags that cargo invokes.

```<code>[term]
verbose = true
</code>```

Body:
With Cargo, I can set a project's development settings to use parallel code generation:

[profile.dev]
codegen-units = 8

According to the documentation, it should be possible to put this into ~/.cargo/config to apply this setting to all projects.  This doesn't work for me: it seems that the .cargo/config file isn't used at all.  Is there any way to apply such configuration to every project I compile?

Body:
You can set rustflags for all builds or per target in your .cargo/config file.

[build] # or [target.$triple]
rustflags = ["-Ccodegen-units=4"]

To be clear, this will set the codegen-units for all your projects (covered by this .cargo/config) regardless of profile.

To make sure it's actually set, you can also set verbose output in the same file. This will show each rustc command with flags that cargo invokes.

[term]
verbose = true


问:
Error "python: not found" in Dockerized PHP application hosted on Elastic Beanstalk
I have a PHP application which will compile Python code upon submission from users and then return the result. The application is hosted on Elastic Beanstalk and it is working fine until I wish to have it runs within a Docker container.

For the working version, I deploy the application on Amazon Elastic Beanstalk running on a platform 64bit Amazon Linux with PHP 7.0 and submit a simple code, for example, print(1+1), I will get the result as 2.

To run the application within a Docker container, I followed the instructions from the tutorial
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker_ecstutorial.html#create_deploy_docker_ecstutorial_connect
, modified its php-app folder to contain my own PHP application and set the platform to Multi-container Docker.

However, when I tried to submit a simple code like print(1+1), I got the result as

Array
(
    [0] => sh: 1: python: not found
)

I checked with my EC2 instance and confirmed that the instance has python installed. The PHP application should not have caused this error(I guess) since it is running perfectly on another platform. So my problem is why can't I get the result instead of having a python not found error?

I am new to AWS and Docker. Please forgive me if I am not expressing my problem clear enough. Do let me know if you need my console output in EC2 instance or my application files or whatever that helps. All bits of help are appreciated!

答:
When running the PHP application in the container, you're using the php:fpm base image, which doesn't come with Python installed. Ideally, you'd write your own Dockerfile and list Python as one of your dependencies. If you want to stick to the Elastic Beanstalk format, one way to get around this is by ensuring that Python is installed when starting the container. The cotainerDefinitions parameter in Dockerrun.aws.json allows, according to the documentation, to include the usual parameters of an ECS Task Definition, so you can include one more field called "command" (which maps to the CMD command in the Docker API), and set it to ["apt-get", "update", "&&", "apt-get", "install", "python"]:

```<code>  "containerDefinitions": [
    {
      "name": "php-app",
      "image": "php:fpm",
      "essential": true,
      "memory": 128,
      "mountPoints": [
        {
          "sourceVolume": "php-app",
          "containerPath": "/var/www/html",
          "readOnly": true,
          "command": ["apt-get", "update", "&&", "apt-get", "install", "python"]
        }
      ]
    },
</code>```

That will install Python when spinning up the container, and make it available to the PHP application.
Alternatively, you can create your own base image from php:fpm, install Python on it, upload it to ECR, and include its URI in the containerDefinitions: image parmeter (instead of php:fpm).

Body:
When running the PHP application in the container, you're using the php:fpm base image, which doesn't come with Python installed. Ideally, you'd write your own Dockerfile and list Python as one of your dependencies. If you want to stick to the Elastic Beanstalk format, one way to get around this is by ensuring that Python is installed when starting the container. The cotainerDefinitions parameter in Dockerrun.aws.json allows, according to the documentation, to include the usual parameters of an ECS Task Definition, so you can include one more field called "command" (which maps to the CMD command in the Docker API), and set it to ["apt-get", "update", "&&", "apt-get", "install", "python"]:

  "containerDefinitions": [
    {
      "name": "php-app",
      "image": "php:fpm",
      "essential": true,
      "memory": 128,
      "mountPoints": [
        {
          "sourceVolume": "php-app",
          "containerPath": "/var/www/html",
          "readOnly": true,
          "command": ["apt-get", "update", "&&", "apt-get", "install", "python"]
        }
      ]
    },

That will install Python when spinning up the container, and make it available to the PHP application.
Alternatively, you can create your own base image from php:fpm, install Python on it, upload it to ECR, and include its URI in the containerDefinitions: image parmeter (instead of php:fpm).


问:
Access to heroku logs without access to app itself
Say, i have a team of developers. I want them to have access to production logs, but nothing else. Preferably they shouldn't even know the heroku's internal app name.

How do i do that?

答:
I don't think it's possible (at the moment) with Heroku command line. You have two options:

Use one of the logging addons and give your teammates access to the logging app only

Write yourself a log drain for Heroku logplex route the logs to AWS S3, your own DB or other, then give your teammates some way to view the logs.


问:
zoom only the clicked part of image JQuery
I am trying to get the image zooming effect using JQuery.

I have only one image that is of higher resolution, When i click any part of that image, i want to get the zoomed view of that part.

For example, i have one computer monitor image.Now if i click the button of monitor on image, the button should get zoomed.

I tried using this
http://jaukia.github.io/zoomooz/ but it is zooming the whole element.

How can i do this? are there any JQuery plugins available?

答:
zoom.js is also a good option. Here is the demo of that plugin.

If you are intrested in here is the source code


问:
No provider for RouterOutletMap

Newest Angular 2.0.0 and via newest angular-cli 1.0.0-beta.14, node: 6.6.0, os: linux x64

What I do:

1) Create new project

```<code>ng new angular-test
ng g component projects
ng g component typings
</code>```

2) Add simple routing

/src/app/app.component.html

```<code> <router-outlet></router-outlet>
</code>```

/src/app/app.module.ts

```<code>export const ROUTES: Routes = [
  {
    path: '',
    redirectTo: '/projects',
    pathMatch: 'full'
  },
  {
    path: 'projects',
    component: ProjectsComponent,
  },
  {
    path: '/typings',
    component: TypingsComponent
  },
  {
    path: '**', redirectTo: ''
  }
];

@NgModule({
  declarations: [
    AppComponent,
    ProjectsComponent,
    TypingsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forChild(ROUTES)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

What I get:

```<code>EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:0 caused by: No provider for RouterOutletMap!
ORIGINAL EXCEPTION: No provider for RouterOutletMap!
</code>```

How I tried to fix this

I tried to add RouterOutletMap to providers in AppModule, exception don't throw, but app don't redirect to projects and don't show nesting components

答:
I also had this issue and . this is how i avoid that..... some time this will be helped.
best wishes!

The Routing array -- app.routes.ts

```<code>const appRoutes:Routes =[
 {
   path: 'home',
   component: CarouselComponent
 },
 {
  path: 'profile',
  component:UserDashboardComponentComponent,
  children: [
     {
      path: 'overview',
      component: ProfileOverviewComponent
     },
     {
      path: 'post',
      component: PostAddComponent
     }
    ]
   }
];

 export const WebRouting: ModuleWithProviders =RouterModule.forRoot(appRoutes);
</code>```

app.module.ts

```<code>@NgModule({
 declarations: [
  AppComponent,
  CarouselComponent,
  .......
],
 imports: [
  BrowserModule,
  MdTabsModule,
  MaterialModule,
  MdInputModule,
  BrowserAnimationsModule,
  FormsModule,
  HttpModule,
  WebRouting
],
 providers: [],
 bootstrap: [AppComponent],
})

export class AppModule { }
</code>```

tempale.html

```<code>  <li>
    <a [routerLink]="['/profile/overview']" routerLinkActive="active" >
      Overview
    </a>
  </li>
  <li>
    <a [routerLink]="['/profile/post']"routerLinkActive="active">
      PostAdd
    </a>
  </li>
</code>```

Title: No provider for RouterOutletMap

Body:
Newest Angular 2.0.0 and via newest angular-cli 1.0.0-beta.14, node: 6.6.0, os: linux x64

What I do:

1) Create new project

ng new angular-test
ng g component projects
ng g component typings

2) Add simple routing

/src/app/app.component.html

 <router-outlet></router-outlet>

/src/app/app.module.ts

export const ROUTES: Routes = [
  {
    path: '',
    redirectTo: '/projects',
    pathMatch: 'full'
  },
  {
    path: 'projects',
    component: ProjectsComponent,
  },
  {
    path: '/typings',
    component: TypingsComponent
  },
  {
    path: '**', redirectTo: ''
  }
];

@NgModule({
  declarations: [
    AppComponent,
    ProjectsComponent,
    TypingsComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forChild(ROUTES)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

What I get:

EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:0 caused by: No provider for RouterOutletMap!
ORIGINAL EXCEPTION: No provider for RouterOutletMap!

How I tried to fix this

I tried to add RouterOutletMap to providers in AppModule, exception don't throw, but app don't redirect to projects and don't show nesting components

Body:
I also had this issue and . this is how i avoid that..... some time this will be helped.
best wishes!

The Routing array -- app.routes.ts

const appRoutes:Routes =[
 {
   path: 'home',
   component: CarouselComponent
 },
 {
  path: 'profile',
  component:UserDashboardComponentComponent,
  children: [
     {
      path: 'overview',
      component: ProfileOverviewComponent
     },
     {
      path: 'post',
      component: PostAddComponent
     }
    ]
   }
];

 export const WebRouting: ModuleWithProviders =RouterModule.forRoot(appRoutes);

app.module.ts

@NgModule({
 declarations: [
  AppComponent,
  CarouselComponent,
  .......
],
 imports: [
  BrowserModule,
  MdTabsModule,
  MaterialModule,
  MdInputModule,
  BrowserAnimationsModule,
  FormsModule,
  HttpModule,
  WebRouting
],
 providers: [],
 bootstrap: [AppComponent],
})

export class AppModule { }

tempale.html

  <li>
    <a [routerLink]="['/profile/overview']" routerLinkActive="active" >
      Overview
    </a>
  </li>
  <li>
    <a [routerLink]="['/profile/post']"routerLinkActive="active">
      PostAdd
    </a>
  </li>


问:
Navigation in UWP app causes memory leak
I have a root page which contains a SplitView and it contains a rootFrame. I show my app's pages in this frame.

```<code><SplitView DisplayMode="Overlay">
    <SplitView.Pane>
        <Grid/>
    </SplitView.Pane>
    <Frame x:Name="rootFrame"/>
</SplitView>
</code>```

I navigate from one page to another with this code

```<code>myRootPage.rootFrame.Navigate(typeof(MySecondPage));
</code>```

The problem is that after a few navigation back and forth memory usage increases and finally app crashes!

using Memory Profiler in Visual Studio, I noticed the huge increase happens after navigating back. but I don't know where should I look in the report to see what causes that.

How to avoid this? Any help is much appreciated.

答:
Set NavigationCacheMode to NavigationCacheMode.Required so the app will not create a new instance of your page every time you navigate to it but only for the first time:

```<code><Page <!-- some unrelated XAML code -->
      NavigationCacheMode="Required"
      >
</code>```

Body:
I have a root page which contains a SplitView and it contains a rootFrame. I show my app's pages in this frame.

<SplitView DisplayMode="Overlay">
    <SplitView.Pane>
        <Grid/>
    </SplitView.Pane>
    <Frame x:Name="rootFrame"/>
</SplitView>

I navigate from one page to another with this code

myRootPage.rootFrame.Navigate(typeof(MySecondPage));

The problem is that after a few navigation back and forth memory usage increases and finally app crashes!

using Memory Profiler in Visual Studio, I noticed the huge increase happens after navigating back. but I don't know where should I look in the report to see what causes that.

How to avoid this? Any help is much appreciated.

Body:
Set NavigationCacheMode to NavigationCacheMode.Required so the app will not create a new instance of your page every time you navigate to it but only for the first time:

<Page <!-- some unrelated XAML code -->
      NavigationCacheMode="Required"
      >


答:
You have to provide a method that returns the server name in the Server class.

For example :

```<code>public String getName(){
  return name;
}
</code>```

In this way you could do it to retrieve it :

```<code>String name = SERVERS[2].getName();
</code>```

Title: Getting parameters from Object

Body:
You have to provide a method that returns the server name in the Server class.

For example :

public String getName(){
  return name;
}

In this way you could do it to retrieve it :

String name = SERVERS[2].getName();


问:
In Django forms, how do I "add" an error into the queue?
```<code>def clean(self):
        cleaned_data = self.cleaned_data
        current_pass = cleaned_data['current_pass']
        new_pass = cleaned_data['new_pass']
        new_pass2 = cleaned_data['new_pass2']
        if current_pass or new_pass or new_pass2:
            if not current_pass:
                raise forms.ValidationError("- You must enter your current password.")
            if not new_pass:
                raise forms.ValidationError("- You must enter a new password.")
            if not new_pass2:
                raise forms.ValidationError("- You must re-confirm your new password.")
        return cleaned_data
</code>```

Right now, I raise my errors. But this means that the other errors won't pop up. it ends the function when I raise the first one. What if I want to have all 3 errors?

答:
(This is a Python question not a Django question.)

This is as it should be: when an error is raised it should immediately propagate upwards until it's handled. You can't expect the rest of the function to be evaluated, because the error hasn't been dealt with yet!

Probably the easiest and cleanest method is to rewrite the code:

```<code>check = (current_pass, new_pass, new_pass2)
code = ("You must enter your current password.", ...)
err = ''.join(code for i, code in enumerate(codes) if check[i])
if err:
    raise forms.ValidationError(err)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
def clean(self):
        cleaned_data = self.cleaned_data
        current_pass = cleaned_data['current_pass']
        new_pass = cleaned_data['new_pass']
        new_pass2 = cleaned_data['new_pass2']
        if current_pass or new_pass or new_pass2:
            if not current_pass:
                raise forms.ValidationError("- You must enter your current password.")
            if not new_pass:
                raise forms.ValidationError("- You must enter a new password.")
            if not new_pass2:
                raise forms.ValidationError("- You must re-confirm your new password.")
        return cleaned_data

Right now, I raise my errors. But this means that the other errors won't pop up. it ends the function when I raise the first one. What if I want to have all 3 errors?

Body:
(This is a Python question not a Django question.)

This is as it should be: when an error is raised it should immediately propagate upwards until it's handled. You can't expect the rest of the function to be evaluated, because the error hasn't been dealt with yet!

Probably the easiest and cleanest method is to rewrite the code:

check = (current_pass, new_pass, new_pass2)
code = ("You must enter your current password.", ...)
err = ''.join(code for i, code in enumerate(codes) if check[i])
if err:
    raise forms.ValidationError(err)


问:
how can I convert a text file with numbers seperated by white space to a CSV file with Python 3
Hello i want to pull data from a numeric website and convert it to a csv file. i was first storing the data in a text file then convert it to a csv file.
how do i get this to work ?</p>

```<code>     <code>
    <while t > 0:
    f = open("testtext.txt", "a")
    url = "http://www.kool.com/en/results"
     newString = newString + " " + data1[start:end]
    print(newString)

    f.write(newString + '\n')
    f.close()
    t =t -1
    x =x - 1
    print("DONE")

  </code>
</code>```

答:
```<code>string = string.replace(" ", ",")
</code>```

This replaces spaces with commas.

Body:
Hello i want to pull data from a numeric website and convert it to a csv file. i was first storing the data in a text file then convert it to a csv file.
how do i get this to work ?

    <while t > 0:
    f = open("testtext.txt", "a")
    url = "http://www.kool.com/en/results"
     newString = newString + " " + data1[start:end]
    print(newString)

    f.write(newString + '\n')
    f.close()
    t =t -1
    x =x - 1
    print("DONE")

Body:
string = string.replace(" ", ",")

This replaces spaces with commas.


问:
OpenAI Gym Atari on Windows
I'm having issues installing OpenAI Gym Atari environment on Windows 10. I have successfully installed and used OpenAI Gym already on the same system.

It keeps tripping up when trying to run a makefile.

I am running the command pip install gym[atari]

Here is the error:

and here is what I currently have on my system...cmake and make are both clearly installed.

答:
This is not fully tested, because I don't remember exactly what I did, but currently I have openAI gym running with all the atari games set up and displaying, and also matplotlib plots, all while using ubuntu on windows (WSL).  In fact I have sublimetext3 and spider working too.

So take these as a guide, but I don't have "clean" environment to test them on.

First, in Windows, Google "xming" (x11 server) and download from sourceforge / install / run.  This is what makes it all possible.

Now in WSL bash install the display stuff to work with xming

```<code>sudo apt-get install x11-apps
export DISPLAY=localhost:0.0
nano ~/.bashrc  #(add  export DISPLAY=localhost:0.0   at the end. Ctrl+X to exit/save)
sudo apt-get install gnome-calculator #will get you GTK
</code>```

Now in WSL bash install Anaconda.  this will involve downloading the .sh file (eg with curl -O "[the http link to latest anaconda]" and running it with bash [the file].sh. Don't use sudo when installing Anaconda.

With anaconda installed, close WSL, and restart it. Now make an environment and activate it

```<code>conda create -n gym python=3.5 anaconda
source activate gym
</code>```

Now get the gym repo

```<code>git clone https://github.com/openai/gym.git
cd gym
</code>```

Now install these gym dependencies mentioned on openai gym repo

```<code>apt-get install -y python-numpy python-dev cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig
</code>```

Now install libgcc with conda

```<code>conda install libgcc
</code>```

Now build gym

```<code>pip install -e '.[all]'
</code>```

That's basically it.  make sure Xming is running on windows, and in WSL type gnome-calculator, and it should bring up the calculator. if it doesn't, keep working on the display side.  If it does, try running some of the agents in the gym examples folder.

I may have missed a couple extra dependencies along the way, but these would have been things I figured out based on error messages.

Here's the pic to keep you motivated:

EDIT: Today I ran the following command which installed Qt5 as the back end, and matplotlib is working fine with Qt5Agg as the back end (vs TkAgg).  This may be helpful if you're running some thing else on WSL which needs Qt5

sudo apt-get update && sudo apt-get install qtbase5-dev

Also, to find your matplotlibrc, and command prompt type:

python
import matplotlib
print(matplotlib.matplotlib_fname())
quit()

Please note that there is NO GPU SUPPORT on ubuntu for windows. This is the top requested feature at uservoice, yet MS has it on "backlog".  If you're interested, vote here

Title: OpenAI Gym Atari on Windows

Body:
This is not fully tested, because I don't remember exactly what I did, but currently I have openAI gym running with all the atari games set up and displaying, and also matplotlib plots, all while using ubuntu on windows (WSL).  In fact I have sublimetext3 and spider working too.

So take these as a guide, but I don't have "clean" environment to test them on.

First, in Windows, Google "xming" (x11 server) and download from sourceforge / install / run.  This is what makes it all possible.

Now in WSL bash install the display stuff to work with xming

sudo apt-get install x11-apps
export DISPLAY=localhost:0.0
nano ~/.bashrc  #(add  export DISPLAY=localhost:0.0   at the end. Ctrl+X to exit/save)
sudo apt-get install gnome-calculator #will get you GTK

Now in WSL bash install Anaconda.  this will involve downloading the .sh file (eg with curl -O "[the http link to latest anaconda]" and running it with bash [the file].sh. Don't use sudo when installing Anaconda.

With anaconda installed, close WSL, and restart it. Now make an environment and activate it

conda create -n gym python=3.5 anaconda
source activate gym

Now get the gym repo

git clone https://github.com/openai/gym.git
cd gym

Now install these gym dependencies mentioned on openai gym repo

apt-get install -y python-numpy python-dev cmake zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig

Now install libgcc with conda

conda install libgcc

Now build gym

pip install -e '.[all]'

That's basically it.  make sure Xming is running on windows, and in WSL type gnome-calculator, and it should bring up the calculator. if it doesn't, keep working on the display side.  If it does, try running some of the agents in the gym examples folder.

I may have missed a couple extra dependencies along the way, but these would have been things I figured out based on error messages.

Here's the pic to keep you motivated:

EDIT: Today I ran the following command which installed Qt5 as the back end, and matplotlib is working fine with Qt5Agg as the back end (vs TkAgg).  This may be helpful if you're running some thing else on WSL which needs Qt5

sudo apt-get update && sudo apt-get install qtbase5-dev

Also, to find your matplotlibrc, and command prompt type:

python
import matplotlib
print(matplotlib.matplotlib_fname())
quit()

Please note that there is NO GPU SUPPORT on ubuntu for windows. This is the top requested feature at uservoice, yet MS has it on "backlog".  If you're interested, vote here


问:
Creating an Excel file on the fly and have it download/save on the client
Question: What is an alternative to the last three lines of the following code in ASP.NET Core 1.1 and/or what are workarounds? On these last three lines VS2015 is complaining HttpResponse does not contain a definition for OutputStream, Flush(), End()

Background: In my ASP.NET Core 1.1 app I'm using EPPlus.Core to export data on the fly to Excel and have it downloaded/save on the client side. As a starter, I'm trying to mimic the following example (taken from here), but VS2015 is not recognizing the last 3 lines of this code.

```<code>public void ExportListUsingEPPlus()
{
    var data = new[]{
                        new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" },
                        new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" },
                        new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" },
                        new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" },
                        new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" },
                        new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }
                };

    ExcelPackage excel = new ExcelPackage();
    var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
    workSheet.Cells[1, 1].LoadFromCollection(data, true);
    using (var memoryStream = new MemoryStream())
    {
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.Headers.Add("content-disposition", "attachment;  filename=Contact.xlsx");
        excel.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}
</code>```

答:
You can return one of FileStreamResult in Controller action.

It returns a file in the specified fileStream with the specified contentType as the Content-Type and the specified fileDownloadName as the suggested file name.

```<code>public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)
</code>```

EDIT:

Sample action method-

```<code>var data = new[]{
                        new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" },
                        new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" },
                        new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" },
                        new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" },
                        new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" },
                        new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }
                };

            ExcelPackage excel = new ExcelPackage();
            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
            workSheet.Cells[1, 1].LoadFromCollection(data, true);

            //var memoryStream = new MemoryStream(excel.GetAsByteArray());

            //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //Response.Headers.Add("content-disposition", "attachment;  filename=Contact.xlsx");
            //excel.SaveAs(memoryStream);
            //memoryStream.WriteTo(Response.OutputStream);
            //Response.Flush();
            //Response.End();

            return File(excel.GetAsByteArray(), "application/vnd.ms-excel", "Contact.xlsx");
</code>```

Generated Excel screenshot-

Body:
Question: What is an alternative to the last three lines of the following code in ASP.NET Core 1.1 and/or what are workarounds? On these last three lines VS2015 is complaining HttpResponse does not contain a definition for OutputStream, Flush(), End()

Background: In my ASP.NET Core 1.1 app I'm using EPPlus.Core to export data on the fly to Excel and have it downloaded/save on the client side. As a starter, I'm trying to mimic the following example (taken from here), but VS2015 is not recognizing the last 3 lines of this code.

public void ExportListUsingEPPlus()
{
    var data = new[]{
                        new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" },
                        new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" },
                        new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" },
                        new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" },
                        new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" },
                        new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }
                };

    ExcelPackage excel = new ExcelPackage();
    var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
    workSheet.Cells[1, 1].LoadFromCollection(data, true);
    using (var memoryStream = new MemoryStream())
    {
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.Headers.Add("content-disposition", "attachment;  filename=Contact.xlsx");
        excel.SaveAs(memoryStream);
        memoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}

Body:
You can return one of FileStreamResult in Controller action.

It returns a file in the specified fileStream with the specified contentType as the Content-Type and the specified fileDownloadName as the suggested file name.

public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)

EDIT:

Sample action method-

var data = new[]{
                        new{ Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" },
                        new{ Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" },
                        new{ Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" },
                        new{ Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" },
                        new{ Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" },
                        new{ Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }
                };

            ExcelPackage excel = new ExcelPackage();
            var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
            workSheet.Cells[1, 1].LoadFromCollection(data, true);

            //var memoryStream = new MemoryStream(excel.GetAsByteArray());

            //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //Response.Headers.Add("content-disposition", "attachment;  filename=Contact.xlsx");
            //excel.SaveAs(memoryStream);
            //memoryStream.WriteTo(Response.OutputStream);
            //Response.Flush();
            //Response.End();

            return File(excel.GetAsByteArray(), "application/vnd.ms-excel", "Contact.xlsx");

Generated Excel screenshot-


问:
Puppet can't use config set server
I've installed Puppet (version 4.10.1) via Ruby Gems.

I then use:

```<code>sudo puppet config set server mysite.org
</code>```

Which returns the following error (same error without sudo).

Error: No such file or directory @ rb_sysopen -
  /etc/puppetlabs/puppet/puppet.conf Error: Try 'puppet
  help config set' for usage

答:
The gem install does not create the configuration files, the packages will.

Puppet is best installed with a package for the operating system you're on, rather than the gem.

The steps for installing are documented here:

https://docs.puppet.com/puppet/4.10/install_linux.html

If you're feeling lazy, I even wrote a script that will do all the work for you!

https://github.com/petems/puppet-install-shell

Title: Puppet can't use config set server

Body:
I've installed Puppet (version 4.10.1) via Ruby Gems.

I then use:

sudo puppet config set server mysite.org

Which returns the following error (same error without sudo).

Error: No such file or directory @ rb_sysopen -
  /etc/puppetlabs/puppet/puppet.conf Error: Try 'puppet
  help config set' for usage


问:
Javascript foreach loop on list items
I have a basic HTML list like below...

```<code><ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>
</code>```

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string.  I have this so far..

```<code>var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}
</code>```

This isn't working for me, is it because it is not really an array?

答:
You're logging the index i, instead, use items[i].id to get the id of the matched element. Something like this

var items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
  console.log(items[i].id);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="test_ul">
  <li class="item" id="item1">
    Item 1
  </li>
  <li class="item" id="item2">
    Item 2
  </li>
  <li class="item" id="item3">
    Item 3
  </li>
  <li class="item" id="item4">
    Item 4
  </li>
</ul></code>```

Title: Javascript foreach loop on list items

Body:
I have a basic HTML list like below...

        Item 1

        Item 2

        Item 3

        Item 4

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string.  I have this so far..

var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}

This isn't working for me, is it because it is not really an array?

Body:
You're logging the index i, instead, use items[i].id to get the id of the matched element. Something like this

var items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
  console.log(items[i].id);
}

<ul class="test_ul">
  <li class="item" id="item1">
    Item 1
  </li>
  <li class="item" id="item2">
    Item 2
  </li>
  <li class="item" id="item3">
    Item 3
  </li>
  <li class="item" id="item4">
    Item 4
  </li>
</ul>


问:
PHP OOP question
I have a syntax question about PHP OOP.

I have two functions.

```<code>public function setBody($body) {
  $this->body = $body;
 }

public function return_value($value) {
  return $value;
 }
</code>```

$body is declared higher up in the function.  if I want to call the return_value function (which I realize does nothing -- it's just an example for me to use to learn) on setBody, what's the syntax for that?

I tried $this->body = return_value($body) and it didn't work.  I also tried return_value($this->body) as a second line as well, and it didn't work either.

Thanks in advance for your help.

答:
You use the $this-> notation on both the property and the method, like this:

```<code>public function setBody($body) {
    $this->body = $this->return_value($body);
}
</code>```

Title: PHP OOP question

Body:
I have a syntax question about PHP OOP.

I have two functions.

public function setBody($body) {
  $this->body = $body;
 }

public function return_value($value) {
  return $value;
 }

$body is declared higher up in the function.  if I want to call the return_value function (which I realize does nothing -- it's just an example for me to use to learn) on setBody, what's the syntax for that?

I tried $this->body = return_value($body) and it didn't work.  I also tried return_value($this->body) as a second line as well, and it didn't work either.

Thanks in advance for your help.

Body:
You use the $this-> notation on both the property and the method, like this:

public function setBody($body) {
    $this->body = $this->return_value($body);
}


问:
String-literals without escaping null-character
When I built a function which gives the hexadecimal representation of a nibble (4 bits) and I looked at the binary file, for the lookuptable of the digits, there was an additional 0-char even if it was not used.

```<code>const char digits[] = "0123456789abcdef";
</code>```

I know that you can write it in form of an array:

```<code>const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
</code>```

But that would take a while to write and use more disk-space for other numerical-systems with more digits.
But is there any way to write it as a literal, but without the null-character at the end?

(I am using Clang with -std=c++14)

答:
I have no idea why you'd want to do such a thing, but if you can cope with using a compiler extension, Clang and GCC will let you write a templated user-defined literal operator which will chop off the trailing null:

```<code>template <typename CharT, std::size_t N>
struct string_literal {
    static constexpr std::size_t size = N;
    const CharT str[N];
};

template <typename CharT, CharT... Str>
constexpr string_literal<CharT, sizeof...(Str)> operator"" _lit()
{
    return {{ Str... }};
}

int main()
{
    constexpr auto s = "test"_lit;
    static_assert(s.size == 4);
    static_assert(s.str[0] == 't'); // etc
}
</code>```

(Returning a std::array<const char, N> is another option.)

I've no idea whether this is what you're after, but then I don't really understand the motivation to be honest -- even back in the 70s the designers of C weren't too worried about "wasting" a single byte in string literal.

Body:
When I built a function which gives the hexadecimal representation of a nibble (4 bits) and I looked at the binary file, for the lookuptable of the digits, there was an additional 0-char even if it was not used.

const char digits[] = "0123456789abcdef";

I know that you can write it in form of an array:

const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

But that would take a while to write and use more disk-space for other numerical-systems with more digits.
But is there any way to write it as a literal, but without the null-character at the end?

(I am using Clang with -std=c++14)

Body:
I have no idea why you'd want to do such a thing, but if you can cope with using a compiler extension, Clang and GCC will let you write a templated user-defined literal operator which will chop off the trailing null:

template <typename CharT, std::size_t N>
struct string_literal {
    static constexpr std::size_t size = N;
    const CharT str[N];
};

template <typename CharT, CharT... Str>
constexpr string_literal<CharT, sizeof...(Str)> operator"" _lit()
{
    return {{ Str... }};
}

int main()
{
    constexpr auto s = "test"_lit;
    static_assert(s.size == 4);
    static_assert(s.str[0] == 't'); // etc
}

(Returning a std::array<const char, N> is another option.)

I've no idea whether this is what you're after, but then I don't really understand the motivation to be honest -- even back in the 70s the designers of C weren't too worried about "wasting" a single byte in string literal.


答:
Using ES6 (might need to transpile or add polyfills for older browsers):

// Get the DOMCollection of node corresponding to the item class
var items = document.getElementsByClassName("item")
// Transform the DOMCollection to an array and map item.id
  , ids = Array.from(items).map(item => item.id);
  ;
console.log(ids);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul></code>```

Using ES5 only:

var items = document.getElementsByClassName("item")
  , ids = []
  ;
for(var i = 0, c = items.length; i<c; i++) {
    ids.push(items[i].id);
}
console.log(ids);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <ul class="test_ul">
        <li class="item" id="item1">
            Item 1
        </li>
        <li class="item" id="item2">
            Item 2
        </li>
        <li class="item" id="item3">
            Item 3
        </li>
        <li class="item" id="item4">
            Item 4
        </li>
    </ul></code>```

Title: Javascript foreach loop on list items

Body:
Using ES6 (might need to transpile or add polyfills for older browsers):

// Get the DOMCollection of node corresponding to the item class
var items = document.getElementsByClassName("item")
// Transform the DOMCollection to an array and map item.id
  , ids = Array.from(items).map(item => item.id);
  ;
console.log(ids);

<ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>

Using ES5 only:

var items = document.getElementsByClassName("item")
  , ids = []
  ;
for(var i = 0, c = items.length; i<c; i++) {
    ids.push(items[i].id);
}
console.log(ids);

    <ul class="test_ul">
        <li class="item" id="item1">
            Item 1
        </li>
        <li class="item" id="item2">
            Item 2
        </li>
        <li class="item" id="item3">
            Item 3
        </li>
        <li class="item" id="item4">
            Item 4
        </li>
    </ul>

ContentLicense: CC BY-SA 4.0


问:
Security considerations when using Google Play App Signing
I just enrolled to App Signing in Play console and everything works great.

But how should I treat my new upload keystore and its passwords now?
Can I just put this keystore under version control and put passwords into build script in plain text?

As I understand this keystore is only used to temporary sign my apk prior to upload. So I consider it to be pretty safe, since nobody except myself can actually upload new apk to Play, and there is no option to access my original release keystore by knowing upload keys.

Another thing that bothers me now is that I can't see any option to change upload keystore. Is it possible now, or at least planned to be added to Play console soon? If I'll publish my upload keystore and passwords to version control it would be nice to have an option to switch to a new private keystore, if something will go wrong.

答:
The way you handle your keystore is pretty personal, but publishing it into your source control specially with the password is not a good idea.

You are right when you say that only you can upload the apk into your account, but your account can be compromized for various reasons, so it is always good to have a second step to upload any apk for your account.

When I worked into a team, since  we had a private source control we upload the keystore with our codebase. But the password was managed through 1password.

Now that I work alone, I handle myself my keystore.

About your question to changing the keystore. This is not possible. That are two things you can't change after you uploaded your apk: the package and the keystore. This is done for security reasons.

You can have more info here: https://developer.android.com/training/articles/keystore.html


问:
free function seems to not work
I have this problem in C, happened about 3 times and I just cant find the answer.
I'm allocating  a memory in a create function, and when I'm trying to free it in a destroy the program crashes.

Here is the program:

```<code>typedef struct Order_t* Order;
struct Order_t {
    char* email;
    TechnionFaculty faculty;
    int id;
    char* time;
    int num_ppl;
};

Order createOrder(char* email, TechnionFaculty faculty, int id, char* time,
    int num_ppl)
{
    if (email == NULL) {
        return NULL;
    }
    if (checkEmail(email) != OK)
        return NULL;
    if (checkFaculty(faculty) != OK)
        return NULL;
    Order order = malloc(sizeof(Order));
    if (order == NULL)
        return NULL;
    (order->email) = malloc(strlen(email) + 1);
    if (order->email == NULL) {
        free(order);
        return NULL;
    }
    strcpy(order->email, email);
    order->faculty = faculty;
    order->id = id;
    order->num_ppl = num_ppl;
    order->time = malloc(strlen(time) + 1);
    if (order->time == NULL) {
        free(order->email);
        free(order);
        return NULL;
    }
    return order;
}

void orderDestroy(Order order)
{
    assert(order != NULL);
    free(order->email);
    free(order->time);
    free(order);
}
</code>```

答:
I did some small changes to your code so that it doesn't crash. When using a struct you should allocate both the struct and its members. I hope it can help you.

```<code>#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#include <assert.h>

typedef struct Order_t *Order;
struct Order_t{
    char* email;
    //TechnionFaculty faculty;
    int id;
    char* time;
    int num_ppl;
};

Order createOrder (char* email, int id, char* time, int num_ppl){
    if (email == NULL) {
        return NULL;
    }

    Order order = malloc(sizeof(struct Order_t));
    if (order == NULL)
        return NULL;
    (order->email) = malloc(strlen(email)+1);
    if (order->email == NULL){
        free(order);
        return NULL;
    }
    strcpy(order->email, email);
    order->id = id;
    order->num_ppl = num_ppl;
    (order->time) = malloc(strlen(time)+1);
    if (order->time == NULL){
        free(order->email);
        free(order);
        return NULL;
    }
    return order;
}

void orderDestroy (Order order){
    assert(order != NULL);
    free(order->email);
    free(order->time);
    free(order);
}

int main() {
    printf("Hello, World!\n");
    Order o1 = createOrder("foo", 42, "24", 420);
    orderDestroy(o1);
    return 0;
}
</code>```

We check it with valgrind.

```<code>$ ./a.out
Hello, World!
developer@1604:~/CLionProjects/untitled4$ valgrind ./a.out
==16288== Memcheck, a memory error detector
==16288== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==16288== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==16288== Command: ./a.out
==16288==
Hello, World!
==16288==
==16288== HEAP SUMMARY:
==16288==     in use at exit: 0 bytes in 0 blocks
==16288==   total heap usage: 4 allocs, 4 frees, 1,063 bytes allocated
==16288==
==16288== All heap blocks were freed -- no leaks are possible
==16288==
==16288== For counts of detected and suppressed errors, rerun with: -v
==16288== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Title: free function seems to not work

Body:
I have this problem in C, happened about 3 times and I just cant find the answer.
I'm allocating  a memory in a create function, and when I'm trying to free it in a destroy the program crashes.

Here is the program:

typedef struct Order_t* Order;
struct Order_t {
    char* email;
    TechnionFaculty faculty;
    int id;
    char* time;
    int num_ppl;
};

Order createOrder(char* email, TechnionFaculty faculty, int id, char* time,
    int num_ppl)
{
    if (email == NULL) {
        return NULL;
    }
    if (checkEmail(email) != OK)
        return NULL;
    if (checkFaculty(faculty) != OK)
        return NULL;
    Order order = malloc(sizeof(Order));
    if (order == NULL)
        return NULL;
    (order->email) = malloc(strlen(email) + 1);
    if (order->email == NULL) {
        free(order);
        return NULL;
    }
    strcpy(order->email, email);
    order->faculty = faculty;
    order->id = id;
    order->num_ppl = num_ppl;
    order->time = malloc(strlen(time) + 1);
    if (order->time == NULL) {
        free(order->email);
        free(order);
        return NULL;
    }
    return order;
}

void orderDestroy(Order order)
{
    assert(order != NULL);
    free(order->email);
    free(order->time);
    free(order);
}

Body:
I did some small changes to your code so that it doesn't crash. When using a struct you should allocate both the struct and its members. I hope it can help you.

#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
#include <assert.h>

typedef struct Order_t *Order;
struct Order_t{
    char* email;
    //TechnionFaculty faculty;
    int id;
    char* time;
    int num_ppl;
};

Order createOrder (char* email, int id, char* time, int num_ppl){
    if (email == NULL) {
        return NULL;
    }

    Order order = malloc(sizeof(struct Order_t));
    if (order == NULL)
        return NULL;
    (order->email) = malloc(strlen(email)+1);
    if (order->email == NULL){
        free(order);
        return NULL;
    }
    strcpy(order->email, email);
    order->id = id;
    order->num_ppl = num_ppl;
    (order->time) = malloc(strlen(time)+1);
    if (order->time == NULL){
        free(order->email);
        free(order);
        return NULL;
    }
    return order;
}

void orderDestroy (Order order){
    assert(order != NULL);
    free(order->email);
    free(order->time);
    free(order);
}

int main() {
    printf("Hello, World!\n");
    Order o1 = createOrder("foo", 42, "24", 420);
    orderDestroy(o1);
    return 0;
}

We check it with valgrind.

$ ./a.out
Hello, World!
developer@1604:~/CLionProjects/untitled4$ valgrind ./a.out
==16288== Memcheck, a memory error detector
==16288== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==16288== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==16288== Command: ./a.out
==16288==
Hello, World!
==16288==
==16288== HEAP SUMMARY:
==16288==     in use at exit: 0 bytes in 0 blocks
==16288==   total heap usage: 4 allocs, 4 frees, 1,063 bytes allocated
==16288==
==16288== All heap blocks were freed -- no leaks are possible
==16288==
==16288== For counts of detected and suppressed errors, rerun with: -v
==16288== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)


问:
Can I use heroku addons from India?
I am trying to create a bot and i have also deployed the node.js file to heroku .
I want mongodb add-on . Will I be able to use that from India because heroku regions cover only the following</p>

```<code>eu         Europe                   Common Runtime

us         United States            Common Runtime

frankfurt  Frankfurt, Germany       Private Spaces

oregon     Oregon, United States    Private Spaces

sydney     Sydney, Australia        Private Spaces

tokyo      Tokyo, Japan             Private Spaces

virginia   Virginia, United States  Private Spaces
</code>```

答:
Yes, you will be able to use it from India. You will not be able to deploy it to servers running in India (at the moment) but no problem to use Heroku from India.

If your target audience is in India then you should test the latency of US vs. EU deployment to see which one performs better from India.

Title: Can I use heroku addons from India?

Body:
I am trying to create a bot and i have also deployed the node.js file to heroku .
I want mongodb add-on . Will I be able to use that from India because heroku regions cover only the following

eu         Europe                   Common Runtime

us         United States            Common Runtime

frankfurt  Frankfurt, Germany       Private Spaces

oregon     Oregon, United States    Private Spaces

sydney     Sydney, Australia        Private Spaces

tokyo      Tokyo, Japan             Private Spaces

virginia   Virginia, United States  Private Spaces


问:
When is LIMIT applied? Will it select all results before limiting?
I'm concerned about the performance of a query such as SELECT * FROM user LIMIT 5 on a very large user table. Will it select all records then limit to 5?

More specifically will the following query select all assetids before limiting...

```<code>SELECT * FROM assets WHERE asset_id IN(1,2,3,4,5,6,7,8,9,10) LIMIT 5
</code>```

I realize it doesn't make sense to include all ids in the IN() clause if I'm limiting but I'd like to know how mysql behaves in this situation.

Thanks.

答:
This depends on your query. See this page for more explanations of how LIMIT is applied:
http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html

For that specific query, the following would apply:
"As soon as MySQL has sent the required number of rows to the client, it aborts the query unless you are using SQL_CALC_FOUND_ROWS."

Hope that helps.

Body:
I'm concerned about the performance of a query such as SELECT * FROM user LIMIT 5 on a very large user table. Will it select all records then limit to 5?

More specifically will the following query select all assetids before limiting...

SELECT * FROM assets WHERE asset_id IN(1,2,3,4,5,6,7,8,9,10) LIMIT 5

I realize it doesn't make sense to include all ids in the IN() clause if I'm limiting but I'd like to know how mysql behaves in this situation.

Thanks.


问:
There are 0 datanode(s) running and no node(s) are excluded in this operation
I have set up a multi node Hadoop Cluster. The NameNode and Secondary namenode runs on the same machine and the cluster has only one Datanode. All the nodes are configured on Amazon EC2 machines.

Following are the configuration files on the master node:

```<code>masters
54.68.218.192 (public IP of the master node)

slaves
54.68.169.62 (public IP of the slave node)
</code>```

core-site.xml

```<code><configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
</configuration>
</code>```

mapred-site.xml

```<code><configuration>
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>
</configuration>
</code>```

hdfs-site.xml

```<code><configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/datanode</value>
</property>
</configuration>
</code>```

Now are the configuration files on the datanode:

core-site.xml

```<code><configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://54.68.218.192:10001</value>
</property>
</configuration>
</code>```

mapred-site.xml

```<code><configuration>
<property>
<name>mapred.job.tracker</name>
<value>54.68.218.192:10002</value>
</property>
</configuration>
</code>```

hdfs-site.xml

```<code><configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/datanode</value>
</property>
</configuration>
</code>```

the jps run on the Namenode give the following:

```<code>5696 NameNode
6504 Jps
5905 SecondaryNameNode
6040 ResourceManager
</code>```

and jps on datanode:

```<code>2883 DataNode
3496 Jps
3381 NodeManager
</code>```

which to me seems right.

Now when I try to run a put command:

```<code>hadoop fs -put count_inputfile /test/input/
</code>```

It gives me the following error:

```<code>put: File /count_inputfile._COPYING_ could only be replicated to 0 nodes instead of minReplication (=1).  There are 0 datanode(s) running and no node(s) are excluded in this operation.
</code>```

The logs on the datanode says the following:

```<code>hadoop-datanode log
INFO org.apache.hadoop.ipc.Client: Retrying connect to server:      54.68.218.192/54.68.218.192:10001. Already tried 8 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
</code>```

yarn-nodemanager log:

```<code>INFO org.apache.hadoop.ipc.Client: Retrying connect to server: 0.0.0.0/0.0.0.0:8031. Already tried 9 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)
</code>```

The web UI of node manager(50070) shows that there are 0 live nodes and 0 dead nodes and the dfs used is 100%

I have also disabled IPV6.

On a few websites I found out that I should also edit the /etc/hosts file. I have also edited them and they look like this:

```<code>127.0.0.1 localhost
172.31.25.151 ip-172-31-25-151.us-west-2.compute.internal
172.31.25.152 ip-172-31-25-152.us-west-2.compute.internal
</code>```

Why I am still geting the error?

答:
I had same error. I had not permission to hdfs file system. So I give permission to my user:</p>

```<code>chmod 777 /usr/local/hadoop_store/hdfs/namenode
chmod 777 /usr/local/hadoop_store/hdfs/datanode
</code>```

Body:
I have set up a multi node Hadoop Cluster. The NameNode and Secondary namenode runs on the same machine and the cluster has only one Datanode. All the nodes are configured on Amazon EC2 machines.

Following are the configuration files on the master node:

masters
54.68.218.192 (public IP of the master node)

slaves
54.68.169.62 (public IP of the slave node)

core-site.xml

<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
</configuration>

mapred-site.xml

<configuration>
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>
</configuration>

hdfs-site.xml

<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/datanode</value>
</property>
</configuration>

Now are the configuration files on the datanode:

core-site.xml

<configuration>
<property>
<name>fs.default.name</name>
<value>hdfs://54.68.218.192:10001</value>
</property>
</configuration>

mapred-site.xml

<configuration>
<property>
<name>mapred.job.tracker</name>
<value>54.68.218.192:10002</value>
</property>
</configuration>

hdfs-site.xml

<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.name.dir</name>
<value>file:/usr/local/hadoop_store/hdfs/datanode</value>
</property>
</configuration>

the jps run on the Namenode give the following:

5696 NameNode
6504 Jps
5905 SecondaryNameNode
6040 ResourceManager

and jps on datanode:

2883 DataNode
3496 Jps
3381 NodeManager

which to me seems right.

Now when I try to run a put command:

hadoop fs -put count_inputfile /test/input/

It gives me the following error:

put: File /count_inputfile._COPYING_ could only be replicated to 0 nodes instead of minReplication (=1).  There are 0 datanode(s) running and no node(s) are excluded in this operation.

The logs on the datanode says the following:

hadoop-datanode log
INFO org.apache.hadoop.ipc.Client: Retrying connect to server:      54.68.218.192/54.68.218.192:10001. Already tried 8 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)

yarn-nodemanager log:

INFO org.apache.hadoop.ipc.Client: Retrying connect to server: 0.0.0.0/0.0.0.0:8031. Already tried 9 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1000 MILLISECONDS)

The web UI of node manager(50070) shows that there are 0 live nodes and 0 dead nodes and the dfs used is 100%

I have also disabled IPV6.

On a few websites I found out that I should also edit the /etc/hosts file. I have also edited them and they look like this:

127.0.0.1 localhost
172.31.25.151 ip-172-31-25-151.us-west-2.compute.internal
172.31.25.152 ip-172-31-25-152.us-west-2.compute.internal

Why I am still geting the error?

Body:
I had same error. I had not permission to hdfs file system. So I give permission to my user:

chmod 777 /usr/local/hadoop_store/hdfs/namenode
chmod 777 /usr/local/hadoop_store/hdfs/datanode


问:
Same key for all key-value pairs?
Can I use the same key for all key-value pairs in a SharedPreference file in Android? (I really don't need the key). I want to access the pairs only by value. Also how long can a key be ?</p>

答:
Android allows you to store a String-Set in your SharedPreferences. I guess that's what you are looking for. See here.

Otherwise, you could also look into a sqlite database.

Title: Same key for all key-value pairs?


问:
Unable to execute curl request PHP?
I am working on curl, and trying to get results from a url, when I hit the url through command prompt then it works, but when I try to hit it through curl then it returns nothing in response.

Here is the URL and the curl request I tried:

```<code>$request =  'https://api.twilio.com/2010-04-01/Accounts/<AccountSid>/Calls/<SID>/Recordings.json -u <AccountSid>:<AccountToken>';
</code>```

When I try to hit the above URL via terminal then it works:

```<code>$ curl -G https://api.twilio.com/2010-04-01/Accounts/<AccountSid>/Calls/<SID>/Recordings.json -u <AccountSid>:<AccountToken>
</code>```

it returns response in json format, but I want to access it throught curl, so I tried the following way:

```<code>$session = curl_init($request);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);

echo "```";
print_r($response);
echo "```";
</code>```

but it returns nothing.

答:
```<code>$request =  'https://api.twilio.com/2010-04-01/Accounts/
                <AccountSid>/Calls/<SID>/Recordings.json -u <AccountSid>:<AccountToken>';
</code>```

The authentication data is not part of the actual request URL;

This is just how you feed HTTP Auth credentials to the command line version of cURL.

You want to set CURLOPT_USERNAME and CURLOPT_USERPWD for that part with PHP's cURL wrapper.

Title: Unable to execute curl request PHP?

Body:
I am working on curl, and trying to get results from a url, when I hit the url through command prompt then it works, but when I try to hit it through curl then it returns nothing in response.

Here is the URL and the curl request I tried:

$request =  'https://api.twilio.com/2010-04-01/Accounts/<AccountSid>/Calls/<SID>/Recordings.json -u <AccountSid>:<AccountToken>';

When I try to hit the above URL via terminal then it works:

$ curl -G https://api.twilio.com/2010-04-01/Accounts/<AccountSid>/Calls/<SID>/Recordings.json -u <AccountSid>:<AccountToken>

it returns response in json format, but I want to access it throught curl, so I tried the following way:

$session = curl_init($request);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
curl_close($session);

echo "
";
print_r($response);
echo "
";

but it returns nothing.

Body:
$request =  'https://api.twilio.com/2010-04-01/Accounts/
                <AccountSid>/Calls/<SID>/Recordings.json -u <AccountSid>:<AccountToken>';

The authentication data is not part of the actual request URL;

This is just how you feed HTTP Auth credentials to the command line version of cURL.

You want to set CURLOPT_USERNAME and CURLOPT_USERPWD for that part with PHP's cURL wrapper.


问:
strange Train and test set are not compatible error in weka
I have read many solution about this error. But my problem is definitely different from the others: I have a "train" dataset(arff) and a "test" dataset(arff), both these two arff have an attribute "id"(string). It works well if I 'remove' "id" of these two arff at the same time(if I don't remove the id in "test" I will get an error); what confuse me is that my friend can do it by remove only the "id" in "train", so his output will contains the "id".

(since he didn't remove the "id" in the "test", the number of attribute will not be the same, and this is against what I read that the number of attribute should be exactly the same).

I really need an output that can contain the "id".
Maybe I did something wrong with the "remove"? I read somewhere said that the test feature may be superior to that of train. And also a paragraph talking about how to remove:"Instead of using a nominal ID attribute, declare it as STRING
attribute. With this you don't have to declare each possible value
like with NOMINAL attributes and it therefore doesn't matter what
strings are used in the test set that you're trying to use the trained
model on. In order to be able to work with this STRING ID attribute
you have to use the FilteredClassifier in conjunction with the Remove
filter (package weka.filters.unsupervised.attribute) and your original
base classifier. This setup will remove the ID attribute for the
learning process (i.e., the base classifier), but you'll still be able
to use it outside for tracking instances. "
http://weka.8497.n7.nabble.com/use-saved-model-td22857.html

Anyone have an idea?

Any help will be appreciated.

my 2 arff, left: train; right: test

left: output of myfriend with id such as test_subject1005 ; right: my output

答: Finally I got my solution. Just click directly the "supplied test set" and in the prompt interface click "Yes". That all! (It seems that I did not see this prompt before, so I did not try)


问:
Thread safety: Does incrementing values of a primitive wrapper okay?
I know that Primitive wrappers such Integer, Double, Float are immutable, at least that was what I read. The thing is if we increment their values, each of the incremented value will be unboxed to their primitive representation and then assign the result to a new reference.

Now that I want to synchronize the incremented value but pretty much confused, because if I synchronize the initial values (before they get incremented) but I've no control over the new references unless I assign each of the new incremented values to new variables, means I have to always synchronize the new references every time I do increment.

How to deal with such situation?

答: You can use Atomic* (AtomicInteger, AtomicBoolean), where the synchronization part is inbuilt.</p>


问:
Using tab identation instead of spaces on Android Studio
Just trying to use tab-indentation on Android Studio 2.2.2

I followed the instructions I found on this thread:

Android Studio "This file is indented with tabs instead of 4 spaces"

But these instructions work only for new documents I create after setting that configuration but for previously created documents the space-indentation persists.

How can I configure all the files on my project to tab-indentation? for files before and after the tab-indentation configuration on the link above?

答:
After changing the settings you have to reformat your codes, you can do this one by one by opening the file and pressing (Command + Option + L) shortcut or right click on your src folder and selecting Reformat Code option:

You can check the result by selecting View -> Active Editor -> Show Whitespaces from the menu:

which would be something like this:


问:
COTS Workshop Registration System
Does anyone have any experience with any COTS systems for managing workshops and the associated registrations, courses, communications, etc.?

We have a home-built Perl system that is about 8 years old and is currently embedded as an iframe in a SharePoint portal site (externally facing). Needless to say, it isn't integrated into our site well, looks like crap, needs an overhaul, lacks features, etc. It would be nice to find either a product we can install or a service that provides those features.

Thanks!

答: You might also look into Moodle - it's a platform developed to supplement classroom teaching (or implement online learning courses) but should have all the major features you listed, and would support your needs reasonably well, as well as enhancing your event with an online component such as slide/presentation distribution only to registered users or users that took a particular class, etc)</p>

Title: COTS Workshop Registration System

OwnerDisplayName: Adam Davis

LastEditorDisplayName: Rich B


答:
Use AtomicInteger or AtomicLong etc. It's all thread safe.

Example :

```<code>AtomicInteger integer = new AtomicInteger(0);
integer.incrementAndGet();
integer.getAndIncrement();
</code>```

Title: Thread safety: Does incrementing values of a primitive wrapper okay?

Body:
I know that Primitive wrappers such Integer, Double, Float are immutable, at least that was what I read. The thing is if we increment their values, each of the incremented value will be unboxed to their primitive representation and then assign the result to a new reference.

Now that I want to synchronize the incremented value but pretty much confused, because if I synchronize the initial values (before they get incremented) but I've no control over the new references unless I assign each of the new incremented values to new variables, means I have to always synchronize the new references every time I do increment.

How to deal with such situation?

Body:
Use AtomicInteger or AtomicLong etc. It's all thread safe.

Example :

AtomicInteger integer = new AtomicInteger(0);
integer.incrementAndGet();
integer.getAndIncrement();


问:
How to use Jest with jsdom to test console.log?
I'm just getting set up with Jest and I've successfully written unit tests that test the DOM. I have a library that types things on the screen, so I'm able to test just fine. In some cases, instead of throwing an error, my library will spit out a console.warn or console.log. Is it possible to use Jest to test that these console messages are happening?

答:
You can set console.log to by a spy like this:

```<code>global.console = {
  warn: jest.fn(),
  log: jest.fn()
}

// run your code

expect(global.console.log).toHaveBeenCalledWith('test')
</code>```

As your test file runs in a separate thread you don't need to reset console to the original methods

Body:
You can set console.log to by a spy like this:

global.console = {
  warn: jest.fn(),
  log: jest.fn()
}

// run your code

expect(global.console.log).toHaveBeenCalledWith('test')

As your test file runs in a separate thread you don't need to reset console to the original methods


答:
Instead of worrying about all of that, why not check out AtomicLong and AtomicInteger? All operations on them are atomic and they are threadsafe.

```<code>private final AtomicInteger counter = new AtomicInteger(0);

public int incrementCounter() {
    counter.incrementAndGet();
}
</code>```

From the documentation:

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer.

Body:
Instead of worrying about all of that, why not check out AtomicLong and AtomicInteger? All operations on them are atomic and they are threadsafe.

private final AtomicInteger counter = new AtomicInteger(0);

public int incrementCounter() {
    counter.incrementAndGet();
}

From the documentation:

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer.


问:
Vue Js filters not working
I'm having achieving a data set through axios which I'm trying to display in VueJs, Following is the data set:

```<code>{
"model":[
    {
        "id":2,
        "company_id":5,
        "salutation":"Mr",
        "first_name":"Check",
        "last_name":"Contact",
        "number":"234567890",
        "email":"check@contact.com",
        "alt_email":null,
        "address":"Thane",
        "city":"Thane",
        "state":"Maharastra",
        "country":"India",
        "profile":"Research-Corporate Access",
        "sectors_interested":"[\"Infrastructure\",\"Financial Services\",\"Capital Goods\",\"Pharmaceuticals\",\"Real Estate\"]",
        "companies_interested":"[{\"value\":7,\"label\":\"Test Company 4\"}]",
        "created_at":"2017-06-02 19:32:30",
        "updated_at":"2017-06-02 19:32:30",
        "deleted_at":null,
        "company":{
            "id":5,
            "name":"Test Company 3",
            "address":"Andheri",
            "city":"Mumbai",
            "state":null,
            "country":"India",
            "type":"Research-Tier II",
            "is_client":0,
            "created_at":"2017-06-02 14:48:20",
            "updated_at":"2017-06-02 14:48:20",
            "deleted_at":null
        }
    },
    {
        "id":3,
        "company_id":4,
        "salutation":"Mr",
        "first_name":"Check 1",
        "last_name":"Contact",
        "number":null,
        "email":"check1@contact.com",
        "alt_email":null,
        "address":null,
        "city":null,
        "state":null,
        "country":null,
        "profile":"Investor-Research Head",
        "sectors_interested":"[\"Economics\",\"Real Estate\",\"Auto\",\"Consumer\",\"Logistics\",\"Oil & Gas\",\"Industrial\",\"Capital Goods\"]",
        "companies_interested":"[{\"value\":7,\"label\":\"Test Company 4\"},{\"value\":8,\"label\":\"Test Company 5\"}]",
        "created_at":"2017-06-03 06:28:03",
        "updated_at":"2017-06-03 06:28:03",
        "deleted_at":null,
        "company":{
            "id":4,
            "name":"Test Company 2",
            "address":"Chennai",
            "city":"Chennai",
            "state":null,
            "country":"India",
            "type":"Investor-Mutual Fund",
            "is_client":0,
            "created_at":"2017-06-02 06:42:16",
            "updated_at":"2017-06-02 15:32:17",
            "deleted_at":null
        }
    },
]
}
</code>```

So basically I'm getting this data set and trying to have filter in this, I defined the data set as model: {} in data() and I'm having a method as fetchContactData() which sets the data into model now after getting the response when I console.log(this.model) I get the object set like this:

but for filtering the data set is not getting:

I've my filter functions in computed property

```<code>contacts: function() {
    if(this.model)
    {
        return this.model
             .filter(f => (f.company.is_client == 0))
            .map(d => ({label: d.name, value: d.id}))
    }
},
</code>```

But here this.model is not working I'm getting error of this

Error in render function: "TypeError: this.model.filter is not a function"

When I do console.log(this.model) before if statement, I get this:

If I do console.log(this) I can see the desired value being placed in model[!

答:
When you initialize the component, you set model to an object.

I defined the data set as model: {} in data()

Objects do not have a filter method. Instead, initialize the model to an empty array.

```<code>data(){
    return {
        model: []
    }
}
</code>```

Title: Vue Js filters not working

Body:
I'm having achieving a data set through axios which I'm trying to display in VueJs, Following is the data set:

{
"model":[
    {
        "id":2,
        "company_id":5,
        "salutation":"Mr",
        "first_name":"Check",
        "last_name":"Contact",
        "number":"234567890",
        "email":"check@contact.com",
        "alt_email":null,
        "address":"Thane",
        "city":"Thane",
        "state":"Maharastra",
        "country":"India",
        "profile":"Research-Corporate Access",
        "sectors_interested":"[\"Infrastructure\",\"Financial Services\",\"Capital Goods\",\"Pharmaceuticals\",\"Real Estate\"]",
        "companies_interested":"[{\"value\":7,\"label\":\"Test Company 4\"}]",
        "created_at":"2017-06-02 19:32:30",
        "updated_at":"2017-06-02 19:32:30",
        "deleted_at":null,
        "company":{
            "id":5,
            "name":"Test Company 3",
            "address":"Andheri",
            "city":"Mumbai",
            "state":null,
            "country":"India",
            "type":"Research-Tier II",
            "is_client":0,
            "created_at":"2017-06-02 14:48:20",
            "updated_at":"2017-06-02 14:48:20",
            "deleted_at":null
        }
    },
    {
        "id":3,
        "company_id":4,
        "salutation":"Mr",
        "first_name":"Check 1",
        "last_name":"Contact",
        "number":null,
        "email":"check1@contact.com",
        "alt_email":null,
        "address":null,
        "city":null,
        "state":null,
        "country":null,
        "profile":"Investor-Research Head",
        "sectors_interested":"[\"Economics\",\"Real Estate\",\"Auto\",\"Consumer\",\"Logistics\",\"Oil & Gas\",\"Industrial\",\"Capital Goods\"]",
        "companies_interested":"[{\"value\":7,\"label\":\"Test Company 4\"},{\"value\":8,\"label\":\"Test Company 5\"}]",
        "created_at":"2017-06-03 06:28:03",
        "updated_at":"2017-06-03 06:28:03",
        "deleted_at":null,
        "company":{
            "id":4,
            "name":"Test Company 2",
            "address":"Chennai",
            "city":"Chennai",
            "state":null,
            "country":"India",
            "type":"Investor-Mutual Fund",
            "is_client":0,
            "created_at":"2017-06-02 06:42:16",
            "updated_at":"2017-06-02 15:32:17",
            "deleted_at":null
        }
    },
]
}

So basically I'm getting this data set and trying to have filter in this, I defined the data set as model: {} in data() and I'm having a method as fetchContactData() which sets the data into model now after getting the response when I console.log(this.model) I get the object set like this:

but for filtering the data set is not getting:

I've my filter functions in computed property

contacts: function() {
    if(this.model)
    {
        return this.model
             .filter(f => (f.company.is_client == 0))
            .map(d => ({label: d.name, value: d.id}))
    }
},

But here this.model is not working I'm getting error of this

Error in render function: "TypeError: this.model.filter is not a function"

When I do console.log(this.model) before if statement, I get this:

If I do console.log(this) I can see the desired value being placed in model[!

Body:
When you initialize the component, you set model to an object.

I defined the data set as model: {} in data()

Objects do not have a filter method. Instead, initialize the model to an empty array.

data(){
    return {
        model: []
    }
}