问:
Swift 4 alternative if let
I have this code, it checks if a file exists in the document directory, if it does it used this to set up the data for the controller, if it doesn't it uses a file supplier in the bundle, and if also that fails it set up an empty view controller.

Is there a way to conditionally set the url variable so that I can write the parse(fromFile:) method once instead of in an if else? The most intuitive way would appear to be if let url = something || let url = somethingElse then perform in the parse(fromFile: url) in the brackets, but it appears that it's not possible with swift.

```<code>if let url = try? FileManager().url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: true).appendingPathComponent("database.json") {
    parse(fromFile: url)
} else if let url = Bundle.main.url(forResource: "database", withExtension: "json") {
    parse(fromFile: url)
} else {
    setUpWithNothing()
}
</code>```

答:
Since you're doing the same thing in the first two cases and something different in the second, this is a good candidate for it's own function:

```<code>func databaseFileURL() -> URL? {
    if let url = try? FileManager().url(for: .documentDirectory, in: .userDomainMask,
                                        appropriateFor: nil, create: true) {
        return url.appendingPathComponent("database.json")
    }
    else {
        return Bundle.main.url(forResource: "database", withExtension: "json")
    }
}
</code>```

and then you can just do

```<code>if let url = databaseFileURL() {
    parse(fromFile: url)
} else {
    setUpWithNothing()
}
</code>```

It nicely separates concerns and makes it cleaner and clearer at the point of use. And if you need to do anything else with the file you can just call the function rather than copy-pasting the logic.

Title: Swift 4 alternative if let

Body:
I have this code, it checks if a file exists in the document directory, if it does it used this to set up the data for the controller, if it doesn't it uses a file supplier in the bundle, and if also that fails it set up an empty view controller.

Is there a way to conditionally set the url variable so that I can write the parse(fromFile:) method once instead of in an if else? The most intuitive way would appear to be if let url = something || let url = somethingElse then perform in the parse(fromFile: url) in the brackets, but it appears that it's not possible with swift.

if let url = try? FileManager().url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: true).appendingPathComponent("database.json") {
    parse(fromFile: url)
} else if let url = Bundle.main.url(forResource: "database", withExtension: "json") {
    parse(fromFile: url)
} else {
    setUpWithNothing()
}

Body:
Since you're doing the same thing in the first two cases and something different in the second, this is a good candidate for it's own function:

func databaseFileURL() -> URL? {
    if let url = try? FileManager().url(for: .documentDirectory, in: .userDomainMask,
                                        appropriateFor: nil, create: true) {
        return url.appendingPathComponent("database.json")
    }
    else {
        return Bundle.main.url(forResource: "database", withExtension: "json")
    }
}

and then you can just do

if let url = databaseFileURL() {
    parse(fromFile: url)
} else {
    setUpWithNothing()
}

It nicely separates concerns and makes it cleaner and clearer at the point of use. And if you need to do anything else with the file you can just call the function rather than copy-pasting the logic.


来源: stackexchange

问:
How to get the warning message as a string when validating XML with schemaValidate() in PHP?
I have this code to validate an XML file against an XSD file:

```<code>$file = 'test.xml';
$schema = 'test.xsd';
$dom = new DOMDocument;
$dom->load($file);

if ($dom->schemaValidate($schema)) {
    print "$file is valid.\n";
} else {
    print "$file is invalid.\n";
}
</code>```

If the xml file is invalid, then it says that it is invalid.
The reason it is invalid (e.g. price is not an integer), however, is only given in a PHP warning, which I have to suppress so that user doesn't see it (with error_reporting(0)).

How can I get the text of that message and pass it on to the user, as I would do in C# with a try/catch?

答:
here is how i did it:

```<code>$errs = [ ];
set_error_handler ( function ($severity, $message, $file, $line) use (&$errs) {
    $errs [] = $message;
} );
$validated = $domd->schemaValidate ( 'factinv-3-0.xsd' );
restore_error_handler ();
</code>```

error descriptions are now in $errs, if any.

ContentLicense: CC BY-SA 2.5

Body:
I have this code to validate an XML file against an XSD file:

$file = 'test.xml';
$schema = 'test.xsd';
$dom = new DOMDocument;
$dom->load($file);

if ($dom->schemaValidate($schema)) {
    print "$file is valid.\n";
} else {
    print "$file is invalid.\n";
}

If the xml file is invalid, then it says that it is invalid.
The reason it is invalid (e.g. price is not an integer), however, is only given in a PHP warning, which I have to suppress so that user doesn't see it (with error_reporting(0)).

How can I get the text of that message and pass it on to the user, as I would do in C# with a try/catch?

Body:
here is how i did it:

$errs = [ ];
set_error_handler ( function ($severity, $message, $file, $line) use (&$errs) {
    $errs [] = $message;
} );
$validated = $domd->schemaValidate ( 'factinv-3-0.xsd' );
restore_error_handler ();

error descriptions are now in $errs, if any.

ContentLicense: CC BY-SA 3.0


问:
django accessing errors
I have the following:

```<code>{% if formDetails.errors %}
{% for key, value in formDetails.errors.items %}
{% for error in value %}
    <div class="ui-widget" id="id-error">
        <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
            <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
            <strong>{{ key }}:</strong> {{ error }}</p>
        </div>
    </div>
{% endfor %}
{% endfor %}
</code>```

But unfortunately key gives me the name of the model field (the one that's lowercase with underscores). How can I get the nice looking name like field.label_tag?

答:
The form.errors template variable is a list not a dictionary, so you should access it as follows:

```<code>{% for error in form.errors %}
    <li>{{ error }}</li>
{% endfor %}
</code>```

In addition it contains form wide errors raised by the clean() method on the Form object you are dealing with. Validation errors raised by the individual fields, can be accessed like this:

```<code>{% for field in form %}
    {% for error in field.errors %}
        {{ error }}
    {% endfor %}
    {{ field.label_tag }}
{% endfor %}
</code>```

Have a read of this part of the Django docs, it seems like you don't have a full understanding of what you have when accessing a form.

Title: django accessing errors

Body:
I have the following:

{% if formDetails.errors %}
{% for key, value in formDetails.errors.items %}
{% for error in value %}

            {{ key }}: {{ error }}

{% endfor %}
{% endfor %}

But unfortunately key gives me the name of the model field (the one that's lowercase with underscores). How can I get the nice looking name like field.label_tag?

Body:
The form.errors template variable is a list not a dictionary, so you should access it as follows:

{% for error in form.errors %}
    <li>{{ error }}</li>
{% endfor %}

In addition it contains form wide errors raised by the clean() method on the Form object you are dealing with. Validation errors raised by the individual fields, can be accessed like this:

{% for field in form %}
    {% for error in field.errors %}
        {{ error }}
    {% endfor %}
    {{ field.label_tag }}
{% endfor %}

Have a read of this part of the Django docs, it seems like you don't have a full understanding of what you have when accessing a form.


问:
How to stop on the Sign Up Form when web page performs Postback?
I'm working on my final year project. In which:

I have Login and Signup forms on one page (WebForm):

When user click on anchor Sign Up the DropDown ddlType (hides) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Displays) in Javascript client side:

```<code>function signupClick() {
  document.getElementById('divType').style.display = 'block' ? 'none' : 'block';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'inherit';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'none';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'inherit';

  document.getElementById('lblLogin').style.display = 'inherit';
  document.getElementById('lblSignup').style.display = 'none';
}
</code>```

Login Form:-

And when user click on anchor Login the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) in Javascript client side:

```<code>function loginClick() {
  document.getElementById('divType').style.display = 'none' ? 'block' : 'none';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'none';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'none';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'none';

  document.getElementById('lblLogin').style.display = 'none';
  document.getElementById('lblSignup').style.display = 'inherit';
}
</code>```

Sign Up Form:-

The .aspx code of anchors and buttons is:

```<code><label id="lblSignup" style="float: right">
    For new account?
  <a href="javascript:;" id="signup" onclick="signupClick()">Sign Up</a>
</label>
  <label id="lblLogin" style="float: right; display: none">
      For existing account?
  <a href="javascript:;" id="login" onclick="loginClick()">Login</a>
  </label>
</div>
<label style="width: 28%">
  <asp:HyperLink ID="hlHome" NavigateUrl="Index.aspx" Text="Home" CssClass="btn btn-default" Width="100%" runat="server" />
</label>
<label style="width: 70%; float: right">
  <asp:Button ID="btnLogin" OnClick="btnLogin_Click" CssClass="btn btn-success" Width="100%" runat="server" Text="Login" />
  <asp:Button ID="btnSignUp" OnClick="btnSignUp_Click" Style="display: none" Width="100%" CssClass="btn btn-primary" runat="server" Text="Sign Up" />
</label>
</code>```

Question:

When user click on button Sign Up the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) but I want to prevent this condition and the sign up form should be shown:

```<code>private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('" + msg + "');", true);
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    string cusname = txtCustName.Text;
    string email = txtEmail.Text;
    string pass = txtPassword.Text;
    string confirm = txtConfirmPassword.Text;

    if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
    {
        ShowMessage("Fill all cradentials of customer.");
    }
    else
    {
        //.. Register user

        Response.Redirect("~/CustomerPanel/Dashboard.aspx");
    }
}

--- JavaScript Function ---
function AutoHideAlert(msg) {
  // lblAlert is an asp:Label for displaying alert message
  var al = document.getElementById('<%=lblAlert.ClientID%>');

  al.innerText = msg;

  // alert is a DIV to show message
  $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
      $("#alert").slideUp(500);
  });
}
</code>```

How I can stop it on the Sign Up Form?

Updated:

My problem is when click on Sign Up button it sets to the Login form as like:

答:
In ASP.NET WebForms the default behavior of a button (asp:Button) is to post-back the page to the server. As you already find out this is what you need to prevent because the server responds with the new HTML which is the login screen in your case.

