答:
You can write authenticated as a property getter:

```<code>public get authenticated(): boolean {
    return this.authService.isAuthenticated();
}
</code>```

Title: Angular(5) - Login button not changing to Logout on successful login

Body:
I'm using Auth0's API to handle user management. Everything is working as intended - On Login() it properly stores local. On Logout() it properly removes them.

However, the actual Login button is not becoming Logout automatically on success - It is when I hard-refresh the page, but not directly. I believe this is an issue with my binding?

Header component

  authenticated: boolean; // Wasn't sure how else to filter in front-end

  constructor(private authService: AuthService) { }

  ngOnInit() {
    this.authenticated = this.authService.isAuthenticated()
  }

  login() {
    this.authService.login();
  }

  logout() {
    this.authService.logout();
  }

}

HTML For Header

     Log In
     Log Out

The docs said to use auth.isAuthenticated() which would call the function from the service

  public isAuthenticated(): boolean {
    // Check whether the current time is past the
    // access token's expiry time
    const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

I was thinking perhaps I should append this.authenticated = this.authService.isAuthenticated() to the end of each login()/logout() function in the header component, but I'm feeling like I'm going the wrong direction with this.

Welcome any input.

Update

Modifying logout() to call this.authenticated = this.authService.isAuthenticated() did resolve the issue for it, but Login is still not becoming Log Out until I refresh the page.

Body:
You can write authenticated as a property getter:

public get authenticated(): boolean {
    return this.authService.isAuthenticated();
}


来源: stackexchange

问:
Use While Loop With setTimeout
I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:

```<code>function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
    var ibumped = i + 1;
    console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
    var weaponChoice = prompt("Which weapon do you choose?");
    switch (weaponChoice) {
        case 1:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");
            break;
        case 2:
            weaponChosen = userWeapons[1];
            console.log(userWeapons[1].name + " chosen.");
            break;
        default:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");

    };
}, 1000);
setTimeout(function() {
    if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
        enemy.shields = enemy.shields - weaponChosen.damage;
        weaponChosen.fire(enemy);
        if (enemy.shields < 0) {
            enemy.health = enemy.health + enemy.shields;
            console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
        } else {
            console.log("Enemy shields have been reduced to " + enemy.shields + ".");
        }
    } else {
        enemy.health = enemy.health - weaponChosen.damage;
        weaponChosen.fire(enemy);
        console.log("Enemy takes " + weaponChosen.damage + " damage!");
    }
    if (enemy.health <= 0 && battleOver === false) {
        console.log("Enemy destroyed!");
        battleOver = true;
    }
}, 3000);
setTimeout(function() {
    if (enemy.health > 0 && battleOver === false) {
        if (enemy.weapons != null) {
            console.log(enemy.weapons.name + " fired at you.");
            health = health - enemy.weapons.damage;
            console.log("You have " + health + " health left.");
            if (health <= 0) {
                console.log("Game over... You were destroyed");
                battleOver = true;
            }
        } else {
            console.log("The enemy did nothing...");
        }
    };
}, 5000);
}
}
</code>```

All help is appreciated!

答:
Things start getting very tricky when you use setTimeout. Most games will have a "main game loop" that runs 60 times a second.

Try using a main game loop and cooldowns.

Here's an example of how you could restructure the program.

```<code>var timeForOneFrame = 1000/60 // 60 Frames per second
var enemy;
var battleOver;

function initGame() {
    /*
      Initialize the enemy etc.
    */
}

function gameLoop() {
  battle(enemy);
}

function battle(enemy) {

  /*
    Do all the battle stuff, this function is called 60 times a second-
    there's no need for setTimeout!
  */

  // If you want an enemy to only be able to attack every 2 seconds, give them
  // a cooldown...
  if (enemy.cooldown <= 0) {
    // Attack!
    enemy.cooldown += 2000
  } else {
    enemy.cooldown -= timeForOneFrame
  }

  if (enemy.health <= 0 && battleOver === false) {
    console.log("Enemy destroyed!");
    battleOver = true;
    clearInterval(gameLoopInterval)
  }
}

initGame();
var gameLoopInterval = setInterval(gameLoop, timeForOneFrame);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Use While Loop With setTimeout

Body:
I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:

function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
    var ibumped = i + 1;
    console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
    var weaponChoice = prompt("Which weapon do you choose?");
    switch (weaponChoice) {
        case 1:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");
            break;
        case 2:
            weaponChosen = userWeapons[1];
            console.log(userWeapons[1].name + " chosen.");
            break;
        default:
            weaponChosen = userWeapons[0];
            console.log(userWeapons[0].name + " chosen.");

    };
}, 1000);
setTimeout(function() {
    if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
        enemy.shields = enemy.shields - weaponChosen.damage;
        weaponChosen.fire(enemy);
        if (enemy.shields < 0) {
            enemy.health = enemy.health + enemy.shields;
            console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
        } else {
            console.log("Enemy shields have been reduced to " + enemy.shields + ".");
        }
    } else {
        enemy.health = enemy.health - weaponChosen.damage;
        weaponChosen.fire(enemy);
        console.log("Enemy takes " + weaponChosen.damage + " damage!");
    }
    if (enemy.health <= 0 && battleOver === false) {
        console.log("Enemy destroyed!");
        battleOver = true;
    }
}, 3000);
setTimeout(function() {
    if (enemy.health > 0 && battleOver === false) {
        if (enemy.weapons != null) {
            console.log(enemy.weapons.name + " fired at you.");
            health = health - enemy.weapons.damage;
            console.log("You have " + health + " health left.");
            if (health <= 0) {
                console.log("Game over... You were destroyed");
                battleOver = true;
            }
        } else {
            console.log("The enemy did nothing...");
        }
    };
}, 5000);
}
}

All help is appreciated!

Body:
Things start getting very tricky when you use setTimeout. Most games will have a "main game loop" that runs 60 times a second.

Try using a main game loop and cooldowns.

Here's an example of how you could restructure the program.

var timeForOneFrame = 1000/60 // 60 Frames per second
var enemy;
var battleOver;

function initGame() {
    /*
      Initialize the enemy etc.
    */
}

function gameLoop() {
  battle(enemy);
}

function battle(enemy) {

  /*
    Do all the battle stuff, this function is called 60 times a second-
    there's no need for setTimeout!
  */

  // If you want an enemy to only be able to attack every 2 seconds, give them
  // a cooldown...
  if (enemy.cooldown <= 0) {
    // Attack!
    enemy.cooldown += 2000
  } else {
    enemy.cooldown -= timeForOneFrame
  }

  if (enemy.health <= 0 && battleOver === false) {
    console.log("Enemy destroyed!");
    battleOver = true;
    clearInterval(gameLoopInterval)
  }
}

initGame();
var gameLoopInterval = setInterval(gameLoop, timeForOneFrame);


问:
Is it possible to get ivars with startMonitoringSignificantLocationChanges in backgrounded mode
When an app uses startMonitoringSignificantLocationChanges while backgrounded or when terminated, if a significant change is detected Apple states that it will bring the app back into the foreground. But, will I still be able to get the value of an ivar (previously set when the app was in the foreground) within the  didUpdateToLocation CLLocationManager delegate method? Or is it lost?

If it is lost, what is the best way to persist those values after the app has terminated/backgrounded and brought back into the foreground by the location manager?

答: Yes of course you will. The only way you'd lose the value of that ivar is if your app has actually quit and been relaunched, at which point you're not simply coming back from the background.</p>

ContentLicense: CC BY-SA 2.5


问:
How to change the number of rows using a st-template
I've created a st-template that contains specific pagination functionality.

Here is mine the div that calls the st-template:

```<code><div st-pagination="" st-items-by-page="itemsPerPage" st-displayed-pages="7" st-template="dashboard-pagination.html"></div>
</code>```

Within this pagination we have a dropdown/button where the user can select the number of rows to display within the table.

```<code><ul aria-activedescendant=""
            class=""
            role="menu"
            tabindex="0"
        >
            <li class="" ng-repeat="page in pages">
                <input
                    id="items-per-page-{{page * 10}}"
                    name="items-per-page-options"
                    type="radio"
                    value=""
                    role="menuitemradio"
                    aria-checked="true"
                    checked
                    ng-model="itemsPerPage"
                >
                <label for="items-per-page-{{page * 10}}">
                    <span class=""></span> {{ page * 10 }}
                </label>
            </li>
        </ul>
</code>```

So 'itemsPerPage' updates in the template but does not reach the , which is in another html file.

I have been looking for an answer for a few hours and haven't really found one.  This is my first experience working with smart-table and angularJS so I may not be using the correct key words.

Any help would be appreciated.

答:
I ended up moving the items per-page html out of the template into the datatable html file.  I created an array of static values that represents the number of row to display ['10','20','30','40','50'].  Once the user selects one I send in the ng-model itemPerPage and the items update to that selection.

The reason it wasn't working in the template was because of the ng-repeat created a child scope so when I used ng-model it was not modify the original scope.

Body:
I've created a st-template that contains specific pagination functionality.

Here is mine the div that calls the st-template:

Within this pagination we have a dropdown/button where the user can select the number of rows to display within the table.

                <input
                    id="items-per-page-{{page * 10}}"
                    name="items-per-page-options"
                    type="radio"
                    value=""
                    role="menuitemradio"
                    aria-checked="true"
                    checked
                    ng-model="itemsPerPage"
                >

                     {{ page * 10 }}

So 'itemsPerPage' updates in the template but does not reach the , which is in another html file.

I have been looking for an answer for a few hours and haven't really found one.  This is my first experience working with smart-table and angularJS so I may not be using the correct key words.

Any help would be appreciated.


问:
Is it safe to cast from List<Optional> to List<Optional<?>>?
If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List can be safely cast to a List<?>, which removes its raw nature and allows you to use it in a safe (type-checked) manner1.

On the other hand, Java doesn't let you cast from a List itself parameterized with a raw type, like List<Optional> to a list of the same type parameter with an unbounded wildcard, like List<Optional<?>>.

You can still do it by dropping all the way down a raw List and back up again (implicitly via the assignment):

```<code>List<Optional> rawOptionalList = null;
List<Optional<?>> wildcardOptionalList = (List)rawOptionalList;
</code>```

Of course, this triggers warning about unchecked conversion (from List to List<Optional<?>>).

It seems to me though that this conversion is guaranteed safe: isn't List<Optional<?>> just as safe as List<Optional> in the same way that casting a raw Optional to an Optional<?> is safe?

1 ... but you'll never be able to add anything to this list, since nothing will match the capture of ? for the add(?) method. That's the price you pay for safety.

答:
Type erasure in Java means that all parameterized types are erased at runtime. In your case, a List<Optional> is just a List at runtime and an Optional<MyClass> is just an Optional at runtime.

When you get a contained class from a List or an Optional, Java makes a cast to the parameterized type. So not only is your code safe, it is exactly what the Java compiler does.

Body:
If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List can be safely cast to a List<?>, which removes its raw nature and allows you to use it in a safe (type-checked) manner1.

On the other hand, Java doesn't let you cast from a List itself parameterized with a raw type, like List<Optional> to a list of the same type parameter with an unbounded wildcard, like List<Optional<?>>.

You can still do it by dropping all the way down a raw List and back up again (implicitly via the assignment):

List<Optional> rawOptionalList = null;
List<Optional<?>> wildcardOptionalList = (List)rawOptionalList;

Of course, this triggers warning about unchecked conversion (from List to List<Optional<?>>).

It seems to me though that this conversion is guaranteed safe: isn't List<Optional<?>> just as safe as List<Optional> in the same way that casting a raw Optional to an Optional<?> is safe?

1 ... but you'll never be able to add anything to this list, since nothing will match the capture of ? for the add(?) method. That's the price you pay for safety.


问:
JavaScript reference to event, declared by addEventListener()
I am trying to implement a Web Application which is supposed to let you draw shapes over a grid of pixels. For this purpose, I need to add several event listeners to each table element of my grid.
This is what I did so far:

```<code>td.addEventListener("click", setpixel);
td.addEventListener("mousedown", function () {
    mousedown = true;
})
td.addEventListener("mouseup", function () {
    mousedown = false;
})
td.addEventListener("mousemove", function () {
    if (mousedown) {
        setpixel(?);
    }
});
</code>```

The setPixel() function needs an event passed as parameter:

```<code>function setpixel(event) {
    var oldColor = this.style.backgroundColor;
    var currentColor=document.getElementById("current-color").style.backgroundColor;
    if (brushwidth > 1 && brushwidth < 4) {
        brushpixel(this.id, offset, currentColor);
    }
    else if (brushwidth == 4) {
        document.body.style.cursor = "url('https://www.wired.com/wp-content/uploads/images_blogs/design/2013/04/Susan-Kare-fill-icon-660x660.jpg')";
        floodfill(this.id, currentColor, oldColor);
        preview();
    }
    else {
        this.style.backgroundColor = currentColor;
    }
    preview();
}
</code>```

Otherwise it cannot function properly.
Where do I get the referenced event from?

Linked thread does not work for me here, not sure why, but I tried it out.

答:
add the event to your listening function arguments </p>

```<code>td.addEventListener("mousemove", function (e) {
    if (mousedown) {
        setpixel(e);
    }
});
</code>```

Body:
I am trying to implement a Web Application which is supposed to let you draw shapes over a grid of pixels. For this purpose, I need to add several event listeners to each table element of my grid.
This is what I did so far:

td.addEventListener("click", setpixel);
td.addEventListener("mousedown", function () {
    mousedown = true;
})
td.addEventListener("mouseup", function () {
    mousedown = false;
})
td.addEventListener("mousemove", function () {
    if (mousedown) {
        setpixel(?);
    }
});

The setPixel() function needs an event passed as parameter:

function setpixel(event) {
    var oldColor = this.style.backgroundColor;
    var currentColor=document.getElementById("current-color").style.backgroundColor;
    if (brushwidth > 1 && brushwidth < 4) {
        brushpixel(this.id, offset, currentColor);
    }
    else if (brushwidth == 4) {
        document.body.style.cursor = "url('https://www.wired.com/wp-content/uploads/images_blogs/design/2013/04/Susan-Kare-fill-icon-660x660.jpg')";
        floodfill(this.id, currentColor, oldColor);
        preview();
    }
    else {
        this.style.backgroundColor = currentColor;
    }
    preview();
}

Otherwise it cannot function properly.
Where do I get the referenced event from?

Linked thread does not work for me here, not sure why, but I tried it out.

Body:
add the event to your listening function arguments

td.addEventListener("mousemove", function (e) {
    if (mousedown) {
        setpixel(e);
    }
});


问:
Finding correlation coefficient from 2 lists
I am working on a project which has many functions when given a couple lists of data. I've already seperated the lists and I have defined some functions which I know for certain work correctly, that being a mean function and standard deviation function. My issue is when testing my lists I get a correct mean, correct standard deviation, but incorrect correlation coefficient. Could my math be off here? I need to find the correlation coefficient with only Python's standard library.

MY CODE:

```<code>def correlCo(someList1, someList2):

    # First establish the means and standard deviations for both lists.
    xMean = mean(someList1)
    yMean = mean(someList2)
    xStandDev = standDev(someList1)
    yStandDev = standDev(someList2)
    zList1 = []
    zList2 = []

    # Create 2 new lists taking (a[i]-a's Mean)/standard deviation of a
    for x in someList1:
        z1 = ((float(x)-xMean)/xStandDev)
        zList1.append(z1)

    for y in someList2:
        z2 = ((float(y)-yMean)/yStandDev)
        zList2.append(z2)

    # Mapping out the lists to be float values instead of string
    zList1 = list(map(float,zList1))
    zList2 = list(map(float,zList2))
    # Multiplying each value from the lists
    zFinal = [a*b for a,b in zip(zList1,zList2)]
    totalZ = 0
    # Taking the sum of all the products
    for a in zFinal:
        totalZ += a
    # Finally calculating correlation coefficient
    r = (1/(len(someList1) - 1)) * totalZ

    return r
</code>```

SAMPLE RUN:

I have a list of [1,2,3,4,4,8] and [3,3,4,5,8,9]

I expect the correct answer of r = 0.8848, but get r = .203727

EDIT: To include the mean and standard deviation functions I have made.

```<code>def mean(someList):
    total = 0
    for a in someList:
        total += float(a)
    mean = total/len(someList)
    return mean

def standDev(someList):
    newList = []
    sdTotal = 0
    listMean = mean(someList)
    for a in someList:
        newNum = (float(a) - listMean)**2
        newList.append(newNum)

    for z in newList:
        sdTotal += float(z)

    standardDeviation = sdTotal/(len(newList))

    return standardDeviation
</code>```

答:
The Pearson correlation can be calculated with numpy's corrcoef.

```<code>import numpy
numpy.corrcoef(list1, list2)[0, 1]
</code>```

Body:
I am working on a project which has many functions when given a couple lists of data. I've already seperated the lists and I have defined some functions which I know for certain work correctly, that being a mean function and standard deviation function. My issue is when testing my lists I get a correct mean, correct standard deviation, but incorrect correlation coefficient. Could my math be off here? I need to find the correlation coefficient with only Python's standard library.

MY CODE:

def correlCo(someList1, someList2):

    # First establish the means and standard deviations for both lists.
    xMean = mean(someList1)
    yMean = mean(someList2)
    xStandDev = standDev(someList1)
    yStandDev = standDev(someList2)
    zList1 = []
    zList2 = []

    # Create 2 new lists taking (a[i]-a's Mean)/standard deviation of a
    for x in someList1:
        z1 = ((float(x)-xMean)/xStandDev)
        zList1.append(z1)

    for y in someList2:
        z2 = ((float(y)-yMean)/yStandDev)
        zList2.append(z2)

    # Mapping out the lists to be float values instead of string
    zList1 = list(map(float,zList1))
    zList2 = list(map(float,zList2))
    # Multiplying each value from the lists
    zFinal = [a*b for a,b in zip(zList1,zList2)]
    totalZ = 0
    # Taking the sum of all the products
    for a in zFinal:
        totalZ += a
    # Finally calculating correlation coefficient
    r = (1/(len(someList1) - 1)) * totalZ

    return r

SAMPLE RUN:

I have a list of [1,2,3,4,4,8] and [3,3,4,5,8,9]

I expect the correct answer of r = 0.8848, but get r = .203727

EDIT: To include the mean and standard deviation functions I have made.

def mean(someList):
    total = 0
    for a in someList:
        total += float(a)
    mean = total/len(someList)
    return mean

def standDev(someList):
    newList = []
    sdTotal = 0
    listMean = mean(someList)
    for a in someList:
        newNum = (float(a) - listMean)**2
        newList.append(newNum)

    for z in newList:
        sdTotal += float(z)

    standardDeviation = sdTotal/(len(newList))

    return standardDeviation

Body:
The Pearson correlation can be calculated with numpy's corrcoef.

import numpy
numpy.corrcoef(list1, list2)[0, 1]


问:
Set HttpOnly for all cookies in spark-java
I developed a web UI to configure a device. To secure this UI which achieves OWASP top 10 and fix bug that reported by Acunetix application, some improvement must be done on it. One of them is setting HTTP-ONLY for cookies.

How can change/set cookie default attribute in java-spark?

答:
Please try this:

```<code>//set HttpOnly properties for all cookies
for (String key : cookies.keySet()) {
    if (key != null) {
        response.removeCookie(key);
        response.cookie("/", key, cookies.get(key), 200, false, true);
    }
}
</code>```

Note that it is not possible to change settings of jetty through spark. Adding such feature to spark can considerably facilitate the process of changing cookie-related settings.

Body:
Please try this:

//set HttpOnly properties for all cookies
for (String key : cookies.keySet()) {
    if (key != null) {
        response.removeCookie(key);
        response.cookie("/", key, cookies.get(key), 200, false, true);
    }
}

Note that it is not possible to change settings of jetty through spark. Adding such feature to spark can considerably facilitate the process of changing cookie-related settings.


问:
Rails 3 ajax javascript rendering issue
I'm trying to issue a simple ajax request in a rails (3.0.3) view through a link_to.

```<code><%= link_to "like", toggle_author_likes_path(current_author, post), :remote => true %>
</code>```

The idea of this being that the action in LikesController#toggle will render some Javascript to alter the page after the request returns. Fairly straightforward stuff, right?

The issue I'm having is that the action seems to have trouble finding the right *.js.erb file. The relevant snippet in the LikesController#toggle action is:

```<code>respond_to do |format|
  format.html { redirect_to post_path(@post) }
  format.js
end
</code>```

When I try to issue this request, the action is executed, but the request responds with a 500 Internal Server Error. The text of the error is:

```<code>Missing template likes/toggle with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:js, :html], :locale=>[:en, :en]}...
</code>```

I have double and triple checked the placement of my _toggle.js.erb file and am sure I have named it right, and the contents are valid (although that's not important because it is never completed).

Just doing a regular GET without any fancy ajax on the js file returns the exact same error, so chances are good that the problem lies somewhere along the Rails rendering chain.

I won't include the rest of the method as is is quite verbose and I am confident that it does not factor into this particular problem, but if anybody thinks it is important, I'll post it.

Thanks!

EDIT:
Fixed the problem. It was my own stupid fault, I named the view like a partial, with an underscore before it. Removed, and the whole thing works perfectly. Idiot, idiot, idiot.

答: You need to have a separate template called toggle.rjs  This RailsCast, while being slightly outdated, still explains what to put in the toggle.rjs file.</p>

Title: Rails 3 ajax javascript rendering issue

Body:
I'm trying to issue a simple ajax request in a rails (3.0.3) view through a link_to.

<%= link_to "like", toggle_author_likes_path(current_author, post), :remote => true %>

The idea of this being that the action in LikesController#toggle will render some Javascript to alter the page after the request returns. Fairly straightforward stuff, right?

The issue I'm having is that the action seems to have trouble finding the right *.js.erb file. The relevant snippet in the LikesController#toggle action is:

respond_to do |format|
  format.html { redirect_to post_path(@post) }
  format.js
end

When I try to issue this request, the action is executed, but the request responds with a 500 Internal Server Error. The text of the error is:

Missing template likes/toggle with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:js, :html], :locale=>[:en, :en]}...

I have double and triple checked the placement of my _toggle.js.erb file and am sure I have named it right, and the contents are valid (although that's not important because it is never completed).

Just doing a regular GET without any fancy ajax on the js file returns the exact same error, so chances are good that the problem lies somewhere along the Rails rendering chain.

I won't include the rest of the method as is is quite verbose and I am confident that it does not factor into this particular problem, but if anybody thinks it is important, I'll post it.

Thanks!

EDIT:
Fixed the problem. It was my own stupid fault, I named the view like a partial, with an underscore before it. Removed, and the whole thing works perfectly. Idiot, idiot, idiot.


问:
Android Floating Action Button Semi Transparent Background Color
I want to use FAB with semi transparent background color.
But I am getting a FAB with two different colors. What's the problem?

```<code><android.support.design.widget.FloatingActionButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|left"
    android:fadingEdgeLength="5dp"
    app:borderWidth="0dp"
    app:elevation="4dp"
    app:backgroundTint="#99f03456"
    app:fabSize="normal"/>
