问:
Spring constructor injection with lots of fields
I have a Spring component that has 8 members.

I am currently autowiring these 8 members with field injection.

I now want make these members private final, and do constructor injection to set them.

This is easy enough to do, but now I have a component constructor with 8 parameters.

I know I can use setter injection and set these values in an XML file, but this I don't want to do.

Are there any other alternatives?

EDIT:

This component just does a single thing. But that involves calling several other services. Hence the 8 injections

答:
First of all you can set the initial values of these parameters in an .properties file and then read this property file as a pojo configuration class and it is very easy in spring to convert .properties file into pojo.

so the constructor will be something like this

@Autowired
public Temp(ConfigPojoClass config) {
.....
}


来源: stackexchange

问:
Digital certificates in chrome
I have the following case in a web application of mine. The usual browser that the user uses is Chrome.

I use digital certificates that users have cryptographic cards that they insert into a card reader.

To log in to the application, basically users access the https link that makes the certificate data read.

So far everything works fine.

If the user to end his session of the application closes the browser, there is no problem. Everything is over.

But if the user wants to leave his application session, without closing all browser windows, here are my problems.

There is a button that closes the session of the application, the user leaves and redirects to the initial login screen. It seems that everything has been reset, because the user has left. But when the new user wants to log in and press the link to read the certificate data, instead of doing a new reading of the new card, use the data from the previous card without just asking for the pin to access it.

The problem goes further, for example, if the user has forgotten the card, the card and tries to logarize, the failure to read the certificate. But now, although inserted correctly, the card will not be read again until the browser is restarted, which maintains a cache that does not have a certificate.

At the moment only the solution was found by closing all Chrome windows, but that depends on whether the user does or not.

A partial solution would be sure to close the browser with javascript () but for some time, it can not be closed with javascript (window.close ()), a window that can not be opened from the site itself, with what is available I think it's ruled out

Can someone contribute to me? Thank you

答:
Chrome and the rest of browsers maintain a cache of the SSL authentications performed and decide when to prompt user for selecting a certificate. There is no "logout" function neither the connection can be closed from server side due to TLS resumption protocol ( client can resume the session)

This a common and known issue when defining an authentication system using client certificates. I only have found a workaround: use different domains to force browser to choose a certificate:

```<code>login.domain.com
   -->login1.domain.com
   -->login2.domain.com

   -->loginN.domain.com
</code>```

You have a virtual authentication URL login.domain.com which redirects user's browser to a random loginN.domain.com every time you need an authentication. Chrome will detect that it is a different domain and will prompt user for selecting a certificate

You could also think about using different ports instead of different DNS, but then you could have problems with the user's firewall because you are not using a standard port, and in this case Firefox does not show the window either.

ContentLicense: CC BY-SA 3.0

Title: Digital certificates in chrome

Body:
Chrome and the rest of browsers maintain a cache of the SSL authentications performed and decide when to prompt user for selecting a certificate. There is no "logout" function neither the connection can be closed from server side due to TLS resumption protocol ( client can resume the session)

This a common and known issue when defining an authentication system using client certificates. I only have found a workaround: use different domains to force browser to choose a certificate:

login.domain.com
   -->login1.domain.com
   -->login2.domain.com

   -->loginN.domain.com

You have a virtual authentication URL login.domain.com which redirects user's browser to a random loginN.domain.com every time you need an authentication. Chrome will detect that it is a different domain and will prompt user for selecting a certificate

You could also think about using different ports instead of different DNS, but then you could have problems with the user's firewall because you are not using a standard port, and in this case Firefox does not show the window either.


问:
jQuery to loop through elements with the same class
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

答:
You can do this concisely using <code>.filter</code>. The following example will hide all .testimonial divs containing the word "something": </p>

```<code>$(".testimonial").filter(function() {
    return $(this).text().toLowerCase().indexOf("something") !== -1;
}).hide();
</code>```

Body:
You can do this concisely using .filter. The following example will hide all .testimonial divs containing the word "something":

$(".testimonial").filter(function() {
    return $(this).text().toLowerCase().indexOf("something") !== -1;
}).hide();

ContentLicense: CC BY-SA 2.5


问:
Use sed to find extract information and print in specific order
I'm currently having some struggle to figure out a sed command that can extract information and then print it in a specific order. For example,
if I have a text document looking like this:

```<code>kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
</code>```

then I want to extract the following pars of each line:

```<code>[,]->0132
</code>```

(any 4 random digits) and

```<code>0132/
</code>```

So far, I have the command:

```<code>sed 's/^.*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*$/\1      \2/; '
</code>```

This command does extract all matches, but my problem is that I don't know how to change the order because right now it prints the order it's found:

(if command run on the example text above)

```<code>[,]->0123        1234/
1234/        [,]->0123
[,]->0123        1234/
1234/        [,]->0123
1234/        [,]->0123
</code>```

but I want it to be sorted like this:

```<code>[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
</code>```

Also, I'm only allowed to use sed.

Body:
I'm currently having some struggle to figure out a sed command that can extract information and then print it in a specific order. For example,
if I have a text document looking like this:

kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd

then I want to extract the following pars of each line:

[,]->0132

(any 4 random digits) and

0132/

So far, I have the command:

sed 's/^.*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*$/\1      \2/; '

This command does extract all matches, but my problem is that I don't know how to change the order because right now it prints the order it's found:

(if command run on the example text above)

[,]->0123        1234/
1234/        [,]->0123
[,]->0123        1234/
1234/        [,]->0123
1234/        [,]->0123

but I want it to be sorted like this:

