问:
How to redirect properly
I´m trying to redirect with rewrite rules in Apache .htaccess.
I want to redirect 360invest.pl to 360investment.pl.

But I want one more address on the server which I do NOT want to be redirected. If somebody tries 360invest.pl/bezrzecze it should not redirect to 360investment.pl.

I used this code:

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^360invest.pl/bezrzecze$ [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [OR,NC]
RewriteCond %{HTTP_HOST} ^360invest.pl$ [NC]
RewriteRule ^ http://www.360investment.pl%{REQUEST_URI} [L,R=301]
</code>```

This works only if you try www.360invest.pl/bezrzecze. It doesn't work if you try http://360invest.pl/bezrzecze.

In addition if you click any link on the website (www.360invest.pl/bezrzecze) it will redirect you to www.360investment.pl - it should not.

I'm not sure what I'm missing here. Thank you for your help.

答:
What you are doing is really messy. The first condition does not make sense, because "360invest.pl/bezrzecze" is not a domain name. It is a domain name and a path. The following conditions with [OR] flags make no sense to me.

Think about what you want to accomplish. Start with the general case, then list your exceptions:

If someone goes to 360invest.pl you want to redirect all urls to 360investment.pl

unless someone goes to the path bezrzecze

The first part is the rule. The second part is a condition that has to be met

```<code>RewriteCond %{REQUEST_URI} !^/bezrzecze
RewriteRule ^ http://www.360investment.pl%{REQUEST_URI} [L,R]
</code>```

Title: How to redirect properly

Body:
I´m trying to redirect with rewrite rules in Apache .htaccess.
I want to redirect 360invest.pl to 360investment.pl.

But I want one more address on the server which I do NOT want to be redirected. If somebody tries 360invest.pl/bezrzecze it should not redirect to 360investment.pl.

I used this code:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^360invest.pl/bezrzecze$ [NC]
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [OR,NC]
RewriteCond %{HTTP_HOST} ^360invest.pl$ [NC]
RewriteRule ^ http://www.360investment.pl%{REQUEST_URI} [L,R=301]

This works only if you try www.360invest.pl/bezrzecze. It doesn't work if you try http://360invest.pl/bezrzecze.

In addition if you click any link on the website (www.360invest.pl/bezrzecze) it will redirect you to www.360investment.pl - it should not.

I'm not sure what I'm missing here. Thank you for your help.

Body:
What you are doing is really messy. The first condition does not make sense, because "360invest.pl/bezrzecze" is not a domain name. It is a domain name and a path. The following conditions with [OR] flags make no sense to me.

Think about what you want to accomplish. Start with the general case, then list your exceptions:

If someone goes to 360invest.pl you want to redirect all urls to 360investment.pl

unless someone goes to the path bezrzecze

The first part is the rule. The second part is a condition that has to be met

RewriteCond %{REQUEST_URI} !^/bezrzecze
RewriteRule ^ http://www.360investment.pl%{REQUEST_URI} [L,R]


来源: stackexchange

问:
Css div selector multiple classes
I am working on a wordpress theme and I have a this code in HTML:

```<code><body>
        <div class="container-fluid mytheme-container" >
        <div class="container-fluid col-lg-offset-5 col-lg-7 404page">
                    <p id="404">404</p>
                    <p id="page-not-found">Page not found... :(</p>
        </div>
        </div>
</body>
</code>```

I want to add height to the last div and I thought my css in this way:

```<code>body > div.container-fluid.mytheme-container > div.container-fluid.col-lg-offset-5.col-lg-7.404page {
    height: 100vmin;
}
</code>```

That doesn't work, just if I let the selector like this:

```<code>body > div.container-fluid.mytheme-container > div {

}
</code>```

But I think that this will apply to every child of mytheme-container  and I don't want that. So, how can I get the selector for that div ( 404page ) in a more specific way than the last one?

答:
Technically you can have classes starting with digits and selectors for them, but you have to escape digits for selector. Also it's possible to add other characters (e.g. !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, {, |, }, and ~) but they need to be escaped. Here is demo

div {
  width: 200px;
  height: 200px;
  background-color: tomato;
}

/* escaped selector */
#\34 04 {
  border: 5px solid lime;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="404"></div></code>```

More info about this. Also CSS escaping online.

But of cource this doesn't look maintainable and I would recommend you to consider changing you identifiers starting with letter (or at least hyphen or underscore).

ContentLicense: CC BY-SA 3.0

Title: Css div selector multiple classes

Body:
I am working on a wordpress theme and I have a this code in HTML:

404

Page not found... :(

I want to add height to the last div and I thought my css in this way:

body > div.container-fluid.mytheme-container > div.container-fluid.col-lg-offset-5.col-lg-7.404page {
    height: 100vmin;
}

That doesn't work, just if I let the selector like this:

body > div.container-fluid.mytheme-container > div {

}

But I think that this will apply to every child of mytheme-container  and I don't want that. So, how can I get the selector for that div ( 404page ) in a more specific way than the last one?

Body:
Technically you can have classes starting with digits and selectors for them, but you have to escape digits for selector. Also it's possible to add other characters (e.g. !, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \, ], ^, {, |, }, and ~) but they need to be escaped. Here is demo

div {
  width: 200px;
  height: 200px;
  background-color: tomato;
}

/* escaped selector */
#\34 04 {
  border: 5px solid lime;
}

<div id="404"></div>

More info about this. Also CSS escaping online.

But of cource this doesn't look maintainable and I would recommend you to consider changing you identifiers starting with letter (or at least hyphen or underscore).


问:
is it ok to instantiate lists in my domain object's constructor when using nhibernate?
i have an object that have many properties that are lists.  to avoid having to do null checks everywhere before i call Add, Count, Clear, etc  . . . i thought it would be better to new up all the lists upfront

so inside by Resource object in this case, i have the following code:

```<code>    public Resource()
    {
        Regions = new List<Region>();
        Directs = new List<Direct>();
    }

   public virtual IList<Direct> Directs { get; set; }
   public virtual IList<Region> Region{ get; set; }
</code>```

i do get the warning in Visual Studio saying calling virtual methods in the constructor

is there anything wrong or any risk to the code above when using nhibernate ?? if it is wrong, is there a better way of achieving this goal?

答: There's nothing wrong with it. The warning is only there because the properties could be overridden in a derived class as far as I know. But yeah, no problem instantiating in the constructor.</p>

ContentLicense: CC BY-SA 2.5

Body:
i have an object that have many properties that are lists.  to avoid having to do null checks everywhere before i call Add, Count, Clear, etc  . . . i thought it would be better to new up all the lists upfront

so inside by Resource object in this case, i have the following code:

    public Resource()
    {
        Regions = new List<Region>();
        Directs = new List<Direct>();
    }

   public virtual IList<Direct> Directs { get; set; }
   public virtual IList<Region> Region{ get; set; }

i do get the warning in Visual Studio saying calling virtual methods in the constructor

is there anything wrong or any risk to the code above when using nhibernate ?? if it is wrong, is there a better way of achieving this goal?


问:
libisabelle with existing Isabelle installation
I want to use libisabelle to invoke Isabelle from Scala. However, by default (i.e., using the invocation as described in the tutorial), libisabelle will download a fresh Isabelle installation.

I wish to use an existing (read-only) Isabelle configuration instead. I tried the following:

```<code>val path = "/opt/Isabelle2016-1"
val setup = Setup.detect(Platform.genericPlatform(new File(path).toPath), Version.Stable("2016-1")).right.get
val resources = Resources.dumpIsabelleResources().right.get
val environment = Await.result(setup.makeEnvironment(resources), Duration.Inf)
val config = Configuration.simple("Example")
System.build(environment,config)
val system = System.create(environment,config)
</code>```

I am not sure whether this is how I am supposed to set things up, but in any case, it does not work:

```<code>java.nio.file.AccessDeniedException: /opt/Isabelle2016-1/.lock
</code>```

So libisabelle wants to write to the Isabelle installation. I want the code to work even with a read-only installation.

How can I get libisabelle to work in the above situation?

答:
Setup.detect will attempt to lock the installation such that no two processes can write into them at the same time.

Using a genericPlatform probably doesn't do what you think, because the path you pass there will be used for everything that libisabelle obtains from or writes to disk, including resources.

Luckily, instantiation a Setup manually is quite simple:

```<code>val setup = Setup(
  Paths.get("/opt/Isabelle2016-1"),
  Platform.guess.get,
  Version.Stable("2016-1")
)
</code>```

With that incantation, you'll use the global installation in /opt/Isabelle2016-1, but nothing is written there. $ISABELLE_HOME_USER etc. will point towards ~/.local/share/libisabelle on Linux.

Body:
I want to use libisabelle to invoke Isabelle from Scala. However, by default (i.e., using the invocation as described in the tutorial), libisabelle will download a fresh Isabelle installation.

I wish to use an existing (read-only) Isabelle configuration instead. I tried the following:

val path = "/opt/Isabelle2016-1"
val setup = Setup.detect(Platform.genericPlatform(new File(path).toPath), Version.Stable("2016-1")).right.get
val resources = Resources.dumpIsabelleResources().right.get
val environment = Await.result(setup.makeEnvironment(resources), Duration.Inf)
val config = Configuration.simple("Example")
System.build(environment,config)
val system = System.create(environment,config)

I am not sure whether this is how I am supposed to set things up, but in any case, it does not work:

java.nio.file.AccessDeniedException: /opt/Isabelle2016-1/.lock

So libisabelle wants to write to the Isabelle installation. I want the code to work even with a read-only installation.

How can I get libisabelle to work in the above situation?

Body:
Setup.detect will attempt to lock the installation such that no two processes can write into them at the same time.

Using a genericPlatform probably doesn't do what you think, because the path you pass there will be used for everything that libisabelle obtains from or writes to disk, including resources.

Luckily, instantiation a Setup manually is quite simple:

val setup = Setup(
  Paths.get("/opt/Isabelle2016-1"),
  Platform.guess.get,
  Version.Stable("2016-1")
)

With that incantation, you'll use the global installation in /opt/Isabelle2016-1, but nothing is written there. $ISABELLE_HOME_USER etc. will point towards ~/.local/share/libisabelle on Linux.


答:
you Should not start class with number.if insert a litter with first 404page like a404page your code works.

body > div.container-fluid.mytheme-container > div.container-fluid.col-lg-offset-5.col-lg-7.a404page {
    background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <div class="container-fluid mytheme-container" >
        <div class="container-fluid col-lg-offset-5 col-lg-7 a404page">
                    <p id="404">404</p>
                    <p id="page-not-found">Page not found... :(</p>
        </div>
        </div></code>```

Title: Css div selector multiple classes

Body:
you Should not start class with number.if insert a litter with first 404page like a404page your code works.

body > div.container-fluid.mytheme-container > div.container-fluid.col-lg-offset-5.col-lg-7.a404page {
    background: red;
}

        <div class="container-fluid mytheme-container" >
        <div class="container-fluid col-lg-offset-5 col-lg-7 a404page">
                    <p id="404">404</p>
                    <p id="page-not-found">Page not found... :(</p>
        </div>
        </div>


问:
Why isnt my jquery working when i echo it out with php
I am trying to echo out to easily change videos and load it up so i can work with it and this is the code for the jquery to echo out

```<code><script type="text/javascript">
  <?php
    $latest = 1;
    include_once 'dbh.inc.php';
    $sql = "SELECT * FROM videos";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) > 0) {
      while ($row = mysqli_fetch_assoc($result)) {
        echo '

          $("' . $row['vid_class'] . '").click(function() {
          $(".video-display iframe").attr("src", "' . $row['vid_link'] . '");
          $(".video-display").toggle();
       });';
      }
    }
  ?>
</script>
</code>```

this is what it will echo out and it doesn't run

```<code><script type="text/javascript">
$("into-the-unknown").click(function() {
  $(".video-display iframe").attr("src", "https://www.youtube.com/embed/DkGKLhDUN4g?rel=0&showinfo=0&autoplay=1");
  $(".video-display").toggle();
});

$("wwoman").click(function() {
  $(".video-display iframe").attr("src", "https://www.youtube.com/embed/VSB4wGIdDwo?rel=0&showinfo=0&autoplay=1");
  $(".video-display").toggle();
});
</script>
</code>```

And it is called after the jquery tag to make it work just above the body

答:
You have forgotten the jQuery selectors: . or #

I'm not really sure how you are trying to grab the elements: by id or by class.
One thing for sure is that you are trying either one of these and you are grabbing by tag-name only.

Try changing the

```<code>$("' . $row['vid_class'] . '").click(function()
</code>```

to

```<code>$(."' . $row['vid_class'] . '").click(function() //If you are using class
</code>```

or

```<code>$(#"' . $row['vid_class'] . '").click(function() //If you are using id
</code>```

wherever it is applicable.

Hope this helps!

Body:
I am trying to echo out to easily change videos and load it up so i can work with it and this is the code for the jquery to echo out

this is what it will echo out and it doesn't run

And it is called after the jquery tag to make it work just above the body

Body:
You have forgotten the jQuery selectors: . or #

I'm not really sure how you are trying to grab the elements: by id or by class.
One thing for sure is that you are trying either one of these and you are grabbing by tag-name only.

Try changing the

$("' . $row['vid_class'] . '").click(function()

to

$(."' . $row['vid_class'] . '").click(function() //If you are using class

or

$(#"' . $row['vid_class'] . '").click(function() //If you are using id

wherever it is applicable.

Hope this helps!


问:
Reference an existing Azure Automation Account in a different Resource Group
I need to use an existing Azure Automation Account in ARM Templates to create a new compilation job. I know how to do this when the Automation Account is in the same Resource Group where I'm deploying, but I can't figure it out when it's an existing Automation Account in a different Resource Group.

for example:

Parent Template (Resource)

{
  "name": "dscCompile",
  "type": "Microsoft.Resources/deployments",
  "apiVersion": "2016-09-01",
  "dependsOn": [
    "[resourceId('Microsoft.Resources/deployments', 'newGuid')]"
  ],
  "properties": {
    "mode": "Incremental",
    "templateLink": {
      "uri": "[variables('templates').dsc]",
      "contentVersion": "1.0.0.0"
    },
    "parameters": {
      "compile-settings": {
        "value": {
          "configurationData": "[concat('{\"AllNodes\": [{\"NodeName\":\"*\",\"PSDscAllowPlainTextPassword\":true,\"RetryIntervalSec\":30,\"RetryCount\":20},{\"Nodename\":\"localhost\",\"domainName\":\"', parameters('extn-settings').domain, '\",\"adminCreds\":\"', parameters('adminPassword'), '\",\"Role\":\"DC\"}]}')]",
          "configurationName": "createPDC",
          "location": "Australia Southeast",
          "name": "[reference('newGuid').outputs.guid.value)]"
        }
      },
      "tag-values": {
        "value": "[parameters('tag-values')]"
      }
    }
 }```
</div>
</div>
</p>

<p><strong>Child Template</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "compile-settings": {
            "type": "object",
            "metadata": {
                "description": "These are settings for a DSC Compile"
            }
        },
        "tag-values": {
            "type": "object",
            "metadata": {
                "description": "These are the Tag values"
            }
        }
    },
    "resources": [
        {
            "name": "[parameters('compile-settings').jobGuid]",
            "type": "Microsoft.Automation/automationAccounts/compilationjobs",
            "apiVersion": "2015-10-31",
            "location": "[parameters('compile-settings').location]",
            "tags": "[parameters('tag-values')]",
            "dependsOn": [],
            "properties": {
                "configuration": {
                    "name": "[parameters('compile-settings').configurationName]"
                },
                "parameters": {
                    "ConfigurationData": "[parameters('compile-settings').ConfigurationData]"
                }
            },
            "resources": []
        }
    ],
    "outputs": {}
}</code>```

Thanks in advance!

答:
Okay, so this wasn't even possible until recently, you can do it with cross resource group deployment.

Basically, you create a template inside a template (aka nested\child template) and pick a different resource group (using the resourceGroup property for that template. no other way.

```<code>{
    "apiVersion": "2017-05-10",
    "name": "nestedTemplate",
    "type": "Microsoft.Resources/deployments",
    "resourceGroup": "crossResourceGroupDeployment",
    "properties": { }
}
</code>```

Body:
I need to use an existing Azure Automation Account in ARM Templates to create a new compilation job. I know how to do this when the Automation Account is in the same Resource Group where I'm deploying, but I can't figure it out when it's an existing Automation Account in a different Resource Group.

for example:

Parent Template (Resource)

{
  "name": "dscCompile",
  "type": "Microsoft.Resources/deployments",
  "apiVersion": "2016-09-01",
  "dependsOn": [
    "[resourceId('Microsoft.Resources/deployments', 'newGuid')]"
  ],
  "properties": {
    "mode": "Incremental",
    "templateLink": {
      "uri": "[variables('templates').dsc]",
      "contentVersion": "1.0.0.0"
    },
    "parameters": {
      "compile-settings": {
        "value": {
          "configurationData": "[concat('{\"AllNodes\": [{\"NodeName\":\"*\",\"PSDscAllowPlainTextPassword\":true,\"RetryIntervalSec\":30,\"RetryCount\":20},{\"Nodename\":\"localhost\",\"domainName\":\"', parameters('extn-settings').domain, '\",\"adminCreds\":\"', parameters('adminPassword'), '\",\"Role\":\"DC\"}]}')]",
          "configurationName": "createPDC",
          "location": "Australia Southeast",
          "name": "[reference('newGuid').outputs.guid.value)]"
        }
      },
      "tag-values": {
        "value": "[parameters('tag-values')]"
      }
    }
 }

Child Template

$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "compile-settings": {
            "type": "object",
            "metadata": {
                "description": "These are settings for a DSC Compile"
            }
        },
        "tag-values": {
            "type": "object",
            "metadata": {
                "description": "These are the Tag values"
            }
        }
    },
    "resources": [
        {
            "name": "[parameters('compile-settings').jobGuid]",
            "type": "Microsoft.Automation/automationAccounts/compilationjobs",
            "apiVersion": "2015-10-31",
            "location": "[parameters('compile-settings').location]",
            "tags": "[parameters('tag-values')]",
            "dependsOn": [],
            "properties": {
                "configuration": {
                    "name": "[parameters('compile-settings').configurationName]"
                },
                "parameters": {
                    "ConfigurationData": "[parameters('compile-settings').ConfigurationData]"
                }
            },
            "resources": []
        }
    ],
    "outputs": {}
}

Thanks in advance!

Body:
Okay, so this wasn't even possible until recently, you can do it with cross resource group deployment.

Basically, you create a template inside a template (aka nested\child template) and pick a different resource group (using the resourceGroup property for that template. no other way.

{
    "apiVersion": "2017-05-10",
    "name": "nestedTemplate",
    "type": "Microsoft.Resources/deployments",
    "resourceGroup": "crossResourceGroupDeployment",
    "properties": { }
}


问:
How to load native library conditionally based on CPU architecture in android
In my app I am using a set of native library .And those library are available for different CPU architecture. But the problem is all those library are taking almost 87% of the apk size .

I want to reduce apk size for downloading, hence I want make conditional apk based of CPU architecture. How can I do it ?

答:
Use AbiSplitOptions.

Example:

```<code>android {
    ...
  splits {

    // Configures multiple APKs based on ABI.
    abi {

    // Enables building multiple APKs.
    enable true

    // By default all ABIs are included, so use reset() and include to specify that we only
    // want APKs for x86, armeabi-v7a, and mips.
    reset()

    // Specifies a list of ABIs that Gradle should create APKs for.
    include "x86", "armeabi-v7a", "mips"

    // Specify that we want to also generate a universal APK that includes all ABIs.
    universalApk true
    }
  }
}
</code>```

Body:
Use AbiSplitOptions.

Example:

android {
    ...
  splits {

    // Configures multiple APKs based on ABI.
    abi {

    // Enables building multiple APKs.
    enable true

    // By default all ABIs are included, so use reset() and include to specify that we only
    // want APKs for x86, armeabi-v7a, and mips.
    reset()

    // Specifies a list of ABIs that Gradle should create APKs for.
    include "x86", "armeabi-v7a", "mips"

    // Specify that we want to also generate a universal APK that includes all ABIs.
    universalApk true
    }
  }
}


问:
angular 2 function continue before return data from API
I have a problem in Angular 2 that function continue work and does not waiting getting data from API.

HTTPHelper Class

```<code>import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { ReturnResultViewModel } from './ReturnResultViewModel';

export class HttpHelpers {

     _result: any = null;
     _errormsg: any = null;
     _returnResultViewModel: ReturnResultViewModel;

     constructor(private http: Http) {
         this._returnResultViewModel = new ReturnResultViewModel();
    }

    postaction(param: any, path: string) {
        let body = JSON.stringify(param);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(path, body, options)
            .map((m:Response) =>  m.json())
    }
}
</code>```

HomeUserService Class

```<code>import 'rxjs/add/operator/map';
import { HttpHelpers } from '../../../HttpHelpers';
import { usersHome } from "././Home.users.ViewModel";
import { ReturnResultViewModel } from "../../../ReturnResultViewModel";

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
Injectable()

export class HomeUsersService extends HttpHelpers {
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor( @Inject(Http) private _http: Http) {
        super(_http);
    }
    private _usersHome: usersHome[];
    getAllUsers(): usersHome[]{

        alert(2);
         this.postaction(null, this._UrlLogin)
            .subscribe(result =>
                this._returnResultViewModel = result);

         if (this._returnResultViewModel == null)
         {
             alert("NULL");
             return null;
         }
         else {
             alert("Has DATA");
             this._usersHome = this._returnResultViewModel.result;
             alert(this._usersHome.length)
             return this._usersHome;
         }

    }
}
</code>```

HomeUserComponent Class

```<code>export class HomeUserComponent implements OnInit{

    _usersHome: [usersHome];
    constructor( private _homeUsersService: HomeUsersService, private _router: Router) {}

   ngOnInit() {
        alert(1);
        var x =  this._homeUsersService.getAllUsers();
   }
}
</code>```

答:
You should avoid calling subscribe in your service, unless necessary. Let your service do all the logic manipulation, and only do a subscribe in your component.

In your service, change your .subscribe to .map:

```<code>export class HomeUsersService extends HttpHelpers {
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor(@Inject(Http) private _http: Http) {
        super(_http);
    }

    private _usersHome: usersHome[];

    getAllUsers(): usersHome[] {

        alert(2);
        this.postaction(null, this._UrlLogin)
            .map(result => {
                if (result === null) {
                    alert("NULL");
                    return null;
                } else {
                    alert("HAS DATA");
                    this._usersHome = result.result;
                    alert(this._usersHome.length);
                    return this._usersHome;
                }
            });
    }
}
</code>```

Now, since your service returns a correctly mapped Observables, you can handle the rest in your component:

```<code>export class HomeUserComponent implements OnInit {

    _usersHome: [usersHome];

    constructor(private _homeUsersService: HomeUsersService, private _router: Router) {
    }

    ngOnInit() {
        alert(1);
        this._homeUsersService.getAllUsers()
            .subscribe(users => {
                //do something to your users.
                let x = users;
            });
    }
}
</code>```

Body:
I have a problem in Angular 2 that function continue work and does not waiting getting data from API.

HTTPHelper Class

import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { ReturnResultViewModel } from './ReturnResultViewModel';

export class HttpHelpers {

     _result: any = null;
     _errormsg: any = null;
     _returnResultViewModel: ReturnResultViewModel;

     constructor(private http: Http) {
         this._returnResultViewModel = new ReturnResultViewModel();
    }

    postaction(param: any, path: string) {
        let body = JSON.stringify(param);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(path, body, options)
            .map((m:Response) =>  m.json())
    }
}

HomeUserService Class

import 'rxjs/add/operator/map';
import { HttpHelpers } from '../../../HttpHelpers';
import { usersHome } from "././Home.users.ViewModel";
import { ReturnResultViewModel } from "../../../ReturnResultViewModel";

import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
Injectable()

export class HomeUsersService extends HttpHelpers {
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor( @Inject(Http) private _http: Http) {
        super(_http);
    }
    private _usersHome: usersHome[];
    getAllUsers(): usersHome[]{

        alert(2);
         this.postaction(null, this._UrlLogin)
            .subscribe(result =>
                this._returnResultViewModel = result);

         if (this._returnResultViewModel == null)
         {
             alert("NULL");
             return null;
         }
         else {
             alert("Has DATA");
             this._usersHome = this._returnResultViewModel.result;
             alert(this._usersHome.length)
             return this._usersHome;
         }

    }
}

HomeUserComponent Class

export class HomeUserComponent implements OnInit{

    _usersHome: [usersHome];
    constructor( private _homeUsersService: HomeUsersService, private _router: Router) {}

   ngOnInit() {
        alert(1);
        var x =  this._homeUsersService.getAllUsers();
   }
}

Body:
You should avoid calling subscribe in your service, unless necessary. Let your service do all the logic manipulation, and only do a subscribe in your component.

In your service, change your .subscribe to .map:

export class HomeUsersService extends HttpHelpers {
    private _UrlLogin: string = "Accounts/getAllUsers";

    constructor(@Inject(Http) private _http: Http) {
        super(_http);
    }

    private _usersHome: usersHome[];

    getAllUsers(): usersHome[] {

        alert(2);
        this.postaction(null, this._UrlLogin)
            .map(result => {
                if (result === null) {
                    alert("NULL");
                    return null;
                } else {
                    alert("HAS DATA");
                    this._usersHome = result.result;
                    alert(this._usersHome.length);
                    return this._usersHome;
                }
            });
    }
}

Now, since your service returns a correctly mapped Observables, you can handle the rest in your component:

export class HomeUserComponent implements OnInit {

    _usersHome: [usersHome];

    constructor(private _homeUsersService: HomeUsersService, private _router: Router) {
    }

    ngOnInit() {
        alert(1);
        this._homeUsersService.getAllUsers()
            .subscribe(users => {
                //do something to your users.
                let x = users;
            });
    }
}


问:
Jenkins error: "ERROR: Unable to install JDK unless a valid username/password is provided."
I have added a new slave to my jenkins server, the connection itself seemed to go successfully via ssh, however when I try to build on that server the Job tries to download Java on the slave(even though java is all-ready installed on that server) and im getting the following Error:

Downloading JDK from http://download.oracle.com/otn/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-linux-x64.tar.gz
  Your Oracle account doesn't appear valid. Please specify a valid username/password
  ERROR: Unable to install JDK unless a valid username/password is provided.
  Finished: FAILURE

This is the output of java -version

openjdk version "1.8.0_131"
  OpenJDK Runtime Environment (build 1.8.0_131-b12)
  OpenJDK 64-Bit Server VM (build 25.131-b12, mixed mode)

what do I need to do here? reinstall java manually?

答: Just set the JAVA_HOME in your Jenkins slave so it doesn't try to install another Java. </p>


问:
Create list with unique id in Java and manipulate it
I want to create a programm that creates a list that looks like this

```<code>ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example
</code>```

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2

答:
you can create class like this

```<code>public class Record{
    private int id;
    private String name;
    private String Surname;
    private String email;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSurname() {
        return Surname;
    }

    public void setSurname(String surname) {
        Surname = surname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</code>```

and then use it like this:

```<code>    Record record1 = new Record();
    record1.setId(1);
    record1.setName("example");
    record1.setSurname("example");
    record1.setEmail("example");

    Record record2 = new Record();
    record2.setId(2);
    record2.setName("example");
    record2.setSurname("example");
    record2.setEmail("example");

    Map<Integer,Record> recordMap = new HashMap<Integer, Record>();
    recordMap.put(record1.getId(),record1);
    recordMap.put(record2.getId(),record2);]

    recordMap.get(2).getName();//example
    recordMap.get(2).setName("ebi");
    recordMap.get(2).getName();//ebi
</code>```

Body:
I want to create a programm that creates a list that looks like this

ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2

Body:
you can create class like this

public class Record{
    private int id;
    private String name;
    private String Surname;
    private String email;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSurname() {
        return Surname;
    }

    public void setSurname(String surname) {
        Surname = surname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

and then use it like this:

    Record record1 = new Record();
    record1.setId(1);
    record1.setName("example");
    record1.setSurname("example");
    record1.setEmail("example");

    Record record2 = new Record();
    record2.setId(2);
    record2.setName("example");
    record2.setSurname("example");
    record2.setEmail("example");

    Map<Integer,Record> recordMap = new HashMap<Integer, Record>();
    recordMap.put(record1.getId(),record1);
    recordMap.put(record2.getId(),record2);]

    recordMap.get(2).getName();//example
    recordMap.get(2).setName("ebi");
    recordMap.get(2).getName();//ebi


问:
Maximum 20 cookie per domain - Why?
I've just come across an interesting fact, apparently a website can have up to 20 seperate cookies.

Ok - fair enough.

But why on earth would you store more than say "UserID", and why would you possibly need 20 cookies?

答:
A site can have multiple pages, and a lot of those pages may have some information that might in turn be stored in cookies. It is ironic that you ask WHY you may want to use a lot of cookies where as I have seen a lot of people complaining why ONLY 20!!!

It is a good practice to ensure that you DO NOT create a lot of cookies, simply because IE has 20 cookie limit. Other browsers may have more [or less]!

Title: Maximum 20 cookie per domain - Why?


问:
Storing NSDate in core data (swift)
I'm new to swift and I'm trying to understand parts of it. I've been working on an app where I need to store a date, and I just can't figure it out.

Any input would be great.

Code to store date

```<code>var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
// Users = Entity in core data
var newuser = NSEntityDescription.insertNewObjectForEntityForName("Users",inManagedObjectContext: context) as! NSManagedObject
// datetostore = attribute of type date
newuser.setValue(NSDate(), forKey: "datetostore")
context.save(nil)
</code>```

Code to get stored data from Core Data

```<code>var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Users")
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var end: AnyObject = results[0]
var end2 = end as! NSObject
var end3 = end2 as! NSDate
</code>```

Please note: I know the end doesn't really work because that's where I get an error.

答:
For the first time you should create an attribute with Date.
Here is code</p>

```<code>let date = Date()
let dateformatter = DateFormatter()
dateformatter.format = "dd-MM-yyyy hh-mm-ss"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext

let user = NSEntityDescription.insertNewObject(forEntityName: "Example", into: context)
user.setValue(date, forKey: "date")

appDelegate.saveContext()
</code>```

Title: Storing NSDate in core data (swift)

Body:
I'm new to swift and I'm trying to understand parts of it. I've been working on an app where I need to store a date, and I just can't figure it out.

Any input would be great.

Code to store date

var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
// Users = Entity in core data
var newuser = NSEntityDescription.insertNewObjectForEntityForName("Users",inManagedObjectContext: context) as! NSManagedObject
// datetostore = attribute of type date
newuser.setValue(NSDate(), forKey: "datetostore")
context.save(nil)

Code to get stored data from Core Data

var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Users")
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var end: AnyObject = results[0]
var end2 = end as! NSObject
var end3 = end2 as! NSDate

Please note: I know the end doesn't really work because that's where I get an error.

Body:
For the first time you should create an attribute with Date.
Here is code

let date = Date()
let dateformatter = DateFormatter()
dateformatter.format = "dd-MM-yyyy hh-mm-ss"
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext

let user = NSEntityDescription.insertNewObject(forEntityName: "Example", into: context)
user.setValue(date, forKey: "date")

appDelegate.saveContext()


问:
Convert std::vector<std::string> to const char* const*
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

```<code>std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();
</code>```

But when I compile, I got this :

```<code>error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();
</code>```

Here's a live example

答:
This is what you're doing in your snippet:

concatenate all the strings in v (or crash if v is empty);

throw away the resulting string;

try to assign a dangling pointer to const char to const char* const*.

The last part did not compile, but that's a good thing - dealing with this in a runtime would be a sad expirience.

By the looks of the interface (namely the ppEnabledLayerNames parameter) one could guess that you don't want to concatenate the strings in the first place, but instead you want to pass an array of c-strings.

Here is how to get it from vector<string>:

```<code>vector<const char*> layer_names(v.size());
std::transform(v.begin(), v.end(), layer_names.begin(), [](const string& s)
             { return s.c_str(); });
const char* const* data = layer_names.data();
</code>```

Notice that it will only be valid until either layer_names or v is destroyed.

The better way would be to find a C++-friendly interface for Vulkan, I can't help with that though.

Body:
I'm working with Vulkan, and I'm trying to pass my validation layer as a vector<string>. But the field ppEnabledLayerNames from VkInstanceCreateInfo only takes const char* const*. I don't understand the type and how to convert my vector's data into it.

std::vector<std::string> v = {
    "VK_LAYER_LUNARG_standard_validation"
};

const char* const* data = std::accumulate(std::next(v.begin()), v.end(),
                                    v[0],
                                    [](std::string a, std::string b) {
                                        return a + b;
                                    }).c_str();

But when I compile, I got this :

error: cannot convert ‘const char*’ to ‘const char* const*’ in assignment
                     }).c_str();

Here's a live example

Body:
This is what you're doing in your snippet:

concatenate all the strings in v (or crash if v is empty);

throw away the resulting string;

try to assign a dangling pointer to const char to const char* const*.

The last part did not compile, but that's a good thing - dealing with this in a runtime would be a sad expirience.

By the looks of the interface (namely the ppEnabledLayerNames parameter) one could guess that you don't want to concatenate the strings in the first place, but instead you want to pass an array of c-strings.

Here is how to get it from vector<string>:

vector<const char*> layer_names(v.size());
std::transform(v.begin(), v.end(), layer_names.begin(), [](const string& s)
             { return s.c_str(); });
const char* const* data = layer_names.data();

Notice that it will only be valid until either layer_names or v is destroyed.

The better way would be to find a C++-friendly interface for Vulkan, I can't help with that though.


问:
How to split a comma-separated value to columns
I have a table like this

Value
String

1
Cleo, Smith

I want to separate the comma delimited string into two columns

Value
Name
Surname

1
Cleo
Smith

I need only two fixed extra columns

答:
You can use a table-valued function STRING_SPLIT, which is available only under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute the STRING_SPLIT function. You can change a compatibility level of the database using the following command:

```<code>ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
</code>```

Syntax

```<code>SELECT * FROM STRING_SPLIT ( string, separator )
</code>```

see documentation here

ContentLicense: CC BY-SA 4.0

Body:
You can use a table-valued function STRING_SPLIT, which is available only under compatibility level 130. If your database compatibility level is lower than 130, SQL Server will not be able to find and execute the STRING_SPLIT function. You can change a compatibility level of the database using the following command:

ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130

Syntax

SELECT * FROM STRING_SPLIT ( string, separator )

see documentation here


问:
Spark - Error "A master URL must be set in your configuration" when submitting an app
I have an Spark app which runs with no problem in local mode,but have some problems when submitting to the Spark cluster.

The error msg are as follows:

```<code>16/06/24 15:42:06 WARN scheduler.TaskSetManager: Lost task 2.0 in stage 0.0 (TID 2, cluster-node-02): java.lang.ExceptionInInitializerError
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:390)
    at org.apache.spark.util.Utils$.getIteratorSize(Utils.scala:1595)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.spark.SparkException: A master URL must be set in your configuration
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:401)
    at GroupEvolutionES$.<init>(GroupEvolutionES.scala:37)
    at GroupEvolutionES$.<clinit>(GroupEvolutionES.scala)
    ... 14 more

16/06/24 15:42:06 WARN scheduler.TaskSetManager: Lost task 5.0 in stage 0.0 (TID 5, cluster-node-02): java.lang.NoClassDefFoundError: Could not initialize class GroupEvolutionES$
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:390)
    at org.apache.spark.util.Utils$.getIteratorSize(Utils.scala:1595)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

In the above code, GroupEvolutionES is the main class. The error msg says "A master URL must be set in your configuration", but I have provided the "--master" parameter to spark-submit.

Anyone who knows how to fix this problem?

Spark version: 1.6.1

答:
```<code>var appName:String ="test"
val conf = new SparkConf().setAppName(appName).setMaster("local[*]").set("spark.executor.memory","1g");
val sc =  SparkContext.getOrCreate(conf)
sc.setLogLevel("WARN")
</code>```

Body:
I have an Spark app which runs with no problem in local mode,but have some problems when submitting to the Spark cluster.

The error msg are as follows:

16/06/24 15:42:06 WARN scheduler.TaskSetManager: Lost task 2.0 in stage 0.0 (TID 2, cluster-node-02): java.lang.ExceptionInInitializerError
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:390)
    at org.apache.spark.util.Utils$.getIteratorSize(Utils.scala:1595)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.spark.SparkException: A master URL must be set in your configuration
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:401)
    at GroupEvolutionES$.<init>(GroupEvolutionES.scala:37)
    at GroupEvolutionES$.<clinit>(GroupEvolutionES.scala)
    ... 14 more