</code>```

And without any drawable.

答:
Unless the elevation is necessary, you can remove the "inner circle" by setting it to 0:

```<code>app:elevation="0dp"
</code>```

As @David notes in the comments, you may want to try 1dp if 0 does not work.

Body:
I want to use FAB with semi transparent background color.
But I am getting a FAB with two different colors. What's the problem?

<android.support.design.widget.FloatingActionButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|left"
    android:fadingEdgeLength="5dp"
    app:borderWidth="0dp"
    app:elevation="4dp"
    app:backgroundTint="#99f03456"
    app:fabSize="normal"/>

And without any drawable.

Body:
Unless the elevation is necessary, you can remove the "inner circle" by setting it to 0:

app:elevation="0dp"

As @David notes in the comments, you may want to try 1dp if 0 does not work.

ContentLicense: CC BY-SA 4.0


问:
"[VKDefault] Tile in current unloaded state" iOS 11 map is not working
I just create project and in my first viewController added MKMapView but what I'm seeing! Map is totally stuck means not able to scroll/zoom in-out and etc.

Is it Bug or doing any mistake to add Map in Xcode 9? Is there any additional setup required for latest system?

I did not write any code so here not adding my code.

答:
MKMapView is very sluggish in XCode 9... this is a known problem on Apple's side. If you want to see faster performance, use your mobile device rather than the simulator for testing. Be advised that XCode 9 doesn't work with iOS 11.1.2 at this point. Found that out the hard way.

At this point, my app doesn't require scrolling, but I am having to press and hold for about 5 - 7 seconds to get my pin to appear.

Fun times.


问:
How to exit from an sql script in oracle
We have a requirement to call the pl/sql stored procedure from an sql script. we are reading the out variable(v_return_code) from a stored procedure and we need to exit from sql/script based on out variable(v_return_code). But in our sql script we are not using any PL/SQL(procedural language).How can we exit from sql script using sql statments only ?.

Sql script code snippet:

```<code>VARIABLE  v_return_code number;
EXECUTE splits(:v_return_code);
</code>```

答:
In your SQL*Plus script add an exit command:

```<code>VARIABLE  v_return_code number;
EXECUTE splits(:v_return_code);
exit :v_return_code
</code>```

Then you can access the return code from your calling environment, for example in unix you could

```<code>echo $?
</code>```

while in windows you could

```<code>echo %errorlevel%
</code>```

to see the value returned.

Body:
We have a requirement to call the pl/sql stored procedure from an sql script. we are reading the out variable(v_return_code) from a stored procedure and we need to exit from sql/script based on out variable(v_return_code). But in our sql script we are not using any PL/SQL(procedural language).How can we exit from sql script using sql statments only ?.

Sql script code snippet:

VARIABLE  v_return_code number;
EXECUTE splits(:v_return_code);

Body:
In your SQL*Plus script add an exit command:

VARIABLE  v_return_code number;
EXECUTE splits(:v_return_code);
exit :v_return_code

Then you can access the return code from your calling environment, for example in unix you could

echo $?

while in windows you could

echo %errorlevel%

to see the value returned.


问:
VBA - Excel Forces Restart
I am having a major issue with my code that is supposed to reset the worksheets, not shut down the entire workbook and force a restart.  This has not been an issue, and has only occured since I added the last bit of code starting at On Error Resume Next.

```<code>Sub Reset()

    Application.ScreenUpdating = False

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "Set Up" Or ws.Name = "Report" Then
            Else:
                Application.DisplayAlerts = False
                ws.Delete
        End If
    Next

    Worksheets("Report").Cells.ClearContents

    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Charts.Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End Sub