[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/

Also, I'm only allowed to use sed.

Body:
GNU awk solution:

awk -v FPAT='\\[,\\]->[0-9]{4}|[0-9]{4}/' '{ print ($1~/^\[/? $1 OFS $2:$2 OFS $1) }' OFS='\t' file

-v FPAT='\\[,\\]->[0-9]{4}|[0-9]{4}/' - regex pattern defining field value

The output:

[,]->0123   1234/
[,]->0123   1234/
[,]->0123   1234/
[,]->0123   1234/
[,]->0123   1234/
[,]->0123   1234/


问:
Split large SAS dataset into smaller datasets
I need some assistance with splitting a large SAS dataset into smaller datasets.

Each month I'll have a dataset containing a few million records. This number will vary from month to month. I need to split this dataset into multiple smaller datasets containing 250,000 records each. For example, if I have 1,050,000 records in the original dataset then I need the end result to be 4 datasets containing 250,000 records and 1 dataset containing 50,000 records.

From what I've been looking at it appears this will require using macros. Unfortunately I'm fairly new to SAS (unfamiliar with using macros) and don't have a lot of time to accomplish this. Any help would be greatly appreciated.

答:
A more efficient option, if you have room in memory to store one of the smaller datasets, is a hash solution.  Here's an example using basically what you're describing in the question:

```<code>data in_data;
  do recid = 1 to 1.000001e7;
    datavar = 1;
    output;
  end;
run;

data _null_;
  if 0 then set in_data;
  declare hash h_out();
  h_out.defineKey('_n_');
  h_out.defineData('recid','datavar');
  h_out.defineDone();

  do filenum = 1 by 1 until (eof);
    do _n_ = 1 to 250000 until (eof);
      set in_data end=eof;
      h_out.add();
    end;
    h_out.output(dataset:cats('file_',filenum));
    h_out.clear();
  end;
  stop;
run;
</code>```

We define a hash object with the appropriate parameters, and simply tell it to output every 250k records, and clear it.  We could do a hash-of-hashes here also, particularly if it weren't just "Every 250k records" but some other criteria drove things, but then you'd have to fit all of the records in memory, not just 250k of them.

Note also that we could do this without specifying the variables explicitly, but it requires having a useful ID on the dataset:

```<code>data _null_;
  if 0 then set in_data;
  declare hash h_out(dataset:'in_data(obs=0)');
  h_out.defineKey('recid');
  h_out.defineData(all:'y');
  h_out.defineDone();

  do filenum = 1 by 1 until (eof);
    do _n_ = 1 to 250000 until (eof);
      set in_data end=eof;
      h_out.add();
    end;
    h_out.output(dataset:cats('file_',filenum));
    h_out.clear();
  end;
  stop;
run;
</code>```

Since we can't use _n_ anymore for the hash ID due to using the dataset option on the constructor (necessary for the all:'y' functionality), we have to have a record ID.  Hopefully there is such a variable, or one could be added with a view.

Body:
A more efficient option, if you have room in memory to store one of the smaller datasets, is a hash solution.  Here's an example using basically what you're describing in the question:

data in_data;
  do recid = 1 to 1.000001e7;
    datavar = 1;
    output;
  end;
run;

data _null_;
  if 0 then set in_data;
  declare hash h_out();
  h_out.defineKey('_n_');
  h_out.defineData('recid','datavar');
  h_out.defineDone();

  do filenum = 1 by 1 until (eof);
    do _n_ = 1 to 250000 until (eof);
      set in_data end=eof;
      h_out.add();
    end;
    h_out.output(dataset:cats('file_',filenum));
    h_out.clear();
  end;
  stop;
run;

We define a hash object with the appropriate parameters, and simply tell it to output every 250k records, and clear it.  We could do a hash-of-hashes here also, particularly if it weren't just "Every 250k records" but some other criteria drove things, but then you'd have to fit all of the records in memory, not just 250k of them.

Note also that we could do this without specifying the variables explicitly, but it requires having a useful ID on the dataset:

data _null_;
  if 0 then set in_data;
  declare hash h_out(dataset:'in_data(obs=0)');
  h_out.defineKey('recid');
  h_out.defineData(all:'y');
  h_out.defineDone();

  do filenum = 1 by 1 until (eof);
    do _n_ = 1 to 250000 until (eof);
      set in_data end=eof;
      h_out.add();
    end;
    h_out.output(dataset:cats('file_',filenum));
    h_out.clear();
  end;
  stop;
run;

Since we can't use _n_ anymore for the hash ID due to using the dataset option on the constructor (necessary for the all:'y' functionality), we have to have a record ID.  Hopefully there is such a variable, or one could be added with a view.


问:
why not update the picture? laravel 5.4
I can upload a picture, but when I try to update it, then there is no error. The file name changes in the database to the name of the new picture. And in the public folder the picture remains old and does not appear new.

I use: Intervention Image

What I did not understand, help please.

Controller: UploadController

```<code>use Illuminate\Http\Request;

use App\Post;
use Image;
use Storage;
use Faker\Provider\File;

public function update (Request $request, $id)
{
    //validate
    $this->validate($request, [
        'title' => 'required|max:255',
        'author' => 'required',
        'text' => 'required',
        'desc' => 'required',
        'image' => 'required',
    ]);
    $posts = Post::find($id);
    $posts->title = $request->input('title');
    $posts->author = $request->input('author');
    $posts->text = $request->input('text');
    $posts->desc = $request->input('desc');
    $posts->image = $request->input('image');

    //update image
    if ($request->hasFile('image'))
    {
        $image = $request->file('image');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/'. $filename);
        Image::make($image)->resize(800, 400)->save($location);
        $oldFilename = $posts->image;
        //update db
        $posts->image = $filename;
        //delete old image
        Storage::delete($oldFilename);
    }
    $posts->save();

    return redirect('/');
}
</code>```

View: edit.blade.php

```<code><div class="container">
<form method="POST" action="{{ route('goUpdate', [$posts->id]) }}">
    {{ csrf_field() }}
    {!!  method_field('patch') !!}
    @if($posts)
        <div class="form-group">
            <br>
            <label>title</label>
            <input name="title" type="text" class="form-control" value="{{ $posts->title }}">
        </div>
        <div class="form-group">
            <label>author</label>
            <input name="author" type="text" class="form-control" value="{{ $posts->author }}">
        </div>
        <div class="form-group">
            <label>text</label>
            <textarea name="text" class="form-control" rows="7">{{ $posts->text }}</textarea>
        </div>
        <div class="form-group">
            <label>desc</label>
            <textarea name="desc" class="form-control" rows="5">{{ $posts->desc }}</textarea>
        </div>
        <div class="form-group">
            <label>image</label>
            <input type="file" name="image" class="form-control-file" value="" >
        </div>
        <div>
            <input name="submit" type="submit" class="btn btn-primary" value="update"/>
            <a href="{{ url('/') }}" class="btn btn-primary">back</a>
        </div>
    @endif
</form>
<br>
</code>```

filesystems.php

```<code>'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => public_path('images/'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],
</code>```

答:
Try using this

```<code>$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalName();
$path = public_path('events/' . $filename);
Image::make($image->getRealPath())->resize(300, 300)->save($path);
$event->image = 'events/' . $filename;
</code>```

Hope this can help you

Title: why not update the picture? laravel 5.4

Body:
I can upload a picture, but when I try to update it, then there is no error. The file name changes in the database to the name of the new picture. And in the public folder the picture remains old and does not appear new.

I use: Intervention Image

What I did not understand, help please.

Controller: UploadController

use Illuminate\Http\Request;

use App\Post;
use Image;
use Storage;
use Faker\Provider\File;

public function update (Request $request, $id)
{
    //validate
    $this->validate($request, [
        'title' => 'required|max:255',
        'author' => 'required',
        'text' => 'required',
        'desc' => 'required',
        'image' => 'required',
    ]);
    $posts = Post::find($id);
    $posts->title = $request->input('title');
    $posts->author = $request->input('author');
    $posts->text = $request->input('text');
    $posts->desc = $request->input('desc');
    $posts->image = $request->input('image');

    //update image
    if ($request->hasFile('image'))
    {
        $image = $request->file('image');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/'. $filename);
        Image::make($image)->resize(800, 400)->save($location);
        $oldFilename = $posts->image;
        //update db
        $posts->image = $filename;
        //delete old image
        Storage::delete($oldFilename);
    }
    $posts->save();

    return redirect('/');
}

View: edit.blade.php

<form method="POST" action="{{ route('goUpdate', [$posts->id]) }}">
    {{ csrf_field() }}
    {!!  method_field('patch') !!}
    @if($posts)

            title
            <input name="title" type="text" class="form-control" value="{{ $posts->title }}">

            author
            <input name="author" type="text" class="form-control" value="{{ $posts->author }}">

            text
            <textarea name="text" class="form-control" rows="7">{{ $posts->text }}</textarea>

            desc
            <textarea name="desc" class="form-control" rows="5">{{ $posts->desc }}</textarea>

            image
            <input type="file" name="image" class="form-control-file" value="" >

            <input name="submit" type="submit" class="btn btn-primary" value="update"/>
            back

    @endif
</form>

filesystems.php

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => public_path('images/'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],

Body:
Try using this

$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalName();
$path = public_path('events/' . $filename);
Image::make($image->getRealPath())->resize(300, 300)->save($path);
$event->image = 'events/' . $filename;

Hope this can help you


问:
How can I set different font size between letter and number in UILabel
I want to make the letter font size bigger and number font size smaller in UILabel's text. How can I do?

I tried to use NSAttributedString, but it seems to receive a confirmed range to change. This can not meet my needs。

Thanks a lot

答:
What is wrong with NSAttributedString?

This is a String extension returning an attributed string. You can pass the font size for letter and digit.

It uses Regular Expression to find the numeric ranges

```<code>extension String {

    func attributedString(letterSize: CGFloat, digitSize: CGFloat) -> NSAttributedString
    {
        let pattern = "\\d+"
        let regex = try! NSRegularExpression(pattern: pattern)
        let matches = regex.matches(in: self, range: NSRange(location: 0, length: self.count))
        let attributedString = NSMutableAttributedString(string: self, attributes: [.font : UIFont.systemFont(ofSize: letterSize)])
        matches.forEach { attributedString.addAttributes([.font : UIFont.systemFont(ofSize: digitSize)], range: $0.range) }
        return attributedString.copy() as! NSAttributedString
    }
}
</code>```

And use it

```<code>let string = """
Apple Computer Inc.
1 Infinite Loop Cupertino
CA 95014
(800) 275-2273
"""

let attributedString = string.attributedString(letterSize: 14.0, digitSize: 18.0)
</code>```

Result:

Body:
What is wrong with NSAttributedString?

This is a String extension returning an attributed string. You can pass the font size for letter and digit.

It uses Regular Expression to find the numeric ranges

extension String {

    func attributedString(letterSize: CGFloat, digitSize: CGFloat) -> NSAttributedString
    {
        let pattern = "\\d+"
        let regex = try! NSRegularExpression(pattern: pattern)
        let matches = regex.matches(in: self, range: NSRange(location: 0, length: self.count))
        let attributedString = NSMutableAttributedString(string: self, attributes: [.font : UIFont.systemFont(ofSize: letterSize)])
        matches.forEach { attributedString.addAttributes([.font : UIFont.systemFont(ofSize: digitSize)], range: $0.range) }
        return attributedString.copy() as! NSAttributedString
    }
}

And use it

let string = """
Apple Computer Inc.
1 Infinite Loop Cupertino
CA 95014
(800) 275-2273
"""

let attributedString = string.attributedString(letterSize: 14.0, digitSize: 18.0)

Result:


问:
Asp.net core 2/Angular 4 template build not working
I have created project using Asp.net core 2/Angular 4 template that ships whith
.Net core 2 Sdk.

Using dotnet build or dotnet run it's not generating new dist folder for client side angular project.

I am using visual studio code as editor.

Can i miss any command beacuse of that new build is not generating?

Following is package.json

```<code>{
  "name": "mcxpricecore",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/animations": "4.2.5",
    "@angular/common": "4.2.5",
    "@angular/compiler": "4.2.5",
    "@angular/compiler-cli": "4.2.5",
    "@angular/core": "4.2.5",
    "@angular/forms": "4.2.5",
    "@angular/http": "4.2.5",
    "@angular/platform-browser": "4.2.5",
    "@angular/platform-browser-dynamic": "4.2.5",
    "@angular/platform-server": "4.2.5",
    "@angular/router": "4.2.5",
    "@ngtools/webpack": "1.5.0",
    "@types/webpack-env": "1.13.0",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "3.2.1",
    "bootstrap": "3.3.7",
    "css": "2.2.1",
    "css-loader": "0.28.4",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "0.7.3",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "html-loader": "0.4.5",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",
    "preboot": "4.5.2",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.4.2",
    "style-loader": "0.18.2",
    "to-string-loader": "1.1.5",
    "typescript": "2.4.1",
    "url-loader": "0.5.9",
    "webpack": "2.5.1",
    "webpack-hot-middleware": "2.18.2",
    "webpack-merge": "4.1.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.5.53",
    "chai": "4.0.2",
    "jasmine-core": "2.6.4",
    "karma": "1.7.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.3"
  }
}
</code>```

答:
It could be that you need to set ASPNETCORE_ENVIRONMENT variable to development.

So in the command line run this:

```<code>set ASPNETCORE_ENVIRONMENT=Development
</code>```

then when you do dotnet run it will pick up your changes.

Instructions on using multiple environments here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments

Body:
I have created project using Asp.net core 2/Angular 4 template that ships whith
.Net core 2 Sdk.

Using dotnet build or dotnet run it's not generating new dist folder for client side angular project.

I am using visual studio code as editor.

Can i miss any command beacuse of that new build is not generating?

Following is package.json

{
  "name": "mcxpricecore",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/animations": "4.2.5",
    "@angular/common": "4.2.5",
    "@angular/compiler": "4.2.5",
    "@angular/compiler-cli": "4.2.5",
    "@angular/core": "4.2.5",
    "@angular/forms": "4.2.5",
    "@angular/http": "4.2.5",
    "@angular/platform-browser": "4.2.5",
    "@angular/platform-browser-dynamic": "4.2.5",
    "@angular/platform-server": "4.2.5",
    "@angular/router": "4.2.5",
    "@ngtools/webpack": "1.5.0",
    "@types/webpack-env": "1.13.0",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "awesome-typescript-loader": "3.2.1",
    "bootstrap": "3.3.7",
    "css": "2.2.1",
    "css-loader": "0.28.4",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.9",
    "expose-loader": "0.7.3",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "html-loader": "0.4.5",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",
    "preboot": "4.5.2",
    "raw-loader": "0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "5.4.2",
    "style-loader": "0.18.2",
    "to-string-loader": "1.1.5",
    "typescript": "2.4.1",
    "url-loader": "0.5.9",
    "webpack": "2.5.1",
    "webpack-hot-middleware": "2.18.2",
    "webpack-merge": "4.1.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@types/chai": "4.0.1",
    "@types/jasmine": "2.5.53",
    "chai": "4.0.2",
    "jasmine-core": "2.6.4",
    "karma": "1.7.0",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.0",
    "karma-webpack": "2.0.3"
  }
}

