问:
How to conciliate the best Object Oriented Programming practices in getters and setters with the needs of ORMs frameworks?
In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database.
However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.

The ORM needs of following getters and setters methods, so that we have:

```<code>@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}
</code>```

The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.

Instead, if we wanted to respect the Oriented Object rules, we have something like this:

```<code>@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}
</code>```

So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?

答:
Some would argue you shouldn't use ORM. Give that article a read. It will challenge your preconceptions even if you don't necessarily agree with it.

You're very much right that ORM relies on the java "bean" pattern of getters and setters which breaks encapsulation and forces objects to be mutable unnecessarily.

In my mind, the best way to give yourself the benefits of both worlds is to use two different classes. The following is just pseudo-code to illustrate the general idea:

```<code>@Entity
class ORMFoo
{
   private int bar;

   ORMFoo(int bar){...}

   void setBar() {...}
   int  getBar() {...}
   Foo  getImmutable() { return new Foo(bar); }
}

class Foo
{
   private final int bar;
   Foo(final int bar) {...}
   save(ORMManager manager) { manager.update(new ORMFoo(bar)); }
}
</code>```

Use the latter throughout most of your application. Use the former only as a transfer object.

Body:
In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database.
However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.

The ORM needs of following getters and setters methods, so that we have:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}

The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.

Instead, if we wanted to respect the Oriented Object rules, we have something like this:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}

So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?

Body:
Some would argue you shouldn't use ORM. Give that article a read. It will challenge your preconceptions even if you don't necessarily agree with it.

You're very much right that ORM relies on the java "bean" pattern of getters and setters which breaks encapsulation and forces objects to be mutable unnecessarily.

In my mind, the best way to give yourself the benefits of both worlds is to use two different classes. The following is just pseudo-code to illustrate the general idea:

@Entity
class ORMFoo
{
   private int bar;

   ORMFoo(int bar){...}

   void setBar() {...}
   int  getBar() {...}
   Foo  getImmutable() { return new Foo(bar); }
}

class Foo
{
   private final int bar;
   Foo(final int bar) {...}
   save(ORMManager manager) { manager.update(new ORMFoo(bar)); }
}

Use the latter throughout most of your application. Use the former only as a transfer object.


来源: stackexchange

问:
Hide or show div based on children's content
After trial and error with many solutions found on SO for hiding and displaying content using jquery based on textarea content I have ended up with a piece of script that nearly does what I want. I'm doing this in MVC 5, though I don't think that any consequence for this dilemma.

I have an edit page which has many optional text areas that can either be empty or have some text, these come from a database. What I wish to do is to hide them by default if they contain no text. They are grouped and they are toggleable with a click of the description text above them.

This is how I have them grouped, displaying one area:

```<code>    <div class="togglerDesc">
    <p class="pointerToggler"><strong>XXX description</strong></p>
        <div class="hiddenContainer">
            <div class="optionalArea">
                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

And the script I have is:

```<code>$(document).ready(function () {
        if (!$.trim($(".optionalArea textarea").val()).length < 1) {
            $(".optionalArea textarea").parents(".hiddenContainer").show();
        }
});
</code>```

Now this works just fine if the immediate text area, Q1p1 in my example has text in it. However if it is empty it does not show the div even if the two other textareas have text in them. It does seem my problem here is that the script is not taking all of the divs into account and only checks the first one. How could I change it so it takes all of the text areas within .optionalArea into account?

答: Are you expecting the call to .val() to combine the values from the 3 text areas?  That will not happen.  .val() will return the value from the first element selected, which is why you only get the desired behavior when Q1p1 has text in it.  You need to select all of your elements, call .val() on them individually, and then concatenate.</p>

ContentLicense: CC BY-SA 3.0

Body:
After trial and error with many solutions found on SO for hiding and displaying content using jquery based on textarea content I have ended up with a piece of script that nearly does what I want. I'm doing this in MVC 5, though I don't think that any consequence for this dilemma.

I have an edit page which has many optional text areas that can either be empty or have some text, these come from a database. What I wish to do is to hide them by default if they contain no text. They are grouped and they are toggleable with a click of the description text above them.

This is how I have them grouped, displaying one area:

XXX description

                    @Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })

And the script I have is:

$(document).ready(function () {
        if (!$.trim($(".optionalArea textarea").val()).length < 1) {
            $(".optionalArea textarea").parents(".hiddenContainer").show();
        }
});

Now this works just fine if the immediate text area, Q1p1 in my example has text in it. However if it is empty it does not show the div even if the two other textareas have text in them. It does seem my problem here is that the script is not taking all of the divs into account and only checks the first one. How could I change it so it takes all of the text areas within .optionalArea into account?


问:
Angular 2 : Remove class if root route not active
I only understood how to remove a whole element with *ngIf , for a specific route that is.

Lets say I have a class applied to an element of my app (header) only for routerLink="/", meaning if I switch to "/other-page", I need the header to lose that class.

How can I achieve this?

How can I link [ngClass] to the route change?

Code:

```<code>import { Component, ElementRef, ViewChild, Renderer, AfterViewInit, Input } from '@angular/core';

import { LayoutService } from 'app/core/services/layout.service';

@Component({
    moduleId: module.id,
    selector: 'header-main',
    template: `

    <header class="header-main"
        [ngClass]="{'transparent' : isMenuShown}" #header>

        <div class="wrapper">
            <a routerLink="/" routerLinkActive="active" routerLinkActiveOptions="{exact: true}" class="logo">
                <img src="../../../assets/images/logo_dark.svg" alt="{{logoAlt}}" title="{{logoAlt}}">
            </a>
            <a (click)="menuToggle($event)" class="nav-trigger" #navTrigger>
                <i class="icon icon-menu" (click)="isMenuShown = !isMenuShown;"></i>
            </a>
        </div>

        <nav class="sub-nav" [ngClass]="{'shown' : isMenuShown}">
            <a href="#" class="nav-item">about us</a>
            <a href="#" class="nav-item">team</a>
            <a href="#" class="nav-item">work</a>
        </nav>

        <div class="lets-talk" [ngClass]="{'white' : isMenuShown}">
            <a href="#" class="talk-link">
            <i class="icon icon-talk"></i>
            <p class="link-text">let's talk</p>
            </a>
        </div>

    </header>

    <main-menu (click)="onMenuSelect()" [ngClass]="{'menuShown': isMenuShown}" #mainMenu></main-menu>
`
})

export class HeaderMainComponent {

    @Input() logoAlt: string;
    @Input() logoTitle: string;

    @ViewChild('navTrigger') navTrigger: ElementRef;

    isMenuShown: false;

    constructor(private layoutService: LayoutService, private renderer: Renderer) { }

    menuToggle(event: any) {
          if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
        } else {
            this.navTrigger.nativeElement.classList.add('opened');
        }
    }

    onMenuSelect(event: any) {
       this.isMenuShown = false;
       this.menuToggle(event);
    }

}
</code>```

答:
Check out the routerLinkActive directive.

This directive allows you to add or remove a class to an element, based on whether a particular route is active or not.

In your situation, you'll probably also want to make use of routerLinkActiveOptions being set to {exact: true}, since you won't want your class added when the '/' route is active.

EDIT:

From your update, you're not setting routerLinkOptions correctly.

Your code example:

```<code>  <a routerLink="/" routerLinkActive="active" routerLinkActiveOptions="{exact: true}" class="logo">
</code>```

You need to change it to:

```<code> <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" class="logo">
</code>```

Note the use of the square brackets to indicate that you want to bind the routerLinkActiveOptions input to an object. When you leave out the square brackets, Angular assumes that you want to bind routerLinkActiveOptions to the string "{exact: true}"

(Basically, Angular translates routerLinkActiveOptions="{exact: true}" to  [routerLinkActiveOptions]="'{exact: true}'" - which is definitely not what you want.)

Body:
I only understood how to remove a whole element with *ngIf , for a specific route that is.

Lets say I have a class applied to an element of my app (header) only for routerLink="/", meaning if I switch to "/other-page", I need the header to lose that class.

How can I achieve this?

How can I link [ngClass] to the route change?

Code:

import { Component, ElementRef, ViewChild, Renderer, AfterViewInit, Input } from '@angular/core';

import { LayoutService } from 'app/core/services/layout.service';

@Component({
    moduleId: module.id,
    selector: 'header-main',
    template: `

            about us
            team
            work

let's talk