</code>```

Thanks in advance

答:
If you have chart sheets, then you should use the following code:</p>

```<code>Sub DeleteChartSheets()

    Dim ch As Chart

    For Each ch In ThisWorkbook.Charts
        ch.Delete
    Next

End Sub
</code>```

Title: VBA - Excel Forces Restart

Body:
I am having a major issue with my code that is supposed to reset the worksheets, not shut down the entire workbook and force a restart.  This has not been an issue, and has only occured since I added the last bit of code starting at On Error Resume Next.

Sub Reset()

    Application.ScreenUpdating = False

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = "Set Up" Or ws.Name = "Report" Then
            Else:
                Application.DisplayAlerts = False
                ws.Delete
        End If
    Next

    Worksheets("Report").Cells.ClearContents

    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Charts.Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End Sub

Thanks in advance

Body:
If you have chart sheets, then you should use the following code:

Sub DeleteChartSheets()

    Dim ch As Chart

    For Each ch In ThisWorkbook.Charts
        ch.Delete
    Next

End Sub


问:
Get variable from JSON output with special character in object name
I cannot find how to get the results from this JSON post in PHP.

```<code>    stdClass Object
(
    [api_job_id] => 398438bf-c0a5-46fc-8774-70d2425e1ce7
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [type] => MESSAGE
                    [message_id] => 15125005817130024103
                    [to] => xxx
                    [error_code] => 0
                    [#meta] => stdClass Object
                        (
                            [error] => stdClass Object
                                (
                                    [error_desc] => NO_USER
                                    [error_code] => 9
                                )

                        )

                )

        )

)
</code>```

as you can see the meta has a # icon before it.

I can read all data to vars instead of the data in the #meta

I tried many ways like:
$result = $arrayResponse['#meta']['error']['error_desc'];
it's not working in PHP because of the # icon.

Any idea how I can get the values from these errors in #meta?

答:
To refer to an object attribute with a name that doesn't make a valid variable, you can use braces:

```<code>$foo = json_decode($string);
var_dump($foo->{'#meta'});
</code>```

Or pass a truthy value to json_decode() as the second argument, and you'll get back an array instead of an object:

```<code>$foo = json_decode($string, true);
var_dump($foo['#meta']);
</code>```

Body:
I cannot find how to get the results from this JSON post in PHP.

    stdClass Object
(
    [api_job_id] => 398438bf-c0a5-46fc-8774-70d2425e1ce7
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [type] => MESSAGE
                    [message_id] => 15125005817130024103
                    [to] => xxx
                    [error_code] => 0
                    [#meta] => stdClass Object
                        (
                            [error] => stdClass Object
                                (
                                    [error_desc] => NO_USER
                                    [error_code] => 9
                                )

                        )

                )

        )

)

as you can see the meta has a # icon before it.

I can read all data to vars instead of the data in the #meta

I tried many ways like:
$result = $arrayResponse['#meta']['error']['error_desc'];
it's not working in PHP because of the # icon.

Any idea how I can get the values from these errors in #meta?

Body:
To refer to an object attribute with a name that doesn't make a valid variable, you can use braces:

$foo = json_decode($string);
var_dump($foo->{'#meta'});

Or pass a truthy value to json_decode() as the second argument, and you'll get back an array instead of an object:

$foo = json_decode($string, true);
var_dump($foo['#meta']);


问:
Firestore: How to set DocumentListenOptions in JavaScript?
While using Firebase-Firestore database, I need to set some configuration parameters accesible via DocumentListenOptions using the Web javascript sdk.
I've found many examples of this in java and other languages, but it seems there is no documentation for JavaScript.

Am I missing something?

Thanks!

答:
The DocumentListenOptions you're pointing to is a part of the Android API.

In the web API there's no special type for this: just pass { includeMetadataChanges: true } as options to the onSnapshot method, as described here:

https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#onSnapshot

Cheers,
-Gil


问:
dplyr differences between pairs in nested groups
I'd like to use dplyr to calculate differences in value between people nested in pair by session.

```<code>dat <- data.frame(person=c(rep(1, 10),
                           rep(2, 10),
                           rep(3, 10),
                           rep(4, 10),
                           rep(5, 10),
                           rep(6, 10),
                           rep(7, 10),
                           rep(8, 10)),
                  pair=c(rep(1, 20),
                         rep(2, 20),
                         rep(3, 20),
                         rep(4, 20)),
                  condition=c(rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10)),
                  session=rep(seq(from=1, to=10, by=1), 8),
                  value=c(0, 2, 4, 8, 16, 16, 18, 20, 20, 20,
                          0, 1, 1, 2, 4, 5, 8, 12, 15, 15,
                          0, 2, 8, 10, 15, 16, 18, 20, 20, 20,
                          0, 4, 4, 6, 6, 8, 10, 12, 12, 18,
                          0, 6, 8, 10, 16, 16, 18, 20, 20, 20,
                          0, 2, 2, 3, 4, 8, 8, 8, 10, 12,
                          0, 10, 12, 16, 18, 18, 18, 20, 20, 20,
                          0, 2, 2, 8, 10, 10, 11, 12, 15, 20)
                  )