16/06/24 15:42:06 WARN scheduler.TaskSetManager: Lost task 5.0 in stage 0.0 (TID 5, cluster-node-02): java.lang.NoClassDefFoundError: Could not initialize class GroupEvolutionES$
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at GroupEvolutionES$$anonfun$6.apply(GroupEvolutionES.scala:579)
    at scala.collection.Iterator$$anon$14.hasNext(Iterator.scala:390)
    at org.apache.spark.util.Utils$.getIteratorSize(Utils.scala:1595)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$count$1.apply(RDD.scala:1157)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1858)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
    at org.apache.spark.scheduler.Task.run(Task.scala:89)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

In the above code, GroupEvolutionES is the main class. The error msg says "A master URL must be set in your configuration", but I have provided the "--master" parameter to spark-submit.

Anyone who knows how to fix this problem?

Spark version: 1.6.1


问:
Match any word of a List/Array in a Sentence java
I have an List of word like below

```<code>List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");
</code>```

How can I understand a String Contains any one of the word of the List. like....

```<code>String name1 = "Adam Smith";      // false (not found)
String name2 = "Late H Milton";   // true  (found Late)
String name3 = "S/O Furi Kerman"; // true  (found S/O)
String name4 = "Conl Faruk";      // false (not found)
String name5 = "Furi Kerman WO";  // true  (found WO)
</code>```