`
})

export class HeaderMainComponent {

    @Input() logoAlt: string;
    @Input() logoTitle: string;

    @ViewChild('navTrigger') navTrigger: ElementRef;

    isMenuShown: false;

    constructor(private layoutService: LayoutService, private renderer: Renderer) { }

    menuToggle(event: any) {
          if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
        } else {
            this.navTrigger.nativeElement.classList.add('opened');
        }
    }

    onMenuSelect(event: any) {
       this.isMenuShown = false;
       this.menuToggle(event);
    }

}

Body:
Check out the routerLinkActive directive.

This directive allows you to add or remove a class to an element, based on whether a particular route is active or not.

In your situation, you'll probably also want to make use of routerLinkActiveOptions being set to {exact: true}, since you won't want your class added when the '/' route is active.

EDIT:

From your update, you're not setting routerLinkOptions correctly.

Your code example:

  <a routerLink="/" routerLinkActive="active" routerLinkActiveOptions="{exact: true}" class="logo">

You need to change it to:

 <a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" class="logo">

Note the use of the square brackets to indicate that you want to bind the routerLinkActiveOptions input to an object. When you leave out the square brackets, Angular assumes that you want to bind routerLinkActiveOptions to the string "{exact: true}"

(Basically, Angular translates routerLinkActiveOptions="{exact: true}" to  [routerLinkActiveOptions]="'{exact: true}'" - which is definitely not what you want.)


问:
Update .net standard PackageReference from command line
We have a bunch of fast moving internal nuget packages.

We want the consumers of these packages to always be on the latest version. We currently do this on our CI system by running nuget update on the command line before build.

However we now are moving to .net standard/core. When we run nuget update on a .net standard csproj we get the following error:

Unable to update. The project does not contain a packages.config file.

Nuget still seems to be expecting a packages.config even though this has been dropped for .net core/standard csproj files.

How do we update PackageReferences to the latest version using the commandline for .net core/standard csproj projects?

UPDATE:
I've created a bug report incase this is a bug here: https://github.com/NuGet/Home/issues/4945

答: As a workaround, you should be able to run dotnet remove package followed by dotnet add package to update to the latest version of some package.


问:
merge unknown number of sub-arrays in array
I have an array like this:

```<code>arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]
</code>```

and I want to turn it into an array like this:

```<code>arr = [  [x,x],[x,x] ,  [x,x],[x,x],[x,x],   [x,x]  ]
</code>```

so I have tried this:

```<code>for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }
</code>```

but it does not work. How can I 'merge' this intermediate level of array?

答:
With ES6 you can use spread syntax with concat()

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = [].concat(...arr)
console.log(JSON.stringify(merged))```
</div>
</div>
</p>

<p>For older versions of ecmascript the same can be done using <code>concat()</code> and <code>apply()</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = [].concat.apply([], arr)
console.log(JSON.stringify(merged))</code>```

Body:
I have an array like this:

arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]

and I want to turn it into an array like this:

arr = [  [x,x],[x,x] ,  [x,x],[x,x],[x,x],   [x,x]  ]

so I have tried this:

for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }

but it does not work. How can I 'merge' this intermediate level of array?

Body:
With ES6 you can use spread syntax with concat()

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = [].concat(...arr)
console.log(JSON.stringify(merged))

For older versions of ecmascript the same can be done using concat() and apply().

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ]

var merged = [].concat.apply([], arr)
console.log(JSON.stringify(merged))


问:
How to differentiate model classes between webapp and unittest
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.

I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, all, fetch and so on (only tried on a small scale) returning dbModel like results.

The one thing I haven't found a solution I'm satisfied with is how to differentiate which model class to use. I want to use the mock-ups for unit tests and the actual db.Model for when webapp is running.

My current solution looks like this in my .py containing all db.Models:

```<code>if 'SERVER_SOFTWARE' in os.environ:
    class dbTest(db.Model):
        content = db.StringProperty()
        comments = db.ListProperty(str)
else:
    class dbTest(Abstract):
        content = 'Test'
        comments = ['test1', 'test2']
</code>```

And it kinda feels like it could break any minute. Is this the way to go or could one combine these as one class and if the db.Model is invoked properly use that else the mockup?

答:
Instead of messing your models.py I would go with gaeunit.

I've used it with success in a couple of projects and the features I like are:

Just one file to add to your project (gaeunit.py) and you are almost done

Gaeunit isolates the test datastore from the development store (i.e. tests don't pollute your development db)

ContentLicense: CC BY-SA 2.5

Body:
I've started looking in to unittest when using google app engine. And it seems to bit tricky from what I've read. Since you can't (and not suppose to) run your test's against the datastore.

I've written an abstract class to emulate a datastore model class. And it quite works pretty nice returning mockup data on get, all, fetch and so on (only tried on a small scale) returning dbModel like results.

The one thing I haven't found a solution I'm satisfied with is how to differentiate which model class to use. I want to use the mock-ups for unit tests and the actual db.Model for when webapp is running.

My current solution looks like this in my .py containing all db.Models:

if 'SERVER_SOFTWARE' in os.environ:
    class dbTest(db.Model):
        content = db.StringProperty()
        comments = db.ListProperty(str)
else:
    class dbTest(Abstract):
        content = 'Test'
        comments = ['test1', 'test2']

And it kinda feels like it could break any minute. Is this the way to go or could one combine these as one class and if the db.Model is invoked properly use that else the mockup?


问:
JavaFX: Set Background Color in TextFlow
I have a text flow widget in my JavaFx application for which I need to change the background color.

The layout is constructed using FXML, and the background color for the text flow needs to be set using external css file.

I'm able to set the background color for both textArea and textField, but unable to do so for textFlow.

答:
Simply set the -fx-background-color property the same way you'd do it for other Regions e.g.:

TextFlow {
    -fx-background-color: lightblue;
}
```


问:
Emulate shell command line in C
I want to emulate the following shell command line in C, with execl():

```<code>find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt
</code>```

I wrote each of them as:

```<code>execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);
</code>```

I also implemented the pipelines but I am getting an error:

```<code>cut: cut: -: Input/Output error -: Input/output error
</code>```

Any idea what it means?
Thanks

答:
This:

```<code> "" ""
</code>```

does not create a string holding a double-quoted string. It creates an empty string, by concatenating one empty string (the first "" pair) with another empty string (the second "" pair). Remember that C automatically concatenates adjacent double-quoted string literals ("foo" "bar" is the same as "foobar").

The quotes shouldn't be passed to cut, anyways. You meant:

```<code>" "
</code>```

Update: On the other hand, it's quite possible that you shouldn't be quoting this space after all. The exec() family of functions don't go through a shell by default, and the quoting is for the shell. You really want to pass a space to cut, so you should do so directly with " ".

Title: Emulate shell command line in C

Body:
I want to emulate the following shell command line in C, with execl():

find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt

I wrote each of them as:

execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);

I also implemented the pipelines but I am getting an error:

cut: cut: -: Input/Output error -: Input/output error

Any idea what it means?
Thanks

Body:
This:

 "" ""

does not create a string holding a double-quoted string. It creates an empty string, by concatenating one empty string (the first "" pair) with another empty string (the second "" pair). Remember that C automatically concatenates adjacent double-quoted string literals ("foo" "bar" is the same as "foobar").

The quotes shouldn't be passed to cut, anyways. You meant:

" "

Update: On the other hand, it's quite possible that you shouldn't be quoting this space after all. The exec() family of functions don't go through a shell by default, and the quoting is for the shell. You really want to pass a space to cut, so you should do so directly with " ".


问:
What is wrong with this operator being undefined
I have a component that has the following lines in the ngOnInit method

```<code>    this.businessTypesService.get()
        .subscribe((businessTypes: string[]) => {
            _.each(businessTypes,
                (businessType: string) => {
                    this.businessTypes.push({ label: businessType, value: businessType });
                });
        });
</code>```

Now I have this same type of block 10 times each loading different drop lists of options.  Each is the same except for which service it calls and which array it pushes the results into, so I want to refactor this into a single method, so that I can change the code to something like this.

```<code>this.loadReferenceList(this.businessTypesService.get, this.businessTypes);
</code>```

and the new loadReferenceList method looks like this

```<code>loadReferenceList(loadMethod: () => Observable<string[]>, lookupList: SelectItem[]): any {
    loadMethod()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}
</code>```

Each of the service classes look like this

```<code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

@Injectable()
export class BusinessUnitsService {

    get(): Observable<string[]> {
        return Observable.of(this.getData());
    }

    constructor(private readonly http: Http) { }

    getData(): string[] {
        return [
            'Beverage',
            'Food',
            'Beverage & Food',
            'Promo Pack'
        ];
    }

}
</code>```

Right now it is just hard coded data, but will be changed to use Http to pull down the real values later.

The problem is that the this.getdata() line is failing saying that this is undefined.  I don't understand why this would be undefined when I change it around to be called like this.