Body:
It could be that you need to set ASPNETCORE_ENVIRONMENT variable to development.

So in the command line run this:

set ASPNETCORE_ENVIRONMENT=Development

then when you do dotnet run it will pick up your changes.

Instructions on using multiple environments here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments


问:
Get data attribute in javascript like jQuery and split it into two values?
I found this nice script from here to calculate the distance between me and other locations.

Script:

```<code>function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
  var dLon = (lon2-lon1).toRad();
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

window.navigator.geolocation.getCurrentPosition(function(pos) {
    console.log(pos);
    console.log(
        distance(pos.coords.latitude, pos.coords.longitude, lat2, lon2)
  );
});
</code>```

My HTML looks like this:

```<code><div class="map" data-latLng="86.55,79.66">Distance:<i></i></div>
<div class="map" data-latLng="96.55,89.66">Distance:<i></i></div>
<div class="map" data-latLng="116.55,179.66">Distance:<i></i></div>
</code>```

At "[i]" I want to show the distance. So, my problems are:

so far I only work with jQuery, how can I get the [data-latLng] by "var", something like "var lat2 = $("div").attr("data-latLng");" seemes not to work in javascript?

how can I split the "data-latLng" into "lat2" and "lon2" for the function?

is there any ".each" function for javascript to do this for all my loactions?

答:
Please find working solution below. Enjoy :)

function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2 - lat1).toRad(); // Javascript functions in radians
  var dLon = (lon2 - lon1).toRad();
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c; // Distance in km
  return d;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
  $('.map').each(function() {
    var latLng = $(this).attr('data-latLng').split(',');
    var dist = distance(pos.coords.latitude, pos.coords.longitude, Number(latLng[0]), Number(latLng[1]));
    $(this).find('i').html(dist);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="map" data-latLng="86.55,79.66">Distance:<i></i></div>
<div class="map" data-latLng="96.55,89.66">Distance:<i></i></div>
<div class="map" data-latLng="116.55,179.66">Distance:<i></i></div></code>```

Body:
I found this nice script from here to calculate the distance between me and other locations.

Script:

function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
  var dLon = (lon2-lon1).toRad();
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

window.navigator.geolocation.getCurrentPosition(function(pos) {
    console.log(pos);
    console.log(
        distance(pos.coords.latitude, pos.coords.longitude, lat2, lon2)
  );
});

My HTML looks like this:

Distance:

Distance:

Distance:

At "[i]" I want to show the distance. So, my problems are:

so far I only work with jQuery, how can I get the [data-latLng] by "var", something like "var lat2 = $("div").attr("data-latLng");" seemes not to work in javascript?

how can I split the "data-latLng" into "lat2" and "lon2" for the function?

is there any ".each" function for javascript to do this for all my loactions?

Body:
Please find working solution below. Enjoy :)

function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2 - lat1).toRad(); // Javascript functions in radians
  var dLon = (lon2 - lon1).toRad();
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c; // Distance in km
  return d;
}
/** Converts numeric degrees to radians */
if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}
window.navigator.geolocation.getCurrentPosition(function(pos) {
  $('.map').each(function() {
    var latLng = $(this).attr('data-latLng').split(',');
    var dist = distance(pos.coords.latitude, pos.coords.longitude, Number(latLng[0]), Number(latLng[1]));
    $(this).find('i').html(dist);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="map" data-latLng="86.55,79.66">Distance:<i></i></div>
<div class="map" data-latLng="96.55,89.66">Distance:<i></i></div>
<div class="map" data-latLng="116.55,179.66">Distance:<i></i></div>


问:
What are good options in 2017 for static web site generators/managers
I am starting a new project and am trying to think about how to keep the need for content servers for non-dynamic resources (articles, API info, etc) to a minimum... to that end I'd like to (possibly) use static web content wherever possible rather than have live web servers (nodejs, Wordpress,etc) and serve things up from S3 and CloudFront (or similar CDNs).

Looking over the obvious static generators like Hugo, Pelican, Jekyll, etc I see that in terms of activity they are all pretty inactive from a Github perspective.

Anyone have any suggestions about new tools I should look at, or if the current ones are all more or less equal,  how well do they scale in terms of managing larger content collections?  Or will, if my needs get big enough, will I basically have to capitulate an go back to more a more server-centric solution?

答:
You might want to have a closer look at Statamic:
https://statamic.com

It's a CMS without a DB and allows you to output a static html page:
https://docs.statamic.com/caching


问:
Get minX, maxX, minY, maxY from multidimensional array
I have an array like this

```<code>var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]
</code>```

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

```<code>var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}
</code>```

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

```<code>var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}
</code>```

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)```

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

答:
If you don't mind using es6, you can do something like this:

const my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4],
];

const results = {
  xMax: Math.max(...my_array.map(e => e[0])),
  xMin: Math.min(...my_array.map(e => e[0])),
  yMax: Math.max(...my_array.map(e => e[1])),
  yMin: Math.min(...my_array.map(e => e[1]))
}

const points = {
  xMax: my_array.filter(e => e[0] === results.xMax),
  xMin: my_array.filter(e => e[0] === results.xMin),
  yMax: my_array.filter(e => e[1] === results.yMax),
  yMin: my_array.filter(e => e[1] === results.yMin)
}

console.log(points);```

EDIT:

Sorry, I misread the question. Edit the answer above.

Body:
I have an array like this

var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

Body:
If you don't mind using es6, you can do something like this:

const my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4],
];

const results = {
  xMax: Math.max(...my_array.map(e => e[0])),
  xMin: Math.min(...my_array.map(e => e[0])),
  yMax: Math.max(...my_array.map(e => e[1])),
  yMin: Math.min(...my_array.map(e => e[1]))
}

const points = {
  xMax: my_array.filter(e => e[0] === results.xMax),
  xMin: my_array.filter(e => e[0] === results.xMin),
  yMax: my_array.filter(e => e[1] === results.yMax),
  yMin: my_array.filter(e => e[1] === results.yMin)
}

console.log(points);

EDIT:

Sorry, I misread the question. Edit the answer above.


问:
How to prevent fetch with same URL being called twice in node.js
I have x number of calls to be made to back-end. Some of them are to same URLs. I am caching the results. But my problem is thatIf I call loadCached immediately twice (or several times) with a same URL, it will actually call fetch twice as well, as cache does not have url before the first fetch is resolved. So, caching works only when one fetch is successfully completed (=resolved). How could I improve the code to wait for the first fetch to be resolved to avoid duplicate query?

```<code>function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());

  if (cache.has(url)) {
    return Promise.resolve(cache.get(url)); // (*)
  }

  return fetch(url)
    .then(response => response.text())
    .then(text => {
      cache[url] = text;
      return text;
    });
}
</code>```

I'm using promise.all() to wait for loadCached to resolve.

答:
You need to cache entire promise:

```<code>function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());
  let promise;

  if (cache.has(url)) {
    promise = cache.get(url)
  } else {
    promise = fetch(url)
    cache.set(url, promise)
  }

  return promise
    .then(response => response.text())
}
</code>```

Also note that in order to set new value with map, you need to use set method, cache[url] is incorrect.

Body:
I have x number of calls to be made to back-end. Some of them are to same URLs. I am caching the results. But my problem is thatIf I call loadCached immediately twice (or several times) with a same URL, it will actually call fetch twice as well, as cache does not have url before the first fetch is resolved. So, caching works only when one fetch is successfully completed (=resolved). How could I improve the code to wait for the first fetch to be resolved to avoid duplicate query?

function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());

  if (cache.has(url)) {
    return Promise.resolve(cache.get(url)); // (*)
  }

  return fetch(url)
    .then(response => response.text())
    .then(text => {
      cache[url] = text;
      return text;
    });
}

I'm using promise.all() to wait for loadCached to resolve.

Body:
You need to cache entire promise:

function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());
  let promise;

  if (cache.has(url)) {
    promise = cache.get(url)
  } else {
    promise = fetch(url)
    cache.set(url, promise)
  }

  return promise
    .then(response => response.text())
}

Also note that in order to set new value with map, you need to use set method, cache[url] is incorrect.


问:
Piping to same c program using stdin and stdout
Let's say I have an executable called myProgram that reads from an input file and writes to an output file. A command line for this program looks like this:

```<code>./myProgram -o outputfile inputfile
</code>```

The argument to the -o option specifies an output file name; if no such file exists then the program will create it.

What I was wondering is whether I can execute myProgram multiple times, piping the output of the one instance to the input of the next. For example,

```<code>./myProgram inputfile | ./myProgram -o outputfile
</code>```

Is it possible to achieve this and if so, what would I have to implement? exec calls and forking? just simple read and write calls?

答:
There is absolutely no problem to run two instances of your program myProgram together as you do with command

```<code>./myProgram inputfile | ./myProgram -o outputfile
</code>```

Body:
Let's say I have an executable called myProgram that reads from an input file and writes to an output file. A command line for this program looks like this:

./myProgram -o outputfile inputfile

The argument to the -o option specifies an output file name; if no such file exists then the program will create it.

What I was wondering is whether I can execute myProgram multiple times, piping the output of the one instance to the input of the next. For example,

./myProgram inputfile | ./myProgram -o outputfile

Is it possible to achieve this and if so, what would I have to implement? exec calls and forking? just simple read and write calls?

Body:
There is absolutely no problem to run two instances of your program myProgram together as you do with command

./myProgram inputfile | ./myProgram -o outputfile


问:
Check if array exist by two keys with PHP
I'd like to check if array exist by two keys: id and type

This code just check by id:

```<code> if (isset($_POST['type'])) {
   $type = $_POST['type'];
 }
 else {
   $type = '';
 }

 if (array_key_exists($id, $_SESSION['cart'])) {
        $_SESSION['cart'][$id]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$id] = $line;
  }