Regular Expression highly appreciated.

答:
Finally I have got a Solution myself with the help all of you....

```<code>    String regex = String.join("|", forbiddenWordList.stream().map(word -> "\\b" + word + "\\b").collect(Collectors.toList()));
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    System.out.println(pattern.matcher(name).find());
</code>```

The word boundary (\\b) helps to find exact word, not the matched text.
Thanks everyone for helping.

Body:
I have an List of word like below

List<String> forbiddenWordList = Arrays.asList("LATE", "S/O", "SO", "W/O", "WO");

How can I understand a String Contains any one of the word of the List. like....

String name1 = "Adam Smith";      // false (not found)
String name2 = "Late H Milton";   // true  (found Late)
String name3 = "S/O Furi Kerman"; // true  (found S/O)
String name4 = "Conl Faruk";      // false (not found)
String name5 = "Furi Kerman WO";  // true  (found WO)

Regular Expression highly appreciated.

Body:
Finally I have got a Solution myself with the help all of you....

    String regex = String.join("|", forbiddenWordList.stream().map(word -> "\\b" + word + "\\b").collect(Collectors.toList()));
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    System.out.println(pattern.matcher(name).find());

The word boundary (\\b) helps to find exact word, not the matched text.
Thanks everyone for helping.


问:
Creating instances of different class types in a function
While building a unit test, I'm struggling with the correct way of trying to achieve the follow:
I'd like to have a function that receives Varargs of Class, and will have the ability to instantiate each of the given classes.
It's something like this:

```<code>    public static void mockContextBeans(Class<?>... classes) throws Exception{
      for (Class<?> c : classes){
          when(context.getBean(c)).thenReturn(c.newInstance());
      }
    }
</code>```

Can someone please point me to the correct way achieving it?

Thanks

答: You're fighting against the way Spring is supposed to be used, but if you really need to make that work you probably could say ....thenReturn(Mockito.mock(c)). Mockito shouldn't care what kinds of constructors exist on the classes.

Body:
While building a unit test, I'm struggling with the correct way of trying to achieve the follow:
I'd like to have a function that receives Varargs of Class, and will have the ability to instantiate each of the given classes.
It's something like this:

    public static void mockContextBeans(Class<?>... classes) throws Exception{
      for (Class<?> c : classes){
          when(context.getBean(c)).thenReturn(c.newInstance());
      }
    }

Can someone please point me to the correct way achieving it?

Thanks


问:
simple algorithm: count 2 numbers for j2me mobile devices
I need now to do a command action for two buttons: "exit" as in notifyDestroyed() and an "Ok" button. How can I implement in commandAction those 2 different buttons?</p>

答:
have u tried for the Keychar method?
u can detect the keys that are pressed by the user and apply whatever u want to do on that</p>


问:
Extending ngx-bootstrap ModalDirective with my own template
I wish to extend ngx-bootstrap modal and use my own template, how would I go about doing this? End product should be custom component that behaves just like ngx-bootstrap's modal but it should predefined template.

