问:
Where to store AppFabric DataCacheFactory in Asp.net?
AppFabric's DataCacheFactory takes long time to initialize so I am trying to create it once and re-use it in next requests.

Currently, the best idea I have is to store it in HttpContext but I also have some WCF services (which don't have HttpContext set). Any other ideas where and how I should handle this?

Thanks!

答:
This is a problem I've been giving some thought to over the last couple of months, but I haven't come up with a definitive answer...

I'm not sure HttpContext is the right place to keep it - according to this page "A new HttpContext object will be created at the beginning of a request and destroyed when the request is completed", so I'd be concerned that if you put DataCacheFactory into HttpContext you're going to lose it when the request pipeline completes. (HttpContext isn't an object I've particularly needed to use so I could have this completely wrong!)

However, I think there are a number of options:

If you use the Singleton pattern
for creating a DataCacheFactory (Jon
Skeet has an excellent piece on
doing Singletons in C# with
thread-safety here), the
Singleton will essentially take care
of storing the DataCacheFactory for
you in the instance field.

This option feels slightly perverse but you could keep your DataCacheFactory in the ASP.NET Cache. Not being a WCF developer I don't know what you've got access to but if you can get to the HttpRuntime object the cache is accessible from there.

Another option you might want to consider is storing DataCacheFactory in Application state, although I think this might also be difficult to access from your WCF services as it's typically accessed through HttpContext.


来源: stackexchange

问:
ng-bootstrap not working in angular 4
I am new with angular 4, I am trying to configure bootstrap.
I installed ng-bootstrap:

https://ng-bootstrap.github.io/#/getting-started

I did all like on the page, but I don't see the bootstrap on my page.
Here is my code:

src/app/app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
imports: [
   BrowserModule,
   FormsModule,  // add  this
   NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

src/app/app.component.html

```<code><div class="container">

<h1 class="text-primary">{{title}} </h1>

<h2 class="text-primary">My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes"
    [class.selected]="hero === selectedHero"
    (click)="onSelect(hero)">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
   </li>
</ul>

<div class="alert alert-success" role="alert">
 <strong>Well done!</strong> You successfully read this important alert
   message.
</div>

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
  <label>name: </label>
  <input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</code>```

I tried also some code in the index.html, but it does not work,

for this line I am expecting to see some color:

```<code><h1 class="text-primary">{{title}} </h1>
</code>```

I don't find any reference of bootstrap when I check the header of the html.
Any help, please?
Thanks

答:
In the page you mentioned, ng-bootstrap mentions bootstrap CSS as a dependency. So that's loaded separately.

If you are using Angular CLI to create your application, you can follow this official guide to add it,

Update:

As mentioned in the comment, adding the CSS to styles in .angular-cli.json (or any other changes to this file) will require you to restart your ng serve or ng build --watch if you have either already running.

Update 2 (Current Recommended Approach):

For Angular 6 and higher you can use this solution.

Go to styles.css and add this line

```<code>@import "~bootstrap/dist/css/bootstrap.css";
</code>```

See also how this works under the hood:

https://blog.angularindepth.com/this-is-how-angular-cli-webpack-delivers-your-css-styles-to-the-client-d4adf15c4975

ContentLicense: CC BY-SA 3.0

Title: ng-bootstrap not working in angular 4

Body:
I am new with angular 4, I am trying to configure bootstrap.
I installed ng-bootstrap:

https://ng-bootstrap.github.io/#/getting-started

I did all like on the page, but I don't see the bootstrap on my page.
Here is my code:

src/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  declarations: [
    AppComponent
  ],
imports: [
   BrowserModule,
   FormsModule,  // add  this
   NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

src/app/app.component.html

{{title}}

My Heroes

    {{hero.id}} {{hero.name}}

 Well done! You successfully read this important alert
   message.

{{selectedHero.name}} details!

id: {{selectedHero.id}}

  name:
  <input [(ngModel)]="selectedHero.name" placeholder="name"/>

I tried also some code in the index.html, but it does not work,

for this line I am expecting to see some color:

{{title}}

I don't find any reference of bootstrap when I check the header of the html.
Any help, please?
Thanks

Body:
In the page you mentioned, ng-bootstrap mentions bootstrap CSS as a dependency. So that's loaded separately.

If you are using Angular CLI to create your application, you can follow this official guide to add it,

Update:

As mentioned in the comment, adding the CSS to styles in .angular-cli.json (or any other changes to this file) will require you to restart your ng serve or ng build --watch if you have either already running.

Update 2 (Current Recommended Approach):

For Angular 6 and higher you can use this solution.

Go to styles.css and add this line

@import "~bootstrap/dist/css/bootstrap.css";

See also how this works under the hood:

https://blog.angularindepth.com/this-is-how-angular-cli-webpack-delivers-your-css-styles-to-the-client-d4adf15c4975

ContentLicense: CC BY-SA 4.0


问:
How to let user download a file in ajax success method?
I'm trying to let user download a file from server.
I use ServletOutputStream in my controller (here is the code)

```<code>@RequestMapping(value = "/get-backup-file", method = RequestMethod.GET)
@ResponseBody
public void getBackupFile(
    HttpServletRequest request,
    HttpServletResponse response) throws MalformedURLException, IOException {

    File backupFile = new File("PATH_TO_FILE");

    ServletOutputStream out = response.getOutputStream();

    response.setContentType("application/octet-stream");
    response.setContentLength((int)backupFile.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "database backup" + "\"");

    FileInputStream in = new FileInputStream(backupFile);
    byte[] buffer = new byte[4096];

    int length;
    while( (length = in.read(buffer) ) > 0) {
        out.write(buffer, 0, length);
    }
    in.close();
    out.flush();
}
</code>```

My client side looks like this:

```<code>      $.ajax({
        url: 'URL_TOCONTROLLER_METHOD',
        contentType: "application/octet-stream; charset=utf-8",
        type: 'GET',
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log("error");
        }
    });
</code>```

when I console.log the data it has the content of the file, but I want this file to be downloaded tu the user, not just printed. how can make let user to save the data as file?

答:
Don't use ajax. Instead provide a download link. </p>

```<code><a href="URL_TOCONTROLLER_METHOD" download>Click To Download</a>
</code>```

Body:
I'm trying to let user download a file from server.
I use ServletOutputStream in my controller (here is the code)

@RequestMapping(value = "/get-backup-file", method = RequestMethod.GET)
@ResponseBody
public void getBackupFile(
    HttpServletRequest request,
    HttpServletResponse response) throws MalformedURLException, IOException {

    File backupFile = new File("PATH_TO_FILE");

    ServletOutputStream out = response.getOutputStream();

    response.setContentType("application/octet-stream");
    response.setContentLength((int)backupFile.length());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + "database backup" + "\"");

    FileInputStream in = new FileInputStream(backupFile);
    byte[] buffer = new byte[4096];

    int length;
    while( (length = in.read(buffer) ) > 0) {
        out.write(buffer, 0, length);
    }
    in.close();
    out.flush();
}

My client side looks like this:

      $.ajax({
        url: 'URL_TOCONTROLLER_METHOD',
        contentType: "application/octet-stream; charset=utf-8",
        type: 'GET',
        success: function(data) {
            console.log(data);
        },
        error: function(data) {
            console.log("error");
        }
    });

when I console.log the data it has the content of the file, but I want this file to be downloaded tu the user, not just printed. how can make let user to save the data as file?

Body:
Don't use ajax. Instead provide a download link.

<a href="URL_TOCONTROLLER_METHOD" download>Click To Download</a>


问:
Built in double-asterisk power function not working as expected
This prints -2.4:

```<code>print(-3**0.8)
</code>```

But this prints an imaginary number...?

```<code>a = -3
b = 0.8
print(a**b)
</code>```

I can't figure out what is causing this and this problem is breaking my program. How do you make it so that the second statement outputs the same as the first in a general case that works for positive and negative values for a?

答:
Per the Python 3.6 documentation:

6.5. The power operator

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

```<code>power ::=  ( await_expr | primary ) ["**" u_expr]
</code>```

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

Thus, in the first example:

```<code>>>> -3 ** 0.8
-2.4082246852806923
</code>```

It's evaluated right to left as ** has higher precedence than unary -, binding tighter -- so here, 3 ** 0.8 is evaluated first, then the unary - operator is applied for a negative value. In the second example however, the expression is equivalent (-3) ** 0.8 as -3 is stored in a name, and evaluation results is an imaginary number:

```<code>>>> a = -3
>>> b = 0.8
>>> a ** b
(-1.9482946966653392+1.4155189542146738j)
</code>```

A solution would be to calculate the result without unary operators, then applying a sign as necessary, per Shakar Bhattarai's answer:

```<code>>>> int(a / abs(a)) * (abs(a) ** b)
-2.4082246852806923
</code>```

The first part, int(a / abs(a)) evaluates to either -1.0 or 1.0 depending on if a is negative or not, basically applying the sign. It then multiplies that by the result of a ** b regardless of a's sign. That will first compute a ** b disregarding it's sign, then applying the sign as necessary. This will get rid of the discrepancy. You could apply the same concept with math.copysign:

```<code>>>> math.copysign(1, a) * (abs(a) ** b)
-2.4082246852806923
</code>```

This will just copy the sign from a to 1, which will give -1.0 or 1.0 based on negativity.

Body:
This prints -2.4:

print(-3**0.8)

But this prints an imaginary number...?

a = -3
b = 0.8
print(a**b)

I can't figure out what is causing this and this problem is breaking my program. How do you make it so that the second statement outputs the same as the first in a general case that works for positive and negative values for a?

Body:
Per the Python 3.6 documentation:

6.5. The power operator

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

power ::=  ( await_expr | primary ) ["**" u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

Thus, in the first example:

>>> -3 ** 0.8
-2.4082246852806923

It's evaluated right to left as ** has higher precedence than unary -, binding tighter -- so here, 3 ** 0.8 is evaluated first, then the unary - operator is applied for a negative value. In the second example however, the expression is equivalent (-3) ** 0.8 as -3 is stored in a name, and evaluation results is an imaginary number:

>>> a = -3
>>> b = 0.8
>>> a ** b
(-1.9482946966653392+1.4155189542146738j)

A solution would be to calculate the result without unary operators, then applying a sign as necessary, per Shakar Bhattarai's answer:

>>> int(a / abs(a)) * (abs(a) ** b)
-2.4082246852806923

The first part, int(a / abs(a)) evaluates to either -1.0 or 1.0 depending on if a is negative or not, basically applying the sign. It then multiplies that by the result of a ** b regardless of a's sign. That will first compute a ** b disregarding it's sign, then applying the sign as necessary. This will get rid of the discrepancy. You could apply the same concept with math.copysign:

>>> math.copysign(1, a) * (abs(a) ** b)
-2.4082246852806923

This will just copy the sign from a to 1, which will give -1.0 or 1.0 based on negativity.


问:
Can I detect XHTML parsing errors using Javascript?
When I have a markup error in my XHTML page, Mozilla Firefox displays the "Yellow Screen of Death", showing only a large red error message on a yellow background.

While these errors are rare, they are extremely user-unfriendly.

Is there a way I can detect these using Javascript, and thereby send a message back to the server?

What I've discovered so far:
 - Scripts placed before the parsing error still run. (Of course.)
 - Timeouts and intervals that were set in these scripts will still execute after the parsing error.
 - In Firefox, the DOM is a <parsererror> with a <sourcetext> inside it. I can detect this if I query document.firstChild.tagName.

Remaining questions:
 - What events are available that I could listen for to detect this happening? (Polling sucks.)
 - How can I detect this in other browsers?

答:
I'd recommend validating the document on the server side. But if you really want to do it on the client side, there's nothing wrong with polling if done correctly (which means that the poll is guaranteed to terminate).

The following should work in at least Firefox and Opera:

```<code>(function() {
    if(document.documentElement &&
        document.documentElement.getAttribute('xmlns') !==
        'http://www.w3.org/1999/xhtml') {
        alert('parsing errors');
    }
    else if(document.body && document.body.lastChild) {
        alert('no parsing errors');
    }
    else setTimeout(arguments.callee, 100);
})();
</code>```

OwnerDisplayName: phyzome

ContentLicense: CC BY-SA 2.5

Body:
I'd recommend validating the document on the server side. But if you really want to do it on the client side, there's nothing wrong with polling if done correctly (which means that the poll is guaranteed to terminate).

The following should work in at least Firefox and Opera:

(function() {
    if(document.documentElement &&
        document.documentElement.getAttribute('xmlns') !==
        'http://www.w3.org/1999/xhtml') {
        alert('parsing errors');
    }
    else if(document.body && document.body.lastChild) {
        alert('no parsing errors');
    }
    else setTimeout(arguments.callee, 100);
})();

OwnerDisplayName: Christoph


问:
how to run my project in time 13:00 for example Every day (in java )
I want to execute my program at 13:00 every day for example

this is my method that I want run in this time>

I hope the experts will write the solution

And, if possible, converted to Windows Service

In order to make the server take a backup at 13:00 every day:

```<code>public static void backup() throws IOException{

        try{
        String date = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
        String path="G:/DataBaseBackup/doctor_" + date + ".sql";
         String user="root";
         String password="12345";
         String db="doctor";

         Process runtimeProcess;
         String exeutedrun="\"C:/Program Files/MySQL/MySQL Server 5.7/bin/mysqldump.exe\" -u " + user + " -p" + password + " --routines --events   --add-drop-database -B " + db + " -r " + path;
         runtimeProcess=Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", exeutedrun });
         int processComplete = runtimeProcess.waitFor();
        System.out.println(path);
         if (processComplete == 0) {
             System.out.println("Data Base is Backup !!");

                error.write("Data Base is Backup in path : "+path);

         } else {
             System.out.println("Data Base is not Backup !!");

                error.write("Data Base is not Backup  : ");
         }

        }catch(Exception e){

            error.Exption(e);
            System.exit(1);

        }

    }
</code>```

答: Instead of writing into the code, export the code as runnable jar. Write a simple shell script for executing the jar save it as .cmd file. Then schedule the .cmd file into task scheduler for 13:00 everday.</p>

Body:
I want to execute my program at 13:00 every day for example

this is my method that I want run in this time>

I hope the experts will write the solution

And, if possible, converted to Windows Service

In order to make the server take a backup at 13:00 every day:

public static void backup() throws IOException{

        try{
        String date = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
        String path="G:/DataBaseBackup/doctor_" + date + ".sql";
         String user="root";
         String password="12345";
         String db="doctor";

         Process runtimeProcess;
         String exeutedrun="\"C:/Program Files/MySQL/MySQL Server 5.7/bin/mysqldump.exe\" -u " + user + " -p" + password + " --routines --events   --add-drop-database -B " + db + " -r " + path;
         runtimeProcess=Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", exeutedrun });
         int processComplete = runtimeProcess.waitFor();
        System.out.println(path);
         if (processComplete == 0) {
             System.out.println("Data Base is Backup !!");

                error.write("Data Base is Backup in path : "+path);

         } else {
             System.out.println("Data Base is not Backup !!");

                error.write("Data Base is not Backup  : ");
         }

        }catch(Exception e){

            error.Exption(e);
            System.exit(1);

        }

    }


问:
Select() not poping up in DbSet<Category> Property
This is first time I am trying EF core. I create separate class library for EF core created dbcontext EXPENSEDBContext class form the existing database and build successfully.

While I tried to select a record through the object of EXPENSEDBContext I could not able to see the Select() and Where()  as below

```<code>var selectvalues = db.Category.Select();
</code>```

So as an alternate I used foreach instead of Select() as below

```<code>using (var db = new EXPENSEDBContext())
        {
            //
            var selectvalues = db.Category;

             foreach(var b in selectvalues)
            {
                Console.WriteLine(b.Name);
            }
        }
</code>```

My question is why Select method is not poping up in db.Category.

答:
If you correctly defined Category property as you said in your comment

```<code>public virtual DbSet<Catagory> Catagory { get; set; }
</code>```

so make sure you added the following using statement:

```<code>using System.Linq;
</code>```

If it doesn't compile so make sure to install the System.Linq nuget package:

```<code>Install-Package System.Linq
</code>```

Body:
This is first time I am trying EF core. I create separate class library for EF core created dbcontext EXPENSEDBContext class form the existing database and build successfully.

While I tried to select a record through the object of EXPENSEDBContext I could not able to see the Select() and Where()  as below

var selectvalues = db.Category.Select();

So as an alternate I used foreach instead of Select() as below

using (var db = new EXPENSEDBContext())
        {
            //
            var selectvalues = db.Category;

             foreach(var b in selectvalues)
            {
                Console.WriteLine(b.Name);
            }
        }

My question is why Select method is not poping up in db.Category.

Body:
If you correctly defined Category property as you said in your comment

public virtual DbSet<Catagory> Catagory { get; set; }

so make sure you added the following using statement:

using System.Linq;

If it doesn't compile so make sure to install the System.Linq nuget package:

Install-Package System.Linq


问:
React componentDidUpdate not receiving latest props
In Redux, I'm running the following in a redux-thunk action creator:

```<code>dispatch({type: "CASCADING_PROMPT_STATUS", promptName, list: 'model', status: 'disabled'});
dispatch({type: "CASCADING_PROMPT_STATUS", promptName, list: 'model', status: 'enabled'});
</code>```

This triggers the reducer twice, and I can see in the console that Redux state changes from disabled -> enabled.

In React, I have the following component which has props connected to state of which CASCADING_PROMPT_STATUS updates.

However, in my component, I'm running a check to see if state changed in componentDidUpdate(prevProps)

This doesn't trigger.

If I change the action creator to delay the second dispatch setTimeout(<dispatch...>, 1); even by one millisecond, prevProps !== this.props, which is what I expect.

My component is connected to redux like so:

```<code>const C_Component = connect(mapStateToProps, mapDispatchToProps, null, {pure: false})(Component);
</code>```

Does React batch up prop changes? Why do I have to delay the second dispatch? I thought redux dispatch were synchronous.

Edit: The way I'm updating the redux state is as follows:

```<code>var newState = {};

if (!_.isUndefined(state)){
    newState = _.cloneDeep(state);
}
...
    case "CASCADING_PROMPT_STATUS":
        newState[action.promptName][action.list].disable = action.status === 'disabled';
        break;
</code>```

答:
Redux dispatches are synchronous (unless a middleware intercepts and delays the action).  However, React updates are batched in most cases.

Second, your reducer is definitely mutating the state, because you're not copying every level of nesting that needs to be updated.  The mutations will cause your connected component to think nothing has changed, and skip updating.  See the Structuring Reducers - Immutable Update Patterns section of the docs for more details on how to properly do immutable updates.

Actually... re-reading your reducer, you are doing a deep clone, so in theory that's not mutating.  However, per the Redux FAQ, deep cloning is a bad idea.  Instead, you should do nested shallow updates.

Third, your shouldComponentUpdate shouldn't compare this.props vs nextProps themselves.  The actual props objects themselves will definitely be different.  Instead, it should compare the contents of those objects - ie, props.a !== nextProps.a && props.b !== nextProps.b, etc.  This is known as a "shallow equality comparison".

Body:
In Redux, I'm running the following in a redux-thunk action creator:

dispatch({type: "CASCADING_PROMPT_STATUS", promptName, list: 'model', status: 'disabled'});
dispatch({type: "CASCADING_PROMPT_STATUS", promptName, list: 'model', status: 'enabled'});

This triggers the reducer twice, and I can see in the console that Redux state changes from disabled -> enabled.

In React, I have the following component which has props connected to state of which CASCADING_PROMPT_STATUS updates.

However, in my component, I'm running a check to see if state changed in componentDidUpdate(prevProps)

This doesn't trigger.

If I change the action creator to delay the second dispatch setTimeout(<dispatch...>, 1); even by one millisecond, prevProps !== this.props, which is what I expect.

My component is connected to redux like so:

const C_Component = connect(mapStateToProps, mapDispatchToProps, null, {pure: false})(Component);

Does React batch up prop changes? Why do I have to delay the second dispatch? I thought redux dispatch were synchronous.

Edit: The way I'm updating the redux state is as follows:

var newState = {};

if (!_.isUndefined(state)){
    newState = _.cloneDeep(state);
}
...
    case "CASCADING_PROMPT_STATUS":
        newState[action.promptName][action.list].disable = action.status === 'disabled';
        break;


问:
How can I use mysqli / php to update all records after a query has already been executed?
I have a user form that sets a single record "current". No more than one record can be set to current at a time. So, I present the user a single drop down list, they choose the item they want to set current and hit "UPDATE" at the bottom of the form.

The PHP/Mysqli needs to go in and set all records column "current" to a value of 0 then update the one from the form to a value of "1".

Initially, I just did a simple count the number of rows, and run a bunch of queries to update the column to 0 or 1 if the loop counter = the id of the row. Well... that broke quick as I started doing testing on other portions and the index numbers got higher than the total number of rows. Yes, dumb way to do it initially!

Here's what I tried to do with the PHP / MySQL code:

// $link  is the database link defined elsewhere. This does work as I use it all over the place
$setCurrent = X; // This is the number passed from my form

$init_query = "SELECT id, current FROM myTable";

if ($stmt = $link->$prepare($init_query) {
  $stmt->execute() or die ($stmt->error);
  $stmt ->bind_result($id, $current)
  while ($stmt->fetch()){
    if ($id == $setCurrent){

    $update_sql = "UPDATE myTable SET current ='1' WHERE id='".$setCurrent."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;

    }

    else {
    $update_sql =  "UPDATE myTable SET current ='0' WHERE id='".$id."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;
 }
 $stmt->close();```

This fails and gives me a Fatal error: Uncaught Error: Call to a member function execute on boolean in .....

I am racking my brain over this and can't figure out what the heck is going on. Its been a few years since I have worked in PHP/MySql and this is my first forray into OO Mysqli. Please be gentle :)

答:
why do them one at a time? You can do it in one query

```<code>$setCurrent = X;
$query = 'UPDATE myTable
          SET `current` = (id = :current)';
$stmt = $link->prepare($query);
$stmt->bindValue(':current', $setCurrent);
$stmt->execute();
</code>```

(and misusing the fact that if id equals $setCurrent,  the part between ( )  resolves to true, which is 1.)

some explaining:

SELECT 10=10; would give a kind of "TRUE". But as Mysql does not give true, it give 1.
the same goes for:

SELECT 10=20;  This is FALSE, so gives you 0.

Now back to your query: you want to get a value 0 for all record for which id not equal to some-number. And you want 1 when equal:
So you have to compare the column id's value to $setCurrent. When they match you get 1 and you put that 1 into the column "current"
And when they don't match, all other cases, then you get a 0 and that 0 goes into the column Current.

And yes, this could also be done as:

```<code>UPDATE mytable
SET `current` = CASE id
                 WHEN $setCurrent  THEN 1
                 ELSE 0
               END CASE
</code>```

or using IF,
But they other syntax is way shorter

edit
backtics are needed around column name, as current is a reserved word

Body:
I have a user form that sets a single record "current". No more than one record can be set to current at a time. So, I present the user a single drop down list, they choose the item they want to set current and hit "UPDATE" at the bottom of the form.

The PHP/Mysqli needs to go in and set all records column "current" to a value of 0 then update the one from the form to a value of "1".

Initially, I just did a simple count the number of rows, and run a bunch of queries to update the column to 0 or 1 if the loop counter = the id of the row. Well... that broke quick as I started doing testing on other portions and the index numbers got higher than the total number of rows. Yes, dumb way to do it initially!

Here's what I tried to do with the PHP / MySQL code:

// $link  is the database link defined elsewhere. This does work as I use it all over the place
$setCurrent = X; // This is the number passed from my form

$init_query = "SELECT id, current FROM myTable";

if ($stmt = $link->$prepare($init_query) {
  $stmt->execute() or die ($stmt->error);
  $stmt ->bind_result($id, $current)
  while ($stmt->fetch()){
    if ($id == $setCurrent){

    $update_sql = "UPDATE myTable SET current ='1' WHERE id='".$setCurrent."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;

    }

    else {
    $update_sql =  "UPDATE myTable SET current ='0' WHERE id='".$id."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;
 }
 $stmt->close();

This fails and gives me a Fatal error: Uncaught Error: Call to a member function execute on boolean in .....

I am racking my brain over this and can't figure out what the heck is going on. Its been a few years since I have worked in PHP/MySql and this is my first forray into OO Mysqli. Please be gentle :)

Body:
why do them one at a time? You can do it in one query

$setCurrent = X;
$query = 'UPDATE myTable
          SET `current` = (id = :current)';
$stmt = $link->prepare($query);
$stmt->bindValue(':current', $setCurrent);
$stmt->execute();

(and misusing the fact that if id equals $setCurrent,  the part between ( )  resolves to true, which is 1.)

some explaining:

SELECT 10=10; would give a kind of "TRUE". But as Mysql does not give true, it give 1.
the same goes for:

SELECT 10=20;  This is FALSE, so gives you 0.

Now back to your query: you want to get a value 0 for all record for which id not equal to some-number. And you want 1 when equal:
So you have to compare the column id's value to $setCurrent. When they match you get 1 and you put that 1 into the column "current"
And when they don't match, all other cases, then you get a 0 and that 0 goes into the column Current.

And yes, this could also be done as:

UPDATE mytable
SET `current` = CASE id
                 WHEN $setCurrent  THEN 1
                 ELSE 0
               END CASE

or using IF,
But they other syntax is way shorter

edit
backtics are needed around column name, as current is a reserved word


问:
Compile R packages from source (Mac OS X)
I'm running Mac OS X 10.7.5 (Lion), which means that the latest version of R I can run is 3.2.1. Since binaries of packages are no longer being made for this version, it means that I need to install the latest package versions from source. I can do this with

install.packages(pkgs, type = "source")

I installed GNU Fortran, although it's not clear to me whether I need it or not in order to compile R packages.

When I try to compile packages from source in R, however, I get error messages indicating that I don't have (or that R cannot find) the necessary compiling tools. Cf. e.g.:

```<code>* installing *source* package ‘scales’ ...
** package ‘scales’ successfully unpacked and MD5 sums checked
** libs
sh: make: command not found
ERROR: compilation failed for package ‘scales’
</code>```

and

```<code>* installing *source* package ‘stringi’ ...
** package ‘stringi’ successfully unpacked and MD5 sums checked
checking for local ICUDT_DIR... icu55/data
checking for R_HOME... /Library/Frameworks/R.framework/Resources
checking for R... /Library/Frameworks/R.framework/Resources/bin/R
checking for R >= 3.1.0 for C++11 use... yes
checking for R < 3.4.0 for CXX1X flag use... yes
checking for cat... /bin/cat
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found

[...]

checking for gcc... no
checking for cc... no
checking for cl.exe... no
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
configure: error: in `/private/var/folders/2r/6c5vhb4s3zx3zs4d1dbf9p940000gn/T/Rtmpob4pMm/R.INSTALLd4676ad8595/stringi':
configure: error: no acceptable C compiler found in $PATH
</code>```

I assume what's needed is to install the necessary compiling tools for R packages. What do I need to do?

(If I need to provide additional information, just ask for it in a comment, and I will provide it)

答:
It might be tricky. First of all, double check whether you can download XCode from AppStore or not. If you can, you will be able to install command line tools as well. Either via Preferences -> Downloads (as far as I recall), or they will be installed during first startup.

Alternatively, create free account here:

http://developer.apple.com

Then, head to:

https://developer.apple.com/download/more/

and find XCode. It might be you will need to install some really old version.

As @hrbrmstr mentioned, it might be that installing virtual machine (e.g. inside VirtualBox) with Linux will be less painful.

Note that you will probably encounter more and more issues while installing packages. There is no easy way if you are forced to stick with old OS X :(

Update:

As @Sverre pointed out, it would be better to have a complete list of links here:

XCode - (Lion version) download from Apple (not to confuse with AppStore)

Command Line Tools - (Lion version) you can install them separately, without installing XCode

Body:
I'm running Mac OS X 10.7.5 (Lion), which means that the latest version of R I can run is 3.2.1. Since binaries of packages are no longer being made for this version, it means that I need to install the latest package versions from source. I can do this with

install.packages(pkgs, type = "source")

I installed GNU Fortran, although it's not clear to me whether I need it or not in order to compile R packages.

When I try to compile packages from source in R, however, I get error messages indicating that I don't have (or that R cannot find) the necessary compiling tools. Cf. e.g.:

* installing *source* package ‘scales’ ...
** package ‘scales’ successfully unpacked and MD5 sums checked
** libs
sh: make: command not found
ERROR: compilation failed for package ‘scales’

and

* installing *source* package ‘stringi’ ...
** package ‘stringi’ successfully unpacked and MD5 sums checked
checking for local ICUDT_DIR... icu55/data
checking for R_HOME... /Library/Frameworks/R.framework/Resources
checking for R... /Library/Frameworks/R.framework/Resources/bin/R
checking for R >= 3.1.0 for C++11 use... yes
checking for R < 3.4.0 for CXX1X flag use... yes
checking for cat... /bin/cat
/Library/Frameworks/R.framework/Resources/bin/config: line 150: make: command not found

[...]

checking for gcc... no
checking for cc... no
checking for cl.exe... no
/Library/Frameworks/R.framework/Resources/bin/config: line 153: make: command not found
/Library/Frameworks/R.framework/Resources/bin/config: line 269: make: command not found
configure: error: in `/private/var/folders/2r/6c5vhb4s3zx3zs4d1dbf9p940000gn/T/Rtmpob4pMm/R.INSTALLd4676ad8595/stringi':
configure: error: no acceptable C compiler found in $PATH

I assume what's needed is to install the necessary compiling tools for R packages. What do I need to do?

(If I need to provide additional information, just ask for it in a comment, and I will provide it)


答:
This is because of the precedence of the power operator. The power operator binds tighter than unary operators. So:

```<code>-3 ** 0.8
</code>```

is evaluated as

```<code>-(3 * 0.8)
</code>```

You can see how Python parses your code using the ast module:

```<code>>>> import ast
>>> ast.dump(ast.parse('-3 ** 0.8'))
'Module(body=[Expr(value=UnaryOp(op=USub(), operand=BinOp(left=Num(n=3), op=Pow(), right=Num(n=0.8))))])'
>>>
</code>```

In the above, the 3 ** 0.8 is treated as one expression with ** being the operator. The unary minus is then applied to the value of the inner expression.

However, in your second example the values are stored in variables, so the precedence does not affect the expression. So a ** b is equivlent to (-3) ** 0.8

The solution is to bind the unary minus to the three using parenthesis:

```<code>>>> (-3) ** 0.8
(-1.94829469666534+1.4155189542146727j)
>>>
</code>```

Title: Built in double-asterisk power function not working as expected

Body:
This is because of the precedence of the power operator. The power operator binds tighter than unary operators. So:

-3 ** 0.8

is evaluated as

-(3 * 0.8)

You can see how Python parses your code using the ast module:

>>> import ast
>>> ast.dump(ast.parse('-3 ** 0.8'))
'Module(body=[Expr(value=UnaryOp(op=USub(), operand=BinOp(left=Num(n=3), op=Pow(), right=Num(n=0.8))))])'
>>>

In the above, the 3 ** 0.8 is treated as one expression with ** being the operator. The unary minus is then applied to the value of the inner expression.

However, in your second example the values are stored in variables, so the precedence does not affect the expression. So a ** b is equivlent to (-3) ** 0.8

The solution is to bind the unary minus to the three using parenthesis:

>>> (-3) ** 0.8
(-1.94829469666534+1.4155189542146727j)
>>>


问:
Split elements before the first number
I have this text appearing after using xpath :

```<code>',\n                             31.05.2017,\n        20h10\n'
</code>```

I have been able to get this by using split(',')[1]:

```<code>'\n                             31.05.2017'
</code>```

However what I want is to only have the date. The thing is the date changes all the time depending on the page I am scraping. So what I need is just to get rid of the /n and the spaces that are before the first number that appears.

If you could help it would be amazing thank you :)

答:
You can simply strip the string to remove leading and trailing whitespaces; the new line character '\n' is also whitespace:

```<code>>>> '\n                             31.05.2017'.strip()
'31.05.2017'
</code>```

Title: Split elements before the first number

Body:
I have this text appearing after using xpath :

',\n                             31.05.2017,\n        20h10\n'

I have been able to get this by using split(',')[1]:

'\n                             31.05.2017'

However what I want is to only have the date. The thing is the date changes all the time depending on the page I am scraping. So what I need is just to get rid of the /n and the spaces that are before the first number that appears.

If you could help it would be amazing thank you :)

Body:
You can simply strip the string to remove leading and trailing whitespaces; the new line character '\n' is also whitespace:

>>> '\n                             31.05.2017'.strip()
'31.05.2017'


问:
FATFS porting on STM32F103 SPI Flash
I have ported FATFS for Free RTOS on STM32F103 SPI Flash of 32 Mbit. In a demo Application I have successfully created a file, written a file, and read back from the file. My requirement is like I have to store multiple files (images) in SPI flash and read it back when required.

I have the following conditions/queries.

I have set the Sector Size to 512 bytes, and block erase size for SPI flash is 4K. As in the SPI Flash, block needs to be erased before written. Do I need to keep track on whether a particular block is erased or not or its the file System who is managing this?

How can I verify that the sector, which I am writing in erased or not? What I am currently doing is, Erase the Complete Block for the sector, which I am going to write?

How can I make sure, The Block for SPI flash I am going to erase will not affect any Sector containing useful data?

Thanking in an Anticipation,

Regards,

AK

答:
The simplest solution is to define the "cluster" size to 4K, the same as the page size of your flash. That mean each file, even if only 1 byte, takes 4K, which is 8 consecutive sectors of 512 bytes each.
As soon as you need to reserve one more cluster, when the file grow above 4096 bytes, you pick a free cluster, chain it to the FAT, and write the next byte.

For performance reason and to increase the durability of the flash, you should avoid to erase of flash sector when not needed. It is many order of magnitude faster to read then erasing. So, as you select a free cluster, you can start a loop to read each of the 8 sectors. As soon as you find even a single byte not equal to 0xFF, then you abort the loop and call the flash erase for that sector.

A further optimization is possible if the flash controller is able to perform the blank test directly. Such test could be done in a few microsecond while reading 8 sectors and looping to check each of the 4096 bytes is probably slower.

Title: FATFS porting on STM32F103 SPI Flash


问:
Using external php
I am building a website using a technique I've never seen, and I may have just found out why, but I thought I'd check with those who know better than I.
My project is set up with a Tasks.php that looks something like:

```<code><?php
    if($_GET['task'] == 'task1'){
        $response = {'someTag':'someValue'};
    }
    if($_GET['task'] == 'task2'){
        $response = {'someTag':'someValue'};
    }
    if($_GET['task'] == 'task3'){
        if($_GET['info'] == 'someInfo'){
            $response = {'someTag':'someValue'};
        }
    }
    echo json_encode($response);
    exit;
?>
</code>```

this way, in my js I can essentially call php functions with ajax I.E.

```<code>$.get('Tasks.php',{'task':'task3','info':'someInfo'},function(response){
    var data = JSON.parse(response);
    console.log(data);
});
</code>```

which would log a js object litteral:

{'someTag':'someValue'}

The problem I have is that my php has lost the functionality to do something like echo "$(body).append($('
'));"; Which would (using jquery) append a div to my document's body.  The reason I'm doing it this way is because I want all my pages to have the html extension for other stuff.  I would assume there's a way to possibly have that div there already, and reference it by id, or somehow make it visible with just php, and maybe my assumption is off base, or I need a plugin or extension or something, but, I need to confirm my crazyness(or stupidity).

答: You're getting a JSON response and you can't get both HTML and JSON, so you're on the right track. You should have a a 'success' block in your ajax that tells it what to do with the JSON that comes back. There are TONS of tutorials out there on how to do this so I don't need to duplicate the code here. But if you get stuck after this, then come back and ask another question. Good luck!</p>

Title: Using external php

Body:
I am building a website using a technique I've never seen, and I may have just found out why, but I thought I'd check with those who know better than I.
My project is set up with a Tasks.php that looks something like:

<?php
    if($_GET['task'] == 'task1'){
        $response = {'someTag':'someValue'};
    }
    if($_GET['task'] == 'task2'){
        $response = {'someTag':'someValue'};
    }
    if($_GET['task'] == 'task3'){
        if($_GET['info'] == 'someInfo'){
            $response = {'someTag':'someValue'};
        }
    }
    echo json_encode($response);
    exit;
?>

this way, in my js I can essentially call php functions with ajax I.E.

$.get('Tasks.php',{'task':'task3','info':'someInfo'},function(response){
    var data = JSON.parse(response);
    console.log(data);
});

which would log a js object litteral:

{'someTag':'someValue'}

The problem I have is that my php has lost the functionality to do something like echo "$(body).append($('
'));"; Which would (using jquery) append a div to my document's body.  The reason I'm doing it this way is because I want all my pages to have the html extension for other stuff.  I would assume there's a way to possibly have that div there already, and reference it by id, or somehow make it visible with just php, and maybe my assumption is off base, or I need a plugin or extension or something, but, I need to confirm my crazyness(or stupidity).


问:
"macro names must be identifiers"
I get the above error message with the code that's shown below. It's for use with a JSN-SR04T sensor. I'm using an Arduino Uno with IDE version 1.8.2.0.

I changed pin numbers and took out all blank spaces just in case there were any embedded characters. Still get the error. Not sure of what else to do. Any suggestions?

Code:

/*
 * Ultrasonic Sensor HC-SR04 and Arduino Tutorial
 *
 * Created by Dejan Nedelkovski,
 * www.HowToMechatronics.com
 *
*/.
#define ECHOPIN 10
#define TRIGPIN 9

const int TRIGPIN = 9;
const int ECHOPIN = 10;
long duration;
int distance;

void setup() {
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);
  duration = pulseIn(ECHOPIN, HIGH);
  distance= duration*0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}
```

答:
```<code> * www.HowToMechatronics.com
 *
*/.
</code>```

What is this dot doing after /?

Title: "macro names must be identifiers"

Body:
 * www.HowToMechatronics.com
 *
*/.

What is this dot doing after /?


问:
Browser stalls request when serving static files with Nginx
I have a situation where when I open the page for the first time, everything works fast, if I reload the page soon after everything works ok, and if I reload the page 3rd time browser stalles the request for about 25 seconds. Sometimes more, sometimes less. Sometimes it's a request for root, sometimes for some static file. If I wait some time and refresh again, everything is opening fast again until about 2nd or 3rd refresh of the webpage.

What could this be? If I use Nginx but serve static files with Node, I don't have that kind of a problem?

```<code>daemon off;
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;

worker_rlimit_nofile 10000;

events {

    use epoll;

    accept_mutex on;

    multi_accept    on;

    worker_connections 1024;
}

error_log   logs/nginx/error.log;

http {

  charset   utf-8;

  include mime.types;

  default_type  application/octet-stream;

  access_log     off;

   log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';

    access_log logs/nginx/access.log l2met;

    sendfile        on;

    tcp_nopush      on;

    tcp_nodelay       on;

    types_hash_max_size       2048;

    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid   30s;
    open_file_cache_min_uses    2;
    open_file_cache_errors  on;

    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

    client_body_buffer_size 16k;

    client_header_buffer_size   1k;

    client_max_body_size    8m;

    large_client_header_buffers 2 1k;

    # # - Configure Timeouts

    reset_timedout_connection on;

    client_body_timeout 12;

    client_header_timeout   12;

    keepalive_timeout   15;

    keepalive_requests 100;

    send_timeout    10;

    server_tokens   off;

  # # - Dynamic gzip compression
  gzip                      on;
    gzip_http_version         1.1;
    gzip_disable              "msie6";
    gzip_vary                 on;
    gzip_min_length           20;
    gzip_buffers              4 16k;
    gzip_comp_level           4;
    gzip_proxied              any;

    # Turn on gzip for all content types that should benefit from it.

    gzip_types  application/ecmascript;
    gzip_types  application/javascript;
    gzip_types  application/json;
    gzip_types  application/pdf;
    gzip_types  application/postscript;
    gzip_types  application/x-javascript;
    gzip_types  image/svg+xml;
    gzip_types  text/css;
    gzip_types  text/csv;
    gzip_types  text/javascript;
    gzip_types  text/plain;
    gzip_types  text/xml;
    gzip_types  text/json;

  # proxying requests to other servers

    upstream nodebeats {
      server unix:/tmp/nginx.socket fail_timeout=0;
    }

    server {
        listen       <%= ENV['PORT'] %>;
        server_name  _;
        root        "/app/";

    limit_conn conn_limit_per_ip 5;
    limit_req zone=req_limit_per_ip burst=10 nodelay;

    location ~* \.(js|css|jpg|png|ico|json|xml|svg)$ {
      root               "/app/src/dist/";
      add_header         Pragma public;
      add_header         Cache-Control public;
      expires            1y;
      gzip_static        on;
      gzip               off;
      log_not_found      off;
      access_log         off;
    }

    location / {
      proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header   Host $http_host;
      proxy_set_header   Connection "";
      proxy_redirect     off;
      proxy_http_version 1.1;
      proxy_pass         http://nodebeats;
      add_header         Cache-Control no-cache;
      proxy_read_timeout 60s;
    }
}
</code>```

}

答:
Ok after inspecting I saw that this is happening because of some Chrome (and other browsers) limitation of 6 tcp connection per server simultaneals. When I look into chrome://net-internals/#sockets I see this. The problem is ssl_socket_pool and 6 active connections. They take a long time to go from active to idle (and then page continues to load). How to fix that?

I tried opening some other pages that have much more static content and http request than mine (which has 8) and they reload fast always. I looked at the same place and saw that there is nothing in Active. All the connections are immediately idle after page reload.

Body:
I have a situation where when I open the page for the first time, everything works fast, if I reload the page soon after everything works ok, and if I reload the page 3rd time browser stalles the request for about 25 seconds. Sometimes more, sometimes less. Sometimes it's a request for root, sometimes for some static file. If I wait some time and refresh again, everything is opening fast again until about 2nd or 3rd refresh of the webpage.

What could this be? If I use Nginx but serve static files with Node, I don't have that kind of a problem?

daemon off;
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;

worker_rlimit_nofile 10000;

events {

    use epoll;

    accept_mutex on;

    multi_accept    on;

    worker_connections 1024;
}

error_log   logs/nginx/error.log;

http {

  charset   utf-8;

  include mime.types;

  default_type  application/octet-stream;

  access_log     off;

   log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';

    access_log logs/nginx/access.log l2met;

    sendfile        on;

    tcp_nopush      on;

    tcp_nodelay       on;

    types_hash_max_size       2048;

    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid   30s;
    open_file_cache_min_uses    2;
    open_file_cache_errors  on;

    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;

    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=5r/s;

    client_body_buffer_size 16k;

    client_header_buffer_size   1k;

    client_max_body_size    8m;

    large_client_header_buffers 2 1k;

    # # - Configure Timeouts

    reset_timedout_connection on;

    client_body_timeout 12;

    client_header_timeout   12;

    keepalive_timeout   15;

    keepalive_requests 100;

    send_timeout    10;

    server_tokens   off;

  # # - Dynamic gzip compression
  gzip                      on;
    gzip_http_version         1.1;
    gzip_disable              "msie6";
    gzip_vary                 on;
    gzip_min_length           20;
    gzip_buffers              4 16k;
    gzip_comp_level           4;
    gzip_proxied              any;

    # Turn on gzip for all content types that should benefit from it.

    gzip_types  application/ecmascript;
    gzip_types  application/javascript;
    gzip_types  application/json;
    gzip_types  application/pdf;
    gzip_types  application/postscript;
    gzip_types  application/x-javascript;
    gzip_types  image/svg+xml;
    gzip_types  text/css;
    gzip_types  text/csv;
    gzip_types  text/javascript;
    gzip_types  text/plain;
    gzip_types  text/xml;
    gzip_types  text/json;

  # proxying requests to other servers

    upstream nodebeats {
      server unix:/tmp/nginx.socket fail_timeout=0;
    }

    server {
        listen       <%= ENV['PORT'] %>;
        server_name  _;
        root        "/app/";

    limit_conn conn_limit_per_ip 5;
    limit_req zone=req_limit_per_ip burst=10 nodelay;

    location ~* \.(js|css|jpg|png|ico|json|xml|svg)$ {
      root               "/app/src/dist/";
      add_header         Pragma public;
      add_header         Cache-Control public;
      expires            1y;
      gzip_static        on;
      gzip               off;
      log_not_found      off;
      access_log         off;
    }

    location / {
      proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header   Host $http_host;
      proxy_set_header   Connection "";
      proxy_redirect     off;
      proxy_http_version 1.1;
      proxy_pass         http://nodebeats;
      add_header         Cache-Control no-cache;
      proxy_read_timeout 60s;
    }
}

}


问:
NoSuchMethodError - CDI fireAsync
I am trying to use the new fireAsync Method which comes with CDI 2. I am running on a Wildfly 10.1.0.
I always get an error by calling the fireAsnyc() Method:

```<code>javax.servlet.ServletException
    Caused by: java.lang.NoSuchMethodError: javax.enterprise.event.Event.fireAsync(Ljava/lang/Object;)Ljava/util/concurrent/CompletionStage;
</code>```

This is my code:

```<code>@Inject Event<Customer > customerEvent ;

public String save() {
    Customer customer = new Customer("Max", "Smith");
    customerEvent.fireAsync(customer);
    return "something";
}
</code>```

And my pom.xml:

```<code>    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
</code>```

答: Wildfly 10.1 is using Java EE 7 which ships CDI 1.2/Weld 2.3.  You can upgrade it to CDI 2, there's a patch available if you look at the weld blog</p>

Title: NoSuchMethodError - CDI fireAsync

Body:
I am trying to use the new fireAsync Method which comes with CDI 2. I am running on a Wildfly 10.1.0.
I always get an error by calling the fireAsnyc() Method:

javax.servlet.ServletException
    Caused by: java.lang.NoSuchMethodError: javax.enterprise.event.Event.fireAsync(Ljava/lang/Object;)Ljava/util/concurrent/CompletionStage;

This is my code:

@Inject Event<Customer > customerEvent ;

public String save() {
    Customer customer = new Customer("Max", "Smith");
    customerEvent.fireAsync(customer);
    return "something";
}

And my pom.xml:

    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>


问:
Identifying Form destination (Spreadsheet AND SHEET)
I'm working on a script that interacts with Google Form' response sheet.

```<code>FormApp.getActiveForm().getDestinationId()
</code>```

give me the spreadsheet id, but I don't find a way to get the sheet itself.  User can change its name and position, so I need to get its id, like in

```<code>Sheet.getSheetId()
</code>```

I also have to determine the number of columns the responses uses.  It's not equal to the number of questions in the form.  I can count the number of items in the form:

```<code>Form.getItems().length
</code>```

and then search for gridItems, add the number of rows in each and add them minus one:

```<code>+ gridItem.getRows().length - 1
</code>```

Finally, I think there's no way to relate each question with each column in the sheet, but by comparing somehow columns names with items title.

Thank you

答:
I needed this also, and remarkably there is still no apps script method that facilitates it. In the end I set about finding a reliable way to determine the sheet id, and this is what I ended up with by way of programmatic workaround:

Add a temporary form item with a title that's a random string (or something similarly suitable)

Wait for the new corresponding column to be added to the destination sheet (typically takes a few seconds)

Look though each sheet in the destination until you find this new form item title string in a header row

Delete the temporary form item that was added

Wait for the corresponding column in the sheet to unlink from the form and become deletable (typically takes a few seconds)

Delete the column corresponding to the temporary form item

Return the sheet ID

I'm sure some won't like this approach because it modifies the form and spreadsheet, but it does work well.

With the necessary wait times included it takes about 12 seconds to perform all the look up / clean up operations.

Here's my code for this method in case anyone else might like to use it.

// Takes Apps Script 'Form' object as single paramater
// The second parameter 'obj', is for recursion (do not pass a second parameter)
// Return value is either:
// - null (if the form is not linked to any spreadsheet)
// - sheetId [int]
// An error is thrown if the operations are taking too long

function getFormDestinationSheetId(form, obj) {

  var obj = obj || {}; // Initialise object to be passed between recursions of this function

  obj.attempts = (obj.attempts || 1);

  Logger.log('Attempt #' + obj.attempts);

  if (obj.attempts > 14) {
    throw 'Unable to determine destination sheet id, too many failed attempts, taking too long. Sorry!';
  }

  obj.spreadsheetId = obj.spreadsheetId || form.getDestinationId();

  if (!obj.spreadsheetId) {
    return null; // This means there actually is no spreadsheet destination set at all.

  } else {
    var tempFormItemTitle = '### IF YOU SEE THIS, PLEASE IGNORE! ###';

    if (!obj.tempFormItemId && !obj.sheetId) { // If the sheet id exists from a previous recusion, we're just in a clean up phase
      // Check that temp item does not already exist in form
      form.getItems(FormApp.ItemType.TEXT).map(function(textItem) {
        var textItemTitle = textItem.getTitle();
        Logger.log('Checking against form text item: ' + textItemTitle);
        if (textItemTitle === tempFormItemTitle) {
          obj.tempFormItemId = textItem.getId();
          Logger.log('Found matching form text item reusing item id: ' + obj.tempFormItemId);
        }
        return 0;
      }); // Note: Just using map as handy iterator, don't need to assign the output to anything

      if (!obj.tempFormItemId) {
        Logger.log('Adding temporary item to form');
        obj.tempFormItemId = form.addTextItem().setTitle(tempFormItemTitle).getId();
      }
    }

    obj.spreadsheet = obj.spreadsheet || SpreadsheetApp.openById(obj.spreadsheetId);
    obj.sheets = obj.sheets || obj.spreadsheet.getSheets();
    obj.sheetId = obj.sheetId || null;

    var sheetHeaderRow = null;

    for (var i = 0, x = obj.sheets.length; i < x; i++) {
      sheetHeaderRow = obj.sheets[i].getSheetValues(1, 1, 1, -1)[0];

      for (var j = 0, y = sheetHeaderRow.length; j < y; j++) {
        if (sheetHeaderRow[j] === tempFormItemTitle) {
          obj.sheetId = obj.sheets[i].getSheetId();
          Logger.log('Temporary item title found in header row of sheet id: ' + obj.sheetId);
          break;
        }
      }
      if (obj.sheetId) break;
    }

    // Time to start cleaning things up a bit!
    if (obj.sheetId) {

      if (obj.tempFormItemId) {
        try {
          form.deleteItem(form.getItemById(obj.tempFormItemId));
          obj.tempFormItemId = null;
          Logger.log('Successfully deleted temporary form item');
        } catch (e) {
          Logger.log('Tried to delete temporary form item, but it seems it was already deleted');
        }
      }

      if (obj.sheetId && !obj.tempFormItemId && !obj.tempColumnDeleted) {
        try {
          obj.sheets[i].deleteColumn(j + 1);
          obj.tempColumnDeleted = true;
          Logger.log('Successfully deleted temporary column');
        } catch (e) {
          Logger.log('Could not delete temporary column as it was still attached to the form');
        }
      }

      if (!obj.tempFormItemId && obj.tempColumnDeleted) {
        Logger.log('Completed!');
        return obj.sheetId;
      }
    }

    SpreadsheetApp.flush(); // Just in case this helps!

    // Normally this process takes three passes, and a delay of 4.5 secs seems to make it work in only 3 passes most of the time
    // Perhaps if many people are submitting forms/editing the spreadsheet, this delay would not be long enough, I don't know.
    obj.delay = ((obj.delay || 4500));

    // If this point is reached then we're not quite finished, so try again after a little delay
    Logger.log('Delay before trying again: ' + obj.delay / 1000 + ' secs');
    Utilities.sleep(obj.delay);
    obj.attempts++;

    return getFormDestinationSheetId(form, obj);
  }
}```

Body:
I'm working on a script that interacts with Google Form' response sheet.

FormApp.getActiveForm().getDestinationId()

give me the spreadsheet id, but I don't find a way to get the sheet itself.  User can change its name and position, so I need to get its id, like in

Sheet.getSheetId()

I also have to determine the number of columns the responses uses.  It's not equal to the number of questions in the form.  I can count the number of items in the form:

Form.getItems().length

and then search for gridItems, add the number of rows in each and add them minus one:

+ gridItem.getRows().length - 1

Finally, I think there's no way to relate each question with each column in the sheet, but by comparing somehow columns names with items title.

Thank you


问:
Get class of appended ajax jquery data
```<code><div id="loadhere></div>
</code>```

Ajax snippet

```<code>  $('#loadhere').append('<span id="1" class="trash">     </span>');

$('.trash').click(function(){
   var x=$(this).attr('id');
 });
</code>```

My problem i was not able to get the data of appended jquery data

答:
Element is appended and there needs event delegation

Use .on()

$(document).on("click",".trash",function(){ var x=$(this).attr('id'); });

Title: Get class of appended ajax jquery data

Body:
Ajax snippet

  $('#loadhere').append('     ');

$('.trash').click(function(){
   var x=$(this).attr('id');
 });

My problem i was not able to get the data of appended jquery data


问:
Bitwise operations, bits falling off, fit into 8 bit container
I'm trying to fit 16, 32 and 64-bit values into an 8-bit container

I'm able to shift the bits to where it's only a 8 bits of data for the container, but I do not know how to bring them back to reflect the value. I've been racking my brain all day and I cannot figure it out. Any help would be so amazing. Here's the code I've been experimenting with before I start my lab project because this is the thing that has me confused. How would I store the 8 bits and then go back and be able to pull it back up without the lost bits

```<code>    #include <iostream>
    #include <stdio.h>
    #include <cstdint>

    using namespace std;

    int main()
    {

        const int MAX_SIZE = 1000;
        uint16_t data = 62153;
        uint8_t mem[MAX_SIZE];

        cout << data << endl;

        data = ( data >> 8) & 0xff;
        cout << data << endl;
        data = ( data << 8);
        cout << data << endl;
        return 0;
    }
</code>```

output is:

1111 0010 1100 1001  = 62153

1111 0010 = 242   after bit shift

1111 0010 0000 0000  = 61952 shift back

those bits are gone, how can I save space by breaking up the bits to being able to store them in a smaller container, while still being able to have a function go back and read what the full value was before the shift. This is homework, so I'm not asking for an answer. A push in the right direction would be greatly appreciated.

答:
This should give you a push in A direction. You could also use a stack to achieve something similar. By using a vector you could determine what the output would be by checking the size of the vector. For example if the vector::size() == 2 you know you need to create a new uint16_t. If the vector size is 4 you need a uint32_t etc...

```<code>#include <vector>
#include <cstdint>
#include <iostream>

int main()
{
    std::vector<uint8_t> bytes;

    uint16_t data = 62153;
    uint8_t lsb = data & 0xff;
    uint8_t msb = (data >> 8) & 0xff;

    bytes.push_back(lsb);
    bytes.push_back(msb);

    uint16_t new_data = 0;
    new_data = new_data | (bytes.at(1) << 8);
    new_data = new_data | bytes.at(0);

    std::cout << new_data << std::endl;
    return 0;
}
</code>```

Body:
I'm trying to fit 16, 32 and 64-bit values into an 8-bit container

I'm able to shift the bits to where it's only a 8 bits of data for the container, but I do not know how to bring them back to reflect the value. I've been racking my brain all day and I cannot figure it out. Any help would be so amazing. Here's the code I've been experimenting with before I start my lab project because this is the thing that has me confused. How would I store the 8 bits and then go back and be able to pull it back up without the lost bits

    #include <iostream>
    #include <stdio.h>
    #include <cstdint>

    using namespace std;

    int main()
    {

        const int MAX_SIZE = 1000;
        uint16_t data = 62153;
        uint8_t mem[MAX_SIZE];

        cout << data << endl;

        data = ( data >> 8) & 0xff;
        cout << data << endl;
        data = ( data << 8);
        cout << data << endl;
        return 0;
    }

output is:

1111 0010 1100 1001  = 62153

1111 0010 = 242   after bit shift

1111 0010 0000 0000  = 61952 shift back

those bits are gone, how can I save space by breaking up the bits to being able to store them in a smaller container, while still being able to have a function go back and read what the full value was before the shift. This is homework, so I'm not asking for an answer. A push in the right direction would be greatly appreciated.

Body:
This should give you a push in A direction. You could also use a stack to achieve something similar. By using a vector you could determine what the output would be by checking the size of the vector. For example if the vector::size() == 2 you know you need to create a new uint16_t. If the vector size is 4 you need a uint32_t etc...

#include <vector>
#include <cstdint>
#include <iostream>

int main()
{
    std::vector<uint8_t> bytes;

    uint16_t data = 62153;
    uint8_t lsb = data & 0xff;
    uint8_t msb = (data >> 8) & 0xff;

    bytes.push_back(lsb);
    bytes.push_back(msb);

    uint16_t new_data = 0;
    new_data = new_data | (bytes.at(1) << 8);
    new_data = new_data | bytes.at(0);

    std::cout << new_data << std::endl;
    return 0;
}


问:
How to generate assembly code from C++ source in Visual Studio 2010
I want to generate assembly code from C++ source code using Microsoft VC++ Compiler. I want to do this in the command line itself. Not from the IDE.

What're the commands/options?

答: I believe this is what the /FA switch is for.</p>


问:
Java @Inject null pointer between modules and ServiceLoader
I have three maven modules:

Commons module: common operations

Provider module: specific implementations to extract data.

Main module: make use of the provider modules.

The sequence works like this:

The main module receives a request, and there's an interface which manages providers (Client) and load providers using ServiceLoader.load(Provider.class).

My Client extracts data (client.retrieveData(request)) selecting the adequate provider.

A provider implements a method buildRequest().

And here's my problem: Support classes from commons module are used in the other two modules. I can use all classes I've injected in my main module, but classes injected in a provider module have a null pointer. For example, this is an implementation of a  provider class:

```<code>public class ScholarProvider extends AbstractProvider {

    @Inject
    private DistanceService distance;
    @Inject
    private final Logger log;
    public static final String URL = "https://scholar.google.com";

    private MapperObjectRDF mapper;

    private String[] domains;
    private Person person;

    public ScholarProvider() {
        person = null;
        mapper = null;
    }
}
</code>```

In ScholarProvider—and in any other provider—distance and log are null. I cannot understand where is the problem. Could it be the problem for loading providers through ServiceLoader? Any suggestions what could be the problem? or is there any possible solution that I could use my DistanceService with a new instantiation?

答:
What you're describing is not how CDI works.  In a CDI fashion, you would define each of the classes and give them qualifiers.  Then you would inject them using qualifiers.

So instead of using ServiceLoader.load() you would inject the reference, something like this

```<code>@Inject
@Named("the name")
private Provider provider
</code>```

Body:
I have three maven modules:

Commons module: common operations

Provider module: specific implementations to extract data.

Main module: make use of the provider modules.

The sequence works like this:

The main module receives a request, and there's an interface which manages providers (Client) and load providers using ServiceLoader.load(Provider.class).

My Client extracts data (client.retrieveData(request)) selecting the adequate provider.

A provider implements a method buildRequest().

And here's my problem: Support classes from commons module are used in the other two modules. I can use all classes I've injected in my main module, but classes injected in a provider module have a null pointer. For example, this is an implementation of a  provider class:

public class ScholarProvider extends AbstractProvider {

    @Inject
    private DistanceService distance;
    @Inject
    private final Logger log;
    public static final String URL = "https://scholar.google.com";

    private MapperObjectRDF mapper;

    private String[] domains;
    private Person person;

    public ScholarProvider() {
        person = null;
        mapper = null;
    }
}

In ScholarProvider—and in any other provider—distance and log are null. I cannot understand where is the problem. Could it be the problem for loading providers through ServiceLoader? Any suggestions what could be the problem? or is there any possible solution that I could use my DistanceService with a new instantiation?

Body:
What you're describing is not how CDI works.  In a CDI fashion, you would define each of the classes and give them qualifiers.  Then you would inject them using qualifiers.

So instead of using ServiceLoader.load() you would inject the reference, something like this

@Inject
@Named("the name")
private Provider provider


问:
@PropertySource cannot be opened because it does not exist
I have the problem with configuration file that is located in other directory than my jar file.

I use @PropertySource for loading properties.

```<code>@PropertySource(ignoreResourceNotFound = true, value = "${ext.properties.dir:classpath:}/properties.properties")
</code>```

I try to run jar using following command:

```<code>java -jar import-0.0.1-SNAPSHOT.jar -Dext.properties.dir=file:/C:\Users\Admin\Desktop\
</code>```

The following error pring in logs: Properties location

Properties location
  [${ext.properties.dir:classpath:}/properties.properties] not resolvable:
  class path resource [properties.properties] cannot be opened because it
  does not exist

How can I fix this error?

答:
Spring Boot looks for application.properties on classpath. You don't need an explicit @PropertySource annotation. And @PropertySource doesn't have the capability to resolve SPEL in the path, which should be evident from the error message you're getting.

Use src/main/resources/application.properties. When you want to use the external file, use spring.config.location like @juan-calvopina-m suggested in his answer.

Body:
I have the problem with configuration file that is located in other directory than my jar file.

I use @PropertySource for loading properties.

@PropertySource(ignoreResourceNotFound = true, value = "${ext.properties.dir:classpath:}/properties.properties")

I try to run jar using following command:

java -jar import-0.0.1-SNAPSHOT.jar -Dext.properties.dir=file:/C:\Users\Admin\Desktop\

The following error pring in logs: Properties location

Properties location
  [${ext.properties.dir:classpath:}/properties.properties] not resolvable:
  class path resource [properties.properties] cannot be opened because it
  does not exist

How can I fix this error?


问:
Built in double-asterisk power function not working as expected
This prints -2.4:

```<code>print(-3**0.8)
</code>```

But this prints an imaginary number...?

```<code>a = -3
b = 0.8
print(a**b)
</code>```

I can't figure out what is causing this and this problem is breaking my program. How do you make it so that the second statement outputs the same as the first in a general case that works for positive and negative values for a?

答:
The ** operator has the highest precedence over all other operators. Hence when you use

```<code>print(-3**0.8)
</code>```

python first evaluates the exponential and then negates it.

But when you run

```<code>a = -3
b = 0.8
print(a**b)
</code>```

a has implicitly been negated first. Hence the result is effectively a imaginary number (a negative number raised to a fractional exponent)

To solve your issue, you could do something like

```<code> print (int(a/abs(a))*(abs(a)**b))
</code>```

Body:
This prints -2.4:

print(-3**0.8)

But this prints an imaginary number...?

a = -3
b = 0.8
print(a**b)

I can't figure out what is causing this and this problem is breaking my program. How do you make it so that the second statement outputs the same as the first in a general case that works for positive and negative values for a?

Body:
The ** operator has the highest precedence over all other operators. Hence when you use

print(-3**0.8)

python first evaluates the exponential and then negates it.

But when you run

a = -3
b = 0.8
print(a**b)

a has implicitly been negated first. Hence the result is effectively a imaginary number (a negative number raised to a fractional exponent)

To solve your issue, you could do something like

 print (int(a/abs(a))*(abs(a)**b))


问:
Univocity parser - parse csv row into existing bean instance
I'm trying to parse a csv file into new and existing instances of a bean, using univocity parser. The csv is generated by using univocity BeanWriterProcessor, for a set of beans that I will call set A.

Now I want to read the csv back, doing the following:

Case 1: if the row corresponds to a bean which was originally present in set A, I do not want to create a new bean instance, but instead read the csv into the "existing" instance. (i.e., "update" the instance). I check existence by using the UUID of the bean.

Case 2: if the row does not correspond to a bean originally present in set A, I want to create a new bean instance for it.

Problem I want to solve: for Case 1, how can I write to an existing bean instance?

In supercsv, I could do it with something like that:

```<code>beanReader.read(targetExistingBean, header, processors);
</code>```

How can I do this in univocity?

答:
Currently, the only way to do it would be by overriding the createBean method of BeanProcessor or BeanListProcessor (whichever you are using):

BeanListProcessor<Car> carProcessor = new BeanListProcessor<Car>(Car.class){
    @Override
    public Car createBean(String[] row, Context context) {
        //analyze the row here to determine whether to return an existing instance
        //if you need a new instance, call super.createBean(row, context);
    }
};
```

Hope this helps.

Body:
I'm trying to parse a csv file into new and existing instances of a bean, using univocity parser. The csv is generated by using univocity BeanWriterProcessor, for a set of beans that I will call set A.

Now I want to read the csv back, doing the following:

Case 1: if the row corresponds to a bean which was originally present in set A, I do not want to create a new bean instance, but instead read the csv into the "existing" instance. (i.e., "update" the instance). I check existence by using the UUID of the bean.

Case 2: if the row does not correspond to a bean originally present in set A, I want to create a new bean instance for it.

Problem I want to solve: for Case 1, how can I write to an existing bean instance?

In supercsv, I could do it with something like that:

beanReader.read(targetExistingBean, header, processors);

How can I do this in univocity?

Body:
Currently, the only way to do it would be by overriding the createBean method of BeanProcessor or BeanListProcessor (whichever you are using):

BeanListProcessor<Car> carProcessor = new BeanListProcessor<Car>(Car.class){
    @Override
    public Car createBean(String[] row, Context context) {
        //analyze the row here to determine whether to return an existing instance
        //if you need a new instance, call super.createBean(row, context);
    }
};

Hope this helps.


答:
Here's an alternative with your original text:

```<code>In [893]: text = ',\n                             31.05.2017,\n        20h10\n'

In [898]: text.split(',\n')[1].strip()
Out[898]: '31.05.2017'
</code>```

Split by ,\n and take the first item from that split list, then call str.strip and remove leading whitespaces.

Title: Split elements before the first number

Body:
I have this text appearing after using xpath :

',\n                             31.05.2017,\n        20h10\n'

I have been able to get this by using split(',')[1]:

'\n                             31.05.2017'

However what I want is to only have the date. The thing is the date changes all the time depending on the page I am scraping. So what I need is just to get rid of the /n and the spaces that are before the first number that appears.

If you could help it would be amazing thank you :)

Body:
Here's an alternative with your original text:

In [893]: text = ',\n                             31.05.2017,\n        20h10\n'

In [898]: text.split(',\n')[1].strip()
Out[898]: '31.05.2017'

Split by ,\n and take the first item from that split list, then call str.strip and remove leading whitespaces.


问:
ImportError: cannot import name 'logsumexp' when importing sklearn.model_selection
I was trying to import sklearn.model_selection with Jupiter Notebook under anaconda environment with python 3.5, but I was warned that I didn't have "model_selection" module, so I did conda update scikit-learn.

After that, I received a message of ImportError: cannot import name 'logsumexp' when importing sklearn.model_selection.

I reinstalled sklearn and scipy, but still received the same error message. May I have some advice?

答: Just closed the Spyder editor and restarted. This Issue got fixed.</p>


问:
Debatch the Incoming message and create fixed batch of input messages in the orchestration?
http://blogs.msdn.com/b/brajens/archive/2006/07/20/biztalk-custom-receive-pipeline-component-to-batch-messages.aspx

I am following above article, but i want to implement this in orchestration

How can i implement this please advise, here are the some of thoughts i know.

Using foreach loop.

 a)read each single message and added to
new message until it reaches the
fixed batch

   b) using xpath position  /[local-name()='Root' and
namespace-uri()='http://mycompany.com']/[local-name()='content'
and namespace-uri()='' and position()   >= 0 and position < fixed size] (Which is not working)

Call the Custom pipline component ( like above)

First of all thanks guyz for all your valuable replies,

Right now I implemented this in the orchestration using foreach loop, xpath(toget count and single input node) and Message Variable (Created new unbounded message to assign concatenated fixed no of input messages). It is working fine now.

Do you guyz agree to this appoach or do you have any concerns?

答:
A simple way of achieving high throughput (large messages and/or large amout of messages) is to run the incoming message thru a map in the receive port that uses a custom XSLT. This map will then group the XML in right sized groups - after the mapping the XML could look something like this.

```<code><ns0:sample xmlns:ns0='http://MGSIBREDemo.LoanRequest' xmlns:ns1='http://MGSIBREDemo.LoanRequestGroup'>
 <ns1:group>
  <data1><name>name1</name></data1>
  <data1><name>name2</name></data1>
  <data1><name>name3</name></data1>
  <data1><name>name4</name></data1>
 </ns1:group>
 <ns1:group>
  <data1><name>name5</name></data1>
  <data1><name>name6</name></data1>
  <data1><name>name7</name></data1>
  <data1><name>name8</name></data1>
 </ns1:group>
 <ns1:group>
  <data1><name>name9</name></data1>
  <data1><name>name10</name></data1>
 </ns1:group>
</ns0:sample>
</code>```

After this first step you'll then have to send the message out of BizTalk and receive it back in again. You can then use an ordinary XML dissasebler pipeline component to debatch the message (as for example described here).

The big advantage to this technice is that you'll use an BizTalk map in a port to transform the message and a out of the box pipeline component. Both of these handles the messages in a streaming fasion and you'll be able to handle both big messages and big amout of messages.

The disadvantge is however that it kills the performance as you write message to disk or queue to then read them back in.

It be great if it be possible to debatch on the send side using the XML assembler but this isn't possible today.

So unless you're ok with reading all messages into memory (using XmlDocument), or spending the time to write your own streaming Xml dissasmbler this is the "hack" we're stuck with.

Body:
A simple way of achieving high throughput (large messages and/or large amout of messages) is to run the incoming message thru a map in the receive port that uses a custom XSLT. This map will then group the XML in right sized groups - after the mapping the XML could look something like this.

<ns0:sample xmlns:ns0='http://MGSIBREDemo.LoanRequest' xmlns:ns1='http://MGSIBREDemo.LoanRequestGroup'>
 <ns1:group>
  <data1><name>name1</name></data1>
  <data1><name>name2</name></data1>
  <data1><name>name3</name></data1>
  <data1><name>name4</name></data1>
 </ns1:group>
 <ns1:group>
  <data1><name>name5</name></data1>
  <data1><name>name6</name></data1>
  <data1><name>name7</name></data1>
  <data1><name>name8</name></data1>
 </ns1:group>
 <ns1:group>
  <data1><name>name9</name></data1>
  <data1><name>name10</name></data1>
 </ns1:group>
</ns0:sample>

After this first step you'll then have to send the message out of BizTalk and receive it back in again. You can then use an ordinary XML dissasebler pipeline component to debatch the message (as for example described here).

The big advantage to this technice is that you'll use an BizTalk map in a port to transform the message and a out of the box pipeline component. Both of these handles the messages in a streaming fasion and you'll be able to handle both big messages and big amout of messages.

The disadvantge is however that it kills the performance as you write message to disk or queue to then read them back in.

It be great if it be possible to debatch on the send side using the XML assembler but this isn't possible today.

So unless you're ok with reading all messages into memory (using XmlDocument), or spending the time to write your own streaming Xml dissasmbler this is the "hack" we're stuck with.


问:
CSS not reflecting for php page even though after linking between Head Tags
My CSS is not getting reflected on a PHP page. I am using Xampp server. The display.css file is in my htdocs folder only. Let me know where I am doing wrong.</p>

```<code>    <?php
Php Code
    ?>
    <html>
    </head>
    <link rel="stylesheet" type="text/css" src="display.css" />
    <title>E-Library Display Section</title>
    </head>
    <center><h1>Books Available for Free Download</h1></center>
    <body>
                <div class="wrapper">
                <div class="table">
                <div class="row header">
                        <div class="cell"><Book Name</div>
                        <div class="cell">Book Description</div>
                        <div class="cell">Book Author</div>
                        <div class="cell">Book Language</div>
                        <div class="cell">Download Link</div>
                        <div class="cell">Uploader Name</div>
                        <div class="cell">Uploader Email</div>
                    </div>
                        <tr>
                            <?php
                                while($row = $result->fetch_assoc()) {
                                echo "<tr>";
                                echo "<td>".$row['bookname']."</td>";
                                echo "<td>".$row['bookdesc']."</td>";
                                echo "<td>".$row['bookauthor']."</td>";
                            ?>
    </body>
    </html>
</code>```

答:
In your stylesheet link, change src to href.

```<code><link rel="stylesheet" type="text/css" href="display.css" />
</code>```

Also, you have two closed  tags and no open ones but that's not causing your problem.

Body:
My CSS is not getting reflected on a PHP page. I am using Xampp server. The display.css file is in my htdocs folder only. Let me know where I am doing wrong.

    <?php
Php Code
    ?>

    <link rel="stylesheet" type="text/css" src="display.css" />
    <title>E-Library Display Section</title>

Books Available for Free Download

<Book Name

Book Description

Book Author

Book Language

Download Link

Uploader Name

Uploader Email

                            <?php
                                while($row = $result->fetch_assoc()) {
                                echo "
";
                                echo "".$row['bookname']."	";
                                echo "".$row['bookdesc']."	";
                                echo "".$row['bookauthor']."	";
                            ?>

Body:
In your stylesheet link, change src to href.

<link rel="stylesheet" type="text/css" href="display.css" />

Also, you have two closed </head> tags and no open ones but that's not causing your problem.


问:
How can I show text in the ActionBar in my apps Preference screen?
I am using an Activity and Fragment as a Preferences screen in my app, as per Google's recommended format. I am wondering how I can get the action bar in this activity to say "Settings". Also, how can I include a back arrow to return to the calling activity? Is this a built-in function in Android, or would I need some extra drawable resource for the arrow?

Currently, with the following code I am getting the error android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.Toolbar

Here is my preferences Activity and Fragment:

```<code>public class SettingsActivity extends AppCompatActivity {

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

        //setContentView(R.layout.activity_settings);
        //setupActionBar();

        // Display the fragment as the main content.
        getSupportFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            super.onActivityCreated(savedInstanceState);

            // Load the preferences from an XML resource
            setPreferencesFromResource(R.xml.preferences, rootKey);

            Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
            ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        }
    }

}
</code>```

This is my preferences.xml:

```<code><?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:title="@string/settings_title"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <PreferenceCategory
        android:key="settings_game_mode"
        android:title="@string/settings_game_mode">

        <ListPreference
            android:key="game_mode_list"
            android:title="Select Rule Mode"
            android:summary="%s"
            android:entries="@array/game_mode_list_entries"
            android:entryValues="@array/game_mode_list_entries_values"
            android:defaultValue="FIRST_TO_21" />

    </PreferenceCategory>

</PreferenceScreen>
</code>```

And this is the style that my SettingsActivity is using:

```<code><style name="SettingsTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>
</code>```

答:
Check the documentation here for adding the toolbar: https://developer.android.com/training/appbar/setting-up.html

Then call the horribly named setDisplayShowHomeEnabled and setDisplayHomeAsUpEnabled on the action bar to get it show the back button.

Your standard Activity.setTitle("Settings") will show the string "Settings" in the toolbar.

Hope that helps!

Body:
I am using an Activity and Fragment as a Preferences screen in my app, as per Google's recommended format. I am wondering how I can get the action bar in this activity to say "Settings". Also, how can I include a back arrow to return to the calling activity? Is this a built-in function in Android, or would I need some extra drawable resource for the arrow?

Currently, with the following code I am getting the error android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.Toolbar

Here is my preferences Activity and Fragment:

public class SettingsActivity extends AppCompatActivity {

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

        //setContentView(R.layout.activity_settings);
        //setupActionBar();

        // Display the fragment as the main content.
        getSupportFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            super.onActivityCreated(savedInstanceState);

            // Load the preferences from an XML resource
            setPreferencesFromResource(R.xml.preferences, rootKey);

            Toolbar toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
            ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        }
    }

}

This is my preferences.xml:

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:title="@string/settings_title"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <PreferenceCategory
        android:key="settings_game_mode"
        android:title="@string/settings_game_mode">

        <ListPreference
            android:key="game_mode_list"
            android:title="Select Rule Mode"
            android:summary="%s"
            android:entries="@array/game_mode_list_entries"
            android:entryValues="@array/game_mode_list_entries_values"
            android:defaultValue="FIRST_TO_21" />

    </PreferenceCategory>

</PreferenceScreen>

And this is the style that my SettingsActivity is using:


问:
Angular 2 dependencies
Please consider this dependencies in package.json:

```<code>"dependencies": {
                  "@angular/common": "2.2.1",
                  "@angular/compiler": "2.2.1",
                  "@angular/core": "2.2.1",
                  "@angular/forms": "2.2.1",
                  "@angular/http": "2.2.1",
                  "@angular/platform-browser": "2.2.1",
                  "@angular/platform-browser-dynamic": "2.2.1",
                  "@angular/router": "3.2.1",
                  "@angular/upgrade": "2.2.1"
                }
</code>```

I want to use the bundle version of Angulajs and when I run this command:

npm install angular

It installs angular.min.js I want to know what is the difference between Those? Is there any way to bundle dependencies using npm and create a single file?

Another question is I know that Angular 4 has been released and when I run this command:

npm install angular

It installs angular.min.js with version v1.6.4 so what is this file? And why it outdated?

答:
As Manubhargav mentioned, when you run npm install angular, AngularJS (v1.x) will be installed.

To install the latest version of angular 2 use npm install angular-2 --save.
 This command will update the package.json and package-lock.json files and add angular-2 dependency to them.

Note: If you got typings install error, install it by npm: npm install typings --global

To install the latest version of angular 4 you can use one of these 2 methods:

Using angular CLI:

Install Angular CLI: npm install -g @angular/cli

Create a new project: ng new my-app

Serve the application: Go to the project directory and launch the server.       cd my-app
ng serve --open

Manual setup using Seed Project:

Clone seed project from github: git clone https://github.com/Plum-Crazy/angular-seed

Run the application: Go to the project directory and launch the server.       cd angular-seed
npm install
npm run

Once the project is built, it will be available at http://localhost:3000/

Title: Angular 2 dependencies

Body:
Please consider this dependencies in package.json:

"dependencies": {
                  "@angular/common": "2.2.1",
                  "@angular/compiler": "2.2.1",
                  "@angular/core": "2.2.1",
                  "@angular/forms": "2.2.1",
                  "@angular/http": "2.2.1",
                  "@angular/platform-browser": "2.2.1",
                  "@angular/platform-browser-dynamic": "2.2.1",
                  "@angular/router": "3.2.1",
                  "@angular/upgrade": "2.2.1"
                }

I want to use the bundle version of Angulajs and when I run this command:

npm install angular

It installs angular.min.js I want to know what is the difference between Those? Is there any way to bundle dependencies using npm and create a single file?

Another question is I know that Angular 4 has been released and when I run this command:

npm install angular

It installs angular.min.js with version v1.6.4 so what is this file? And why it outdated?


问:
Deploying django(python) project with mod_wsgi
I am new to django and mod_wsgi, when I was trying to deploy a django project(in python) demo on Apache using mod_wsgi, I encountered some problem as following:

When the demo runs on django's built-in webserver with command 'python manage.py runserver',  everything looks normal like Running on built-in server

while when running on Apache/mod_wsgi with command 'mod_wsgi-express start-server wsgi.py' , it looks like this:
Running on Apache/mod-wsgi

I have no idea which part of my code or configuration goes wrong, could anyone help me out?

答:
This is because runserver serves css files for you. But in production you need to set up Apache to serve your static folder. Add alias to your apache config, e.g.

```<code>Alias /static /path/to/static_folder
</code>```

Read more on managing static files.

Body:
This is because runserver serves css files for you. But in production you need to set up Apache to serve your static folder. Add alias to your apache config, e.g.

Alias /static /path/to/static_folder

Read more on managing static files.


问:
Python/Django excel to html
Okay, so what I want to do is upload an excel sheet and display it on my website, in html. What are my options here ? I've found this xlrd module that allows you to read the data from spreadsheets, but I don't really need that right now.</p>

答:
Why don't you need xlrd? It sounds like exactly what you need.

Create a Django model with a FileField that holds the spreadsheet. Then your view uses xlrd to loop over the rows and columns and put them into an HTML table. Job done.

Possible complications: multiple sheets in one Excel file; formulas; styles.

Title: Python/Django excel to html