Another pitfall is that the server controls don't keep their names on the client side, so you need to use the ClientId property within inline server tags to render proper names in a script.

To begin resolving the issue, do create a client side event handler by duplicating your validation criteria from the C# handler to JavaScript. Then add the OnClientClick attribute to the server button.

So the solution of the problem would look like the following.

```<code>function btnSignUp_Click(e) {
    var cusname = $("<%=txtCustomerName.ClientId%>").val();
    var email = $("<%=txtCustomerName.ClientId%>").val();
    var password = $("<%=txtEmail.ClientId%>").val();
    var confirmPassword = $("<%=txtPassword.ClientId%>").val();

    var isValid = cusName !== "" && email !== "" && password !== ""
        && password === confirmPassword;

    return isValid;
}
</code>```

Then, in the markup of the asp:Button element add the OnClientClick attribute:

```<code><asp:Button runat="server" ... OnClientClick="btnSignUp_Click">SignUp</asp:Button>
</code>```

This way the unnecessary round trip to the server is prevented and the UI in the browser doesn't change.

Body:
I'm working on my final year project. In which:

I have Login and Signup forms on one page (WebForm):

When user click on anchor Sign Up the DropDown ddlType (hides) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Displays) in Javascript client side:

function signupClick() {
  document.getElementById('divType').style.display = 'block' ? 'none' : 'block';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'inherit';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'none';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'inherit';

  document.getElementById('lblLogin').style.display = 'inherit';
  document.getElementById('lblSignup').style.display = 'none';
}

Login Form:-

And when user click on anchor Login the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) in Javascript client side:

function loginClick() {
  document.getElementById('divType').style.display = 'none' ? 'block' : 'none';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'none';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'none';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'none';

  document.getElementById('lblLogin').style.display = 'none';
  document.getElementById('lblSignup').style.display = 'inherit';
}

Sign Up Form:-

The .aspx code of anchors and buttons is:

    For new account?
  Sign Up

      For existing account?
  Login

  <asp:HyperLink ID="hlHome" NavigateUrl="Index.aspx" Text="Home" CssClass="btn btn-default" Width="100%" runat="server" />

  <asp:Button ID="btnLogin" OnClick="btnLogin_Click" CssClass="btn btn-success" Width="100%" runat="server" Text="Login" />
  <asp:Button ID="btnSignUp" OnClick="btnSignUp_Click" Style="display: none" Width="100%" CssClass="btn btn-primary" runat="server" Text="Sign Up" />

Question:

When user click on button Sign Up the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) but I want to prevent this condition and the sign up form should be shown:

private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('" + msg + "');", true);
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    string cusname = txtCustName.Text;
    string email = txtEmail.Text;
    string pass = txtPassword.Text;
    string confirm = txtConfirmPassword.Text;

    if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
    {
        ShowMessage("Fill all cradentials of customer.");
    }
    else
    {
        //.. Register user

        Response.Redirect("~/CustomerPanel/Dashboard.aspx");
    }
}

--- JavaScript Function ---
function AutoHideAlert(msg) {
  // lblAlert is an asp:Label for displaying alert message
  var al = document.getElementById('<%=lblAlert.ClientID%>');

  al.innerText = msg;

  // alert is a DIV to show message
  $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
      $("#alert").slideUp(500);
  });
}

How I can stop it on the Sign Up Form?

Updated:

My problem is when click on Sign Up button it sets to the Login form as like:

Body:
In ASP.NET WebForms the default behavior of a button (asp:Button) is to post-back the page to the server. As you already find out this is what you need to prevent because the server responds with the new HTML which is the login screen in your case.

Another pitfall is that the server controls don't keep their names on the client side, so you need to use the ClientId property within inline server tags to render proper names in a script.

To begin resolving the issue, do create a client side event handler by duplicating your validation criteria from the C# handler to JavaScript. Then add the OnClientClick attribute to the server button.

So the solution of the problem would look like the following.

function btnSignUp_Click(e) {
    var cusname = $("<%=txtCustomerName.ClientId%>").val();
    var email = $("<%=txtCustomerName.ClientId%>").val();
    var password = $("<%=txtEmail.ClientId%>").val();
    var confirmPassword = $("<%=txtPassword.ClientId%>").val();

    var isValid = cusName !== "" && email !== "" && password !== ""
        && password === confirmPassword;

    return isValid;
}

Then, in the markup of the asp:Button element add the OnClientClick attribute:

<asp:Button runat="server" ... OnClientClick="btnSignUp_Click">SignUp</asp:Button>

This way the unnecessary round trip to the server is prevented and the UI in the browser doesn't change.


问:
How can i calculate Caltalan numbers without a for loop?
I have this code for calculating Catalan numbers but in the code I used a for loop.
How can I do it without using any loops?
Thankyou for the help!
This is the code:</p>

```<code>def catalan_rec(n):
    answer=0
    lst_rec=[]
    if n==0 or n==1:
        return 1
    else:
        for i in range(0,n):
            answer+= (catalan_rec(i))*(catalan_rec(n-1-i))

        return answer
</code>```

答:
Direct formula from https://en.wikipedia.org/wiki/Catalan_number</p>

```<code>from math import factorial

def catalan(n):
    if n == 0 or n == 1:
        return 1
    else:
        answer = factorial(2*n)/(factorial(n+1)*factorial(n))
    return int(answer)
</code>```

Body:
I have this code for calculating Catalan numbers but in the code I used a for loop.
How can I do it without using any loops?
Thankyou for the help!
This is the code:

def catalan_rec(n):
    answer=0
    lst_rec=[]
    if n==0 or n==1:
        return 1
    else:
        for i in range(0,n):
            answer+= (catalan_rec(i))*(catalan_rec(n-1-i))

        return answer

Body:
Direct formula from https://en.wikipedia.org/wiki/Catalan_number

from math import factorial

def catalan(n):
    if n == 0 or n == 1:
        return 1
    else:
        answer = factorial(2*n)/(factorial(n+1)*factorial(n))
    return int(answer)


问:
amazon pinpoint integration with webapp
Have cognito setup and working and I'm using pinpoint for analytics to track user sign-ups, sign-ins. etc. the problem is I have setup pinpoint according to this doc (http://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-pinpoint-integration.html) and have connected it to the app client in cognito but I am not getting any data in pinpoint when I sign up a new user etc. Specifically when I create a new user in my webapp I confirm that the new user has indeed been created in cognito and then check pinpoint and pinpoint shows zero users have signed up. </p>

答: What SDKs are you exactly using to interact with the services? If you are using any of the Javascript SDKs, you need to populate the AnalyticsMetadata https://github.com/aws/aws-sdk-js/blob/master/apis/cognito-idp-2016-04-18.normal.json#L2344 in the particular requests since the Javascript AWS frameworkds don't provide this functionality on your behalf (similar to the Android and iOS SDKs).</p>

Title: amazon pinpoint integration with webapp


问:
Can't make executable file with Pyinstaller 3.3 and Python 3.6
I can't get to make an .exe file using Pyinstaller 3.3 and python 3.6, on Windows 10 64bits.

I know all the dependencies are installed because i can run my script without any problems, from the command line.

I checked Pyinstaller page and they say python 3.6 is now supported.

```<code>E:\Fichier\Programming\Python>pyinstaller CheckNewEpisodes.py
371 INFO: PyInstaller: 3.3
372 INFO: Python: 3.6.1
372 INFO: Platform: Windows-10-10.0.15063-SP0
374 INFO: wrote E:\Fichier\Programming\Python\CheckNewEpisodes.spec
376 INFO: UPX is not available.
377 INFO: Extending PYTHONPATH with paths
['E:\\Fichier\\Programming\\Python', 'E:\\Fichier\\Programming\\Python']
377 INFO: checking Analysis
378 INFO: Building Analysis because out00-Analysis.toc is non existent
378 INFO: Initializing module dependency graph...
380 INFO: Initializing module graph hooks...
382 INFO: Analyzing base_library.zip ...
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
4277 INFO: running Analysis out00-Analysis.toc
4280 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\del\appdata\local\programs\python\python36\python.exe
4346 WARNING: lib not found: api-ms-win-crt-locale-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\python.exe
5519 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll

5767 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll
5773 INFO: Caching module hooks...
5781 INFO: Analyzing E:\Fichier\Programming\Python\CheckNewEpisodes.py
6041 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "c:\users\del\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_safe_import_module\hook-urllib3.packages.six.moves.py", line 31, in pre_safe_import_module
    for real_module_name, six_module_name in real_to_six_module_name.items():
AttributeError: 'str' object has no attribute 'items'
</code>```

I had to truncate the error log, hope this is enough to get an idea about where the problem is.

答:
I solved the bugs, and pyinstaller is awesome !!

First I removed enum34 module, because it was causing compatibility issues, pyinstaller was calling it when I wanted to call just enum.py:

```<code>pip uninstall enum34
</code>```

Then I add --debug when I make an executable so I can see what's wrong

```<code>pyinstaller -F --debug scriptname
</code>```

Then I solve the bugs one by one, most of the time it was missing modules, that were imported secretly by the modules I imported, for example with matplotlib I had to install PyQt5 and PySide, etc

Body:
I can't get to make an .exe file using Pyinstaller 3.3 and python 3.6, on Windows 10 64bits.

I know all the dependencies are installed because i can run my script without any problems, from the command line.

I checked Pyinstaller page and they say python 3.6 is now supported.