</code>```

For instance, person 1 and 2 make a pair (pair==1):

person==1 & session==2: 2

person==2 & session==2: 1

Difference (NEW-OLD) is 2-1=1.

Here's what I have tried so far. I think I need to group_by() first and then summarise(), but I have not cracked this nut.

```<code>dat %>%
    mutate(session = factor(session)) %>%
    group_by(condition, pair, session) %>%
    summarise(pairDiff = value-first(value))
</code>```

Desired output:

答:
Your output can be obtained by:

```<code>dat %>% group_by(pair,session) %>% arrange(condition) %>% summarise(diff = -diff(value))
Source: local data frame [40 x 3]
Groups: pair [?]

# A tibble: 40 x 3
    pair session  diff
   <dbl>   <dbl> <dbl>
 1     1       1     0
 2     1       2     1
 3     1       3     3
 4     1       4     6
 5     1       5    12
 6     1       6    11
 7     1       7    10
 8     1       8     8
 9     1       9     5
10     1      10     5
# ... with 30 more rows
</code>```

The arrange ensures that NEW and OLD are in the correct positions, but the solution does depend on there being exactly 2 values for each combination of pair and session.

Body:
I'd like to use dplyr to calculate differences in value between people nested in pair by session.

dat <- data.frame(person=c(rep(1, 10),
                           rep(2, 10),
                           rep(3, 10),
                           rep(4, 10),
                           rep(5, 10),
                           rep(6, 10),
                           rep(7, 10),
                           rep(8, 10)),
                  pair=c(rep(1, 20),
                         rep(2, 20),
                         rep(3, 20),
                         rep(4, 20)),
                  condition=c(rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10),
                              rep("NEW", 10),
                              rep("OLD", 10)),
                  session=rep(seq(from=1, to=10, by=1), 8),
                  value=c(0, 2, 4, 8, 16, 16, 18, 20, 20, 20,
                          0, 1, 1, 2, 4, 5, 8, 12, 15, 15,
                          0, 2, 8, 10, 15, 16, 18, 20, 20, 20,
                          0, 4, 4, 6, 6, 8, 10, 12, 12, 18,
                          0, 6, 8, 10, 16, 16, 18, 20, 20, 20,
                          0, 2, 2, 3, 4, 8, 8, 8, 10, 12,
                          0, 10, 12, 16, 18, 18, 18, 20, 20, 20,
                          0, 2, 2, 8, 10, 10, 11, 12, 15, 20)
                  )

For instance, person 1 and 2 make a pair (pair==1):

person==1 & session==2: 2

person==2 & session==2: 1

Difference (NEW-OLD) is 2-1=1.

Here's what I have tried so far. I think I need to group_by() first and then summarise(), but I have not cracked this nut.

dat %>%
    mutate(session = factor(session)) %>%
    group_by(condition, pair, session) %>%
    summarise(pairDiff = value-first(value))

Desired output:

Body:
Your output can be obtained by:

dat %>% group_by(pair,session) %>% arrange(condition) %>% summarise(diff = -diff(value))
Source: local data frame [40 x 3]
Groups: pair [?]

# A tibble: 40 x 3
    pair session  diff
   <dbl>   <dbl> <dbl>
 1     1       1     0
 2     1       2     1
 3     1       3     3
 4     1       4     6
 5     1       5    12
 6     1       6    11
 7     1       7    10
 8     1       8     8
 9     1       9     5
10     1      10     5
# ... with 30 more rows

The arrange ensures that NEW and OLD are in the correct positions, but the solution does depend on there being exactly 2 values for each combination of pair and session.


问:
How do we check if a browser's auto-update is enabled through javascript
I want to check form the javascript if a browser's auto-update is enabled.

The reason I want this is that our software supports only a set of Browser versions and we want to alert them if auto-update is on.

Is there any way we can do this?

Abhi

答:
Not sure why you require a set version, but one thing to do is check if the browser supports a specific method (One that your app requires).

If not, tell them to update their browser. This example test if the user has WebSockets:

if (window.WebSocket) {
  alert("BROWSER SUPPORTED");
} else {
  alert("BROWSER NOT SUPPORTED");
}```


问:
How to add aria-hidden property to span on focus change?
I have to change the span element aria-hidden value to "true" on focus change event. How can I do that?

Here is my span element declaration-

```<code><span id="jawshide">#someText</span>
</code>```

and here is javascript part-

```<code>document.getElementById('jawshide').innerHTML= "aria-hidden='true'";
</code>```

What is the correct way to add this property?

答:
You can do this using setAttribute

```<code>document.getElementById('jawshide').setAttribute('aria-hidden', 'true');
</code>```

Body:
I have to change the span element aria-hidden value to "true" on focus change event. How can I do that?

Here is my span element declaration-

#someText

and here is javascript part-

document.getElementById('jawshide').innerHTML= "aria-hidden='true'";

What is the correct way to add this property?

Body:
You can do this using setAttribute

document.getElementById('jawshide').setAttribute('aria-hidden', 'true');


答:
Using jQuery: </p>

```<code>('#jawshide').attr('aria-hidden', 'true');
</code>```

Title: How to add aria-hidden property to span on focus change?

Body:
Using jQuery:

('#jawshide').attr('aria-hidden', 'true');


问:
Python: change global variable from within another file
In my main class I use a global variable ADDRESS that is defined in another file called config.py.
I want to change the value of ADDRESS from within my main class, by calling a function in config.py.

In my main class I have:

```<code>from config import ADDRESS, change_address
change_address("192.168.10.100")
print("new address " + ADDRESS)
</code>```

In my config file I have the following:

```<code>ADDRESS = "0.0.0.0"

def change_address(address):
    global ADDRESS
    ADDRESS = address
    print("changed address to: " + ADDRESS)
</code>```

The print statement in my config file correctly prints the new address of 192.168.10.100.
However, the print statement in my main class prints 0.0.0.0.
What am I missing here?

答:
I would recommend that you try not to change the global state in a module. Instead, I would re-write the code such that ADDRESS in config.py doesn't change. If the configuration for your application can change from invocation to invocation I would change config to be something like:

```<code>ADDRESS = '0.0.0.0'

def get_default_config():
    return {'address': ADDRESS, 'some_other_config_value': 'foo'}
</code>```

Then in main I would do:

```<code>app_config = config.get_default_config()
app_config = "192.168.10.100"
print("new address " + app_config['address']
</code>```

As a general rule it isn't a good idea to change the value of variables/constants in other modules.

NOTE: You could also create a config class as well, so that you could access configuration values like config.address.

I recommend that you read the stackexchange post Why is Global State so Evil?

Body:
In my main class I use a global variable ADDRESS that is defined in another file called config.py.
I want to change the value of ADDRESS from within my main class, by calling a function in config.py.

In my main class I have:

from config import ADDRESS, change_address
change_address("192.168.10.100")
print("new address " + ADDRESS)

In my config file I have the following:

ADDRESS = "0.0.0.0"

def change_address(address):
    global ADDRESS
    ADDRESS = address
    print("changed address to: " + ADDRESS)

The print statement in my config file correctly prints the new address of 192.168.10.100.
However, the print statement in my main class prints 0.0.0.0.
What am I missing here?

Body:
I would recommend that you try not to change the global state in a module. Instead, I would re-write the code such that ADDRESS in config.py doesn't change. If the configuration for your application can change from invocation to invocation I would change config to be something like:

ADDRESS = '0.0.0.0'

def get_default_config():
    return {'address': ADDRESS, 'some_other_config_value': 'foo'}

Then in main I would do:

app_config = config.get_default_config()
app_config = "192.168.10.100"
print("new address " + app_config['address']

As a general rule it isn't a good idea to change the value of variables/constants in other modules.

NOTE: You could also create a config class as well, so that you could access configuration values like config.address.

I recommend that you read the stackexchange post Why is Global State so Evil?


问:
Images take time and get loaded after loading text contents on my website
I want my images to be loaded fast as HTML and CSS get loaded.
As of now HTML and CSS don't take time but loading images (all are in .svg format and small) take more than 2 seconds after other content.

Is there a way to load them faster?

I found answers regarding fast-loading and followed as well, which are:

-compress images

-Minify HTML and JS files

But my issue is still unresolved.

答:
It is actually considered a good practice to load images after all contents of a webpage. You could try with the following-

Clear the cache or try in Incognito and different browsers and devices to check if the issue pertains.

Store the images for faster loading times in AWS or similar services.


问:
In Excel, how can I plot data based on user inputting number of rows?
Prefer not to use VBA if I can help it. I have 1000 rows x 2 columns of data. In cell B2, I (or user) would enter 600 for example and would like the scatter plot that already exists in the worksheet to plot just the first 600 rows x 2 columns. Change B2 to 200 and plot just those first 200 rows, etc... Thanks for any assistance...</p>

答:
I learnt this off Mr. Peltier. You can look up dynamic charts.

But basically this will give you the first n rows. For this n is in D2 as I used A & B as my chart range.

Define two named ranges.

chtrng:

```<code>=OFFSET(Sheet1!$A$1,1,0,MIN(Sheet1!$D$2,COUNTA(Sheet1!$A:$A)-1),1)
</code>```

chtvals:

```<code>=OFFSET(chtrng,0,1)
</code>```

Then pick a cell and insert scatter chart.
Add a series.

xvalues =

```<code>=Sheet1!chtrng
</code>```

yvalues=

```<code>=Sheet1!chtvals
</code>```

Now it should change rows plotted when you change D2.

Body:
I learnt this off Mr. Peltier. You can look up dynamic charts.

But basically this will give you the first n rows. For this n is in D2 as I used A & B as my chart range.

Define two named ranges.

chtrng:

=OFFSET(Sheet1!$A$1,1,0,MIN(Sheet1!$D$2,COUNTA(Sheet1!$A:$A)-1),1)

chtvals:

=OFFSET(chtrng,0,1)

Then pick a cell and insert scatter chart.
Add a series.

xvalues =

=Sheet1!chtrng

yvalues=

=Sheet1!chtvals

Now it should change rows plotted when you change D2.


问:
JS to generate HTML table, but one first row cell won't get value, comes up as 'undefined'
So I have a function that's below (I broke the lines after innerHTML so it's easier to see) and the forloop generates a table, with id's for each tags. I'm wanting to calculate the total of each item(quantity * price).

