问:
Polymer app-route return empty data attributes
I'm learning Polymer and i got some issues with app-route and app-location. I tried a simple example like this:

```<code><dom-module id="test-component">
    <template>
        <style scoped>

        </style>
        <app-location route="{{route}}" use-hash-as-path></app-location>
        <app-route route="{{route}}" pattern="/test/:advisor_id/:user_id"
                   data="{{data}}" tail="{{subroute}}">
        </app-route>
        route : [[route.path]]<br>
        data.advisor_id : [[data.advisor_id]]<br>
        data.user_id : [[data.user_id]]
    </template>
    <script>
       Polymer({
            is: "test-component",
            properties: {
                route: String,
                data: Object
            },
            ready: function() {
                console.log(this.route);
            }
       });
    </script>
</dom-module>
</code>```

The main page only loads components and have test-component tags on the body
With the url localhost/test/advisor_id/14152, i see the component but data.advisor_id and data.user_id are empty. I tested route.path and it is empty too.

It seems like i forgot something but don't understand what it is.

Thanks in advance for your time

答: remove the 'use-hash-as-path' from your app-location, since it expects a 'http://..../#!/path' syntax for location</p>

Body:
I'm learning Polymer and i got some issues with app-route and app-location. I tried a simple example like this:

<dom-module id="test-component">
    <template>

        <app-location route="{{route}}" use-hash-as-path></app-location>
        <app-route route="{{route}}" pattern="/test/:advisor_id/:user_id"
                   data="{{data}}" tail="{{subroute}}">
        </app-route>
        route : [[route.path]]

        data.advisor_id : [[data.advisor_id]]

        data.user_id : [[data.user_id]]
    </template>

</dom-module>

The main page only loads components and have test-component tags on the body
With the url localhost/test/advisor_id/14152, i see the component but data.advisor_id and data.user_id are empty. I tested route.path and it is empty too.

It seems like i forgot something but don't understand what it is.

Thanks in advance for your time


来源: stackexchange

问:
Get variable using string
Lets say i have 2 arrays called fruitbasket01 and fruitbasket02.

I want to get the fruitbasket based on my id, which could be 01 or 02.

```<code>var fruitbasket01 = ['apple','orange'];
var fruitbasket02 = ['mango','grapes','peach','potato']
var id1 = '01';
var id2 = '02';

if (condition 1) {
     var string = 'fruitbasket'.concat(id1);
} else {
     var string = 'fruitbasket'.concat(id2);
}

for (var i=0; i<string.length; i++) {
     /** more code here **/
}
</code>```

may I know what is wrong with this method and how can I go about it instead.

答:
I suggest to use an object instead of single array, because the object is accessible with a key and easily maintainable.

var baskets = {
        '01': ['apple', 'orange'],
        '02': ['mango', 'grapes', 'peach', 'potato']
    },
    id = '02';