E:\Fichier\Programming\Python>pyinstaller CheckNewEpisodes.py
371 INFO: PyInstaller: 3.3
372 INFO: Python: 3.6.1
372 INFO: Platform: Windows-10-10.0.15063-SP0
374 INFO: wrote E:\Fichier\Programming\Python\CheckNewEpisodes.spec
376 INFO: UPX is not available.
377 INFO: Extending PYTHONPATH with paths
['E:\\Fichier\\Programming\\Python', 'E:\\Fichier\\Programming\\Python']
377 INFO: checking Analysis
378 INFO: Building Analysis because out00-Analysis.toc is non existent
378 INFO: Initializing module dependency graph...
380 INFO: Initializing module graph hooks...
382 INFO: Analyzing base_library.zip ...
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
4277 INFO: running Analysis out00-Analysis.toc
4280 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\del\appdata\local\programs\python\python36\python.exe
4346 WARNING: lib not found: api-ms-win-crt-locale-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\python.exe
5519 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll

5767 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll
5773 INFO: Caching module hooks...
5781 INFO: Analyzing E:\Fichier\Programming\Python\CheckNewEpisodes.py
6041 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "c:\users\del\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_safe_import_module\hook-urllib3.packages.six.moves.py", line 31, in pre_safe_import_module
    for real_module_name, six_module_name in real_to_six_module_name.items():
AttributeError: 'str' object has no attribute 'items'

I had to truncate the error log, hope this is enough to get an idea about where the problem is.

Body:
I solved the bugs, and pyinstaller is awesome !!

First I removed enum34 module, because it was causing compatibility issues, pyinstaller was calling it when I wanted to call just enum.py:

pip uninstall enum34

Then I add --debug when I make an executable so I can see what's wrong

pyinstaller -F --debug scriptname

Then I solve the bugs one by one, most of the time it was missing modules, that were imported secretly by the modules I imported, for example with matplotlib I had to install PyQt5 and PySide, etc


问:
Should I cache System.getProperty("line.separator")?
Consider such method:

```<code>@Override
public String toString()
{
    final StringBuilder sb = new StringBuilder();
    for (final Room room : map)
    {
        sb.append(room.toString());
        sb.append(System.getProperty("line.separator")); // THIS IS IMPORTANT
    }
    return sb.toString();
}
</code>```

System.getProperty("line.separator") can be called many times.

Should I cache this value with public final static String lineSeperator = System.getProperty("line.separator")
and later use only lineSeperator?

Or System.getProperty("line.separator") is as fast as using a static field?

答:
If the system property is guaranteed to remain constant during the application it can be cached but in general you will loose the feature of the property which is changing the behavior when you change it.

For instance a text generator could use the property to generate text for windows or for linux and allow the property to be changed dynamically in the application, why not ?

In general, catching a property implies making useless the function setProperty.

Body:
Consider such method:

@Override
public String toString()
{
    final StringBuilder sb = new StringBuilder();
    for (final Room room : map)
    {
        sb.append(room.toString());
        sb.append(System.getProperty("line.separator")); // THIS IS IMPORTANT
    }
    return sb.toString();
}

System.getProperty("line.separator") can be called many times.

Should I cache this value with public final static String lineSeperator = System.getProperty("line.separator")
and later use only lineSeperator?

Or System.getProperty("line.separator") is as fast as using a static field?


问:
Style of froala for angular wrong
I install and use froala， but only got this? what's wrong with it?</p>

答:
I encountered the same problem upon first installing froala with angular. The problem is that in the index.html file in your src folder you probably have a line like below if you followed the installation instructions.

```<code> <!-- index.html -->
 <link href="node_modules/froala-editor/css/froala_editor.pkgd.min.css"
 rel="stylesheet">
 <link href="node_modules/font-awesome/css/font-awesome.min.css" rel="stylesheet">
</code>```

What is happening is that the link is not finding your froala_editor.pkgd.min.css package in your NPM. Check your paths.

The easiest way to fix is to just reference the file from a CDN and replace with the link below.

```<code><link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.7.2/css/froala_editor.min.css" rel="stylesheet">
</code>```

Title: Style of froala for angular wrong

Body:
I encountered the same problem upon first installing froala with angular. The problem is that in the index.html file in your src folder you probably have a line like below if you followed the installation instructions.

 <!-- index.html -->
 <link href="node_modules/froala-editor/css/froala_editor.pkgd.min.css"
 rel="stylesheet">
 <link href="node_modules/font-awesome/css/font-awesome.min.css" rel="stylesheet">

What is happening is that the link is not finding your froala_editor.pkgd.min.css package in your NPM. Check your paths.

The easiest way to fix is to just reference the file from a CDN and replace with the link below.

<link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.7.2/css/froala_editor.min.css" rel="stylesheet">


问:
Future Any does not conform with Future E
I am having a problem in Scala when trying to return a result from a method.

I am using Play 2.6 and ReactiveMongo.

Error in the images bellow:

Could somebody give some clues?

答:
I suspect that what you really want is Future.transform instead of map. Something like this

```<code>  val result: Future[WriteResult] = ???
  result.transform(_ => entity,
    e => {
      e.printStackTrace()
      e // or return here your custom wrapper exception
    })
</code>```

Body:
I suspect that what you really want is Future.transform instead of map. Something like this

  val result: Future[WriteResult] = ???
  result.transform(_ => entity,
    e => {
      e.printStackTrace()
      e // or return here your custom wrapper exception
    })


答:
I don't follow the logic for your result set.  The following, however, should give the same results:</p>

```<code>SELECT COALESCE(A.RowNumber, 1),
       COALESCE(B.RowNumber, 1),
       COALESCE(A.InvoiceNumber, B.InvoiceNumber),
       COALESCE(A.InvoiceNumber, B.InvoiceNumber)
FROM TestA A FULL OUTER JOIN
     TestB B
     ON A.InvoiceNumber = B.InvoiceNumber AND
        A.RowNumber = B.RowNumber;
</code>```

Title: Full Outer Join Duplicate Results

Body:
Good Day,

This may seem long (but it's the data I'm showing) I have two tables.  TestA and TestB.  TestA has two columns (INT, VARCHAR(32)) called RowNumber and InvoiceNumber.  The following result is:  SELECT RowNumber, InvoiceNumber FROM TestA.

1   GB01530111600236
2   GB01530111600236
3   GB01530111600236
1   GB01530121600001
2   GB01530121600001

TestB is identical in that there are two columns with the same name.

1   GB01530111600236
1   GB01530121600001
2   GB01530121600001
3   GB01530121600001
4   GB01530121600001
5   GB01530121600001
6   GB01530121600001
7   GB01530121600001
8   GB01530121600001
9   GB01530121600001
10  GB01530121600001
11  GB01530121600001
12  GB01530121600001

My understanding of a FULL OUTER JOIN is that it will match all rows from both tables based on a JOIN and WHERE clause.  The reason is that TableA can have 1 or more invoice numbers and that TableB can also have 1 or more invoice numbers.

So from TestA, there are three invoice numbers of 'GB01530111600236' and one in TestB with 'GB01530111600236'.  In addition, there are 12 invoice numbers in TestB that are 'GB01530121600001' and two in TestA with 'GB01530121600001'  So what I'm trying to get is:

[   Table A        ]    [   Table B        ]
1   GB01530111600236    1   G01530111600236
2   GB01530111600236    1   G01530111600236
3   GB01530111600236    1   G01530111600236
1   GB01530121600001    1   GB01530121600001
2   GB01530121600001    2   GB01530121600001
1   GB01530121600001    3   GB01530121600001
1   GB01530121600001    4   GB01530121600001
1   GB01530121600001    5   GB01530121600001
1   GB01530121600001    6   GB01530121600001
1   GB01530121600001    7   GB01530121600001
1   GB01530121600001    8   GB01530121600001
1   GB01530121600001    9   GB01530121600001
1   GB01530121600001    10  GB01530121600001
1   GB01530121600001    11  GB01530121600001
1   GB01530121600001    12  GB01530121600001

My query is:

SELECT A.RowNumber, B.RowNumber, A.InvoiceNumber, B.InvoiceNumber
FROM TestA A
    FULL OUTER JOIN TestB B ON A.InvoiceNumber = B.InvoiceNumber

This query is half way right in that it gives me the correct output for 'GB01530111600236'.  The abridged version displays only 1-5 instead of 1 to 12.

1   GB01530111600236    1   GB01530111600236
2   GB01530111600236    1   GB01530111600236
3   GB01530111600236    1   GB01530111600236
1   GB01530121600001    1   GB01530121600001
1   GB01530121600001    2   GB01530121600001
1   GB01530121600001    3   GB01530121600001
1   GB01530121600001    4   GB01530121600001
1   GB01530121600001    5   GB01530121600001
2   GB01530121600001    1   GB01530121600001
2   GB01530121600001    2   GB01530121600001
2   GB01530121600001    3   GB01530121600001
2   GB01530121600001    4   GB01530121600001
2   GB01530121600001    5   GB01530121600001

But for the second invoice number 'GB01530121600001', it's giving me duplicates.  How do I get rid of the duplicates?

TIA,

coson

Body:
I don't follow the logic for your result set.  The following, however, should give the same results:

SELECT COALESCE(A.RowNumber, 1),
       COALESCE(B.RowNumber, 1),
       COALESCE(A.InvoiceNumber, B.InvoiceNumber),
       COALESCE(A.InvoiceNumber, B.InvoiceNumber)
FROM TestA A FULL OUTER JOIN
     TestB B
     ON A.InvoiceNumber = B.InvoiceNumber AND
        A.RowNumber = B.RowNumber;


问:
unknown type of struct in parameter function C when using Struct type data in parameter

how to pass struct type data using parameters to another function ? i have already create a global struct but i think i've miss something

```<code>#include <stdio.h>
#include <stdlib.h>

struct Stuff
{
    int id;
    String name[20];
}

// call another function
int myFunctionInsert(Stuff *stuff);

int main()
{
    struct Stuff *stuff[20];
    myFunctionInsert(*stuff);
}

int myFunctionInsert(Stuff *stuff)
{
    int x;
    for(x = 0; x < 25; x++){
        stuff[x].id = x;
        stuff[x].name = 'stuff';
    }
}
</code>```

