问:
update_attributes validation fails though values are correct
I have in my model

```<code>class Account < ActiveRecord::Base
 validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
 validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?

end
</code>```

when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have

```<code>@account.update_attributes({:name => "king", :amount => "1223"}
</code>```

the save fails and when I check errors I get

```<code>@account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}
</code>```

Strong Params are not an issue because I have
     def self.params
          params.require(:account).permit!
     end

I have no idea why it fails though the value are present and correct.

答:
Try this the following:</p>

```<code>class Account < ActiveRecord::Base
    validates :amount, length: { in: 1..255 }, on: :update
    validates :name, length: { in: 1..255 }, on: :update
end
</code>```

Body:
I have in my model

class Account < ActiveRecord::Base
 validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
 validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?

end

when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have

@account.update_attributes({:name => "king", :amount => "1223"}

the save fails and when I check errors I get

@account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}

Strong Params are not an issue because I have
     def self.params
          params.require(:account).permit!
     end

I have no idea why it fails though the value are present and correct.

Body:
Try this the following:

class Account < ActiveRecord::Base
    validates :amount, length: { in: 1..255 }, on: :update
    validates :name, length: { in: 1..255 }, on: :update
end


来源: stackexchange

问:
Qt + VTK +Ubuntu on VirtualBox
I need to run a Qt project with VTK on Ubuntu and I'm using VirtualBox, but I have an error:

GL version 2.1 with the gpu_shader4 extension is not supported by your
  graphics driver but is required for the new OpenGL rendering backend.
  Please update your OpenGL driver. If you are using Mesa please make
  sure you have version 10.6.5 or later and make sure your driver in
  Mesa supports OpenGL 3.2.

答:
Recent version of VTK use a new rendering backend by default. In the CMake cache file used to configure your build, the corresponding cmake variable VTK_RENDERING_BACKEND has the value "OpenGL2" which assumes a minimum OpenGL API version of 2.1. But the problem is that a vanilla installation of VirtualBox does not grant access to 3D acceleration by default as it cannot presumably infer these informations from the host system.

So I think that you have several options here depending on your needs and constraints, you could install the VirtualBox Guest Additions to enable hardware 3D acceleration, allow access to a newer version of the OpenGL API and use in the end the host to performs the requested 3D operations. You could also use a recent version of the Mesa3D library to performs the needed 3D operations on the CPU (to choose preferably if you don't have graphics hardware on the host). For a presentation of its features, you can take a look here

ContentLicense: CC BY-SA 3.0

Title: Qt + VTK +Ubuntu on VirtualBox


问:
Docker-Compose file has yaml.scanner.ScannerError but i don´t see anything
when i try to compose i get shown this:

```<code>    yaml.scanner.ScannerError: mapping values are not allowed here
  in "./docker-compose.yml", line 6, column 15
</code>```

my docker-compose.yml:

```<code>version: '2'

services:
    fhem:
        restart:always
        expose:
            - "8083"
            - "7072"
        ports:
            - "8083:8083"
            - "7072:7072"
        build: fhem
        privileged: true
        devices:
          - "/dev/ttyUSB0:/dev/ttyUSB0"
       ....
</code>```

can´t see any wrong syntax at all

答:
You're missing a space after the colon following restart (per @bartimar), and your device line isn't indented correctly, since you're using 4 space indent.

```<code>version: '2'

services:
    fhem:
        restart: always
        expose:
            - "8083"
            - "7072"
        ports:
            - "8083:8083"
            - "7072:7072"
        build: fhem
        privileged: true
        devices:
            - "/dev/ttyUSB0:/dev/ttyUSB0"
</code>```

Body:
when i try to compose i get shown this:

    yaml.scanner.ScannerError: mapping values are not allowed here
  in "./docker-compose.yml", line 6, column 15

my docker-compose.yml:

version: '2'

services:
    fhem:
        restart:always
        expose:
            - "8083"
            - "7072"
        ports:
            - "8083:8083"
            - "7072:7072"
        build: fhem
        privileged: true
        devices:
          - "/dev/ttyUSB0:/dev/ttyUSB0"
       ....

can´t see any wrong syntax at all

Body:
You're missing a space after the colon following restart (per @bartimar), and your device line isn't indented correctly, since you're using 4 space indent.

version: '2'

services:
    fhem:
        restart: always
        expose:
            - "8083"
            - "7072"
        ports:
            - "8083:8083"
            - "7072:7072"
        build: fhem
        privileged: true
        devices:
            - "/dev/ttyUSB0:/dev/ttyUSB0"


问:
Rails :Can't save audio file (paperclip)
I can't save audio file, so can you tell me how to save about audio file .
I use gem paperclip !

log is
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-1bal5v0.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.1ms)  begin transaction
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-wh10af.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.2ms)  rollback transaction
Redirected to http://localhost:3000/listings/new
Completed 302 Found in 128ms (ActiveRecord: 3.0ms)

show you model listing.rb

```<code>class Listing < ApplicationRecord
     belongs_to :user
     has_many :photos
     has_many :likes
     has_many :customers
     has_many :reviews
     validates :listing_title, presence: true

    has_attached_file  :file,  :storage => :s3,
                               :s3_credentials => "#{Rails.root}/config/s3.yml"

   validates_attachment :file, content_type: { content_type: ['file/mp3'] }

 end
</code>```

show you view new.html.erb

```<code><%= form_for @listing do |f| %>
    <div class="row">
     <div class="col-md-12 select">
       <div class="form-group">
        <label>タイトル</label>
           <%= f.text_field :listing_title, autofocus: true, :placeholder => "タイトル", :class => 'form-control', required: "true" %>
       </div>
      </div>
     </div>
     <br>

     <div class="row">
      <div class="col-md-12 select">
       <div class="form-group">
        <label>ファイル</label>
          <%= f.file_field :file, :class => 'form-control' %>
       </div>
      </div>
     </div>
     <br>

     <div class="actions">
       <%= f.submit "Save", class: "btn btn-danger" %>
     </div>
<% end %>
</code>```

Controller is nothing problem! I set params!
What should I need I success to save audio file?
Please tell me!

答:
Try with:

```<code>{ content_type: ['audio/mp3'] }
</code>```

If this still doesn't work you can try this:

```<code>{ content_type: ['audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio'] }
</code>```

Body:
I can't save audio file, so can you tell me how to save about audio file .
I use gem paperclip !

log is
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-1bal5v0.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.1ms)  begin transaction
Command :: file -b --mime '/var/folders/1z/psyvq9q911b7hclx5xw03dk40000gn/T/4266fc074db087b967597da8e4d2d11020171116-3739-wh10af.mp3'
[paperclip] Content Type Spoof: Filename as333auda.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: video/mp4. See documentation to allow this combination.
   (0.2ms)  rollback transaction
Redirected to http://localhost:3000/listings/new
Completed 302 Found in 128ms (ActiveRecord: 3.0ms)

show you model listing.rb

class Listing < ApplicationRecord
     belongs_to :user
     has_many :photos
     has_many :likes
     has_many :customers
     has_many :reviews
     validates :listing_title, presence: true

    has_attached_file  :file,  :storage => :s3,
                               :s3_credentials => "#{Rails.root}/config/s3.yml"

   validates_attachment :file, content_type: { content_type: ['file/mp3'] }

 end

show you view new.html.erb

<%= form_for @listing do |f| %>

        タイトル
           <%= f.text_field :listing_title, autofocus: true, :placeholder => "タイトル", :class => 'form-control', required: "true" %>

        ファイル
          <%= f.file_field :file, :class => 'form-control' %>

       <%= f.submit "Save", class: "btn btn-danger" %>

<% end %>

Controller is nothing problem! I set params!
What should I need I success to save audio file?
Please tell me!

Body:
Try with:

{ content_type: ['audio/mp3'] }

If this still doesn't work you can try this:

{ content_type: ['audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio'] }


问:
Twitter text retrieval with new 280 character system
Using Google Scripts, I have a program that retrieves the text from one account's tweets and uses it for various other things. It's been running for over a year with minimal issues, but now the tweets are being adjusted to 280 characters and I can't retrieve the second half of the tweet. I have:

```<code> function refreshing_v2() {

  var service = getTwitterService();
  if (service.hasAccess()) {

var url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=(redacted)&count=1&include_rts=0&exclude_replies=1';

var response = service.fetch(url);
var tweets = JSON.parse(response.getContentText());
for (var i = 0; i < tweets.length; i++) {

  //Parse the tweet
  var latest = new String(tweets[i].text);
  var maxi_id = tweets[i].id;
  var startpos = latest.indexOf("1: ");
</code>```

etc, etc, continues doing stuff with what it's found.

This allows me to get the FIRST half of the text. What's retrieved looks something like "[Content of first half]...(link to tweet)"

How do I get the full text?

答:
You need to add tweet_mode=extended to get the full text in the response. You may need to check the entities you receive to see if it is what you are expecting.

Documentation link - https://developer.twitter.com/en/docs/tweets/tweet-updates

Additionally, you will need to use full_text rather than just text

So:

```<code>//Parse the tweet
var latest = new String(tweets[i].full_text);
</code>```

See the sample tweet at https://github.com/twitterdev/tweet-updates/blob/master/samples/initial/compatibilityplus_extended_13997.json