********Answer************
I made the following changes to get this to work based off of the answer below
the loadReferenceList method was changed to look like this.  Basically added a parameter for the service, so that I could have a reference to what this was supposed to be and then added the .bind method to give the method scope.

```<code>loadReferenceList(loadMethod: () => Observable<string[]>, service: any, lookupList: SelectItem[]): any {
    const method = loadMethod.bind(service);

    method()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}
</code>```

答:
You either need to bind your .get() to your object, i.e.

loadReferenceList(this.businessTypesService.get.bind(this.businessTypesServices), ...)

or you need to define abstract interface for all services and pass objects as is

loadReferenceList(service: AbstractService, ...) {
     service.get()
}

all your services need to implement this interface

Body:
I have a component that has the following lines in the ngOnInit method

    this.businessTypesService.get()
        .subscribe((businessTypes: string[]) => {
            _.each(businessTypes,
                (businessType: string) => {
                    this.businessTypes.push({ label: businessType, value: businessType });
                });
        });

Now I have this same type of block 10 times each loading different drop lists of options.  Each is the same except for which service it calls and which array it pushes the results into, so I want to refactor this into a single method, so that I can change the code to something like this.

this.loadReferenceList(this.businessTypesService.get, this.businessTypes);

and the new loadReferenceList method looks like this

loadReferenceList(loadMethod: () => Observable<string[]>, lookupList: SelectItem[]): any {
    loadMethod()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}

Each of the service classes look like this

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';

@Injectable()
export class BusinessUnitsService {

    get(): Observable<string[]> {
        return Observable.of(this.getData());
    }

    constructor(private readonly http: Http) { }

    getData(): string[] {
        return [
            'Beverage',
            'Food',
            'Beverage & Food',
            'Promo Pack'
        ];
    }

}

Right now it is just hard coded data, but will be changed to use Http to pull down the real values later.

The problem is that the this.getdata() line is failing saying that this is undefined.  I don't understand why this would be undefined when I change it around to be called like this.

********Answer************
I made the following changes to get this to work based off of the answer below
the loadReferenceList method was changed to look like this.  Basically added a parameter for the service, so that I could have a reference to what this was supposed to be and then added the .bind method to give the method scope.

loadReferenceList(loadMethod: () => Observable<string[]>, service: any, lookupList: SelectItem[]): any {
    const method = loadMethod.bind(service);

    method()
        .subscribe(((items: string[]) => {
            _.each(items,
                (item: string) => {
                    lookupList.push({ label: item, value: item });
                });
        }));
}


问:
what is a good mocking framework to start mocking with in asp.net MVC? (novice and probably not a hardcore mocker)
i want to use mocking in my unit tests.

Till now i more programmed 'tests' and not 'unittests' because i tested whole program flows, but reading discussions i can see the beauty of a mock object, from time to time.

But, looking around, there are a lot of frameworks available, and i want to make sure i start with a good one, because i'd like to invest time in learning a mock framework only once.

So as i said in the title, i'm a novice for mocking, using asp.net mvc, and don't think i'll be a hardcore mocker, investigating the edges of a mocking framework.

To give you an idea of what i like in the IOC frameworks i like unity and structuremap.

Michel

答: I would recommend Moq. I previously tried Rhino, but I personally find the Moq API to be slicker.</p>


问:
React JS maintain array inside state
I have been using React state to maintain some data. For ints and strings it's working well, but unfortunately arrays are not working.

In my component constructor, I have

```<code>constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }
</code>```

and then, I am trying to maintain it in componentDidUpdate

```<code>componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }
</code>```

but myArray: this.state.myArray is not working. However terms: this.state.terms is working perfectly.

Can someone help!

答:
You cannot use this.state with purpose to update state, you have to use:

```<code>this.setState(newStateObject);
</code>```

Title: React JS maintain array inside state

Body:
I have been using React state to maintain some data. For ints and strings it's working well, but unfortunately arrays are not working.

In my component constructor, I have

constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }

and then, I am trying to maintain it in componentDidUpdate

componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }

but myArray: this.state.myArray is not working. However terms: this.state.terms is working perfectly.

Can someone help!

Body:
You cannot use this.state with purpose to update state, you have to use:

this.setState(newStateObject);


问:
Page able to be viewed in browser is resulting in 404 when curled
I have a Heroku Ember/RoR application (https://sleepy-forest-31423.herokuapp.com) that is able to be viewed in the browser, but when I try to curl https://sleepy-forest-31423.herokuapp.com, I have the following error:

```<code><!DOCTYPE html>
<html>
<head>
  <title>The page you were looking for doesn't exist (404)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  body {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body>
  <!-- This file lives in public/404.html -->
  <div class="dialog">
    <div>
      <h1>The page you were looking for doesn't exist.</h1>
      <p>You may have mistyped the address or the page may have moved.</p>
    </div>
    <p>If you are the application owner check the logs for more information.</p>
  </div>
</body>
</html>
</code>```

This is further confirmed by Facebook OG Debugger:

What's further is that if I do a view source on the page (view-source:https://sleepy-forest-31423.herokuapp.com/) there is nothing in the body tags but javascript files.

What is happening to make it so I'm not able to curl the website or view the contents of the body?

答:
The reason this was happening was because Rails wasn't set to API-mode only and essentially didn't trust Ember with the views which I had mounted at the root

```<code>mount_ember_app :frontend, to: "/"
</code>```

There were a lot of ways to resolve this, but I ended up separating the two services completely so that the frontend of the project (Ember) was hosted on one heroku project while my Rails backend was hosted on another. If my Ember frontend needed to call resources from Rails it could.

If I had wanted to have a unified domain name, for instance, www.somename.com showing the Ember frontend and www.somename.com/api/ showing my rails backend, I could do so by configuring CNAMEs with my domain service provider.

Body:
I have a Heroku Ember/RoR application (https://sleepy-forest-31423.herokuapp.com) that is able to be viewed in the browser, but when I try to curl https://sleepy-forest-31423.herokuapp.com, I have the following error:

<!DOCTYPE html>

  <title>The page you were looking for doesn't exist (404)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">

The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

If you are the application owner check the logs for more information.

This is further confirmed by Facebook OG Debugger:

What's further is that if I do a view source on the page (view-source:https://sleepy-forest-31423.herokuapp.com/) there is nothing in the body tags but javascript files.

What is happening to make it so I'm not able to curl the website or view the contents of the body?

Body:
The reason this was happening was because Rails wasn't set to API-mode only and essentially didn't trust Ember with the views which I had mounted at the root

mount_ember_app :frontend, to: "/"

There were a lot of ways to resolve this, but I ended up separating the two services completely so that the frontend of the project (Ember) was hosted on one heroku project while my Rails backend was hosted on another. If my Ember frontend needed to call resources from Rails it could.

If I had wanted to have a unified domain name, for instance, www.somename.com showing the Ember frontend and www.somename.com/api/ showing my rails backend, I could do so by configuring CNAMEs with my domain service provider.


问:
cannot resolve method 'getFont(?)'
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

```<code>cannot resolve method 'getFont(?)'
</code>```

Previously I used to do the following:

```<code>Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
</code>```

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.

答: Since it's a new method being released in O, you have to target the developer preview as your build target to use it.  For more info, check this link.</p>

Title: cannot resolve method 'getFont(?)'

Body:
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

cannot resolve method 'getFont(?)'

Previously I used to do the following:

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.


答:
Issue is you are updating the state value in a wrong way, Update the state value like this:

```<code>this.setState({
     terms: this.state.terms,
     myArray : this.state.myArray
});
</code>```

As per DOC:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

Update the state array like this, first create a copy of that by using slice(), then do the change and use setState to update:

```<code>let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});
</code>```

Title: React JS maintain array inside state

Body:
Issue is you are updating the state value in a wrong way, Update the state value like this:

this.setState({
     terms: this.state.terms,
     myArray : this.state.myArray
});

As per DOC:

Never mutate this.state directly, as calling setState() afterwards may
  replace the mutation you made. Treat this.state as if it were
  immutable.

Update the state array like this, first create a copy of that by using slice(), then do the change and use setState to update:

let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});


问:
changing a sql view query into a relational algebra?
I want to convert this sql query into relational algebra.

sql query:

```<code>SELECT *
FROM Library
WHERE libName='florence'
</code>```

答:
that view is the same as the result of: </p>

```<code>SELECT *
FROM Library
WHERE libName='florence'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to convert this sql query into relational algebra.

sql query:

SELECT *
FROM Library
WHERE libName='florence'

Body:
that view is the same as the result of:

SELECT *
FROM Library
WHERE libName='florence'


问:
Jquery dynamically moving a Div and getting its position relative to it's parent
I have a script that requires the user to be able to position a div on top of a selected image. I have done thaty part but I am stuck on how to get the position of the movable div relative to its parent div.

My current JavaScript:

```<code>window.onload = addListeners();
var x_pos = 0,
y_pos = 0;