so my purpose is when i already call the myFunctionInsert, the struct data same as i was input in that function.

for example, when i call myFunctionShow (which is i'm not write in) the data show should be like this

```<code>id   : 1
name : stuff

// until 25
</code>```

when i tried my code above, i got an error

Unknown type name 'Stuff' (in line i call myFunctionInsert(Stuff *stuff))

any help will be appreciated

thanks

答:
The problem is not only with lack of typedef.
Also memory will be smashed since    for(x = 0; x < 25; x++){ crosses the boundary of

```<code>struct Stuff *stuff[20];
</code>```

Also stuff[x].name = 'stuff'; will not fly. You mean "stuff". Notice that there is no String type in C language.

The working version of the program where size of the passed array of structures is specified may look like this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    typedef struct stuff
    {
        int id;
        char name[20];
    }Stuff;

    // call another function
    int myFunctionInsert(Stuff *stuff, int len);

    int myFunctionInsert(Stuff *stuff,int len)
    {
        int x;
        for(x = 0; x < len; x++){
            stuff[x].id = x;
            strcpy( stuff[x].name, "stuff");

            printf("stuff %i id=%d  name=%s\n", x, stuff[x].id, stuff[x].name );
        }
    }

    int main()
    {
        Stuff sf[25];
        myFunctionInsert(sf,5); // init 5 structures
        return 0;
    }
</code>```

OUTPUT:

```<code>stuff 0 id=0  name=stuff
stuff 1 id=1  name=stuff
stuff 2 id=2  name=stuff
stuff 3 id=3  name=stuff
stuff 4 id=4  name=stuff
</code>```

Body:
how to pass struct type data using parameters to another function ? i have already create a global struct but i think i've miss something

#include <stdio.h>
#include <stdlib.h>

struct Stuff
{
    int id;
    String name[20];
}

// call another function
int myFunctionInsert(Stuff *stuff);

int main()
{
    struct Stuff *stuff[20];
    myFunctionInsert(*stuff);
}

int myFunctionInsert(Stuff *stuff)
{
    int x;
    for(x = 0; x < 25; x++){
        stuff[x].id = x;
        stuff[x].name = 'stuff';
    }
}

so my purpose is when i already call the myFunctionInsert, the struct data same as i was input in that function.

for example, when i call myFunctionShow (which is i'm not write in) the data show should be like this

id   : 1
name : stuff

// until 25

when i tried my code above, i got an error

Unknown type name 'Stuff' (in line i call myFunctionInsert(Stuff *stuff))

any help will be appreciated

thanks

Body:
The problem is not only with lack of typedef.
Also memory will be smashed since    for(x = 0; x < 25; x++){ crosses the boundary of

struct Stuff *stuff[20];

Also stuff[x].name = 'stuff'; will not fly. You mean "stuff". Notice that there is no String type in C language.

The working version of the program where size of the passed array of structures is specified may look like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    typedef struct stuff
    {
        int id;
        char name[20];
    }Stuff;

    // call another function
    int myFunctionInsert(Stuff *stuff, int len);

    int myFunctionInsert(Stuff *stuff,int len)
    {
        int x;
        for(x = 0; x < len; x++){
            stuff[x].id = x;
            strcpy( stuff[x].name, "stuff");

            printf("stuff %i id=%d  name=%s\n", x, stuff[x].id, stuff[x].name );
        }
    }

    int main()
    {
        Stuff sf[25];
        myFunctionInsert(sf,5); // init 5 structures
        return 0;
    }

OUTPUT:

stuff 0 id=0  name=stuff
stuff 1 id=1  name=stuff
stuff 2 id=2  name=stuff
stuff 3 id=3  name=stuff
stuff 4 id=4  name=stuff


问:
Unable to center div properly
I am trying to center a div inside of a div. Instead, its shaded to the right. I have tried all combinations of positions. I tried everything I found in other threads and have not been able to fix this. This is how it looks: https://jsfiddle.net/L13qa1tr/

content_page.html:

```<code><div id="wrapper">
      <div id="main-content" class="container">
          <h1 class="text-center">This is a test, remove before release.This is a test, remove before release.This is a test, remove before release.</h1>
      </div>
</div>
</code>```

Relevant CSS, content_page.css:

```<code>body {
  font-family: 'Lora', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  position: relative;
  top: 61px;
  width: 100%;
  height: 100%;
  color: white;
  background-color: black; }

html {
  width: 100%;
  height: 100%; }

h1 {
  font-family: 'Cabin', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
  margin: 0 0 35px;
  letter-spacing: 1px;
  text-transform: uppercase; }

#wrapper{
    background-color: #555555;
    width: 100%;
    height: auto;
    padding: 5px;
    margin: 0 auto;
}
#main-content {
    position: relative;
    top: 32px;
    left: 88px;
    right: 88px;
    bottom: 32px;
    background-color: #E1E1E1;
    height: auto;
    box-sizing: border-box;
    margin-right: auto;
    margin-left: auto;
}
</code>```

I can post any other information needed, just let me know. If anyone can point me in the right direction that would be great. The part that also confuses me is that the width of the inner div should be 100% so it would make sense if it took up all of the space, but in this case it isn't taking up enough.

答:
If you are trying to center your #main-content div, here is how you can do it.

```<code>#main-content {
    position: relative;
    width: 80%;
    width:calc( 100% - 88px - 88px);
    margin-left: auto;
    margin-right: auto;
    background-color: #E1E1E1;
    height: auto;
}
</code>```

The calc method is just using your left and right peramters. You can remove this and just use the percent, which will still align it in the middle.

To center a div you need to set a width, followed by automatic margins on the left and right:

```<code>margin-left: auto;
margin-right: auto
</code>```

See this updated fiddle.

Title: Unable to center div properly

Body:
I am trying to center a div inside of a div. Instead, its shaded to the right. I have tried all combinations of positions. I tried everything I found in other threads and have not been able to fix this. This is how it looks: https://jsfiddle.net/L13qa1tr/

content_page.html:

This is a test, remove before release.This is a test, remove before release.This is a test, remove before release.

Relevant CSS, content_page.css:

body {
  font-family: 'Lora', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  position: relative;
  top: 61px;
  width: 100%;
  height: 100%;
  color: white;
  background-color: black; }

html {
  width: 100%;
  height: 100%; }

h1 {
  font-family: 'Cabin', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
  margin: 0 0 35px;
  letter-spacing: 1px;
  text-transform: uppercase; }

#wrapper{
    background-color: #555555;
    width: 100%;
    height: auto;
    padding: 5px;
    margin: 0 auto;
}
#main-content {
    position: relative;
    top: 32px;
    left: 88px;
    right: 88px;
    bottom: 32px;
    background-color: #E1E1E1;
    height: auto;
    box-sizing: border-box;
    margin-right: auto;
    margin-left: auto;
}

I can post any other information needed, just let me know. If anyone can point me in the right direction that would be great. The part that also confuses me is that the width of the inner div should be 100% so it would make sense if it took up all of the space, but in this case it isn't taking up enough.

Body:
If you are trying to center your #main-content div, here is how you can do it.

#main-content {
    position: relative;
    width: 80%;
    width:calc( 100% - 88px - 88px);
    margin-left: auto;
    margin-right: auto;
    background-color: #E1E1E1;
    height: auto;
}

The calc method is just using your left and right peramters. You can remove this and just use the percent, which will still align it in the middle.

To center a div you need to set a width, followed by automatic margins on the left and right:

margin-left: auto;
margin-right: auto

See this updated fiddle.


问:
For loop for printing unicode characters in Python
I did a basic for loop in Python as I wanted to print all possible charactes using unicode notation.

```<code>for i in range(1000,1100):
    print('\\u'+str(i))
</code>```

and it prints the following

```<code>...
\u1077
\u1078
\u1079
</code>```

and so on...

I don't understand why loop prints strings like that, but if I executed just:

```<code>print('\u0227')
</code>```

it would have printed ȧ.

I don't understand the difference between printing as a concatenated string from for loop vs printing it just by calling print and typing a unicode representation. Also a string generated by for loop seems to need one more backslash for escaping.

I called type function and in both cases it says those are strings as they are but just wanted to be sure since of this behaviour.

答:
So called string literals in code are processed before they become strings. A backslash in a string marks that something follows that must be interpreted specially.

If followed by a second backslash, the final string is rendered to
just contain one backslash. So string literal '\\u' becomes
string \u

If followed by a u and four hexadecimal digits the whole sequence
(including the backslash) in the literal become the denoted unicode character in the string: Literal '\u0227' becomes string ȧ

As Paul Panzer already wrote, chr() (for Python 3.x) or unichr() (for Python 2.x) take the number of a unicode character and return a string containing only this character.

Body:
I did a basic for loop in Python as I wanted to print all possible charactes using unicode notation.

for i in range(1000,1100):
    print('\\u'+str(i))

and it prints the following

...
\u1077
\u1078
\u1079

and so on...

I don't understand why loop prints strings like that, but if I executed just:

print('\u0227')

it would have printed ȧ.

I don't understand the difference between printing as a concatenated string from for loop vs printing it just by calling print and typing a unicode representation. Also a string generated by for loop seems to need one more backslash for escaping.

I called type function and in both cases it says those are strings as they are but just wanted to be sure since of this behaviour.


答:
There is a lot of unnecessary code in there. I removed a lot of it.

The margin: 0 auto; needs to be placed inside the #main-content to center it instead of the #wrapper.
I changed the width to show you that it works.

body {
  font-family: 'Lora', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  position: relative;
  top: 61px;
  color: white;
  background-color: black; }

h1 {
  font-family: 'Cabin', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
  margin: 0 0 35px;
  letter-spacing: 1px;
  text-transform: uppercase; }

#wrapper{
    background-color: #555555;
    padding: 5px;
}
#main-content {
    position: relative;
    top: 32px;
    background-color: #E1E1E1;
    box-sizing: border-box;
    margin: 0 auto;
    width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
      <div id="main-content" class="container">
          <h1 class="text-center">This is a test, remove before release.This is a test, remove before release.This is a test, remove before release.</h1>
      </div>
</div></code>```