Body:
Using Google Scripts, I have a program that retrieves the text from one account's tweets and uses it for various other things. It's been running for over a year with minimal issues, but now the tweets are being adjusted to 280 characters and I can't retrieve the second half of the tweet. I have:

 function refreshing_v2() {

  var service = getTwitterService();
  if (service.hasAccess()) {

var url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=(redacted)&count=1&include_rts=0&exclude_replies=1';

var response = service.fetch(url);
var tweets = JSON.parse(response.getContentText());
for (var i = 0; i < tweets.length; i++) {

  //Parse the tweet
  var latest = new String(tweets[i].text);
  var maxi_id = tweets[i].id;
  var startpos = latest.indexOf("1: ");

etc, etc, continues doing stuff with what it's found.

This allows me to get the FIRST half of the text. What's retrieved looks something like "[Content of first half]...(link to tweet)"

How do I get the full text?

Body:
You need to add tweet_mode=extended to get the full text in the response. You may need to check the entities you receive to see if it is what you are expecting.

Documentation link - https://developer.twitter.com/en/docs/tweets/tweet-updates

Additionally, you will need to use full_text rather than just text

So:

//Parse the tweet
var latest = new String(tweets[i].full_text);

See the sample tweet at https://github.com/twitterdev/tweet-updates/blob/master/samples/initial/compatibilityplus_extended_13997.json


问:
How to change working directory in Jupyter Notebook?
I couldn't find a place for me to change the working directory in Jupyter Notebook, so I couldn't use the pd.read_csv method to read in a specific csv document.

Is there any way to make it? FYI, I'm using Python3.5.1 currently.

Thanks!

答:
First you need to create the config file, using cmd :
jupyter notebook --generate-config
Then, search for C:\Users\your_username\.jupyter folder (Search for that folder), and right click edit the jupyter_notebook_config.py.

Then, Ctrl+F: #c.NotebookApp.notebook_dir ='' . Note that the quotes are single quotes. Select your directory you want to have as home for your jupyter, and copy it with Ctrl+C, for example: C:\Users\username\Python Projects.

Then on that line, paste it like this : c.NotebookApp.notebook_dir = 'C:\\Users\\username\\Python Projects'

Make sure to remove #, as it is as comment.

Make sure to double slash \\ on each name of your path.
Ctrl+S to save the config.py file !!!

Go back to your cmd and run jupyter notebook. It should be in your directory of choice. Test it by making a folder and watch your directory from your computer.

ContentLicense: CC BY-SA 4.0


问:
Laravel (5.2) Blade - How to prevent a Blade Directive in an email address from being parsed?
Update This is a bug in Laravel 5.2 & 5.3

I've got a weird one here. A user's email address on our client's system has a domain with the following substring in it '@parent'. I am not including the whole thing just for the sake of privacy.

Because @parent is a Blade directive, Laravel seems to either process or ignore the @parent and strips it out of the rendered email address on the page.

For example, let's say the email address is john@parentstuff.com. Laravel will render the following on the page: johnstuff.com. See how it removes @parent from the email?

What I've tried to fix it:

```<code>1. {!! $user->email !!}

2. {{ e($user->email) }}
</code>```

I know that this is an issue with Blade as AJAX & jQuery rendered content with this same email address is displayed just fine elsewhere on the site.

UPDATE

Upon further investigation, it appears this may be a bug in how Blade processes the @parent directive. I set up 3 new Laravel projects for the following versions: 5.2, 5.3 and 5.4. The project in question is a Laravel 5.2 project, FYI.

I created the following setup for each of the above mentioned versions to test the bug.

Route

```<code>Route::get('/test', function () {
    $foo = 'john@parentingstuff.org';

    return view('test')->with('foo', $foo);
});
</code>```

Templates

Base

```<code><html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>
</code>```

Test View

```<code>@extends('test-base')

@section('content')
    {{$foo}}
@endsection
</code>```

Outputs

L5.2: johningstuff.org

L5.3: johningstuff.org

L5.4: john@parentingstuff.org

Theories

One very interesting case I noticed while running these tests was that having the {{$foo}} variable inside of a @section directive vs moving it outside of the @section directive led to two different outputs.

Example

```<code>{{$foo}}

@section('content')
    {{$foo}}
@endsection
</code>```

The output of this was...

john@parentingstuff.org

johningstuff.org

Conclusion
So, does anyone know how to patch this bug in Laravel 5.2 or Laravel 5.3? Currently, upgrading to L5.4 is not an option for our client.

Anyone have any clever tricks they can think of that might help?

答:
I believe the problem is elsewhere. You are doing probably something more than you wrote.

Sample controller method content

```<code>return view('test', ['email' => 'john@parentstuff.com'];
</code>```

Sample view:

```<code>Email is: {{ $email }}
</code>```

Result is:

```<code>Email is: john@parentstuff.com
</code>```

so I believe you are doing something more than you wrote.

Body:
Update This is a bug in Laravel 5.2 & 5.3

I've got a weird one here. A user's email address on our client's system has a domain with the following substring in it '@parent'. I am not including the whole thing just for the sake of privacy.

Because @parent is a Blade directive, Laravel seems to either process or ignore the @parent and strips it out of the rendered email address on the page.

For example, let's say the email address is john@parentstuff.com. Laravel will render the following on the page: johnstuff.com. See how it removes @parent from the email?

What I've tried to fix it:

1. {!! $user->email !!}

2. {{ e($user->email) }}

I know that this is an issue with Blade as AJAX & jQuery rendered content with this same email address is displayed just fine elsewhere on the site.

UPDATE

Upon further investigation, it appears this may be a bug in how Blade processes the @parent directive. I set up 3 new Laravel projects for the following versions: 5.2, 5.3 and 5.4. The project in question is a Laravel 5.2 project, FYI.

I created the following setup for each of the above mentioned versions to test the bug.

Route

Route::get('/test', function () {
    $foo = 'john@parentingstuff.org';

    return view('test')->with('foo', $foo);
});

Templates

Base

        <title>App Name - @yield('title')</title>

            @yield('content')

Test View

@extends('test-base')

@section('content')
    {{$foo}}
@endsection

Outputs

L5.2: johningstuff.org

L5.3: johningstuff.org

L5.4: john@parentingstuff.org

Theories

One very interesting case I noticed while running these tests was that having the {{$foo}} variable inside of a @section directive vs moving it outside of the @section directive led to two different outputs.

Example

{{$foo}}

@section('content')
    {{$foo}}
@endsection

The output of this was...

john@parentingstuff.org

johningstuff.org

Conclusion
So, does anyone know how to patch this bug in Laravel 5.2 or Laravel 5.3? Currently, upgrading to L5.4 is not an option for our client.

Anyone have any clever tricks they can think of that might help?

Body:
I believe the problem is elsewhere. You are doing probably something more than you wrote.

Sample controller method content

return view('test', ['email' => 'john@parentstuff.com'];

Sample view:

Email is: {{ $email }}

Result is:

Email is: john@parentstuff.com

so I believe you are doing something more than you wrote.


问:
Compare DATETIME and DATE ignoring time portion
I have two tables where column [date] is type of DATETIME2(0).

I have to compare two records only by theirs Date parts (day+month+year), discarding Time parts (hours+minutes+seconds).

How can I do that?

答:
You can try this one

```<code>CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000')
</code>```

I test that for MS SQL 2014 by following code

```<code>select case when CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000') then 'ok'
            else '' end
</code>```

Body:
You can try this one

CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000')

I test that for MS SQL 2014 by following code

select case when CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000') then 'ok'
            else '' end


问:
Clicking on Unity Build and release Does nothing! Weird
So I was following this tutorial https://www.youtube.com/watch?v=khavGQ7Dy3c until 8.28 and until then everything was ok. I checked the project working on my mac camera. However after setting my bundle identifier (i have apple dev id and all certificates are loaded in my keychain so no worries), i click Build and Run, it asks to provide me location, I make a folder and then nothing happens. The folder is made, but no xcode project inside. I tried 2/3 times but same.</p>

答: sorry guys...i got the answer. i was signed inside with a student limited access acount...also i did not provide camera description neede to open the ios camera. I made a new account in unity, signed in via studio, and puff..all error were fixed.</p>


问:
REGEX to get ID ath the end of an URL without /
I'm trying to do a GreaseMonkey script and i'm stucked on a REGEX to get the ID of an article in URL.

I have URL like https://www.blabla.com/poney-2000-poneys-dance-bla,272317

And i want to use the ID at the end after the Comma : 272317

I tried this REGEX : (,([\d]+)) to avoid taking digit in the rest of the URL and it get me ,272317 but I want it without the comma at the begining.

Do you have an idea how i can improve my REGEX ?

Thanks a lot :)

答:
An alternative approach without regex:

```<code>var url = 'https://www.blabla.com/poney-2000-poneys-dance-bla,272317';
url.substring(url.lastIndexOf(',') + 1);
</code>```

The regex would be (\d+)$ to lookup the digits in the end but it doesn't consider the comma.

Body:
An alternative approach without regex:

var url = 'https://www.blabla.com/poney-2000-poneys-dance-bla,272317';
url.substring(url.lastIndexOf(',') + 1);

The regex would be (\d+)$ to lookup the digits in the end but it doesn't consider the comma.


问:
Finishing File Class
I keep getting an error telling me lineNumber cannot be resolved to a variable? I'm not really sure how to fix this exactly. Am I not importing a certain file to java that helps with this?

And also how would I count the number of chars with spaces and without spaces.

Also I need a method to count unique words but I'm not really sure what unique words are.

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;

public class LineWordChar {
public void main(String[] args) throws IOException {
    // Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";

// while next lines are present in file int linesi will add 1
    while ((lines=bf.readLine())!=null){
    linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
 while (st.hasMoreTokens()){
    s = st.nextToken();
      words++;
// We take every word during separation and count number of char in this words
      for (int i = 0; i < s.length(); i++) {
          chars++;}
    }
 System.out.println("Number of lines: "+linesi);
 System.out.println("Number of words: "+words);
 System.out.print("Number of chars: "+chars);
}
}
 abstract class WordCount {

/**
 * @return HashMap a map containing the Character count, Word count and
 *         Sentence count
 * @throws FileNotFoundException
 *
 */
public static void main() throws FileNotFoundException {
    lineNumber=2; // as u want
    File f = null;
    ArrayList<Integer> list=new ArrayList<Integer>();

    f = new File("file_stats.txt");
    Scanner sc = new Scanner(f);
    int totalLines=0;
    int totalWords=0;
    int totalChars=0;
    int totalSentences=0;
    while(sc.hasNextLine())
    {
        totalLines++;
        if(totalLines==lineNumber){
            String line = sc.nextLine();
            totalChars += line.length();
            totalWords += new StringTokenizer(line, " ,").countTokens();  //line.split("\\s").length;
            totalSentences += line.split("\\.").length;
            break;
        }
        sc.nextLine();

    }

    list.add(totalChars);
    list.add(totalWords);
    list.add(totalSentences);
    System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);

}
}
</code>```

答:
In order to get your code running you have to do at least two changes:

Replace:

```<code>lineNumber=2; // as u want
</code>```

with

```<code>int lineNumber=2; // as u want
</code>```

Also, you need to modify your main method, you can not throw an exception in your main method declaration because there is nothing above it to catch the exception, you have to handle exceptions inside it:

```<code>public static void main(String[] args) {
        // Convert our text file to string
        try {
            String text = new Scanner(new File("way to your file"), "UTF-8").useDelimiter("\\A").next();
            BufferedReader bf = new BufferedReader(new FileReader("way to your file"));
            String lines = "";
            int linesi = 0;
            int words = 0;
            int chars = 0;
            String s = "";

            // while next lines are present in file int linesi will add 1
            while ((lines = bf.readLine()) != null) {
                linesi++;
            }
            // Tokenizer separate our big string "Text" to little string and count them
            StringTokenizer st = new StringTokenizer(text);
            while (st.hasMoreTokens()) {
                s = st.nextToken();
                words++;
                // We take every word during separation and count number of char in this words
                for (int i = 0; i < s.length(); i++) {
                    chars++;
                }
            }
            System.out.println("Number of lines: " + linesi);
            System.out.println("Number of words: " + words);
            System.out.print("Number of chars: " + chars);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

I've used a global Exception catch, you can separate expetion in several catches, in order to handle them separatedly. It gives me an exception telling me an obvious FileNotFoundException, besides of that your code runs now.

Title: Finishing File Class

Body:
I keep getting an error telling me lineNumber cannot be resolved to a variable? I'm not really sure how to fix this exactly. Am I not importing a certain file to java that helps with this?

And also how would I count the number of chars with spaces and without spaces.

Also I need a method to count unique words but I'm not really sure what unique words are.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.List;

public class LineWordChar {
public void main(String[] args) throws IOException {
    // Convert our text file to string
String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
String lines="";
int linesi=0;
int words=0;
int chars=0;
String s="";

// while next lines are present in file int linesi will add 1
    while ((lines=bf.readLine())!=null){
    linesi++;}
// Tokenizer separate our big string "Text" to little string and count them
StringTokenizer st=new StringTokenizer(text);
 while (st.hasMoreTokens()){
    s = st.nextToken();
      words++;
// We take every word during separation and count number of char in this words
      for (int i = 0; i < s.length(); i++) {
          chars++;}
    }
 System.out.println("Number of lines: "+linesi);
 System.out.println("Number of words: "+words);
 System.out.print("Number of chars: "+chars);
}
}
 abstract class WordCount {

/**
 * @return HashMap a map containing the Character count, Word count and
 *         Sentence count
 * @throws FileNotFoundException
 *
 */
public static void main() throws FileNotFoundException {
    lineNumber=2; // as u want
    File f = null;
    ArrayList<Integer> list=new ArrayList<Integer>();

    f = new File("file_stats.txt");
    Scanner sc = new Scanner(f);
    int totalLines=0;
    int totalWords=0;
    int totalChars=0;
    int totalSentences=0;
    while(sc.hasNextLine())
    {
        totalLines++;
        if(totalLines==lineNumber){
            String line = sc.nextLine();
            totalChars += line.length();
            totalWords += new StringTokenizer(line, " ,").countTokens();  //line.split("\\s").length;
            totalSentences += line.split("\\.").length;
            break;
        }
        sc.nextLine();

    }

    list.add(totalChars);
    list.add(totalWords);
    list.add(totalSentences);
    System.out.println(lineNumber+";"+totalWords+";"+totalChars+";"+totalSentences);

}
}

Body:
In order to get your code running you have to do at least two changes:

Replace:

lineNumber=2; // as u want

with

int lineNumber=2; // as u want

Also, you need to modify your main method, you can not throw an exception in your main method declaration because there is nothing above it to catch the exception, you have to handle exceptions inside it:

public static void main(String[] args) {
        // Convert our text file to string
        try {
            String text = new Scanner(new File("way to your file"), "UTF-8").useDelimiter("\\A").next();
            BufferedReader bf = new BufferedReader(new FileReader("way to your file"));
            String lines = "";
            int linesi = 0;
            int words = 0;
            int chars = 0;
            String s = "";

            // while next lines are present in file int linesi will add 1
            while ((lines = bf.readLine()) != null) {
                linesi++;
            }
            // Tokenizer separate our big string "Text" to little string and count them
            StringTokenizer st = new StringTokenizer(text);
            while (st.hasMoreTokens()) {
                s = st.nextToken();
                words++;
                // We take every word during separation and count number of char in this words
                for (int i = 0; i < s.length(); i++) {
                    chars++;
                }
            }
            System.out.println("Number of lines: " + linesi);
            System.out.println("Number of words: " + words);
            System.out.print("Number of chars: " + chars);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I've used a global Exception catch, you can separate expetion in several catches, in order to handle them separatedly. It gives me an exception telling me an obvious FileNotFoundException, besides of that your code runs now.


答:
Something very screwy is going on in your setup, because that shouldn't be possible. Laravel processes Blade instructions before interpreting any variables.

I tested with a very simple example:

```<code>Route::get('test', function() {
    $foo = 'john@parentstuff.com';

    return view('test')->with('foo', $foo);
});
</code>```

and a Blade template of:

```<code>{{ $foo }}
</code>```

and it works just fine. @parent is not interpreted.

Title: Laravel (5.2) Blade - How to prevent a Blade Directive in an email address from being parsed?

Body:
Something very screwy is going on in your setup, because that shouldn't be possible. Laravel processes Blade instructions before interpreting any variables.

I tested with a very simple example:

Route::get('test', function() {
    $foo = 'john@parentstuff.com';

    return view('test')->with('foo', $foo);
});

and a Blade template of:

{{ $foo }}

and it works just fine. @parent is not interpreted.


问:
Why isn't the variable and its content visible in HTML
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

```<code>var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(agetest)</script>,</span> to THE SESH</h3>
</code>```

No dice

```<code>var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(age)</script>,</span> to THE SESH</h3>
</code>```

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

```<code><div id="overlay">
<div id="text">Are you over 18 years old?</div>
<div id="off"><button onclick="off(), ageinyear()">Submit</button></div>
<div id="test"><form>
    <label>
        Name
        <input id="name" name="lblname" type="text" />
    </label>
    <label>
        Age
        <input id="year" name="lblyear" type="text" />
    </label>
</form>
</div>
</code>```

答:
By prefixing the variable age with the var keyword the variable is declared only in the scope of the

    Welcome <script> document.write(age)</script>, to THE SESH

```

Body:
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

    Welcome , to THE SESH

No dice

var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

    Welcome , to THE SESH

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

Are you over 18 years old?

<button onclick="off(), ageinyear()">Submit</button>

<form>

        Name
        <input id="name" name="lblname" type="text" />

        Age
        <input id="year" name="lblyear" type="text" />

</form>

Body:
By prefixing the variable age with the var keyword the variable is declared only in the scope of the <script> element which contains it. To get what you have to work then you could declare the variable in the global scope by removing the var keyword.

<script>
    age ={}; // declare the variable in the global scope - can access it anywhere
    function ageinyear() {
        age = document.getElementById("year").value;
    }
</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(age)</script>,</span> to THE SESH
</h3>


问:
Jenkins with kubernetes on GKE
I'm new to kubernetes in combination with jenkins. Therefor I've done some tutorials.

My goal is:
1) build docker images
2) push docker images to GCR
3) deploy image in kubernetes

I've setup my GKE 1:1 like the tutorial.
https://cloud.google.com/solutions/continuous-delivery-jenkins-container-engine
Also did these tutorials:
"jenkins-on-container-engine-tutorial"
"configuring-jenkins-container-engine"

Since these tutorials are depending on each other I've done them multiple times completely from scratch to avoid errors from my side.

The issue is the build agent can't find the docker command!
I've also tried some custom images like in this thread:
Easiest way to do docker build command within Jenkinsfile running on Jenkins slave node?

But nothing seems to work :(

答:
I'm running on GKE, so I also needed the gcloud cli which also provides docker commands.

So here are the steps:
1) create custom Jenkins image with gcloud cli installed
2) Be sure to enable the scope "cloud plattform"
3) use gcloud docker  command :)

Title: Jenkins with kubernetes on GKE


答:
Check your strong parameters. Your error tells you that something is wrong before you get to validation: :name =>[{:error=>:too_short, :count=>1}] This is saying that the minimum string count is 1 but that your string is not even that long. Here is the docs on that.

You can try: Account.find(1).update_attributes({:name => "king", :amount => "1223"} to see if @account is not being set properly.

You can also customize the language on your errors to help further:

```<code>validates_length_of : name, within: 1..255, too_long: 'pick a shorter name', too_short: 'pick a longer name'
</code>```

Title: update_attributes validation fails though values are correct

Body:
I have in my model

class Account < ActiveRecord::Base
 validates_length_of :amount, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.amount.blank? }
 validates_length_of :name, :in 1..255, :on => update, :if => Proc.new { |a| false if a.id == nil;a.name.blank? }, :unless => user_has_amount?

end

when I comment out the if condition, it works fine but with them validation fails which is confusing. I know that the validation should only run if the proc returns true or unless returns false
in my controller I have

@account.update_attributes({:name => "king", :amount => "1223"}

the save fails and when I check errors I get

@account.errors.details
{:name =>[{:error=>:too_short, :count=>1}], :amount =>[{:error=>:too_short, :count=>1}]}

Strong Params are not an issue because I have
     def self.params
          params.require(:account).permit!
     end

I have no idea why it fails though the value are present and correct.

Body:
Check your strong parameters. Your error tells you that something is wrong before you get to validation: :name =>[{:error=>:too_short, :count=>1}] This is saying that the minimum string count is 1 but that your string is not even that long. Here is the docs on that.

You can try: Account.find(1).update_attributes({:name => "king", :amount => "1223"} to see if @account is not being set properly.

You can also customize the language on your errors to help further:

validates_length_of : name, within: 1..255, too_long: 'pick a shorter name', too_short: 'pick a longer name'


问:
Perl, Alias sub to variable
I'm currently doing micro-optimization of a perl program and like to optimize some getters.

I have a package with this getter-structure:

```<code>package Test;

our $ABC;

sub GetABC { $ABC } # exported sub...
</code>```

Calling GetABC() creates a lot of sub-related overhead. Accessing the variable directly via $Test::ABC is insanely faster.

Is there a way to alias the getter to the variable to gain the same performanceboost as if I would call the variable directly? Inlining hint with "()" doesn seem to work...

答:
There is no way to turn a variable into an accessor sub, or to replace a sub with a variable access. You will have to live with the overhead.

Non-solutions:

Using a () prototype does not turn calls into your sub to constant accesses because that prototype merely makes a sub potentially eligible for inlining. Since the body of the sub is not itself constant, this sub cannot be a constant.

The overhead is per-call as perl has to do considerable bookkeeping for each call. Therefore, rewriting that accessor in XS won't help much.

Creating a constant won't help because the constant will be a copy, not an  alias of your variable.

But looking at the constant.pm source code seems to open up an interesting solution. Note that this a hack, and may not work in all versions of Perl: When we assign a scalar ref to a symbol table entry directly where that entry does not yet contain a typeglob, then an inlineable sub springs into place:

```<code>package Foo;
use strict;
use warnings;
use feature 'say';

my $x = 7;
BEGIN { $Foo::{GetX} = \$x }  # don't try this at home
say GetX; #=> 7
$x = 3;
say GetX; #=> 3
</code>```

This currently works on most of my installed perl versions (5.14, 5.22, 5.24, 5.26). However, my 5.22-multi and 5.26-multi die with “Modification of a read-only value attempted”. This is not a problem for the constant module since it makes the reference target readonly first and (more importantly) never modifies that variable.

So not only doesn't this work reliably, this will also completely mess up constant folding.

If the function call overhead is indeed unbearable (e.g. takes a double-digit percentage of your processing time), then doing the inlining yourself in the source code is going to be your best bet. Even if you have a lot of call locations, you can probably create a simple script that fixes the easy cases for you: select all files that import your module and only have a single package declaration. Within such files, replace calls to GetABC (with or without parens) to fully qualified variable accesses. Hopefully that token is not mentioned within any strings. Afterwards, you can manually inspect the few remaining occurrences of these calls.

Title: Perl, Alias sub to variable

Body:
I'm currently doing micro-optimization of a perl program and like to optimize some getters.

I have a package with this getter-structure:

package Test;

our $ABC;

sub GetABC { $ABC } # exported sub...

Calling GetABC() creates a lot of sub-related overhead. Accessing the variable directly via $Test::ABC is insanely faster.

Is there a way to alias the getter to the variable to gain the same performanceboost as if I would call the variable directly? Inlining hint with "()" doesn seem to work...

Body:
There is no way to turn a variable into an accessor sub, or to replace a sub with a variable access. You will have to live with the overhead.

Non-solutions:

Using a () prototype does not turn calls into your sub to constant accesses because that prototype merely makes a sub potentially eligible for inlining. Since the body of the sub is not itself constant, this sub cannot be a constant.

The overhead is per-call as perl has to do considerable bookkeeping for each call. Therefore, rewriting that accessor in XS won't help much.

Creating a constant won't help because the constant will be a copy, not an  alias of your variable.

But looking at the constant.pm source code seems to open up an interesting solution. Note that this a hack, and may not work in all versions of Perl: When we assign a scalar ref to a symbol table entry directly where that entry does not yet contain a typeglob, then an inlineable sub springs into place:

package Foo;
use strict;
use warnings;
use feature 'say';

my $x = 7;
BEGIN { $Foo::{GetX} = \$x }  # don't try this at home
say GetX; #=> 7
$x = 3;
say GetX; #=> 3

This currently works on most of my installed perl versions (5.14, 5.22, 5.24, 5.26). However, my 5.22-multi and 5.26-multi die with “Modification of a read-only value attempted”. This is not a problem for the constant module since it makes the reference target readonly first and (more importantly) never modifies that variable.

So not only doesn't this work reliably, this will also completely mess up constant folding.

If the function call overhead is indeed unbearable (e.g. takes a double-digit percentage of your processing time), then doing the inlining yourself in the source code is going to be your best bet. Even if you have a lot of call locations, you can probably create a simple script that fixes the easy cases for you: select all files that import your module and only have a single package declaration. Within such files, replace calls to GetABC (with or without parens) to fully qualified variable accesses. Hopefully that token is not mentioned within any strings. Afterwards, you can manually inspect the few remaining occurrences of these calls.


问:
vim ruby mismatch on Mac High Sierra
I recently upgraded my Mac to High Sierra

After the upgrade, Macvim (mvim) stopped working because (I assume) HighSierra upgraded ruby to 2.3, and mvim is using ruby 2.0.

Following is the error I am getting

dyld: Library not loaded:
  /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/libruby.2.0.0.dylib

Referenced from: /usr/local/Cellar/macvim/8.0-134/MacVim.app/Contents/bin/../MacOS/Vim

Do I need to compile vim again or is there any way to fix this problem?

Thanks in advance.

答: Tried to use brew upgrade macvim an error was raised and the failed. What worked for me is to open the MacVim in a normal window (not a iTerm or terminal) the graphic version noticed that a newer version is available and asked if I want to update. Clicked yes, please and done. macvim in terminal or iTerm works just fine (as well as the "window" version).

Title: vim ruby mismatch on Mac High Sierra


问:
Highlight barChart xAxis data
I want to style some letters at xAxis from this barChart
https://bl.ocks.org/mbostock/3885304

I'm getting the value for x at this step

```<code>.attr("x", function(d) { return x(d.letter); })
</code>```

Can I add extra div at this step, something like:

```<code>.attr("x", function(d) {
    if (d.letter ==='A') svg.append('div').style('fill', 'red');
return x(d.letter); })
</code>```

Or should use another select, like?

```<code>~d3.select('svg').selectAll('xAxis')
</code>```

答:
For styling xAxis texts, this would be a better option:

```<code> d3.select('svg').select('g.axis.axis--x').selectAll('text')
        .style('fill', function(d) { if(d === 'A') return 'red'; });
</code>```

NOTE: .attr("x", function(d) { }) is for x position of the bar

Title: Highlight barChart xAxis data

Body:
I want to style some letters at xAxis from this barChart
https://bl.ocks.org/mbostock/3885304

I'm getting the value for x at this step

.attr("x", function(d) { return x(d.letter); })

Can I add extra div at this step, something like:

.attr("x", function(d) {
    if (d.letter ==='A') svg.append('div').style('fill', 'red');
return x(d.letter); })

Or should use another select, like?

~d3.select('svg').selectAll('xAxis')

Body:
For styling xAxis texts, this would be a better option:

 d3.select('svg').select('g.axis.axis--x').selectAll('text')
        .style('fill', function(d) { if(d === 'A') return 'red'; });

NOTE: .attr("x", function(d) { }) is for x position of the bar


问:
zend framework join 3 tables
I have 3 tables (order, product, order_item). In order i have the date. In order_item i have product_id and order_id. I need to select all products with orders, what created in the current month. It is my select:

```<code>$select = $this->select()
    ->setIntegrityCheck(false)
    ->from(array('o' => 'order'))
    ->join(array('oi' => 'order_item'), 'o.id = oi.order_id', array('quantity'))
        ->joinLeft(array('p' => 'product'), 'p.id = oi.product_id', array('id', 'pbv', 'name'))
        ->where('MONTH(o.date) = MONTH(CURDATE())');
</code>```

But when i haven't orders result is empty. And i should always have all products. Sorry for my english. Thanks.

答: You need to either switch your joinLeft to a joinRight, or put your product table first in the query.</p>

ContentLicense: CC BY-SA 2.5

Title: zend framework join 3 tables

Body:
I have 3 tables (order, product, order_item). In order i have the date. In order_item i have product_id and order_id. I need to select all products with orders, what created in the current month. It is my select:

$select = $this->select()
    ->setIntegrityCheck(false)
    ->from(array('o' => 'order'))
    ->join(array('oi' => 'order_item'), 'o.id = oi.order_id', array('quantity'))
        ->joinLeft(array('p' => 'product'), 'p.id = oi.product_id', array('id', 'pbv', 'name'))
        ->where('MONTH(o.date) = MONTH(CURDATE())');

But when i haven't orders result is empty. And i should always have all products. Sorry for my english. Thanks.


问:
unable to view PDF after uploading to s3. uploading images works fine (NodeJS)
I've been using aws-sdk to upload images for quite some time now with no issue but have just recently needed to upload a pdf. I thought I could use the same functionality

It looks like I get a successful response when uploading but when I try to open the PDF I get Failed to load PDF document.

I've tried using putObject instead of uploadObject with no luck.

Here is the code I'm using currently

```<code>var deferred = q.defer();
var s3 = new AWS.S3();
var buf = new Buffer( file.replace( /^data:image\/\w+;base64,/, '' ), 'base64' );
var params = {
    Bucket: config.bucket,
    Key: config.environment + '/' + fileName,
    ContentType: fileType,
    Body: buf
};

s3.upload( params, function( err, data ) {
    err ? console.log( err ) : console.log( data );
    deferred.resolve( data );
} );
return deferred.promise;
</code>```

答:
Aha!

So i was stripping the mime type from my data on line 3 so that ONLY the file data remained BUT pdf files don't have a mime type that start with image so it wasn't getting picked up by my regex. Its actually application/pdf

I found a better way of doing this removes mime type regardless of file type. Replace line three with:

```<code>var fileWithoutMimeType = file.match( /,(.*)$/ )[ 1 ];
var buf = new Buffer( fileWithoutMimeType, 'base64' );
</code>```

Body:
I've been using aws-sdk to upload images for quite some time now with no issue but have just recently needed to upload a pdf. I thought I could use the same functionality

It looks like I get a successful response when uploading but when I try to open the PDF I get Failed to load PDF document.

I've tried using putObject instead of uploadObject with no luck.

Here is the code I'm using currently

var deferred = q.defer();
var s3 = new AWS.S3();
var buf = new Buffer( file.replace( /^data:image\/\w+;base64,/, '' ), 'base64' );
var params = {
    Bucket: config.bucket,
    Key: config.environment + '/' + fileName,
    ContentType: fileType,
    Body: buf
};

s3.upload( params, function( err, data ) {
    err ? console.log( err ) : console.log( data );
    deferred.resolve( data );
} );
return deferred.promise;

Body:
Aha!

So i was stripping the mime type from my data on line 3 so that ONLY the file data remained BUT pdf files don't have a mime type that start with image so it wasn't getting picked up by my regex. Its actually application/pdf

I found a better way of doing this removes mime type regardless of file type. Replace line three with:

var fileWithoutMimeType = file.match( /,(.*)$/ )[ 1 ];
var buf = new Buffer( fileWithoutMimeType, 'base64' );


问:
Delphi multiline regex
I have some non-regression test code in Delphi that calls an external diff tool. Then my code loads the diff results and should remove acceptable differences, such as dates in the compared results. I'm trying to do this with a multiline TRegEx.Replace , but no match is found ...

https://regex101.com/r/QBZuws/2 shows the pattern I came up with and a sample test diff file. I need to delete the matching "pararaphs" of 3 lines

Here is my code :

```<code>function FilterDiff(AText:string):string;
var
  LStr:string;
  Regex: TRegEx;
begin
  // AText:=StringReplace(AText,#13+#10,'\n',[rfReplaceAll]); // doesn't help ...
  LStr := '\d\d.\d\d.20\d\d \d\d:\d\d:\d\d'; // regex for date and time
  LStr := '@@.*@@\n-'+LStr+'\n\+'+LStr; // regex for paragraphs to remove
  Regex := TRegEx.Create(LStr, [roMultiLine]);
  Result := Regex.Replace(AText,'');
end;

procedure TReportTest.NonRegression;
var
  LDiff : TStringList;
  // others removed for clarity
begin
  // removed section code that call an external tool and produces diff.txt file
  LDiff := TStringList.Create;
  LDiff.LoadFromFile('diff.txt');
  Status(FilterDiff(LDiff.Text)); // show the diffs in DUnit GUI for now
  LDiff.Free;
end;
</code>```

Besides, while tracing TRegEx.Replace down to

```<code>System.RegularExpressionsAPI.pcre_exec($4D72A50,nil,'--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A,132,0,1024,$7D56800,300)
System.RegularExpressionsCore.TPerlRegEx.Match
System.RegularExpressionsCore.TPerlRegEx.ReplaceAll
System.RegularExpressions.TRegEx.Replace(???,???)
TestReportAuto.FilterDiff('--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A)
</code>```

I was surprised to see quotes before and after each newline #$D#$A in the debugger, but they don't look "real" ... or are they ?

答: As you seem to have issues with different kinds of line breaks, I would recommend to adjust your Regex to use \R instead of \n which matches Windows style linebreaks (CR + LF) as well as Unix style linebreaks (LF).

Title: Delphi multiline regex

Body:
I have some non-regression test code in Delphi that calls an external diff tool. Then my code loads the diff results and should remove acceptable differences, such as dates in the compared results. I'm trying to do this with a multiline TRegEx.Replace , but no match is found ...

https://regex101.com/r/QBZuws/2 shows the pattern I came up with and a sample test diff file. I need to delete the matching "pararaphs" of 3 lines

Here is my code :

function FilterDiff(AText:string):string;
var
  LStr:string;
  Regex: TRegEx;
begin
  // AText:=StringReplace(AText,#13+#10,'\n',[rfReplaceAll]); // doesn't help ...
  LStr := '\d\d.\d\d.20\d\d \d\d:\d\d:\d\d'; // regex for date and time
  LStr := '@@.*@@\n-'+LStr+'\n\+'+LStr; // regex for paragraphs to remove
  Regex := TRegEx.Create(LStr, [roMultiLine]);
  Result := Regex.Replace(AText,'');
end;

procedure TReportTest.NonRegression;
var
  LDiff : TStringList;
  // others removed for clarity
begin
  // removed section code that call an external tool and produces diff.txt file
  LDiff := TStringList.Create;
  LDiff.LoadFromFile('diff.txt');
  Status(FilterDiff(LDiff.Text)); // show the diffs in DUnit GUI for now
  LDiff.Free;
end;

Besides, while tracing TRegEx.Replace down to

System.RegularExpressionsAPI.pcre_exec($4D72A50,nil,'--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A,132,0,1024,$7D56800,300)
System.RegularExpressionsCore.TPerlRegEx.Match
System.RegularExpressionsCore.TPerlRegEx.ReplaceAll
System.RegularExpressions.TRegEx.Replace(???,???)
TestReportAuto.FilterDiff('--- '#$D#$A'+++ '#$D#$A'@@ -86 +86 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A'@@ -400 +400 @@'#$D#$A'-16.11.2017 15:00:36'#$D#$A'+15.11.2017 10:47:58'#$D#$A)

I was surprised to see quotes before and after each newline #$D#$A in the debugger, but they don't look "real" ... or are they ?


问:
Laravel external(from another domain) api request to check if the user is logged in a server (main server)
How can I make a logged-in-check via an external call (external domain) to a main server? Should be a js client-server call.

In other words domain1.com makes a client-server call to the main-domain.com to check if the user is already logged-in in main-domain.com

答:
There are two ways you can:

Use simply api token authentication on main domain.

Setup OAuth on main domain.


问:
Safest way to update game score from client to server database? Javascript
So I have this game that is completely run on the client. No server interaction what so ever apart from downloading the initial scripts to play the game. Anyway at the end of the game I would like for the client to send me back the scores which should be updated in the server database. Now I have come to accept the fact that there is no way on earth I can hide this from a hacker and send the scores unaltered. But I would like to know till what level can I modify the whole process that it virtually becomes pretty infeasible for the hacker manipulate the data which is being sent. For sure I would not like the score to be sent as plain text from client machine and I don't want my server to perform complex decryption algorithm. What is the best way hence to achieve considerable amount of security that every tom dick and harry doesn't hack the scores... I hope someone could provide a nice little way that I could work on... :) Thanks

So my ideal result should be -> have trusted result from a calculation (of score) made by an untrusted party (the player)!

-Edit-

Someone told me something about hiding the data in a picture get request. Like, I am implementing this game on canvas (html5). So he asked me at the end of the game to fetch a game over image from my server, and they request should contain the hashed score. I did not exactly understand the complete process but if you could explain it, would be really glad! :)

coda^   so you can mask the requests nicely

shouvik how do I do it!?

coda^   you can compose the checksum you want to submit. like 12312312a12313a232 is your md5 which contains the score. bring in an asset into the canvas like

coda^   server.com/images/md5_hash_of_score/congratulations.png

coda^   which you can rewrite server side via htaccess

答:
Can you use ajax to send the score (and any identifiers) to the server? Unless they have something like firebug open they won't see it happening.</p>

```<code>var url = '/savescores.asp?userID=fredsmith&score=1098';
createRequest();
request.open('GET', url, true);
etc
</code>```

Body:
Can you use ajax to send the score (and any identifiers) to the server? Unless they have something like firebug open they won't see it happening.

var url = '/savescores.asp?userID=fredsmith&score=1098';
createRequest();
request.open('GET', url, true);
etc


问:
I need to extract some data using python from a html page
This is part of a html page from which i need to extract the following items:
name from the strong tag, classification type (Actor and Singer), born and died location.

```<code><li class="clearfix">
   <div style="margin-top:10px;">
      <div class="float-left" style="margin-bottom:10px;">
         <a href="http://" title="Elvis Presley" name="Elvis Presley" class="float-left">
         <strong>Mr. Elvis Presley</strong></a>
      </div>
      <div class="rating_overall fleft" style="margin:0px 0px 0px 10px;">
         <div class="rating_overall voted_rating_overall" style='width:72.96px;'></div>
      </div>
      <span class="result-vote float-left" id="result" style="line-height:15px; color: #AAA; font-size: 0.9em; margin-top: 1px;">   (15 vots)</span>
      <div class="clear"></div>
      <a href="http://" title="Mr. Elvis Presley" name="Mr. Elvis Presley">
      <img style="float:left;" src="http://a.jpg" alt="Mr. Elvis Presley" title="Mr. Elvis Presley"  />
      </a>
      <br/>
      <p>
         <b>Classification:</b>
         <a href="http://" title="Actor " name="Actor " class="underline">Actor </a>
         ,                      <a href="" title="Singer" name="Singer" class="underline">Singer</a>
         <br />
         <b>Born:</b> <a href="http://" title="Tupelo" name="Tupelo" class="underline">Tupelo</a><br />
         <b>Died:</b>
         Memphis,
         <!--<b>City:</b>-->
         <a href="http://" title="Memphis" name="Memphis" class="underline">Memphis</a>
      </p>
      <div class="clk"></div>
   </div>
</li>
</code>```

I had try using the BeautifulSoup but i'm a newbie on python :

```<code>    data2 = soup.find_all('li',{'class':'clearfix'})

for container in data2:
    if container.find('a', {'class':'float-left'}):
        name = container.a.text
        print (name)

    if container.find('a', {'class':'underline'}):
        classification=container.div.p.a.text
        print (classification)

flag
</code>```

Although I didn't get any errors from the script, I managed to extract only the name and the first classification. How do I target the rest of the elements that I need: classification("Singer") and the born and died location?

答:
You can use beautiful soup for html parser , I am showing you both first with beautiful soup and second  with regex and catch the results with group capturing :

First with Beautiful soup:

```<code>string_1="""<li class="clearfix">
   <div style="margin-top:10px;">
      <div class="float-left" style="margin-bottom:10px;">
         <a href="http://" title="Elvis Presley" name="Elvis Presley" class="float-left">
         <strong>Mr. Elvis Presley</strong></a>
      </div>
      <div class="rating_overall fleft" style="margin:0px 0px 0px 10px;">
         <div class="rating_overall voted_rating_overall" style='width:72.96px;'></div>
      </div>
      <span class="result-vote float-left" id="result" style="line-height:15px; color: #AAA; font-size: 0.9em; margin-top: 1px;">   (15 vots)</span>
      <div class="clear"></div>
      <a href="http://" title="Mr. Elvis Presley" name="Mr. Elvis Presley">
      <img style="float:left;" src="http://a.jpg" alt="Mr. Elvis Presley" title="Mr. Elvis Presley"  />
      </a>
      <br/>
      <p>
         <b>Classification:</b>
         <a href="http://" title="Actor " name="Actor " class="underline">Actor </a>
         ,                      <a href="" title="Singer" name="Singer" class="underline">Singer</a>
         <br />
         <b>Born:</b> <a href="http://" title="Tupelo" name="Tupelo" class="underline">Tupelo</a><br />
         <b>Died:</b>
         Memphis,
         <!--<b>City:</b>-->
         <a href="http://" title="Memphis" name="Memphis" class="underline">Memphis</a>
      </p>
      <div class="clk"></div>
   </div>
</li>"""

from bs4 import BeautifulSoup
soup=BeautifulSoup(string_1,"html.parser")
for a in soup.find_all('a'):
    print(a['name'])
</code>```

Output:

```<code>Elvis Presley
Mr. Elvis Presley
Actor
Singer
Tupelo
Memphis
</code>```

Second with regex:

Use it if the form code is same as you shown there :

```<code>import re
string_1="""<li class="clearfix">
   <div style="margin-top:10px;">
      <div class="float-left" style="margin-bottom:10px;">
         <a href="http://" title="Elvis Presley" name="Elvis Presley" class="float-left">
         <strong>Mr. Elvis Presley</strong></a>
      </div>
      <div class="rating_overall fleft" style="margin:0px 0px 0px 10px;">
         <div class="rating_overall voted_rating_overall" style='width:72.96px;'></div>
      </div>
      <span class="result-vote float-left" id="result" style="line-height:15px; color: #AAA; font-size: 0.9em; margin-top: 1px;">   (15 vots)</span>
      <div class="clear"></div>
      <a href="http://" title="Mr. Elvis Presley" name="Mr. Elvis Presley">
      <img style="float:left;" src="http://a.jpg" alt="Mr. Elvis Presley" title="Mr. Elvis Presley"  />
      </a>
      <br/>
      <p>
         <b>Classification:</b>
         <a href="http://" title="Actor " name="Actor " class="underline">Actor </a>
         ,                      <a href="" title="Singer" name="Singer" class="underline">Singer</a>
         <br />
         <b>Born:</b> <a href="http://" title="Tupelo" name="Tupelo" class="underline">Tupelo</a><br />
         <b>Died:</b>
         Memphis,
         <!--<b>City:</b>-->
         <a href="http://" title="Memphis" name="Memphis" class="underline">Memphis</a>
      </p>
      <div class="clk"></div>
   </div>
</li>"""
pattern=r'<strong>(\w.+)<\/strong>|<b>Classification:<\/b>(\s.+)(\s.+)|(Born:.+)|(Died:.+\s.+\s.+\s.+)'
pattern_2=r'name=["](\w.+?)["]'

match=re.finditer(pattern,string_1,re.M)
for find in match:
    if find.group(1):
        print("Name {}".format(find.group(1)))
    if find.group(2):
        print("Classificiation first {}".format(re.search(pattern_2,str(find.group(2))).group(1)))
        print("Classification second {}".format(re.search(pattern_2,str(find.group(3))).group(1)))
    if find.group(4):
        print("Born {}".format(re.search(pattern_2, str(find.group(4))).group(1)))
    if find.group(5):
        print("Dead {}".format(re.search(pattern_2, str(find.group(5))).group(1)))
</code>```

output:

```<code>Name Mr. Elvis Presley
Classificiation first Actor
Classification second Singer
Born Tupelo
Dead Memphis
</code>```

Body:
This is part of a html page from which i need to extract the following items:
name from the strong tag, classification type (Actor and Singer), born and died location.

         Mr. Elvis Presley

         (15 vots)

         Classification:
         Actor
         ,                      Singer

         Born: Tupelo

         Died:
         Memphis,

         Memphis

I had try using the BeautifulSoup but i'm a newbie on python :

    data2 = soup.find_all('li',{'class':'clearfix'})

for container in data2:
    if container.find('a', {'class':'float-left'}):
        name = container.a.text
        print (name)

    if container.find('a', {'class':'underline'}):
        classification=container.div.p.a.text
        print (classification)

flag

Although I didn't get any errors from the script, I managed to extract only the name and the first classification. How do I target the rest of the elements that I need: classification("Singer") and the born and died location?

Body:
You can use beautiful soup for html parser , I am showing you both first with beautiful soup and second  with regex and catch the results with group capturing :

First with Beautiful soup:

string_1="""<li class="clearfix">
   <div style="margin-top:10px;">
      <div class="float-left" style="margin-bottom:10px;">
         <a href="http://" title="Elvis Presley" name="Elvis Presley" class="float-left">
         <strong>Mr. Elvis Presley</strong></a>
      </div>
      <div class="rating_overall fleft" style="margin:0px 0px 0px 10px;">
         <div class="rating_overall voted_rating_overall" style='width:72.96px;'></div>
      </div>
      <span class="result-vote float-left" id="result" style="line-height:15px; color: #AAA; font-size: 0.9em; margin-top: 1px;"> &nbsp; (15 vots)</span>
      <div class="clear"></div>
      <a href="http://" title="Mr. Elvis Presley" name="Mr. Elvis Presley">
      <img style="float:left;" src="http://a.jpg" alt="Mr. Elvis Presley" title="Mr. Elvis Presley"  />
      </a>
      <br/>
      <p>
         <b>Classification:</b>
         <a href="http://" title="Actor " name="Actor " class="underline">Actor </a>
         ,                      <a href="" title="Singer" name="Singer" class="underline">Singer</a>
         <br />
         <b>Born:</b> <a href="http://" title="Tupelo" name="Tupelo" class="underline">Tupelo</a><br />
         <b>Died:</b>
         Memphis,
         <!--<b>City:</b>-->
         <a href="http://" title="Memphis" name="Memphis" class="underline">Memphis</a>
      </p>
      <div class="clk"></div>
   </div>
</li>"""

from bs4 import BeautifulSoup
soup=BeautifulSoup(string_1,"html.parser")
for a in soup.find_all('a'):
    print(a['name'])

Output:

Elvis Presley
Mr. Elvis Presley
Actor
Singer
Tupelo
Memphis

Second with regex:

Use it if the form code is same as you shown there :

import re
string_1="""<li class="clearfix">
   <div style="margin-top:10px;">
      <div class="float-left" style="margin-bottom:10px;">
         <a href="http://" title="Elvis Presley" name="Elvis Presley" class="float-left">
         <strong>Mr. Elvis Presley</strong></a>
      </div>
      <div class="rating_overall fleft" style="margin:0px 0px 0px 10px;">
         <div class="rating_overall voted_rating_overall" style='width:72.96px;'></div>
      </div>
      <span class="result-vote float-left" id="result" style="line-height:15px; color: #AAA; font-size: 0.9em; margin-top: 1px;"> &nbsp; (15 vots)</span>
      <div class="clear"></div>
      <a href="http://" title="Mr. Elvis Presley" name="Mr. Elvis Presley">
      <img style="float:left;" src="http://a.jpg" alt="Mr. Elvis Presley" title="Mr. Elvis Presley"  />
      </a>
      <br/>
      <p>
         <b>Classification:</b>
         <a href="http://" title="Actor " name="Actor " class="underline">Actor </a>
         ,                      <a href="" title="Singer" name="Singer" class="underline">Singer</a>
         <br />
         <b>Born:</b> <a href="http://" title="Tupelo" name="Tupelo" class="underline">Tupelo</a><br />
         <b>Died:</b>
         Memphis,
         <!--<b>City:</b>-->
         <a href="http://" title="Memphis" name="Memphis" class="underline">Memphis</a>
      </p>
      <div class="clk"></div>
   </div>
</li>"""
pattern=r'<strong>(\w.+)<\/strong>|<b>Classification:<\/b>(\s.+)(\s.+)|(Born:.+)|(Died:.+\s.+\s.+\s.+)'
pattern_2=r'name=["](\w.+?)["]'

match=re.finditer(pattern,string_1,re.M)
for find in match:
    if find.group(1):
        print("Name {}".format(find.group(1)))
    if find.group(2):
        print("Classificiation first {}".format(re.search(pattern_2,str(find.group(2))).group(1)))
        print("Classification second {}".format(re.search(pattern_2,str(find.group(3))).group(1)))
    if find.group(4):
        print("Born {}".format(re.search(pattern_2, str(find.group(4))).group(1)))
    if find.group(5):
        print("Dead {}".format(re.search(pattern_2, str(find.group(5))).group(1)))

output:

Name Mr. Elvis Presley
Classificiation first Actor
Classification second Singer
Born Tupelo
Dead Memphis


问:
Replace substring of text matching regexp
I have text that looks like something like this:

```<code>1. Must have experience in Java 2. Team leader...
</code>```

I want to render this in HTML as an ordered list. Now adding the
 tag to the end is simple enough:

```<code>s = replace(s, ". ", "</li>");
</code>```

But how do I go about replacing the 1., 2. etc with
?

I have the regular expression \d*\.$ which matches a number with a period, but the problem is is that is a substring so matching 1. Must have experience in Java 2. Team leader with \d*\.$ returns false.

答:
Code

See regex in use here

```<code>\d+\.\s+(.*?)\s*(?=\d+\.\s+|$)
</code>```

Replace

```<code><li>$1</li>\n
</code>```

Results

Input

Must have experience in Java 2. Team leader...

Output

```<code><li>Must have experience in Java</li>
<li>Team leader...</li>
</code>```

Explanation

\d+ Match one or more digits

\. Match the dot character . literally

\s+ Match one or more whitespace characters

(.*?) Capture any character any number of times, but as few as possible, into capture group 1

\s* Match any number of whitespace characters

(?=\d+\.\s+|$) Positive lookahead ensuring either of the following doesn't match

\d+\.\s+

\d+ Match one or more digits

\. Match the dot character . literally

\s+ Match one or more whitespace characters

$ Assert position at the end of the line

Body:
I have text that looks like something like this:

1. Must have experience in Java 2. Team leader...

I want to render this in HTML as an ordered list. Now adding the
 tag to the end is simple enough:

s = replace(s, ". ", "
");

But how do I go about replacing the 1., 2. etc with
?

I have the regular expression \d*\.$ which matches a number with a period, but the problem is is that is a substring so matching 1. Must have experience in Java 2. Team leader with \d*\.$ returns false.

Body:
Code

See regex in use here

\d+\.\s+(.*?)\s*(?=\d+\.\s+|$)

Replace

<li>$1</li>\n

Results

Input

Must have experience in Java 2. Team leader...

Output

<li>Must have experience in Java</li>
<li>Team leader...</li>

Explanation

\d+ Match one or more digits

\. Match the dot character . literally

\s+ Match one or more whitespace characters

(.*?) Capture any character any number of times, but as few as possible, into capture group 1

\s* Match any number of whitespace characters

(?=\d+\.\s+|$) Positive lookahead ensuring either of the following doesn't match

\d+\.\s+

\d+ Match one or more digits

\. Match the dot character . literally

\s+ Match one or more whitespace characters

$ Assert position at the end of the line


问:
add new column (string length) to df by UserDefinedFunction in spark python
I have dataframe with 2 columns name, age.
I would like to add new column, name_length, which contain the str.count(name) value.

code:

```<code>from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import DoubleType

udf = UserDefinedFunction(lambda x: str.count(x.alias(name)), DoubleType())
df_with_new_column = nonull_df.withColumn('name_length', udf())
print df_with_new_column.show()
</code>```

when i run this, I receive the error:
 "ValueError: (ValueError('No args or kwargs',), <function <lambda> at 0x7feac13329b0>, ())"

答:
As David Griffin said earlier, you don't need a UDF for this as there is a built in function length() in pyspark sql functions. Just to clarify his answer with out-of-the-box working code, you'll need to call the method from pyspark sql functions as below.</p>

```<code>import pyspark.sql.functions as F
df = df.withColumn('your_column_length', F.length(your_column))
</code>```

Body:
I have dataframe with 2 columns name, age.
I would like to add new column, name_length, which contain the str.count(name) value.

code:

from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import DoubleType

udf = UserDefinedFunction(lambda x: str.count(x.alias(name)), DoubleType())
df_with_new_column = nonull_df.withColumn('name_length', udf())
print df_with_new_column.show()

when i run this, I receive the error:
 "ValueError: (ValueError('No args or kwargs',), <function <lambda> at 0x7feac13329b0>, ())"

Body:
As David Griffin said earlier, you don't need a UDF for this as there is a built in function length() in pyspark sql functions. Just to clarify his answer with out-of-the-box working code, you'll need to call the method from pyspark sql functions as below.

import pyspark.sql.functions as F
df = df.withColumn('your_column_length', F.length(your_column))


问:
In Tableau, how do I use two parts of a pivotted column for x and y values on a graph?
I'm trying to plot some data (standard curves for analytical chemistry) where the x axis is the mass of a compound I added to a solution, and the y axis is the signal recorded from an instrument (peak height on a mass spectrometer). I'd like Tableau to color code the data by compound (compound A, compound B, compound C, etc.), so that I'd wind up with a graph that looks something like this:

The original structure of my data was like this:

```<code> SampleID   | Mass A | Mass B | ... | Signal A | Signal B | ...
 standard 0 |       0|       0| ... |         0|         0| ...
 standard 5 |   2.535|   2.555| ... |     0.494|     1.240| ...
 standard 25|  12.675|  12.775| ... |     2.426|     7.235| ...
</code>```

I know how to make graphs one compound at a time with these original data, but for the purposes of other analyses I'm doing with these data and because I want multiple compounds on the same graph, I've pivotted them so that the structure is now like this:

```<code> SampleID   | Compound | Parameter | Value
 standard 0 | A        | Mass      |     0
 standard 0 | A        | Signal    |     0
 standard 5 | A        | Mass      | 2.535
</code>```

etc.

How do I make a graph where the mass is on the x axis, the signal is on the y axis, and the points are colored by compound? I don't see a good way to do it when my data are in this format. I've tried making new calculated variables where the value = NULL if the parameter is not equal to "Mass" and another calculated variable where the value = NULL if the parameter is not equal to "Signal" and then putting those pills on the columns and rows, but that's not working. Is there a way to do this in Tableau with data structured like this pivotted form?

Alternatively, is there a way to spread my pivotted data so that the new structure is like this:

```<code> SampleID   | Compound | Mass  |  Signal
 standard 0 | A        |      0|       0
 standard 5 | A        |  2.535|   0.494
 standard 25| A        | 12.675|   2.426
 standard 0 | B        |      0|       0
</code>```

etc.

and would that work better?

(For R users, that last bit would be the equivalent of the tidyr package gather and spread functions.)

答:
To make the second structure appear like the third, add a calculated field called Mass defined as if Parameter = "Mass" then Value end. Do the same for Signal.

You can then hide the fields Parameter and Value if you like, and work with Mass and Value instead.

Put AVG(Mass) on the Columns Shelf and AVG(Signal) on the Rows shelf -- AVG, not ATTR. Then finally, put [Sample Id] on detail.

Body:
I'm trying to plot some data (standard curves for analytical chemistry) where the x axis is the mass of a compound I added to a solution, and the y axis is the signal recorded from an instrument (peak height on a mass spectrometer). I'd like Tableau to color code the data by compound (compound A, compound B, compound C, etc.), so that I'd wind up with a graph that looks something like this:

The original structure of my data was like this:

 SampleID   | Mass A | Mass B | ... | Signal A | Signal B | ...
 standard 0 |       0|       0| ... |         0|         0| ...
 standard 5 |   2.535|   2.555| ... |     0.494|     1.240| ...
 standard 25|  12.675|  12.775| ... |     2.426|     7.235| ...

I know how to make graphs one compound at a time with these original data, but for the purposes of other analyses I'm doing with these data and because I want multiple compounds on the same graph, I've pivotted them so that the structure is now like this:

 SampleID   | Compound | Parameter | Value
 standard 0 | A        | Mass      |     0
 standard 0 | A        | Signal    |     0
 standard 5 | A        | Mass      | 2.535

etc.

How do I make a graph where the mass is on the x axis, the signal is on the y axis, and the points are colored by compound? I don't see a good way to do it when my data are in this format. I've tried making new calculated variables where the value = NULL if the parameter is not equal to "Mass" and another calculated variable where the value = NULL if the parameter is not equal to "Signal" and then putting those pills on the columns and rows, but that's not working. Is there a way to do this in Tableau with data structured like this pivotted form?

Alternatively, is there a way to spread my pivotted data so that the new structure is like this:

 SampleID   | Compound | Mass  |  Signal
 standard 0 | A        |      0|       0
 standard 5 | A        |  2.535|   0.494
 standard 25| A        | 12.675|   2.426
 standard 0 | B        |      0|       0

etc.

and would that work better?

(For R users, that last bit would be the equivalent of the tidyr package gather and spread functions.)


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
Using pandas.cut:

```<code>import numpy as np
import pandas as pd

bins = [-np.inf, 50, 60, 70, 80, 100]
labels=list('UDCBA')
print(pd.cut(pd.Series(m), bins=bins, labels=labels).iat[0])
# D
</code>```

This is particularly applicable if you have more than one grade:

```<code>grades = np.random.randint(low=45, high=99, size=5)  # 5 grades

print(pd.cut(pd.Series(grades), bins=bins, labels=labels).tolist())
# ['U', 'C', 'A', 'A', 'A']
</code>```

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
Using pandas.cut:

import numpy as np
import pandas as pd

bins = [-np.inf, 50, 60, 70, 80, 100]
labels=list('UDCBA')
print(pd.cut(pd.Series(m), bins=bins, labels=labels).iat[0])
# D

This is particularly applicable if you have more than one grade:

grades = np.random.randint(low=45, high=99, size=5)  # 5 grades

print(pd.cut(pd.Series(grades), bins=bins, labels=labels).tolist())
# ['U', 'C', 'A', 'A', 'A']


问:
unknown override specifier in CString?
I have created a class and having CString data member.

```<code>class Clistof
{
CString m_exe;
public:
Clistof(CString temp){m_exe = temp}
};
</code>```

error : C3646 'exe': unknown override specifier

Any idea ?

Thanks,

答:
You probably did not include a header that contains the definition for CString. Try including #include <atlstr.h> if you haven't done so already.

Also, please note that you forgot to add a ; after the assignment statement in your constructor: instead of Clistof(CString temp){m_exe = temp} you should write Clistof(CString temp) { m_exe = temp; }.

Title: unknown override specifier in CString?

Body:
I have created a class and having CString data member.

class Clistof
{
CString m_exe;
public:
Clistof(CString temp){m_exe = temp}
};

error : C3646 'exe': unknown override specifier

Any idea ?

Thanks,


问:
.NET Core 2 / Identity Server 4 - refresh all of the claims
I have a .net core application using Identity Server 4 that creates numerous non-standard claims for authorization in the application.  Some of those non-standard claims have a direct impact on how the application behaves and are set by a database.  If the user performs some action on the UI I will need to reset those claims.

So my question, using the hybrid flow if I do the renew tokens found here https://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Clients/src/MvcHybrid/Controllers/HomeController.cs, will that call the user info endpoint to get an updated list of claims?  So more or less, resetting the login without having to log out and log back in.  Or will I need to update the Claims principal manually?

I would much rather no have to update the principal manually and let IS4 do the heavy lifting.

EDIT

Using the code above I was able to refresh the tokens and I see that it's calling IS4 and resetting the claims in the IS4 code, but it's not getting the user profile which isn't actually updating the claims on the client side.  I cannot save the claims in the token since the token becomes too large for log out so I have the "GetClaimsFromUserInfoEndpoint" enabled on the options.  Anyway of programmatically resetting the UserProfile?

答:
Found it!  Using the refresh tokens from the sample code you will need to manually call the UserInfo endpoint to get the updated list of claims after you authenticate the cookie but before you sign in the cookie.

```<code>var disco = await DiscoveryClient.GetAsync(this.applicationSettings.IdentityServerAuthority);
if (disco.IsError) throw new Exception(disco.Error);

var userInfoClient = new UserInfoClient(disco.UserInfoEndpoint);
var tokenClient = new TokenClient(disco.TokenEndpoint, this.applicationSettings.IdentityServerAuthorityClient, this.applicationSettings.IdentityServerAuthorityPassword);
var rt = await this.httpContext.HttpContext.GetTokenAsync("refresh_token");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(rt);

if (!tokenResult.IsError)
{
    var old_id_token = await this.httpContext.HttpContext.GetTokenAsync("id_token");
    var new_access_token = tokenResult.AccessToken;
    var new_refresh_token = tokenResult.RefreshToken;

    var tokens = new List<AuthenticationToken>();
    tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token });
    tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token });
    tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token });

    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
    tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });
    var info = await this.httpContext.HttpContext.AuthenticateAsync("Cookies");
    //get the updated user profile (claims)
    var response = await userInfoClient.GetAsync(new_access_token);
    info.Properties.StoreTokens(tokens);

    //merge the new claims with the current principal
    var currentIdentity = info.Principal.Identity as ClaimsIdentity;
    var distinctClaimTypes = response.Claims.Select(x => x.Type).Distinct();
    foreach (var claimType in distinctClaimTypes)
    {
        var currentCount = currentIdentity.Claims.Count(x => x.Type == claimType);
        if (currentCount > 0)
        {
            //remove the claims from the current
            var currentClaims = currentIdentity.Claims.Where(x => x.Type == claimType).ToList();
            foreach (var currentClaim in currentClaims)
            {
                currentIdentity.RemoveClaim(currentClaim);
            }
        }

        //add the new claims
        currentIdentity.AddClaims(response.Claims.Where(x => x.Type == claimType));
    }

    //update the cookies with the new principal and identity
    await this.httpContext.HttpContext.SignInAsync("Cookies", info.Principal, info.Properties);

    return true;
}
</code>```

There is probably a way to authenticate/signin with "oidc" as well.  I tried, but wasn't able to get it to work.

Body:
Found it!  Using the refresh tokens from the sample code you will need to manually call the UserInfo endpoint to get the updated list of claims after you authenticate the cookie but before you sign in the cookie.

var disco = await DiscoveryClient.GetAsync(this.applicationSettings.IdentityServerAuthority);
if (disco.IsError) throw new Exception(disco.Error);

var userInfoClient = new UserInfoClient(disco.UserInfoEndpoint);
var tokenClient = new TokenClient(disco.TokenEndpoint, this.applicationSettings.IdentityServerAuthorityClient, this.applicationSettings.IdentityServerAuthorityPassword);
var rt = await this.httpContext.HttpContext.GetTokenAsync("refresh_token");
var tokenResult = await tokenClient.RequestRefreshTokenAsync(rt);

if (!tokenResult.IsError)
{
    var old_id_token = await this.httpContext.HttpContext.GetTokenAsync("id_token");
    var new_access_token = tokenResult.AccessToken;
    var new_refresh_token = tokenResult.RefreshToken;

    var tokens = new List<AuthenticationToken>();
    tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.IdToken, Value = old_id_token });
    tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.AccessToken, Value = new_access_token });
    tokens.Add(new AuthenticationToken { Name = OpenIdConnectParameterNames.RefreshToken, Value = new_refresh_token });

    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
    tokens.Add(new AuthenticationToken { Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) });
    var info = await this.httpContext.HttpContext.AuthenticateAsync("Cookies");
    //get the updated user profile (claims)
    var response = await userInfoClient.GetAsync(new_access_token);
    info.Properties.StoreTokens(tokens);

    //merge the new claims with the current principal
    var currentIdentity = info.Principal.Identity as ClaimsIdentity;
    var distinctClaimTypes = response.Claims.Select(x => x.Type).Distinct();
    foreach (var claimType in distinctClaimTypes)
    {
        var currentCount = currentIdentity.Claims.Count(x => x.Type == claimType);
        if (currentCount > 0)
        {
            //remove the claims from the current
            var currentClaims = currentIdentity.Claims.Where(x => x.Type == claimType).ToList();
            foreach (var currentClaim in currentClaims)
            {
                currentIdentity.RemoveClaim(currentClaim);
            }
        }

        //add the new claims
        currentIdentity.AddClaims(response.Claims.Where(x => x.Type == claimType));
    }

    //update the cookies with the new principal and identity
    await this.httpContext.HttpContext.SignInAsync("Cookies", info.Principal, info.Properties);

    return true;
}

There is probably a way to authenticate/signin with "oidc" as well.  I tried, but wasn't able to get it to work.


问:
IntelliJ IDEA 2017 - Missing Debug window
My Intellij Debugger window went missing and I can't find any resources on how to get it back, the closest think I can get to my problem is a missing console window but that doesn't help. So I'm hoping someone here can help me retrieve it.

This pic shows a normal Intellij IDE (that I got from my friend) that shows the tab that's missing for me (in red) and the area in which this tab normally shows (in yellow).

And this pic shows my IDE with the missing Debugger window.

I also opened Intellij's help dialogue which claims that the window will show up when your code hits a break point but that didn't do it for me either.

答: Try the "restore layout" button at the left toolbar of the debugger toolwindow


问:
.gitignore Syntax: bin vs bin/ vs. bin/* vs. bin/**
What's the difference between adding bin, bin/, bin/* and bin/** in my .gitignore file? I've been using bin/, but looking at other .gitignore files (in the eclipse file the double and single star are even used together like this: tmp/**/* what's up with that?) I see that the first two patterns are also widely used as well. Can someone please explain the differences between the three?

答:
There's another difference between bin/* and bin/.

bin/ matches foo/bin/test.txt (as expected), but bin/* does not, which seems strange, but it's documented: https://git-scm.com/docs/gitignore

"Documentation/*.html" matches "Documentation/git.html" but not
  "Documentation/ppc/ppc.html" or "tools/perf/Documentation/perf.html".

The reason for this appears to be these rules:

If the pattern ends with a slash, it is removed for the purpose of the following description …

If the pattern does not contain a slash /, Git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file …

Otherwise, Git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag …

So if the pattern ends with a slash, the slash is removed and it's treated as a shell glob pattern, in which case bin matches foo/bin/test.txt.
If it ends with /*, the slash isn't removed and it's passed to fnmatch, which doesn't match in subdirectories.

However, the same is not true for foo/bin/ and foo/bin/*, because even after removing the trailing slash from foo/bin/, it still contains a slash, so it's treated as an fnmatch pattern, not a glob. I.e. it will not match bar/foo/bin/test.txt


问:
What is the difference between ActivePython and Python?
I am new to Python. I am supposed to launch an application and perform some tasks on the application from Python.

I found Python from python.org and ActivePython from activestate.com.

What is the difference between them? Which should I install?

答:
ActiveState is an open source company which bundles Python with some additional packages and makes it available for variety of platforms. Sometimes they support platforms which the standard Python distrubution does not. For example AIX comes to my mind.

Many beginners to python on Windows have this doubt when they start with Python. ActiveState provides a bundle of Python executable with Python Windows Extensions and PEPS and Dive into Python ebook as package, so that you will have a good solution.

Technically there is not any difference between Python from activestate.com and from python.org if it available for download for your platform.

And yes, you can install Python 2.7.1 as it is latest supported version in 2.x series.


问:
How do could I insert a certain value into a specific column
```<code>import sqlite3 as db

def criar_grupos():
    global cursor3,nome_grupo
    nome_grupo = raw_input('name of group')
    nome_criador = raw_input('new user')
    conn3 = db.connect("tabela_grupos.db")
    cursor3 = conn3.cursor()
    cursor3.execute('CREATE TABLE IF NOT EXISTS groups (name string NOT NULL
UNIQUE)')
    conn3.commit()

    cursor3.execute("alter table grupos add column '%s' 'string'" %
nome_grupo)
    cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?',
(nome_grupo, nome_criador))