</code>```

I have tried with this code but it doesn't work:

```<code> if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
        $_SESSION['cart'][$id]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$id] = $line;
    }
</code>```

$_SESSION['cart'] is an array contains arrays of $line

```<code> $line = array(
        'id' => $id,
        'type' => $type,
        'quantity' => $quantity,
        'price' => $price,
        'picture' => $dish->getPicture()->getWebPath(),
    );
</code>```

This is the output of $_SESSION['cart']:

As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.

答:
If you want to check if type and id exists then you should do something like this

```<code>if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
  // stuff here..
}
</code>```

if $id is the value of the key id so 'id' => 5 then you should check like this:

```<code>if ($_SESSION['cart']['type'] == $id) {
 // stuff here
}
</code>```

Hope this somewhat helps you further!

Body:
I'd like to check if array exist by two keys: id and type

This code just check by id:

 if (isset($_POST['type'])) {
   $type = $_POST['type'];
 }
 else {
   $type = '';
 }

 if (array_key_exists($id, $_SESSION['cart'])) {
        $_SESSION['cart'][$id]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$id] = $line;
  }

I have tried with this code but it doesn't work:

 if (array_key_exists($id, $_SESSION['cart']) && array_key_exists($type, $_SESSION['cart'])) {
        $_SESSION['cart'][$id]['quantity'] += $quantity;
    } else {
        $_SESSION['cart'][$id] = $line;
    }

$_SESSION['cart'] is an array contains arrays of $line

 $line = array(
        'id' => $id,
        'type' => $type,
        'quantity' => $quantity,
        'price' => $price,
        'picture' => $dish->getPicture()->getWebPath(),
    );

This is the output of $_SESSION['cart']:

As you see in th last array with id 55 and type "french bred" , what I'd like to do is to check if th user chose the same product but a with different type so insert new line else if the same product and the same type so just update quantity.

Body:
If you want to check if type and id exists then you should do something like this

if (array_key_exists('id', $_SESSION['cart']) && array_key_exists('type', $_SESSION['cart'])) {
  // stuff here..
}

if $id is the value of the key id so 'id' => 5 then you should check like this:

if ($_SESSION['cart']['type'] == $id) {
 // stuff here
}

Hope this somewhat helps you further!


问:
C++ Avoiding library linking
I currently have a c++ setup like the following

```<code>class FlowController
{
   public:
    //...
   private:
       cntrl::OneWayValve _intake;
}
</code>```

As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a cntrl::Value within its implementation like so.

```<code>class OneWayValve
{
   public:
    //...
   private:
       cntrl::Valve _valve;
}
</code>```

And as before the cntrl::Valve resides in a different library for reasons you'll have to ask the previous developer about.

Now when i compile my FlowController class i'm required to link with the OneWayValve library and the cntrl::Valve library as well.

My question:
Is it possible to only link with the cntrl::OneWayValve library at compile time?

Forward declaration?

Static libraries (really don't want to do this tho)?

Another alternative?

Basically i don't want to know that its using a cntrl::Valve internally, its none of my business.

Note: apologies the OS is Unix.

Cheers,
Ben

答:
What you could do is make your Valve library part of your OneWayValve library using a tool called a librarian. I don't know what OS/compiler you are using so I'm going to describe how do it using Visual Studio since that's the only system I've actually done this with (unless you want to count CP/M + LIB-80 :-)

If you bring up the Tools|Options dialog for you OneWayValve project and select Configuration Properties|Librarian|Additional Dependencies, you can put a reference to your Valve library in the Additional Dependencies setting. This will cause OneWayValve.lib to contain any objects that it references from Valve.lib.

Title: C++ Avoiding library linking

Body:
I currently have a c++ setup like the following

class FlowController
{
   public:
    //...
   private:
       cntrl::OneWayValve _intake;
}

As you can see i'm using a cntrl::OneWayValve instance within my class. The Valve class resides in another library which i link with at compile time. The cntrl::OneWayValve has a cntrl::Value within its implementation like so.

class OneWayValve
{
   public:
    //...
   private:
       cntrl::Valve _valve;
}

And as before the cntrl::Valve resides in a different library for reasons you'll have to ask the previous developer about.

Now when i compile my FlowController class i'm required to link with the OneWayValve library and the cntrl::Valve library as well.

My question:
Is it possible to only link with the cntrl::OneWayValve library at compile time?

Forward declaration?

Static libraries (really don't want to do this tho)?

Another alternative?

Basically i don't want to know that its using a cntrl::Valve internally, its none of my business.

Note: apologies the OS is Unix.

Cheers,
Ben


问:
Create parent node in XMLSCHEMA
Have objects:

```<code>create or replace type test.type_numberlist as table of number;
/

create or replace type test.type_test as object (
    LIST  test.type_numberlist
  , OBJ1  number
  , OBJ2  number
)
/
</code>```

create simple xml schema:

```<code>BEGIN DBMS_XMLSCHEMA.registerSchema(
  SCHEMAURL => 'testschema.xsd',
  SCHEMADOC => '<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xdb="http://xmlns.oracle.com/xdb"
            xsi:schemaLocation="http://xmlns.oracle.com/xdb http://xmlns.oracle.com/xdb/XDBSchema.xsd">
  <xsd:element name="document" type="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST"/>
  <xsd:complexType name="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST" xdb:maintainDOM="false">
  <xsd:sequence>
   <xsd:element name="LIST" type="xsd:double" maxOccurs="unbounded" minOccurs="0" xdb:SQLName="LIST" xdb:SQLCollType="TYPE_NUMBERLIST" xdb:SQLType="NUMBER" xdb:SQLCollSchema="TEST"/>
   <xsd:element name="OBJ1" type="xsd:double" xdb:SQLName="OBJ1" xdb:SQLType="NUMBER"/>
   <xsd:element name="OBJ2" type="xsd:double" xdb:SQLName="OBJ2" xdb:SQLType="NUMBER"/>
  </xsd:sequence>
 </xsd:complexType>
</xsd:schema>',
   LOCAL     => FALSE,
   GENTYPES  => FALSE,
   OWNER     => 'TEST');
END;
/
</code>```

test generation xml by object:

```<code>declare
  i test.type_test := new test.type_test(LIST => test.type_numberlist(1,2)
                                        ,OBJ1 => 1
                                        ,OBJ2 => 2);
  v_xml xmltype;
begin
  v_xml := xmltype( xmlData => i
                  , schema => 'TESTSCHEMA.xsd'
                  , element => 'document'
                  , validated => 1);
  dbms_output.put_line(v_xml.getstringval());
end;
</code>```

get this xml:

```<code><document>
  <LIST>1</LIST>
  <LIST>2</LIST>
  <OBJ1>1</OBJ1>
  <OBJ2>2</OBJ2>
</document>
</code>```

LIST on same level as OBJ1, OBJ2. Is there any way to change XMLSCHEMA to create parent node to LIST to create xml like:

```<code><document>
  <LIST>
    <value>1</value>
    <value>2</value>
  </LIST>
  <OBJ1>1</OBJ1>
  <OBJ2>2</OBJ2>
</document>
</code>```

答:
Create a new  complexType named LISTType:

```<code><xsd:complexType name="LISTType" xdb:maintainDOM="false" xdb:SQLType="TYPE_NUMBERLIST" >
    <xsd:sequence>
        <xsd:element name="VALUE" type="xsd:double" maxOccurs="unbounded" minOccurs="0" xdb:SQLType="NUMBER"/>
    </xsd:sequence>