```<code>@Injectable()
@Component({
    selector: 'register-patient',
    templateUrl: 'register-patient.component.html',
    styleUrls: ['register-patient.component.scss']
})
export class RegisterPatientComponent extends ModalDirective {
    // constructor, my own methods etc.
}
</code>```

seems like promising start. When I open dialog though, I see only standard backdrop and nothing else. I suspect my template file needs to include some special directive or something but I can't find any topic online. I also can't find original ngx-bootstrap html templates which I could copy and modify. What do I need to include in register-patient.component.html for this to work?

答: Why you want to do so. You can achieve what you want with parent component controlling the child modal component. Check this stackoverflow question Similar question</p>

Body:
I wish to extend ngx-bootstrap modal and use my own template, how would I go about doing this? End product should be custom component that behaves just like ngx-bootstrap's modal but it should predefined template.

@Injectable()
@Component({
    selector: 'register-patient',
    templateUrl: 'register-patient.component.html',
    styleUrls: ['register-patient.component.scss']
})
export class RegisterPatientComponent extends ModalDirective {
    // constructor, my own methods etc.
}

seems like promising start. When I open dialog though, I see only standard backdrop and nothing else. I suspect my template file needs to include some special directive or something but I can't find any topic online. I also can't find original ngx-bootstrap html templates which I could copy and modify. What do I need to include in register-patient.component.html for this to work?


问:
Only one match is returned after using (.|\s)*
String:

```<code>Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))
</code>```

I'd like to select all contents in has() for Person1, i.e ['1, 1', '2, 2', '3, 3'].

I tried: has\((\d, \d)\)(.|\s)*Person2 with Global pattern flags, but only 1, 1 was returned.

答:
Why not parse it fully and then you can pick up whatever you may need - you'll need two patterns, one to grab each person and it's contents, and the other to grab individual parts within them + you can add some more parsing to get individual elements and convert them to native Python types. Something like:

```<code>import collections
import re

persons = re.compile(r"(Person\d+)\(((?:.*?\(.*?\)\s*)+)\)")
contents = re.compile(r"(\w+)\((.*?)\)")

def parse_input(data, parse_inner=True, map_inner=str):
    result = {}  # store for our parsed data
    for match in persons.finditer(data):  # loop through our `Persons`
        person = match.group(1)  # grab the first group to get our Person
        elements = collections.defaultdict(list)  # store for the parsed inner elements
        for element in contents.finditer(match.group(2)):  # loop through the has/had/etc.
            element_name = element.group(1)  # the first group holds the name
            element_data = element.group(2)  # this is the inner content of each has/had/etc.
            if parse_inner:  # if we want to parse the inner elements...
                element_data = [map_inner(x.strip()) for x in element_data.split(",")]
            elements[element_name].append(element_data)  # add our inner results
        result[person] = elements  # add persons to our result
    return result  # well, obvious...
</code>```

Then you can parse everything and access it to your heart's content. The most basic example would be:

```<code>test = """Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))"""

parsed = parse_input(test, False)  # basic string grab

print(parsed["Person1"]["has"])  # ['1, 1', '2, 2', '3, 3']
print(parsed["Person2"]["has"])  # ['6, 6']
print(parsed["Person2"]["had"])  # ['7, 7']
</code>```

But then you can do so much more... You can have multiple added persons and have it 'converted' to an actual Python structure:

```<code>test = """Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))
Person3(has(1, 2) has(3, 4) has(4, 5) foo(6, 7))"""

parsed = parse_input(test, True, int)  # parses everything and auto-converts to int

print(parsed["Person3"]["has"])  # [[1, 2], [3, 4], [4, 5]]
print(parsed["Person3"]["has"][1])  # [3, 4]
print(sum(parsed["Person3"]["foo"][0]))  # 13
print(parsed["Person1"]["has"][1] + parsed["Person2"]["has"][0])  # [2, 2, 6, 6]
# etc.
</code>```

Body:
String:

Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))

I'd like to select all contents in has() for Person1, i.e ['1, 1', '2, 2', '3, 3'].

I tried: has\((\d, \d)\)(.|\s)*Person2 with Global pattern flags, but only 1, 1 was returned.

Body:
Why not parse it fully and then you can pick up whatever you may need - you'll need two patterns, one to grab each person and it's contents, and the other to grab individual parts within them + you can add some more parsing to get individual elements and convert them to native Python types. Something like:

import collections
import re

persons = re.compile(r"(Person\d+)\(((?:.*?\(.*?\)\s*)+)\)")
contents = re.compile(r"(\w+)\((.*?)\)")

def parse_input(data, parse_inner=True, map_inner=str):
    result = {}  # store for our parsed data
    for match in persons.finditer(data):  # loop through our `Persons`
        person = match.group(1)  # grab the first group to get our Person
        elements = collections.defaultdict(list)  # store for the parsed inner elements
        for element in contents.finditer(match.group(2)):  # loop through the has/had/etc.
            element_name = element.group(1)  # the first group holds the name
            element_data = element.group(2)  # this is the inner content of each has/had/etc.
            if parse_inner:  # if we want to parse the inner elements...
                element_data = [map_inner(x.strip()) for x in element_data.split(",")]
            elements[element_name].append(element_data)  # add our inner results
        result[person] = elements  # add persons to our result
    return result  # well, obvious...

Then you can parse everything and access it to your heart's content. The most basic example would be:

test = """Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))"""

parsed = parse_input(test, False)  # basic string grab

print(parsed["Person1"]["has"])  # ['1, 1', '2, 2', '3, 3']
print(parsed["Person2"]["has"])  # ['6, 6']
print(parsed["Person2"]["had"])  # ['7, 7']

But then you can do so much more... You can have multiple added persons and have it 'converted' to an actual Python structure:

test = """Person1(has(1, 1) has(2, 2)
    has(3, 3)
    had(4, 4) had(5, 5))
Person2(has(6, 6) had(7, 7))
Person3(has(1, 2) has(3, 4) has(4, 5) foo(6, 7))"""

parsed = parse_input(test, True, int)  # parses everything and auto-converts to int

print(parsed["Person3"]["has"])  # [[1, 2], [3, 4], [4, 5]]
print(parsed["Person3"]["has"][1])  # [3, 4]
print(sum(parsed["Person3"]["foo"][0]))  # 13
print(parsed["Person1"]["has"][1] + parsed["Person2"]["has"][0])  # [2, 2, 6, 6]
# etc.


