问:
Perl Script Help needed for duplicate filenames
I have developed the below shell script for finding duplicate part of filename and delete it. Similiarly i need to prepare in Perl script also as perl script text processing takes lesser time.

```<code>#!/bin/bash
for i in `ls -t *xml|awk 'BEGIN{FS="_"}{if (++dup[$1] >= 2) print}'`;
do
rm $i
done
</code>```

I have to prepare my perl script my code in such a way that only recent modified filename patterns for example

```<code>File 1: AAA_555_0000
File 2: AAAA_123_123
File 3: AAAA_452_452 [latest]

File 4: BBB_555_0000
File 5: BBB_555_555
File 6: BBB_999_999 [latest]

File 7: CCC_555_0000
File 8: CCC_000_000
File 9: CCC_000_111 [latest]
</code>```

Perl Script has to pick latest file in all the filename patterns (means part of filename) in the folder and it should compare and delete the duplicates.
For example: script has to pick latest file in the AAA filename pattern and it has to compare with other AAA pattern if pattern found it has to delete. in the end only latest file in all filename pattern has to remain.

Appreciate if you can help me with this logic.

Thanks much!

答:
Your question is a bit unclear to me, because I am not sure how you determine the order of your files to tell which one is newer. This code will do what I think you need:

```<code>my $dir = shift || '.';

opendir(my $dh, $dir);
my @files = sort grep !/^\./, readdir($dh);

my $last;
my @batch;
foreach my $f (@files) {
  my @parts = split /_/, $f;

  if( !$last ) {
    $last = $parts[0];
    push @batch, [ @parts ];
  }
  elsif( index($last, $parts[0]) != -1 ) {
    push @batch, [ @parts ];
  }
  else {
    delete_files(@batch);

    @batch = ([ @parts ]);
    $last  = $parts[0];
  }
}
delete_files(@batch);

sub delete_files {
  my @batch = @_;

  @batch = sort {
    $a->[0] cmp $b->[0] ||
    $a->[1] cmp $b->[1] ||
    $a->[2] cmp $b->[2]
  } @batch;
  pop @batch;

  map { print "Delete: ", join('_', @$_), "\n"; } @batch;
}
</code>```

It assumes that a batch of files is one in which files have the same prefix (up to the first '_' character). When two prefixes have a different length, then the common length has to match.

It also assumes that "version numbers" (text bits separated by '_') should be compared, with the leftmost being the most significative.

Given those assumptions, the code, pointed at a directory with the files you mention, outputs:

```<code># latest.pl <dir>
Delete: AAA_555_0000
Delete: AAAA_123_123
Delete: BBB_555_0000
Delete: BBB_555_555
Delete: CCC_000_000
Delete: CCC_000_111
</code>```

The unclear part is why you think that file 7 is not the latest...

Once the order is clear, you may change the line:

```<code>map { print "Delete: ", join('_', @$_), "\n"; } @batch;
</code>```

With:

```<code>map { unlink join('_', @$_); } @batch;
</code>```

So that it will delete the files.

You may play with the sorting algorthm in the sub, which is the one that determines which files to delete. Now it compares the file name parts from left to right as strings. You may use <=> to compare as numbers instead of cmp where necessary.

Body:
I have developed the below shell script for finding duplicate part of filename and delete it. Similiarly i need to prepare in Perl script also as perl script text processing takes lesser time.

#!/bin/bash
for i in `ls -t *xml|awk 'BEGIN{FS="_"}{if (++dup[$1] >= 2) print}'`;
do
rm $i
done

I have to prepare my perl script my code in such a way that only recent modified filename patterns for example

File 1: AAA_555_0000
File 2: AAAA_123_123
File 3: AAAA_452_452 [latest]

File 4: BBB_555_0000
File 5: BBB_555_555
File 6: BBB_999_999 [latest]

File 7: CCC_555_0000
File 8: CCC_000_000
File 9: CCC_000_111 [latest]

Perl Script has to pick latest file in all the filename patterns (means part of filename) in the folder and it should compare and delete the duplicates.
For example: script has to pick latest file in the AAA filename pattern and it has to compare with other AAA pattern if pattern found it has to delete. in the end only latest file in all filename pattern has to remain.

Appreciate if you can help me with this logic.

Thanks much!

Body:
Your question is a bit unclear to me, because I am not sure how you determine the order of your files to tell which one is newer. This code will do what I think you need:

my $dir = shift || '.';

opendir(my $dh, $dir);
my @files = sort grep !/^\./, readdir($dh);

my $last;
my @batch;
foreach my $f (@files) {
  my @parts = split /_/, $f;

  if( !$last ) {
    $last = $parts[0];
    push @batch, [ @parts ];
  }
  elsif( index($last, $parts[0]) != -1 ) {
    push @batch, [ @parts ];
  }
  else {
    delete_files(@batch);

    @batch = ([ @parts ]);
    $last  = $parts[0];
  }
}
delete_files(@batch);

sub delete_files {
  my @batch = @_;

  @batch = sort {
    $a->[0] cmp $b->[0] ||
    $a->[1] cmp $b->[1] ||
    $a->[2] cmp $b->[2]
  } @batch;
  pop @batch;

  map { print "Delete: ", join('_', @$_), "\n"; } @batch;
}

It assumes that a batch of files is one in which files have the same prefix (up to the first '_' character). When two prefixes have a different length, then the common length has to match.

It also assumes that "version numbers" (text bits separated by '_') should be compared, with the leftmost being the most significative.

Given those assumptions, the code, pointed at a directory with the files you mention, outputs:

# latest.pl <dir>
Delete: AAA_555_0000
Delete: AAAA_123_123
Delete: BBB_555_0000
Delete: BBB_555_555
Delete: CCC_000_000
Delete: CCC_000_111

The unclear part is why you think that file 7 is not the latest...

Once the order is clear, you may change the line:

map { print "Delete: ", join('_', @$_), "\n"; } @batch;

With:

map { unlink join('_', @$_); } @batch;

So that it will delete the files.

You may play with the sorting algorthm in the sub, which is the one that determines which files to delete. Now it compares the file name parts from left to right as strings. You may use <=> to compare as numbers instead of cmp where necessary.


来源: stackexchange

问:
Remove 0, if return 0 year or 0 month DateFormat
```<code>$createdTime = Carbon::parse($specialist->created_at)
                        ->diff(Carbon::now())
                        ->format('%y yr, %m mo and %d days');
</code>```

This returns 0 yr, 0 mo and 8 days. I want to return only 8 days.

Or if 1 yr, 0 mo and 8 days, return 1 yr and 8 days

答:
There is a better solution rather than using diffForHumans() and remove ago with str_replace($time->diffForHumans(), ' ago').

I recommand using the CarbonInterval like this :

```<code>$now = Carbon::now();
$years = $specialist->created_at->diffInYears($now);
$months = $specialist->created_at->diffInDays($now->subYears($years));
$days = $specialist->created_at->diffInDays($now->subMonths($years));

// $hours = $specialist->created_at->diffInHours($now->subDays($days));
// $minutes = $specialist->created_at->diffInMinutes($with_duration->subHours($hours));
// $seconds = $specialist->created_at->diffInSeconds($with_duration->subMinutes($minutes));

return CarbonInterval::years($years)->months($months)->days($days)->forHumans();

//return CarbonInterval::years($years)->months($months)->days($days)->hours($hours)->minutes($minutes)->seconds($seconds)->forHumans();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
$createdTime = Carbon::parse($specialist->created_at)
                        ->diff(Carbon::now())
                        ->format('%y yr, %m mo and %d days');

This returns 0 yr, 0 mo and 8 days. I want to return only 8 days.

Or if 1 yr, 0 mo and 8 days, return 1 yr and 8 days

Body:
There is a better solution rather than using diffForHumans() and remove ago with str_replace($time->diffForHumans(), ' ago').

I recommand using the CarbonInterval like this :

$now = Carbon::now();
$years = $specialist->created_at->diffInYears($now);
$months = $specialist->created_at->diffInDays($now->subYears($years));
$days = $specialist->created_at->diffInDays($now->subMonths($years));

// $hours = $specialist->created_at->diffInHours($now->subDays($days));
// $minutes = $specialist->created_at->diffInMinutes($with_duration->subHours($hours));
// $seconds = $specialist->created_at->diffInSeconds($with_duration->subMinutes($minutes));

return CarbonInterval::years($years)->months($months)->days($days)->forHumans();

//return CarbonInterval::years($years)->months($months)->days($days)->hours($hours)->minutes($minutes)->seconds($seconds)->forHumans();


问:
Service Oriented Application in Windows Form client?
What could be the best way to create a server sided program on windows? The client will be a windows form application. Is there any problem with speeds on the client because of the load time. And also for heavy requested method, is it possible for async?</p>

答:
Try this proof of concept code http://www.ienablemuch.com/2011/01/nhibernate-saves-your-whole-object.html I must admit that my code doesn't faithfully adhere to SOA design; anyhow, you can use some of the principles how to retrieve POCOs(which is bandwidth-friendly) from WCF

Others has a strong view about what constitutes a real service-oriented application, i.e. the domain entities are internal to a business and need not be exposed to business's clients(or for public consumption).  If you adhere faithfully to that tenet, you should use DTO (google this) and automapper(not related to fluent nhibernate's automapper) combo

ContentLicense: CC BY-SA 2.5


问:
PHP PDO how to hash password upon registration and then 'unhash' during login
I am finishing up an application. I have fairly heavy validation going on within the scripting but I want to step it up by hashing the password when it is sent to the database that way it does not go in as plain text. I have tried several methods but found no luck with it as of yet.

Here is the code (Hosted on GitHub's Gist program):

https://gist.github.com/anonymous/e5c4f6ab9443d9ce887266b79bc36a1a

As you can see in the password validation portion of the script, I have it where if the password passes all other validation then it get's hashed. But it doesn't seem to be working when I check my database. That is issue #1. On top of that I couldn't find any methods that would unhash the password and also how to implement an 'unhashing' technique in my login.php file that I included in the link above. I appreciate any help or tips you guys may offer. Thanks so much!

答:
General information on (cryptographic) hashing

Hashing is often confused with encrypting, but they're different and have different use-cases:

Encryption is meant for encoding something such that it can be deciphered again (with the right key), making it a two-way process.

(Cryptographic) hashing, on the other hand, is a one-way process to encode something that is explicitly not meant to be decipherable. Furthermore, a hashing function is deterministic, meaning that given the same message, it will always produce the same digest.1

So, here is why cryptographic hashing is used to encode passwords:

For hopefully obvious security reasons, you don't want anyone to be able to decipher the hashed password (not some adversary who was able to compromise your database and not even you, the web master, since that would allow you to compromise a user's account somewhere else, if they use the same password over there), but you do want to be able to verify that the password entered by the user matches the password they signed up with.

Since, as mentioned before, a hashing function is deterministic, we can achieve this by comparing the hash produced at an authentication process (such as logging in) and the hash produced at the sign-up process.

"But wait...," I hear you think, "in your comment you told me I would not be able to simply compare them".

If the message given to a bare hashing function is the same, you can and that's the problem with the deterministic aspect of hashing functions, in the context of password hashing: they produce the same output.

This means that if Alice, Bob and Charlie use the same password, they all produce the same digests:

```<code> id | username | pwdhash
----+----------+---------
 17 | Alice    | 9Wdm...
 48 | Bob      | 9Wdm...
 57 | Charlie  | 9Wdm...