console.log(baskets[id]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

ContentLicense: CC BY-SA 3.0

Title: Get variable using string

Body:
Lets say i have 2 arrays called fruitbasket01 and fruitbasket02.

I want to get the fruitbasket based on my id, which could be 01 or 02.

var fruitbasket01 = ['apple','orange'];
var fruitbasket02 = ['mango','grapes','peach','potato']
var id1 = '01';
var id2 = '02';

if (condition 1) {
     var string = 'fruitbasket'.concat(id1);
} else {
     var string = 'fruitbasket'.concat(id2);
}

for (var i=0; i<string.length; i++) {
     /** more code here **/
}

may I know what is wrong with this method and how can I go about it instead.

Body:
I suggest to use an object instead of single array, because the object is accessible with a key and easily maintainable.

var baskets = {
        '01': ['apple', 'orange'],
        '02': ['mango', 'grapes', 'peach', 'potato']
    },
    id = '02';

console.log(baskets[id]);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
When selected option from dropdown then how to hide that selected option into another dropdown using jQuery

<select>
  <option value = "volvo" > Volvo < /option>
  <option value = "saab" > Saab < /option>
  <option value = "vw" > VW < /option>
  <option value = "audi"> Audi < /option>
</select>```

I am having many dropdown where all dropdown having same option value but when user select option then that selected value should hide or remove in others dropdown and if user changes option that that previous selected option should come into that option and currently selected option should hide into other dropdown.
when selected option from dropdown then how to hide that selected option into another dropdown.I tried to find solution of this but no one's code working properly.

答:
3 select boxes:

```<code><select id="1">
  <option value = "volvo" > Volvo </option>
  <option value = "saab" > Saab </option>
  <option value = "vw" > VW </option>
  <option value = "audi"> Audi </option>
</select>
<select id="2">
  <option value = "volvo" > Volvo </option>
  <option value = "saab" > Saab </option>
  <option value = "vw" > VW </option>
  <option value = "audi"> Audi </option>
</select>
<select id="3">
  <option value = "volvo" > Volvo </option>
  <option value = "saab" > Saab </option>
  <option value = "vw" > VW </option>
  <option value = "audi"> Audi </option>
</select>
</code>```

Your js code:

```<code>m_val="";
m_text="";
$(document).ready(function(){
  val = $("select:first").val();
  text = $("select:first option:selected").text();
  $("select:not(:first) option[value='"+val+"']").remove();

  m_val=val;
  m_text=text;

  $("select").change(function(){
    val = $(this).val();
    id = $(this).attr("id");
    text = $(this).text();

    $("select[id!='"+id+"'] option[value='"+val+"']").remove();

    $("select").each(function( index ) {
      i = $(this).attr("id");
      if($("select[id='"+i+"'] option[value='"+m_val+"']").length==0){
        $(this).append("<option value = '"+m_val+"' > "+m_text+"</option> ");
      }
    });

    m_val=val;
    m_text=text;
  });
});
</code>```

Here is a working fiddle: https://jsfiddle.net/1krwzL4j/

Body:
<select>
  <option value = "volvo" > Volvo < /option>
  <option value = "saab" > Saab < /option>
  <option value = "vw" > VW < /option>
  <option value = "audi"> Audi < /option>
</select>

I am having many dropdown where all dropdown having same option value but when user select option then that selected value should hide or remove in others dropdown and if user changes option that that previous selected option should come into that option and currently selected option should hide into other dropdown.
when selected option from dropdown then how to hide that selected option into another dropdown.I tried to find solution of this but no one's code working properly.

Body:
3 select boxes:

<select id="1">
  <option value = "volvo" > Volvo </option>
  <option value = "saab" > Saab </option>
  <option value = "vw" > VW </option>
  <option value = "audi"> Audi </option>
</select>
<select id="2">
  <option value = "volvo" > Volvo </option>
  <option value = "saab" > Saab </option>
  <option value = "vw" > VW </option>
  <option value = "audi"> Audi </option>
</select>
<select id="3">
  <option value = "volvo" > Volvo </option>
  <option value = "saab" > Saab </option>
  <option value = "vw" > VW </option>
  <option value = "audi"> Audi </option>
</select>

Your js code:

m_val="";
m_text="";
$(document).ready(function(){
  val = $("select:first").val();
  text = $("select:first option:selected").text();
  $("select:not(:first) option[value='"+val+"']").remove();

  m_val=val;
  m_text=text;

  $("select").change(function(){
    val = $(this).val();
    id = $(this).attr("id");
    text = $(this).text();

    $("select[id!='"+id+"'] option[value='"+val+"']").remove();

    $("select").each(function( index ) {
      i = $(this).attr("id");
      if($("select[id='"+i+"'] option[value='"+m_val+"']").length==0){
        $(this).append("<option value = '"+m_val+"' > "+m_text+"</option> ");
      }
    });

    m_val=val;
    m_text=text;
  });
});

Here is a working fiddle: https://jsfiddle.net/1krwzL4j/


问:
How to set password connecting to a web service with client-authentication for KeyFile?
I have to write a program (Delphi XE5, Indy 10: TIdHTTP & TIdSSLIOHandlerSocketOpenSSL) which can connect to a web service with client authentication. With several days of working, finally it has become success. I can connect using the authentication, setting the TIdSSLIOHandlerSocketOpenSSL’s SSLOptions.CertFile and SSLOptions.KeyFile properties. It’s fine. (I've got a pfx file from my partner, I exported it to a certificate and a private key file with OpenSSL so I use these 2 files in the program.)

I have one TButton, TMemo and TIdHTTP component on the form.

Source code (Button's click event - the IdHTTP1.Request.ContentType := '.......' line is necessary just for the communication because of the server settings):

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  URL: string;
  XML: TStrings;
  S: string;
  Req: TStream;
  SL: TStringList;
  SSL1 : TIdSSLIOHandlerSocketOpenSSL;

begin
  XML := TStringList.Create;

  XML.Add('<soap:Envelope xmlns:ns="http://docs.oasis-open.org/ws-sx/ws-trust/200512" ' +
    'xmlns:soap="http://www.w3.org/2003/05/soap-envelope">');
…
  XML.Add('   <soap:Body>');
…
  XML.Add('   </soap:Body>');
  XML.Add('</soap:Envelope>');
  URL := 'https://…………………….';
  end

  Req := TStringStream.Create(XML.Text, TEncoding.UTF8);
  try
    SSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    SSL1.SSLOptions.CertFile := 'd:\certificate.pem';
    SSL1.SSLOptions.KeyFile := 'd:\private.pem';
    SSL1.SSLOptions.Mode := sslmClient;
    try
      SSL1.SSLOptions.Method := sslvSSLv23;
      IdHTTP1.IOHandler := SSL1;
      IdHTTP1.Request.ContentType := 'application/soap+xml;charset=UTF-8;action="http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"';
      S := IdHTTP1.Post(URL, Req);
    finally
      SSl1.Free;
    end;
  finally
    Req.Free;
  end;

  ResultMemo.Lines.Add(Format('Response Code: %d', [IdHTTP1.ResponseCode]));
  ResultMemo.Lines.Add(Format('Response Text: %s', [IdHTTP1.ResponseText]));

  SL := TStringList.Create;
  try
    SL.Text := S;
    ResultMemo.Lines.AddStrings(SL);
  finally
    SL.Free;
  end;

end;
</code>```

The problem is: my partner said this case is not the best if the file I use is not password-protected. They told me how to create a password-protected (and encrypted) file for the KeyFile with OpenSSL. When I set this password-protected file to the SSLOptions.KeyFile I get the following error message: „Could not load key, check password. error:0906A068:PEM routines:PEM_do_header:bad password read.”

I tried to set the password in the idHTTP1.Request.Password property, but the result is the same.

Question: how and where do I have to set the password for the KeyFile if I have to use a password-protected keyfile? Because I have to publish the certification files, too, the best solution would be to set the password in the program and use the password-protected KeyFile, instead of using not the password-protected KeyFile.

Thanks a lot.

Regards,
Attila

答:
Use the IdSSLIOHandlerSocketOpenSSL.OnGetPassword event and set it here.

procedure TForm1.IdSSLIOHandlerSocketOpenSSL1GetPassword(var Password: string);
begin
  Password := 'thepassword';
end;

Body:
I have to write a program (Delphi XE5, Indy 10: TIdHTTP & TIdSSLIOHandlerSocketOpenSSL) which can connect to a web service with client authentication. With several days of working, finally it has become success. I can connect using the authentication, setting the TIdSSLIOHandlerSocketOpenSSL’s SSLOptions.CertFile and SSLOptions.KeyFile properties. It’s fine. (I've got a pfx file from my partner, I exported it to a certificate and a private key file with OpenSSL so I use these 2 files in the program.)

I have one TButton, TMemo and TIdHTTP component on the form.

Source code (Button's click event - the IdHTTP1.Request.ContentType := '.......' line is necessary just for the communication because of the server settings):

procedure TForm1.Button1Click(Sender: TObject);
var
  URL: string;
  XML: TStrings;
  S: string;
  Req: TStream;
  SL: TStringList;
  SSL1 : TIdSSLIOHandlerSocketOpenSSL;

begin
  XML := TStringList.Create;

  XML.Add('<soap:Envelope xmlns:ns="http://docs.oasis-open.org/ws-sx/ws-trust/200512" ' +
    'xmlns:soap="http://www.w3.org/2003/05/soap-envelope">');
…
  XML.Add('   <soap:Body>');
…
  XML.Add('   </soap:Body>');
  XML.Add('</soap:Envelope>');
  URL := 'https://…………………….';
  end

  Req := TStringStream.Create(XML.Text, TEncoding.UTF8);
  try
    SSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
    SSL1.SSLOptions.CertFile := 'd:\certificate.pem';
    SSL1.SSLOptions.KeyFile := 'd:\private.pem';
    SSL1.SSLOptions.Mode := sslmClient;
    try
      SSL1.SSLOptions.Method := sslvSSLv23;
      IdHTTP1.IOHandler := SSL1;
      IdHTTP1.Request.ContentType := 'application/soap+xml;charset=UTF-8;action="http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"';
      S := IdHTTP1.Post(URL, Req);
    finally
      SSl1.Free;
    end;
  finally
    Req.Free;
  end;

  ResultMemo.Lines.Add(Format('Response Code: %d', [IdHTTP1.ResponseCode]));
  ResultMemo.Lines.Add(Format('Response Text: %s', [IdHTTP1.ResponseText]));

  SL := TStringList.Create;
  try
    SL.Text := S;
    ResultMemo.Lines.AddStrings(SL);
  finally
    SL.Free;
  end;

end;

The problem is: my partner said this case is not the best if the file I use is not password-protected. They told me how to create a password-protected (and encrypted) file for the KeyFile with OpenSSL. When I set this password-protected file to the SSLOptions.KeyFile I get the following error message: „Could not load key, check password. error:0906A068:PEM routines:PEM_do_header:bad password read.”

I tried to set the password in the idHTTP1.Request.Password property, but the result is the same.

Question: how and where do I have to set the password for the KeyFile if I have to use a password-protected keyfile? Because I have to publish the certification files, too, the best solution would be to set the password in the program and use the password-protected KeyFile, instead of using not the password-protected KeyFile.

Thanks a lot.

Regards,
Attila


问:
Drupal — disable CSS cache
I am using Drupal 6. Every time I modify the CSS files, I need to clear the cache to see the updated result, which is a waste of my time. Is there any way to disable the cache system?</p>

答:
Also, for the purpose of development you could place the following in your template.php (assuming you're working on a theme).

```<code>drupal_flush_all_caches();
</code>```

See http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_flush_all_caches/6

ContentLicense: CC BY-SA 2.5

Title: Drupal — disable CSS cache

Body:
Also, for the purpose of development you could place the following in your template.php (assuming you're working on a theme).

drupal_flush_all_caches();

See http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_flush_all_caches/6


问:
access textfield text from another viewController
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
```

<p>and here is my <code>profileController</code> prepare func:</p>

<pre class="lang-swift prettyprint-override"><code>    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }
</code>```

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

答:
You just need a small fix since UITextField and any other components of UIKit are not initialised yet in the prepare for segue:</p>

```<code>var login: String!

@IBOutlet weak var myLabel: UILabel!

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("prepare")
    if (segue.identifier == "mainMenu")
    {
        let svc = segue.source as! ViewController
        login = svc.loginField.text
        // self.myLabel.text = login
        print(login)
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.myLabel.text = login
}
</code>```

Body:
I try to access a textfield content in my view profileView from my first view viewController but it doesn't work.
I read that I have to use override func prepare(for segue: UIStoryboardSegue, sender: Any?) {} so I did but it still not working and I don't understand why.

Here is my viewController code:

// This code is the code generated by xCode, only the loginField was added.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var loginField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

and here is my profileController prepare func:

    var login: String!
    @IBOutlet weak var myLabel: UILabel!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("prepare")
        if (segue.identifier == "mainMenu")
        {
            let svc = segue.source as! ViewController
            login = svc.loginField.text
            self.myLabel.text = login
            print(login)
        }
    }

Actually, the thing i really read was "prepareForSegue" func but when I try to override it, xCode won't compile the code...

Thanks for your help.

Body:
You just need a small fix since UITextField and any other components of UIKit are not initialised yet in the prepare for segue:

var login: String!

@IBOutlet weak var myLabel: UILabel!

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("prepare")
    if (segue.identifier == "mainMenu")
    {
        let svc = segue.source as! ViewController
        login = svc.loginField.text
        // self.myLabel.text = login
        print(login)
    }
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.myLabel.text = login
}


问:
Ignore trailing commas mid file, ignore trailing incomplete rows
I am dealing with CSV files which have been tampered with by others in Excel and thus somehow contain additional commas (seperators) mid file and incomplete rows at the end of the file.

Naturally Pandas/Python's CSV reader can't handle such files.

I was wondering if someone knows of an already existing solution for working around such annoying features. I appreciate non-trivial advice on writing a solution from scratch.

To illustrate :

```<code>CSV file contents:

header1, header2
1,1
2,3
5,8,,
1
1
</code>```

答:
```<code>def preprocess(filename):
    with open(filename, 'r', encoding="utf-8") as csvfile:
        for line in csvfile.readlines[1:]:
            if ',' in line:
                yield list(map(int, line.split(',')[0:2]))
</code>```

Body:
I am dealing with CSV files which have been tampered with by others in Excel and thus somehow contain additional commas (seperators) mid file and incomplete rows at the end of the file.

Naturally Pandas/Python's CSV reader can't handle such files.

I was wondering if someone knows of an already existing solution for working around such annoying features. I appreciate non-trivial advice on writing a solution from scratch.

To illustrate :

CSV file contents:

header1, header2
1,1
2,3
5,8,,
1
1


问:
Preserve order when indexing a multilevel with a list
Using Pandas 0.20.2 with Python 3.6.1:

When you index a single-level DataFrame with a list, the returned DataFrame respects the order of the list, for example consider this DataFrame:

```<code>df = pd.DataFrame({'col1': [0,1,2],
                   'col2': ['foo', 'bar', 'baz']},
                  index=list('ABD'))
</code>```

Which, when indexed with a list in a different order as the index, returns:

```<code>df.loc[['D','B'],:]
</code>```

I would like to have exactly this behavior when i use a multi-index DataFrame. But if i add one of the columns to the index, and index again, the order is like the original DataFrame, instead of the list used for indexing:

```<code>df = df.set_index('col2', append=True)
df.loc[['D','B'],:]
</code>```

Since the level contains strings, sorting the DataFrame before indexing is not as simple. A workaround could be to convert the index to Categorical, where the categories are mapped according to my preferred order, then a normal sort could work. But that seems really far-fetched, especially if you want different 'orders' all the time.

edit:

@EdChum's answer works for the 2-level example i posted, but doesn't with a 3-level, so caution is needed!

Consider this DataFrame:

```<code>df = pd.DataFrame({'col1': ['foo', 'bar', 'baz'],
                   'col2': ['green', 'blue', 'red'],
                   'col3': [0,1,2], },
                   index=list('ABD'))

df.index.names = ['col0']
df = df.set_index(['col1','col2'], append=True)
</code>```

```<code>df.reindex(index=['baz', 'bar'], level='col1')
</code>```

edit2:

Trying @piRSquared's answer on the 3-level index, if you sort for the same level as the one your indexing with, it seems to be a solution.

```<code>df = df.sort_index(level='col1')
df.iloc[df.index.get_level_values('col1').searchsorted(['baz', 'bar'])]
</code>```

答:
Assuming the index is already sorted.

```<code>df1 = df.set_index('col2', append=True)

df1.iloc[df1.index.get_level_values(0).searchsorted(['D', 'B'])]

        col1
  col2
D baz      2
B bar      1
</code>```

But @EdChum's answer is far superior

Body:
Using Pandas 0.20.2 with Python 3.6.1:

When you index a single-level DataFrame with a list, the returned DataFrame respects the order of the list, for example consider this DataFrame:

df = pd.DataFrame({'col1': [0,1,2],
                   'col2': ['foo', 'bar', 'baz']},
                  index=list('ABD'))

Which, when indexed with a list in a different order as the index, returns:

df.loc[['D','B'],:]

I would like to have exactly this behavior when i use a multi-index DataFrame. But if i add one of the columns to the index, and index again, the order is like the original DataFrame, instead of the list used for indexing:

df = df.set_index('col2', append=True)
df.loc[['D','B'],:]

Since the level contains strings, sorting the DataFrame before indexing is not as simple. A workaround could be to convert the index to Categorical, where the categories are mapped according to my preferred order, then a normal sort could work. But that seems really far-fetched, especially if you want different 'orders' all the time.

edit:

@EdChum's answer works for the 2-level example i posted, but doesn't with a 3-level, so caution is needed!

Consider this DataFrame:

df = pd.DataFrame({'col1': ['foo', 'bar', 'baz'],
                   'col2': ['green', 'blue', 'red'],
                   'col3': [0,1,2], },
                   index=list('ABD'))

df.index.names = ['col0']
df = df.set_index(['col1','col2'], append=True)

df.reindex(index=['baz', 'bar'], level='col1')

edit2:

Trying @piRSquared's answer on the 3-level index, if you sort for the same level as the one your indexing with, it seems to be a solution.

df = df.sort_index(level='col1')
df.iloc[df.index.get_level_values('col1').searchsorted(['baz', 'bar'])]

Body:
Assuming the index is already sorted.

df1 = df.set_index('col2', append=True)

df1.iloc[df1.index.get_level_values(0).searchsorted(['D', 'B'])]

        col1
  col2
D baz      2
B bar      1

But @EdChum's answer is far superior


问:
Android JNI under the hood
I cannot find any references to a detailed explanation about how JNI works on Android in detail, so:

Since every Android application runs in its own process, with its own instance of the Dalvik/ART virtual machine, I think that the native code will be executed in the same process, am I right?

I read that when the VM invokes a function, it passes a JNIEnv pointer, a jobject pointer, and any Java arguments declared by the Java method.
But how is this made at assembly level (under the hood)?

I read that you can instantiate objects, call methods, and so on, like Reflection, using the functions provided by the JNIEnv. Therefore, my question is: have I a "direct" memory access to the VM or I have always to use the JNIEnv's functions?

答:
The Android JVM is under Apache license, so the best detailed and precise description can be found in the form of source code. Note that there are two different JVMs: dalvik and art. Under the hood they are very different, to the extent that a user of JNI may consider special adaptations.

the native code will be executed in the same process

Exactly. Note that an Android app can run in more than one process, and also it can spawn child processes (normal Unix behavior). But JNI is not IPC.

how is this made at assembly level?

More or less, this is described in a related
question: What does a JVM have to do when calling a native method?

have I a "direct" memory access to the VM?

Yes, you have. There is no security barrier between your C code and the JVM. You can reverse engineer the data structures, and do whatever you like. The exact implementations of the JVM not only depend on the Android version, but may be modified without notice by the vendor, as long as the public API of the JVM (including JNI) is compatible. The chances that you will do something useful with direct memory access to JVM are minimal, but the risk that it will crash is very high.

Note that this is not a security issue: your C code is running in a separate process (with your Java code), and is subject to the same permissions restrictions as the Java code. It has no access to the private memory of other apps or procsses. Whatever you change in your instance of JVM will not effect VM that runs other apps.

Title: Android JNI under the hood


问:
Why event.target.value is undefined?
I have two components named parent and child.

Child component contains checkbox's and it will send selected checkbox's values to Parent component

Child

```<code>class Child extends Component{
  state = {
    options: [],
    selected_options: []
  }
  handleClose = (e) => {
    this.props.add(this.state.selected_options)
  }
  handleChange = (event) => {
    console.log(event.target.name);
    if(event.target.checked==true){
      event.target.checked=false
      this.state.selected_options.slice(this.state.options.indexOf(event.target.value),1)
    }
    else{
      event.target.checked = true
      this.state.selected_options.push(event.target.value)
    }
  }
  render() {
    return(
      <div>
        <Grid>
          {
            this.state.options.map(value => {
              return(
                    <Checkbox onChange={this.handleChange} label={value.name} value={value.name}   checked={false} />
              )
            })
          }
        <Button color='green' onClick={this.handleClose} inverted>
          <Icon name='checkmark' /> Apply
        </Button>
      </div>
    );
  }
}
</code>```

and Parent Component

```<code>class Parent extends Component {
  constructor(props){
    super(props);
    this.state =  {
      selected_options:[],
    }
  }
  addOptions = (options) => {
    this.setState({
      selected_options: options
    })
  }
  render() {
    return(
      <div>
        <Child selected_options={this.state.selected_options} add={this.addOptions}  />
      </div>
    );
  }
}
</code>```

When a checkbox is selected it must output its corresponding value in the console. but it showing undefined

答:
Directly mutating the state or the event value is not the correct idea

You should be doing it like

```<code>class Child extends Component{
  state = {
    checkedState: []
    options: [],
    selected_options: []
  }
  handleClose = (e) => {
    this.props.add(this.state.selected_options)
  }
  handleChange = (index, value) => {
    var checkedState = [...this.state.checkedState];
    if(checkedState[index] === undefined) {
       checkedState.push(true)
    }
    else {
       if(checkedState[index] === true) {
             var selected_options=[...this.state.selected_options];
             var idx = selected_options.findIndex((obj) => obj.name == value)
             selected_options.splice(idx, 1);
             checkedState[index] = false
       } else {
          var selected_options=[...this.state.selected_options];
          selected_options.push(value);
       }
    }
    this.setState({checkedState, selected_options})
  }
  render() {
    return(
      <div>
        <Grid>
          {
            this.state.options.map((value, index) => {
              return(
                    <Checkbox onChange={() => this.handleChange(index, value.name)} label={value.name} value={value.name}   checked={this.state.checkedState[index] || false} />
              )
            })
          }
        <Button color='green' onClick={this.handleClose} inverted>
          <Icon name='checkmark' /> Apply
        </Button>
      </div>
    );
  }
}
</code>```

and from the Parent render the child and not the Parent

Parent

```<code>render() {
    return(
      <div>
        <Child selected_options={this.state.selected_options} add={this.addOptions}  />
      </div>
    );
  }
</code>```

Title: Why event.target.value is undefined?

Body:
I have two components named parent and child.

Child component contains checkbox's and it will send selected checkbox's values to Parent component

Child

class Child extends Component{
  state = {
    options: [],
    selected_options: []
  }
  handleClose = (e) => {
    this.props.add(this.state.selected_options)
  }
  handleChange = (event) => {
    console.log(event.target.name);
    if(event.target.checked==true){
      event.target.checked=false
      this.state.selected_options.slice(this.state.options.indexOf(event.target.value),1)
    }
    else{
      event.target.checked = true
      this.state.selected_options.push(event.target.value)
    }
  }
  render() {
    return(

        <Grid>
          {
            this.state.options.map(value => {
              return(
                    <Checkbox onChange={this.handleChange} label={value.name} value={value.name}   checked={false} />
              )
            })
          }
        <Button color='green' onClick={this.handleClose} inverted>
          <Icon name='checkmark' /> Apply
        </Button>

    );
  }
}

and Parent Component

class Parent extends Component {
  constructor(props){
    super(props);
    this.state =  {
      selected_options:[],
    }
  }
  addOptions = (options) => {
    this.setState({
      selected_options: options
    })
  }
  render() {
    return(

        <Child selected_options={this.state.selected_options} add={this.addOptions}  />

    );
  }
}

When a checkbox is selected it must output its corresponding value in the console. but it showing undefined

Body:
Directly mutating the state or the event value is not the correct idea

You should be doing it like

class Child extends Component{
  state = {
    checkedState: []
    options: [],
    selected_options: []
  }
  handleClose = (e) => {
    this.props.add(this.state.selected_options)
  }
  handleChange = (index, value) => {
    var checkedState = [...this.state.checkedState];
    if(checkedState[index] === undefined) {
       checkedState.push(true)
    }
    else {
       if(checkedState[index] === true) {
             var selected_options=[...this.state.selected_options];
             var idx = selected_options.findIndex((obj) => obj.name == value)
             selected_options.splice(idx, 1);
             checkedState[index] = false
       } else {
          var selected_options=[...this.state.selected_options];
          selected_options.push(value);
       }
    }
    this.setState({checkedState, selected_options})
  }
  render() {
    return(
      <div>
        <Grid>
          {
            this.state.options.map((value, index) => {
              return(
                    <Checkbox onChange={() => this.handleChange(index, value.name)} label={value.name} value={value.name}   checked={this.state.checkedState[index] || false} />
              )
            })
          }
        <Button color='green' onClick={this.handleClose} inverted>
          <Icon name='checkmark' /> Apply
        </Button>
      </div>
    );
  }
}

and from the Parent render the child and not the Parent

Parent

render() {
    return(
      <div>
        <Child selected_options={this.state.selected_options} add={this.addOptions}  />
      </div>
    );
  }


问:
create a session that is accessible on all methods of the controller
I am working on an e-commerce project in laravel and the guest can add items to his cart before logging in and for that I am planning to use a session which will help be keep track of all items for this customer..

the project has many views but I am using same controller for displaying all of them so I was trying to find someway in which I can create a session ( I tried in the constructor but then it is not working as it is getting re-created )

my constructor code

```<code>public function __construct()
    {
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $finalCode = substr(str_shuffle(str_repeat($pool, 12)), 0, 12);
            session(['UserIdentity' => $finalCode]);
        $abc = session('UserIdentity');
        if(!(isset($abc)))
        {
            // Auto generated Code
            $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $finalCode = substr(str_shuffle(str_repeat($pool, 12)), 0, 12);
            session(['UserIdentity' => $finalCode]);

            $finalsession = session('UserIdentity');
            dd($finalsession);
        }
    }
</code>```

Please suggest me a workaround where I can make this work or any other solution is also welcome.

Thanking you in anticipation..

答:
You should set up a middleware on guest routes and then you can use sessions as per your application requirements.

From Laravel 5.3 and onwards, sessions are not accessible within constructors. As all routes use web middleware which enables sessions feature for your application. which is executed after the constructor.

Body:
I am working on an e-commerce project in laravel and the guest can add items to his cart before logging in and for that I am planning to use a session which will help be keep track of all items for this customer..

the project has many views but I am using same controller for displaying all of them so I was trying to find someway in which I can create a session ( I tried in the constructor but then it is not working as it is getting re-created )

my constructor code

public function __construct()
    {
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $finalCode = substr(str_shuffle(str_repeat($pool, 12)), 0, 12);
            session(['UserIdentity' => $finalCode]);
        $abc = session('UserIdentity');
        if(!(isset($abc)))
        {
            // Auto generated Code
            $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $finalCode = substr(str_shuffle(str_repeat($pool, 12)), 0, 12);
            session(['UserIdentity' => $finalCode]);

            $finalsession = session('UserIdentity');
            dd($finalsession);
        }
    }

Please suggest me a workaround where I can make this work or any other solution is also welcome.

Thanking you in anticipation..


问:
Need advice before I develop a bad habit
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

```<code>//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}
</code>```

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

```<code>@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            IDSubcategory
        </th>
        <th>
            IDCity
        </th>
        <th>
            IDPerson
        </th>
        <th>
            Title
        </th>
        <th>
            TextBody
        </th>
        <th>
            ContactNumber
        </th>
        <th>
            AskingPrice
        </th>
        <th>
            AddressDirection
        </th>
        <th>
            LatestUpdateDate
        </th>
        <th>
            VisitCount
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
        <td>
            @item.IDSubcategory
        </td>
        <td>
            @item.IDCity
        </td>
        <td>
            @item.IDPerson
        </td>
        <td>
            @item.Title
        </td>
        <td>
            @item.TextBody
        </td>
        <td>
            @item.ContactNumber
        </td>
        <td>
            @String.Format("{0:F}", item.AskingPrice)
        </td>
        <td>
            @item.AddressDirection
        </td>
        <td>
            @String.Format("{0:g}", item.LatestUpdateDate)
        </td>
        <td>
            @item.VisitCount
        </td>
    </tr>
}

</table>
</code>```

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.

答:
Like any framework ASP.NET MVC gives you plenty of opportunities to shoot yourself in the foot. Without forethought the reuse of controller actions, view models, and views can quickly become a maintenance nightmare. Not to mention that without similar consideration your routes will become hard to tie together.

Following the tenets of convention over configuration you could solve your problem by using separate actions but reusing a view partial. To me the index action of the AuctionsController should be responsible for listing all Auctions in the system. I wouldn't call my category action AuctionCategoryListing, but would instead call it simply Category. Through convention this has the nice effect of laying out the routes as:

site.com/auctions/ for the index

site.com/auctions/category/CATEGORYNAME for the category.

The route is easily understandable by the user and easy for you to understand explicitly what each does. (To this point Omar provides a good suggestion in his answer to let your repository handle pagination, filtering etc.)

As far as what each action should return you have several options. My preference would be to return separate views each containing a reference to a common partial. This gives you flexibility to create different views surrounding the partial but provides reuse for the piece that is common.

Further reading that might be of help:

One ViewModel per View

ASP.NET MVC terminology is tripping me up - why 'ViewModel'?

when should i use partial views in asp.net mvc?

OwnerDisplayName: delete

LastEditorDisplayName: delete

Body:
I have a controller called AuctionsController. In it I have Actions called Index() and AuctionCategoryListing():

//Used for displaying all auctions.
public ActionResult Index()
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions();
    return View(auctions);
}

//Used for displaying auctions for a single category.
public ActionResult AuctionCategoryListing(string categoryName)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions()
                       .Where(c => c.Subcategory.Category.Name == categoryName);
    return View("Index", auctions);
}

As you can tell, they both invoke the same View (is this action called 'to invoke a view'. What is it's proper name?).

@model IEnumerable<Cumavi.Models.Auction>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            IDSubcategory

            IDCity

            IDPerson

            Title

            TextBody

            ContactNumber

            AskingPrice

            AddressDirection

            LatestUpdateDate

            VisitCount

@foreach (var item in Model) {

            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })

            @item.IDSubcategory

            @item.IDCity

            @item.IDPerson

            @item.Title

            @item.TextBody

            @item.ContactNumber

            @String.Format("{0:F}", item.AskingPrice)

            @item.AddressDirection

            @String.Format("{0:g}", item.LatestUpdateDate)

            @item.VisitCount

}