问:
Non negative matrix factorisation in python on individual images
I am trying to apply NMF to a particular image that is loaded in grayscale mode. I have tried several links but my image after application of NMF remains almost the same and cannot be distinguished with the grayscale image initially loaded.

However, when i come across the scikit-learn's code on implementing decomposition on a dataset, i see that the faces there have been transformed into ghost - like faces. Here is the link:

http://scikit-learn.org/stable/auto_examples/decomposition/plot_faces_decomposition.html#sphx-glr-auto-examples-decomposition-plot-faces-decomposition-py

And here is the code I am using:

```<code>import cv2
from sklearn import decomposition
import matplotlib.pyplot as plt

img = cv2.imread('test1.jpeg',0)
estimator = decomposition.NMF(n_components = 2, init = 'nndsvda', tol = 5e-3)
estimator.fit(img)
vmax = max(img.max(), -img.min())
plt.imshow(img, cmap=plt.cm.gray, interpolation = 'nearest',vmin=-vmax,vmax=vmax)
plt.show()
</code>```

I am new to the techniques of NMF on matrices espicially such a large image numpy array.

My image is test1.jpeg that is 225 * 224 .jpeg image.

Can someone please help me on implementing the code for a single image?
Thanks a lot in advance.

答:
The reason  you get the original image in the plot is that you actually plot the original image. Instead you would need to work with the output of estimator.

The NMF decomposition produces two matrices W and H that compose the original matrix. You need to multiply those to get the image.

```<code>import cv2
from sklearn import decomposition
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('data/trump2.jpg',0)
vmax = max(img.max(), -img.min())

fig, (ax, ax2)  =plt.subplots(ncols=2)
ax.imshow(img, cmap=plt.cm.gray, interpolation = 'nearest',vmin=-vmax,vmax=vmax)

n_components = 20

estimator = decomposition.NMF(n_components = n_components, init = 'random', tol=5e-3)
W = estimator.fit_transform(img)
H = estimator.components_

new_img = np.dot(W,H)
ax2.imshow(new_img, cmap=plt.cm.gray,
                   interpolation='nearest',
                   vmin=-vmax, vmax=vmax)

plt.show()
</code>```

Body:
I am trying to apply NMF to a particular image that is loaded in grayscale mode. I have tried several links but my image after application of NMF remains almost the same and cannot be distinguished with the grayscale image initially loaded.

However, when i come across the scikit-learn's code on implementing decomposition on a dataset, i see that the faces there have been transformed into ghost - like faces. Here is the link:

http://scikit-learn.org/stable/auto_examples/decomposition/plot_faces_decomposition.html#sphx-glr-auto-examples-decomposition-plot-faces-decomposition-py

And here is the code I am using:

import cv2
from sklearn import decomposition
import matplotlib.pyplot as plt

img = cv2.imread('test1.jpeg',0)
estimator = decomposition.NMF(n_components = 2, init = 'nndsvda', tol = 5e-3)
estimator.fit(img)
vmax = max(img.max(), -img.min())
plt.imshow(img, cmap=plt.cm.gray, interpolation = 'nearest',vmin=-vmax,vmax=vmax)
plt.show()

I am new to the techniques of NMF on matrices espicially such a large image numpy array.

My image is test1.jpeg that is 225 * 224 .jpeg image.

Can someone please help me on implementing the code for a single image?
Thanks a lot in advance.

Body:
The reason  you get the original image in the plot is that you actually plot the original image. Instead you would need to work with the output of estimator.

The NMF decomposition produces two matrices W and H that compose the original matrix. You need to multiply those to get the image.

import cv2
from sklearn import decomposition
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('data/trump2.jpg',0)
vmax = max(img.max(), -img.min())

fig, (ax, ax2)  =plt.subplots(ncols=2)
ax.imshow(img, cmap=plt.cm.gray, interpolation = 'nearest',vmin=-vmax,vmax=vmax)

n_components = 20

estimator = decomposition.NMF(n_components = n_components, init = 'random', tol=5e-3)
W = estimator.fit_transform(img)
H = estimator.components_

new_img = np.dot(W,H)
ax2.imshow(new_img, cmap=plt.cm.gray,
                   interpolation='nearest',
                   vmin=-vmax, vmax=vmax)

plt.show()


问:
How can i remove “addDisposableTo” when i used RxSwift
when i use RxSwift, i must write many many addDisposableTo, how can i remove it?</p>

```<code>usernameTextField.rx.text.orEmpty
            .bindTo(viewModel.username)
            .addDisposableTo(disposeBag)

    passwordTextField.rx.text.orEmpty
        .bindTo(viewModel.password)
        .addDisposableTo(disposeBag)

    repeatPasswordTextField.rx.text.orEmpty
        .bindTo(viewModel.repeatPassword)
        .addDisposableTo(disposeBag)
</code>```

答:
As pointed out by Nimble, you have to do it; otherwise you will most certainly leak memory. The subscribe/unsubscribe couple at work relies on the same principle as native Swift Notification Center/KVO observers: if you open a "channel", you have to "close" it.

The middle ground here is to use NSObject-Rx (by Ash Furrow) that prevents you from creating a dispose bag everywhere you import RxSwift in an NSObject subclass: simply call .disposed(by: rx.disposeBag).

Body:
when i use RxSwift, i must write many many addDisposableTo, how can i remove it?

usernameTextField.rx.text.orEmpty
            .bindTo(viewModel.username)
            .addDisposableTo(disposeBag)

    passwordTextField.rx.text.orEmpty
        .bindTo(viewModel.password)
        .addDisposableTo(disposeBag)

    repeatPasswordTextField.rx.text.orEmpty
        .bindTo(viewModel.repeatPassword)
        .addDisposableTo(disposeBag)


问:
Use Perl to edit HTML files
The output below is generated by a third party tool which validates XML files against a XML Schema. It will output validation errors. Ok, so that was just a little context.

From the errors above are displayed in HTML, I want to be able to perform "syntax highlighting" using perl. For instance, I want to be able to highlight certain parts of the text above.

Specifically, I want to colour any text that conforms to "Line [0-9]*" as bold and in red. I've tried to experiment with regex search and replace but I've not been that successful.

Any pointers/hints would be fantastic.

Thank you!

```<code>Line 8: Element 'alphabet', attribute 'letters': The value 'XYZ' does not match the fixed value constraint 'ABC'.
Line 185: Element 'drink': The attribute 'coffee' is required but missing.
Line 254: Element 'timeout': This element is not expected.
Line 269: Element 'commands': This element is not expected. Expected is one of ( eat, drink, sleep ).
Line 812: Element 'software': The attribute 'version' is required but missing.
Line 876: Element 'windows-software': The attribute 'version' is required but missing.
Line 890: Element 'contact': The attribute 'telephone' is required but missing.
Line 890: Element 'operating': The attribute 'mode' is required but missing.
</code>```

答:
Have a try with this:

```<code>#!/usr/bin/perl
use strict;
use warnings;

while(<DATA>) {
    s#(Line \d+)#<span style="font-weight:bold;color:red;">$1</span>#;
    s#(Element\s|attribute\s)('[^']*')#$1<span style="font-weight:bold;color:blue;">$2</span>#g;
    print
}

__DATA__
Line 8: Element 'alphabet', attribute 'letters': The value 'XYZ' does not match the fixed value constraint 'ABC'.
Line 185: Element 'drink': The attribute 'coffee' is required but missing.
Line 254: Element 'timeout': This element is not expected.
</code>```

output

```<code><span style="font-weight:bold;color:red;">Line 8</span>: Element <span style="font-weight:bold;color:blue;">'alphabet'</span>, attribute <span style="font-weight:bold;color:blue;">'letters'</span>: The value 'XYZ' does not match the fixed value constraint 'ABC'.
<span style="font-weight:bold;color:red;">Line 185</span>: Element <span style="font-weight:bold;color:blue;">'drink'</span>: The attribute <span style="font-weight:bold;color:blue;">'coffee'</span> is required but missing.
<span style="font-weight:bold;color:red;">Line 254</span>: Element <span style="font-weight:bold;color:blue;">'timeout'</span>: This element is not expected.
</code>```

Instead of style attribut, you can use a css class.

```<code>s#(Line \d+)#<span class="bold_red">$1</span>#;
</code>```

Title: Use Perl to edit HTML files

Body:
The output below is generated by a third party tool which validates XML files against a XML Schema. It will output validation errors. Ok, so that was just a little context.

From the errors above are displayed in HTML, I want to be able to perform "syntax highlighting" using perl. For instance, I want to be able to highlight certain parts of the text above.

Specifically, I want to colour any text that conforms to "Line [0-9]*" as bold and in red. I've tried to experiment with regex search and replace but I've not been that successful.

Any pointers/hints would be fantastic.

Thank you!

Line 8: Element 'alphabet', attribute 'letters': The value 'XYZ' does not match the fixed value constraint 'ABC'.
Line 185: Element 'drink': The attribute 'coffee' is required but missing.
Line 254: Element 'timeout': This element is not expected.
Line 269: Element 'commands': This element is not expected. Expected is one of ( eat, drink, sleep ).
Line 812: Element 'software': The attribute 'version' is required but missing.
Line 876: Element 'windows-software': The attribute 'version' is required but missing.
Line 890: Element 'contact': The attribute 'telephone' is required but missing.
Line 890: Element 'operating': The attribute 'mode' is required but missing.

Body:
Have a try with this:

#!/usr/bin/perl
use strict;
use warnings;

while(<DATA>) {
    s#(Line \d+)#<span style="font-weight:bold;color:red;">$1</span>#;
    s#(Element\s|attribute\s)('[^']*')#$1<span style="font-weight:bold;color:blue;">$2</span>#g;
    print
}