criar_grupos()
</code>```

I'm having a bad time trying to execute this function.

I keep getting the error message:
sqlite3.OperationalError: near "(": syntax error

What could I be doing wrong.?

答:
Change this:

```<code>cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?', (nome_grupo, nome_criador))
</code>```

To this:

```<code>cursor3.execute('INSERT INTO grupos (?) VALUES (?);', (nome_grupo, nome_criador))
</code>```

Body:
import sqlite3 as db

def criar_grupos():
    global cursor3,nome_grupo
    nome_grupo = raw_input('name of group')
    nome_criador = raw_input('new user')
    conn3 = db.connect("tabela_grupos.db")
    cursor3 = conn3.cursor()
    cursor3.execute('CREATE TABLE IF NOT EXISTS groups (name string NOT NULL
UNIQUE)')
    conn3.commit()

    cursor3.execute("alter table grupos add column '%s' 'string'" %
nome_grupo)
    cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?',
(nome_grupo, nome_criador))

criar_grupos()

I'm having a bad time trying to execute this function.

I keep getting the error message:
sqlite3.OperationalError: near "(": syntax error

What could I be doing wrong.?

Body:
Change this:

cursor3.execute('UPDATE grupos SET ("nome"=?) WHERE name=?', (nome_grupo, nome_criador))

To this:

cursor3.execute('INSERT INTO grupos (?) VALUES (?);', (nome_grupo, nome_criador))


问:
Concatenating Series using the addition (+) operator?
So this is more of a question than a problem i have.

I wanted to .append() some pandas series' together and without thinking i just did total=series1+series2+series3.

The length of each series is 2199902,171175, and 178989 respectively and sum(pd.isnull(i) for i in total) = 2214596

P.S all 3 series' had no null values to start with, is it something to do with merging 3 series' of different lengths which creates missing values? Even if that is the case why aer 2,214,596 null values created?

答:
If sum Series all index are align. So if some index exist in series1 and not in another Series, get NaNs.

So need add with fill_value=0:

```<code>s = s1.add(s2, fill_value=0).add(s3, fill_value=0)
</code>```

Sample:

```<code>s1 = pd.Series([1,2,4,5])
s2 = pd.Series([4,7], index=[10,11])
s3 = pd.Series([40,70], index=[2,4])