function addListeners() {
   document.getElementById('ClientNametext').addEventListener('mousedown', mouseDown, false);
   window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e) {
    var div = document.getElementById('ClientNametext');
    x_pos = e.clientX - div.offsetLeft;
    y_pos = e.clientY - div.offsetTop;
    window.addEventListener('mousemove', divMove, true);
}

function divMove(e) {
    var div = document.getElementById('ClientNametext');
    div.style.position = 'absolute';
    div.style.top = (e.clientY - y_pos) + 'px';
    div.style.left = (e.clientX - x_pos) + 'px';
   console.log(div.style.top);
   console.log(div.style.left);
}
</code>```

Is there a way of tracking and capturing the movable div position and storing the result in a variable I can use with a PHP insert query.

Many thanks in advance for your time.

答:
I went ahead and added a new function updatePos, it is invoked on page load and mousemove.

var posX = 0,
    posY = 0;

function updatePos() {
    var div = document.getElementById('ClientNametext');
    var parentPos = div.parentElement.getBoundingClientRect();
    var childPos = div.getBoundingClientRect();
    var offsets = {
        top: childPos.top - parentPos.top,
        left: childPos.left - parentPos.left
    }
    posY = offsets.top;
    posX = offsets.left;
    document.getElementById("pos").innerHTML = "(" + posX + ", " + posY + ")";
}

updatePos();

function divMove(e) {
    var div = document.getElementById('ClientNametext');
    div.style.position = 'absolute';
    div.style.top = (e.clientY - y_pos) + 'px';
    div.style.left = (e.clientX - x_pos) + 'px';

    updatePos(); //added this line
}

//your code:

window.onload = addListeners();
var x_pos = 0,
y_pos = 0;

function addListeners() {
   document.getElementById('ClientNametext').addEventListener('mousedown', mouseDown, false);
   window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e) {
    var div = document.getElementById('ClientNametext');
    x_pos = e.clientX - div.offsetLeft;
    y_pos = e.clientY - div.offsetTop;
    window.addEventListener('mousemove', divMove, true);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#ClientNametext {
  width:100px;
  height:100px;
  background:red;
}
#offset {
  position:fixed;
  width:200px;
  height:200px;
  left:90px;
  top:80px;
  background:blue;
}</code>```

```

Body:
I have a script that requires the user to be able to position a div on top of a selected image. I have done thaty part but I am stuck on how to get the position of the movable div relative to its parent div.

My current JavaScript:

window.onload = addListeners();
var x_pos = 0,
y_pos = 0;

function addListeners() {
   document.getElementById('ClientNametext').addEventListener('mousedown', mouseDown, false);
   window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e) {
    var div = document.getElementById('ClientNametext');
    x_pos = e.clientX - div.offsetLeft;
    y_pos = e.clientY - div.offsetTop;
    window.addEventListener('mousemove', divMove, true);
}

function divMove(e) {
    var div = document.getElementById('ClientNametext');
    div.style.position = 'absolute';
    div.style.top = (e.clientY - y_pos) + 'px';
    div.style.left = (e.clientX - x_pos) + 'px';
   console.log(div.style.top);
   console.log(div.style.left);
}

Is there a way of tracking and capturing the movable div position and storing the result in a variable I can use with a PHP insert query.

Many thanks in advance for your time.

Body:
I went ahead and added a new function updatePos, it is invoked on page load and mousemove.

var posX = 0,
    posY = 0;

function updatePos() {
    var div = document.getElementById('ClientNametext');
    var parentPos = div.parentElement.getBoundingClientRect();
    var childPos = div.getBoundingClientRect();
    var offsets = {
        top: childPos.top - parentPos.top,
        left: childPos.left - parentPos.left
    }
    posY = offsets.top;
    posX = offsets.left;
    document.getElementById("pos").innerHTML = "(" + posX + ", " + posY + ")";
}

updatePos();

function divMove(e) {
    var div = document.getElementById('ClientNametext');
    div.style.position = 'absolute';
    div.style.top = (e.clientY - y_pos) + 'px';
    div.style.left = (e.clientX - x_pos) + 'px';

    updatePos(); //added this line
}

//your code:

window.onload = addListeners();
var x_pos = 0,
y_pos = 0;

function addListeners() {
   document.getElementById('ClientNametext').addEventListener('mousedown', mouseDown, false);
   window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e) {
    var div = document.getElementById('ClientNametext');
    x_pos = e.clientX - div.offsetLeft;
    y_pos = e.clientY - div.offsetTop;
    window.addEventListener('mousemove', divMove, true);
}

#ClientNametext {
  width:100px;
  height:100px;
  background:red;
}
#offset {
  position:fixed;
  width:200px;
  height:200px;
  left:90px;
  top:80px;
  background:blue;
}

<div id="pos"></div>
<div id="offset">
  <div id="ClientNametext">&nbsp;</div>
</div>


问:
re.search and urlopen in Python
I have this script :

```<code>for url in urls:
    u = urlopen(url).read
    owner_id = re.search(r'ownerId: ([1-9]+)?,', u).group(1)
    id = re.search(r'id: ([1-9]+)?,', u).group(1)

    print(owner_id)
    print(id)
</code>```

url is a list of urls

The script returns me "TypeError: expected string or bytes-like object"
Do you have an idea how to fix that ?

答:
Not sure what version of Python your using (below is for v3+, for v2, replace urllib with urllib2).

need to import urllib and beautiful soup

```<code>import urllib
from bs4 import BeautifulSoup

url = "url address"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, "lxml")
</code>```

Title: re.search and urlopen in Python

Body:
I have this script :

for url in urls:
    u = urlopen(url).read
    owner_id = re.search(r'ownerId: ([1-9]+)?,', u).group(1)
    id = re.search(r'id: ([1-9]+)?,', u).group(1)

    print(owner_id)
    print(id)

url is a list of urls

The script returns me "TypeError: expected string or bytes-like object"
Do you have an idea how to fix that ?

Body:
Not sure what version of Python your using (below is for v3+, for v2, replace urllib with urllib2).

need to import urllib and beautiful soup

import urllib
from bs4 import BeautifulSoup

url = "url address"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, "lxml")


问:
PaStreamCallbackTimeInfo members are all 0
From the PortAudio docs:

Stream Timing Information

When using the callback I/O method your stream callback function
  receives timing information via a pointer to a
  PaStreamCallbackTimeInfo structure. This structure contains the
  current time along with the estimated hardware capture and playback
  time of the first sample of the input and output buffers. All times
  are measured in seconds relative to a Stream-specific clock. The
  current Stream clock time can be retrieved using Pa_GetStreamTime().

So PaStreamCallbackTimeInfo::currentTime somehow indicates the current time and PaStreamCallbackTimeInfo::outputBufferDacTime should indicate the output time of the first sample in the current buffer. I don't know why but, on Linux, these values are all zero for me. Maybe I'm doing something wrong. Here's the code and the output:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include "portaudio.h"

#define PI 3.14159265359
#define SRATE 44100
#define FREQ 440
#define DURATION 5000

int
audio_callback(
    const void* inbuf,
    void* outbuf,
    unsigned long bufsize,
    const PaStreamCallbackTimeInfo* time_info,
    PaStreamCallbackFlags status_flags,
    void* user_data)
{
    (void)inbuf;
    (void)status_flags;

    double* phase = (double*)user_data;
    float* out = (float*)outbuf;

    printf(
        "current time = %f; out time = %f\n",
        time_info->currentTime,
        time_info->outputBufferDacTime);

    for (unsigned long i = 0; i < bufsize; i++)
    {
        *phase += 2 * PI * FREQ / SRATE;
        out[i] = sin(*phase);
    }

    return 0;
}

int
main(int argc, char** argv)
{
    (void)argc;
    (void)argv;

    PaError pa_error;
    PaStream* stream = NULL;
    int error = 0;
    double phase = 0;

    pa_error = Pa_Initialize();
    if (pa_error != paNoError)
    {
        return 1;
    }

    pa_error = Pa_OpenDefaultStream(
        &stream,
        0,
        1,
        paFloat32,
        SRATE,
        paFramesPerBufferUnspecified,
        &audio_callback,
        &phase);
    if (pa_error != paNoError)
    {
        error = 1;
        goto exit;
    }

    pa_error = Pa_StartStream(stream);
    if (pa_error != paNoError)
    {
        error = 1;
        goto exit;
    }

    Pa_Sleep(DURATION);

    pa_error = Pa_CloseStream(stream);
    if (pa_error != paNoError)
    {
        error = 1;
        goto exit;
    }

    printf("Done.\n");

exit:
    Pa_Terminate();

    if (pa_error != paNoError)
    {
        printf("PortAudio error: %s\n", Pa_GetErrorText(pa_error));
    }

    return error;
}
</code>```