</code>```

This poses two prominent security risks:

if you know Alice's password, you know the others' as well;

an adversary could, knowing the hashing function you use, theoretically generate, what is called, a rainbow table2 and compare its hashes with your hashes (if your database was compromised), to infer the actual passwords that match those in the rainbow table.

So, to mitigate these risks it is considered mandatory practice to add, what is called, a salt to the message (the password), before hashing it. A salt is meant to be unique enough to guarantee that two identical passwords produce completely different digests when fed to the same hashing function.

Pseudo example:

```<code>// produces same digests:
hash( 'password' ) -> bhZPmushb...
hash( 'password' ) -> bhZPmushb...

// produces unique digests:
        salt       message
hash( 'SeNib6' . 'password' ) -> qDHkfTW9m...
hash( '9pBq7y' . 'password' ) -> XH26YVUnA...
</code>```

And this, by default, is what password_hash() automatically does for you, under the hood.3 It then prepends the used salt to the digest, along with information about the actual algorithm that was used and the cost.4 password_verify() will then use this additional information and the used salt to generate the same digest again, if the provided password matches the earlier hashed password.

It's therefore essential that the complete output of password_hash() is stored so that it can be fed into password_verify() as its second argument.

So, what does all this mean for your case?

Since password_hash() automatically adds a salt and therefore generates two different digests for identical passwords, you can't simply compare password_hash()'s output. This also means you can't (easily; I wouldn't be surprised if there was some way to make it work) compare password hashes at the database level, like you intended, with password = :password; you will have to compare the hashes in PHP, which means that you will have to fetch the user's record first and then verify the password hashes:

$query = "SELECT * FROM credentials WHERE username = :username";
$statement = $conn->prepare($query);
$statement->execute(array('username' => $_POST["userName"]));

// I believe PDOStatement::rowCount() doesn't work with MySQL for SELECT statements
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = count($rows);
if($count > 1) { // this might be redundant in your setup
  // this is not supposed to happen, usernames should be unique
  // log or alert developer
}
else if($count == 1) {
  $row = $rows[0];
  if(password_verify($_POST["userPass"], $row['password')) {
    // don't store $_POST["userName"] in $_SESSION["username"], but use the database value
    $_SESSION["username"] = $row["username"];
    header("Location: user-homepage.php");
    // it's good practice to exit after a redirect, unless other code still needs to be executed
    exit();
  }
}

$message = 'Invalid Credentials';
```

1) The output of a hashing function is often called the digest or simply the hash.

2) A rainbow table is a database generated by giving the target hashing function a large list of probable passwords, i.e. generating, by brute force, a long list of digests to compare to a compromised set of digests. This is usually a rather time-intensive operation.

3) I'm not actually sure whether password_hash() prepends or appends the salt to the password to generate the digest.

4) See the documentation for more information about the format of the output (explained in the FAQ about password hashing) algorithms (explained in password_hash()) and cost (explained in crypt()).

Body:
General information on (cryptographic) hashing

Hashing is often confused with encrypting, but they're different and have different use-cases:

Encryption is meant for encoding something such that it can be deciphered again (with the right key), making it a two-way process.

(Cryptographic) hashing, on the other hand, is a one-way process to encode something that is explicitly not meant to be decipherable. Furthermore, a hashing function is deterministic, meaning that given the same message, it will always produce the same digest.1

So, here is why cryptographic hashing is used to encode passwords:

For hopefully obvious security reasons, you don't want anyone to be able to decipher the hashed password (not some adversary who was able to compromise your database and not even you, the web master, since that would allow you to compromise a user's account somewhere else, if they use the same password over there), but you do want to be able to verify that the password entered by the user matches the password they signed up with.

Since, as mentioned before, a hashing function is deterministic, we can achieve this by comparing the hash produced at an authentication process (such as logging in) and the hash produced at the sign-up process.

"But wait...," I hear you think, "in your comment you told me I would not be able to simply compare them".

If the message given to a bare hashing function is the same, you can and that's the problem with the deterministic aspect of hashing functions, in the context of password hashing: they produce the same output.

This means that if Alice, Bob and Charlie use the same password, they all produce the same digests:

 id | username | pwdhash
----+----------+---------
 17 | Alice    | 9Wdm...
 48 | Bob      | 9Wdm...
 57 | Charlie  | 9Wdm...

This poses two prominent security risks:

if you know Alice's password, you know the others' as well;

an adversary could, knowing the hashing function you use, theoretically generate, what is called, a rainbow table2 and compare its hashes with your hashes (if your database was compromised), to infer the actual passwords that match those in the rainbow table.

So, to mitigate these risks it is considered mandatory practice to add, what is called, a salt to the message (the password), before hashing it. A salt is meant to be unique enough to guarantee that two identical passwords produce completely different digests when fed to the same hashing function.

Pseudo example:

// produces same digests:
hash( 'password' ) -> bhZPmushb...
hash( 'password' ) -> bhZPmushb...

// produces unique digests:
        salt       message
hash( 'SeNib6' . 'password' ) -> qDHkfTW9m...
hash( '9pBq7y' . 'password' ) -> XH26YVUnA...

And this, by default, is what password_hash() automatically does for you, under the hood.3 It then prepends the used salt to the digest, along with information about the actual algorithm that was used and the cost.4 password_verify() will then use this additional information and the used salt to generate the same digest again, if the provided password matches the earlier hashed password.

It's therefore essential that the complete output of password_hash() is stored so that it can be fed into password_verify() as its second argument.

So, what does all this mean for your case?

Since password_hash() automatically adds a salt and therefore generates two different digests for identical passwords, you can't simply compare password_hash()'s output. This also means you can't (easily; I wouldn't be surprised if there was some way to make it work) compare password hashes at the database level, like you intended, with password = :password; you will have to compare the hashes in PHP, which means that you will have to fetch the user's record first and then verify the password hashes:

$query = "SELECT * FROM credentials WHERE username = :username";
$statement = $conn->prepare($query);
$statement->execute(array('username' => $_POST["userName"]));

// I believe PDOStatement::rowCount() doesn't work with MySQL for SELECT statements
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = count($rows);
if($count > 1) { // this might be redundant in your setup
  // this is not supposed to happen, usernames should be unique
  // log or alert developer
}
else if($count == 1) {
  $row = $rows[0];
  if(password_verify($_POST["userPass"], $row['password')) {
    // don't store $_POST["userName"] in $_SESSION["username"], but use the database value
    $_SESSION["username"] = $row["username"];
    header("Location: user-homepage.php");
    // it's good practice to exit after a redirect, unless other code still needs to be executed
    exit();
  }
}

$message = '<label>Invalid Credentials</label>';

1) The output of a hashing function is often called the digest or simply the hash.

2) A rainbow table is a database generated by giving the target hashing function a large list of probable passwords, i.e. generating, by brute force, a long list of digests to compare to a compromised set of digests. This is usually a rather time-intensive operation.

3) I'm not actually sure whether password_hash() prepends or appends the salt to the password to generate the digest.

4) See the documentation for more information about the format of the output (explained in the FAQ about password hashing) algorithms (explained in password_hash()) and cost (explained in crypt()).