Title: Unable to center div properly

Body:
There is a lot of unnecessary code in there. I removed a lot of it.

The margin: 0 auto; needs to be placed inside the #main-content to center it instead of the #wrapper.
I changed the width to show you that it works.

body {
  font-family: 'Lora', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  position: relative;
  top: 61px;
  color: white;
  background-color: black; }

h1 {
  font-family: 'Cabin', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
  margin: 0 0 35px;
  letter-spacing: 1px;
  text-transform: uppercase; }

#wrapper{
    background-color: #555555;
    padding: 5px;
}
#main-content {
    position: relative;
    top: 32px;
    background-color: #E1E1E1;
    box-sizing: border-box;
    margin: 0 auto;
    width: 50%;
}

<div id="wrapper">
      <div id="main-content" class="container">
          <h1 class="text-center">This is a test, remove before release.This is a test, remove before release.This is a test, remove before release.</h1>
      </div>
</div>


答:
Well that was a part of your issue, that you were moving the div using

position:relative and adding top,left,right and bottom.

Instead all you are supposed to add is margin:auto.
Width is reduced just for bring the content in the center.

```<code>#main-content {
  width:600px;
  margin:auto;
  background-color: #E1E1E1;
}
</code>```

Title: Unable to center div properly

Body:
Well that was a part of your issue, that you were moving the div using

position:relative and adding top,left,right and bottom.

Instead all you are supposed to add is margin:auto.
Width is reduced just for bring the content in the center.

#main-content {
  width:600px;
  margin:auto;
  background-color: #E1E1E1;
}


问:
Get custom values of variations from order items in WooCommerce
I am trying to get the variation values selected by customer at checkout from an order (by id or otherwise) to map to variables $storage and $tier which are used to build an API url.

I have tried a variety of methods to get the data onto the variables but the API url is failing, which leads me to believe I do not have the indented values on my variables.

My current code is as follows (extract):

```<code>add_action( 'woocommerce_order_status_processing', 'my_function' );
    function my_function( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
        foreach ( $items as $key => $item ) {
                $storage = get_post_meta( $key, 'attribute_addon-storage' );
                $tier = get_post_meta( $key, 'attribute_subscription-type' );
</code>```

Does anyone have any idea how I would grab the values of those two variables, addon-storage and subscription-type?

I can see the values I want to get in my database in the woocommerce_order_itemmeta table.

Can I get the values from there?

Edit:

So as per LoicTheAztec's advice, the right way to get the value of the data I see in the woocommerce_order_itemmeta table as $meta_key is:

```<code>add_action( 'woocommerce_order_status_processing', 'my_function', 10, 1 );
    function my_function( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
        foreach ( $items as $key => $item ) {
                $storage = wc_get_order_item_meta( $key, 'addon-storage', true );
                $tier = wc_get_order_item_meta( $key, 'subscription-type', true );
                $anyMetaValue = wc_get_order_item_meta( $key, '$meta_key', true );

// Then I can create the variable I need in the the API url with:

$package = "$tier$storage";
</code>```

答:
Updated: Your are confusing order post meta data and order item meta data, which are very different things and located in different database tables.

Also your code is incomplete and you will not get anything using get_post_meta() with the $key (which is the item ID)...

The get_post_meta( $order_id, 'meta_key', true ) function will look for Order post meta data (not related to order items) and use Order ID as argument.

The wc_get_order_item_meta( $item_id, 'meta_key', true ) function will look for Order item meta data realated and will use the Item ID as argument (the $key in your code)…

So this function should need to be used in the foreach loop, where you get the order items data, instead.

Then 2 ways:

You should check in your database for the last order ID you have (via phpMyAdmin) in wp_postmeta and wp_woocommerce_order_itemmeta tables, to see where is located the data…

Or you can use the following code (just for testing) that will output the order items raw data where your data is located.

This raw data will be output in the shop, archive and product pages, only visible for logged in admins. You will need to define an order ID in it.

Here is this testing function

```<code>add_action( 'woocommerce_before_main_content', 'my_testing_order_function' );
function my_testing_order_function() {

    // Define an Order ID
    $order_id = 724;

    // Only for admin user role
    if( ! current_user_can('edit_products')) return;

    $order = wc_get_order( $order_id ); // The order object

    foreach ( $order->get_items() as $item_id => $item ) {
        // Order item meta data Raw output
        echo "```ORDER ITEM META DATA - (Item_id $item_id):"; print_r($item->get_data()); echo'```';
        echo "```ORDER ITEM META META DATA - (Item_id $item_id):"; print_r($item->get_meta_data()); echo'```';
    }
}
</code>```

Now you have everything needed to locate and get the data. The code below should normally work for you, allowing you to get the data from your variations:

```<code>add_action( 'woocommerce_order_status_processing', 'my_function', 10, 1 );
function my_function( $order_id ) {
    $order = wc_get_order( $order_id );
    foreach ( $order->get_items() as $key => $item ) {
        // get the data
        $storage = wc_get_order_item_meta( $item_id, 'attribute_addon-storage', true );
        $tier = wc_get_order_item_meta( $item_id, 'attribute_subscription-type', true );
    }
}
</code>```

Body:
I am trying to get the variation values selected by customer at checkout from an order (by id or otherwise) to map to variables $storage and $tier which are used to build an API url.

I have tried a variety of methods to get the data onto the variables but the API url is failing, which leads me to believe I do not have the indented values on my variables.

My current code is as follows (extract):

add_action( 'woocommerce_order_status_processing', 'my_function' );
    function my_function( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
        foreach ( $items as $key => $item ) {
                $storage = get_post_meta( $key, 'attribute_addon-storage' );
                $tier = get_post_meta( $key, 'attribute_subscription-type' );

Does anyone have any idea how I would grab the values of those two variables, addon-storage and subscription-type?

I can see the values I want to get in my database in the woocommerce_order_itemmeta table.

Can I get the values from there?

Edit:

So as per LoicTheAztec's advice, the right way to get the value of the data I see in the woocommerce_order_itemmeta table as $meta_key is:

add_action( 'woocommerce_order_status_processing', 'my_function', 10, 1 );
    function my_function( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
        foreach ( $items as $key => $item ) {
                $storage = wc_get_order_item_meta( $key, 'addon-storage', true );
                $tier = wc_get_order_item_meta( $key, 'subscription-type', true );
                $anyMetaValue = wc_get_order_item_meta( $key, '$meta_key', true );

// Then I can create the variable I need in the the API url with:

$package = "$tier$storage";

Body:
Updated: Your are confusing order post meta data and order item meta data, which are very different things and located in different database tables.

Also your code is incomplete and you will not get anything using get_post_meta() with the $key (which is the item ID)...

The get_post_meta( $order_id, 'meta_key', true ) function will look for Order post meta data (not related to order items) and use Order ID as argument.

The wc_get_order_item_meta( $item_id, 'meta_key', true ) function will look for Order item meta data realated and will use the Item ID as argument (the $key in your code)…

So this function should need to be used in the foreach loop, where you get the order items data, instead.

Then 2 ways:

You should check in your database for the last order ID you have (via phpMyAdmin) in wp_postmeta and wp_woocommerce_order_itemmeta tables, to see where is located the data…

Or you can use the following code (just for testing) that will output the order items raw data where your data is located.

This raw data will be output in the shop, archive and product pages, only visible for logged in admins. You will need to define an order ID in it.

Here is this testing function

add_action( 'woocommerce_before_main_content', 'my_testing_order_function' );
function my_testing_order_function() {

    // Define an Order ID
    $order_id = 724;

    // Only for admin user role
    if( ! current_user_can('edit_products')) return;

    $order = wc_get_order( $order_id ); // The order object

    foreach ( $order->get_items() as $item_id => $item ) {
        // Order item meta data Raw output
        echo "<pre>ORDER ITEM META DATA - (Item_id $item_id):"; print_r($item->get_data()); echo'</pre>';
        echo "<pre>ORDER ITEM META META DATA - (Item_id $item_id):"; print_r($item->get_meta_data()); echo'</pre>';
    }
}

Now you have everything needed to locate and get the data. The code below should normally work for you, allowing you to get the data from your variations:

add_action( 'woocommerce_order_status_processing', 'my_function', 10, 1 );
function my_function( $order_id ) {
    $order = wc_get_order( $order_id );
    foreach ( $order->get_items() as $key => $item ) {
        // get the data
        $storage = wc_get_order_item_meta( $item_id, 'attribute_addon-storage', true );
        $tier = wc_get_order_item_meta( $item_id, 'attribute_subscription-type', true );
    }
}


问:
How to install a plugin in Jenkins manually
Installing a plugin from the Update center results in:

Checking internet connectivity Failed to connect to
  http://www.google.com/. Perhaps you need to configure HTTP proxy? Deploy Plugin  Failure - Details hudson.util.IOException2: Failed to download from
  http://updates.jenkins-ci.org/download/plugins/deploy/1.9/deploy.hpi

Is it possible to download the plugin and install it manually into Jenkins?

答:
In my case, I needed to install a plugin to an offline build server that's running a Windows Server (version won't matter here). I already installed Jenkins on my laptop to test out changes in advance and it is running on localhost:8080 as a windows service.

So if you are willing to take the time to setup Jenkins on a machine with Internet connection and carry these changes to the offline server Jenkins (it works, confirmed by me!), these are steps you could follow:

Jenkins on my laptop: Open up Jenkins, http://localhost:8080

Navigator: Manage Jenkins | Download plugin without install option

Windows Explorer: Copy the downloaded plugin file that is located at "c:\program files (x86)\Jenkins\plugins" folder (i.e. role-strategy.jpi)

Paste it into a shared folder in the offline server

Stop the Jenkins Service (Offline Server Jenkins) through Component Services, Jenkins Service

Copy the plugin file (i.e. role-strategy.jpi) into "c:\program files (x86)\Jenkins\plugins" folder on the (Offline Jenkins) server

Restart Jenkins and voila! It should be installed.

ContentLicense: CC BY-SA 4.0


问:
LINQ to SQL - 'Select' not found
I have been looking to solve this for hours with no luck.

I have a very simple scenario - I am trying the following in LINQ-to-SQL

```<code> var qry = (from row
   in DBConnect.SEARCHhash("test", "1234")
    select row);