The function works fine after the first row, but first row's total returns an undefined value, which i'm assuming is because the variables are declared later on.

How could i possible solve this issue, and work out the total?

The relevant JS:

```<code>function load() {
  for (var i = 0; i <= localStorage.length - 1; i++) {
    var key = localStorage.key(i);
    document.getElementById(key).setAttribute('checked', 'checked');
    document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'></td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
    var name = $('#name-' + i).val();
    var id = $('#' + name);
    var price = id.data('price');
    var quantity = document.getElementById('input-' + i);
    var quantityValue = quantity.value;
    var total = price * quantityValue;
    document.getElementById('price-' + i).innerHTML = '£' + price;
    var getQuantity = $('#input-' + i).val();
    var totalPrice = price * getQuantity;
  }
}
</code>```

Local storage's data:

key: photo2, value: checked

key: photo6, value: checked

key: photo7, value: checked

答:
You are updating total after appending dom. you need to calculate everything before updating it to DOM.</p>

```<code>function load() {
  for (var i = 0; i <= localStorage.length - 1; i++) {
    var key = localStorage.key(i);
    var id = $('#' + key);
    var price = id.data('price'); // assuming this will be there in dom
    var quantityValue = 1; // adding this 1 in table
    var total = price * quantityValue;
    document.getElementById('price-' + i).innerHTML = '£' + price;
    var getQuantity = 1;
    var totalPrice = price * getQuantity;
    document.getElementById(key).setAttribute('checked', 'checked');
    document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'>£" + price  + "</td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
  }
}
</code>```

Body:
So I have a function that's below (I broke the lines after innerHTML so it's easier to see) and the forloop generates a table, with id's for each tags. I'm wanting to calculate the total of each item(quantity * price).

The function works fine after the first row, but first row's total returns an undefined value, which i'm assuming is because the variables are declared later on.

How could i possible solve this issue, and work out the total?

The relevant JS:

function load() {
  for (var i = 0; i <= localStorage.length - 1; i++) {
    var key = localStorage.key(i);
    document.getElementById(key).setAttribute('checked', 'checked');
    document.getElementById("content").innerHTML += "

<input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled />

<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button>
	" + totalPrice + "
<button class='delete' id='delete-" + i + "'>Delete</button>
";
    var name = $('#name-' + i).val();
    var id = $('#' + name);
    var price = id.data('price');
    var quantity = document.getElementById('input-' + i);
    var quantityValue = quantity.value;
    var total = price * quantityValue;
    document.getElementById('price-' + i).innerHTML = '£' + price;
    var getQuantity = $('#input-' + i).val();
    var totalPrice = price * getQuantity;
  }
}

Local storage's data:

key: photo2, value: checked

key: photo6, value: checked

key: photo7, value: checked

Body:
You are updating total after appending dom. you need to calculate everything before updating it to DOM.

function load() {
  for (var i = 0; i <= localStorage.length - 1; i++) {
    var key = localStorage.key(i);
    var id = $('#' + key);
    var price = id.data('price'); // assuming this will be there in dom
    var quantityValue = 1; // adding this 1 in table
    var total = price * quantityValue;
    document.getElementById('price-' + i).innerHTML = '£' + price;
    var getQuantity = 1;
    var totalPrice = price * getQuantity;
    document.getElementById(key).setAttribute('checked', 'checked');
    document.getElementById("content").innerHTML += "<tr>
<td><input type='text' class='name' id='name-" + i + "' value='" + key + "'disabled /></td>
<td id='quantity-" + i + "'>
<input type='text' class='quantity' id='input-" + i + "' value='1' disabled/>
<button class='update' id='increment-" + i + "' onclick='incrementQuantity(this);'>+</button><button class='update' id='decrement-" + i + "' onclick='decrementQuantity(this);'>-</button></td>
<td id='price-" + i + "'>£" + price  + "</td><td>" + totalPrice + "</td>
<td><button class='delete' id='delete-" + i + "'>Delete</button></td></tr>";
  }
}


问:
Haskell: I don't know how to match types
So, I have this Haskell question to resolve:

Define a mapIO function that receives a function f and an input and output action a and results in an input and output action that, when executed, performs the given action a and returns the application of f to the return of a.

Here's my code:

```<code>mapIO f a = do b <- a
               return f(b);
</code>```

It compiles but it doesn't work. When I try to do the same as the following execution example, it doesn't work. Please, can someone help me?

```<code>Prelude Data.Char> mapIO even readLn
75
False
</code>```

答:
In many other languages, g(x) is the syntax for applying function g to argument x. In Haskell, juxtaposition suffices, so that g x applies g to x. By coincidence, this means g(x) is also valid syntax that applies g to the value (x), which is the same as x, so to a beginner it may seem that g(x) is the correct syntax for function application. But it ain't, and that confusion has bitten you here.

When you write return f(b), you probably assume this means to use the special syntax return and the thing to return should be the function application f(b). However, return is itself a function in Haskell. So what it actually means is to apply return to the function f, then apply the result to the term (b). (Function application is "left-associative" in that sense.)

Luckily the fix for function application associativity problems, as with other associativity problems, is to use parentheses. So:

```<code>return (f(b))
</code>```

Or, without the coincidentally correct extra parentheses:

```<code>return (f b)
</code>```

This leaves only the question of why it "worked" (in the sense of compiled and type-checked) in return f(b) form. This is a bit of an advanced topic; but it turns out that functions also form a Monad with return = const, and so return f(b) actually meant const f(b), which threw away the (b) term. (Aside: in addition to being allowed to use the function instance of Monad, we also must be using the function instance of Monad here. Since we are applying return f to (b), the type of return f must be a function.) So your definition was the same as:

```<code>mapIO' f a = do b <- a
                f
</code>```

That is: first do a, throw away its result, then do f as if it were another input/output action. If you check the type inferred for mapIO you will see it matches this intuition:

```<code>mapIO :: Monad m => m b -> m t -> m b
</code>```

Whoops!

Body:
So, I have this Haskell question to resolve:

Define a mapIO function that receives a function f and an input and output action a and results in an input and output action that, when executed, performs the given action a and returns the application of f to the return of a.

Here's my code:

mapIO f a = do b <- a
               return f(b);

It compiles but it doesn't work. When I try to do the same as the following execution example, it doesn't work. Please, can someone help me?

Prelude Data.Char> mapIO even readLn
75
False

Body:
In many other languages, g(x) is the syntax for applying function g to argument x. In Haskell, juxtaposition suffices, so that g x applies g to x. By coincidence, this means g(x) is also valid syntax that applies g to the value (x), which is the same as x, so to a beginner it may seem that g(x) is the correct syntax for function application. But it ain't, and that confusion has bitten you here.

When you write return f(b), you probably assume this means to use the special syntax return and the thing to return should be the function application f(b). However, return is itself a function in Haskell. So what it actually means is to apply return to the function f, then apply the result to the term (b). (Function application is "left-associative" in that sense.)

Luckily the fix for function application associativity problems, as with other associativity problems, is to use parentheses. So:

return (f(b))

Or, without the coincidentally correct extra parentheses:

return (f b)

This leaves only the question of why it "worked" (in the sense of compiled and type-checked) in return f(b) form. This is a bit of an advanced topic; but it turns out that functions also form a Monad with return = const, and so return f(b) actually meant const f(b), which threw away the (b) term. (Aside: in addition to being allowed to use the function instance of Monad, we also must be using the function instance of Monad here. Since we are applying return f to (b), the type of return f must be a function.) So your definition was the same as:

mapIO' f a = do b <- a
                f

That is: first do a, throw away its result, then do f as if it were another input/output action. If you check the type inferred for mapIO you will see it matches this intuition:

mapIO :: Monad m => m b -> m t -> m b

Whoops!


问:
Get only JSON string as output without any html
I am developing a webiste in ASP.NET. On one of the pages page named menu.aspx, with the help of a certain login, I am getting the output in this format

foo({"1":"Jeff","2":"Mik","5":"Tom"});

I am using this code to get the output on the JSON form.

```<code>outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";
            Response.Clear();
            Response.Write(outputText);
            Response.ContentType = "application/json";
</code>```

However, I must get the output only in simple JSON on the page without any HTML.

For eg: Here's the screenshot showing the source of the output page. http://i.stack.imgur.com/faUtY.jpg

Notice that it has only the JSON string as the output.

And here's the screenshot showing the output page source (with HTML). http://i.stack.imgur.com/gIxzR.jpg  .This HTML is what I have to remove. How can do I do this?
The full code of menu.aspx.cs is putup here. http://pastebin.com/M14Srrgf

答: It sounds like you might be interested in an ASHX Handler. Think of it as code-behind without the view. Here is a good explanation.</p>

Body:
I am developing a webiste in ASP.NET. On one of the pages page named menu.aspx, with the help of a certain login, I am getting the output in this format

foo({"1":"Jeff","2":"Mik","5":"Tom"});