__DATA__
Line 8: Element 'alphabet', attribute 'letters': The value 'XYZ' does not match the fixed value constraint 'ABC'.
Line 185: Element 'drink': The attribute 'coffee' is required but missing.
Line 254: Element 'timeout': This element is not expected.

output

<span style="font-weight:bold;color:red;">Line 8</span>: Element <span style="font-weight:bold;color:blue;">'alphabet'</span>, attribute <span style="font-weight:bold;color:blue;">'letters'</span>: The value 'XYZ' does not match the fixed value constraint 'ABC'.
<span style="font-weight:bold;color:red;">Line 185</span>: Element <span style="font-weight:bold;color:blue;">'drink'</span>: The attribute <span style="font-weight:bold;color:blue;">'coffee'</span> is required but missing.
<span style="font-weight:bold;color:red;">Line 254</span>: Element <span style="font-weight:bold;color:blue;">'timeout'</span>: This element is not expected.

Instead of style attribut, you can use a css class.

s#(Line \d+)#<span class="bold_red">$1</span>#;


问:
Google sheets error: Resource at url contents exceeded maximum size
My IMPORTXML functions sometimes work, but sometimes don't. When they don't, I get the following error:

Resource at url contents exceeded maximum size.

I tried downloading the website, and then hosting only the HTML at a domain that I own. When I do this, I am able to import using IMPORTXML, but my data obviously won't update automatically.

Is there a way to overcome this by somehow forcing the IMPORTXML function to only look at the HTML?

答:
I recommend using a custom function that technically grabs all of it. If it is really a ton of content then wrap the (.*) with the content that surrounds the real content you want... such as (.*)<\/head> (just for example sake)

```<code>function importWebsite(url) {
  var found, html, content = '';
  var response = UrlFetchApp.fetch(url);
  if (response) {
    html = response.getContentText();
    if (html) content = html.match(/^(.*)/gi)[0];
  }
  return content;
}
</code>```

Body:
I recommend using a custom function that technically grabs all of it. If it is really a ton of content then wrap the (.*) with the content that surrounds the real content you want... such as <head>(.*)<\/head> (just for example sake)

function importWebsite(url) {
  var found, html, content = '';
  var response = UrlFetchApp.fetch(url);
  if (response) {
    html = response.getContentText();
    if (html) content = html.match(/^(.*)/gi)[0];
  }
  return content;
}


问:
Pick a number from two columns and calculate
A given file contains pairs of <two-digit number, amount>.  Then take a toss-up two-digit number (called X), and compute the win/loss amount.  The win/loss rule is if the input number matches X, then it’s a win and the winning total is (amount * 70); otherwise, it’s a loss of (-amount).

For example: [ticket.txt]
  09 10
  13 15
  25 21

If the toss-up number is 09, the win/loss amount of the ticket is (10 * 70 - 15 - 21)

If the toss-up number is 42, the win/loss amount of the ticket is (-10 - 15 - 21).

This is my beginner project. I stuck at calculating the win amount and lost amount.
This is my problem

```<code>#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount, lostAmount;
    int num = 0; // num start at 0
    ifstream inFile;
    inFile.open("Ticket.txt"); //open File
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;
        return 1;
    }
    cout << "Numbers from File: " << endl;
    while (!inFile.eof()) // read File to end of file
        {
            inFile >> line1[num]; // read first column, the first column is the number that user choosing
            inFile >> line2[num]; // read second column, the second column is the amount of money that user paying
            cout << "\n" << line1[num] << "\t" << line2[num];
            ++num;
        }
    inFile.close();
    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;
    if (line1[num] == winNum)
    {
        winAmount = line2[num] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        cout << winAmount;
        }
        else
        {
            lostAmount =- line2[num]; //number user choose != win number, the amount will be -lost amounts
cout << lostAmount;
        }
        cout << endl << endl;
        system("pause");
        return 0;
    }
</code>```

答:
You can see result at the end of the code</p>

```<code>#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount = 0, lostAmount = 0, result = 0;
    int num = 0; // num start at 0
    ifstream inFile;
    ifstream inFile2;
    int rowNumber = 0;
    string line;
    inFile.open("Ticket.txt"); //open File
    inFile2.open("Ticket.txt");
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;
        return 1;
    }

     while (getline(inFile2, line))
        ++rowNumber;
    cout << "Number of lines in text file: " << rowNumber << "\n";

    int myArray[rowNumber][2];
    for(int i = 0; i < rowNumber; i++)
        for(int j = 0; j < 2; j++)
            inFile >> myArray[i][j];

    cout << "Numbers from File: " << endl;

    for(int i = 0; i < rowNumber; i++)
    {
        for(int j = 0; j < 2; j++)
        {
            cout << myArray[i][j] << " ";
        }
        cout << "\n";
    }

    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;

    for(int i = 0; i< rowNumber; i++)
    {
        if (myArray[i][0] == winNum)
        {
            winAmount = myArray[i][1] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        }
        else
        {
            lostAmount = lostAmount + myArray[i][1]; //number user choose != win number, the amount will be -lost amounts
        }
    }

    result = winAmount - lostAmount;
    cout << result;

    cout << endl << endl;
    system("pause");
    return 0;
    }
</code>```

Body:
A given file contains pairs of <two-digit number, amount>.  Then take a toss-up two-digit number (called X), and compute the win/loss amount.  The win/loss rule is if the input number matches X, then it’s a win and the winning total is (amount * 70); otherwise, it’s a loss of (-amount).

For example: [ticket.txt]
  09 10
  13 15
  25 21

If the toss-up number is 09, the win/loss amount of the ticket is (10 * 70 - 15 - 21)

If the toss-up number is 42, the win/loss amount of the ticket is (-10 - 15 - 21).

This is my beginner project. I stuck at calculating the win amount and lost amount.
This is my problem

#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount, lostAmount;
    int num = 0; // num start at 0
    ifstream inFile;
    inFile.open("Ticket.txt"); //open File
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;
        return 1;
    }
    cout << "Numbers from File: " << endl;
    while (!inFile.eof()) // read File to end of file
        {
            inFile >> line1[num]; // read first column, the first column is the number that user choosing
            inFile >> line2[num]; // read second column, the second column is the amount of money that user paying
            cout << "\n" << line1[num] << "\t" << line2[num];
            ++num;
        }
    inFile.close();
    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;
    if (line1[num] == winNum)
    {
        winAmount = line2[num] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        cout << winAmount;
        }
        else
        {
            lostAmount =- line2[num]; //number user choose != win number, the amount will be -lost amounts
cout << lostAmount;
        }
        cout << endl << endl;
        system("pause");
        return 0;
    }

Body:
You can see result at the end of the code

#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount = 0, lostAmount = 0, result = 0;
    int num = 0; // num start at 0
    ifstream inFile;
    ifstream inFile2;
    int rowNumber = 0;
    string line;
    inFile.open("Ticket.txt"); //open File
    inFile2.open("Ticket.txt");
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;
        return 1;
    }

     while (getline(inFile2, line))
        ++rowNumber;
    cout << "Number of lines in text file: " << rowNumber << "\n";

    int myArray[rowNumber][2];
    for(int i = 0; i < rowNumber; i++)
        for(int j = 0; j < 2; j++)
            inFile >> myArray[i][j];

    cout << "Numbers from File: " << endl;

    for(int i = 0; i < rowNumber; i++)
    {
        for(int j = 0; j < 2; j++)
        {
            cout << myArray[i][j] << " ";
        }
        cout << "\n";
    }

    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;

    for(int i = 0; i< rowNumber; i++)
    {
        if (myArray[i][0] == winNum)
        {
            winAmount = myArray[i][1] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        }
        else
        {
            lostAmount = lostAmount + myArray[i][1]; //number user choose != win number, the amount will be -lost amounts
        }
    }

    result = winAmount - lostAmount;
    cout << result;

    cout << endl << endl;
    system("pause");
    return 0;
    }


问:
Compiler gives warning on performSelectorOnMainThread:@selector(delegateMethod)
I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation lives on a different thread I have to make the call like this:

```<code>[delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
</code>```

It works just fine, but it gives me a warning:

warning:
  '-performSelectorOnMainThread:withObject:waitUntilDone:'
  not found in protocol(s)

I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.

My question is: can I remove the warning by making this call in a different manner?

My two guesses are that I could (1) write a method called

```<code>- (void) callDelegateMethodOnMainThred {
    [delegate getDealersIDSuccess:result]
}
</code>```

and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.

The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.

I would really appreciate a third solution from someone with a better understanding of the language:)

Thank you in advance.

EDIT: Added delegate declaration:

```<code>id <ISDealersIDDelegate> delegate;
</code>```

I declare my delegate as id. The delegate it self extends UIViewController.

I could see that declaring it NSObject would work.

答:
performSelectorOnMainThread:withObject:waitUntilDone: method is declared in NSObject class. If your delegate object inherits from NSObject you can declare it as

```<code>NSObject<MyDelegateProtocol> *delegate;
</code>```

So compiler will know that delegate responds to NSObject's methods and won't issue a warning.

Body:
I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation lives on a different thread I have to make the call like this:

[delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];

It works just fine, but it gives me a warning:

warning:
  '-performSelectorOnMainThread:withObject:waitUntilDone:'
  not found in protocol(s)

I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.

My question is: can I remove the warning by making this call in a different manner?

My two guesses are that I could (1) write a method called

- (void) callDelegateMethodOnMainThred {
    [delegate getDealersIDSuccess:result]
}

and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.

The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.