</code>```

Where the SEARCHhash is a stored procedure - Unfortunately, I can't even put .ToList() at the end because IntelliSense shows the following error

Could not find an implementation of the query pattern for source type 'void'.  'Select' not found.

All my other stored procedures work fine, just this one doesn't work.

Then I remember that when I dragged and dropped the stored procedure to Designer I got the following warning

The return types for the following stored procedures could not be detected. Set the return type for each stored procedure in the Properties window.

So, I opened the properties and clicked on dropdown and only available option was int(int32) so selected int

But now then I started getting the following error

Could not find an implementation of the query pattern for source type 'int'.  'Select' not found

The following is the code from Designer

```<code>[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.SEARCHhash")]
        public int SEARCHhash([global::System.Data.Linq.Mapping.ParameterAttribute(Name="Keywords", DbType="VarChar(540)")] string keywords, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="UserId", DbType="NVarChar(128)")] string userId)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), keywords, userId);
            return ((int)(result.ReturnValue));
        }
</code>```

I also started comparing my stored procedures and I noticed that this stored procedure has JOIN in it and of course it is using `FREETEXT'

Here is my stored procedure code:

```<code>SELECT
    [dbo].[SEARCHMLinksData].PageID,
    [dbo].[SEARCHMLinksData].PageTitle,
    [dbo].[SEARCHMLinksData].PageDescription,
    [dbo].[SEARCHMLinksData].PageType
FROM
    [dbo].[SEARCHMLinksData]
LEFT JOIN
    [dbo].[SEARCHMLinksTags] ON [SEARCHMLinksData].PageID = [SEARCHMLinksTags].PageID
WHERE
    (FREETEXT([SEARCHMLinksData].*, @Keywords) OR
     FREETEXT([SEARCHMLinksTags].*,@Keywords) )
    AND
    ([SEARCHMLinksData].UserID = @UserId OR [SEARCHMLinksTags].[user_id] = @UserId)
</code>```

Any idea or help will be appreciated

Cheers

In addition, I tried so many things including the following
https://www.mssqltips.com/sqlservertip/1542/using-stored-procedures-with-linq-to-sql/
The return types for the following stored procedures could not be detected
Could not find an implementation of the query pattern for source type 'System.Data.Entity.DbSet'

答:
Just in case if anyone is looking for the solution

It is not possible to use FREETEXT in LINQ and that was the reason I created the Stored Procedure although in my case it seems like it was not possible to use the Stored Procedure either for some reason (i don't know why) Although the solution I found was to

create a function and call the function using LINQ

It works for me now

One thing I had to do in the function though that - Instead of using

```<code>(FREETEXT([SEARCHMLinksData].*,@Keywords)
</code>```

I had to use

```<code>(FREETEXT([SEARCHMLinksData].Title,[SEARCHMLinksData].Description,@Keywords)
</code>```

Means, list all the columns getting indexed by their [names] as it didn't take wildcard

Why all this? I have no idea but that's the only solution I could found

Hope this helps someone.

Title: LINQ to SQL - 'Select' not found

Body:
I have been looking to solve this for hours with no luck.

I have a very simple scenario - I am trying the following in LINQ-to-SQL

 var qry = (from row
   in DBConnect.SEARCHhash("test", "1234")
    select row);

Where the SEARCHhash is a stored procedure - Unfortunately, I can't even put .ToList() at the end because IntelliSense shows the following error

Could not find an implementation of the query pattern for source type 'void'.  'Select' not found.

All my other stored procedures work fine, just this one doesn't work.

Then I remember that when I dragged and dropped the stored procedure to Designer I got the following warning

The return types for the following stored procedures could not be detected. Set the return type for each stored procedure in the Properties window.

So, I opened the properties and clicked on dropdown and only available option was int(int32) so selected int

But now then I started getting the following error

Could not find an implementation of the query pattern for source type 'int'.  'Select' not found

The following is the code from Designer

[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.SEARCHhash")]
        public int SEARCHhash([global::System.Data.Linq.Mapping.ParameterAttribute(Name="Keywords", DbType="VarChar(540)")] string keywords, [global::System.Data.Linq.Mapping.ParameterAttribute(Name="UserId", DbType="NVarChar(128)")] string userId)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), keywords, userId);
            return ((int)(result.ReturnValue));
        }

I also started comparing my stored procedures and I noticed that this stored procedure has JOIN in it and of course it is using `FREETEXT'

Here is my stored procedure code:

SELECT
    [dbo].[SEARCHMLinksData].PageID,
    [dbo].[SEARCHMLinksData].PageTitle,
    [dbo].[SEARCHMLinksData].PageDescription,
    [dbo].[SEARCHMLinksData].PageType
FROM
    [dbo].[SEARCHMLinksData]
LEFT JOIN
    [dbo].[SEARCHMLinksTags] ON [SEARCHMLinksData].PageID = [SEARCHMLinksTags].PageID
WHERE
    (FREETEXT([SEARCHMLinksData].*, @Keywords) OR
     FREETEXT([SEARCHMLinksTags].*,@Keywords) )
    AND
    ([SEARCHMLinksData].UserID = @UserId OR [SEARCHMLinksTags].[user_id] = @UserId)

Any idea or help will be appreciated

Cheers

In addition, I tried so many things including the following
https://www.mssqltips.com/sqlservertip/1542/using-stored-procedures-with-linq-to-sql/
The return types for the following stored procedures could not be detected
Could not find an implementation of the query pattern for source type 'System.Data.Entity.DbSet'

Body:
Just in case if anyone is looking for the solution

It is not possible to use FREETEXT in LINQ and that was the reason I created the Stored Procedure although in my case it seems like it was not possible to use the Stored Procedure either for some reason (i don't know why) Although the solution I found was to

create a function and call the function using LINQ

It works for me now

One thing I had to do in the function though that - Instead of using

(FREETEXT([SEARCHMLinksData].*,@Keywords)

I had to use

(FREETEXT([SEARCHMLinksData].Title,[SEARCHMLinksData].Description,@Keywords)

Means, list all the columns getting indexed by their [names] as it didn't take wildcard

Why all this? I have no idea but that's the only solution I could found

Hope this helps someone.


问:
phpMyAdmin reports 'No Privileges'
Long story short, I ended up deleting the root user from PHPMyAdmin in EasyPHP.  After some researching, I used skip-grant-tables to regain database access.  Now, however, I cannot do anything as the root user has 'No Privileges.'

That stated, when logged in as 'root,' I do, indeed, have the ability to create a database via SQL.

I've tried the following, and similar:

```<code>GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;
</code>```

Still, I can't do anything.  Additionally, I have this message:

The additional features for working with linked tables have been deactivated. To find out why click here.

Clicking through shows:

```<code>$cfg['Servers'][$i]['pmadb'] ...    OK
$cfg['Servers'][$i]['relation'] ... not OK [ Documentation ]
General relation features: Disabled

$cfg['Servers'][$i]['table_info'] ...   not OK [ Documentation ]
Display Features: Disabled

$cfg['Servers'][$i]['table_coords'] ... not OK [ Documentation ]
$cfg['Servers'][$i]['pdf_pages'] ...    not OK [ Documentation ]
Creation of PDFs: Disabled

$cfg['Servers'][$i]['column_info'] ...  not OK [ Documentation ]
Displaying Column Comments: Disabled
Browser transformation: Disabled

$cfg['Servers'][$i]['bookmarktable'] ...    not OK [ Documentation ]
Bookmarked SQL query: Disabled

$cfg['Servers'][$i]['history'] ...  not OK [ Documentation ]
SQL history: Disabled

$cfg['Servers'][$i]['designer_coords'] ...  not OK [ Documentation ]
Designer: Disabled