Output:

```<code>current time = 0.000000; out time = 0.000000
current time = 0.000000; out time = 0.000000
current time = 0.000000; out time = 0.000000
current time = 0.000000; out time = 0.000000
...
</code>```

Addendum: This same piece of code seems to work fine with Visual Studio in Windows 10.

答:
Your example compiles fine on my Mac and returns meaningful time information so the issue is not in your code.

You haven't said which audio backend you're using on Linux, but if you're using ALSA and PulseAudio, there've been problems getting time info with those (see there for instance). In this specific case of ALSA/PulseAudio, Pulse is the one to blame and PortAudio has nothing to do with that.

If you're using a different audio backend, you might want to check the implementation of the GetStreamTime() function in the corresponding src/hostapi/<your_backend> PortAudio source folder.

As a side note, never make I/O operations in an audio callback in a real product. printf is a huge function which takes quite a lot of time to execute (from an audio callback point-of-view).

Body:
From the PortAudio docs:

Stream Timing Information

When using the callback I/O method your stream callback function
  receives timing information via a pointer to a
  PaStreamCallbackTimeInfo structure. This structure contains the
  current time along with the estimated hardware capture and playback
  time of the first sample of the input and output buffers. All times
  are measured in seconds relative to a Stream-specific clock. The
  current Stream clock time can be retrieved using Pa_GetStreamTime().

So PaStreamCallbackTimeInfo::currentTime somehow indicates the current time and PaStreamCallbackTimeInfo::outputBufferDacTime should indicate the output time of the first sample in the current buffer. I don't know why but, on Linux, these values are all zero for me. Maybe I'm doing something wrong. Here's the code and the output:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include "portaudio.h"

#define PI 3.14159265359
#define SRATE 44100
#define FREQ 440
#define DURATION 5000

int
audio_callback(
    const void* inbuf,
    void* outbuf,
    unsigned long bufsize,
    const PaStreamCallbackTimeInfo* time_info,
    PaStreamCallbackFlags status_flags,
    void* user_data)
{
    (void)inbuf;
    (void)status_flags;

    double* phase = (double*)user_data;
    float* out = (float*)outbuf;

    printf(
        "current time = %f; out time = %f\n",
        time_info->currentTime,
        time_info->outputBufferDacTime);

    for (unsigned long i = 0; i < bufsize; i++)
    {
        *phase += 2 * PI * FREQ / SRATE;
        out[i] = sin(*phase);
    }

    return 0;
}

int
main(int argc, char** argv)
{
    (void)argc;
    (void)argv;

    PaError pa_error;
    PaStream* stream = NULL;
    int error = 0;
    double phase = 0;

    pa_error = Pa_Initialize();
    if (pa_error != paNoError)
    {
        return 1;
    }

    pa_error = Pa_OpenDefaultStream(
        &stream,
        0,
        1,
        paFloat32,
        SRATE,
        paFramesPerBufferUnspecified,
        &audio_callback,
        &phase);
    if (pa_error != paNoError)
    {
        error = 1;
        goto exit;
    }

    pa_error = Pa_StartStream(stream);
    if (pa_error != paNoError)
    {
        error = 1;
        goto exit;
    }

    Pa_Sleep(DURATION);

    pa_error = Pa_CloseStream(stream);
    if (pa_error != paNoError)
    {
        error = 1;
        goto exit;
    }

    printf("Done.\n");

exit:
    Pa_Terminate();

    if (pa_error != paNoError)
    {
        printf("PortAudio error: %s\n", Pa_GetErrorText(pa_error));
    }

    return error;
}

Output:

current time = 0.000000; out time = 0.000000
current time = 0.000000; out time = 0.000000
current time = 0.000000; out time = 0.000000
current time = 0.000000; out time = 0.000000
...

Addendum: This same piece of code seems to work fine with Visual Studio in Windows 10.


问:
Click event triggered from parent page not working in IE
I am working with a filter on page to display different products. I am trying to make it so that when you click a button from an external page, it navigates to the product page and automatically clicks the "organics filter" checkbox and then displays the organic items. This code works in every browser except IE and EDGE. Any ideas what could be wrong? It appears to click the organics checkbox but it does not actually click the submit button for IE and EDGE.

**Update: It works if I put an alert after the window.load function. I think its a timing issue or something. Anyone have any suggestions?

```<code>//force organic filter if coming from organics article
    $(window).load(function(){
    var organicURL = document.referrer;
    if (organicURL === "http://www.sampleurl.com") {
       $('#organicFilter').trigger('click');
       if ($('#organicFilter').is(':checked')) {
          $('#submitFilter').trigger('click');
       }
    }
    });
</code>```

答:
In order to trigger click event, you should use the jQuery .click() function. Also, have a look here : jQuery.trigger('click') not working
and here :
Trigger click event not working in IE10</p>

Body:
I am working with a filter on page to display different products. I am trying to make it so that when you click a button from an external page, it navigates to the product page and automatically clicks the "organics filter" checkbox and then displays the organic items. This code works in every browser except IE and EDGE. Any ideas what could be wrong? It appears to click the organics checkbox but it does not actually click the submit button for IE and EDGE.

**Update: It works if I put an alert after the window.load function. I think its a timing issue or something. Anyone have any suggestions?

//force organic filter if coming from organics article
    $(window).load(function(){
    var organicURL = document.referrer;
    if (organicURL === "http://www.sampleurl.com") {
       $('#organicFilter').trigger('click');
       if ($('#organicFilter').is(':checked')) {
          $('#submitFilter').trigger('click');
       }
    }
    });


问:
Efficient synthesis of a 4-to-1 function in Verilog
I need to implement a 4-to-1 function in Veriog.  The input is 4 bits, a number from 0-15.  The output is a single bit, 0 or 1.  Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not.  I want vcs to successfully optimizing the code and also have it be as short/neat as possible.  My solution so far:

```<code>wire [3:0] a;
wire b;
wire [15:0] c;

assign c = 16'b0100110010111010; //for example but could be any constant
assign b = c[a];
</code>```

Having to declare c is ugly and I don't know if vcs will recognize the K-map there.  Will this work as well as a case statement or an assignment in conjunctive normal form?

答: My preference - if it makes sense for your problem - is for a case statement that makes use of enums or `defines. Anything to make code review, maintenance and verification easier.</p>

OwnerDisplayName: Eyal

Body:
I need to implement a 4-to-1 function in Veriog.  The input is 4 bits, a number from 0-15.  The output is a single bit, 0 or 1.  Each input gives a different output and the mapping from inputs to outputs is known, but the inputs and outputs themselves are not.  I want vcs to successfully optimizing the code and also have it be as short/neat as possible.  My solution so far:

wire [3:0] a;
wire b;
wire [15:0] c;

assign c = 16'b0100110010111010; //for example but could be any constant
assign b = c[a];

Having to declare c is ugly and I don't know if vcs will recognize the K-map there.  Will this work as well as a case statement or an assignment in conjunctive normal form?

OwnerDisplayName: Dallas


问:
Is it possible to have a custom webpart listen to default SharePoint search box?
SharePoint has a search box by default at the top of the Portal.  I want my WebPart to be able to intercept that search and provide search results.  Is this possible, and if so any tips or links on how to do this?  </p>

答:
On the result page, just remove the Core Search Results webpart and add your webpart instead.

In your webpart, get the query from the querystring (argument k for keywords and s for scope).

OwnerDisplayName: Nico


问:
Windows EventLog: How fast are operations with it?
I have a service application that is processing client requests over TCP and writing any events into Windows EventLog. Since this application is expected to service many clients and lots of requests from each client in a short amount of time (let's say between 1 and 50 requests per second), I'm curious to know how intensive (CPU wise and time wise) and how fast can writing into Windows EventLog be?

More specifically, how intensive are the operations of connecting to, reading from and writing to EventLog?

答:
I made a test with my 2 event log classes, one writing to file (each log_event() writes to and flushes already opened file) and one based on EventLog (ReportEvent() call on already registered EventSource). In my case file log was about 10 times faster than EventLog. In multithread envirnonment I would add critical section to protect writing to file.

In my opinion files are better: they are easily parsed in tools such as grep. Speed is less important for me.


问:
Multiple Eddystone-URL/UID's from same Bluetooth Beacon?
Is it possible to program a BT beacon to advertise a sequence of different Eddystone-URL/UID's in sequence?  I imagine I could from something like a Raspberry Pi3 with a BT adapter, but I was wondering about something like an actual beacon.  </p>

答:
Yes, this is possible.   This technique is called "interleaving", and it is possible to do with both software beacons and hardware beacons.

Eddystone actually relies on this technique in order to match its multiple frames.  When a receiver sees an Eddystone-TLM frame coming from the same device as Eddystone-URL  or Eddystone-UID, it knows that the telemetry is for that beacon frame.

Using the same technique, it is possible to send out multiple URL or UID frames from the same device using different identifiers for each frame.  Some commercial manufacturers such as Radius Networks support doing this in some of their products.


问:
jQuery check 2 checkboxes in a PHP foreach's loop
I have a javascript's script which allow to check 2 checkboxes with the same values at the same time but it doesn't work.

I get the values from a databases thanks to a php's foreach loop. Here is my test code:

```<code>    <?php
            //checkboxes
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
           //script
           foreach($host1 as $row){ ?>
            <script type="text/javascript">
           var $checkboxes = $("input[type=checkbox][name='list[]'][value='<?php echo $row['table']?>']");
                $checkboxes.on("click", function() {
                var checkedState = this.checked
                $checkboxes.each(function() {
                    this.checked = checkedState;
            });
           });
            </script>
<?php    }
</code>```

If I change the value $row['table'] into a simple number, "2" for example, it's working. I also look if the values ($row['table']) of every checkboxes are the same and they are all good.

Strange thing : When I check any checkboxes, it will not check the corresponding ones, but it will instead check the lasts of the table.

Any ideas where is my mistake ?

Thank you ;)

答:
Instead of doing a php loop and assigning each click event separately, let jQuery handle that:

```<code>// this selector should get all your checkboxes
var checkboxes = $("input[type=checkbox][name='list[]']");