They both inherit from the same Model.

My question is, am I doing things the right appropriate way? Or is this just a hack I managed to scrape together. Help me before I learn a bad habit.


问:
Creating html elements through nested JSON objects
So I've managed to successfully create HTML elements through JSON objects before, but now that I've changed my JSON objects to nested JSON, I am not able to reproduce the HTML elements accordingly. I am pretty new to programming so can anyone help me find out where I have gone wrong?

JSON File:

```<code>{
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
}
</code>```

Script:

```<code><script>
    $.ajax({
      url : "TestFiles.json",
      type : "post",
      contentType:"application/json",
      success : function(list){
          var divCol  = "<div class='col-md-offset-1 col-sm-5 col-md-5'>";
          var divWell = "<div class='well' style='position:relative'>";
          var divClose= "</div>";

          list.forEach(function(obj, index) {

            var title     = "<h4>"      + obj.ThreeG.title    + "</h4>";
            var linkStart = "<a href='" + obj.ThreeG.filePath + "' target='_blank'>" ;
            var image     = "<img data-toggle='tooltip' data-placement='left' title='Click to open data' src='" + obj.ThreeG.imagePath + "' height='100%' width='100%'/>"
            var linkEnd   =  "</a>";

            var div = divCol    +
            divWell     +
            title       +
            linkStart       +
            image       +
            linkEnd +
            divClose +
            divClose;

            console.log(obj);
           $("#test").append(div);

           })
        }
    });
  </script>
</code>```