$cfg['Servers'][$i]['tracking'] ... not OK [ Documentation ]
Tracking: Disabled
</code>```

Reinstalling EasyPHP doesn't fix the problem, and nothing exists in VirtualStore (as one forum post suggested).  Is there a specific MySQL file I should be looking for?

Any ideas?  This has really put a stop to my application development.

Thanks.

答:
Turns out to be some sort of issue specific to Google Chrome, as it now works in IE.  I'll try running CCleaner.

Thanks all.

Title: phpMyAdmin reports 'No Privileges'

Body:
Long story short, I ended up deleting the root user from PHPMyAdmin in EasyPHP.  After some researching, I used skip-grant-tables to regain database access.  Now, however, I cannot do anything as the root user has 'No Privileges.'

That stated, when logged in as 'root,' I do, indeed, have the ability to create a database via SQL.

I've tried the following, and similar:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

Still, I can't do anything.  Additionally, I have this message:

The additional features for working with linked tables have been deactivated. To find out why click here.

Clicking through shows:

$cfg['Servers'][$i]['pmadb'] ...    OK
$cfg['Servers'][$i]['relation'] ... not OK [ Documentation ]
General relation features: Disabled

$cfg['Servers'][$i]['table_info'] ...   not OK [ Documentation ]
Display Features: Disabled

$cfg['Servers'][$i]['table_coords'] ... not OK [ Documentation ]
$cfg['Servers'][$i]['pdf_pages'] ...    not OK [ Documentation ]
Creation of PDFs: Disabled

$cfg['Servers'][$i]['column_info'] ...  not OK [ Documentation ]
Displaying Column Comments: Disabled
Browser transformation: Disabled

$cfg['Servers'][$i]['bookmarktable'] ...    not OK [ Documentation ]
Bookmarked SQL query: Disabled

$cfg['Servers'][$i]['history'] ...  not OK [ Documentation ]
SQL history: Disabled

$cfg['Servers'][$i]['designer_coords'] ...  not OK [ Documentation ]
Designer: Disabled

$cfg['Servers'][$i]['tracking'] ... not OK [ Documentation ]
Tracking: Disabled

Reinstalling EasyPHP doesn't fix the problem, and nothing exists in VirtualStore (as one forum post suggested).  Is there a specific MySQL file I should be looking for?

Any ideas?  This has really put a stop to my application development.

Thanks.


问:
How could I use per-folder color schemes? (Sublime Text 3)
Here is my problem: when writing javascript for both server and client-side, I regularly share methods and/or have close file names. I would love to be able to keep the context in mind, just by the background color of the opened files. I thus look for a way to tell sublime text to use one color scheme for files in the server folder and an other for those in the client folder: any clue on how I could do that?

I'm not sure it's even possible as it would imply a per-folder config file I guess, but that's my bottle in the sea...
thanks!

答:
I modified MattDMo's solution and it works with the latest Sublime Text 3 (build 3143):</p>

```<code>import sublime, sublime_plugin
class ColorSchemeByPathCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        settings = self.view.settings()
        if "/test/" in self.view.file_name():
            settings.set('color_scheme', "Packages/User/SublimeLinter/Orange01 (SL).tmTheme")
        else:
            settings.set('color_scheme', "Packages/User/SublimeLinter/Blue01 (SL).tmTheme")
class ColorSchemeByPathEventListener(sublime_plugin.EventListener):
    def on_load_async(self, view):
        view.run_command("color_scheme_by_path")
</code>```

Body:
I modified MattDMo's solution and it works with the latest Sublime Text 3 (build 3143):

import sublime, sublime_plugin
class ColorSchemeByPathCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        settings = self.view.settings()
        if "/test/" in self.view.file_name():
            settings.set('color_scheme', "Packages/User/SublimeLinter/Orange01 (SL).tmTheme")
        else:
            settings.set('color_scheme', "Packages/User/SublimeLinter/Blue01 (SL).tmTheme")
class ColorSchemeByPathEventListener(sublime_plugin.EventListener):
    def on_load_async(self, view):
        view.run_command("color_scheme_by_path")


问:
Error takes exactly 2 arguments (3 given)
Hi i am trying to plot points in a google map by indexing the dictionary with a foor loop, have this dictionary of lat:long

```<code> latlon = {32.1243973: -101.8856125, 32.666694: -104.233502, 32.222012:
 -101.819122, 32.53151: -103.353018, 32.668496: -104.235722, 32.1041336: -101.8818588}
</code>```

And i have this code:

```<code>if __name__ == "__main__":
        map = Map()
        for latitude, longitude in latlon.iteritems():
            map.add_point(latitude, longitude)
</code>```

I get the error TypeError: add_point() takes exactly 2 arguments (3 given)

I am giving only latitude and longitude why it says i am giving 3 arguments?

Thanks in advance!

Edit: addint the class map:

```<code>class Map(object):
    def __init__(self):
        self._points = []
    def add_point(self, coordinates):
        self._points.append(coordinates)
    def __str__(self):
        centerLat = sum(( x[0] for x in self._points )) / len(self._points)
        centerLon = sum(( x[1] for x in self._points )) / len(self._points)
        markersCode = "\n".join(
            [ """new google.maps.Marker({{
                position: new google.maps.LatLng({lat}, {lon}),
                map: map
                }});""".format(lat=x[0], lon=x[1]) for x in self._points
            ])
        return """
            <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
            <div id="map-canvas" style="height: 100%; width: 100%"></div>
            <script type="text/javascript">
                var map;
                function show_map() {{
                    map = new google.maps.Map(document.getElementById("map-canvas"), {{
                        zoom: 8,
                        center: new google.maps.LatLng({centerLat}, {centerLon})
                    }});
                    {markersCode}
                }}
                google.maps.event.addDomListener(window, 'load', show_map);
            </script>
        """.format(centerLat=centerLat, centerLon=centerLon,
                   markersCode=markersCode)
</code>```

答:
addPoint() is supposed to take both coordinates as one parameter.

Another way to write map.addPoint(p) is Map.addPoint(map, p).  From the second example, you can see why you were getting an error by having too many parameters.

You can call your function like this to include both latitude and longitude in one parameter:

```<code>for i in latlon.iteritems:
    map.addPoint(i)
</code>```

Body:
Hi i am trying to plot points in a google map by indexing the dictionary with a foor loop, have this dictionary of lat:long

 latlon = {32.1243973: -101.8856125, 32.666694: -104.233502, 32.222012:
 -101.819122, 32.53151: -103.353018, 32.668496: -104.235722, 32.1041336: -101.8818588}

And i have this code:

if __name__ == "__main__":
        map = Map()
        for latitude, longitude in latlon.iteritems():
            map.add_point(latitude, longitude)

I get the error TypeError: add_point() takes exactly 2 arguments (3 given)

I am giving only latitude and longitude why it says i am giving 3 arguments?

Thanks in advance!

Edit: addint the class map:

class Map(object):
    def __init__(self):
        self._points = []
    def add_point(self, coordinates):
        self._points.append(coordinates)
    def __str__(self):
        centerLat = sum(( x[0] for x in self._points )) / len(self._points)
        centerLon = sum(( x[1] for x in self._points )) / len(self._points)
        markersCode = "\n".join(
            [ """new google.maps.Marker({{
                position: new google.maps.LatLng({lat}, {lon}),
                map: map
                }});""".format(lat=x[0], lon=x[1]) for x in self._points
            ])
        return """

        """.format(centerLat=centerLat, centerLon=centerLon,
                   markersCode=markersCode)

Body:
addPoint() is supposed to take both coordinates as one parameter.

Another way to write map.addPoint(p) is Map.addPoint(map, p).  From the second example, you can see why you were getting an error by having too many parameters.

You can call your function like this to include both latitude and longitude in one parameter:

for i in latlon.iteritems:
    map.addPoint(i)


问:
PhpStorm update on Ubuntu/Mint
I am running PhpStorm on Linux Mint installed in /opt. PhpStorm is notifying me that there is an update available (8.0.3), but then it tells me it doesn't have write permission to apply the update, and that I should run it as a privileged user to update it.

If I run phpstorm.sh as root/sudo it asks for license info and looks as though it's running the installer rather than the program. PhpStorm is licensed when I run it from the desktop.

So how can I run updates?

答:
No need (and not recommended) to change the ownership or the permissions of the opt/phpstorm directory. In fact, the error message returned says exactly what you should do: run it as a privileged user to update it.

After exiting PHPStorm, you can run it as a privileged user using the following instructions

```<code>sudo updatedb && sudo locate phpstorm.sh
sudo /path/to/phpstorm.sh
</code>```

The first instruction updates the locate database and returns the location of the phpstorm executable in your computer.
Use the returned location as the path in the second instruction.

When starting PHPStorm as root, it will start with the default settings. It might even ask you if you want to apply your license... No need to change any of this: the default settings and running PHPStorm in evaluation mode will work just fine. After it starts, check for updates in the menu Help and apply them normally. PHPStorm might restart once again as root. Just close it once more and restart normally. When restarting as your user, you'll be given the ability to select your normal settings (usually stored in your user's directory: the path will be suggested). Accept and continue. PHPStorm will start with all your preferences and settings restored and properly upgraded.

If plugin updates are required, you can update them normally. No need to do it using root.

This solution is recommended by JetBrains. Changing the ownership or the permissions of the opt/phpstorm directory is not recommended and in fact pointed as incorrect by Jet Brains, as you can verify on their answer regarding the process of upgrading a similar product: Fixed: PyCharm automatic update fails on Linux due to permissions.

Title: PhpStorm update on Ubuntu/Mint

Body:
No need (and not recommended) to change the ownership or the permissions of the opt/phpstorm directory. In fact, the error message returned says exactly what you should do: run it as a privileged user to update it.

After exiting PHPStorm, you can run it as a privileged user using the following instructions

sudo updatedb && sudo locate phpstorm.sh
sudo /path/to/phpstorm.sh

The first instruction updates the locate database and returns the location of the phpstorm executable in your computer.
Use the returned location as the path in the second instruction.

When starting PHPStorm as root, it will start with the default settings. It might even ask you if you want to apply your license... No need to change any of this: the default settings and running PHPStorm in evaluation mode will work just fine. After it starts, check for updates in the menu Help and apply them normally. PHPStorm might restart once again as root. Just close it once more and restart normally. When restarting as your user, you'll be given the ability to select your normal settings (usually stored in your user's directory: the path will be suggested). Accept and continue. PHPStorm will start with all your preferences and settings restored and properly upgraded.

If plugin updates are required, you can update them normally. No need to do it using root.

This solution is recommended by JetBrains. Changing the ownership or the permissions of the opt/phpstorm directory is not recommended and in fact pointed as incorrect by Jet Brains, as you can verify on their answer regarding the process of upgrading a similar product: Fixed: PyCharm automatic update fails on Linux due to permissions.


问:
Terraform AWS Cognito App Client
Currently stuck in the mud with trying to to set up an 'app client' for an AWS Cognito User Pool through Terraform. Here is my resource as it stands:

```<code>resource "aws_cognito_user_pool" "notes-pool" {
  name = "notes-pool"
  username_attributes = ["email"]

  verification_message_template {
    default_email_option = "CONFIRM_WITH_CODE"
  }

  password_policy {
    minimum_length    = 10
    require_lowercase = false
    require_numbers   = true
    require_symbols   = false
    require_uppercase = true
  }

  tags {
    "Name"    = "notes-pool"
    "Environment" = "production"
  }
}
</code>```

The above works just fine, and my user pool is created. If anybody has any ideas on how to create an app client in the same resource, I'm all ears. I'm beginning to suspect that this functionality doesn't exist!

答: Once user pool is created, you can use create-user-pool-client API to create app-client within the userpool. Please refer the API documentation: https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html</p>

Title: Terraform AWS Cognito App Client

Body:
Currently stuck in the mud with trying to to set up an 'app client' for an AWS Cognito User Pool through Terraform. Here is my resource as it stands:

resource "aws_cognito_user_pool" "notes-pool" {
  name = "notes-pool"
  username_attributes = ["email"]

  verification_message_template {
    default_email_option = "CONFIRM_WITH_CODE"
  }

  password_policy {
    minimum_length    = 10
    require_lowercase = false
    require_numbers   = true
    require_symbols   = false
    require_uppercase = true
  }

  tags {
    "Name"    = "notes-pool"
    "Environment" = "production"
  }
}

The above works just fine, and my user pool is created. If anybody has any ideas on how to create an app client in the same resource, I'm all ears. I'm beginning to suspect that this functionality doesn't exist!


问:
Keep getting unexpected unindent on Python 2.7
I keep getting "unexpected unindent" error on python, i tried everything but i just can't seem to find where i'm making mistakes. Without the while statement the script works, but with the while statement i get the error, here is the part of the code involved

```<code>import time, requests, json