I am using this code to get the output on the JSON form.

outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";
            Response.Clear();
            Response.Write(outputText);
            Response.ContentType = "application/json";

However, I must get the output only in simple JSON on the page without any HTML.

For eg: Here's the screenshot showing the source of the output page. http://i.stack.imgur.com/faUtY.jpg

Notice that it has only the JSON string as the output.

And here's the screenshot showing the output page source (with HTML). http://i.stack.imgur.com/gIxzR.jpg  .This HTML is what I have to remove. How can do I do this?
The full code of menu.aspx.cs is putup here. http://pastebin.com/M14Srrgf


问:
How to get key from a Firebase list through Angularfire 5.0
I was trying to upgrade my Angularfire 4 code to its latest version. There are some breaking changes as it no longer emits $key. The official documentation states to manage it by nesting map operators that I am struggling hard to understand -

```<code>constructor(afDb: AngularFireDatabase) {
  afDb.list('items').snapshotChanges().map(actions => {
    return actions.map(action => ({ key: action.key, ...action.payload.val() }));
  }).subscribe(items => {
    return items.map(item => item.key);
  });
}
</code>```

How is this nested map working? Why can't I perform the same operation in single map operator?

答:
You have to map the list to a list containing this key value.
I just played around a bit with it and this is my firebase 4 vs firebase 5 code

Old code :

```<code>.map(gamesList => {
   console.log(gamesList.$key)
})
</code>```

New code :

```<code>.map(gamesList =>
{
     return gamesList.map(action => ({ key: action.key, ...action.payload.val()
})
.map(gamesKey => {
    console.log(gamesKey.key)
})
</code>```

Body:
I was trying to upgrade my Angularfire 4 code to its latest version. There are some breaking changes as it no longer emits $key. The official documentation states to manage it by nesting map operators that I am struggling hard to understand -

constructor(afDb: AngularFireDatabase) {
  afDb.list('items').snapshotChanges().map(actions => {
    return actions.map(action => ({ key: action.key, ...action.payload.val() }));
  }).subscribe(items => {
    return items.map(item => item.key);
  });
}

How is this nested map working? Why can't I perform the same operation in single map operator?

Body:
You have to map the list to a list containing this key value.
I just played around a bit with it and this is my firebase 4 vs firebase 5 code

Old code :

.map(gamesList => {
   console.log(gamesList.$key)
})

New code :