checkboxes.click(function() {
     // not sure what you are trying to do here but it just looks like you are trying to set all checkboxes to the same state as the current one
     checkboxes.prop('checked', this.checked);
});
</code>```

Update

As you only have 2 list of checkboxes with the same name, I have shown options for if they have different parent elements or the same parent element

JS:

var list = $('.parent-element').find("input[type=checkbox][name='list[]']"),
    list1 = $('.parent-element1').find("input[type=checkbox][name='list[]']");

list.click(function() {
  var checkbox = $(this),
      thisIndex = list.index(checkbox);

   list1.eq(thisIndex).prop('checked', this.checked);

   // if at all possible I would use the above index to change the corresponding checkbox in the other list.

   // if all checkboxes are under the same parent then you will only have list (list1 won't be needed)
   // and it will contain all children so to get the corresponding index you would need to do:

   var thisIndex = list.index(checkbox) + (list.length / 2);
   list.eq(thisIndex).prop('checked', this.checked);

});
```

Body:
I have a javascript's script which allow to check 2 checkboxes with the same values at the same time but it doesn't work.

I get the values from a databases thanks to a php's foreach loop. Here is my test code:

    <?php
            //checkboxes
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
            foreach($host1 as $row){
                echo'<input type="checkbox" name="list[]" value="'.$row['table'].'">';
            }
           //script
           foreach($host1 as $row){ ?>

<?php    }

If I change the value $row['table'] into a simple number, "2" for example, it's working. I also look if the values ($row['table']) of every checkboxes are the same and they are all good.

Strange thing : When I check any checkboxes, it will not check the corresponding ones, but it will instead check the lasts of the table.

Any ideas where is my mistake ?

Thank you ;)

Body:
Instead of doing a php loop and assigning each click event separately, let jQuery handle that:

// this selector should get all your checkboxes
var checkboxes = $("input[type=checkbox][name='list[]']");

checkboxes.click(function() {
     // not sure what you are trying to do here but it just looks like you are trying to set all checkboxes to the same state as the current one
     checkboxes.prop('checked', this.checked);
});

Update

As you only have 2 list of checkboxes with the same name, I have shown options for if they have different parent elements or the same parent element

JS:

var list = $('.parent-element').find("input[type=checkbox][name='list[]']"),
    list1 = $('.parent-element1').find("input[type=checkbox][name='list[]']");

list.click(function() {
  var checkbox = $(this),
      thisIndex = list.index(checkbox);

   list1.eq(thisIndex).prop('checked', this.checked);

   // if at all possible I would use the above index to change the corresponding checkbox in the other list.

   // if all checkboxes are under the same parent then you will only have list (list1 won't be needed)
   // and it will contain all children so to get the corresponding index you would need to do:

   var thisIndex = list.index(checkbox) + (list.length / 2);
   list.eq(thisIndex).prop('checked', this.checked);

});


问:
Laravel 5.2 Update with foreign key
hello i've been working on a laravel project lately, and i've wanted to be able to update my records that have foreign keys in them. i've succesfully been able to update records in tables that dont have a foreign key but for some reason my table with a foreign key doesn't want to update. when i var_dump($voorraad) i get the new value on my screen but it doesn't update into the database. I have the same code for my Product table and Location table and there it works completely fine.

My Controller:

```<code> public function update(Request $request, $id)
{
    //voorraad = stock in dutch
    //Product_id = foreign key from the table products
    //locatie_Id = foreign key from the tabe locations
    //aantal = ammount of a certain product

    $voorraad = Voorraad::FindOrFail($id);

    $voorraad->fill($request->only('aantal', 'Product_id', 'locatie_Id'));

    $voorraad->save();

    return redirect(route('voorraad.index'));

}
</code>```

My voorraad model

```<code>   class Voorraad extends Model
{
    //aantal is the ammount

protected $fillable = ['aantal', 'Product_id', 'locatie_Id'];
protected $table = 'voorraad';

public function products()
{
    return $this->belongsTo('App\Product', 'Product_id');
}

public function locaties()
{
    return $this->belongsTo('App\Locatie', 'locatie_Id');
}
</code>```

My Product Model

```<code>class Product extends Model
{
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name

protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','created_at', 'updated_at'];

protected $table = 'product';
</code>```

}

My Location Model:

```<code>class Locatie extends Model
{
protected $fillable = ['naam'];

protected $table = 'locatie';
}
</code>```

My edit form:

```<code>    {!! Form::model($voorraad,['action' => ['VoorraadsController@update', $voorraad->Id], 'method' => 'PATCH'])!!}

{!! Form::label('aantal', 'aantal:') !!}
{!! Form::text('aantal')!!}<br>

{!! Form::label('Product_id', 'product:') !!}
{!! Form::select('Product_id', $products)!!}<br>

{!! Form::label('locatie_Id', 'locatie:') !!}
{!! Form::select('locatie_Id', $locaties)!!} <br>

{!! Form::submit('edit') !!}
</code>```

Gyazo of Var_dump($voorraad): https://gyazo.com/109d54e2bb7a91bbb8b047611e66dbe0

gyazo of var_dump($request):https://gyazo.com/8437ee90881ba38a039b5b583f8296a5

If there is any information missing just let me know and i'll add it

答:
You can update the model and associate it with the Product and Location it belongs to like this: </p>

```<code>$voorraad = Voorraad::findOrFail($id);
$product = Product::findOrFail($request->input('Product_id'));
$location = Location::findOrFail($request->input('locatie_Id'));

$voorraad->aantal = $request->input('aantal');
$voorraad->save();

$product->voorraad()->associate($voorraad);
$location->voorraad()->associate($voorraad);
</code>```

<p>Of course you have to use the proper names for your models. </p>

Title: Laravel 5.2 Update with foreign key

Body:
hello i've been working on a laravel project lately, and i've wanted to be able to update my records that have foreign keys in them. i've succesfully been able to update records in tables that dont have a foreign key but for some reason my table with a foreign key doesn't want to update. when i var_dump($voorraad) i get the new value on my screen but it doesn't update into the database. I have the same code for my Product table and Location table and there it works completely fine.

My Controller:

 public function update(Request $request, $id)
{
    //voorraad = stock in dutch
    //Product_id = foreign key from the table products
    //locatie_Id = foreign key from the tabe locations
    //aantal = ammount of a certain product

    $voorraad = Voorraad::FindOrFail($id);

    $voorraad->fill($request->only('aantal', 'Product_id', 'locatie_Id'));

    $voorraad->save();

    return redirect(route('voorraad.index'));

}