while True:
    try:
        BU = requests.session()
        URL = 'https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-PART'
        r = BU.get(URL, timeout=(15, 10))
        MarketPairs = json.loads(r.content)
        for element in MarketPairs['result']:
            id = element['Id']
            price = element['Price']
            tot = element['Total']
            time = element['TimeStamp']
            type = element['OrderType']
            print type, tot, time, id

except Exception as e:
    print e
    print 'Error... possible timeout'
</code>```

The error is: There is an error in your program: unexpected unindent.

答:
The full error message should make the problem pretty obvious.

```<code>File "./test.py", line 17

                                         ^
IndentationError: unexpected unindent
</code>```

The line that it is having an error on is one right after the end of the file, so it's expecteing something else.

Every time you have a try statement, it needs an except statement to know what to do. Your program is expecting that, and since the following line isn't indented equal to the try block, it throws an indentation error because the fact that the line isn't indented is the first thing the program sees and quits.

See This guide on try/excepts for more information.

Body:
I keep getting "unexpected unindent" error on python, i tried everything but i just can't seem to find where i'm making mistakes. Without the while statement the script works, but with the while statement i get the error, here is the part of the code involved

import time, requests, json

while True:
    try:
        BU = requests.session()
        URL = 'https://bittrex.com/api/v1.1/public/getmarkethistory?market=BTC-PART'
        r = BU.get(URL, timeout=(15, 10))
        MarketPairs = json.loads(r.content)
        for element in MarketPairs['result']:
            id = element['Id']
            price = element['Price']
            tot = element['Total']
            time = element['TimeStamp']
            type = element['OrderType']
            print type, tot, time, id

except Exception as e:
    print e
    print 'Error... possible timeout'

The error is: There is an error in your program: unexpected unindent.

Body:
The full error message should make the problem pretty obvious.

File "./test.py", line 17

                                         ^
IndentationError: unexpected unindent

The line that it is having an error on is one right after the end of the file, so it's expecteing something else.

Every time you have a try statement, it needs an except statement to know what to do. Your program is expecting that, and since the following line isn't indented equal to the try block, it throws an indentation error because the fact that the line isn't indented is the first thing the program sees and quits.

See This guide on try/excepts for more information.


问:
How many rows should be in the (main) buffer of a virtual Listview control?
How many rows should be in the (main) buffer of a virtual Listview control?

I am witting an application in pure 'c' to the Win32 API.  There is an ODBC connection to a database which will retrieve the items (actually rows).

The MSDN sample code implies a fixed size buffer of 30 for the end cache (Which would almost certainly not be optimal).  I think the end cache and the main cache should be the same size.

My thinking is that the buffer should be more than the maximum number of items that could be displayed by the list view at one time.  I guess this could be re-calculated each time the Listivew was resized?

Or, is it just better to go with a large fixed value.  If so what is that value?

答: The LVN_ODCACHEHINT notification message will let you know how many items it is going to ask. This could help you in deciding how big your cache should be.</p>

OwnerDisplayName: David Morris

LastEditorDisplayName: David Morris

OwnerDisplayName: Lars Truijens


问:
What are the File Permission Signs @ and + for?
My mac has folders Shared and Public folders. Their permissions are drwxr-xr-x+ for Public and drwxrwxrwt@ for Shared. What do the signs + and @ mean?</p>

答: I'm not familiar with extended attributes, but the extended security information, aka ACLs, give more fine-grained control over file permissions.  Basically, that + comes up whenever you set permissions on a file/directory beyond the usual choices of read/write/execute for user/group/other.  You can see the ACLs by doing a 'ls -le'.</p>

OwnerDisplayName: HL

LastEditorDisplayName: GregD

OwnerDisplayName: Jeff


问:
Call a function whenever the viewport size is changed by user
I'm trying to make an event listener like this:

```<code>window.addEventListener("resize", console.log("You just resized the browser window."));
</code>```

But it only fires once when page is loaded, and never fires again no matter how I resize the window in whatever way. Why?

I've also tried jQuery:

```<code>$(window).on("resize", console.log("You just resized the browser window."));
</code>```

and

```<code>$(window).resize(console.log("You just resized the browser window."));
</code>```

They didn't work either. The three are essentially all the same.

答:
You are executing console.log instead of passing a reference to the call for the event listener to fire.

This will work:

```<code>notify = function() { console.log("You just resized the browser window.")}
window.addEventListener("resize", notify)
</code>```

Body:
I'm trying to make an event listener like this:

window.addEventListener("resize", console.log("You just resized the browser window."));

But it only fires once when page is loaded, and never fires again no matter how I resize the window in whatever way. Why?

I've also tried jQuery:

$(window).on("resize", console.log("You just resized the browser window."));

and

$(window).resize(console.log("You just resized the browser window."));

They didn't work either. The three are essentially all the same.

Body:
You are executing console.log instead of passing a reference to the call for the event listener to fire.

This will work:

notify = function() { console.log("You just resized the browser window.")}
window.addEventListener("resize", notify)


问:
Ruby on Rails, jquery doesn't assign value to model
I have a basic form in my Ruby on Rails application. One of the fields is calculated according to others. If validation fails, and new action is rendered, calculated value is evaporated.

```<code>class Model < ApplicationRecord

end
</code>```

This is my controller:

```<code>class ModelsController < ApplicationController

    def create
        @model = Model.new(secure_params)

        if @model.save
          redirect_to @model
        else
          render 'new'
        end
    end

    def secure_params
       params.require(:model).permit(:count,:unitPrice,:totalPrice);
    end

end
</code>```

This is new.html.erb form:

```<code><%= form_with model: @model, local: true do |form| %>
    <p>
      <%= form.label :count %><br>
      <%= form.number_field :count, id:'count' %>
    </p>
    <p>
      <%= form.label :unitPrice %><br>
      <%= form.number_field :unitPrice, id:'unitPrice' %>
    </p>

    <p>
      <%= form.label :totalPrice %><br>
      <%= form.number_field :totalPrice, id:'totalPrice' %>
    </p>

    <p>
      <%= form.submit %>
    </p>
<% end %>

<script>

  function calculateTotalPrice(){

     var count=$("#count").val();
     var unitPrice=$("#unitPrice").val();

     if(unitPrice && count ){
        var totalPrice=parseFloat(unitPrice*count).toFixed(2);
        $("#totalPrice").val(totalPrice);
     }
  }

  $(document).ready(function(){

      $("#count").bind('keyup mouseup',calculateTotalPrice);
      $("#unitPrice").bind('keyup mouseup',calculateTotalPrice);

  });

</script>
</code>```

When I submit the form, if validation is ok then there is no problem. But if model has errors, totalPrice value is removed from model. I think value inserted to totalPrice field is not injected to the Ruby model.

What am I missing?

Thanks.

答:
The jQuery looks fine.

It could be blocked because number inputs only accept integer values by default. Setting parameter step to 'any' will allow for decimal values. Try:

<%= form.number_field :totalPrice, id:'totalPrice', step: :any %>

Also, double check that the totalPrice field is not of type integer in Model, but rather float or decimal.

Body:
I have a basic form in my Ruby on Rails application. One of the fields is calculated according to others. If validation fails, and new action is rendered, calculated value is evaporated.

class Model < ApplicationRecord

end

This is my controller:

class ModelsController < ApplicationController

    def create
        @model = Model.new(secure_params)

        if @model.save
          redirect_to @model
        else
          render 'new'
        end
    end

    def secure_params
       params.require(:model).permit(:count,:unitPrice,:totalPrice);
    end

end

This is new.html.erb form:

<%= form_with model: @model, local: true do |form| %>

      <%= form.label :count %>

      <%= form.number_field :count, id:'count' %>

      <%= form.label :unitPrice %>

      <%= form.number_field :unitPrice, id:'unitPrice' %>

      <%= form.label :totalPrice %>

      <%= form.number_field :totalPrice, id:'totalPrice' %>

      <%= form.submit %>

<% end %>

When I submit the form, if validation is ok then there is no problem. But if model has errors, totalPrice value is removed from model. I think value inserted to totalPrice field is not injected to the Ruby model.

What am I missing?

Thanks.