</xsd:complexType>
<xsd:element name="document" type="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST"/>
<xsd:complexType name="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST" xdb:maintainDOM="false">
    <xsd:sequence>
        <xsd:element name="LIST" xdb:SQLCollType="TYPE_NUMBERLIST" xdb:SQLCollSchema="TEST"/>
        <xsd:element name="OBJ1" type="xsd:double" xdb:SQLName="OBJ1" xdb:SQLType="NUMBER"/>
        <xsd:element name="OBJ2" type="xsd:double" xdb:SQLName="OBJ2" xdb:SQLType="NUMBER"/>
    </xsd:sequence>
 </xsd:complexType>
</code>```

Title: Create parent node in XMLSCHEMA

Body:
Have objects:

create or replace type test.type_numberlist as table of number;
/

create or replace type test.type_test as object (
    LIST  test.type_numberlist
  , OBJ1  number
  , OBJ2  number
)
/

create simple xml schema:

BEGIN DBMS_XMLSCHEMA.registerSchema(
  SCHEMAURL => 'testschema.xsd',
  SCHEMADOC => '<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xdb="http://xmlns.oracle.com/xdb"
            xsi:schemaLocation="http://xmlns.oracle.com/xdb http://xmlns.oracle.com/xdb/XDBSchema.xsd">
  <xsd:element name="document" type="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST"/>
  <xsd:complexType name="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST" xdb:maintainDOM="false">
  <xsd:sequence>
   <xsd:element name="LIST" type="xsd:double" maxOccurs="unbounded" minOccurs="0" xdb:SQLName="LIST" xdb:SQLCollType="TYPE_NUMBERLIST" xdb:SQLType="NUMBER" xdb:SQLCollSchema="TEST"/>
   <xsd:element name="OBJ1" type="xsd:double" xdb:SQLName="OBJ1" xdb:SQLType="NUMBER"/>
   <xsd:element name="OBJ2" type="xsd:double" xdb:SQLName="OBJ2" xdb:SQLType="NUMBER"/>
  </xsd:sequence>
 </xsd:complexType>
</xsd:schema>',
   LOCAL     => FALSE,
   GENTYPES  => FALSE,
   OWNER     => 'TEST');
END;
/

test generation xml by object:

declare
  i test.type_test := new test.type_test(LIST => test.type_numberlist(1,2)
                                        ,OBJ1 => 1
                                        ,OBJ2 => 2);
  v_xml xmltype;
begin
  v_xml := xmltype( xmlData => i
                  , schema => 'TESTSCHEMA.xsd'
                  , element => 'document'
                  , validated => 1);
  dbms_output.put_line(v_xml.getstringval());
end;

get this xml:

<document>
  <LIST>1</LIST>
  <LIST>2</LIST>
  <OBJ1>1</OBJ1>
  <OBJ2>2</OBJ2>
</document>

LIST on same level as OBJ1, OBJ2. Is there any way to change XMLSCHEMA to create parent node to LIST to create xml like:

<document>
  <LIST>
    <value>1</value>
    <value>2</value>
  </LIST>
  <OBJ1>1</OBJ1>
  <OBJ2>2</OBJ2>
</document>

Body:
Create a new  complexType named LISTType:

<xsd:complexType name="LISTType" xdb:maintainDOM="false" xdb:SQLType="TYPE_NUMBERLIST" >
    <xsd:sequence>
        <xsd:element name="VALUE" type="xsd:double" maxOccurs="unbounded" minOccurs="0" xdb:SQLType="NUMBER"/>
    </xsd:sequence>
</xsd:complexType>
<xsd:element name="document" type="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST"/>
<xsd:complexType name="TYPE_TESTType" xdb:SQLType="TYPE_TEST" xdb:SQLSchema="TEST" xdb:maintainDOM="false">
    <xsd:sequence>
        <xsd:element name="LIST" xdb:SQLCollType="TYPE_NUMBERLIST" xdb:SQLCollSchema="TEST"/>
        <xsd:element name="OBJ1" type="xsd:double" xdb:SQLName="OBJ1" xdb:SQLType="NUMBER"/>
        <xsd:element name="OBJ2" type="xsd:double" xdb:SQLName="OBJ2" xdb:SQLType="NUMBER"/>
    </xsd:sequence>
 </xsd:complexType>


问:
Java inheritance, generics and the byte-code
When a class in Java inherits another, does the inherited class become (physically) part of the inheriting class such that its byte-code is added to the .class file for the inheriting class? Or does the .class file for the inheriting class contain only the part specific to it and it's at run time that object details from the two .class files of both classes are built together into one object? If either or both classes was generic, would it have effect on the process? Thx.</p>

答:
The second one, for example if you compile the following two classes:

```<code>public class Parent {
  public void myMethod(String arg) {
  }
}

public class Child extends Parent {
  public void myMethod(String arg) {
    super.myMethod(arg);
  }
}
</code>```

Then, after you had compiled both classes, you change the Parent class like:

```<code>public class Parent {
  public void myMethod(Integer arg) {
  }
}
</code>```

You'll get a NoSuchMethodError, this happens because Child call the parent's myMethod at runtime.

I hope it was clear, bye.

Body:
The second one, for example if you compile the following two classes:

public class Parent {
  public void myMethod(String arg) {
  }
}

public class Child extends Parent {
  public void myMethod(String arg) {
    super.myMethod(arg);
  }
}

Then, after you had compiled both classes, you change the Parent class like:

public class Parent {
  public void myMethod(Integer arg) {
  }
}

You'll get a NoSuchMethodError, this happens because Child call the parent's myMethod at runtime.

I hope it was clear, bye.


问:
Rails: TypeError: Object doesn't support this property or method
So I'm trying to make my first ruby on rails app. I don't have any experience neither with ruby nor with rails. I tried to find answer, but it was not successful.

My error is:
C:/Sites/projects/test/app/views/layouts/application.html.erb where line #10 raised:
TypeError: Object doesn't support this property or method
Extracted source (around line #10)

My application.html.erb:

```<code> <!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <%= csrf_meta_tags %>

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.css">

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div class="container">
  <%= yield %>
</div>
  </body>
</html>
</code>```

My gemfile:

```<code>source 'https://rubygems.org'
    git_source(:github) do |repo_name|
      repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
      "https://github.com/#{repo_name}.git"
    end

    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
    gem 'rails', '~> 5.1.4'
    # Use sqlite3 as the database for Active Record
    gem 'sqlite3'
    # Use Puma as the app server
    gem 'puma', '~> 3.7'
    # Use SCSS for stylesheets
    gem 'sass-rails', '~> 5.0'
    # Use Uglifier as compressor for JavaScript assets
    gem 'uglifier', '>= 1.3.0'
    # See https://github.com/rails/execjs#readme for more supported runtimes
    # gem 'therubyracer', platforms: :ruby

    # Use CoffeeScript for .coffee assets and views
    gem 'coffee-rails', '~> 4.2'
    # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
    gem 'turbolinks', '~> 5'
    # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 2.5'
    # Use Redis adapter to run Action Cable in production
    # gem 'redis', '~> 3.0'
    # Use ActiveModel has_secure_password
    # gem 'bcrypt', '~> 3.1.7'

    # Use Capistrano for deployment
    # gem 'capistrano-rails', group: :development

    group :development, :test do
      # Call 'byebug' anywhere in the code to stop execution and get a debugger console
      gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
      # Adds support for Capybara system testing and selenium driver
      gem 'capybara', '~> 2.13'
      gem 'selenium-webdriver'
    end

    group :development do
      # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
      gem 'web-console', '>= 3.3.0'
    end

    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

Route file :

```<code>Rails.application.routes.draw do
    root to: redirect('/ideas')
  resources :ideas
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
</code>```

And controllers:

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