答:
var obj = {
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
};

for(var i=0;i<obj.ThreeG.length;i++) {
var data = obj.ThreeG[i];//Take a reference here
console.log(data.title, data.filePath, data.imagePath);
}```

You cannot say obj.ThreeG.title since obj.ThreeG is an array. You need to use obj.ThreeG[0].title and obj.ThreeG[1].title etc.

Do some looping as shown above.

Body:
So I've managed to successfully create HTML elements through JSON objects before, but now that I've changed my JSON objects to nested JSON, I am not able to reproduce the HTML elements accordingly. I am pretty new to programming so can anyone help me find out where I have gone wrong?

JSON File:

{
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
}

Script:

Body:
var obj = {
  "ThreeG": [
    {
        "title":"Testing 1",
        "filePath":"https://example.com",
        "imagePath":"images/test.jpg"
    },
    {
        "title":"Testing 2",
        "filePath":"https://example.com",
        "imagePath":"images/test2.jpg"
    }
   ]
};

for(var i=0;i<obj.ThreeG.length;i++) {
var data = obj.ThreeG[i];//Take a reference here
console.log(data.title, data.filePath, data.imagePath);
}

You cannot say obj.ThreeG.title since obj.ThreeG is an array. You need to use obj.ThreeG[0].title and obj.ThreeG[1].title etc.

Do some looping as shown above.


问:
Angular 4 - displaying message after an asynchronous call
I have a page where I display a list of posts, and clicking on each of them I am displaying comments for that post. That works fine, what I wanted to add is to display a message if there are no comments for the post that was clicked. I have tried with setting up the template like this:

```<code><li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.title }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <ng-container *ngIf="currentPost.comments.length > 0;else message">
          <li *ngFor="let comment of currentPost.comments" class="document">
            <p>{{ comment.author }}</p>
            <p>{{ comment.text }}</p>
          </li>
        </ng-container>
        <ng-template #message>No comments for {{ post.title }}</ng-template>
      </ul>
  </li>
</code>```

And in the component, I have tried to first set the empty posts array, and an empty currentPost object with a property comments:

```<code>  posts: any[] = [];
  currentPost: any = {};
  currentPost.comments;
</code>```

And then in the method select I am fetching the comments like this:

```<code>this.postService.getComments(post.id)
      .subscribe(
        comments => this.currentPost.comments = comments,
      );
</code>```

But, if I do so, I get an error:

posts.component.html:7 ERROR TypeError: Cannot read property 'length'
  of undefined

How can I avoid that error, and check and display a message after a async call to the service method getComments?

答: Try something like currentPost.comments?.length in order to get rid of that error.

Body:
I have a page where I display a list of posts, and clicking on each of them I am displaying comments for that post. That works fine, what I wanted to add is to display a message if there are no comments for the post that was clicked. I have tried with setting up the template like this:

      {{ post.title }}

        <ng-container *ngIf="currentPost.comments.length > 0;else message">

{{ comment.author }}

{{ comment.text }}

        </ng-container>
        <ng-template #message>No comments for {{ post.title }}</ng-template>

And in the component, I have tried to first set the empty posts array, and an empty currentPost object with a property comments:

  posts: any[] = [];
  currentPost: any = {};
  currentPost.comments;

And then in the method select I am fetching the comments like this:

this.postService.getComments(post.id)
      .subscribe(
        comments => this.currentPost.comments = comments,
      );

But, if I do so, I get an error:

posts.component.html:7 ERROR TypeError: Cannot read property 'length'
  of undefined

How can I avoid that error, and check and display a message after a async call to the service method getComments?


问:
Adding class cotaining std::thread to a vector
Class declaration:

```<code>class cA{
private:
  std::thread t;
public:
  cA()=default;
};
</code>```

Somehere in another source file:

```<code>cA *a = new cA();
std::vector<cA> v;
v.push_back(*a);
</code>```

This results in the following error at compile time:

```<code>C2280: cA::cA(const cA &)': attempting to reference a deleted function
</code>```

I think it might have something to do with the fact that std::thread is missing a copy constructor and that the vector tries to make a copy of the cA object. Would anyone be willing to explain?

答:
You can also try </p>

```<code>v.push_back(std::move(*a));
</code>```

Body:
Class declaration:

class cA{
private:
  std::thread t;
public:
  cA()=default;
};

Somehere in another source file:

cA *a = new cA();
std::vector<cA> v;
v.push_back(*a);

This results in the following error at compile time:

C2280: cA::cA(const cA &)': attempting to reference a deleted function

I think it might have something to do with the fact that std::thread is missing a copy constructor and that the vector tries to make a copy of the cA object. Would anyone be willing to explain?

Body:
You can also try

v.push_back(std::move(*a));


问:
Meteor React: What is the simplest way to ensure a user is logged in before rendergin a page?

Situation:

I'm using React in a Meteor app.

My packages for authentication: accounts-password; useraccounts:core

I also use the gadicc:blaze-react-component to render the {{> atForm }} template in my react component =><Blaze template="atForm" />

Problem:

I don't know what should be the proper syntax to secure a specific page as described in the useraccounts guide but with react.

Lets suppose that I want to secure <Mypage /> imported from './mypage.jsx'

How can I call {{> ensureSignedIn template="myTemplate"}} and reaplace "myTemplate" by <Mypage /> ?

I tried <Blaze template="atForm" template={Mypage} /> without success...

Is it even possible to make something like this ?

答: You can check Meteor.userId() in ComponentWillMount(), set state and check it in render(). Or use some kind of checkings in your router


问:
Understand Java Debug SSL message
We have a java email application that connects to a Domino Mail Server. The application works if I test sending emails to Gmail or other mail servers. However when I changed the configuration and connect to Domino Mail server. It always gives the error below.

ERROR MESSAGE

```<code>JavaFX Application Thread, handling exception: javax.net.ssl.SSLHandshakeExcepti
on: Server chose SSLv3, but that protocol version is not enabled or not supporte
d by the client
</code>```

Tried to enabled the SSL debug using the command below to gather the SSL debug logs. Using this link tried to make sense as to what happened during the handshake. It seems that initially the client and server agreed to connect using TLSv1 show on ClientHello, TLSv1. But then server responded with ServerHello, SSLv3 where the error showed afterwards.
Can anyone help in analyzing this logs? Might provide some other ideas on how to fix this problem.

```<code>java -Djavax.net.debug=all -Dmail.socket.debug=true -Dhttps.protocols=TLSv1.1,TLSv1.2 -jar app.jar
</code>```

SSL Debug Logs

```<code>[DEBUG] 2017-06-08 11:24:08.046 [JavaFX Application Thread] ManEmailService
 - Load Mail Properties in into Javamail Session
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.s
mtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "164.39.7.92", port 25, isSSL false
220 mailserver ESMTP Service (Lotus Domino Release 8.5.3FP6) read
y at Thu, 8 Jun 2017 08:24:09 +0100
DEBUG SMTP: connected to host "164.39.7.92", port: 25