.map(gamesList =>
{
     return gamesList.map(action => ({ key: action.key, ...action.payload.val()
})
.map(gamesKey => {
    console.log(gamesKey.key)
})


问:
django REST framework nested serializer and POST nested JSON with files
How do I send a POST request with nested data including files (images) to django REST nested serializers?

Given this JS object:

```<code>bookData: {
    title: 'Anne of Green Gables',
    coverImage: File(123456),
    pages: 123,
    author: {
        name: 'Lucy Maud Montgomery',
        born: 1874,
        profilepicture_set: [
            {file: File(234567), description: 'Young L. M. Montgomery'},
            {file: File(234568), description: 'Old L. M. Montgomery}
        ],
        quote_set: [
            {text: "I'm so glad I live in a world where there are Octobers."},
            {text: "True friends are always together in spirit."},
        ]
    },

}
</code>```

I want to send a POST request to my django REST API (I use VueJS on frontend, but this does not really matter).

```<code># views.py
class CreateBookView(generics.CreateAPIView):
    serializer_class = CreateBookSerializer
    queryset = Book.objects.all()

# serializers.py
class CreateBookSerializer(serializers.ModelSerializer):
    author = CreateAuthorSerializer()

    class Meta:
        model = Book
        fields = ('title', 'pages', 'author')

    @transaction.atomic
    def create(self, validated_data):
        author_data = validated_data.pop('author')
        uploader = self.context['request'].user
        book = Book.objects.create(uploader=uploader, **validated_data)

        Author.objects.create(book=book, **author_data)

        return book

# models.py
class AuthorManager(models.Manager):

    def create(self, **author_data):
        quotes_data = author_data.pop('quote_set')
        photos_data = author_data.pop('profilepicture_set')

        author = Author(**author_data)
        author.save()

        for quote_data in quotes_data:
            Quote.objects.create(author=author, **quote_data)

        for photo_data in photos_data :
            ProfilePicture.objects.create(author=author, **photo_data)

        return author

## Skipping the CreateAuthorSerializer, Quote and ProfilePicture Managers as they are analogous.
## Assume one Author can only write one Book (OneToOneField). No need to look the name up for existing Authors.
</code>```

EDIT

I wanted to add some info on how I send the data in the frontend in VueJS.

```<code>sendData(){
    var fd = new FormData()
    var bookData = {
        title: this.$store.getters.title, # 'Anne of Green Gables"
        coverImage: this.$store.getters.coverImage, # File(somesize)
        pages: this.$store.getters.pages, # 123
        author: this.$store.getters.author, # nested object
        ...
    }
    fd = objectToFormData(bookData, fd) # external function, see below
    this.$http.post('api/endpoint/create/', fd, headers: {
        'Content-Type': 'multipart/form-data',
        'X-CSRFToken': Cookies.get('csrftoken'),
        }
    }).then(...)
}
</code>```

The sendData() is invoked on button click.
The objectToFormData is an external lib from npm (click) that transforms the nested object into flat form.

The problem with this solution (as well as @Saji Xavier's solution) is that the request.data contains an ugly QueryDict which is far from the original bookData object structure and is not accepted by the REST serializer (namely, the author field is missing - which is true, the object has been flattened).

```<code><QueryDict: {
'title': ['Anne of Green Gables'],
'coverImage':[InMemoryUploadedFile: cover.jpg (image/jpeg)],
'pages': ['123'],
'name': ['Lucy Maud Montgomery'],
'born': ['1874'],
'profilepicture_set[][description]': ['Young L. M. Montgomery', 'Old L. M. Montgomery'],
'profilepicture_set[][file]': [
    InMemoryUploadedFile: young.jpg (image/jpeg),
    InMemoryUploadedFile: old.jpg (image/jpeg)
    ],
'quote_set[][text]': [
    "I'm so glad I live in a world where there are Octobers.",
    "True friends are always together in spirit."
    ]
}>
</code>```

How do I deal with it now? It seems sooooo ugly. What I can think of is to overwrite the create() function.

```<code>class CreateBookView(generics.CreateAPIView):
    (...)
    def create(self, request, *args, **kwargs):
        book_data = {}
        book_data['title'] = request.data['title']
        book_data['pages'] = request.data['pages']
        book_data['cover_image'] = request.data['coverImage']
        book_data['author'] = {}
        book_data['author']['name'] = request.data['name']
        book_data['author']['born'] = request.data['born']
        (...)
        serializer = self.get_serializer(data=book_data)
        (...)
</code>```

This is extremely ugly solution, ineffective for models with multitude of fields and several levels of nestedness (this book/author is just a toy example).

How should I handle it? Do i change the way of POSTing (to get a nice request.data format) or do I handle this ugly one?

答:
According DRF documentation,

Most parsers, such as e.g. JSON don't support file uploads. Django's
  regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.

One option is to use Javascript FormData API to send multipart data (works with VueJS/AngularJS)

```<code>var fd = new FormData();
fd.append('title', 'Anne of Green Gables')
fd.append('author_name', 'Lucy Maud Montgomery')
fd.append('author_profilepicture_set', files[])
$http.post('url', fd, {
   headers: {
       'Content-Type': 'multipart/form-data'
   }
});
</code>```

Body:
How do I send a POST request with nested data including files (images) to django REST nested serializers?

Given this JS object:

bookData: {
    title: 'Anne of Green Gables',
    coverImage: File(123456),
    pages: 123,
    author: {
        name: 'Lucy Maud Montgomery',
        born: 1874,
        profilepicture_set: [
            {file: File(234567), description: 'Young L. M. Montgomery'},
            {file: File(234568), description: 'Old L. M. Montgomery}
        ],
        quote_set: [
            {text: "I'm so glad I live in a world where there are Octobers."},
            {text: "True friends are always together in spirit."},
        ]
    },

}

I want to send a POST request to my django REST API (I use VueJS on frontend, but this does not really matter).

# views.py
class CreateBookView(generics.CreateAPIView):
    serializer_class = CreateBookSerializer
    queryset = Book.objects.all()

# serializers.py
class CreateBookSerializer(serializers.ModelSerializer):
    author = CreateAuthorSerializer()

    class Meta:
        model = Book
        fields = ('title', 'pages', 'author')

    @transaction.atomic
    def create(self, validated_data):
        author_data = validated_data.pop('author')
        uploader = self.context['request'].user
        book = Book.objects.create(uploader=uploader, **validated_data)

        Author.objects.create(book=book, **author_data)

        return book

# models.py
class AuthorManager(models.Manager):

    def create(self, **author_data):
        quotes_data = author_data.pop('quote_set')
        photos_data = author_data.pop('profilepicture_set')

        author = Author(**author_data)
        author.save()

        for quote_data in quotes_data:
            Quote.objects.create(author=author, **quote_data)

        for photo_data in photos_data :
            ProfilePicture.objects.create(author=author, **photo_data)

        return author

## Skipping the CreateAuthorSerializer, Quote and ProfilePicture Managers as they are analogous.
## Assume one Author can only write one Book (OneToOneField). No need to look the name up for existing Authors.

EDIT

I wanted to add some info on how I send the data in the frontend in VueJS.

sendData(){
    var fd = new FormData()
    var bookData = {
        title: this.$store.getters.title, # 'Anne of Green Gables"
        coverImage: this.$store.getters.coverImage, # File(somesize)
        pages: this.$store.getters.pages, # 123
        author: this.$store.getters.author, # nested object
        ...
    }
    fd = objectToFormData(bookData, fd) # external function, see below
    this.$http.post('api/endpoint/create/', fd, headers: {
        'Content-Type': 'multipart/form-data',
        'X-CSRFToken': Cookies.get('csrftoken'),
        }
    }).then(...)
}

The sendData() is invoked on button click.
The objectToFormData is an external lib from npm (click) that transforms the nested object into flat form.

The problem with this solution (as well as @Saji Xavier's solution) is that the request.data contains an ugly QueryDict which is far from the original bookData object structure and is not accepted by the REST serializer (namely, the author field is missing - which is true, the object has been flattened).

<QueryDict: {
'title': ['Anne of Green Gables'],
'coverImage':[InMemoryUploadedFile: cover.jpg (image/jpeg)],
'pages': ['123'],
'name': ['Lucy Maud Montgomery'],
'born': ['1874'],
'profilepicture_set[][description]': ['Young L. M. Montgomery', 'Old L. M. Montgomery'],
'profilepicture_set[][file]': [
    InMemoryUploadedFile: young.jpg (image/jpeg),
    InMemoryUploadedFile: old.jpg (image/jpeg)
    ],
'quote_set[][text]': [
    "I'm so glad I live in a world where there are Octobers.",
    "True friends are always together in spirit."
    ]
}>

How do I deal with it now? It seems sooooo ugly. What I can think of is to overwrite the create() function.

class CreateBookView(generics.CreateAPIView):
    (...)
    def create(self, request, *args, **kwargs):
        book_data = {}
        book_data['title'] = request.data['title']
        book_data['pages'] = request.data['pages']
        book_data['cover_image'] = request.data['coverImage']
        book_data['author'] = {}
        book_data['author']['name'] = request.data['name']
        book_data['author']['born'] = request.data['born']
        (...)
        serializer = self.get_serializer(data=book_data)
        (...)

This is extremely ugly solution, ineffective for models with multitude of fields and several levels of nestedness (this book/author is just a toy example).

How should I handle it? Do i change the way of POSTing (to get a nice request.data format) or do I handle this ugly one?

Body:
According DRF documentation,

Most parsers, such as e.g. JSON don't support file uploads. Django's
  regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.

One option is to use Javascript FormData API to send multipart data (works with VueJS/AngularJS)

var fd = new FormData();
fd.append('title', 'Anne of Green Gables')
fd.append('author_name', 'Lucy Maud Montgomery')
fd.append('author_profilepicture_set', files[])
$http.post('url', fd, {
   headers: {
       'Content-Type': 'multipart/form-data'
   }
});


问:
Hiding the file path of a programming computer from hexdigit
I programmed a C# program for my friend and when he got it, he opened it with hexedit and was able to see the filepath to the debugging folder on my computer saved on the program. I gave him the exe that was compiled in the debugging folder. Is there anyway to hide the file structure of your programming computer from decompiling software in Visual Studios?

Note: I am not sure if this applies to files that are created when you "publish." I do not want the user to install a program, it is just a 1-file exe that does not need to be installed. I need an answer that does not involve publishing the project.

答:
Use the release configuration instead of debug, and set Debug Info to None in your project settings. See these articles for more information:

How to: Set Debug and Release Configurations

/debug (C# Compiler Options)


问:
Jenkins Test Result Trend Graph Numbers Don't Work
I'm having an issue with Jenkins Test Result Trend. The graph appears when it needs to, however the numbers are no longer there and replaced with a bunch of symbols.

I am running the latest Jenkins (2.84) with all plugins up to date.

I've tried disabling some plugins, triple checking junit plugin is fully up to date, and other various tasks.

答:
Hopefully you've already resolved this, but for others - turns out this is related to the availability of the dejavu-sans font on your host.

I encountered this when installing Jenkins on CentOS.  Resolved with:

```<code>yum install dejavu-sans-fonts.noarch dejavu-sans-mono-fonts.noarch
</code>```

See:
Jenkins - Load Statistics graph weird encoding

Body:
Hopefully you've already resolved this, but for others - turns out this is related to the availability of the dejavu-sans font on your host.

I encountered this when installing Jenkins on CentOS.  Resolved with:

yum install dejavu-sans-fonts.noarch dejavu-sans-mono-fonts.noarch

See:
Jenkins - Load Statistics graph weird encoding


问:
Autowire HashMap of @Component
I have an interface:

```<code>public interface EmailSender {

    void send(Locale locale, List<User> recipients, int ticketId);

}
</code>```

And few different implementations, and I want to autowire a HashMap of them, to have possibility to get concrete realization by class name, but when I write:

```<code>@Autowired
private HashMap<String, EmailSender> emailSenders;
</code>```

I get an exception:

No qualifying bean of type 'java.util.HashMap'

```<code>@Autowired
private List<EmailSender> emailSenders;
</code>```

It is interesting that whet I tried to change HashMap to List all worked fine, do you know how to correctly do that?

答:
create a class which will extends hashMap and Autowire that class. it will work fine for you.

In list you are actually autowiring EmailSender class unlike string in hashmap.

mark that class as component and autowire that. hopefully, it will work for you.
Cheers

Title: Autowire HashMap of @Component

Body:
I have an interface:

public interface EmailSender {

    void send(Locale locale, List<User> recipients, int ticketId);

}

And few different implementations, and I want to autowire a HashMap of them, to have possibility to get concrete realization by class name, but when I write:

@Autowired
private HashMap<String, EmailSender> emailSenders;

I get an exception:

No qualifying bean of type 'java.util.HashMap'

@Autowired
private List<EmailSender> emailSenders;

It is interesting that whet I tried to change HashMap to List all worked fine, do you know how to correctly do that?


问:
delete all folders and files within a linux directory except one folder and all contents inside that folder
I have a directory structure as :-

```<code>/usr/testing/member/
   ---> public--->folder1--->file1
           \----> file2
   ---> folder3:- contains files and folders
   ---> folder4:- contains files and folders
   ---> several files
</code>```

I want to keep the public folder and all its contents (further folders and files within it) but want to delete everything else under the directory /usr/testing/member/. But that also means member folder is not deleted.
Is there any shell script or command that can be used to achieve this exactly as i stated.

答:
I think below will do the work,

```<code>$ cd  /usr/testing/member/
$ rm -rf $(ls | grep -v "public")
</code>```

explanation:

we are passing everything inside /usr/testing/member/ but public to rm by making use of  -v(exclude) option of grep

Body:
I have a directory structure as :-

/usr/testing/member/
   ---> public--->folder1--->file1
           \----> file2
   ---> folder3:- contains files and folders
   ---> folder4:- contains files and folders
   ---> several files

I want to keep the public folder and all its contents (further folders and files within it) but want to delete everything else under the directory /usr/testing/member/. But that also means member folder is not deleted.
Is there any shell script or command that can be used to achieve this exactly as i stated.

Body:
I think below will do the work,

$ cd  /usr/testing/member/
$ rm -rf $(ls | grep -v "public")

explanation:

we are passing everything inside /usr/testing/member/ but public to rm by making use of  -v(exclude) option of grep


答:
I think, you should declare your bean in Configuration class.</p>

```<code>@Bean
public HashMap<String, EmailSender> emailSenders(List<EmailSender> emailSenders){
    HashMap<String, EmailSender> map = new HashMap<>();
    emailSenders.forEach(sender -> map.put(sender.getClass().getName(), sender));
    return map;
}
</code>```

Title: Autowire HashMap of @Component

Body:
I think, you should declare your bean in Configuration class.

@Bean
public HashMap<String, EmailSender> emailSenders(List<EmailSender> emailSenders){
    HashMap<String, EmailSender> map = new HashMap<>();
    emailSenders.forEach(sender -> map.put(sender.getClass().getName(), sender));
    return map;
}


问:
Counting rows with a condition
i work with a table "ships" like this:

```<code>shipid
container1
container2
</code>```

shipid and container1 are always filled, container2 is optional.

This is my query for now:

```<code>SELECT COUNT(container1) FROM table
</code>```

How can i achieve that this query counts the amount of the container2's too?!

It must be a joined query made of those both queries:

```<code>SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''
</code>```

Thanks for any hints!

答:
To add to the previous answers, you can do this to get the count in 1 result.

```<code> SELECT SUM(count) FROM
  (
   SELECT COUNT(container1) as count FROM table
   UNION ALL
   SELECT COUNT(container2) as count FROM table
  ) as a
</code>```

or you can do this:

```<code>SELECT COUNT(*) FROM
  (
   SELECT container1  FROM table
   UNION ALL
   SELECT container2  FROM table
  ) as a
</code>```

Title: Counting rows with a condition

Body:
i work with a table "ships" like this:

shipid
container1
container2

shipid and container1 are always filled, container2 is optional.

This is my query for now:

SELECT COUNT(container1) FROM table

How can i achieve that this query counts the amount of the container2's too?!

It must be a joined query made of those both queries:

SELECT COUNT(container1) FROM table
SELECT COUNT(container2) FROM table WHERE container2!=''

Thanks for any hints!

Body:
To add to the previous answers, you can do this to get the count in 1 result.

 SELECT SUM(count) FROM
  (
   SELECT COUNT(container1) as count FROM table
   UNION ALL
   SELECT COUNT(container2) as count FROM table
  ) as a

or you can do this:

SELECT COUNT(*) FROM
  (
   SELECT container1  FROM table
   UNION ALL
   SELECT container2  FROM table
  ) as a


问:
Design a language L such that neither L nor its complement has an infinite regular subset?
I'm having a class on automata theory, and right now we are learning the pumping lemma. There is an exercise question asking us to "Design a language L such that neither L nor its complement has an infinite regular subset?" But I don't understand the question. What is an infinite regular subset? How should I find a language that can meet this requirement?

Can anyone shed some light on this question?

Thanks!

答:
Well, an infinite regular subset of a language is a subset that is infinite and regular. Okay, that's probably not very helpful.

So "subset" is pretty clear.

A "regular subset" is one that is accepted by a deterministic finite state machine (there's actually an amazing theorem in the theory of languages that says this condition is equivalent to a handful of other conditions).

An "infinite set" is a set that is not finite, or equivalently, a set that has infinitely many elements.

So let's say that a language L is special if it has an infinite regular subset.

It's your job to find a language L such that both L and the complement of L are not special.

To get somewhere with this problem, you need to wrap your head around that definition first. Take some of the examples of languages from your notes and your text. Figure out if they are regular. If you find one that isn't, think about what makes it not regular, and see if you design a language that has the property that all of its infinite subsets are not regular. Then see what happens when you look at its complement.

You have to build your intuition, and the only way to do that is to get your hands dirty.


问:
Shiny nesting a link within a paragraph has unwanted whitespace
I'm building a Shiny app with some dynamically generated HTML which includes a link in mid-sentence. Unfortunately if I use the tags functions to do this, every element has a space around it whether I want it or not.

For example, if I wanted to write

This is my favorite link ever!

One might think you could do this

```<code>p('This is my ', a(href = 'https://stackoverflow.com/', 'favorite link ever'), '!')
</code>```

But this results in each element being on a separate line, which by the HTML spec means there will be a space rendered between each.

```<code><p>
  This is my
  <a href="https://stackoverflow.com/">favorite link ever</a>
  !
</p>
</code>```

Which looks like this (note the space before the exclamation mark)

This is my favorite link ever !

Do I have to resort to using HTML(paste0(...)) to construct my HTML, or is there some technique to using the tags functions that I'm missing?

Thanks..

答:
I think you have to use paste. Otherwise nesting wouldn't work like expected.

```<code>div(p('hi'),p('what up'),p(HTML(paste0('This is my ',a(href = 'https://stackoverflow.com/', 'favorite link ever'),'!'))))
</code>```

Result:

```<code><div>
  <p>hi</p>
  <p>what up</p>
  <p>This is my <a href="https://stackoverflow.com/">favorite link ever</a>!</p>
</div>
</code>```

You wouldn't want all those on the same line.

From the help: Named arguments become attributes, and positional arguments become children.

It would be more complexity to have positional arguments to also sometimes not be children; and probably wouldn't be as simple, flexible, and powerful as just constructing it yourself.

Body:
I'm building a Shiny app with some dynamically generated HTML which includes a link in mid-sentence. Unfortunately if I use the tags functions to do this, every element has a space around it whether I want it or not.

For example, if I wanted to write

This is my favorite link ever!

One might think you could do this

p('This is my ', a(href = 'https://stackoverflow.com/', 'favorite link ever'), '!')

But this results in each element being on a separate line, which by the HTML spec means there will be a space rendered between each.

  This is my
  favorite link ever
  !

Which looks like this (note the space before the exclamation mark)

This is my favorite link ever !

Do I have to resort to using HTML(paste0(...)) to construct my HTML, or is there some technique to using the tags functions that I'm missing?

Thanks..

Body:
I think you have to use paste. Otherwise nesting wouldn't work like expected.

div(p('hi'),p('what up'),p(HTML(paste0('This is my ',a(href = 'https://stackoverflow.com/', 'favorite link ever'),'!'))))

Result:

<div>
  <p>hi</p>
  <p>what up</p>
  <p>This is my <a href="https://stackoverflow.com/">favorite link ever</a>!</p>
</div>

You wouldn't want all those on the same line.

From the help: Named arguments become attributes, and positional arguments become children.

It would be more complexity to have positional arguments to also sometimes not be children; and probably wouldn't be as simple, flexible, and powerful as just constructing it yourself.


问:
How to get column values of csv file in pandas or other methods in python
I have .csv file which looks like this:

```<code>id,product
1,car
1,phone
2,tv
</code>```

I want to get all rows which match the certain condition e.g:
If the id==1, and product value contains letter "a", print all matched rows (e.g '1,car' will be printed). I know this would be better to work with database but I need to work with csv file.

I tried with pandas:

```<code>import pandas as pd

df = pd.read_csv('products.csv')

for value_i in df.id:
    for value_p in df.product:
         if (value_i==2 and "a" in value_p):
             print(value_i, value_p)
</code>```

But I don't get a good result. If someone can give me a hint how to access values of a columns I would be thankful.

答:
You can use boolean indexing and for check values in strings use str.contains:

```<code>df1 = df[(df['id'] == 1) & (df['product'].str.contains('a'))]
print (df1)
   id product
0   1     car
</code>```

Detail:

```<code>print ((df['id'] == 1) & (df['product'].str.contains('a')))
0     True
1    False
2    False
dtype: bool
</code>```

Body:
I have .csv file which looks like this:

id,product
1,car
1,phone
2,tv

I want to get all rows which match the certain condition e.g:
If the id==1, and product value contains letter "a", print all matched rows (e.g '1,car' will be printed). I know this would be better to work with database but I need to work with csv file.

I tried with pandas:

import pandas as pd

df = pd.read_csv('products.csv')

for value_i in df.id:
    for value_p in df.product:
         if (value_i==2 and "a" in value_p):
             print(value_i, value_p)

But I don't get a good result. If someone can give me a hint how to access values of a columns I would be thankful.

Body:
You can use boolean indexing and for check values in strings use str.contains:

df1 = df[(df['id'] == 1) & (df['product'].str.contains('a'))]
print (df1)
   id product
0   1     car

Detail:

print ((df['id'] == 1) & (df['product'].str.contains('a')))
0     True
1    False
2    False
dtype: bool


问:
Identify 'ng-reflect-opened' by using selenium web driver
I am trying to get the value of 'ng-reflect-opened', by this value i can assert whether on click of side navigation, left menu is visible or not

```<code><mat-sidenav class="mat-elevation-z8 mat-drawer mat-sidenav ng-tns-c5-0 ng-trigger ng-trigger-transform mat-drawer-side" fixedtopgap="56" tabindex="-1" ng-reflect-mode="side" ng-reflect-opened="true" ng-reflect-fixed-in-viewport="false" ng-reflect-fixed-top-gap="56" style="transform: translate3d(0px, 0px, 0px); visibility: visible;">
</code>```

currently i am unable to get the value, as selenium do not support this property of ng model .. i am new to selenium and want to assert the test case on click action of side navigation button .. which is placed in the header section of the page

when button is clicked left navigation menu is not visible ..

When button is clicked again ..left navigation menu is displayed ..

答:
The question doesn't mentions the Selenium Client/bindings to be used. Though its an Angular Element still we must be able to extract the ng-reflect-opened attribute through the following line of Java code :

```<code>driver.findElement(By.xpath("//mat-sidenav[@class='mat-elevation-z8 mat-drawer mat-sidenav ng-tns-c5-0 ng-trigger ng-trigger-transform mat-drawer-side']")).getAttribute("ng-reflect-opened");
</code>```

Body:
I am trying to get the value of 'ng-reflect-opened', by this value i can assert whether on click of side navigation, left menu is visible or not

<mat-sidenav class="mat-elevation-z8 mat-drawer mat-sidenav ng-tns-c5-0 ng-trigger ng-trigger-transform mat-drawer-side" fixedtopgap="56" tabindex="-1" ng-reflect-mode="side" ng-reflect-opened="true" ng-reflect-fixed-in-viewport="false" ng-reflect-fixed-top-gap="56" style="transform: translate3d(0px, 0px, 0px); visibility: visible;">

currently i am unable to get the value, as selenium do not support this property of ng model .. i am new to selenium and want to assert the test case on click action of side navigation button .. which is placed in the header section of the page

when button is clicked left navigation menu is not visible ..

When button is clicked again ..left navigation menu is displayed ..

Body:
The question doesn't mentions the Selenium Client/bindings to be used. Though its an Angular Element still we must be able to extract the ng-reflect-opened attribute through the following line of Java code :

driver.findElement(By.xpath("//mat-sidenav[@class='mat-elevation-z8 mat-drawer mat-sidenav ng-tns-c5-0 ng-trigger ng-trigger-transform mat-drawer-side']")).getAttribute("ng-reflect-opened");


问:
Catchable Fatal Error: Object of class AppBundle\Entity\Job could not be converted to string
Can anyone help me to fix this problem? I don't know why but I get this exception:

Catchable Fatal Error: Object of class AppBundle\Entity\Job could not be converted to string

my entity Category:

```<code>namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
 */
class Category
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="label", type="string", length=255)
     */
    private $label;

    /**
    * @var string
     *@ORM\ManyToMany(targetEntity="Job", mappedBy="categories", cascade={"persist", "merge"})
    */
    private $jobs ;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->jobs = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set label
     *
     * @param string $label
     *
     * @return Category
     */
    public function setLabel($label)
    {
        $this->label = $label;

        return $this;
    }

    /**
     * Get label
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }
    /**
     * Add job
     *
     * @param \AppBundle\Entity\Job $job
     *
     * @return Category
     */
    public function addJob(\AppBundle\Entity\Job $job)
    {
        $this->jobs[] = $job;

        return $this;
    }

    /**
     * Remove job
     *
     * @param \AppBundle\Entity\Job $job
     */
    public function removeJob(\AppBundle\Entity\Job $job)
    {
        $this->jobs->removeElement($job);
    }

    /**
     * Get jobs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getJobs()
    {
        return $this->jobs;
    }

}
</code>```

the entity config (easyadmin), where I choose to custom some fields:

```<code>easy_admin:

    design:

    entities:
        Category:
            class: AppBundle\Entity\Category
</code>```

Does the screenshot explain the bug or what does it mean exactly?

答:
add this method to your Job class</p>

```<code>public function __toString() {
    return "some string representation of your object"
}
</code>```

Body:
Can anyone help me to fix this problem? I don't know why but I get this exception:

Catchable Fatal Error: Object of class AppBundle\Entity\Job could not be converted to string

my entity Category:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
 */
class Category
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="label", type="string", length=255)
     */
    private $label;

    /**
    * @var string
     *@ORM\ManyToMany(targetEntity="Job", mappedBy="categories", cascade={"persist", "merge"})
    */
    private $jobs ;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->jobs = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set label
     *
     * @param string $label
     *
     * @return Category
     */
    public function setLabel($label)
    {
        $this->label = $label;

        return $this;
    }

    /**
     * Get label
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }
    /**
     * Add job
     *
     * @param \AppBundle\Entity\Job $job
     *
     * @return Category
     */
    public function addJob(\AppBundle\Entity\Job $job)
    {
        $this->jobs[] = $job;

        return $this;
    }

    /**
     * Remove job
     *
     * @param \AppBundle\Entity\Job $job
     */
    public function removeJob(\AppBundle\Entity\Job $job)
    {
        $this->jobs->removeElement($job);
    }

    /**
     * Get jobs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getJobs()
    {
        return $this->jobs;
    }

}

the entity config (easyadmin), where I choose to custom some fields:

easy_admin:

    design:

    entities:
        Category:
            class: AppBundle\Entity\Category

Does the screenshot explain the bug or what does it mean exactly?

Body:
add this method to your Job class

public function __toString() {
    return "some string representation of your object"
}