问:
use ngx-translate in nativescript ,issure : ERROR Error: Uncaught (in promise): [object Object]
I want implement mulit-language ,using ngx-translate in my nativescript app. I do all the code like this  (https://nativescript.nl/tips/how-to-create-a-multilingual-nativescript-app-with-angular-4/). when run 'tns run ios' , it will appear the issue  as blew:

this is my demo code:

app.module.ts

```<code>import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NSModuleFactoryLoader } from "nativescript-angular/router";
import { NativeScriptFormsModule } from "nativescript-angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

import { NativeScriptHttpModule } from "nativescript-angular/http";
import { HttpClient, HttpClientModule } from "@angular/common/http";

import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
// import { Http } from "@angular/http";

// for AoT compilation
export function translateLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, "/i18n/", ".json");
};

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        NativeScriptFormsModule,
        AppRoutingModule,
        NativeScriptHttpModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                deps: [HttpClient],
                useFactory: (translateLoaderFactory)
            }
        })

    ],
    declarations: [
        AppComponent
    ],
    providers: [
        { provide: NgModuleFactoryLoader, useClass: NSModuleFactoryLoader },
        HttpClient,
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from "@angular/core";

// import * as Platform from "platform";
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html"
})
export class AppComponent {

    constructor(private translate: TranslateService) {

        translate.addLangs(["en", "zh"]);
        translate.setDefaultLang("en");
        // translate.use(Platform.device.language);
    }
}
</code>```

home.component.html

```<code><GridLayout class="page page-content">
    <Label  [text]="'HOME.TITLE' | translate"></Label>
</GridLayout>
</code>```

package.json

```<code>{
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.MutilLanguageDemo",
    "tns-ios": {
      "version": "3.3.0"
    }
  },
  "scripts": {
    "lint": "tslint \"app/**/*.ts\""
  },
  "dependencies": {
    "@angular/animations": "4.4.6",
    "@angular/common": "4.4.6",
    "@angular/compiler": "4.4.6",
    "@angular/core": "4.4.6",
    "@angular/forms": "4.4.6",
    "@angular/http": "4.4.6",
    "@angular/platform-browser": "4.4.6",
    "@angular/router": "4.4.6",
    "@ngx-translate/core": "7.2.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "nativescript-angular": "4.4.1",
    "nativescript-theme-core": "1.0.4",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.5.2",
    "tns-core-modules": "3.3.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "codelyzer": "3.2.2",
    "nativescript-dev-sass": "1.3.2",
    "nativescript-dev-typescript": "0.5.1",
    "node-sass": "4.5.3",
    "tslint": "5.8.0",
    "typescript": "2.4.2"
  }
}
</code>```

error code

```<code>CONSOLE LOG file:///app/tns_modules/@angular/core/./bundles/core.umd.js:2957:20: Angular is running in the development mode. Call enableProdMode() to enable the production mode.
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): Error: Template parse errors:
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): [object Object]
</code>```

that all ，Any suggestions are very grateful. thanks!

答:
sorry,error code

CONSOLE LOG file:///app/tns_modules/@angular/core/./bundles/core.umd.js:2957:20: Angular is running in the development mode. Call enableProdMode() to enable the production mode.
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): Error: Template parse errors:
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): [object Object]```

Body:
I want implement mulit-language ,using ngx-translate in my nativescript app. I do all the code like this  (https://nativescript.nl/tips/how-to-create-a-multilingual-nativescript-app-with-angular-4/). when run 'tns run ios' , it will appear the issue  as blew:

this is my demo code:

app.module.ts

import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NSModuleFactoryLoader } from "nativescript-angular/router";
import { NativeScriptFormsModule } from "nativescript-angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

import { NativeScriptHttpModule } from "nativescript-angular/http";
import { HttpClient, HttpClientModule } from "@angular/common/http";

import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
// import { Http } from "@angular/http";

// for AoT compilation
export function translateLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(http, "/i18n/", ".json");
};

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        NativeScriptFormsModule,
        AppRoutingModule,
        NativeScriptHttpModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                deps: [HttpClient],
                useFactory: (translateLoaderFactory)
            }
        })

    ],
    declarations: [
        AppComponent
    ],
    providers: [
        { provide: NgModuleFactoryLoader, useClass: NSModuleFactoryLoader },
        HttpClient,
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

app.component.ts

import { Component } from "@angular/core";

// import * as Platform from "platform";
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html"
})
export class AppComponent {

    constructor(private translate: TranslateService) {

        translate.addLangs(["en", "zh"]);
        translate.setDefaultLang("en");
        // translate.use(Platform.device.language);
    }
}

home.component.html

<GridLayout class="page page-content">

</GridLayout>

package.json

{
  "description": "NativeScript Application",
  "license": "SEE LICENSE IN <your-license-filename>",
  "readme": "NativeScript Application",
  "repository": "<fill-your-repository-here>",
  "nativescript": {
    "id": "org.nativescript.MutilLanguageDemo",
    "tns-ios": {
      "version": "3.3.0"
    }
  },
  "scripts": {
    "lint": "tslint \"app/**/*.ts\""
  },
  "dependencies": {
    "@angular/animations": "4.4.6",
    "@angular/common": "4.4.6",
    "@angular/compiler": "4.4.6",
    "@angular/core": "4.4.6",
    "@angular/forms": "4.4.6",
    "@angular/http": "4.4.6",
    "@angular/platform-browser": "4.4.6",
    "@angular/router": "4.4.6",
    "@ngx-translate/core": "7.2.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "nativescript-angular": "4.4.1",
    "nativescript-theme-core": "1.0.4",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.5.2",
    "tns-core-modules": "3.3.0",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "codelyzer": "3.2.2",
    "nativescript-dev-sass": "1.3.2",
    "nativescript-dev-typescript": "0.5.1",
    "node-sass": "4.5.3",
    "tslint": "5.8.0",
    "typescript": "2.4.2"
  }
}

error code

CONSOLE LOG file:///app/tns_modules/@angular/core/./bundles/core.umd.js:2957:20: Angular is running in the development mode. Call enableProdMode() to enable the production mode.
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): Error: Template parse errors:
CONSOLE ERROR file:///app/tns_modules/@angular/core/./bundles/core.umd.js:1052:24: ERROR Error: Uncaught (in promise): [object Object]

that all ，Any suggestions are very grateful. thanks!


问:
How do I make buttons go across horizontal vs. stacking & make them 50% (2 by 2) on mobile?
I am trying to achieve the following look for desktop & mobile -

Here is what I have so far -

    .container {
        display: flex;
        flex-direction:row;
        margin: 0 auto;
        width: 100%;
        max-width: 1170px;
        flex-wrap: wrap;
        height:100vh;
    }

    .button {
        letter-spacing: 1px;
        justify-content: space-between;
        flex: 1 0 auto;
        align-items: flex-start;
    }
    /* ---- Intro ---- */

    #intro {
        background: #ff6400;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4em 0;
    }

    #intro .cta {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;
    }

    #intro .cta .splash {
        display: none;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='intro'>
    <div class='cta container'>
        <div class="herosvg-container"><img src="http://svgshare.com/i/407.svg" width="100%"></div>
        <p>Delectus illum corporis laundantium illo repudiandae et doloemque.</p>
         <span>SHOP NOW</span>
         <span>SHOP NOW</span>
         <span>SHOP NOW</span>
         <span>SHOP NOW</span>
    </div>
</div></code>```

I'd like to avoid running into the issue where the buttons might overlap the svg, or vise versa. Also I'd like the ability to control the width of buttons and svg separately while being able to say "i want to float the svg and buttons to the left or right of the hero."

If you have any ideas or can point me to the right direction you would be a life saver.

Thanks!

答:
Adding a min-width to your buttons should cause them to wrap when they get smaller than that width.

I believe all the buttons will be the same width, but if not you could add width: 50% to the buttons inside a media query for smaller screens.

Body:
I am trying to achieve the following look for desktop & mobile -

Here is what I have so far -

    .container {
        display: flex;
        flex-direction:row;
        margin: 0 auto;
        width: 100%;
        max-width: 1170px;
        flex-wrap: wrap;
        height:100vh;
    }

    .button {
        letter-spacing: 1px;
        justify-content: space-between;
        flex: 1 0 auto;
        align-items: flex-start;
    }
    /* ---- Intro ---- */

    #intro {
        background: #ff6400;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 4em 0;
    }

    #intro .cta {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;
    }

    #intro .cta .splash {
        display: none;
    }

Delectus illum corporis laundantium illo repudiandae et doloemque.

         SHOP NOW
         SHOP NOW
         SHOP NOW
         SHOP NOW

I'd like to avoid running into the issue where the buttons might overlap the svg, or vise versa. Also I'd like the ability to control the width of buttons and svg separately while being able to say "i want to float the svg and buttons to the left or right of the hero."

If you have any ideas or can point me to the right direction you would be a life saver.

Thanks!


问:
Performing an operation over the elements of one collection and iterating over the result to perform some other operation
If I have 2 collections,

```<code>List<String> domainArr;
List<Person> personArr;
</code>```

I would like to make a minor transformation on each of the elements in the String and then iterate over the personArr to

```<code>List<String> urlArr = strArr.stream()
    .map(str -> "https://" + strArr)
    .collect(Collectors.toList());
</code>```

I have a method like

```<code>List<Person> getPersons(String url){
 /*makes a restful call to the url and gets a List of objects for each URL.*/
}
</code>```

I would like to iterate over each of the urls from urlArr and pass it to the getPersons(url) method and for each of the obtained result (a List), I would like to iterate over the person and perform more operations on the persons like

```<code>persons.stream()
     .filter(Objects::nonNull)
     .map(Person::getName)
     .filter(Objects::nonNull)
     .collect(Collectors.toList());
</code>```

I am hoping to have all the person names here from all the results.

I was wondering how to do this the functional way in Java 8. Any pointers?

答:
You can use flatMap to convert your stream of List<T> into flat stream of T

```<code>strArr.stream()
    .map(str -> "https://" + strArr)
    .map(url -> getPersons(url))
    .flatMap(persons -> persons.stream())
    .filter(Objects::nonNull)
    .map(Person::getName)
    .filter(Objects::nonNull)
    .collect(Collectors.toList());
</code>```

Body:
If I have 2 collections,

List<String> domainArr;
List<Person> personArr;

I would like to make a minor transformation on each of the elements in the String and then iterate over the personArr to

List<String> urlArr = strArr.stream()
    .map(str -> "https://" + strArr)
    .collect(Collectors.toList());

I have a method like

List<Person> getPersons(String url){
 /*makes a restful call to the url and gets a List of objects for each URL.*/
}

I would like to iterate over each of the urls from urlArr and pass it to the getPersons(url) method and for each of the obtained result (a List), I would like to iterate over the person and perform more operations on the persons like

persons.stream()
     .filter(Objects::nonNull)
     .map(Person::getName)
     .filter(Objects::nonNull)
     .collect(Collectors.toList());

I am hoping to have all the person names here from all the results.

I was wondering how to do this the functional way in Java 8. Any pointers?

Body:
You can use flatMap to convert your stream of List<T> into flat stream of T

strArr.stream()
    .map(str -> "https://" + strArr)
    .map(url -> getPersons(url))
    .flatMap(persons -> persons.stream())
    .filter(Objects::nonNull)
    .map(Person::getName)
    .filter(Objects::nonNull)
    .collect(Collectors.toList());


问:
Porting web-app for a tablet
My web app is written in Java with front-end in JS. I want to port to tablet and other touch mobile devices. Developing a native API is ofcourse an option but I would prefer making the old app work on tablet.

I know I would need to make some changes in UI for the touch interface and I am willing to do it.

So My question is: A*re there tablet Simulators available on which I can try my app and see where it breaks on such device.*

What would be the best approach to proceed on this?

thanks in advance!

答: Tablets use various OS's and, thus, different API's, supported features, etc...  For iPad, for imstance, XCode provides a simulator.  I read somewhere that the BB tablet coming out will have a simulator for dev as well.</p>

Title: Porting web-app for a tablet


问:
Django - prefetch_related for specific situation doesn't work
I have a three models: Trip, City and GoogleApiCityCache.

If I want to know name of the city, I use @property on City object which tries to get GoogleApiCityCache for current language.

I want to reduce a number of queries in my template:

```<code>{% for trip in trips %}
    {{ trip.city.formatted_address }}
{% endfor %}
</code>```

Now, it performs new db query to find GoogleApiCityCache in each iteration. I want to prefetch these caches.

So property formatted_address has to find a GoogleApiCityCache and get formatted_address from this object.

Tried to use prefetch_related but it doesn't help.