I would really appreciate a third solution from someone with a better understanding of the language:)

Thank you in advance.

EDIT: Added delegate declaration:

id <ISDealersIDDelegate> delegate;

I declare my delegate as id. The delegate it self extends UIViewController.

I could see that declaring it NSObject would work.

Body:
performSelectorOnMainThread:withObject:waitUntilDone: method is declared in NSObject class. If your delegate object inherits from NSObject you can declare it as

NSObject<MyDelegateProtocol> *delegate;

So compiler will know that delegate responds to NSObject's methods and won't issue a warning.


问:
How create entity. Hibernate
Each company has two properties, they are company name and estimated annual earnings.
There are two types of companies: 1- Main company, 2 - Subsidiary company.
The company can belong only to one company but can have a few child companies.</p>

答:
Just to set you in the right direction, you need to look at association mapping, Hibernate provides field/method annotation for defining associations - of particular note in your case;

```<code>@Entity
@OneToMany
@ManyToOne
</code>```

I'd recommend taking some time to familiarize yourself with the Hibernate Documentation on the subject; it's fundamental to using hibernate.  Google for some starer tutorials on the subject to get you started - there are so many out there (here for example).  I'm sure you can get more help if you run into specific problems when you get started.

Title: How create entity. Hibernate

Body:
Just to set you in the right direction, you need to look at association mapping, Hibernate provides field/method annotation for defining associations - of particular note in your case;

@Entity
@OneToMany
@ManyToOne

I'd recommend taking some time to familiarize yourself with the Hibernate Documentation on the subject; it's fundamental to using hibernate.  Google for some starer tutorials on the subject to get you started - there are so many out there (here for example).  I'm sure you can get more help if you run into specific problems when you get started.


问:
you are trying to add a non-nullable field 'description' to wine without a default
I tried to add a description column and i tried to make changes in models.py. However, when I was trying to migrate I get this error

```<code>C:\Users\Adhista Chapagain\Desktop\winerama>python manage.py makemigrations
You are trying to add a non-nullable field 'description' to wine without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:
</code>```

models.py code looks like this:

```<code>from django.db import models
import numpy as np

class Wine(models.Model):
    name = models.CharField(max_length=200)
    images = models.ImageField(null = True, blank=True)
    description = models.CharField(max_length=200)
</code>```

and code for load_wine

```<code>def save_wine_from_row(wine_row):
    wine = Wine()
    wine.id = wine_row[0]
    wine.name = wine_row[1]
    wine.images = wine_row[2]
    wine.description = wine_row[3]
    wine.save()
</code>```

答:
When you add fields to an already-existing model, if those fields are not 'nullable' (i.e. You don't have null=True on the field) then you need to provide the migration with a default to use for all existing rows in the database for that model. It doesn't know at this point whether there are any or not, so you have to do this even if the database is empty.

Just choose one of the options and provide a default (even if that is just an empty string).

Body:
I tried to add a description column and i tried to make changes in models.py. However, when I was trying to migrate I get this error

C:\Users\Adhista Chapagain\Desktop\winerama>python manage.py makemigrations
You are trying to add a non-nullable field 'description' to wine without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option:

models.py code looks like this:

from django.db import models
import numpy as np

class Wine(models.Model):
    name = models.CharField(max_length=200)
    images = models.ImageField(null = True, blank=True)
    description = models.CharField(max_length=200)

and code for load_wine

def save_wine_from_row(wine_row):
    wine = Wine()
    wine.id = wine_row[0]
    wine.name = wine_row[1]
    wine.images = wine_row[2]
    wine.description = wine_row[3]
    wine.save()


问:
Create list with unique id in Java and manipulate it
I want to create a programm that creates a list that looks like this

```<code>ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example
</code>```

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2

答:
```<code>import java.util.ArrayList;
import java.util.List;

public class Person {

private int id;
private String name;
private String Surname;
private String email;

public Person(int id, String name, String surname, String email) {
    super();
    this.id = id;
    this.name = name;
    Surname = surname;
    this.email = email;
}

public int getId() {
    return id;
}

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

public String getName() {
    return name;
}

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

public String getSurname() {
    return Surname;
}

public void setSurname(String surname) {
    Surname = surname;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public static void main(String[] args) {

    List<Person> list = new ArrayList<Person>();
    list.add(new Person(1, "example", "example", "example"));
    list.add(new Person(2, "example", "example", "example"));
  }

 }
</code>```

Body:
I want to create a programm that creates a list that looks like this

ID: 1
Name: Example
Surname: Example
email: example

//New list

ID: 2
Name: Example
Surname: Example
email: example

and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2


问:
Python: Accessing List of Dict. Typeerror: Column name can't be str
I have a question about accessing a list of dict in Python. I'm trying to access all value in a column of a CSV file. I've isolated and simplified the problem into the code below.

I'm trying to define a function which

inputs:
1) data set (list of dict)
2) column name

outputs: 1) printed list of all value in column

Instead i receive a "TypeError: list indices must be integers or slices, not str"

```<code>dict_1 = {'a':1, 'b':2, 'c':3}
dict_2 = {'a':4, 'b':5, 'c':6}
list_1 = [dict_1, dict_2]

def len_unique_element(data_set,column_name):

    data = ([data_set[column_name] for row in data_set])

    return print (data)

len_unique_element (list_1, 'a')
</code>```

Thanks!

答:
You should replace data_set with row in the list comprehension. The data_set is a list and row is a dict in the data_set.

```<code>data = [row[column_name] for row in data_set]
</code>```

You should use return or print instead of combine them.

Body:
I have a question about accessing a list of dict in Python. I'm trying to access all value in a column of a CSV file. I've isolated and simplified the problem into the code below.

I'm trying to define a function which

inputs:
1) data set (list of dict)
2) column name

outputs: 1) printed list of all value in column

Instead i receive a "TypeError: list indices must be integers or slices, not str"

dict_1 = {'a':1, 'b':2, 'c':3}
dict_2 = {'a':4, 'b':5, 'c':6}
list_1 = [dict_1, dict_2]

def len_unique_element(data_set,column_name):

    data = ([data_set[column_name] for row in data_set])

    return print (data)

len_unique_element (list_1, 'a')

Thanks!

Body:
You should replace data_set with row in the list comprehension. The data_set is a list and row is a dict in the data_set.

data = [row[column_name] for row in data_set]

You should use return or print instead of combine them.


问:
Jquery callback function on animate
I figured out how to do a callback function for this type jquery animate method

```<code>$("#div1").animate({top: "-=100"}, 2000, function(){alert("hi")});
</code>```

But I cant seem to figure out how to make a simple alert callback function with this animate() function.

```<code>$('#div1').animate({top: "-800"}, {duration: 3000}).animate({left: "-700"},
{duration: 3000, queue: false});
</code>```

答:
Try this

```<code>$('#div1')
.animate({top: "-800"}, {duration: 3000})
.animate({left: "-700"}, {duration: 3000, queue: false, complete: function() {console.log('done');}});
</code>```

in this case, the the callback function must be part of the options object, like complete: function() { // code here }

Title: Jquery callback function on animate

Body:
I figured out how to do a callback function for this type jquery animate method

$("#div1").animate({top: "-=100"}, 2000, function(){alert("hi")});

But I cant seem to figure out how to make a simple alert callback function with this animate() function.

$('#div1').animate({top: "-800"}, {duration: 3000}).animate({left: "-700"},
{duration: 3000, queue: false});

Body:
Try this

$('#div1')
.animate({top: "-800"}, {duration: 3000})
.animate({left: "-700"}, {duration: 3000, queue: false, complete: function() {console.log('done');}});

in this case, the the callback function must be part of the options object, like complete: function() { // code here }


答:
The error is telling you that you are trying to add a column to an existing table which does not have a default value, but it is not allowed to be blank. So this is an impossible situation - either it should have a default value, or make it "null" in the database. Unless you provide a solution, the migration cannot continue.

So you have few options:

Give a default value, which will be applied to all existing records.

Make the field optional (ie, set null=True).

Give it a default value in models (default="No Description")

Just pick an option and then migrate will work.

Title: you are trying to add a non-nullable field 'description' to wine without a default


问:
MVC View Problem
I have an mvc application running on IIS 7.0 on windows vista.The appication is redirecting to the proper controller and action.But i am getting an error saying view is not found in the path, when the view is present at the particular path.

Route is as shown below.

routes.MapRoute(
"Default",                                              // Route name

"home/{action}/{id}",                           // URL with parameters

new { controller = "Home", action = "Index", id = "" } // Parameter constraints
             );

I am getting the error as The view 'Index' could not be located at these paths: ~/Views/Home/Index.aspx, ~/Views/Home/Index.ascx, ~/Views/Shared/Index.aspx, ~/Views/Shared/Index.ascx when i run the mvc application http://localhost/mvcsf/Home/

答:
The choice of view is defined by the controller. What does the home controller do for the Index action? If this is the vanilla site generated by the system, then it is expecting to find "~/Views/Home/Index.aspx", via the controller's action (below). So: does this index page exist?

```<code>    public ActionResult Index()
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }
</code>```

(the default view has the pattern {controller}/{action}; you can specify other views via overloads on View(...))

Title: MVC View Problem

Body:
The choice of view is defined by the controller. What does the home controller do for the Index action? If this is the vanilla site generated by the system, then it is expecting to find "~/Views/Home/Index.aspx", via the controller's action (below). So: does this index page exist?

    public ActionResult Index()
    {
        ViewData["Title"] = "Home Page";
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

(the default view has the pattern {controller}/{action}; you can specify other views via overloads on View(...))

OwnerDisplayName: Marc Gravell