EHLO chol130
250-mailserver Hello chol130 ([10.210.136.21]), pleased to meet y
ou
250-TLS
250-HELP
250-STARTTLS
250-DSN
250-SIZE 52428800
250 PIPELINING
DEBUG SMTP: Found extension "TLS", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "SIZE", arg "52428800"
DEBUG SMTP: Found extension "PIPELINING", arg ""
STARTTLS
220 Ready to start TLS
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
EHLO chol130
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 for T
LSv1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for TLS
v1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 for TL
Sv1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 for TLSv
1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1

Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for TLSv1

Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
%% No cached client session
*** ClientHello, TLSv1
RandomCookie:  GMT: 1496840856 bytes = { 144, 229, 226, 93, 29, 240, 155, 120, 3
1, 198, 49, 168, 69, 96, 192, 17, 63, 179, 48, 152, 162, 151, 80, 52, 74, 227, 1
08, 212 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128
_CBC_SHA, **TLS_RSA_WITH_AES_128_CBC_SHA**, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS
_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WI
TH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3D
ES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_
SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_
DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1, sect28
3k1, sect283r1, sect409k1, sect409r1, sect571k1, sect571r1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension server_name, server_name: [type=host_name (0), value=gb.gb.t
p.com]
***
[write] MD5 and SHA1 hashes:  len = 140
0000: 01 00 00 88 03 01 59 38   FB 98 90 E5 E2 5D 1D F0  ......Y8.....]..
0010: 9B 78 1F C6 31 A8 45 60   C0 11 3F B3 30 98 A2 97  .x..1.E`..?.0...
0020: 50 34 4A E3 6C D4 00 00   1E C0 09 C0 13 00 2F C0  P4J.l........./.
0030: 04 C0 0E 00 33 00 32 C0   08 C0 12 00 0A C0 03 C0  ....3.2.........
0040: 0D 00 16 00 13 00 FF 01   00 00 41 00 0A 00 16 00  ..........A.....
0050: 14 00 17 00 18 00 19 00   09 00 0A 00 0B 00 0C 00  ................
0060: 0D 00 0E 00 16 00 0B 00   02 01 00 00 00 00 1D 00  ................
0070: 1B 00 00 18 67 62 61 68   65 6C 62 76 33 2E 67 62  ....gb.gb
0080: 2E 74 6E 74 70 6F 73 74   2E 63 6F 6D              .tp.com
JavaFX Application Thread, WRITE: TLSv1 Handshake, length = 140
[Raw write]: length = 145
0000: 16 03 01 00 8C 01 00 00   88 03 01 59 38 FB 98 90  ...........Y8...
0010: E5 E2 5D 1D F0 9B 78 1F   C6 31 A8 45 60 C0 11 3F  ..]...x..1.E`..?
0020: B3 30 98 A2 97 50 34 4A   E3 6C D4 00 00 1E C0 09  .0...P4J.l......
0030: C0 13 00 2F C0 04 C0 0E   00 33 00 32 C0 08 C0 12  .../.....3.2....
0040: 00 0A C0 03 C0 0D 00 16   00 13 00 FF 01 00 00 41  ...............A
0050: 00 0A 00 16 00 14 00 17   00 18 00 19 00 09 00 0A  ................
0060: 00 0B 00 0C 00 0D 00 0E   00 16 00 0B 00 02 01 00  ................
0070: 00 00 00 1D 00 1B 00 00   18 67 62 61 68 65 6C 62  .........gbahelb
0080: 76 33 2E 67 62 2E 74 6E   74 70 6F 73 74 2E 63 6F  v3.gb.tp.co
0090: 6D                                                 m
[Raw read]: length = 5
0000: 16 03 00 00 3A                                     ....:
[Raw read]: length = 58
0000: 02 00 00 36 03 00 59 60   96 A9 99 8D 55 45 0D 78  ...6..Y`....UE.x
0010: 0F B5 CE 45 42 77 D6 3F   DF 76 BD F5 F3 70 86 DD  ...EBw.?.v...p..
0020: 02 E8 E6 B3 7F 3E 10 75   40 52 B5 B0 21 51 62 6B  .....>.u@R..!Qbk
0030: F4 72 53 FC B0 1B FC 00   2F 00                    .rS...../.
JavaFX Application Thread, READ: SSLv3 Handshake, length = 58
*** **ServerHello, SSLv3**
RandomCookie:  GMT: 1499436457 bytes = { 153, 141, 85, 69, 13, 120, 15, 181, 206
, 69, 66, 119, 214, 63, 223, 118, 189, 245, 243, 112, 134, 221, 2, 232, 230, 179
, 127, 62 }
Session ID:  {117, 64, 82, 181, 176, 33, 81, 98, 107, 244, 114, 83, 252, 176, 27
, 252}
***Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA***
Compression Method: 0
***
JavaFX Application Thread, handling exception: javax.net.ssl.SSLHandshakeExcepti
on: Server chose SSLv3, but that protocol version is not enabled or not supporte
d by the client.
JavaFX Application Thread, SEND TLSv1.2 ALERT:  fatal, description = handshake_f
ailure
JavaFX Application Thread, WRITE: TLSv1.2 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 03 00 02 02 28                               ......(
JavaFX Application Thread, called closeSocket()
[ERROR] 2017-06-08 11:24:08.748 [JavaFX Application Thread] ManEmailService
 - Mail Message crap!!!javax.mail.MessagingException: Can't send command to SMTP
 host;
  nested exception is:
        javax.net.ssl.SSLHandshakeException: Server chose SSLv3, but that protoc
ol version is not enabled or not supported by the client.
</code>```

Javamail Properties file

```<code>#Set Mail Sender
sender.mail.from=sample@xwy.com
sender.mail.username=
sender.mail.password=
sender.mail.subject=subject

#Set Mail Sender Properties
mail.smtp.port=25
mail.smtp.host=<IP_ADDRESS>
#mail.smtp.ssl.trust=<IP_ADDRESS>
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.timeout=5000
#mail.smtp.ssl.enable=true
mail.debug=true
</code>```

答:
It seems that the server only supports the old and unsecure SSLv3 protocol.
If you still want to use this server (for instance because of being in a secure and sealed internal network) you need to either activate protocols >SSLv3 (like TLSv1 or TLSv1.1 etc) on the server side or tell your client to support SSLv3 as well.

On your java email application, try to set following system properties as arguments (as part of the java .. arguments):

```<code>-Dhttps.protocols=SSLv3,TLSv1,TLSv1.2
</code>```

If this does not help, most probably the SSL protocol is hardcoded in the source code.

For other options to set protocols on source code level, have a look here:
how to use TLSV1 or SSLV3 for first handshake(Client Hello) in Java?

//Update

What about this one in the property file: mail.smtps.ssl.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2

Source: https://discretemkt.wordpress.com/2014/11/15/javamail-enables-or-disables-sslv3/

Title: Understand Java Debug SSL message

Body:
We have a java email application that connects to a Domino Mail Server. The application works if I test sending emails to Gmail or other mail servers. However when I changed the configuration and connect to Domino Mail server. It always gives the error below.

ERROR MESSAGE

JavaFX Application Thread, handling exception: javax.net.ssl.SSLHandshakeExcepti
on: Server chose SSLv3, but that protocol version is not enabled or not supporte
d by the client

Tried to enabled the SSL debug using the command below to gather the SSL debug logs. Using this link tried to make sense as to what happened during the handshake. It seems that initially the client and server agreed to connect using TLSv1 show on ClientHello, TLSv1. But then server responded with ServerHello, SSLv3 where the error showed afterwards.
Can anyone help in analyzing this logs? Might provide some other ideas on how to fix this problem.

java -Djavax.net.debug=all -Dmail.socket.debug=true -Dhttps.protocols=TLSv1.1,TLSv1.2 -jar app.jar

SSL Debug Logs

[DEBUG] 2017-06-08 11:24:08.046 [JavaFX Application Thread] ManEmailService
 - Load Mail Properties in into Javamail Session
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.s
mtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "164.39.7.92", port 25, isSSL false
220 mailserver ESMTP Service (Lotus Domino Release 8.5.3FP6) read
y at Thu, 8 Jun 2017 08:24:09 +0100
DEBUG SMTP: connected to host "164.39.7.92", port: 25