```<code>def profile(request, slug):
    owner = User.objects.filter(userprofile__slug=slug).prefetch_related('trips__city__city_caches').first()
    trips = Trip.objects.filter(user=owner).select_related('city').prefetch_related('city__city_caches')
    return render(request, 'profiles/profile/profile.html', {'owner': owner,'trips':trips})
</code>```

My models:

```<code>class Trip(models.Model):
    user = models.ForeignKey('auth.User', related_name='trips')
    city = models.ForeignKey('locations.City', related_name='trips')
    date_from = models.DateField()
    date_to = models.DateField()
    detail = models.TextField(null=True, blank=True)
    # participants = models.ManyToManyField('auth.User', related_name='participating_on_trips', blank=True)
    objects = TripManager()

class City(models.Model):
    ...
    def get_cache_by_lang(self, lang=None, force_refresh=False):
        if not lang:
            lang = get_language() or 'en'
        cache, requested = GoogleApiCityCache.objects.get_or_request(city=self, lang=lang)
        return cache

    @property
    def formatted_address(self):
        return self.get_cache_by_lang().formatted_address

class GoogleApiCityCacheManager(models.Manager):
    def _request_create(self, city, lang):
        """ Create cache (wasn't found) """
        ....
        return cache

    def get_or_request(self, city, lang):
        created = False
        try:
            cache = GoogleApiCityCache.objects.get(city=city, language_code=lang)
        except GoogleApiCityCache.DoesNotExist:
            cache = self._request_create(city, lang)
            created = True
        return cache,created

class GoogleApiCityCache(models.Model):
    language_code = models.CharField(max_length=5)
    api_json_response = JSONField(null=True, blank=True)
    city = models.ForeignKey('locations.City', on_delete=models.CASCADE, related_name='city_caches')
    objects = GoogleApiCityCacheManager()

    class Meta:
        unique_together = ('city', 'language_code')

    @property
    def formatted_address(self):
        try:
            return self.api_json_response['result']['formatted_address']
        except:
            return None
</code>```

As you can see, GoogleApiCityCache for city and language_code can be none. In this case, the Google Api is requested, created a new GoogleApiCityCache object and returned.

答:
When you prefetch_related('trips__city__city_caches'), you are prefetching the city_caches. That means that the following loop will not cause any extra queries.

```<code>for cache in city.city_caches.all()
    print(cache)
</code>```

However, in your code formatted_address calls get_cache_by_lang which calls get_or_request which calls GoogleApiCityCache.objects.get(), which will cause extra queries.

In order to take advantage of prefetch_related, you need to rewrite get_cache_by_lang so that it loops through self.city_caches.all() to find the correct object.

Body:
I have a three models: Trip, City and GoogleApiCityCache.

If I want to know name of the city, I use @property on City object which tries to get GoogleApiCityCache for current language.

I want to reduce a number of queries in my template:

{% for trip in trips %}
    {{ trip.city.formatted_address }}
{% endfor %}

Now, it performs new db query to find GoogleApiCityCache in each iteration. I want to prefetch these caches.

So property formatted_address has to find a GoogleApiCityCache and get formatted_address from this object.

Tried to use prefetch_related but it doesn't help.

def profile(request, slug):
    owner = User.objects.filter(userprofile__slug=slug).prefetch_related('trips__city__city_caches').first()
    trips = Trip.objects.filter(user=owner).select_related('city').prefetch_related('city__city_caches')
    return render(request, 'profiles/profile/profile.html', {'owner': owner,'trips':trips})

My models:

class Trip(models.Model):
    user = models.ForeignKey('auth.User', related_name='trips')
    city = models.ForeignKey('locations.City', related_name='trips')
    date_from = models.DateField()
    date_to = models.DateField()
    detail = models.TextField(null=True, blank=True)
    # participants = models.ManyToManyField('auth.User', related_name='participating_on_trips', blank=True)
    objects = TripManager()

class City(models.Model):
    ...
    def get_cache_by_lang(self, lang=None, force_refresh=False):
        if not lang:
            lang = get_language() or 'en'
        cache, requested = GoogleApiCityCache.objects.get_or_request(city=self, lang=lang)
        return cache

    @property
    def formatted_address(self):
        return self.get_cache_by_lang().formatted_address

class GoogleApiCityCacheManager(models.Manager):
    def _request_create(self, city, lang):
        """ Create cache (wasn't found) """
        ....
        return cache

    def get_or_request(self, city, lang):
        created = False
        try:
            cache = GoogleApiCityCache.objects.get(city=city, language_code=lang)
        except GoogleApiCityCache.DoesNotExist:
            cache = self._request_create(city, lang)
            created = True
        return cache,created

class GoogleApiCityCache(models.Model):
    language_code = models.CharField(max_length=5)
    api_json_response = JSONField(null=True, blank=True)
    city = models.ForeignKey('locations.City', on_delete=models.CASCADE, related_name='city_caches')
    objects = GoogleApiCityCacheManager()

    class Meta:
        unique_together = ('city', 'language_code')

    @property
    def formatted_address(self):
        try:
            return self.api_json_response['result']['formatted_address']
        except:
            return None

As you can see, GoogleApiCityCache for city and language_code can be none. In this case, the Google Api is requested, created a new GoogleApiCityCache object and returned.

Body:
When you prefetch_related('trips__city__city_caches'), you are prefetching the city_caches. That means that the following loop will not cause any extra queries.

for cache in city.city_caches.all()
    print(cache)

However, in your code formatted_address calls get_cache_by_lang which calls get_or_request which calls GoogleApiCityCache.objects.get(), which will cause extra queries.

In order to take advantage of prefetch_related, you need to rewrite get_cache_by_lang so that it loops through self.city_caches.all() to find the correct object.


问:
Segmented Control returning wrong value?
I have the following code: </p>

```<code>@IBAction func didSelect(_ segmentIndex: Int) {
    switch segmentIndex
    {
    case 0:
        print ("1")

    case 1:
        // SHOWING THE PROFILE VIEW
        print ("2")

    default:
        print  ("break")
    }
}
</code>```

<p>I only have 2 tabs on the segment control, and whatever I click, it keeps printing "break". Why does that happen? </p>

答:
The parameter of an IBAction must be the type of the connected UI element.

So you have to pass UISegmentedControl and switch on its selectedSegmentIndex

```<code>@IBAction func didSelect(_ control: UISegmentedControl) {
    switch control.selectedSegmentIndex
    {
    case 0:
        print ("1")

    case 1:
        // SHOWING THE PROFILE VIEW
        print ("2")

    default:
        print  ("break")
    }
}
</code>```

Body:
I have the following code:

@IBAction func didSelect(_ segmentIndex: Int) {
    switch segmentIndex
    {
    case 0:
        print ("1")

    case 1:
        // SHOWING THE PROFILE VIEW
        print ("2")

    default:
        print  ("break")
    }
}

I only have 2 tabs on the segment control, and whatever I click, it keeps printing "break". Why does that happen?

Body:
The parameter of an IBAction must be the type of the connected UI element.

So you have to pass UISegmentedControl and switch on its selectedSegmentIndex

@IBAction func didSelect(_ control: UISegmentedControl) {
    switch control.selectedSegmentIndex
    {
    case 0:
        print ("1")

    case 1:
        // SHOWING THE PROFILE VIEW
        print ("2")

    default:
        print  ("break")
    }
}


答:
Since diff() returns a DateInterval instance you could run conditional checks to get your expected result.

```<code>$createdTime = Carbon::parse($specialist->created_at)
                        ->diff(Carbon::now());

$final_string = '';
$year = '';
$month = '';
$days = '';

if ($createdTime->y) {
    $year = $createdTime->y . ' yr';
}

if ($createdTime->m) {
    $month = ' '. $createdTime->m . ' mo';
}

if ($createdTime->d) {
    $days = ' ' . $createdTime->d . ' days';
}

$final_string = trim($year . $month . $days);
</code>```

Title: Remove 0, if return 0 year or 0 month DateFormat

Body:
Since diff() returns a DateInterval instance you could run conditional checks to get your expected result.

$createdTime = Carbon::parse($specialist->created_at)
                        ->diff(Carbon::now());

$final_string = '';
$year = '';
$month = '';
$days = '';

if ($createdTime->y) {
    $year = $createdTime->y . ' yr';
}

if ($createdTime->m) {
    $month = ' '. $createdTime->m . ' mo';
}

if ($createdTime->d) {
    $days = ' ' . $createdTime->d . ' days';
}

$final_string = trim($year . $month . $days);


问:
Test plain javascript file returning different objects
Is it possible to test the code below with Jasmine testing tool or any other npm module like rewire or similar?</p>

```<code>const AuthValidatorDumb = require('./src/AuthValidatorDumb');
const AuthValidator = require('./src/AuthValidator');
const config = require('../config');

let instance;

if (!instance) {
  if (config.get('auth.enabled')) {
    instance = AuthValidator;
  } else {
    instance = AuthValidatorDumb;
  }
}

module.exports = instance;
</code>```

答:
I've got a variant for testing the code above.Suppose you have:

1) The code for index.js in the question above.

2) AuthValidator.js:

```<code>class AuthValidator {}
module.exports = AuthValidator;
</code>```

3) AuthValidatorDumb.js:

```<code>class AuthValidatorDumb {}
module.exports = AuthValidatorDumb;
</code>```

Here is test/index.spec.js:

```<code>const proxyquire = require('proxyquire');
const AuthValidator = require('../src/AuthValidator');
const AuthValidatorDumb = require('../src/AuthValidatorDumb');

describe('auth index', () => {
  it('should return AuthValidator', () => {
    const configMock = { get: () => 'sth' };
    const Instance = proxyquire('../index', {
      '../config': configMock,
    });
    expect(new Instance() instanceof AuthValidator).toBeTruthy();
  });

  it('should return AuthValidatorDumb', () => {
    const configMock = { get: () => undefined };
    const Instance = proxyquire('../index', {
      '../config': configMock,
    });
    expect(new Instance() instanceof AuthValidatorDumb).toBeTruthy();
  });
});
</code>```

Body:
Is it possible to test the code below with Jasmine testing tool or any other npm module like rewire or similar?

const AuthValidatorDumb = require('./src/AuthValidatorDumb');
const AuthValidator = require('./src/AuthValidator');
const config = require('../config');

let instance;

if (!instance) {
  if (config.get('auth.enabled')) {
    instance = AuthValidator;
  } else {
    instance = AuthValidatorDumb;
  }
}

module.exports = instance;