class IdeasController < ApplicationController
  before_action :set_idea, only: [:show, :edit, :update, :destroy]

  # GET /ideas
  # GET /ideas.json
  def index
    @ideas = Idea.all
  end

  # GET /ideas/1
  # GET /ideas/1.json
  def show
  end

  # GET /ideas/new
  def new
    @idea = Idea.new
  end

  # GET /ideas/1/edit
  def edit
  end

  # POST /ideas
  # POST /ideas.json
  def create
    @idea = Idea.new(idea_params)

    respond_to do |format|
      if @idea.save
        format.html { redirect_to @idea, notice: 'Idea was successfully created.' }
        format.json { render :show, status: :created, location: @idea }
      else
        format.html { render :new }
        format.json { render json: @idea.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /ideas/1
  # PATCH/PUT /ideas/1.json
  def update
    respond_to do |format|
      if @idea.update(idea_params)
        format.html { redirect_to @idea, notice: 'Idea was successfully updated.' }
        format.json { render :show, status: :ok, location: @idea }
      else
        format.html { render :edit }
        format.json { render json: @idea.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /ideas/1
  # DELETE /ideas/1.json
  def destroy
    @idea.destroy
    respond_to do |format|
      format.html { redirect_to ideas_url, notice: 'Idea was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_idea
      @idea = Idea.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def idea_params
      params.require(:idea).permit(:name, :description, :picture)
    end
end
</code>```

I've already tried to replace application with default in application.html.erb.

答:
There's a similar question I've flagged which might help - their solution was the following:

I removed the require_tree from application.js and it worked

//= require jquery

  //= require jquery_ujs

  //= require turbolinks

  // require_tree .

That would suggest there's a problem within your javascript somewhere - if this approach works, I'd look for anything amiss there, and / or add them in one by one.

The other thing I'd try would be removing the Turbolinks option in your javascript_include_tag to see if that's messing anything up.

Let me know if this helps!

Edit:

To directly link the other thread in the answer, it's here:

TypeError: Object doesn't support this property or method

With a couple more branching off it:

Rails ExecJS::ProgramError in Pages#home?

ExecJS::RuntimeError on Windows trying to follow rubytutorial

A fair bit of reading in there :)

Body:
So I'm trying to make my first ruby on rails app. I don't have any experience neither with ruby nor with rails. I tried to find answer, but it was not successful.

My error is:
C:/Sites/projects/test/app/views/layouts/application.html.erb where line #10 raised:
TypeError: Object doesn't support this property or method
Extracted source (around line #10)

My application.html.erb:

 <!DOCTYPE html>

    <title>Test</title>
    <%= csrf_meta_tags %>

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.css">

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

  <%= yield %>

My gemfile:

source 'https://rubygems.org'
    git_source(:github) do |repo_name|
      repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
      "https://github.com/#{repo_name}.git"
    end

    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
    gem 'rails', '~> 5.1.4'
    # Use sqlite3 as the database for Active Record
    gem 'sqlite3'
    # Use Puma as the app server
    gem 'puma', '~> 3.7'
    # Use SCSS for stylesheets
    gem 'sass-rails', '~> 5.0'
    # Use Uglifier as compressor for JavaScript assets
    gem 'uglifier', '>= 1.3.0'
    # See https://github.com/rails/execjs#readme for more supported runtimes
    # gem 'therubyracer', platforms: :ruby

    # Use CoffeeScript for .coffee assets and views
    gem 'coffee-rails', '~> 4.2'
    # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
    gem 'turbolinks', '~> 5'
    # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
    gem 'jbuilder', '~> 2.5'
    # Use Redis adapter to run Action Cable in production
    # gem 'redis', '~> 3.0'
    # Use ActiveModel has_secure_password
    # gem 'bcrypt', '~> 3.1.7'

    # Use Capistrano for deployment
    # gem 'capistrano-rails', group: :development

    group :development, :test do
      # Call 'byebug' anywhere in the code to stop execution and get a debugger console
      gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
      # Adds support for Capybara system testing and selenium driver
      gem 'capybara', '~> 2.13'
      gem 'selenium-webdriver'
    end

    group :development do
      # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
      gem 'web-console', '>= 3.3.0'
    end

    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
    gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Route file :

Rails.application.routes.draw do
    root to: redirect('/ideas')
  resources :ideas
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

And controllers:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

class IdeasController < ApplicationController
  before_action :set_idea, only: [:show, :edit, :update, :destroy]

  # GET /ideas
  # GET /ideas.json
  def index
    @ideas = Idea.all
  end

  # GET /ideas/1
  # GET /ideas/1.json
  def show
  end

  # GET /ideas/new
  def new
    @idea = Idea.new
  end

  # GET /ideas/1/edit
  def edit
  end

  # POST /ideas
  # POST /ideas.json
  def create
    @idea = Idea.new(idea_params)

    respond_to do |format|
      if @idea.save
        format.html { redirect_to @idea, notice: 'Idea was successfully created.' }
        format.json { render :show, status: :created, location: @idea }
      else
        format.html { render :new }
        format.json { render json: @idea.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /ideas/1
  # PATCH/PUT /ideas/1.json
  def update
    respond_to do |format|
      if @idea.update(idea_params)
        format.html { redirect_to @idea, notice: 'Idea was successfully updated.' }
        format.json { render :show, status: :ok, location: @idea }
      else
        format.html { render :edit }
        format.json { render json: @idea.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /ideas/1
  # DELETE /ideas/1.json
  def destroy
    @idea.destroy
    respond_to do |format|
      format.html { redirect_to ideas_url, notice: 'Idea was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_idea
      @idea = Idea.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def idea_params
      params.require(:idea).permit(:name, :description, :picture)
    end
end

I've already tried to replace application with default in application.html.erb.


问:
How do I select rows in a data frame before and after a condition is met?
I'm searching the web for a few a days now and I can't find a solution to my (probably easy to solve) problem.

I have huge data frames with 4 variables and over a million observations each. Now I want to select 100 rows before, all rows while and 1000 rows after a specific condition is met and fill the rest with NA's. I tried it with a for loop and if/ifelse but it doesn't work so far. I think it shouldn't be a big thing, but in the moment I just don't get the hang of it.

I create the data using:

```<code>foo<-data.frame(t = 1:15, a = sample(1:15), b = c(1,1,1,1,1,4,4,4,4,1,1,1,1,1,1), c = sample(1:15))
</code>```

My Data looks like this:

```<code>ID    t   a   b   c
1     1   4   1   7
2     2   7   1   10
3     3   10  1   6
4     4   2   1   4
5     5   13  1   9
6     6   15  4   3
7     7   8   4   15
8     8   3   4   1
9     9   9   4   2
10   10   14  1   8
11   11   5   1   11
12   12   11  1   13
13   13   12  1   5
14   14   6   1   14
15   15   1   1   12
</code>```

What I want is to pick the value of a (in this example) 2 rows before, all rows while and 3 rows after the value of b is >1 and fill the rest with NA's. [Because this is just an example I guess you can imagine that after these 15 rows there are more rows with the value for b changing from 1 to 4 several times (I did not post it, so I won't spam the question with unnecessary data).]
So I want to get something like:

```<code>ID    t   a   b   c   d
1     1   4   1   7  NA
2     2   7   1   10 NA
3     3   10  1   6  NA
4     4   2   1   4   2
5     5   13  1   9  13
6     6   15  4   3  15
7     7   8   4   15  8
8     8   3   4   1   3
9     9   9   4   2   9
10   10   14  1   8  14
11   11   5   1   11  5
12   12   11  1   13 11
13   13   12  1   5  NA
14   14   6   1   14 NA
15   15   1   1   12 NA
</code>```

I'm thankful for any help.

Thank you.

Best regards,
Chris

答:
```<code>library(dplyr)
library(purrr)

# example dataset
foo<-data.frame(t = 1:15,
                a = sample(1:15),
                b = c(1,1,1,1,1,4,4,4,4,1,1,1,1,1,1),
                c = sample(1:15))

# function to get indices of interest
# for a given index x go 2 positions back and 3 forward
# keep only positive indices
GetIDsBeforeAfter = function(x) {
  v = (x-2) : (x+3)
  v[v > 0]
}

foo %>%                        # from your dataset
  filter(b > 1) %>%            # keep rows where b > 1
  pull(t) %>%                  # get the positions
  map(GetIDsBeforeAfter) %>%   # for each position apply the function
  unlist() %>%                 # unlist all sets indices
  unique() -> ids_to_remain    # keep unique ones and save them in a vector

foo$d = foo$c                  # copy column c as d
foo$d[-ids_to_remain] = NA     # put NA to all positions not in our vector

foo

#     t  a b  c  d
# 1   1  5 1  8 NA
# 2   2  6 1 14 NA
# 3   3  4 1 10 NA
# 4   4  1 1  7  7
# 5   5 10 1  5  5
# 6   6  8 4  9  9
# 7   7  9 4 15 15
# 8   8  3 4  6  6
# 9   9  7 4  2  2
# 10 10 12 1  3  3
# 11 11 11 1  1  1
# 12 12 15 1  4  4
# 13 13 14 1 11 NA
# 14 14 13 1 13 NA
# 15 15  2 1 12 NA
</code>```

Body:
I'm searching the web for a few a days now and I can't find a solution to my (probably easy to solve) problem.

I have huge data frames with 4 variables and over a million observations each. Now I want to select 100 rows before, all rows while and 1000 rows after a specific condition is met and fill the rest with NA's. I tried it with a for loop and if/ifelse but it doesn't work so far. I think it shouldn't be a big thing, but in the moment I just don't get the hang of it.

I create the data using:

foo<-data.frame(t = 1:15, a = sample(1:15), b = c(1,1,1,1,1,4,4,4,4,1,1,1,1,1,1), c = sample(1:15))

My Data looks like this:

ID    t   a   b   c
1     1   4   1   7
2     2   7   1   10
3     3   10  1   6
4     4   2   1   4
5     5   13  1   9
6     6   15  4   3
7     7   8   4   15
8     8   3   4   1
9     9   9   4   2
10   10   14  1   8
11   11   5   1   11
12   12   11  1   13
13   13   12  1   5
14   14   6   1   14
15   15   1   1   12

What I want is to pick the value of a (in this example) 2 rows before, all rows while and 3 rows after the value of b is >1 and fill the rest with NA's. [Because this is just an example I guess you can imagine that after these 15 rows there are more rows with the value for b changing from 1 to 4 several times (I did not post it, so I won't spam the question with unnecessary data).]
So I want to get something like:

ID    t   a   b   c   d
1     1   4   1   7  NA
2     2   7   1   10 NA
3     3   10  1   6  NA
4     4   2   1   4   2
5     5   13  1   9  13
6     6   15  4   3  15
7     7   8   4   15  8
8     8   3   4   1   3
9     9   9   4   2   9
10   10   14  1   8  14
11   11   5   1   11  5
12   12   11  1   13 11
13   13   12  1   5  NA
14   14   6   1   14 NA
15   15   1   1   12 NA

I'm thankful for any help.

Thank you.

Best regards,
Chris


问:
Check if a value exists in an Array object in JavaScript or Angular
I want to check if a value exist in an array object. Example:

I have this array:

```<code>[
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'test'}
]
</code>```

And I want check if id = 2 exists here.

答:
You can use the find method as below:

var x=[
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'test'}
]
var target=x.find(temp=>temp.id==2)
if(target)
  console.log(target)
else
  console.log("doesn't exists")```

ContentLicense: CC BY-SA 4.0

Body:
I want to check if a value exist in an array object. Example:

I have this array:

[
    {id: 1, name: 'foo'},
    {id: 2, name: 'bar'},
    {id: 3, name: 'test'}
]

And I want check if id = 2 exists here.


答:
Pipes work by chaining stdin and stdout of multiple programs together.

You need to modify your program to have the ability to read from stdin and write to stdout instead of to specific files.  Then you can use pipes.

Title: Piping to same c program using stdin and stdout


答:
You can use Array.prototype.some

var a = [
   {id: 1, name: 'foo'},
   {id: 2, name: 'bar'},
   {id: 3, name: 'test'}
];

var isPresent = a.some(function(el){ return el.id === 2});
console.log(isPresent);```

Title: Check if a value exists in an Array object in JavaScript or Angular


答:
Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem </p>

```<code>$lineExists = false;
    foreach($_SESSION['cart'] as $index => $line){
        if($line['id'] === $id)
        {
            $_SESSION['cart'][$index]['quantity'] += $quantity;
            $lineExists = true;
        }
    }
    if(!$lineExists)
    {
        $_SESSION['cart'][] = $newLine;
    }
</code>```

Title: Check if array exist by two keys with PHP

Body:
Something like this should do, however the question is too vague and too little code is shown for me to properly understand your problem

$lineExists = false;
    foreach($_SESSION['cart'] as $index => $line){
        if($line['id'] === $id)
        {
            $_SESSION['cart'][$index]['quantity'] += $quantity;
            $lineExists = true;
        }
    }
    if(!$lineExists)
    {
        $_SESSION['cart'][] = $newLine;
    }


问:
How to make new decorators available within a class without explicitly importing them?
Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator):

```<code>class SomeClass:

    @some_decorator
    def some_method(self):
        pass
</code>```

I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass.

Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery.

To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible.

ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

答:
Write a decorator that takes a list of strings and imports them before the function is called for the first time. This avoids explicit imports until the last possible moment before they're needed. This, like all the other answers here, is probably an indication that your code should be restructured instead.

```<code>from functools import wraps
from importlib import import_module

def deferred(*names):
    def decorator(f):
        # this will hold the fully decorated function
        final_f = None

        @wraps(f)
        def wrapper(*args, **kwargs):
            nonlocal final_f

            if final_f is None:
                # start with the initial function
                final_f = f

                for name in names:
                    # assume the last . is the object to import
                    # import the module then get the object
                    mod, obj = name.rsplit('.', 1)
                    d = getattr(import_module(mod), obj)
                    # decorate the function and keep going
                    final_f = d(final_f)

            return final_f(*args, **kwargs)

        return wrapper

    return decorator
</code>```

```<code># for demonstration purposes, decorate with a function defined after this
# assumes this file is called "example.py"
@deferred('example.double')
def add(x, y):
    return x + y

def double(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return 2 * f(*args, **kwargs)

    return wrapper

if __name__ == '__main__':
    print(add(3, 6))  # 18
</code>```

The arguments to deferred should be strings of the form 'path.to.module.decorator. path.to.module is imported and then decorator is retrieved from the module. Each decorator is applied to wrap the function. The function is stored in a nonlocal so that this import and decorating only needs to happen the first time the function is called.

Body:
Is it possible to modify a class so as to make available a certain method decorator, without having to explicitly import it and without having to prefix it (@something.some_decorator):

class SomeClass:

    @some_decorator
    def some_method(self):
        pass

I don't think this is possible with a class decorator, because that is applied too late. The option that seems more promising is using a metaclass, but I am unsure how, my guess is that I would have to have some_decorator be introduced into the namespace of SomeClass.

Thanks to @MartijnPieters for pointing out that staticmethod and classmethod are built-ins. I had expected them to be part of the type machinery.

To be clear, I don't have any explicit use-case for this, I am just curious as to whether this is at all possible.

ADDENDUM, now that the question has been answered. The original reason why I was looking beyond simply importing or defining a decorator locally, was that I had defined a decorator that would only work if a certain container attribute was initialised on an object, and I was looking for a way to tie enforcing this to the availability of the decorator. I ended up checking whether the attribute existed and if not initialising it within the decorator, which may very well be the lesser evil here.

Body:
Write a decorator that takes a list of strings and imports them before the function is called for the first time. This avoids explicit imports until the last possible moment before they're needed. This, like all the other answers here, is probably an indication that your code should be restructured instead.

from functools import wraps
from importlib import import_module

def deferred(*names):
    def decorator(f):
        # this will hold the fully decorated function
        final_f = None

        @wraps(f)
        def wrapper(*args, **kwargs):
            nonlocal final_f

            if final_f is None:
                # start with the initial function
                final_f = f

                for name in names:
                    # assume the last . is the object to import
                    # import the module then get the object
                    mod, obj = name.rsplit('.', 1)
                    d = getattr(import_module(mod), obj)
                    # decorate the function and keep going
                    final_f = d(final_f)

            return final_f(*args, **kwargs)

        return wrapper

    return decorator

# for demonstration purposes, decorate with a function defined after this
# assumes this file is called "example.py"
@deferred('example.double')
def add(x, y):
    return x + y

def double(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return 2 * f(*args, **kwargs)

    return wrapper

if __name__ == '__main__':
    print(add(3, 6))  # 18

The arguments to deferred should be strings of the form 'path.to.module.decorator. path.to.module is imported and then decorator is retrieved from the module. Each decorator is applied to wrap the function. The function is stored in a nonlocal so that this import and decorating only needs to happen the first time the function is called.


问:
d3.js radial treed downloads differently to svg
I was creating a radial tree and trying to download it to SVG but it has some issues

It downloads with those black thick strokes which are not displayed on the webpage.

Any idea where the black lines are coming from?

```<code>var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + (width / 2 - 15) + ","
+ (height / 2 + 25) + ")");

var stratify = d3.stratify()
.parentId(function(d) {
console.log(d.id.substring(0, d.id.lastIndexOf(".")));
return d.id.substring(0, d.id.lastIndexOf(".")); });

var tree = d3.cluster()
tree.size([360, 360])
tree.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) /
a.depth; });