EHLO chol130
250-mailserver Hello chol130 ([10.210.136.21]), pleased to meet y
ou
250-TLS
250-HELP
250-STARTTLS
250-DSN
250-SIZE 52428800
250 PIPELINING
DEBUG SMTP: Found extension "TLS", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "SIZE", arg "52428800"
DEBUG SMTP: Found extension "PIPELINING", arg ""
STARTTLS
220 Ready to start TLS
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
EHLO chol130
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 for T
LSv1
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 for TLS
v1
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 for TLSv1
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 for TL
Sv1
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 for TLSv
1
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 for TLSv1

Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 for TLSv1

Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
%% No cached client session
*** ClientHello, TLSv1
RandomCookie:  GMT: 1496840856 bytes = { 144, 229, 226, 93, 29, 240, 155, 120, 3
1, 198, 49, 168, 69, 96, 192, 17, 63, 179, 48, 152, 162, 151, 80, 52, 74, 227, 1
08, 212 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128
_CBC_SHA, **TLS_RSA_WITH_AES_128_CBC_SHA**, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS
_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WI
TH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3D
ES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_
SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_
DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, secp384r1, secp521r1, sect28
3k1, sect283r1, sect409k1, sect409r1, sect571k1, sect571r1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension server_name, server_name: [type=host_name (0), value=gb.gb.t
p.com]
***
[write] MD5 and SHA1 hashes:  len = 140
0000: 01 00 00 88 03 01 59 38   FB 98 90 E5 E2 5D 1D F0  ......Y8.....]..
0010: 9B 78 1F C6 31 A8 45 60   C0 11 3F B3 30 98 A2 97  .x..1.E`..?.0...
0020: 50 34 4A E3 6C D4 00 00   1E C0 09 C0 13 00 2F C0  P4J.l........./.
0030: 04 C0 0E 00 33 00 32 C0   08 C0 12 00 0A C0 03 C0  ....3.2.........
0040: 0D 00 16 00 13 00 FF 01   00 00 41 00 0A 00 16 00  ..........A.....
0050: 14 00 17 00 18 00 19 00   09 00 0A 00 0B 00 0C 00  ................
0060: 0D 00 0E 00 16 00 0B 00   02 01 00 00 00 00 1D 00  ................
0070: 1B 00 00 18 67 62 61 68   65 6C 62 76 33 2E 67 62  ....gb.gb
0080: 2E 74 6E 74 70 6F 73 74   2E 63 6F 6D              .tp.com
JavaFX Application Thread, WRITE: TLSv1 Handshake, length = 140
[Raw write]: length = 145
0000: 16 03 01 00 8C 01 00 00   88 03 01 59 38 FB 98 90  ...........Y8...
0010: E5 E2 5D 1D F0 9B 78 1F   C6 31 A8 45 60 C0 11 3F  ..]...x..1.E`..?
0020: B3 30 98 A2 97 50 34 4A   E3 6C D4 00 00 1E C0 09  .0...P4J.l......
0030: C0 13 00 2F C0 04 C0 0E   00 33 00 32 C0 08 C0 12  .../.....3.2....
0040: 00 0A C0 03 C0 0D 00 16   00 13 00 FF 01 00 00 41  ...............A
0050: 00 0A 00 16 00 14 00 17   00 18 00 19 00 09 00 0A  ................
0060: 00 0B 00 0C 00 0D 00 0E   00 16 00 0B 00 02 01 00  ................
0070: 00 00 00 1D 00 1B 00 00   18 67 62 61 68 65 6C 62  .........gbahelb
0080: 76 33 2E 67 62 2E 74 6E   74 70 6F 73 74 2E 63 6F  v3.gb.tp.co
0090: 6D                                                 m
[Raw read]: length = 5
0000: 16 03 00 00 3A                                     ....:
[Raw read]: length = 58
0000: 02 00 00 36 03 00 59 60   96 A9 99 8D 55 45 0D 78  ...6..Y`....UE.x
0010: 0F B5 CE 45 42 77 D6 3F   DF 76 BD F5 F3 70 86 DD  ...EBw.?.v...p..
0020: 02 E8 E6 B3 7F 3E 10 75   40 52 B5 B0 21 51 62 6B  .....>.u@R..!Qbk
0030: F4 72 53 FC B0 1B FC 00   2F 00                    .rS...../.
JavaFX Application Thread, READ: SSLv3 Handshake, length = 58
*** **ServerHello, SSLv3**
RandomCookie:  GMT: 1499436457 bytes = { 153, 141, 85, 69, 13, 120, 15, 181, 206
, 69, 66, 119, 214, 63, 223, 118, 189, 245, 243, 112, 134, 221, 2, 232, 230, 179
, 127, 62 }
Session ID:  {117, 64, 82, 181, 176, 33, 81, 98, 107, 244, 114, 83, 252, 176, 27
, 252}
***Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA***
Compression Method: 0
***
JavaFX Application Thread, handling exception: javax.net.ssl.SSLHandshakeExcepti
on: Server chose SSLv3, but that protocol version is not enabled or not supporte
d by the client.
JavaFX Application Thread, SEND TLSv1.2 ALERT:  fatal, description = handshake_f
ailure
JavaFX Application Thread, WRITE: TLSv1.2 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 03 00 02 02 28                               ......(
JavaFX Application Thread, called closeSocket()
[ERROR] 2017-06-08 11:24:08.748 [JavaFX Application Thread] ManEmailService
 - Mail Message crap!!!javax.mail.MessagingException: Can't send command to SMTP
 host;
  nested exception is:
        javax.net.ssl.SSLHandshakeException: Server chose SSLv3, but that protoc
ol version is not enabled or not supported by the client.

Javamail Properties file

#Set Mail Sender
sender.mail.from=sample@xwy.com
sender.mail.username=
sender.mail.password=
sender.mail.subject=subject

#Set Mail Sender Properties
mail.smtp.port=25
mail.smtp.host=<IP_ADDRESS>
#mail.smtp.ssl.trust=<IP_ADDRESS>
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.timeout=5000
#mail.smtp.ssl.enable=true
mail.debug=true

Body:
It seems that the server only supports the old and unsecure SSLv3 protocol.
If you still want to use this server (for instance because of being in a secure and sealed internal network) you need to either activate protocols >SSLv3 (like TLSv1 or TLSv1.1 etc) on the server side or tell your client to support SSLv3 as well.

On your java email application, try to set following system properties as arguments (as part of the java .. arguments):

-Dhttps.protocols=SSLv3,TLSv1,TLSv1.2

If this does not help, most probably the SSL protocol is hardcoded in the source code.

For other options to set protocols on source code level, have a look here:
how to use TLSV1 or SSLV3 for first handshake(Client Hello) in Java?

//Update

What about this one in the property file: mail.smtps.ssl.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2

Source: https://discretemkt.wordpress.com/2014/11/15/javamail-enables-or-disables-sslv3/


问:
Binary representation of a IP with inet_aton()
When I use inet_aton() like this

```<code>packed_ip_addr = socket.inet_aton(ip_addr)
</code>```

and print the value of packed IP:

```<code>print "Packed IP: %s" %packed_ip_addr
</code>```

Nothing shown in the screen. How can I print the exact binary format of IP address?

Body:
When I use inet_aton() like this

packed_ip_addr = socket.inet_aton(ip_addr)

and print the value of packed IP:

print "Packed IP: %s" %packed_ip_addr

Nothing shown in the screen. How can I print the exact binary format of IP address?

Body:
Try this:

>>> ip = "192.168.137.39"
>>> print(bin(sum([int(k) * v for k, v in zip(ip.split("."), [1 << 24, 1 << 16, 1 << 8, 1])])))
0b11000000101010001000100100100111


问:
Doctrine select all users that manage other users via column
Maybe I am missing something completely, but I cannot get it working. I only want to select User objects that are linked to User objects.

User:

```<code>class User implements AdvancedUserInterface, \Serializable
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

// other fields ...

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $firstManager;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $secondManager;

}
</code>```

I want to select those who are firstManager or secondManager for a User. Sounds simple eh?

I thought, this would do:

```<code>public function findAllManagers()
{
    $qb = $this->createQueryBuilder('user')
        ->join('user.firstManager', 'first_manager')
        ->join('user.secondManager', 'second_manager')
        ->orWhere('first_manager = user')
        ->orWhere('second_manager = user');
    $qb = $qb->getQuery();

    return $qb->getResult();
}
</code>```

But only got one result, not all three I needed. I think this is valid SQL?

答:
For what i see your sql query should look like:

```<code>SELECT user.* FROM user_table user
INNER JOIN user_table first_manager ON first_manager.id = user.first_manager_id
INNER JOIN user_table second_manager ON second_manager.id = user.second_manager_id
WHERE first_manager.id = user.id
OR second_manager.id = user.id
</code>```

The result of this would be users who are their own first or second manager.

I think what you are looking for is this:

```<code>public function findAllManagers()
{
    $qb = $this->createQueryBuilder('m')
        ->leftJoin('u1', 'AppBundle\Entity\User', 'WITH', m = u1.firstManager)
        ->leftJoin('u2', 'AppBundle\Entity\User', 'WITH', m = u2.secondManager)
        ->where('u1.firstManager IS NOT NULL')
        ->orWhere('u2.secondManager IS NOT NULL')
        ->getQuery()
    ;

    return $qb->getResult();
}
</code>```

The equivalent SQL query should be:

```<code>SELECT m.* FROM user_table m
LEFT JOIN user_table u1 ON u1.first_manager_id = m.id
LEFT JOIN user_table u2 ON u2.second_manager_id = m.id
WHERE u1.first_manager_id IS NOT NULL
OR u2.second_manager_id IS NOT NULL
</code>```

Body:
Maybe I am missing something completely, but I cannot get it working. I only want to select User objects that are linked to User objects.

User:

class User implements AdvancedUserInterface, \Serializable
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

// other fields ...

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $firstManager;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
 */
private $secondManager;

}

I want to select those who are firstManager or secondManager for a User. Sounds simple eh?

I thought, this would do:

public function findAllManagers()
{
    $qb = $this->createQueryBuilder('user')
        ->join('user.firstManager', 'first_manager')
        ->join('user.secondManager', 'second_manager')
        ->orWhere('first_manager = user')
        ->orWhere('second_manager = user');
    $qb = $qb->getQuery();

    return $qb->getResult();
}

But only got one result, not all three I needed. I think this is valid SQL?

Body:
For what i see your sql query should look like:

SELECT user.* FROM user_table user
INNER JOIN user_table first_manager ON first_manager.id = user.first_manager_id
INNER JOIN user_table second_manager ON second_manager.id = user.second_manager_id
WHERE first_manager.id = user.id
OR second_manager.id = user.id

The result of this would be users who are their own first or second manager.

I think what you are looking for is this:

public function findAllManagers()
{
    $qb = $this->createQueryBuilder('m')
        ->leftJoin('u1', 'AppBundle\Entity\User', 'WITH', m = u1.firstManager)
        ->leftJoin('u2', 'AppBundle\Entity\User', 'WITH', m = u2.secondManager)
        ->where('u1.firstManager IS NOT NULL')
        ->orWhere('u2.secondManager IS NOT NULL')
        ->getQuery()
    ;

    return $qb->getResult();
}

The equivalent SQL query should be:

SELECT m.* FROM user_table m
LEFT JOIN user_table u1 ON u1.first_manager_id = m.id
LEFT JOIN user_table u2 ON u2.second_manager_id = m.id
WHERE u1.first_manager_id IS NOT NULL
OR u2.second_manager_id IS NOT NULL


问:
Hide Angular UI Bootstrap popover when clicking outside of it
I am trying to manually close a bootstrap popover to get it to close when I click anywhere on the document or body that isn't the popover.

The closest thing I have found to accomplishing this is to create a directive (found this answer) but this is for a manual trigger if a variable is true or false.

Could anyone help me figure out how to to get it to close if I click on anything that isn't the popover?

I don't mind using jQuery $(document).click(function(e){}); I just have no clue how to call a close.

```<code><div id="new_button" popover-template="plusButtonURL" popover-placement="right" popover-append-to-body="true" popover-animation="false">+</div>
</code>```

Normally popover-trigger="focus" would do the trick, however my popover contains content that needs to be clicked on. I have an ng-click inside my popover that get's ignored if I use the focus trigger so I am looking for a not-so-conventional way to get around that.

答:
What about the 'outsideClick' option in the '$uibTooltipProvider' setTriggers method. Documentation says "The outsideClick trigger will cause the tooltip to toggle on click, and hide when anything else is clicked."
Documentation

Body:
I am trying to manually close a bootstrap popover to get it to close when I click anywhere on the document or body that isn't the popover.

The closest thing I have found to accomplishing this is to create a directive (found this answer) but this is for a manual trigger if a variable is true or false.

Could anyone help me figure out how to to get it to close if I click on anything that isn't the popover?

I don't mind using jQuery $(document).click(function(e){}); I just have no clue how to call a close.

+

Normally popover-trigger="focus" would do the trick, however my popover contains content that needs to be clicked on. I have an ng-click inside my popover that get's ignored if I use the focus trigger so I am looking for a not-so-conventional way to get around that.


问:
Form control with angular.js
I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.

HTML:

```<code><!DOCTYPE html>
    <html lang="en" ng-app="file">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
        <script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script types=text/javascript" src="formLoops.js"></script>
        <title>Title</title>
    </head>
    <body ng-controller="PersonalDetailsController as person">
        <p ng-repeat="info in person.details">{{info.forename}}</p>

    <form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">
        <blockquote>
            <p>{{dataCtrl.person.forename}}</p>
            <p>{{dataCtrl.person.surname}}</p>
        </blockquote>

        <label>Forename:</label>
        <input ng-model="dataCtrl.person.forename"/>
        <label>Surname:</label>
        <input ng-model="dataCtrl.person.surname"/>
        <input type="submit" value="submit"/>

    </form>

    </body>
    </html>