Body:
I've got a variant for testing the code above.Suppose you have:

1) The code for index.js in the question above.

2) AuthValidator.js:

class AuthValidator {}
module.exports = AuthValidator;

3) AuthValidatorDumb.js:

class AuthValidatorDumb {}
module.exports = AuthValidatorDumb;

Here is test/index.spec.js:

const proxyquire = require('proxyquire');
const AuthValidator = require('../src/AuthValidator');
const AuthValidatorDumb = require('../src/AuthValidatorDumb');

describe('auth index', () => {
  it('should return AuthValidator', () => {
    const configMock = { get: () => 'sth' };
    const Instance = proxyquire('../index', {
      '../config': configMock,
    });
    expect(new Instance() instanceof AuthValidator).toBeTruthy();
  });

  it('should return AuthValidatorDumb', () => {
    const configMock = { get: () => undefined };
    const Instance = proxyquire('../index', {
      '../config': configMock,
    });
    expect(new Instance() instanceof AuthValidatorDumb).toBeTruthy();
  });
});


问:
Correct way to do Create and Update actions for one to many objects in .Net Core Ef Core
I'm working on my first .Net Core application and I was able to put together the CRUD actions for my first table.

The second table has a foreign key to the first table and I think I've gone off on the wrong path in trying to put together the Create and Update actions. The Update action needs to pass in all items from the foreign key table for the user to select from. But as an update Action, the View needs to have the actual objects foreign key selected from the drop-down list.

What's the correct way to do this? I can't seem to find a consistent answer on Google.

Table 1 Model:

```<code> public class HTMLElement
{
    public int Id { get; set; }
    public string Element { get; set; }
    public string ElementName { get; set; }

    public virtual ICollection<CustomizedElement> CustomizeHTMLElements { get; set; }
}
</code>```

Table 2 Model:

```<code>public class CustomizedElement
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int? HTMLElementId { get; set; }
    public HTMLElement HTMLElement { get; set; }
}
</code>```

ViewModel for Table Two:

```<code>public class CustomizedHTMLElementViewModel
{
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "HTML Element")]
    public int HTMLElement { get; set; }

    [Display(Name = "HTML Elements")]
    public ICollection<HTMLElement> HTMLElements { get; set; }
}
</code>```

Create Controller:

I want to pass in all of the items from Table 1 into the view for a drop-down list that the user can select from and this works but not sure if it's the correct way to do this.