My voorraad model

   class Voorraad extends Model
{
    //aantal is the ammount

protected $fillable = ['aantal', 'Product_id', 'locatie_Id'];
protected $table = 'voorraad';

public function products()
{
    return $this->belongsTo('App\Product', 'Product_id');
}

public function locaties()
{
    return $this->belongsTo('App\Locatie', 'locatie_Id');
}

My Product Model

class Product extends Model
{
//inkoopprijs = sell price
//verkoop prijs = buy price
//naam = product name

protected $fillable = ['naam', 'inkoopprijs', 'verkoopprijs','created_at', 'updated_at'];

protected $table = 'product';

}

My Location Model:

class Locatie extends Model
{
protected $fillable = ['naam'];

protected $table = 'locatie';
}

My edit form:

    {!! Form::model($voorraad,['action' => ['VoorraadsController@update', $voorraad->Id], 'method' => 'PATCH'])!!}

{!! Form::label('aantal', 'aantal:') !!}
{!! Form::text('aantal')!!}

{!! Form::label('Product_id', 'product:') !!}
{!! Form::select('Product_id', $products)!!}

{!! Form::label('locatie_Id', 'locatie:') !!}
{!! Form::select('locatie_Id', $locaties)!!}

{!! Form::submit('edit') !!}

Gyazo of Var_dump($voorraad): https://gyazo.com/109d54e2bb7a91bbb8b047611e66dbe0

gyazo of var_dump($request):https://gyazo.com/8437ee90881ba38a039b5b583f8296a5

If there is any information missing just let me know and i'll add it

Body:
You can update the model and associate it with the Product and Location it belongs to like this:

$voorraad = Voorraad::findOrFail($id);
$product = Product::findOrFail($request->input('Product_id'));
$location = Location::findOrFail($request->input('locatie_Id'));

$voorraad->aantal = $request->input('aantal');
$voorraad->save();

$product->voorraad()->associate($voorraad);
$location->voorraad()->associate($voorraad);

Of course you have to use the proper names for your models.


问:
typescript: resolving typeahead.js with typescript and webpack 2
I am getting the following error from webpack.

ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts
  Module not found: Error: Can't resolve 'typeahead' in ...

I have the following installed

```<code>npm install typeahead.js
npm install @types/typeahead
</code>```

My typescript is as follows, using node module resolution.

```<code>import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.

class TypeAheadController {
    foo(e) {
       $(e).typeahead(...)
    }
}
</code>```

this generates javascript as follows:

```<code>"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...
</code>```

My webpack.config.js is as follows:

```<code>module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};
</code>```

imported into a gulp task.

How do I specify that typeahead is located in node_modules/typeahead.js/dist/typeahead.bundle.js

答:
You could solve this using aliasing. Minimal example of what to change  in your webpack.config.js:

```<code>module.exports = {
  /* ... everything you currently have */
  resolve: {
    alias: {
      typeahead: 'typeahead.js'
    }
  }
}
</code>```

Body:
I am getting the following error from webpack.

ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts
  Module not found: Error: Can't resolve 'typeahead' in ...

I have the following installed

npm install typeahead.js
npm install @types/typeahead

My typescript is as follows, using node module resolution.

import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.

class TypeAheadController {
    foo(e) {
       $(e).typeahead(...)
    }
}

this generates javascript as follows:

"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...

My webpack.config.js is as follows:

module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};

imported into a gulp task.

How do I specify that typeahead is located in node_modules/typeahead.js/dist/typeahead.bundle.js

Body:
You could solve this using aliasing. Minimal example of what to change  in your webpack.config.js:

module.exports = {
  /* ... everything you currently have */
  resolve: {
    alias: {
      typeahead: 'typeahead.js'
    }
  }
}


问:
facing issue with deleting items from cart in codeigniter
can we delete two items at a time from the cart in codeigniter?? i try to delete but it is not happened. because the rowid is different for every items in the cart. Anyone Knows the solution of this problem? </p>

答:
yes you can delete multiple items at the same time

You can set the qty to zero for multiple items https://www.codeigniter.com/userguide3/libraries/cart.html#updating-the-cart

```<code> $data = array(
        array(
                'rowid'   => 'b99ccdf16028f015540f341130b6d8ec',
                'qty'     => 0
        ),
        array(
                'rowid'   => 'xw82g9q3r495893iajdh473990rikw23',
                'qty'     => 0
        )
);

$this->cart->update($data);
</code>```

Body:
yes you can delete multiple items at the same time

You can set the qty to zero for multiple items https://www.codeigniter.com/userguide3/libraries/cart.html#updating-the-cart

 $data = array(
        array(
                'rowid'   => 'b99ccdf16028f015540f341130b6d8ec',
                'qty'     => 0
        ),
        array(
                'rowid'   => 'xw82g9q3r495893iajdh473990rikw23',
                'qty'     => 0
        )
);

$this->cart->update($data);


问:
relation does not exist ActiveSupport::Concern
I have simple module and it included to my model

```<code>module Inputable
  extend ActiveSupport::Concern

  included do
    has_many :inputs, as: :inputable, dependent: :destroy
  end
end

 class Product < ActiveRecord::Base
    include Inputable
end
</code>```

But when i try to call Product.first.inputs i have got an error

```<code>    PG::UndefinedTable: ERROR:  relation "inputs" does not exist
LINE 5: WHERE a.attrelid = '"inputs"'::regclass
: SELECT a.attname, format_type(a.atttypid, a.atttypmod)

Product.reflect_on_all_associations.map { |assoc| assoc.name}
=>[:inputs]
</code>```

What is wrong with my code?

答:
Make sure you've generated the Input model and run the migrations.

Also, when I use the included hook, it tends to look more like this:

```<code>module Inputable
  extend ActiveSupport::Concern

  self.included(base)
    base.class_eval do
      has_many :inputs, as: :inputable, dependent: :destroy
    end
  end

end
</code>```

I'd be interested to know if the syntax you're using works for you. Happy metaprogramming!

Body:
I have simple module and it included to my model

module Inputable
  extend ActiveSupport::Concern

  included do
    has_many :inputs, as: :inputable, dependent: :destroy
  end
end

 class Product < ActiveRecord::Base
    include Inputable
end

But when i try to call Product.first.inputs i have got an error

    PG::UndefinedTable: ERROR:  relation "inputs" does not exist
LINE 5: WHERE a.attrelid = '"inputs"'::regclass
: SELECT a.attname, format_type(a.atttypid, a.atttypmod)

Product.reflect_on_all_associations.map { |assoc| assoc.name}
=>[:inputs]

What is wrong with my code?

Body:
Make sure you've generated the Input model and run the migrations.

Also, when I use the included hook, it tends to look more like this:

module Inputable
  extend ActiveSupport::Concern

  self.included(base)
    base.class_eval do
      has_many :inputs, as: :inputable, dependent: :destroy
    end
  end

end

I'd be interested to know if the syntax you're using works for you. Happy metaprogramming!


问:
How to select an ListView item after long click?
I've got a silly little problem. I've registered a ListFragment both as OnItemClickListener and OnItemLongClickListener of its own ListView.

When the onItemClick event is called, an intent for the detail view activity of that item is started, no problems there.

When the onItemLongClickevent happens, I want to accomplish the following things:

Create a CAB

Keep the long-pressed item selected

Code:

```<code>@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    if(this.cabMode != null)
        return false;
    this.cabMode = getActivity().startActionMode(editModeCallback);
    view.setSelected(true);
    return true;
}
</code>```

The CAB will show, however, the selection won't stay with the item.

Some bits and pieces, in case they are relevant: I've read about fixing this issue with calls to view.requestFocusFromTouch() or using listView.setItemChecked(), but that didn't work for me. Also, the views for the list items are instanced from a custom layout, but don't have any custom event listeners attached.

Any help is appreciated. Thx!

答:
My solution:(trick)</p>

```<code>final ListView lvMain = (ListView) activity.findViewById(R.id.listTHEMES);
lvMain.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvMain.setItemsCanFocus(false);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
            android.R.layout.simple_list_item_multiple_choice, ArrayTheme);
lvMain.setAdapter(adapter);
lvMain.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int pos, long id) {
        // TODO Auto-generated method stub
        if (lvMain.isItemChecked(pos)){lvMain.setItemChecked(pos,false);}else{lvMain.setItemChecked(pos,true);}
        Log.v(LOG_TAG,"long clicked pos: " + pos);
        //lvMain.setSelection();

        return true;
    }
});
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
        //Log.d(LOG_TAG, "itemClick: position = " + position + ", id = " + id);
        if (lvMain.isItemChecked(position)){lvMain.setItemChecked(position,false);}else{lvMain.setItemChecked(position,true);}

    }
});
</code>```

Body:
I've got a silly little problem. I've registered a ListFragment both as OnItemClickListener and OnItemLongClickListener of its own ListView.

When the onItemClick event is called, an intent for the detail view activity of that item is started, no problems there.

When the onItemLongClickevent happens, I want to accomplish the following things:

Create a CAB