</code>```

JS:

```<code>var app = angular.module("file", []);

app.controller("PersonalDetailsController", function() {
  this.details = personalDetails;
});

app.controller("DataEntryController", function() {
  this.person = {};
  this.addPerson = function(person) {
    person.personalDetails.push(this.person);
  };
});

var personalDetails = [{
    forename: "John",
    surname: "Doe"
  },
  {
    forename: "John",
    surname: "Smith"
  }
];
</code>```

答:
since you are using the controllerAs use the controllerAs reference when you are calling the function. like ng-submit="dataCtrl.addPerson(person)"

```<code><form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="dataCtrl.addPerson(person)">
</code>```

Title: Form control with angular.js

Body:
I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.

HTML:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

        <title>Title</title>

{{info.forename}}

    <form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">

{{dataCtrl.person.forename}}

{{dataCtrl.person.surname}}

        Forename:
        <input ng-model="dataCtrl.person.forename"/>
        Surname:
        <input ng-model="dataCtrl.person.surname"/>
        <input type="submit" value="submit"/>

    </form>

JS:

var app = angular.module("file", []);

app.controller("PersonalDetailsController", function() {
  this.details = personalDetails;
});

app.controller("DataEntryController", function() {
  this.person = {};
  this.addPerson = function(person) {
    person.personalDetails.push(this.person);
  };
});

var personalDetails = [{
    forename: "John",
    surname: "Doe"
  },
  {
    forename: "John",
    surname: "Smith"
  }
];

Body:
since you are using the controllerAs use the controllerAs reference when you are calling the function. like ng-submit="dataCtrl.addPerson(person)"

<form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="dataCtrl.addPerson(person)">


问:
PostgreSQL Installation on Windows 8.1 - database cluster initialisation failed
I'm trying to install PostgreSQL 9.6.2 on my computer via installation package from EnterpriseDB.com. And everytime I get this error at the end:

```<code>Problem running post-install step. Installation may not complete correctly
The database cluster initialisation failed.
</code>```

I have done some googling and found a few "solutions" to this issue, but none of them worked for me. I'm using Windows 8.1, the "normal", not "Pro" edition. Most of these solutions were for Win 7 or Vista. Reason for installing PostgreSQL is using PostGIS for my attempt at creating map application.

I tried this one - https://cppoon.wordpress.com/2013/03/07/how-to-solve-problem-running-post-install-step-postgresql-window/

It's written for Win 7 Pro, so I had to do few things diffrently - for example compmgmt.msc doesn't contain anything about Users and Groups, so I went to lusrmgr.msc - but it said to me that it's not usable for my version of Windows (i would probably need Pro version). So i created new user via Settings, granted him admin rights via Control panel and tried to install it via CMD as written in the instructions. Well, didn't work, still got the same error.

Then I tried this - http://www.geekscribes.net/blog/2009/04/22/postgresql-database-cluster-initialisation-failed-solution/ .

It's for Windows Vista, but I gave it shot anyway. At first, I installed it in different folder outside Program Files (C:\Hry\postgres), got the same error. Then I tried to create user postgres there as written in the article, but when I wanted to assign rights to the folder, I got error with stm like this (my Win is not in english, so I'm translating it in the best way i can):

```<code>Error occured during attempt to use security information for:
C:\Hry\postgres\bin
Unable to load list of objects in the container. Access denied.
</code>```

And the same one for every sub-folder of postgres. I still tried to re-run installation into the same folder as advised in the article, but nothing, still same error.

I'm including the last lines from install-postgresql log, if it will help someone with identifying where the problem is:

```<code>Called CreateDirectory(C:\Hry\postgres\data)...
Called CreateDirectory(C:\Hry\postgres)...
WScript.Network initialized...
strParentOfDataDirC:\Hry\postgres
logged in userPETR\Petr
Called AclCheck(C:\Hry\postgres\data)
Called IsVistaOrNewer()...
'winmgmts' object initialized...
Version:6.3
MajorVersion:6
Executing icacls to ensure the PETR\Petr account can read the path     C:\Hry\postgres\data
Executing batch file 'rad1F88F.bat'...
'icacls' is not recognized as an internal or external command,
operable program or batch file.

Called IsVistaOrNewer()...
'winmgmts' object initialized...
Version:6.3
MajorVersion:6
Ensuring we can write to the data directory (using icacls) to  PETR\Petr:
Executing batch file 'rad1F88F.bat'...
'icacls' is not recognized as an internal or external command, operable program or batch file.

Failed to ensure the data directory is accessible (C:\Hry\postgres\data)
Called Die(Failed to initialise the database cluster with initdb)...
Failed to initialise the database cluster with initdb

Script stderr:
 Program ended with an error exit code

Error running cscript //NoLogo     "C:\Hry\postgres/installer/server/initcluster.vbs" "NT AUTHORITY\NetworkService"     "postgres" "****" "C:\Hry\postgres" "C:\Hry\postgres\data" 5432 "DEFAULT" 0:     Program ended with an error exit code
Problem running post-install step. Installation may not complete correctly
 The database cluster initialisation failed.
</code>```

At this point, I've spent a few hours on this and I'm running out of ideas. Any help would be greatly appreciated. Thanks very much in advance.

答: I got the same problem before, solution for me is to install postgresql in usual place ("C:\Program Files") but the data in another drive that can be accessed by all Users on your computer.

Body:
I'm trying to install PostgreSQL 9.6.2 on my computer via installation package from EnterpriseDB.com. And everytime I get this error at the end:

Problem running post-install step. Installation may not complete correctly
The database cluster initialisation failed.

I have done some googling and found a few "solutions" to this issue, but none of them worked for me. I'm using Windows 8.1, the "normal", not "Pro" edition. Most of these solutions were for Win 7 or Vista. Reason for installing PostgreSQL is using PostGIS for my attempt at creating map application.

I tried this one - https://cppoon.wordpress.com/2013/03/07/how-to-solve-problem-running-post-install-step-postgresql-window/

It's written for Win 7 Pro, so I had to do few things diffrently - for example compmgmt.msc doesn't contain anything about Users and Groups, so I went to lusrmgr.msc - but it said to me that it's not usable for my version of Windows (i would probably need Pro version). So i created new user via Settings, granted him admin rights via Control panel and tried to install it via CMD as written in the instructions. Well, didn't work, still got the same error.

Then I tried this - http://www.geekscribes.net/blog/2009/04/22/postgresql-database-cluster-initialisation-failed-solution/ .

It's for Windows Vista, but I gave it shot anyway. At first, I installed it in different folder outside Program Files (C:\Hry\postgres), got the same error. Then I tried to create user postgres there as written in the article, but when I wanted to assign rights to the folder, I got error with stm like this (my Win is not in english, so I'm translating it in the best way i can):

Error occured during attempt to use security information for:
C:\Hry\postgres\bin
Unable to load list of objects in the container. Access denied.

And the same one for every sub-folder of postgres. I still tried to re-run installation into the same folder as advised in the article, but nothing, still same error.

I'm including the last lines from install-postgresql log, if it will help someone with identifying where the problem is:

Called CreateDirectory(C:\Hry\postgres\data)...
Called CreateDirectory(C:\Hry\postgres)...
WScript.Network initialized...
strParentOfDataDirC:\Hry\postgres
logged in userPETR\Petr
Called AclCheck(C:\Hry\postgres\data)
Called IsVistaOrNewer()...
'winmgmts' object initialized...
Version:6.3
MajorVersion:6
Executing icacls to ensure the PETR\Petr account can read the path     C:\Hry\postgres\data
Executing batch file 'rad1F88F.bat'...
'icacls' is not recognized as an internal or external command,
operable program or batch file.

Called IsVistaOrNewer()...
'winmgmts' object initialized...
Version:6.3
MajorVersion:6
Ensuring we can write to the data directory (using icacls) to  PETR\Petr:
Executing batch file 'rad1F88F.bat'...
'icacls' is not recognized as an internal or external command, operable program or batch file.

Failed to ensure the data directory is accessible (C:\Hry\postgres\data)
Called Die(Failed to initialise the database cluster with initdb)...
Failed to initialise the database cluster with initdb

Script stderr:
 Program ended with an error exit code

Error running cscript //NoLogo     "C:\Hry\postgres/installer/server/initcluster.vbs" "NT AUTHORITY\NetworkService"     "postgres" "****" "C:\Hry\postgres" "C:\Hry\postgres\data" 5432 "DEFAULT" 0:     Program ended with an error exit code
Problem running post-install step. Installation may not complete correctly
 The database cluster initialisation failed.

At this point, I've spent a few hours on this and I'm running out of ideas. Any help would be greatly appreciated. Thanks very much in advance.


问:
prevent default of click event when keyup event ocuurs in angular2
In search input field when keyup event is fired, data showing, after keyup event is fire again click event is working, but I want once keyup or click is fired other one will not work.

Here is my form in header.html

```<code><form>
     <div class="box">
         <div class="container-1">
            <input type="search" id="search" placeholder="Type
                 your search..." name="searchStr" (keyup.enter)="searchKey(input.value)"
                [(ngModel)]="searchStr" #input>
            <a (click)="searchKey(input.value)"><img
              src="/assets/search.png" class="search-img"></a>
        </div>
     </div>