```<code>[HttpGet]
    public IActionResult AddCustomizedHTMLElement()
    {
        var elements = new CustomizedHTMLElementViewModel
        {
            HTMLElements = db.HTMLElements.ToList()
        };

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

The Post action is working but not sure if it's the most efficient.

```<code>[HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AddCustomizedHTMLElement(CustomizedHTMLElementViewModel CHTMLEV)
    {
    if (ModelState.IsValid)
    {
        var element = db.HTMLElements.Single(e => e.Id == CHTMLEV.HTMLElement);

        CustomizedElement cElement = new CustomizedElement()
        {
            Name = CHTMLEV.Name,
            HTMLElement = element,
        };
        db.CustomizedElements.Add(cElement);
        db.SaveChanges();
        return RedirectToAction("CustomizedHTMLElements");
    }
    return View(CHTMLEV);
}
</code>```

I'm having a really hard time with the Update action. I want to pass in all foreign keys but also have the objects foreign key selected in the drop-down list in the View

```<code>[HttpGet]
public IActionResult UpdateCustomizedHTMLElement(int Id)
{
    var mElement = db.CustomizedElements.Include(e => e.HTMLElement).FirstOrDefault(e => e.Id == Id);
    ViewBag.ElementsList = db.HTMLElements.ToList();
    return View(mElement);
}
</code>```

I haven't worked on the Update actions [HttpPost] yet until I get the View right.

Update View:

```<code><form method="post" asp-controller="Templates" asp-action="UpdateCustomizedHTMLElement">
    <div class="form-group">
        <label asp-for="Name"></label>:
        <input class="form-control form-control-sm" type="text" asp-for="Name" />
        <span class="text-danger" asp-validation-for="Name"></span>
    </div>
    <div class="form-group">
        <label asp-for="HTMLElement"></label>:
        @Html.DropDownListFor(m => m.HTMLElement, new SelectList(ViewBag.ElementsList, "Id", "Element"), new { @class = "form-control" })
         <span class="text-danger" asp-validation-for="HTMLElement"></span>
    </div>
    <div>
         <button class="btn btn-primary" type="submit" value="Submit">Save</button>
         <button class="btn btn-secondary" type="button" value="Cancel" onclick="location.href='@Url.Action("CustomizedHTMLElements", "Templates")'">Cancel</button>
    </div>
</form>
</code>```

答:
```<code>public class UpdateCustomizedHTMLViewModel
{
   public int SelectedHtmlElementId { get; set;}
   public CustomizedElement ElementToUpdate { get; set;}
   public ICollection<HTMLElement> HTMLElements { get; set;}
}
</code>```

Then fill ElementToUpdate and HTMLElements in your get and when you select the HTMLElement you want to update with in the dropdown you assign that Id to SelectedHtmlElementId

Body:
I'm working on my first .Net Core application and I was able to put together the CRUD actions for my first table.

The second table has a foreign key to the first table and I think I've gone off on the wrong path in trying to put together the Create and Update actions. The Update action needs to pass in all items from the foreign key table for the user to select from. But as an update Action, the View needs to have the actual objects foreign key selected from the drop-down list.

What's the correct way to do this? I can't seem to find a consistent answer on Google.

Table 1 Model:

 public class HTMLElement
{
    public int Id { get; set; }
    public string Element { get; set; }
    public string ElementName { get; set; }

    public virtual ICollection<CustomizedElement> CustomizeHTMLElements { get; set; }
}

Table 2 Model:

public class CustomizedElement
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int? HTMLElementId { get; set; }
    public HTMLElement HTMLElement { get; set; }
}

ViewModel for Table Two:

public class CustomizedHTMLElementViewModel
{
    [Display(Name = "Name")]
    public string Name { get; set; }

    [Display(Name = "HTML Element")]
    public int HTMLElement { get; set; }

    [Display(Name = "HTML Elements")]
    public ICollection<HTMLElement> HTMLElements { get; set; }
}

Create Controller:

I want to pass in all of the items from Table 1 into the view for a drop-down list that the user can select from and this works but not sure if it's the correct way to do this.

[HttpGet]
    public IActionResult AddCustomizedHTMLElement()
    {
        var elements = new CustomizedHTMLElementViewModel
        {
            HTMLElements = db.HTMLElements.ToList()
        };

        return View(elements);
}

The Post action is working but not sure if it's the most efficient.

[HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AddCustomizedHTMLElement(CustomizedHTMLElementViewModel CHTMLEV)
    {
    if (ModelState.IsValid)
    {
        var element = db.HTMLElements.Single(e => e.Id == CHTMLEV.HTMLElement);

        CustomizedElement cElement = new CustomizedElement()
        {
            Name = CHTMLEV.Name,
            HTMLElement = element,
        };
        db.CustomizedElements.Add(cElement);
        db.SaveChanges();
        return RedirectToAction("CustomizedHTMLElements");
    }
    return View(CHTMLEV);
}

I'm having a really hard time with the Update action. I want to pass in all foreign keys but also have the objects foreign key selected in the drop-down list in the View

[HttpGet]
public IActionResult UpdateCustomizedHTMLElement(int Id)
{
    var mElement = db.CustomizedElements.Include(e => e.HTMLElement).FirstOrDefault(e => e.Id == Id);
    ViewBag.ElementsList = db.HTMLElements.ToList();
    return View(mElement);
}

I haven't worked on the Update actions [HttpPost] yet until I get the View right.

Update View:

<form method="post" asp-controller="Templates" asp-action="UpdateCustomizedHTMLElement">

        :
        <input class="form-control form-control-sm" type="text" asp-for="Name" />

        :
        @Html.DropDownListFor(m => m.HTMLElement, new SelectList(ViewBag.ElementsList, "Id", "Element"), new { @class = "form-control" })

         <button class="btn btn-primary" type="submit" value="Submit">Save</button>
         <button class="btn btn-secondary" type="button" value="Cancel" onclick="location.href='@Url.Action("CustomizedHTMLElements", "Templates")'">Cancel</button>

</form>

Body:
public class UpdateCustomizedHTMLViewModel
{
   public int SelectedHtmlElementId { get; set;}
   public CustomizedElement ElementToUpdate { get; set;}
   public ICollection<HTMLElement> HTMLElements { get; set;}
}

Then fill ElementToUpdate and HTMLElements in your get and when you select the HTMLElement you want to update with in the dropdown you assign that Id to SelectedHtmlElementId


问:
Disable all site creation except for a certain group
I want to lock down site creation to a certain group of admin suresh. We have created a group for this, but what do I tell the SharePoint Admin to do in order to achieve this?</p>

答:
To lock down site creation, you basically need to run a few PowerShell commands as below using Azure AD PowerShell. Run them commands with Global admin priviledges.

I am assuming that you have created an Azure AD group with certain users who will have access to create the site.

```<code>$creds = Get-Credential

Connect-AzureAD -Credential $creds

$group = Get-AzureADGroup -All $True | Where-Object {$_.DisplayName -eq "ENTER GROUP DISPLAY NAME HERE"}

$policySetting = Get-AzureADDirectorySetting | where-object {$_.displayname -eq "Group.Unified"}

if($policySetting -eq $null) {

    $template = Get-AzureADDirectorySettingTemplate | Where-Object {$_.DisplayName -eq "Group.Unified"}

    $settings = $template.CreateDirectorySetting()

    $settings["EnableGroupCreation"] = $false

    $settings["GroupCreationAllowedGroupId"] = $group.ObjectId

    $policySetting = New-AzureADDirectorySetting -DirectorySetting $settings
}
else{

    $policySetting["EnableGroupCreation"] = $false

    $policySetting["GroupCreationAllowedGroupId"] = $group.ObjectId

    Set-AzureADDirectorySetting -Id $policySetting.Id -DirectorySetting $policySetting
}
</code>```

Links:

Installing the Azure AD module

Code modified from - Managing Office 365 group creation using Azure AD PowerShell v2

Body:
To lock down site creation, you basically need to run a few PowerShell commands as below using Azure AD PowerShell. Run them commands with Global admin priviledges.

I am assuming that you have created an Azure AD group with certain users who will have access to create the site.

$creds = Get-Credential

Connect-AzureAD -Credential $creds

$group = Get-AzureADGroup -All $True | Where-Object {$_.DisplayName -eq "ENTER GROUP DISPLAY NAME HERE"}

$policySetting = Get-AzureADDirectorySetting | where-object {$_.displayname -eq "Group.Unified"}

if($policySetting -eq $null) {

    $template = Get-AzureADDirectorySettingTemplate | Where-Object {$_.DisplayName -eq "Group.Unified"}

    $settings = $template.CreateDirectorySetting()

    $settings["EnableGroupCreation"] = $false

    $settings["GroupCreationAllowedGroupId"] = $group.ObjectId

    $policySetting = New-AzureADDirectorySetting -DirectorySetting $settings
}
else{

    $policySetting["EnableGroupCreation"] = $false

    $policySetting["GroupCreationAllowedGroupId"] = $group.ObjectId

    Set-AzureADDirectorySetting -Id $policySetting.Id -DirectorySetting $policySetting
}

Links:

Installing the Azure AD module

Code modified from - Managing Office 365 group creation using Azure AD PowerShell v2


问:
VS 2017 AWS Lamda Publish error Max version supported by netcoreapp1.0 is 1.6.0
I am trying to publish from VA 2017 to AWS Lambda. It was working before updated some packages via NuGet.

I am now getting this following error:

```<code>Project is referencing NETStandard.Library version 1.6.1. Max version supported by netcoreapp1.0 is 1.6.0.
</code>```

How can I resolve this error?

答:
I had to downgrade the .net core version using package manager console command:

```<code>Install-Package NETStandard.Library -Version 1.6.0
</code>```

Worked

Body:
I am trying to publish from VA 2017 to AWS Lambda. It was working before updated some packages via NuGet.

I am now getting this following error:

Project is referencing NETStandard.Library version 1.6.1. Max version supported by netcoreapp1.0 is 1.6.0.

How can I resolve this error?

Body:
I had to downgrade the .net core version using package manager console command:

Install-Package NETStandard.Library -Version 1.6.0

Worked


问:
Loop to 100 then change change row x times
I am trying to create a vba loop that loops to 100 then continues value 101 at row 1 on the next column.

Column A data would have 1-100, B = 101-200, C = 201-300 etc.,

This is some code I got online and I am trying to modify it.

```<code>Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    'Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    'Set wks = wbTemp.Worksheets(1)
    Set wks = ThisWorkbook.Worksheets(1)
    Set rngInput = wks.Range("A:A")

    rngInput.Offset(, -1).ColumnWidth = 6.5
    rngInput.ColumnWidth = 6.5
    rngInput.HorizontalAlignment = xlRight

    For i = 1 To 100
        ctl.FaceId = i
        ctl.CopyFace
        rngInput.Cells(i).PasteSpecial
        rngInput.Cells(i).Value = i
    Next

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub
</code>```

Thanks for any help

答:
Here you can try this:

```<code>Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    Set wks = ThisWorkbook.Worksheets("Sheet1")

    Dim Number As Integer
    Dim FaceNumber As Integer
    Number = 1
    'Only doing the first 5 columns, change the 5 to what ever number you want to get the number of columns desired
    For x = 1 To 5
    'Moved the setting of the range into the first FOR loop to assign the column
    Set rngInput = wks.Range(wks.Cells(1, x), wks.Cells(100, x))
    'This will move down each row
        For i = 1 To 100
        'This updates the Face that you are producing so that it will not repeat the same 100 every column
            If x > 1 Then
                If i > 1 Then
                    FaceNumber = FaceNumber + 1
                Else
                    FaceNumber = 100 * x - 99
                End If
            Else
                FaceNumber = i
            End If
            ctl.FaceId = FaceNumber
            ctl.CopyFace
            rngInput.Cells(i).PasteSpecial
            rngInput.Cells(i).Value = FaceNumber
        Next i
    Next x

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub
</code>```

I've added comments to help you understand the updates that I made.

As a bonus here is a script that will remove the pictures that this places on your sheet so that you can test several times without having to select each picture one at a time to delete them:

```<code>Sub DeleteAllPics()
    Dim pic As Object
    For Each pic In ActiveSheet.Pictures
        pic.Delete
    Next pic
End Sub
</code>```

Body:
I am trying to create a vba loop that loops to 100 then continues value 101 at row 1 on the next column.

Column A data would have 1-100, B = 101-200, C = 201-300 etc.,

This is some code I got online and I am trying to modify it.

Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    'Set wbTemp = Workbooks.Add(xlWBATWorksheet)
    'Set wks = wbTemp.Worksheets(1)
    Set wks = ThisWorkbook.Worksheets(1)
    Set rngInput = wks.Range("A:A")

    rngInput.Offset(, -1).ColumnWidth = 6.5
    rngInput.ColumnWidth = 6.5
    rngInput.HorizontalAlignment = xlRight

    For i = 1 To 100
        ctl.FaceId = i
        ctl.CopyFace
        rngInput.Cells(i).PasteSpecial
        rngInput.Cells(i).Value = i
    Next

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub

Thanks for any help

Body:
Here you can try this:

Sub exa()
    Dim CB          As CommandBar
    Dim ctl         As CommandBarButton
    Dim strCBName   As String
    Dim wbTemp      As Workbook
    Dim wks         As Worksheet
    Dim rngInput    As Range
    Dim i           As Long

    Set CB = CommandBars.Add(Position:=msoBarPopup, MenuBar:=False, Temporary:=True)
    Set ctl = CB.Controls.Add(Type:=msoControlButton, Temporary:=True)
    strCBName = CB.Name

    Set wks = ThisWorkbook.Worksheets("Sheet1")

    Dim Number As Integer
    Dim FaceNumber As Integer
    Number = 1
    'Only doing the first 5 columns, change the 5 to what ever number you want to get the number of columns desired
    For x = 1 To 5
    'Moved the setting of the range into the first FOR loop to assign the column
    Set rngInput = wks.Range(wks.Cells(1, x), wks.Cells(100, x))
    'This will move down each row
        For i = 1 To 100
        'This updates the Face that you are producing so that it will not repeat the same 100 every column
            If x > 1 Then
                If i > 1 Then
                    FaceNumber = FaceNumber + 1
                Else
                    FaceNumber = 100 * x - 99
                End If
            Else
                FaceNumber = i
            End If
            ctl.FaceId = FaceNumber
            ctl.CopyFace
            rngInput.Cells(i).PasteSpecial
            rngInput.Cells(i).Value = FaceNumber
        Next i
    Next x

    rngInput.Cells(1).Select

    On Error Resume Next
    Set CB = CommandBars(strCBName)
    On Error GoTo 0

    If Not CB Is Nothing Then
        CB.Delete
    Else
        MsgBox "no toolbar!", 0, vbNullString
    End If
End Sub

I've added comments to help you understand the updates that I made.

As a bonus here is a script that will remove the pictures that this places on your sheet so that you can test several times without having to select each picture one at a time to delete them:

Sub DeleteAllPics()
    Dim pic As Object
    For Each pic In ActiveSheet.Pictures
        pic.Delete
    Next pic
End Sub


问:
Android App responding to USSD
Im Trying to develop an APP that responds to an USSD menu, can anyone give any pointer on how to respond on the menu USSD programmatically, i covered the part were to dial the fisrt USSD but how to repond on the secod menu???</p>

答:
This depends on the mobile operator you wish to integrate with or if you will be using a third party to facilitate your connectivity with mobile operators.

It also depends on whether you specified that the session is to be a continuing session when you displayed the first menu. This could be in the form of keywords such as CON or NEXTSTATE.

Majority of the mobile operators use HTTP so as long as you maintain the HTTP connection with them you can have interactive sessions.

Title: Android App responding to USSD


问:
React Redux - Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
I'm new to React, please keep this in mind.

I have seen many people having issues with the binding of "this" keyword, I think I got it right, however I'm still getting the error "Cannot read property 'props' of undefined".

I'm doing something wrong with my React+Redux app but I can't figure out what.

Here's my code:
Recipes_list.js

```<code>import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { getRecipe } from "../actions/index";

class RecipeList extends Component {
    constructor(props) {
        super(props);
        this.functionGetRecipe = this.functionGetRecipe.bind(this);
    }

    functionGetRecipe(recipe_id){
        this.props.getRecipe(recipe_id);
    }

    renderRecipes(recipeData) {
        const publisher = recipeData.publisher;
        const recipe_id = recipeData.recipe_id;
        const title = recipeData.title;
        const source_url = recipeData.source_url;
        const image_url = recipeData.image_url;

        return (
            <tr onClick={this.props.functionGetRecipe(recipe_id)} key={recipe_id}>
                <td>{publisher}</td>
                <td>{title}</td>
                <td><a href={source_url}>View on original website</a></td>
                <td><img className="img-fluid" src={image_url} /></td>
            </tr>
        );
    }

    render() {
        if (!this.props.recipes) {
            return <div>Nothing to show yet</div>;
        }
        return (
            <table style={{width: "50%"}} className="table table-hover float-right">
                <thead>
                    <tr>
                        <th>Publisher</th>
                        <th>Title</th>
                        <th>Source</th>
                        <th>Image</th>
                    </tr>
                </thead>
                <tbody>
                    {this.props.recipes.map(this.renderRecipes)}
                </tbody>
            </table>
        );
    }
}

function mapStateToProps(state){
    return { recipes: state.searchRecipes.recipes };
}

function mapDispachToProps(dispatch) {
    return bindActionCreators({ getRecipe }, dispatch);
}

export default connect(mapStateToProps, mapDispachToProps)(RecipeList);
</code>```

When this Container/Component gets re-rendered with an array of values (this.props.recipes) Chrome's console logs the following error:

```<code>Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
at renderRecipes (bundle.js:36675)
at Array.map (<anonymous>)
at RecipeList.render (bundle.js:36746)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:7779)
at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:7799)
at ReactCompositeComponentWrapper.wrapper [as _renderValidatedComponent] (bundle.js:1530)
at ReactCompositeComponentWrapper._updateRenderedComponent (bundle.js:7752)
at ReactCompositeComponentWrapper._performComponentUpdate (bundle.js:7736)
at ReactCompositeComponentWrapper.updateComponent (bundle.js:7665)
at ReactCompositeComponentWrapper.wrapper [as updateComponent] (bundle.js:1530)
</code>```

Any help is appreciated. Thank you.

NOTE: if I remove all the code related to the Action everything works fine, the table is displayed correctly

==============================================================================

EDIT: Modifing onClick={this.props.functionGetRecipe(recipe_id)} to onClick={this.functionGetRecipe(recipe_id)}
returns me the following error:

```<code>bundle.js:36675 Uncaught (in promise) TypeError: Cannot read property 'functionGetRecipe' of undefined
</code>```

Just in case, here's my /actions/index.js:

```<code>import axios from 'axios';
const API_KEY = "***********************************";
export const GET_URL = `https://food2fork.com/api/get?key=${API_KEY}`;
export function getRecipe(recipeId) {
    const url = `${GET_URL}&Id=${recipeId}`;
    const request = axios.get(url);

    return {
        type: GET_RECIPE,
        payload: request
    };
}
</code>```

==============================================================================

EDIT2:
That was it, now it works. Here's the change:

```<code>constructor(props) {
    super(props);
    this.renderRecipes = this.renderRecipes.bind(this);
}
</code>```

答:
Try replacing

```<code><tr onClick={this.props.functionGetRecipe(recipe_id)} key={recipe_id}>
</code>```

By :

```<code><tr onClick={this.functionGetRecipe(recipe_id)} key={recipe_id}>
</code>```

Edit : I think declaring your method functionGetRecipe() is useless you can use this.props.getRecipe(recipe_id) directly

Edit 2 : try binding renderRecipes instead :

```<code>constructor(props) {
        super(props);
        this.renderRecipes = this.renderRecipes.bind(this);
    }