d3.csv("flare.csv", function(error, data) {
 if (error) throw error;

 var root = tree(stratify(data)
  .sort(function(a, b) { return (a.height - b.height + 100) ||
a.id.localeCompare(b.id); }));

 var link = g.selectAll(".link")
.data(root.descendants().slice(1))
.enter().append("path")
  .attr("class", "link")
  .attr("d", function(d) {
    return "M" + project(d.x, d.y)
        + "C" + project(d.x, (d.y + d.parent.y) / 2)
        + " " + project(d.parent.x, (d.y + d.parent.y) / 2)
        + " " + project(d.parent.x, d.parent.y);
  });

link.attr('stroke', function(d) {
   if (d.id.startsWith("Mother.Biological")){
      return "#386eff";
    }
    if (d.id.startsWith("Mother.Env")){
      return "#45cbf2";
    }
    else return '#70f2ad';
    });
var node = g.selectAll(".node")
.data(root.descendants())
.enter().append("g")
  .attr("class", function(d) { return "node" + (d.children ? " node--
internal" : " node--leaf"); })
    .attr("transform", function(d) { return "translate(" + project(d.x,
d.y)
+ ")"; });

node.append("circle")
  .attr("r", function(d) {
  console.log(d.value);
  if (d.id == "Mother") return 4.4;
  else return 2.4;
  } )
  .style('fill', function(d) {
   if (d.id.startsWith("Mother.Biological")){
      return "#386eff";
    }
     if (d.id.startsWith("Mother.Env")){
      return "#45cbf2";
    }
   if (d.id.startsWith("Mother.Biological")){
      return "#386eff";
    }
     if (d.id.startsWith("Mother.Form")){
      return '#70f2ad';
    }
  d.color = 'red';

  return d.color});

  node.append("text")
  .attr("dy", ".31em")
  .attr("x", function(d) { return d.x < 180 === !d.children ? 6 : -6; })
  .style("text-anchor", function(d) { return d.x < 180 === !d.children ?
"start" : "end"; })
  .attr("transform", function(d) { return "rotate(" + (d.x < 180 ? d.x - 90
: d.x + 90) + ")"; })
  .text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });
});

function project(x, y) {
  var angle = (x - 90) / 180 * Math.PI, radius = y;
  return [radius * Math.cos(angle), radius * Math.sin(angle)];
}

d3.select("#download")
.on("mouseover", writeDownloadLink);

function writeDownloadLink(){
var html = d3.select("svg")
    .attr("title", "svg_title")
    .attr("version", 1.1)
    .attr("xmlns", "http://www.w3.org/2000/svg")
    .node().parentNode.innerHTML;

d3.select(this)
    .attr("href-lang", "image/svg+xml")
    .attr("href", "data:image/svg+xml;base64,\n" + btoa(html))
    .on("mousedown", function(){
        if(event.button != 2){
            d3.select(this)
                .attr("href", null)
                .html("Use right click");
        }
    })
    .on("mouseout", function(){
        d3.select(this)
            .html("Download");
    });
</code>```

};

It looks ok in any browser but when I download it and convert it to SVG or EFM it comes back with those lines.

答:
Page that you provided contains style tag. I'm not sure how exactly do you export SVG, but some css rules seems to be lost along the way.

In similar case I managed to get current css properties and put them into style property:

```<code>d3.selectAll('...').each(function() {
  var that = d3.select(this);
  ['stroke', 'stroke-width', 'opacity', 'fill', ...].forEach(function(property) {
    that.style(property, that.style(property))
  });
});
</code>```

Hope this will help you.

Body:
I was creating a radial tree and trying to download it to SVG but it has some issues

It downloads with those black thick strokes which are not displayed on the webpage.

Any idea where the black lines are coming from?

var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + (width / 2 - 15) + ","
+ (height / 2 + 25) + ")");

var stratify = d3.stratify()
.parentId(function(d) {
console.log(d.id.substring(0, d.id.lastIndexOf(".")));
return d.id.substring(0, d.id.lastIndexOf(".")); });

var tree = d3.cluster()
tree.size([360, 360])
tree.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) /
a.depth; });

d3.csv("flare.csv", function(error, data) {
 if (error) throw error;

 var root = tree(stratify(data)
  .sort(function(a, b) { return (a.height - b.height + 100) ||
a.id.localeCompare(b.id); }));

 var link = g.selectAll(".link")
.data(root.descendants().slice(1))
.enter().append("path")
  .attr("class", "link")
  .attr("d", function(d) {
    return "M" + project(d.x, d.y)
        + "C" + project(d.x, (d.y + d.parent.y) / 2)
        + " " + project(d.parent.x, (d.y + d.parent.y) / 2)
        + " " + project(d.parent.x, d.parent.y);
  });

link.attr('stroke', function(d) {
   if (d.id.startsWith("Mother.Biological")){
      return "#386eff";
    }
    if (d.id.startsWith("Mother.Env")){
      return "#45cbf2";
    }
    else return '#70f2ad';
    });
var node = g.selectAll(".node")
.data(root.descendants())
.enter().append("g")
  .attr("class", function(d) { return "node" + (d.children ? " node--
internal" : " node--leaf"); })
    .attr("transform", function(d) { return "translate(" + project(d.x,
d.y)
+ ")"; });

node.append("circle")
  .attr("r", function(d) {
  console.log(d.value);
  if (d.id == "Mother") return 4.4;
  else return 2.4;
  } )
  .style('fill', function(d) {
   if (d.id.startsWith("Mother.Biological")){
      return "#386eff";
    }
     if (d.id.startsWith("Mother.Env")){
      return "#45cbf2";
    }
   if (d.id.startsWith("Mother.Biological")){
      return "#386eff";
    }
     if (d.id.startsWith("Mother.Form")){
      return '#70f2ad';
    }
  d.color = 'red';

  return d.color});

  node.append("text")
  .attr("dy", ".31em")
  .attr("x", function(d) { return d.x < 180 === !d.children ? 6 : -6; })
  .style("text-anchor", function(d) { return d.x < 180 === !d.children ?
"start" : "end"; })
  .attr("transform", function(d) { return "rotate(" + (d.x < 180 ? d.x - 90
: d.x + 90) + ")"; })
  .text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });
});

function project(x, y) {
  var angle = (x - 90) / 180 * Math.PI, radius = y;
  return [radius * Math.cos(angle), radius * Math.sin(angle)];
}

d3.select("#download")
.on("mouseover", writeDownloadLink);

function writeDownloadLink(){
var html = d3.select("svg")
    .attr("title", "svg_title")
    .attr("version", 1.1)
    .attr("xmlns", "http://www.w3.org/2000/svg")
    .node().parentNode.innerHTML;

d3.select(this)
    .attr("href-lang", "image/svg+xml")
    .attr("href", "data:image/svg+xml;base64,\n" + btoa(html))
    .on("mousedown", function(){
        if(event.button != 2){
            d3.select(this)
                .attr("href", null)
                .html("Use right click");
        }
    })
    .on("mouseout", function(){
        d3.select(this)
            .html("Download");
    });

};

It looks ok in any browser but when I download it and convert it to SVG or EFM it comes back with those lines.

Body:
Page that you provided contains style tag. I'm not sure how exactly do you export SVG, but some css rules seems to be lost along the way.

In similar case I managed to get current css properties and put them into style property:

d3.selectAll('...').each(function() {
  var that = d3.select(this);
  ['stroke', 'stroke-width', 'opacity', 'fill', ...].forEach(function(property) {
    that.style(property, that.style(property))
  });
});

Hope this will help you.


问:
Single SWF file for Flex 4 created apps?
I made an application in Flex 4. When I export a release build, it generates a whole bunch of files. (including the skins used, etc, etc.)

How do I make those plentiful files except the container HTML file, get compiled into a single SWF file?

E.g.,
My folder should only contain:

my_app.swf

my_app.html

But my_app.swf should still run like a normal Flex 4 app, only this time, all the files, images, skins, etc are inside that one SWF file.

Thanks to those who'd help!

答:
Open your project in Flash Builder, go to:

Project->Properties

than

Flex Build Path->Library Path

and finally change the dropdown named "Framework linkage" to "Merged into code".

Recompile :)


问:
Bootstrap 4 carousel slider arrows alignment
I'm using Bootstrap 4 Alpha 6 carousel plugin to interactive a div slider.

I want the right and left transparent buttons to be positioned to the extreme right and extreme left respectively, as shown in the image below.

I have tried changing the position and followed previous post method, but all does not work for my case.

```<code>.carousel-control .glyphicon-chevron-right, .carousel-control .icon-next {
  right: 0;
}

.carousel-control .glyphicon-chevron-left, .carousel-control .icon-prev {
  left: 0;
}
</code>```

Does anyone have a recommendation for the best way to handle this?
Thanks in advance!

答:
Bootstrap 4 dosen't use glyphicon's, and the framework as a whole has been rewritten in this newer version. This means that carousel snippets for bootstrap 3 likely won't work in Bootstrap 4.

The left and right arrows in the Bootstrap 4 Alpha are tied to the icon-prev and icon-next classes.

Therefore you can set them to be positioned to the extreme right and extreme left respectively with this code.

```<code>.carousel-control .icon-prev{
  left: 5px
}
.carousel-control .icon-next{
  right: 5px
}
</code>```

Codepen demo: https://codepen.io/Washable/pen/EbbOXd?editors=1100

Body:
I'm using Bootstrap 4 Alpha 6 carousel plugin to interactive a div slider.

I want the right and left transparent buttons to be positioned to the extreme right and extreme left respectively, as shown in the image below.

I have tried changing the position and followed previous post method, but all does not work for my case.

.carousel-control .glyphicon-chevron-right, .carousel-control .icon-next {
  right: 0;
}

.carousel-control .glyphicon-chevron-left, .carousel-control .icon-prev {
  left: 0;
}

Does anyone have a recommendation for the best way to handle this?
Thanks in advance!

Body:
Bootstrap 4 dosen't use glyphicon's, and the framework as a whole has been rewritten in this newer version. This means that carousel snippets for bootstrap 3 likely won't work in Bootstrap 4.

The left and right arrows in the Bootstrap 4 Alpha are tied to the icon-prev and icon-next classes.

Therefore you can set them to be positioned to the extreme right and extreme left respectively with this code.

.carousel-control .icon-prev{
  left: 5px
}
.carousel-control .icon-next{
  right: 5px
}

Codepen demo: https://codepen.io/Washable/pen/EbbOXd?editors=1100


问:
Call function from different sampler in JMeter - Groovy
I have a sampler that get data from DB (budget), and I have some assertions that I made using JSR223 assertion.
In each assertion I write the same function (check_budget) and to each assertion I pass different values (start_budget, end_budget etc)

The problem is that I duplicate the code for each assertion and it is not friendly for maintenance.(if logic change need to change at 7 duplicate functions)
It there a way to create a sampler and write generic function in it (calc_budget) and to call it from each assertion,
like creating a class in java and perform import?

答:
In that case, and in general also, you can keep groovy script in a script file and call the same script file from all JSR223 elements

Script File
  Name of a file to be used as a JSR223 script, if a relative file path is used, then it will be relative to directory referenced by "user.dir" System property


问:
Firebase RT returns 4 objects but only 3 are available
If there is anything I could add to assist please let me know. Trying to obtain the key for the items, but trying to first tackle retrieving the data and displaying it.

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  coursesRef: AngularFireObject<any>;
  courses: Observable<any>;

  constructor(db: AngularFireDatabase) {
    this.coursesRef = db.object('/courses');
    this.courses = this.coursesRef.valueChanges();

    this.courses.subscribe(course => console.log(course));
  }
}
</code>```

app.component.html

```<code><ul>
  <li *ngFor="let course of courses | async">
    {{ course | json }}
  </li>
</ul>
</code>```

this returns a 4 objects although the database only contains 3.

答:
I believe the answer is that the object should be called in the ngOnInit function.

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  coursesRef: AngularFireList<any>;
  courses: Observable<any[]>;

  constructor(private db: AngularFireDatabase) {
    this.coursesRef = db.list('/courses');
  }

  ngOnInit() {
    this.courses = this.coursesRef.valueChanges();

    this.courses.subscribe(course => console.log(course));
  }
}
</code>```

Body:
If there is anything I could add to assist please let me know. Trying to obtain the key for the items, but trying to first tackle retrieving the data and displaying it.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  coursesRef: AngularFireObject<any>;
  courses: Observable<any>;

  constructor(db: AngularFireDatabase) {
    this.coursesRef = db.object('/courses');
    this.courses = this.coursesRef.valueChanges();

    this.courses.subscribe(course => console.log(course));
  }
}

app.component.html

    {{ course | json }}

this returns a 4 objects although the database only contains 3.

Body:
I believe the answer is that the object should be called in the ngOnInit function.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  coursesRef: AngularFireList<any>;
  courses: Observable<any[]>;

  constructor(private db: AngularFireDatabase) {
    this.coursesRef = db.list('/courses');
  }

  ngOnInit() {
    this.courses = this.coursesRef.valueChanges();

    this.courses.subscribe(course => console.log(course));
  }
}