</form>
</code>```

Here is my header.component.ts

```<code>searchKey(value: any) {
    console.log(value);
    this.router.navigate(['search', { searchkey : value }]);
}
</code>```

thank you in advance.

答:
Try to set a flag variable which will checks whether to search or not like,

```<code>export ... {

    flag = true;

    searchKey(value: any) {
        console.log(value);
        this.flag && this.router.navigate(['search', { searchkey : value }]);
        this.flag=false;
    }

    // don't forget to add a condition when flag must be set to true.
}
</code>```

Hope this will help you.

Body:
In search input field when keyup event is fired, data showing, after keyup event is fire again click event is working, but I want once keyup or click is fired other one will not work.

Here is my form in header.html

<form>

            <input type="search" id="search" placeholder="Type
                 your search..." name="searchStr" (keyup.enter)="searchKey(input.value)"
                [(ngModel)]="searchStr" #input>

</form>

Here is my header.component.ts

searchKey(value: any) {
    console.log(value);
    this.router.navigate(['search', { searchkey : value }]);
}

thank you in advance.

Body:
Try to set a flag variable which will checks whether to search or not like,

export ... {

    flag = true;

    searchKey(value: any) {
        console.log(value);
        this.flag && this.router.navigate(['search', { searchkey : value }]);
        this.flag=false;
    }

    // don't forget to add a condition when flag must be set to true.
}

Hope this will help you.


问:
Body overflow hidden problem in Internet Explorer 7
I need to apply the overflow:hidden to the body of a page with CSS, but is doesn't work in Internet Explorer 7.
I've read about this topic but always with divs.
How can I make this work to Internet Explorer 7? I don't mind using jQuery.

答:
See here: http://www.artmov.com/dev/snippets/apply-overflow-x-overflow-y-to-body-in-ie7-ie6-84/:

Applying overflow-x:hidden or overflow-y:hidden; to the body element of the document will not work. The overflow-x:hidden or overflow-y:hidden must be applied to the html element, not body element.


问:
How to get text with some specific tags' text together in a tag by scrapy in python?
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

```<code><div class="user-info">
    <p class="user-img">
        something in p tag
    </p>
    <em>text</em> data I want
    <a href="#">
        something in a tag
    </a>
</div>
</code>```

I want to get the text data I want only. But the text is in the tag . So if I use div[contains(@class, "user-info")]/text(), I can get data I want only. If I use div[contains(@class, "user-info")]/node() I get all the tags inside div.user-info, and also div[contains(@class, "user-info")]/node()/text(). So the question is, how can I get the text and the data I want together to be text data I want?

答:
If you want all nodes after
 and before something in a tag, you can use the following axis:

the following axis contains all nodes in the same document as the context node that are after the context node in document order, excluding any descendants and excluding attribute nodes and namespace nodes

```<code>>>> s = scrapy.Selector(text='''<div class="user-info">
...     <p class="user-img">
...         something in p tag
...     </p>
...     <em>text</em> data I want
...     <a href="#">
...         something in a tag
...     </a>
... </div>''')
>>> s.css('p.user-img')
[<Selector xpath="descendant-or-self::p[@class and contains(concat(' ', normalize-space(@class), ' '), ' user-img ')]" data='<p class="user-img">\n        something i'>]

>>> s.css('p.user-img').xpath('following::text()[following::a]').getall()
['\n    ', 'text', ' data I want\n    ']

>>> ''.join(s.css('p.user-img').xpath('following::text()[following::a]').getall())
'\n    text data I want\n    '
</code>```

Body:
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

        something in p tag

    text data I want

        something in a tag

I want to get the text data I want only. But the text is in the tag . So if I use div[contains(@class, "user-info")]/text(), I can get data I want only. If I use div[contains(@class, "user-info")]/node() I get all the tags inside div.user-info, and also div[contains(@class, "user-info")]/node()/text(). So the question is, how can I get the text and the data I want together to be text data I want?

Body:
If you want all nodes after <p class="user-img"> and before <a href="#">something in a tag</a>, you can use the following axis:

the following axis contains all nodes in the same document as the context node that are after the context node in document order, excluding any descendants and excluding attribute nodes and namespace nodes

>>> s = scrapy.Selector(text='''<div class="user-info">
...     <p class="user-img">
...         something in p tag
...     </p>
...     <em>text</em> data I want
...     <a href="#">
...         something in a tag
...     </a>
... </div>''')
>>> s.css('p.user-img')
[<Selector xpath="descendant-or-self::p[@class and contains(concat(' ', normalize-space(@class), ' '), ' user-img ')]" data='<p class="user-img">\n        something i'>]

>>> s.css('p.user-img').xpath('following::text()[following::a]').getall()
['\n    ', 'text', ' data I want\n    ']

>>> ''.join(s.css('p.user-img').xpath('following::text()[following::a]').getall())
'\n    text data I want\n    '


问:
Python pandas: add new columns based on the existed a column value, and set the value of new columns as 1 or 0
I have a dataframe named df as following:

```<code>ticker        class_n
  1              a
  2              b
  3              c
  4              d
  5              e
  6              f
  7              a
  8              b
  ............................
</code>```

I want to add new columns to this dataframe, the new columns names is the value of unique category of class_n(I mean no repeat class_n). Further, the value of new columns is 1 (if the value of class_n is same with column name), other is 0.
for example as the following dataframe. I want to get the new dataframe as following:

```<code>ticer  class_n   a     b    c   d   e    f
  1       a      1     0    0   0   0    0
  2       b      0     1    0   0   0    0
  3       c      0     0    1   0   0    0
  4       d      0     0    0   1   0    0
  5       e      0     0    0   0   1    0
  6       f      0     0    0   0   0    1
  7       a      1     0    0   0   0    0
  8       b      0     1    0   0   0    0
</code>```

My code is following:

```<code>lst_class = list(set(list(df['class_n'])))
for cla in lst_class:
    df[c] = 0
    df.loc[df['class_n'] is cla, cla] =1
</code>```

but there is error:

```<code>KeyError: 'cannot use a single bool to index into setitem'
</code>```

Thanks!

答:
Use pd.get_dummies

```<code>df.join(pd.get_dummies(df.class_n))

   ticker class_n  a  b  c  d  e  f
0       1       a  1  0  0  0  0  0
1       2       b  0  1  0  0  0  0
2       3       c  0  0  1  0  0  0
3       4       d  0  0  0  1  0  0
4       5       e  0  0  0  0  1  0
5       6       f  0  0  0  0  0  1
6       7       a  1  0  0  0  0  0
7       8       b  0  1  0  0  0  0
</code>```

Or the same thing but a little more manually

```<code>f, u = pd.factorize(df.class_n.values)
d = pd.DataFrame(np.eye(u.size, dtype=int)[f], df.index, u)
df.join(d)

   ticker class_n  a  b  c  d  e  f
0       1       a  1  0  0  0  0  0
1       2       b  0  1  0  0  0  0
2       3       c  0  0  1  0  0  0
3       4       d  0  0  0  1  0  0
4       5       e  0  0  0  0  1  0
5       6       f  0  0  0  0  0  1
6       7       a  1  0  0  0  0  0
7       8       b  0  1  0  0  0  0
</code>```

Body:
I have a dataframe named df as following:

ticker        class_n
  1              a
  2              b
  3              c
  4              d
  5              e
  6              f
  7              a
  8              b
  ............................

I want to add new columns to this dataframe, the new columns names is the value of unique category of class_n(I mean no repeat class_n). Further, the value of new columns is 1 (if the value of class_n is same with column name), other is 0.
for example as the following dataframe. I want to get the new dataframe as following:

ticer  class_n   a     b    c   d   e    f
  1       a      1     0    0   0   0    0
  2       b      0     1    0   0   0    0
  3       c      0     0    1   0   0    0
  4       d      0     0    0   1   0    0
  5       e      0     0    0   0   1    0
  6       f      0     0    0   0   0    1
  7       a      1     0    0   0   0    0
  8       b      0     1    0   0   0    0

My code is following:

lst_class = list(set(list(df['class_n'])))
for cla in lst_class:
    df[c] = 0
    df.loc[df['class_n'] is cla, cla] =1

but there is error:

KeyError: 'cannot use a single bool to index into setitem'

Thanks!

Body:
Use pd.get_dummies

df.join(pd.get_dummies(df.class_n))

   ticker class_n  a  b  c  d  e  f
0       1       a  1  0  0  0  0  0
1       2       b  0  1  0  0  0  0
2       3       c  0  0  1  0  0  0
3       4       d  0  0  0  1  0  0
4       5       e  0  0  0  0  1  0
5       6       f  0  0  0  0  0  1
6       7       a  1  0  0  0  0  0
7       8       b  0  1  0  0  0  0

Or the same thing but a little more manually

f, u = pd.factorize(df.class_n.values)
d = pd.DataFrame(np.eye(u.size, dtype=int)[f], df.index, u)
df.join(d)

   ticker class_n  a  b  c  d  e  f
0       1       a  1  0  0  0  0  0
1       2       b  0  1  0  0  0  0
2       3       c  0  0  1  0  0  0
3       4       d  0  0  0  1  0  0
4       5       e  0  0  0  0  1  0
5       6       f  0  0  0  0  0  1
6       7       a  1  0  0  0  0  0
7       8       b  0  1  0  0  0  0