Keep the long-pressed item selected

Code:

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    if(this.cabMode != null)
        return false;
    this.cabMode = getActivity().startActionMode(editModeCallback);
    view.setSelected(true);
    return true;
}

The CAB will show, however, the selection won't stay with the item.

Some bits and pieces, in case they are relevant: I've read about fixing this issue with calls to view.requestFocusFromTouch() or using listView.setItemChecked(), but that didn't work for me. Also, the views for the list items are instanced from a custom layout, but don't have any custom event listeners attached.

Any help is appreciated. Thx!

Body:
My solution:(trick)

final ListView lvMain = (ListView) activity.findViewById(R.id.listTHEMES);
lvMain.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lvMain.setItemsCanFocus(false);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
            android.R.layout.simple_list_item_multiple_choice, ArrayTheme);
lvMain.setAdapter(adapter);
lvMain.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int pos, long id) {
        // TODO Auto-generated method stub
        if (lvMain.isItemChecked(pos)){lvMain.setItemChecked(pos,false);}else{lvMain.setItemChecked(pos,true);}
        Log.v(LOG_TAG,"long clicked pos: " + pos);
        //lvMain.setSelection();

        return true;
    }
});
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
        //Log.d(LOG_TAG, "itemClick: position = " + position + ", id = " + id);
        if (lvMain.isItemChecked(position)){lvMain.setItemChecked(position,false);}else{lvMain.setItemChecked(position,true);}

    }
});


问:
PHP Query returns 'Conversion failed when converting the varchar value'
Basically i send some data via an Ajax request to a php script which should run a query to update a table in the database.

However its been taking the text and note id i want no problem:

So i know its sending the data i want, however the table just isnt updating (it doesnt have the words "Additional text" from the data i sent there)

Now in the firefox Developer window under the network tab and under preview i have:

which seems to be throwing a sql error?

This is the php script run from the request:

```<code><?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];

    $stmt = "UPDATE Notes SET Note = ? WHERE NoteID = ?";
    $params = array($noteid2, $notetext2);

    $stmt = sqlsrv_query($conn, $stmt, $params);

    if ($stmt === false)
    {
        die( print_r(sqlsrv_errors(), true));
    }
}
else
{
    echo "No Data";

}

?>
</code>```

and this is the request itself:

```<code>function submitNoteText()
{
    var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
    var notetext = $("#ta1").val();

    if(noteid == ''||notetext == '')
    {
        alert("NoteID or Text is blank");
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "submitNoteText.php",
            dataType: 'json',
            data: {noteid1: noteid, notetext1: notetext},
            cache: false,
            success: function(result){
                alert("Success");
            }
        });
    }
    return false;
};
</code>```

so i guess the reason its not updating the table is that error, so my question is how do i write the query safely in php without getting that error?

答:
I think you've forgot the single quotes in Note column. Try this:

```<code>$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];

$stmt = "UPDATE Notes SET Note = '$notetext2' WHERE NoteID = ?";
</code>```

Body:
Basically i send some data via an Ajax request to a php script which should run a query to update a table in the database.

However its been taking the text and note id i want no problem:

So i know its sending the data i want, however the table just isnt updating (it doesnt have the words "Additional text" from the data i sent there)

Now in the firefox Developer window under the network tab and under preview i have:

which seems to be throwing a sql error?

This is the php script run from the request:

<?php include 'connectionDetails.php'; ?>

<?php

if (isset($_POST['noteid1'], $_POST['notetext1']))
{

    $noteid2 = $_POST['noteid1'];
    $notetext2 = $_POST['notetext1'];

    $stmt = "UPDATE Notes SET Note = ? WHERE NoteID = ?";
    $params = array($noteid2, $notetext2);

    $stmt = sqlsrv_query($conn, $stmt, $params);

    if ($stmt === false)
    {
        die( print_r(sqlsrv_errors(), true));
    }
}
else
{
    echo "No Data";

}

?>

and this is the request itself:

function submitNoteText()
{
    var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
    var notetext = $("#ta1").val();

    if(noteid == ''||notetext == '')
    {
        alert("NoteID or Text is blank");
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "submitNoteText.php",
            dataType: 'json',
            data: {noteid1: noteid, notetext1: notetext},
            cache: false,
            success: function(result){
                alert("Success");
            }
        });
    }
    return false;
};

so i guess the reason its not updating the table is that error, so my question is how do i write the query safely in php without getting that error?

Body:
I think you've forgot the single quotes in Note column. Try this:

$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];

$stmt = "UPDATE Notes SET Note = '$notetext2' WHERE NoteID = ?";


问:
Do I need test method that is inside the test class
So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

```<code>public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}
</code>```

I have to write a JUnit test (and I did it):

```<code>@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}
</code>```

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

```<code>public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}
</code>```

And it works.
But that is not my question.
I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't  ask google right).
Thanks :)

答: No, this isn't a good idea to write "test for test". I worked in many companies and nowhere we did it. There is enough of what you wrote.</p>

Body:
So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}

I have to write a JUnit test (and I did it):

@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}

And it works.
But that is not my question.
I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't  ask google right).
Thanks :)


问:
merge unknown number of sub-arrays in array
I have an array like this:

```<code>arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]
</code>```

and I want to turn it into an array like this:

```<code>arr = [  [x,x],[x,x] ,  [x,x],[x,x],[x,x],   [x,x]  ]
</code>```

so I have tried this:

```<code>for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }
</code>```

but it does not work. How can I 'merge' this intermediate level of array?

答:
The array.concat() doesn't change the array you call it on, but rather returns a new array - a new array you are ignoring.

You should create a result array and then append everything to that, instead of trying to modify arr.

```<code>var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ];
var new_arr = [];

for(var i = 0; i < arr.length; i++){
    new_arr = new_arr.concat(arr[i]);
}
</code>```

Body:
I have an array like this:

arr = [ [[x,x],[x,x]], [[x,x],[x,x],[x,x]], [[x,x]] ]

and I want to turn it into an array like this:

arr = [  [x,x],[x,x] ,  [x,x],[x,x],[x,x],   [x,x]  ]

so I have tried this:

for (var i=1; i< arr.length; i++){ arr[0].concat(arr[i]); }

but it does not work. How can I 'merge' this intermediate level of array?

Body:
The array.concat() doesn't change the array you call it on, but rather returns a new array - a new array you are ignoring.

You should create a result array and then append everything to that, instead of trying to modify arr.

var arr = [ [['x','x'],['x','x']], [['x','x'],['x','x'],['x','x']], [['x','x']] ];
var new_arr = [];

for(var i = 0; i < arr.length; i++){
    new_arr = new_arr.concat(arr[i]);
}


问:
git push not a git repository
I'm trying to deploy an PHP application at Heroku.
I am following they're guide, that can be found here https://devcenter.heroku.com/articles/getting-started-with-php
But I got stuck in the Deploying the app step
The tutorial tells me to run git push heroku master, but I keep getting "fatal: Not a git repository (or any of the parent directories): .git"
I've never done this before, but I tried to push other repositories and I keep getting the same message
I have no idea if the problem is with git, heroku, or if it's actually me who's doing something wrong

please help DDD:

答: I guess you are trying to push into a non-repo on the remote side.</p>

Title: git push not a git repository


问:
How do I detect if a user has got to a page using the back button?
This question is similar to Track when user hits back button on the browser, but not the same...  I have a solution and am posting it here for reference and feedback.  If anyone has any better options, I'm all ears!

The situation is that I have a page with an "in place edit", a la flickr.  I.e. there is a "click here to add a description" DIV, which when clicked turns into a TEXTAREA with Save and Cancel buttons.  Clicking Save posts the data to the server to update the database and puts the new description in the DIV in place of the TEXTAREA.  If the page is refreshed, the new description is displayed from the database with a "click to edit" option.  Fairly standard web 2.0 stuff these days.

The issue is that if:

the page is loaded without the description

a description is added by the user

the page is navigated away from by clicking a link

the user clicks the back button

Then what is displayed (from the browser's cache) is the version of the page without the dynamically modified DIV containing the new description.

This is a fairly big problem as the user assumes that their update has been lost and won't necessarily understand that they need to refresh the page to see the changes.

So, the question is: How can you flag a page as being modified after it has loaded, and then detect when the user "goes back to it" and force a refresh in that situation?

答:
Here's a jQuery version. I've run into needing to use it a few times due to the way Safari desktop/mobile handles the cache when a user presses the back button.</p>

```<code>$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        // Loading from cache
    }
});
</code>```

Body:
Here's a jQuery version. I've run into needing to use it a few times due to the way Safari desktop/mobile handles the cache when a user presses the back button.

$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        // Loading from cache
    }
});