</code>```

Body:
I'm new to React, please keep this in mind.

I have seen many people having issues with the binding of "this" keyword, I think I got it right, however I'm still getting the error "Cannot read property 'props' of undefined".

I'm doing something wrong with my React+Redux app but I can't figure out what.

Here's my code:
Recipes_list.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { getRecipe } from "../actions/index";

class RecipeList extends Component {
    constructor(props) {
        super(props);
        this.functionGetRecipe = this.functionGetRecipe.bind(this);
    }

    functionGetRecipe(recipe_id){
        this.props.getRecipe(recipe_id);
    }

    renderRecipes(recipeData) {
        const publisher = recipeData.publisher;
        const recipe_id = recipeData.recipe_id;
        const title = recipeData.title;
        const source_url = recipeData.source_url;
        const image_url = recipeData.image_url;

        return (

                {publisher}
                {title}
                View on original website

        );
    }

    render() {
        if (!this.props.recipes) {
            return
Nothing to show yet
;
        }
        return (

                        Publisher
                        Title
                        Source
                        Image

                    {this.props.recipes.map(this.renderRecipes)}

        );
    }
}

function mapStateToProps(state){
    return { recipes: state.searchRecipes.recipes };
}

function mapDispachToProps(dispatch) {
    return bindActionCreators({ getRecipe }, dispatch);
}

export default connect(mapStateToProps, mapDispachToProps)(RecipeList);

When this Container/Component gets re-rendered with an array of values (this.props.recipes) Chrome's console logs the following error:

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
at renderRecipes (bundle.js:36675)
at Array.map (<anonymous>)
at RecipeList.render (bundle.js:36746)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:7779)
at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:7799)
at ReactCompositeComponentWrapper.wrapper [as _renderValidatedComponent] (bundle.js:1530)
at ReactCompositeComponentWrapper._updateRenderedComponent (bundle.js:7752)
at ReactCompositeComponentWrapper._performComponentUpdate (bundle.js:7736)
at ReactCompositeComponentWrapper.updateComponent (bundle.js:7665)
at ReactCompositeComponentWrapper.wrapper [as updateComponent] (bundle.js:1530)

Any help is appreciated. Thank you.

NOTE: if I remove all the code related to the Action everything works fine, the table is displayed correctly

==============================================================================

EDIT: Modifing onClick={this.props.functionGetRecipe(recipe_id)} to onClick={this.functionGetRecipe(recipe_id)}
returns me the following error:

bundle.js:36675 Uncaught (in promise) TypeError: Cannot read property 'functionGetRecipe' of undefined

Just in case, here's my /actions/index.js:

import axios from 'axios';
const API_KEY = "***********************************";
export const GET_URL = `https://food2fork.com/api/get?key=${API_KEY}`;
export function getRecipe(recipeId) {
    const url = `${GET_URL}&Id=${recipeId}`;
    const request = axios.get(url);

    return {
        type: GET_RECIPE,
        payload: request
    };
}

==============================================================================

EDIT2:
That was it, now it works. Here's the change:

constructor(props) {
    super(props);
    this.renderRecipes = this.renderRecipes.bind(this);
}

Body:
Try replacing

<tr onClick={this.props.functionGetRecipe(recipe_id)} key={recipe_id}>

By :

<tr onClick={this.functionGetRecipe(recipe_id)} key={recipe_id}>

Edit : I think declaring your method functionGetRecipe() is useless you can use this.props.getRecipe(recipe_id) directly

Edit 2 : try binding renderRecipes instead :

constructor(props) {
        super(props);
        this.renderRecipes = this.renderRecipes.bind(this);
    }


问:
Python - string and tuple comparison
How to compare a string and a tuple, raise an error if the string has repeated letters , for example ('PTMP',('P','T','M'))  will say raise ValueError(...) but if the tuple had an extra P, like in  ('P','T','M','P') the answer would be valid?

```<code>def whatever(string,tup):
    for j in string:
        if j not in tup:
            raise ValueError('')
        for u in tup:
            if j not in tup: raise ValueError('')
</code>```

答:
If all you're looking for is that the string doesn't have more of any particular letter than the tuple, you can use Counter subtraction

```<code>from collection import Counter

def can_be_built(s, tup):
   if Counter(s) - Counter(tup):
       # The string does not use letters the tuple doesn't have
       return True
   else:
       return False
</code>```

Title: Python - string and tuple comparison

Body:
How to compare a string and a tuple, raise an error if the string has repeated letters , for example ('PTMP',('P','T','M'))  will say raise ValueError(...) but if the tuple had an extra P, like in  ('P','T','M','P') the answer would be valid?

def whatever(string,tup):
    for j in string:
        if j not in tup:
            raise ValueError('')
        for u in tup:
            if j not in tup: raise ValueError('')

Body:
If all you're looking for is that the string doesn't have more of any particular letter than the tuple, you can use Counter subtraction

from collection import Counter

def can_be_built(s, tup):
   if Counter(s) - Counter(tup):
       # The string does not use letters the tuple doesn't have
       return True
   else:
       return False


问:
Moveup List with Definition list items
Recently Chris posted an awesome jQuery code on his Css-Tricks blog that allows a list to scroll up and down by mouse movement.  He used it for unordered list items though.

I would love to use this on my current client project, but I can't figure out how to use this on
 items

The HTML is this:

```<code><dl>

            <dt><a href="#">Example.net</a></dt>
            <dd>
              1 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.
            </dd>

            <dt><a href="#">Example2.net</a></dt>
            <dd>
              2 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.
            </dd>

            <dt><a href="#">Example3.net</a></dt>
            <dd>
              3 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.
            </dd>

            <dt><a href="#">Example4.net</a></dt>
            <dd>
              4 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.
            </dd>
</dl>
</code>```

 is not below the
 items, its in another div placed by jQuery, so the
 of items is just lined up as links.

Also I am using the jQuery Plugin TinyScroll for the scrollbar, that sets the overflow: autoflow; or whatever. So that might be a reason that its not working for me.

But here is Chris Code from the blog post:

```<code>$("#menu").css("overflow", "hidden").wrapInner("<div id='mover' />");

var $el,
    speed = 13.5,    // needs to be manually tinkered with
    items = $("#menu a");

items
.each(function(i) {
        $(this).attr("data-pos", i);
})
.hover(function() {

        $el = $(this);
        $el.addClass("hover");

        $("#mover").css("top", -($el.data("pos") * speed - 40));
        // 40 is the top padding for the fadeout

}, function() {
        $(this).removeClass("hover");
});
</code>```

What would I have to change to get it working for me?

答:
hide your
s and use another container to hold their content

```<code><div class="fancy-dl">
  <dl>
    ...
  </dl>
  <div class="displayer"></div>
</div>
</code>```

and

```<code>$(function() {
  $('dd').hide();
  $('dt').hover(function() {
    var ddHtml = $(this).next('dd').html();
    $(this).parent().siblings('.displayer').hide().html(ddHtml).show();
  });
});
</code>```

you may want to fade/animate the displayer rather than hide and show.

Title: Moveup List with Definition list items

Body:
Recently Chris posted an awesome jQuery code on his Css-Tricks blog that allows a list to scroll up and down by mouse movement.  He used it for unordered list items though.

I would love to use this on my current client project, but I can't figure out how to use this on
 items

The HTML is this:

Example.net

              1 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.

Example2.net

              2 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.

Example3.net

              3 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.

Example4.net

              4 dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor.

 is not below the
 items, its in another div placed by jQuery, so the
 of items is just lined up as links.

Also I am using the jQuery Plugin TinyScroll for the scrollbar, that sets the overflow: autoflow; or whatever. So that might be a reason that its not working for me.

But here is Chris Code from the blog post:

$("#menu").css("overflow", "hidden").wrapInner("
");

var $el,
    speed = 13.5,    // needs to be manually tinkered with
    items = $("#menu a");

items
.each(function(i) {
        $(this).attr("data-pos", i);
})
.hover(function() {

        $el = $(this);
        $el.addClass("hover");

        $("#mover").css("top", -($el.data("pos") * speed - 40));
        // 40 is the top padding for the fadeout

}, function() {
        $(this).removeClass("hover");
});

What would I have to change to get it working for me?

Body:
hide your <dd>s and use another container to hold their content

<div class="fancy-dl">
  <dl>
    ...
  </dl>
  <div class="displayer"></div>
</div>

and

$(function() {
  $('dd').hide();
  $('dt').hover(function() {
    var ddHtml = $(this).next('dd').html();
    $(this).parent().siblings('.displayer').hide().html(ddHtml).show();
  });
});

you may want to fade/animate the displayer rather than hide and show.


问:
Trying to extend SerializeObject method of Newtonsoft.Json.JsonConvert
I am try to extend Newtonsoft.Json.JsonConvert to make returned JSON always formatted but I am getting an error "cannot declare variable of static type Newtonsoft.Json.JsonConvert". I don't know what is wrong with the code, is it because I cannot extend static class JsonConvert? maybe my approach is fundamentally wrong because extension method would not override instance method. I am not sure.

```<code>using Newtonsoft.Json;

namespace SomeNameSpace
{
    public static class MakeSerializationPrettyAlways
    {
        public static string SerializeObject(this JsonConvert jc, object value)
        {
            return JsonConvert.SerializeObject(value, Formatting.Indented);
        }
    }
}
</code>```

答:
JsonConvert is a static class. You can't create an extension method using a static class as the target.

The following should change your default serialization:

```<code>JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};
</code>```

Body:
I am try to extend Newtonsoft.Json.JsonConvert to make returned JSON always formatted but I am getting an error "cannot declare variable of static type Newtonsoft.Json.JsonConvert". I don't know what is wrong with the code, is it because I cannot extend static class JsonConvert? maybe my approach is fundamentally wrong because extension method would not override instance method. I am not sure.

using Newtonsoft.Json;

namespace SomeNameSpace
{
    public static class MakeSerializationPrettyAlways
    {
        public static string SerializeObject(this JsonConvert jc, object value)
        {
            return JsonConvert.SerializeObject(value, Formatting.Indented);
        }
    }
}

Body:
JsonConvert is a static class. You can't create an extension method using a static class as the target.

The following should change your default serialization:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Formatting = Formatting.Indented
};


问:
Create objects for a JComboBox in a list

I have an interface that is implemented by multiple classes. I want to create a JComboBox with all of the classes using the objects themselves as items.

This is kind of what I have now using a line for each class:

```<code>JComboBox<Vehicle> box = new JComboBox<>();
box.addItem(new Car());
box.addItem(new Truck());
box.addItem(new Plane());
// could be 5 more lines of object instantiation and adding
</code>```

When you call getSelectedItem() on the JComboBox, it will return the object and that object will be added to a list of the interface type. Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?

答:
Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?

Not sure what the point of this would be? You will still need to :

create the List

add the classes to the List

iterate through the List, create an instance of each class and then add the object to the combo box.

This doesn't save any code and make the process more complicated.

In any case to answer your basic question yes, you can create an instance of a class using code like:

```<code>Class aClass = Car.class;
Car car = aClass.newInstance();
</code>```

So you could create a List using something like:

```<code>List<Class> items = new ArrayList<Class>();
items.add( Car.class );
items.add( Truck.class );
</code>```

Then you iterate through the List as required.

Body:
I have an interface that is implemented by multiple classes. I want to create a JComboBox with all of the classes using the objects themselves as items.

This is kind of what I have now using a line for each class:

JComboBox<Vehicle> box = new JComboBox<>();
box.addItem(new Car());
box.addItem(new Truck());
box.addItem(new Plane());
// could be 5 more lines of object instantiation and adding

When you call getSelectedItem() on the JComboBox, it will return the object and that object will be added to a list of the interface type. Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?

Body:
Is there a way to do this with a loop through a list of classes instead of instantiating each object explicitly?

Not sure what the point of this would be? You will still need to :

create the List

add the classes to the List

iterate through the List, create an instance of each class and then add the object to the combo box.

This doesn't save any code and make the process more complicated.

In any case to answer your basic question yes, you can create an instance of a class using code like:

Class aClass = Car.class;
Car car = aClass.newInstance();

So you could create a List using something like:

List<Class> items = new ArrayList<Class>();
items.add( Car.class );
items.add( Truck.class );

Then you iterate through the List as required.


问:
Pandas Python: Slice / Transform URL to get item and item counts
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

```<code>http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1
</code>```

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

答:
Python already has library to parse urls.</p>

```<code>>>> import urllib.parse as urlparse
>>> url = 'http//mysportswebsite.com/shop/?Baseball+Bat=5'
>>> parsed_url = urlparse.urlparse(url)
>>> params = urlparse.parse_qs(parsed_url.query)
>>> print(params)
{'Baseball Bat': ['5']}
</code>```

Body:
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

Body:
Python already has library to parse urls.

>>> import urllib.parse as urlparse
>>> url = 'http//mysportswebsite.com/shop/?Baseball+Bat=5'
>>> parsed_url = urlparse.urlparse(url)
>>> params = urlparse.parse_qs(parsed_url.query)
>>> print(params)
{'Baseball Bat': ['5']}


问:
Scala cake pattern and multiproject
In common-project I have this:

```<code>trait DBProvider
trait DBTableNamesProvider
trait DefaultDBProvider extends DBProvider
trait DefaultTableNames extends  DBTableNamesProvider

trait MyService extends DBProvider with DBTableNamesProvider

object MyService {
  def apply() = new MyService with DefaultDBProvider with DefaultTableNames {}
}
</code>```

In projectA which has a reference to common-project as a jar I wish to construct MyService

projectA (has dependency on common-project):

```<code>object MyOtherApp {
  trait MyOtherTableName extends DBTableNamesProvider
  val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits?
}
</code>```

The above will not compile I cannot just call MyService() construction and override some of the dependencies.

The above is what I wish to do, I wish to override from a different project the factory construction of MyService() apply with my own implementation of MyProjectATableNames is that possible in scala? if not what is the recommended way without code repetition?

答:
You cannot override constructed type like that because MyService() is an object not a type anymore. So to reuse your code you might create a class like

```<code>class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames
</code>```

in the first app you can declare

```<code>object MyService {
  def apply() = new ConfiguredMyService
}
</code>```

and in the second

```<code>val MyCustomService = new ConfiguredMyService with MyOtherTableName
</code>```

Note: Nowadays, Cake pattern is considered an anti-pattern, so I recommend you checkout Dependency Injection.

Title: Scala cake pattern and multiproject

Body:
In common-project I have this:

trait DBProvider
trait DBTableNamesProvider
trait DefaultDBProvider extends DBProvider
trait DefaultTableNames extends  DBTableNamesProvider

trait MyService extends DBProvider with DBTableNamesProvider

object MyService {
  def apply() = new MyService with DefaultDBProvider with DefaultTableNames {}
}

In projectA which has a reference to common-project as a jar I wish to construct MyService

projectA (has dependency on common-project):

object MyOtherApp {
  trait MyOtherTableName extends DBTableNamesProvider
  val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits?
}

The above will not compile I cannot just call MyService() construction and override some of the dependencies.

The above is what I wish to do, I wish to override from a different project the factory construction of MyService() apply with my own implementation of MyProjectATableNames is that possible in scala? if not what is the recommended way without code repetition?

Body:
You cannot override constructed type like that because MyService() is an object not a type anymore. So to reuse your code you might create a class like

class ConfiguredMyService extends DefaultDBProvider with DefaultTableNames

in the first app you can declare

object MyService {
  def apply() = new ConfiguredMyService
}

and in the second

val MyCustomService = new ConfiguredMyService with MyOtherTableName

Note: Nowadays, Cake pattern is considered an anti-pattern, so I recommend you checkout Dependency Injection.


问:
Position child div to the left of parent div?
I have an image that has a width of 50% and a div with text that is 65% because I want the heading inside the div to overlap the image. But, the problem is that I don't want the other content inside the div to overlap the image - just the heading. I want the text and the button to be next to the image not on top of it.
But I can't seem to figure it out.

Here's a Codepen: https://codepen.io/tayanderson/pen/EbJZxy

```<code>.project {
    height: 75vh;
    margin: 15em 0;
    position: relative;

    .project-info {
        z-index: 100;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        width: 65%;
        height: 100%;
        right: 0;
        h2 {
            text-transform: initial;
            color: #eee;
        }
        p {
            font-weight: 300;
            color: #ccc;
            margin: 40px 0;
        }
        .project-desc {
            width: 70%;
            .button {display:inline-block;}
        }
    }

    .project-img {
        background-size: cover;
        background-position: center;
        height: 100%;
        -webkit-filter: grayscale(100%) brightness(50%);
        filter: grayscale(100%) brightness(50%);
        width: 51.3%;
    }

    a {text-decoration:none;
        color: #fff;}
    @media only screen and (max-width: 768px) {
        .project-info, .project-img {
            width: 100%;
        }
        .project-info {
            left: 0;
            padding: 0 20px;
            .project-desc>*{
                width: 100% !important;
                float: left !important;
            }
            p {display: none;}
        }
    }
}
</code>```

答:
why don´t you make the two divs to 50% and give padding to project-info?
You need this attribute for do correctly the padding inside the div

```<code>*{
  box-sizing:border-box;
}
</code>```

Here you have the result

https://codepen.io/marcosefrem/pen/BmERmY

Body:
I have an image that has a width of 50% and a div with text that is 65% because I want the heading inside the div to overlap the image. But, the problem is that I don't want the other content inside the div to overlap the image - just the heading. I want the text and the button to be next to the image not on top of it.
But I can't seem to figure it out.

Here's a Codepen: https://codepen.io/tayanderson/pen/EbJZxy

.project {
    height: 75vh;
    margin: 15em 0;
    position: relative;

    .project-info {
        z-index: 100;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        width: 65%;
        height: 100%;
        right: 0;
        h2 {
            text-transform: initial;
            color: #eee;
        }
        p {
            font-weight: 300;
            color: #ccc;
            margin: 40px 0;
        }
        .project-desc {
            width: 70%;
            .button {display:inline-block;}
        }
    }

    .project-img {
        background-size: cover;
        background-position: center;
        height: 100%;
        -webkit-filter: grayscale(100%) brightness(50%);
        filter: grayscale(100%) brightness(50%);
        width: 51.3%;
    }

    a {text-decoration:none;
        color: #fff;}
    @media only screen and (max-width: 768px) {
        .project-info, .project-img {
            width: 100%;
        }
        .project-info {
            left: 0;
            padding: 0 20px;
            .project-desc>*{
                width: 100% !important;
                float: left !important;
            }
            p {display: none;}
        }
    }
}

Body:
why don´t you make the two divs to 50% and give padding to project-info?
You need this attribute for do correctly the padding inside the div

*{
  box-sizing:border-box;
}

Here you have the result

https://codepen.io/marcosefrem/pen/BmERmY


问:
Auto run macro in excel when "Disable all macros with notification"
In Macro Setting,  I have chosen "Disable all macros with notification" but when i open file, macro still run. I use office 2013.Can anyone help me with this issue?</p>

答:
I figured out how to handle it

http://smallbusiness.chron.com/open-excel-macros-disabled-28054.html

Disable all Trusted Locations, Trust Trusted Document,Add-ins