s = s1.add(s2, fill_value=0).add(s3, fill_value=0)
print (s)
0      1.0
1      2.0
2     44.0
3      5.0
4     70.0
10     4.0
11     7.0
dtype: float64
</code>```

But if need append them together (or use concat as mentioned cᴏʟᴅsᴘᴇᴇᴅ):

```<code>s = s1.append(s2, ignore_index=True).append(s3, ignore_index=True)
print (s)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64
</code>```

And numpy alternative:

```<code>#alternative, thanks cᴏʟᴅsᴘᴇᴇᴅ - np.concatenate([s1, s2, s3])
s = pd.Series(np.concatenate([s1.values, s2.values, s3.values]))

print (s)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64
</code>```

If want use + for append then need convert Series to lists:

```<code>s = pd.Series(s1.tolist() + s2.tolist() + s3.tolist())
print (s)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64
</code>```

Body:
If sum Series all index are align. So if some index exist in series1 and not in another Series, get NaNs.

So need add with fill_value=0:

s = s1.add(s2, fill_value=0).add(s3, fill_value=0)

Sample:

s1 = pd.Series([1,2,4,5])
s2 = pd.Series([4,7], index=[10,11])
s3 = pd.Series([40,70], index=[2,4])

s = s1.add(s2, fill_value=0).add(s3, fill_value=0)
print (s)
0      1.0
1      2.0
2     44.0
3      5.0
4     70.0
10     4.0
11     7.0
dtype: float64

But if need append them together (or use concat as mentioned cᴏʟᴅsᴘᴇᴇᴅ):

s = s1.append(s2, ignore_index=True).append(s3, ignore_index=True)
print (s)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64

And numpy alternative:

#alternative, thanks cᴏʟᴅsᴘᴇᴇᴅ - np.concatenate([s1, s2, s3])
s = pd.Series(np.concatenate([s1.values, s2.values, s3.values]))

print (s)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64

If want use + for append then need convert Series to lists:

s = pd.Series(s1.tolist() + s2.tolist() + s3.tolist())
print (s)
0     1
1     2
2     4
3     5
4     4
5     7
6    40
7    70
dtype: int64