问:
Can I set ng-model to two values?
I have an input

```<code><input type="text" ng-model="choice.text">
</code>```

Where choice.text creates a new text property in the object choice. This allows me to send the contents of the input to different page. While this feature works, I would also like to add another feature where the content of the input is displayed and updated in real time on the page. Something to this effect.

Unfortunately, ng-model is already set to choice.text. Is there a way I can have set two values to one ng-model? It would perhaps look like this:

```<code><input type="text" ng-model="choice.text name"></p>
<p ng-bind="name"></p>
</code>```

If not, is there another way to achieve this effect?

EDIT: For those wondering, when I try

it doesnt work for some reason.

EDIT 2: I simplified the code for the sake of the question. Here is the actual code for more detail:

```<code><div class ="ask-container">
    <div ng-switch="cbstate">
      <div ng-switch-when="not-pressed">
        <h1>Choose between... </h1> <!-- I would like to add the dynamic element here -->
      </div>
      <div ng-switch-when="pressed">
        <h1>Hi</h1>
      </div>
    </div>
    <form role="form" ng-submit="submitChoice()">
      <div class="input" ng-repeat="choice in poll.options">
        <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}"><br>
      </div>
      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>
</div>
</code>```

EDIT 3: Same code, but with the ng-bind:

```<code><div class ="ask-container">
    <div ng-switch="cbstate">
      <div ng-switch-when="not-pressed">
        <h1>Choose between... </h1>
      </div>
      <div ng-switch-when="pressed">
        <h1>Hi</h1>
      </div>
    </div>
    <form role="form" ng-submit="submitChoice()">
      <div class="input" ng-repeat="choice in poll.options">
        <input type="text"  ng-model="choice.text" ng-change="temp=choice.text" placeholder="Choice {{$index+1}}"><br>
      </div>
      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>
    <p ng-bind="temp"></p>
    <p ng-bind="choice.text"></p>
</div>
</code>```

Note: Somebody said that the ng-repeat may be messing with my scope. Maybe keep that in mind as you try and fix my problem.

答:
Is this not acceptable?</p>

```<code><input type="text" ng-model="choice.text"></p>
<p ng-bind="choice.text"></p>
</code>```

Title: Can I set ng-model to two values?

Body:
I have an input

<input type="text" ng-model="choice.text">

Where choice.text creates a new text property in the object choice. This allows me to send the contents of the input to different page. While this feature works, I would also like to add another feature where the content of the input is displayed and updated in real time on the page. Something to this effect.

Unfortunately, ng-model is already set to choice.text. Is there a way I can have set two values to one ng-model? It would perhaps look like this:

<input type="text" ng-model="choice.text name">

If not, is there another way to achieve this effect?

EDIT: For those wondering, when I try

it doesnt work for some reason.

EDIT 2: I simplified the code for the sake of the question. Here is the actual code for more detail:

Choose between...

Hi

    <form role="form" ng-submit="submitChoice()">

        <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}">

      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>

EDIT 3: Same code, but with the ng-bind:

Choose between...

Hi

    <form role="form" ng-submit="submitChoice()">

        <input type="text"  ng-model="choice.text" ng-change="temp=choice.text" placeholder="Choice {{$index+1}}">

      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>

Note: Somebody said that the ng-repeat may be messing with my scope. Maybe keep that in mind as you try and fix my problem.

Body:
Is this not acceptable?

<input type="text" ng-model="choice.text"></p>
<p ng-bind="choice.text"></p>


来源: stackexchange

问:
Click expand on html
I want to do Expand/collapse on click (See pic below).

When a person clicks on the PLUS(+) sign, it expands and the signs change itself to Minus(-) sign and when a person clicks on Minus Sign it Collapse and again changes to Plus Sign.

Here is the Image,

答:
I think you are looking for Tree view. If its you can achieve this using jquery plugin

jQuery-Folder-Tree-Plugin

ContentLicense: CC BY-SA 3.0

Title: Click expand on html


问:
Create CSR(Certificate Signing Request) using javascript at client side
I want to create CSR(Certificate Signing Request) using javascript at client side using any browser(IE, Firefox, Chrome etc).

I have google it and found some js belows like PKIJS and WEB API Crypto and HTML KEYGEN Tag.

https://pkijs.org/

https://developer.mozilla.org/en/docs/Web/API/SubtleCrypto

But not able to find some relavant resources or example to generate CSR using javascript at client side.

It will be much appreciated if anyone can help me ..

答: Here is a sample using PKI.js to generate a CSR. Source code here</p>

ContentLicense: CC BY-SA 4.0


问:
Problem with jQuery append in ie7
Hi guys I am having a very strange problem in ie with the append function. Basicly i retrieve data from an ajax call in xml. Parse the xml into variables then using the each function append to a specific div. Works fine in firefox had to do a work around to get the file to parse in ie. Please note 'ALL WORKS' fine my variables etc. all have values etc.

However when I use the append function some of the text randomly appears outside its containing div see picture below:

alt text http://www.freeimagehosting.net/uploads/e21468dd49.png

As you can see some of the text overflows the container or almost seems to reflect ?
Any way below is a snippet of the code where i make the append: I should also add I am opening this div in a dialog box created with jquery ui - which sets the containing div to display: block - so i am wondering if this is having any effect.

```<code>$(xml).find("entry").each(function()
{

var $item = $(this);
var title = $item.find("title").text();
var linkN = $item.find("link").attr("href");
var output = "<a href=\"" + linkN + "\" target=\"_self\">" + title + "<\/a>" + "<br />";
$("#notifyBox").append($(output));
$('#notifyBox').show();
});
</code>```

Really hope you guys can help this is the strangest problem I have ever encountered.

答:
I've solved this:</p>

```<code>var a = '<span>Attachment: '+Filedata.substr(Filedata.lastIndexOf('\\')+1).toLowerCase()+'</span>';
var b = '<span ><a href="#" class="remove_link" style="cursor:pointer; ">Remove</a></span></br></br>';
                var c = a+' '+b; // use instead of append
                $('div.attach_file').hide();
                $('div.Multi_Attach_file').show().html(c); // display c
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem with jQuery append in ie7

Body:
Hi guys I am having a very strange problem in ie with the append function. Basicly i retrieve data from an ajax call in xml. Parse the xml into variables then using the each function append to a specific div. Works fine in firefox had to do a work around to get the file to parse in ie. Please note 'ALL WORKS' fine my variables etc. all have values etc.

However when I use the append function some of the text randomly appears outside its containing div see picture below:

alt text http://www.freeimagehosting.net/uploads/e21468dd49.png

As you can see some of the text overflows the container or almost seems to reflect ?
Any way below is a snippet of the code where i make the append: I should also add I am opening this div in a dialog box created with jquery ui - which sets the containing div to display: block - so i am wondering if this is having any effect.

$(xml).find("entry").each(function()
{

var $item = $(this);
var title = $item.find("title").text();
var linkN = $item.find("link").attr("href");
var output = "" + title + "<\/a>" + "
";
$("#notifyBox").append($(output));
$('#notifyBox').show();
});

Really hope you guys can help this is the strangest problem I have ever encountered.

Body:
I've solved this:

var a = '<span>Attachment: '+Filedata.substr(Filedata.lastIndexOf('\\')+1).toLowerCase()+'</span>';
var b = '<span ><a href="#" class="remove_link" style="cursor:pointer; ">Remove</a></span></br></br>';
                var c = a+' '+b; // use instead of append
                $('div.attach_file').hide();
                $('div.Multi_Attach_file').show().html(c); // display c


问:
Serving stored user images through authenticated rails api
I am using a Rails 4 api server. There are some stored user images on production server storage. Only authenticated and authorised users should be able to view their respective images.

I have authentication and authorisation modules sorted out in my APIs. However, what would be the way to serve these assets through API other than putting them in asset pipeline?

答:
As a solution to this, I used regular Rails APIs with authentication and authorisation.
The show controller method serves the file like this:</p>

```<code>send_file file_path_on_server, disposition: 'inline'
</code>```

Body:
As a solution to this, I used regular Rails APIs with authentication and authorisation.
The show controller method serves the file like this:

send_file file_path_on_server, disposition: 'inline'


问:
Basic Approach to Diagnostic Logging in SSIS
Given help from this microsoft link, I am aware of many tools related to SSIS diagnostics:

Event Handlers (in particular, "OnError")

Error Outputs

Operations Reports

SSISDB Views

Logging

Debug Dump Files

I just want to know what is the basic, "go to" approach for (non-production) diagnostics setup with SSIS.  I am a developer who WILL have access to the QA and UAT servers where I will be performing diagnostics.

In my first attempt to find the source of an error, I used SSMS to view operational reports.  All I saw was this:

I followed the instructions shown above, but all it did was lead me in a circle.  The overview allows me to see the details, but the details show the above message and ask me to go back to the overview.  In short, there is zero error information beyond telling me which task failed within the SSIS package.

I simply want to get to a point where I can at last see SOMETHING about the error(s).

If the answer is that I first need to configure an OnError event in my package, then my next question is: what would the basic, "go to" designer-flow look like for that OnError event?

FYI, this question is similar to "best way of logging in SSIS"

I also noticed an overall strategy for success with SSIS in this answer.  The author says:

Instrument your code - have it make log entries, possibly recording diagnostics such as check totals or counts. Without this, troubleshooting is next to impossible. Also, assertion checking is a good way to think of error handling for this (does row count in a equal row count in b, is A:B relationship really 1:1).

Sounds good!  But I'd like to have a more concrete example...particularly for feeding me the basics of what specific errors were generated.

I'm trying to avoid learning ALL the SSIS diagnostic approaches, just for the purpose of picking one good "all around" approach.

Update

Per Nick.McDermaid suggestion, in the SSISDB DB I run this:

```<code>SELECT * FROM [SSISDB].[catalog].[executions] ORDER BY start_time DESC
</code>```

This shows to me the packages that I manually executed.  The timestamps correctly reflect when I ran them.  If anything is unusual(?) it is that the reference_id, reference_type and environment_name columns are null. All the other columns have values.

Update #2

I discovered half the answer I'm looking for.  The reason no error information is available, is because by default the SSIS package execution logging level is "none".  I had to change the logging level.

Nick.McDermaid gave me the rest of the answering by explaining that I don't need to dive into OnError tooling or SSIS logging provider tooling.

答:
I'm not sure what the issue with your reports are but in answer to the question "Which SSIS diagnostics should I learn", I suggest the vanilla ones out of the box.

In other words use built in SSIS logging (which does not require any additional code) to log failures. Then use the built in reports (once you get them working) to check those logs.

vanilla functionality requires no maintenance. Custom functionality (i.e. filling your packages up with OnError events) requires a lot more maintenance.

You may find situations where you need to learn some of the SSISDB tricks to troubleshoot but in the first instance, try to get everything you can out of the vanilla reports.

If you need to maintain an SQL 2012 or after existing system, then all of this logging is built in. Manual OnError additions are not guaranteed to be built in

The only other thing to be aware of is that script tasks never yield informative errors. I actually suggest you avoid the use of script tasks in SSIS. I feel that if you have to use a script task, you might be using the wrong tool

Body:
Given help from this microsoft link, I am aware of many tools related to SSIS diagnostics:

Event Handlers (in particular, "OnError")

Error Outputs

Operations Reports

SSISDB Views

Logging

Debug Dump Files

I just want to know what is the basic, "go to" approach for (non-production) diagnostics setup with SSIS.  I am a developer who WILL have access to the QA and UAT servers where I will be performing diagnostics.

In my first attempt to find the source of an error, I used SSMS to view operational reports.  All I saw was this:

I followed the instructions shown above, but all it did was lead me in a circle.  The overview allows me to see the details, but the details show the above message and ask me to go back to the overview.  In short, there is zero error information beyond telling me which task failed within the SSIS package.

I simply want to get to a point where I can at last see SOMETHING about the error(s).

If the answer is that I first need to configure an OnError event in my package, then my next question is: what would the basic, "go to" designer-flow look like for that OnError event?

FYI, this question is similar to "best way of logging in SSIS"

I also noticed an overall strategy for success with SSIS in this answer.  The author says:

Instrument your code - have it make log entries, possibly recording diagnostics such as check totals or counts. Without this, troubleshooting is next to impossible. Also, assertion checking is a good way to think of error handling for this (does row count in a equal row count in b, is A:B relationship really 1:1).

Sounds good!  But I'd like to have a more concrete example...particularly for feeding me the basics of what specific errors were generated.

I'm trying to avoid learning ALL the SSIS diagnostic approaches, just for the purpose of picking one good "all around" approach.

Update

Per Nick.McDermaid suggestion, in the SSISDB DB I run this:

SELECT * FROM [SSISDB].[catalog].[executions] ORDER BY start_time DESC

This shows to me the packages that I manually executed.  The timestamps correctly reflect when I ran them.  If anything is unusual(?) it is that the reference_id, reference_type and environment_name columns are null. All the other columns have values.

Update #2

I discovered half the answer I'm looking for.  The reason no error information is available, is because by default the SSIS package execution logging level is "none".  I had to change the logging level.

Nick.McDermaid gave me the rest of the answering by explaining that I don't need to dive into OnError tooling or SSIS logging provider tooling.


问:
can i combine if else and with try catch python?
i have a code :

```<code>s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")
</code>```

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

答:
You can raise an exception if the function returns False, by doing:

```<code>s = '127.0.0.0'

def validate(a):
    a = a.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return True

try:
    if not validate(s): #ip validation
        raise TypeError
except TypeError:
    print("insert you're ip correctly")
</code>```

Note: you probably want to return True for the end, since I believe that's when the function validates successfully, and a = a.split('.') not s.split, or else you're splitting the global variable s.

Tip: when using try...except, try to catch a specific error than to use the catch-all except:.

Body:
i have a code :

s = '127.0.0.0'

def validate(a):
    a = s.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return False

try:
    validate(s) #ip validation
    #my code here
except :
    print("insert you're ip correctly")

can i combine if else with try catch like that?

if the try catch got error message or like return false from if condition it will run the except condition, if not it will run the try condition until the process is end.

there's have a better ways to dot this?

Body:
You can raise an exception if the function returns False, by doing:

s = '127.0.0.0'

def validate(a):
    a = a.split('.')
    if len(a) !=4:
        return False
    for x in a :
        if not x.isdigit():
            return False
        i = int(x)
        if i < 0 or i > 255 :
            return False
    return True

try:
    if not validate(s): #ip validation
        raise TypeError
except TypeError:
    print("insert you're ip correctly")

Note: you probably want to return True for the end, since I believe that's when the function validates successfully, and a = a.split('.') not s.split, or else you're splitting the global variable s.

Tip: when using try...except, try to catch a specific error than to use the catch-all except:.


问:
All cv2 functions are not found
I have pip installed opencv-python on my Ubuntu guest OS hosted in a virtual box. Both my python and Ubuntu are 64-bit. But when I import cv2 I couldn't find all the functions to manipulate images. The following is an image of the ini file I get when I do ctrl+B.

I uninstalled the opencv and followed many tutorials to install opencv using apt-get including from the official opencv website and none of them worked for me. Can someone give me a hint what I can do to get opencv to work?

答:
Following this tutorial, I was able to finally install opencv properly. I am posting my answer to help someone in a similar situation. Ubuntu version is the most important thing you have to check before you follow any of the tutorials. Just like my case, if you happen to follow one of the old tutorials but your Ubuntu version is 16, you need to remove the opencv altogether then follow the tutorial.
After the fix, my ini looks like this. It consists all the functions to manipulate image. The screenshot shows the partial shot in my ide.

Title: All cv2 functions are not found


问:
How to make NSIS create a file in an %APPDATA% of another user?
I wrote an NSIS installer script for postgresql 9.1. The installer works properly, but after the reboot, the service is not started (right after the install, the database started properly though)

I guess this is because the postgres service user has no pgpass.conf file in its %APPDATA%. As far as I understand my install script, the pgpass.conf file is added to the %APPDATA% of the user running the installer (an administrator account in my case). This will not help.

I tried the following, to add the pgpass.conf to all users, bt I guess this adds it to a kind of wildcard, not to the %APPDATA% of each user :

```<code>SetShellVarContext "all"
SetOutPath "$APPDATA\postgresql"
File config\pgpass.conf
SetShellVarContext "current"
SetOutPath "$APPDATA\postgresql"
File config\pgpass.conf
</code>```

I couldn't find the macro name for c:/Users/postgres in the documentation. This could be a way to achieve it. But with WindowsXP, 7, I wish I need a portable way to address the /Users directory.

I wish I could use something like SetShellVarContext "postgres", and then have NSIS write the pgpass.conf file in c:\Users\postgres\AppData\postgresql.

Is there a way to do this ?

Thnk you !

答:
SID (security identifier) is a security identifier that identifies a user account, groups, Domain or computer for Windows NT. The system operates with account SIDs, and not their profile usernames. SID is assigned to each account at the time of its creation so if you were to create an account again with the same name and password, the SID will, of course be different. The re-creation of an account will result in the generation of a new SID. They are unique, if you are picking up what I am laying down..

MACRO:

```<code>;=#
;= ${GETUSERSID} $0 "Username"
;       $0          = The returning SID value
;       "Username"  = The username of the account you wish the SID
;                   If the username is an empty value, then the SID of the
;                   current user will be given to $0.
!define GETUSERSID "!insertmacro _GETUSERSID"
!macro _GETUSERSID _RESULT _USER
      System::Store S
      StrCpy $0 ${_USER}
      StrCmp $0 "" 0 +2
      ExpandEnvStrings $0 "%USERNAME%"
      System::Call "*(&t1024)i.r1"
      System::Call "advapi32::LookupAccountName(tn,tr0,ir1,*i1024,tn,*i1024,*in)i.r0"
      IntCmp $0 1 0 +2 +2
      System::Call "advapi32::ConvertSidToStringSid(ir1,*t.s)"
      IntCmp $0 1 +2 0 0
      Push error
      System::Free $1
      System::Store L
      Pop "${_RESULT}"
!macroend

${GETUSERSID} $0 "Username"
MessageBox MB_ICONINFORMATION|MB_OK "User's SID:$\r$\n$$0 is holding $0" IDOK
</code>```

Now here is an example of listing all the registered user accounts on a host PC:

```<code>System::Call "netapi32::NetQueryDisplayInformation(wn,i1,i0,i-1,i${NSIS_MAX_STRLEN},*i.R0,*i.R1)i.R4"
${If} $R4 = 0
    ${For} $R4 1 $R0
        System::Call "*$R1(i.R2,i.R3,i,w,i,i)"
        IntFmt "$R2" ${STR} $R2
        IntFmt "$R3" ${STR} $R3
        ${GetUserSID} "$R2" "$R5"
        IntOp $R1 $R1 + 24
        DetailPrint "-----------------"
        DetailPrint "Name: $R2"
        DetailPrint "SID: $R5"
        DetailPrint "$R3"
    ${Next}
    System::Call "netapi32::NetApiBufferFree(iR1)"
${EndIf}
</code>```

Now I am not sure if this will work or not (premissions maybe, but then there is always ACL) but here is an example (if I understand your issue correctly) of implimenting what you are asking.

```<code>${GETUSERSID} $0 "postgres"
ReadRegStr $1 HKU "$0\Volatile Environment" "APPDATA"
DetailPrint "APPDATA: $1"
AccessControl::GrantOnFile $1 "USER" "ListDirectory + GenericRead + GenericExecute"
AccessControl::EnableFileInheritance $1
SetOutPath "$1\postgresql"
File config\pgpass.conf
</code>```

This was just a quick fix ..not even sure this will work but maybe a step in the right direction for you? Hope this helps!

Body:
I wrote an NSIS installer script for postgresql 9.1. The installer works properly, but after the reboot, the service is not started (right after the install, the database started properly though)

I guess this is because the postgres service user has no pgpass.conf file in its %APPDATA%. As far as I understand my install script, the pgpass.conf file is added to the %APPDATA% of the user running the installer (an administrator account in my case). This will not help.

I tried the following, to add the pgpass.conf to all users, bt I guess this adds it to a kind of wildcard, not to the %APPDATA% of each user :

SetShellVarContext "all"
SetOutPath "$APPDATA\postgresql"
File config\pgpass.conf
SetShellVarContext "current"
SetOutPath "$APPDATA\postgresql"
File config\pgpass.conf

I couldn't find the macro name for c:/Users/postgres in the documentation. This could be a way to achieve it. But with WindowsXP, 7, I wish I need a portable way to address the /Users directory.

I wish I could use something like SetShellVarContext "postgres", and then have NSIS write the pgpass.conf file in c:\Users\postgres\AppData\postgresql.

Is there a way to do this ?

Thnk you !

Body:
SID (security identifier) is a security identifier that identifies a user account, groups, Domain or computer for Windows NT. The system operates with account SIDs, and not their profile usernames. SID is assigned to each account at the time of its creation so if you were to create an account again with the same name and password, the SID will, of course be different. The re-creation of an account will result in the generation of a new SID. They are unique, if you are picking up what I am laying down..

MACRO:

;=#
;= ${GETUSERSID} $0 "Username"
;       $0          = The returning SID value
;       "Username"  = The username of the account you wish the SID
;                   If the username is an empty value, then the SID of the
;                   current user will be given to $0.
!define GETUSERSID "!insertmacro _GETUSERSID"
!macro _GETUSERSID _RESULT _USER
      System::Store S
      StrCpy $0 ${_USER}
      StrCmp $0 "" 0 +2
      ExpandEnvStrings $0 "%USERNAME%"
      System::Call "*(&t1024)i.r1"
      System::Call "advapi32::LookupAccountName(tn,tr0,ir1,*i1024,tn,*i1024,*in)i.r0"
      IntCmp $0 1 0 +2 +2
      System::Call "advapi32::ConvertSidToStringSid(ir1,*t.s)"
      IntCmp $0 1 +2 0 0
      Push error
      System::Free $1
      System::Store L
      Pop "${_RESULT}"
!macroend

${GETUSERSID} $0 "Username"
MessageBox MB_ICONINFORMATION|MB_OK "User's SID:$\r$\n$$0 is holding $0" IDOK

Now here is an example of listing all the registered user accounts on a host PC:

System::Call "netapi32::NetQueryDisplayInformation(wn,i1,i0,i-1,i${NSIS_MAX_STRLEN},*i.R0,*i.R1)i.R4"
${If} $R4 = 0
    ${For} $R4 1 $R0
        System::Call "*$R1(i.R2,i.R3,i,w,i,i)"
        IntFmt "$R2" ${STR} $R2
        IntFmt "$R3" ${STR} $R3
        ${GetUserSID} "$R2" "$R5"
        IntOp $R1 $R1 + 24
        DetailPrint "-----------------"
        DetailPrint "Name: $R2"
        DetailPrint "SID: $R5"
        DetailPrint "$R3"
    ${Next}
    System::Call "netapi32::NetApiBufferFree(iR1)"
${EndIf}

Now I am not sure if this will work or not (premissions maybe, but then there is always ACL) but here is an example (if I understand your issue correctly) of implimenting what you are asking.

${GETUSERSID} $0 "postgres"
ReadRegStr $1 HKU "$0\Volatile Environment" "APPDATA"
DetailPrint "APPDATA: $1"
AccessControl::GrantOnFile $1 "USER" "ListDirectory + GenericRead + GenericExecute"
AccessControl::EnableFileInheritance $1
SetOutPath "$1\postgresql"
File config\pgpass.conf

This was just a quick fix ..not even sure this will work but maybe a step in the right direction for you? Hope this helps!


问:
What CSS properties are likely to cause problems in Internet Explorer?
I designed a web page with lot of CSS properties, and when viewing it in IE its alignment is not so proper compared to all other browsers.

For the next time, what are the CSS properties I should take care with in IE?

Thank you.

答:
If you have a div with a margin floated to the same side, it will cause a double margin in IE:

```<code>div
{
  margin-left: 10px;
  float: left;
}
</code>```

or

```<code>div
{
  margin-right: 10px;
  float: right;
}
</code>```

The margin will in fact be 20px in IE.

The fix is to add display:inline.

Body:
If you have a div with a margin floated to the same side, it will cause a double margin in IE:

div
{
  margin-left: 10px;
  float: left;
}

or

div
{
  margin-right: 10px;
  float: right;
}

The margin will in fact be 20px in IE.

The fix is to add display:inline.


问:
TypeError: corr() missing 1 required positional argument: 'other'
I am new to python and have hit a wall. I should count pearson correlation coefficient, but I have error. The only thing I can think of is that python requires different syntax.

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

data = pandas.read_csv('One_imortant_table.csv', index_col='Id')
corr1 = data['Numb'].corr(method='pearson', min_periods=1)
print(corr1)
</code>```

TypeError:

```<code>--->  corr1 = data['Numb'].corr(method='pearson', min_periods=1)
TypeError: corr() missing 1 required positional argument: 'other'
</code>```

What am I doing wrong here? I have searched for this mistake, but can't find any more. I am using windows 10 with the latest version of python, coding in Jupyter.

答:
You need at least 2 columns to calculate correlation. Try this to see if it works?</p>

```<code>data.corr(method='pearson', min_periods=1)
</code>```

Body:
I am new to python and have hit a wall. I should count pearson correlation coefficient, but I have error. The only thing I can think of is that python requires different syntax.

import pandas
import numpy as np

data = pandas.read_csv('One_imortant_table.csv', index_col='Id')
corr1 = data['Numb'].corr(method='pearson', min_periods=1)
print(corr1)

TypeError:

--->  corr1 = data['Numb'].corr(method='pearson', min_periods=1)
TypeError: corr() missing 1 required positional argument: 'other'

What am I doing wrong here? I have searched for this mistake, but can't find any more. I am using windows 10 with the latest version of python, coding in Jupyter.

Body:
You need at least 2 columns to calculate correlation. Try this to see if it works?

data.corr(method='pearson', min_periods=1)


问:
How to find due date from selected date?
I want to find due date from select date but it does't get. So please help me how to get due date. Here is my code below.

```<code>Calendar date = Calendar.getInstance();
date.setTimeInMillis(date_in_mil);
date.add(Calendar.DAY_OF_WEEK_IN_MONTH, 40);
</code>```

This is for a pregnancy app I am creating.

答:
You are adding 40 to the day of the week in month. This has a different representation as compared to what you actually want.
try this instead

```<code>date.add(Calendar.DAY_OF_YEAR, 40);
</code>```

Please read official documentation here

EDIT

here is the complete solution :

```<code>String currentDate = "01/05/2017";

try {
  Date curentDateObj = new SimpleDateFormat("dd/mm/yyyy").parse(currentDate);
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(curentDateObj);
  calendar.add(Calendar.WEEK_OF_YEAR, 40);
  System.out.println(calendar.getTime());
} catch (ParseException e) {
  e.printStackTrace();
}
</code>```

Body:
I want to find due date from select date but it does't get. So please help me how to get due date. Here is my code below.

Calendar date = Calendar.getInstance();
date.setTimeInMillis(date_in_mil);
date.add(Calendar.DAY_OF_WEEK_IN_MONTH, 40);

This is for a pregnancy app I am creating.

Body:
You are adding 40 to the day of the week in month. This has a different representation as compared to what you actually want.
try this instead

date.add(Calendar.DAY_OF_YEAR, 40);

Please read official documentation here

EDIT

here is the complete solution :

String currentDate = "01/05/2017";

try {
  Date curentDateObj = new SimpleDateFormat("dd/mm/yyyy").parse(currentDate);
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(curentDateObj);
  calendar.add(Calendar.WEEK_OF_YEAR, 40);
  System.out.println(calendar.getTime());
} catch (ParseException e) {
  e.printStackTrace();
}


问:
Changing Deeply Nested Object Value
This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

```<code>> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'
</code>```

```<code>> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'
</code>```

答:
You could assign the innermost object to a variable.

```<code>var foo = obj.key1.key2.key3.key4;
</code>```

From there on out, accessing/modifying foo.key5 will be equivalent to accessing/modifying obj.key1.key2.key3.key4.key5.

```<code>foo.key5 = 'new value'
console.log(obj.key1.key2.key3.key4.key5); // 'new value'
</code>```

Title: Changing Deeply Nested Object Value

Body:
This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'

> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'

Body:
You could assign the innermost object to a variable.

var foo = obj.key1.key2.key3.key4;

From there on out, accessing/modifying foo.key5 will be equivalent to accessing/modifying obj.key1.key2.key3.key4.key5.

foo.key5 = 'new value'
console.log(obj.key1.key2.key3.key4.key5); // 'new value'


问:
web api returning HTTP 401 – Unauthorized when using a Bearer Token from Xamarin or UWP client - Azure Active Directory
I have an issue with a web api returning HTTP 401 – Unauthorized  when I use a Bearer Token to access it from a xamarin client. Either the iOS or UWP fail.

-This is an application that authenticates with Azure Active Directory to allow a user to login
-Once successfully logged in it gets a token that in turn is added to the web api request header
-The web api has its authentication  turn on

The issue with azure settings
https://1drv.ms/v/s!ApPhjsvemKJggpR2ax5w4wRJcY7uXQ

the code
https://github.com/wleon12/XamarinForms-AAD-WebAPI.git

I cant seem to figure out what is wrong, appreciate any input or guidance

答:
It depends how you protect the web API.

Normally, when we protect the web API using Azure AD, we will provide the the Audience and Tenant like this code sample. So that when we send the request with the token, the web API will verify the signature of the token and the value we config.

So for the 401 issue, please check the token you acquired with the value you config for the web API project. To check the Audience, Tenant and other values in the token, you can decode it from this site.


问:
Autosys job to start after another job with any status
I need to run job after another job with whatever status the previous job finished.

So far I use

```<code>condition: success(x) or failure(x)
</code>```

can it be written for any status?

I dont know the exact version of the autosys. But not the very latest.

答: condition: done(x)</p>

Body:
I need to run job after another job with whatever status the previous job finished.

So far I use

condition: success(x) or failure(x)

can it be written for any status?

I dont know the exact version of the autosys. But not the very latest.

Body: condition: done(x)


问:
Lumen @ foreach Invalid argument
When I use this code:

```<code> $body=$request->all();
        $contacts = json_decode($request->get('contacts'), true);
        $user_contacts = array_flatten($this->_model->scan_contacts($this->_user->user_id, $contacts));
        $nonsync_contacts = array();
        foreach ($contacts as $contact) {

            if (!in_array($contact["mobile"], $user_contacts)) {
                $nonsync_contacts[] = $contact;
            }
        }
</code>```

I get this error message:

```<code>ErrorException in Arr.php line 493:
Invalid argument supplied for foreach()
</code>```

How do I avoid this error?

答:
You should check your $contacts value before foreach-ing:

```<code>$contacts = json_decode($request->get('contacts'), true);
$contacts = is_array($contacts) ? $contacts : [];
</code>```

Or simply right before foreach

```<code>foreach (($contacts ?: []) as $contact)
</code>```

If you're using PHP 7.0, use null coalesce operator

```<code>foreach (($contacts ?? []) as $contact)
</code>```

As json_decode will always return null the value cannot be decoded due to invalid JSON structure or he encoded data is deeper than the recursion limit. Be sure that your $request->get('contacts') never returns ANY boolean value.

Title: Lumen @ foreach Invalid argument

Body:
When I use this code:

 $body=$request->all();
        $contacts = json_decode($request->get('contacts'), true);
        $user_contacts = array_flatten($this->_model->scan_contacts($this->_user->user_id, $contacts));
        $nonsync_contacts = array();
        foreach ($contacts as $contact) {

            if (!in_array($contact["mobile"], $user_contacts)) {
                $nonsync_contacts[] = $contact;
            }
        }

I get this error message:

ErrorException in Arr.php line 493:
Invalid argument supplied for foreach()

How do I avoid this error?

Body:
You should check your $contacts value before foreach-ing:

$contacts = json_decode($request->get('contacts'), true);
$contacts = is_array($contacts) ? $contacts : [];

Or simply right before foreach

foreach (($contacts ?: []) as $contact)

If you're using PHP 7.0, use null coalesce operator

foreach (($contacts ?? []) as $contact)

As json_decode will always return null the value cannot be decoded due to invalid JSON structure or he encoded data is deeper than the recursion limit. Be sure that your $request->get('contacts') never returns ANY boolean value.


问:
Containerized Kafka client errors when producing messages to the host Kafka server
There are a number of similar types of queries on stackoverflow, but none quite match the problem that I am seeing.

I have a zookeeper/kafka setup on my server which work perfectly.  One can produce

```<code>bin/kafka-console-producer.sh --broker-list 192.168.2.80:9092 --topic test
</code>```

and consume

```<code>bin/kafka-console-consumer.sh --bootstrap-server 192.168.2.80:9092 --topic test --from-beginning
</code>```

locally on the Linux Ubuntu 16.04 server.

From a Docker container - also running Ubuntu 16.04 - I want to produce and consume.  The container's Kafka code was copied from that on the server.
Firstly I can create a new topic

```<code>bin/kafka-topics.sh --create --zookeeper 192.168.2.80:2181 --replication-factor 1 --partitions 1 --topic test2
</code>```

from the container and then list it again

```<code>bin/kafka-topics.sh --list --zookeeper 192.168.2.80:2181
</code>```

However when I try to produce new messages, using the above (kafka-console-producer.sh) command it fails with the following message:

```<code>[2017-06-05 13:59:05,317] ERROR Error when sending message to topic test2  with key: null, value: 2 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for test2-0: 1526 ms has passed since batch creation plus linger time
</code>```

immediately after entering the text of the message and pressing enter.

It may seem strange running a Docker container on the same host, but once this works I will move the container to a separate host for production.

My kafka server.properties file:

```<code>listeners=PLAINTEXT://0.0.0.0:9092
</code>```

Kafka version:

```<code>2.12-0.10.2.1
</code>```

Docker version:

```<code>Docker version 1.12.6, build 78d1802
</code>```

答: Your producer (in the container) can't resolve the host name of your Linux guest OS which is returned in the Kafka producers initial metadata request to the bootstrap server. You can add it manually to the /etc/hosts file inside the container or add "--add-host" parameter to the docker run command that launches the image running your producer</p>

Body:
There are a number of similar types of queries on stackoverflow, but none quite match the problem that I am seeing.

I have a zookeeper/kafka setup on my server which work perfectly.  One can produce

bin/kafka-console-producer.sh --broker-list 192.168.2.80:9092 --topic test

and consume

bin/kafka-console-consumer.sh --bootstrap-server 192.168.2.80:9092 --topic test --from-beginning

locally on the Linux Ubuntu 16.04 server.

From a Docker container - also running Ubuntu 16.04 - I want to produce and consume.  The container's Kafka code was copied from that on the server.
Firstly I can create a new topic

bin/kafka-topics.sh --create --zookeeper 192.168.2.80:2181 --replication-factor 1 --partitions 1 --topic test2

from the container and then list it again

bin/kafka-topics.sh --list --zookeeper 192.168.2.80:2181

However when I try to produce new messages, using the above (kafka-console-producer.sh) command it fails with the following message:

[2017-06-05 13:59:05,317] ERROR Error when sending message to topic test2  with key: null, value: 2 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for test2-0: 1526 ms has passed since batch creation plus linger time

immediately after entering the text of the message and pressing enter.

It may seem strange running a Docker container on the same host, but once this works I will move the container to a separate host for production.

My kafka server.properties file:

listeners=PLAINTEXT://0.0.0.0:9092

Kafka version:

2.12-0.10.2.1

Docker version:

Docker version 1.12.6, build 78d1802


问:
"The system cannot find the file specified"
I saw many questions on SO with this error. But none were related to forms. I just hosted my application server after testing locally. I think it worked for a few mins but I'm not sure as I may have looked at the localhost tab for a moment. Then it stopped working. I may have changed something as I was making changes on server too.

I checked my connection string and also tried logging into the DB using other ways and it is online. So, any clues what could be wrong. I don't think it is possible that sql server is only not responding to requests from an app and is available if you log in through SSMS.

Below is the error I get.

Server Error in '/' Application.

The system cannot find the file specified

Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system
  cannot find the file specified

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

[Win32Exception (0x80004005): The system cannot find the file
  specified]

[SqlException (0x80131904): A network-related or instance-specific
  error occurred while establishing a connection to SQL Server. The
  server was not found or was not accessible. Verify that the instance
  name is correct and that SQL Server is configured to allow remote
  connections. (provider: SQL Network Interfaces, error: 52 - Unable to
  locate a Local Database Runtime installation. Verify that SQL Server
  Express is properly installed and that the Local Database Runtime
  feature is enabled.)]

  System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
  exception, Boolean breakConnection, Action1 wrapCloseInAction)
  +5296071    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
  stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558

  System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo,
  SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout,
  Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean
  integratedSecurity, Boolean withFailover) +5308555

  System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo
  serverInfo, String newPassword, SecureString newSecurePassword,
  Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean
  withFailover) +145

  System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo
  serverInfo, String newPassword, SecureString newSecurePassword,
  Boolean redirectedUserInstance, SqlConnectionString connectionOptions,
  SqlCredential credential, TimeoutTimer timeout) +920

  System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer
  timeout, SqlConnectionString connectionOptions, SqlCredential
  credential, String newPassword, SecureString newSecurePassword,
  Boolean redirectedUserInstance) +307

  System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
  identity, SqlConnectionString connectionOptions, SqlCredential
  credential, Object providerInfo, String newPassword, SecureString
  newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
  userConnectionOptions) +434

  System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
  options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
  DbConnectionPool pool, DbConnection owningConnection,
  DbConnectionOptions userOptions) +225

  System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool
  pool, DbConnectionOptions options, DbConnectionPoolKey poolKey,
  DbConnectionOptions userOptions) +37

  System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions
  userOptions) +558

  System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions
  userOptions) +67

  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
  allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +1052

  System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
  owningObject, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +78

  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
  owningConnection, TaskCompletionSource1 retry, DbConnectionOptions
  userOptions, DbConnectionInternal& connection) +167

  System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory,
  TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143

  System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1
  retry) +83    System.Data.SqlClient.SqlConnection.Open() +96

  System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection
  sqlConnection, Action1 act) +79

  System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection
  sqlConnection, Action`1 act) +384

  System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection
  connection) +241

  System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection
  connection) +26

[ProviderIncompatibleException: The provider did not return a
  ProviderManifestToken string.]

  System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection
  connection) +170

  System.Web.Providers.ModelHelper.GetStorageMetadata(String
  providerName, DbConnection connection, String ssdl) +35

  System.Web.Providers.ModelHelper.CreateMetadataWorkspace(String
  providerName, DbConnection connection, String csdl, String ssdl,
  String msl) +154

  System.Web.Providers.ModelHelper.CreateEntityConnection(ConnectionStringSettings
  setting, String csdl, String ssdl, String msl) +109

  System.Web.Providers.ModelHelper.CreateMembershipEntities(ConnectionStringSettings
  setting) +28

  System.Web.Providers.DefaultMembershipProvider.GetPasswordWithFormat(String
  userName, Boolean updateLastLoginActivityDate, Int32& status, String&
  password, Int32& format, String& salt, Int32&
  failedPasswordAttemptCount, Int32& failedPasswordAnswerAttemptCount,
  Boolean& isApproved, DateTime& lastLoginDate, DateTime&
  lastActivityDate) +118

  System.Web.Providers.DefaultMembershipProvider.CheckPassword(String
  userName, String password, Boolean updateLastActivityDate, Boolean
  failIfNotApproved, String& salt, Int32& passwordFormat) +81

  System.Web.Providers.DefaultMembershipProvider.ValidateUser(String
  username, String password) +105

  System.Web.Security.Membership.ValidateUser(String username, String
  password) +26    Staff.Web.Account.Login.OnAuthenticate(Object sender,
  AuthenticateEventArgs e) in
  c:\Assembla\SVN\servicesdue\Staff.Web\Staff.Web\Account\Login.aspx.cs:28
  System.Web.UI.WebControls.Login.OnAuthenticate(AuthenticateEventArgs
  e) +9449786    System.Web.UI.WebControls.Login.AttemptLogin() +119

  System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs
  e) +75    System.Web.UI.Control.RaiseBubbleEvent(Object source,
  EventArgs args) +37

  System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +114

  System.Web.UI.WebControls.Button.RaisePostBackEvent(String
  eventArgument) +159

  System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
  eventArgument) +10

  System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument) +13

  System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
  +35    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  +1724

Version Information: Microsoft .NET Framework Version:4.0.30319;
  ASP.NET Version:4.0.30319.18055

Someone also had this error and they said they were using the wrong store to connect to DB and hence the error. I only have one store in my code. There is no other.

Update:

I found the problem. It is membership related. Something is not right with my membership connection string. But I don't know what. My app requires registration so authentication is enabled. I left the default settings alone. Also published the mdf file in the App_Data folder.
There is a similar question here: Deploying ASP.NET membership to Godaddy. But the solution is not clear and the answer is marked. I added the

to the connection string and I see the error

The connection name 'LocalSqlServer' was not found in the applications
  configuration or the connection string is empty.

So, what should I do? This membership is working flawlessly locally.

Update:

I also tried what this one suggests Godaddy ASP.NET membership database woes. I removed the conn string and added with the name "LocalSqlServer" to make Godaddy happy. Then I removed and added the following with this connectionStringName - DefaultProfileProvider, DefaultMembershipProvider, DefaultRoleProvider and DefaultSessionProvider. Still get the same error of system cannot find the specified file.

答: start the sql server agent, that should fix your problem</p>


问:
How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
I am writing my testcode and I do not want wo write:

```<code>List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
</code>```

I would love to write

```<code>List<string> nameslist = new List<string>({"one", "two", "three"});
</code>```

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

答:
Remove the parentheses:</p>

```<code>List<string> nameslist = new List<string> {"one", "two", "three"};
</code>```

Body:
I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

Body:
Remove the parentheses:

List<string> nameslist = new List<string> {"one", "two", "three"};


问:
I can't connect to mysql?
here is my code please help me to solve this prob.i think error is inside the function. compiler show error on line 9. thanks in advance  </p>

```<code><?php

class db_connector{
var $db_dsn="mysql:host=localhost;dbname=erp5_temp2";
var $db_username = "root";
var $db_password = "";
var $dbh ="";

    public db_connector(){
        $dbh = new PDO($this->$db_dsn,$this->$db_username,$this->$db_password);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
    }
    public get_db_handler(){
        return $dbh;
    }
}
</code>```

<p>?></p>

答:
You forgot function keyword:

```<code>class ClassName
{
    public function methodName()
    {
        // ...
    }
}
</code>```

Title: I can't connect to mysql?

Body:
here is my code please help me to solve this prob.i think error is inside the function. compiler show error on line 9. thanks in advance

<?php

class db_connector{
var $db_dsn="mysql:host=localhost;dbname=erp5_temp2";
var $db_username = "root";
var $db_password = "";
var $dbh ="";

    public db_connector(){
        $dbh = new PDO($this->$db_dsn,$this->$db_username,$this->$db_password);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
    }
    public get_db_handler(){
        return $dbh;
    }
}

?>

Body:
You forgot function keyword:

class ClassName
{
    public function methodName()
    {
        // ...
    }
}


问:
How to use node package in my website?
I'm working on project which is in angularjs . I want to use a node module in current running angular project, how i will added node module in this project.</p>

答:
if you use npm then npm install <package_name> to install package. this will install the package to the node_modules folder by default

Then include via script tag in your index.html

or for styles  use

<link rel="stylesheet" type="text/css" href="path/to/node_module/package.css">

Title: How to use node package in my website?

Body:
if you use npm then npm install <package_name> to install package. this will install the package to the node_modules folder by default

Then include via script tag in your index.html

<script src="./path/to/node_module/package.js"></script>

or for styles  use

<link rel="stylesheet" type="text/css" href="path/to/node_module/package.css">


问:
Ignore Classes and Methods form Code Coverage (jacoco)
In my application I want to ignore to classes (packageName1/Starter/packageName1/IO/CmdException.class) and for every class equals and hashCode method.

My pom.xml looks like:

```<code><build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.0.201403182114</version>
                <configuration>
                    <instrumentation>
                        <ignores>
                            <ignore>*hashCode</ignore>
                             <ignore>*equals</ignore>
                        </ignores>
                        <excludes>
                            <exclude>packageName1/Starter.class</exclude>
                            <exclude>packageName1/IO/CmdException.class</exclude>
                        </excludes>
                    </instrumentation>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</code>```

The problem is that coverage still threats these classes and methods.

答:
This Works for me to exclude classes.</p>

```<code><plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.8</version>

                <configuration>

                    <ignores>
                        <ignore>com.sample.package.bean.*</ignore>

                    </ignores>
                    <excludes>
                        <!-- all class which we want to exclude from the coverage report -->
                        <exclude>**/*class1.class</exclude>
                        <exclude>**/*class2.class</exclude>
                        <exclude>**/*class3.class</exclude>
                        <exclude>**/*class4.class</exclude>

                    </excludes>

                </configuration>

                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
</code>```

Body:
In my application I want to ignore to classes (packageName1/Starter/packageName1/IO/CmdException.class) and for every class equals and hashCode method.

My pom.xml looks like:

<build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.0.201403182114</version>
                <configuration>
                    <instrumentation>
                        <ignores>
                            <ignore>*hashCode</ignore>
                             <ignore>*equals</ignore>
                        </ignores>
                        <excludes>
                            <exclude>packageName1/Starter.class</exclude>
                            <exclude>packageName1/IO/CmdException.class</exclude>
                        </excludes>
                    </instrumentation>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

The problem is that coverage still threats these classes and methods.

Body:
This Works for me to exclude classes.

<plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.8</version>

                <configuration>

                    <ignores>
                        <ignore>com.sample.package.bean.*</ignore>

                    </ignores>
                    <excludes>
                        <!-- all class which we want to exclude from the coverage report -->
                        <exclude>**/*class1.class</exclude>
                        <exclude>**/*class2.class</exclude>
                        <exclude>**/*class3.class</exclude>
                        <exclude>**/*class4.class</exclude>

                    </excludes>

                </configuration>

                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>report</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>


答:
Correlation should be calculated between two columns. The argument 'other' is the second column that should be used. For example, you could do something like that:

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

data = pandas.DataFrame({'Numb':[1,2,3],'a':[7,8,9]})
corr1 = data['Numb'].corr(data['a'],method='pearson', min_periods=1)
print(corr1)
</code>```

This prints 1.0

Body:
I am new to python and have hit a wall. I should count pearson correlation coefficient, but I have error. The only thing I can think of is that python requires different syntax.

import pandas
import numpy as np

data = pandas.read_csv('One_imortant_table.csv', index_col='Id')
corr1 = data['Numb'].corr(method='pearson', min_periods=1)
print(corr1)

TypeError:

--->  corr1 = data['Numb'].corr(method='pearson', min_periods=1)
TypeError: corr() missing 1 required positional argument: 'other'

What am I doing wrong here? I have searched for this mistake, but can't find any more. I am using windows 10 with the latest version of python, coding in Jupyter.

Body:
Correlation should be calculated between two columns. The argument 'other' is the second column that should be used. For example, you could do something like that:

import pandas
import numpy as np

data = pandas.DataFrame({'Numb':[1,2,3],'a':[7,8,9]})
corr1 = data['Numb'].corr(data['a'],method='pearson', min_periods=1)
print(corr1)

This prints 1.0


问:
How to select latest date record and show other columns in mysql?
I'm using XAMPP MYSQL

I have table and the Date Column is String

```<code>  Date    |  Customer   |   Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/20    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  South Beach   15000   1000
2015/6/22    LBalance      California    5000    4000
2015/6/22    LBalance      New York      6000    6000
2015/6/17    InHoss Dept.  North Beach   18000   1000
</code>```

How to select query the latest date record of each customer with different locations?

Expect result:

```<code>Date      |  Customer   |    Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  North Beach   18000   1000
</code>```

this is the closest i've been to: SELECT Customer, Location, Cash, Balance, max(Date) AS "As Of" FROM mytable WHERE Customer = 'LBalance' GROUP BY Customer, Location. Although It's showing the most recent date of a customer but the other column is just showing their first result.

答:
select (*) from xampp
where date = (select max(date) from xampp)</p>

Body:
I'm using XAMPP MYSQL

I have table and the Date Column is String

  Date    |  Customer   |   Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/20    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  South Beach   15000   1000
2015/6/22    LBalance      California    5000    4000
2015/6/22    LBalance      New York      6000    6000
2015/6/17    InHoss Dept.  North Beach   18000   1000

How to select query the latest date record of each customer with different locations?

Expect result:

Date      |  Customer   |    Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  North Beach   18000   1000

this is the closest i've been to: SELECT Customer, Location, Cash, Balance, max(Date) AS "As Of" FROM mytable WHERE Customer = 'LBalance' GROUP BY Customer, Location. Although It's showing the most recent date of a customer but the other column is just showing their first result.


答:
try it

```<code>with cte (date, Customer, Location, Cash , Balance) as
(
select cast('2015/6/23' as datetime) date, 'LBalance' Customer, 'California' Location, 5000 Cash , 3000 Balance
union all
select cast('2015/6/25' as datetime) date, 'LBalance' Customer, 'New York' Location, 6000 Cash , 4500 Balance
union all
select cast('2015/6/25' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/20' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/17' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/22' as datetime) date, 'LBalance' Customer, 'California' Location, 5000 Cash , 4000 Balance
union all
select cast('2015/6/22' as datetime) date, 'LBalance' Customer, 'New York' Location, 6000 Cash , 6000 Balance
union all
select cast('2015/6/27' as datetime) date, 'InHoss Dept.' Customer, 'North Beach' Location, 18000 Cash , 1000 Balance
)

select m.Date, m.Customer, m.Location, m.Cash, m.Balance
   from cte m
   where m.Date = (select max(mm.Date)
                     from cte mm
                    where mm.customer=m.customer
                      and mm.location = m.location )
</code>```

i have checked in my example everething is ok, please be sure that you are using mysql example

Title: How to select latest date record and show other columns in mysql?

Body:
try it

with cte (date, Customer, Location, Cash , Balance) as
(
select cast('2015/6/23' as datetime) date, 'LBalance' Customer, 'California' Location, 5000 Cash , 3000 Balance
union all
select cast('2015/6/25' as datetime) date, 'LBalance' Customer, 'New York' Location, 6000 Cash , 4500 Balance
union all
select cast('2015/6/25' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/20' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/17' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/22' as datetime) date, 'LBalance' Customer, 'California' Location, 5000 Cash , 4000 Balance
union all
select cast('2015/6/22' as datetime) date, 'LBalance' Customer, 'New York' Location, 6000 Cash , 6000 Balance
union all
select cast('2015/6/27' as datetime) date, 'InHoss Dept.' Customer, 'North Beach' Location, 18000 Cash , 1000 Balance
)

select m.Date, m.Customer, m.Location, m.Cash, m.Balance
   from cte m
   where m.Date = (select max(mm.Date)
                     from cte mm
                    where mm.customer=m.customer
                      and mm.location = m.location )

i have checked in my example everething is ok, please be sure that you are using mysql example


问:
OFFSET FETCH unexpected results when PRIMARY KEY is UNIQUEIDENTIFIER
Synopsis:

When querying a table that uses a UNIQUEIDENTIFIER (populated using newsequentialid()) for its primary key, OFFSET / FETCH seems to return inaccurate results if records are inserted that have out of order keys.

I recently implemented a solution using an Entity Attribute Value pattern for a SQL Server table. I created a data layer utilizing the Entity Framework for paged data access. The only relevance of mentioning the Entity Framework is that it is what is responsible for creating the OFFSET / FETCH SQL statements that I will be discussing. I'm aware of alternative solutions that could be implemented that work without using OFFSET / FETCH, however, this is not the intent of my post. The intent of this post is to understand exactly what is happening with the OFFSET / FETCH query.

I'm including the necessary SQL required to replicate this issue.

The following SQL statement will create a Table that implements the EAV pattern:

```<code>CREATE TABLE [dbo].[OptionalValues]
(
     [Id] [uniqueidentifier] NOT NULL
         CONSTRAINT [DF_OptionalValues_Id] DEFAULT (newsequentialid()),
     [Type] [nvarchar](450) NOT NULL,
     [Name] [nvarchar](450) NOT NULL,
     [Value] [nvarchar](450) NOT NULL,

     CONSTRAINT [PK_OptionalValues]
         PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]
</code>```

The following statements will insert test data into the table:

```<code>INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'04c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Eyes', N'Eyes');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'05c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Skin', N'Skin');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'06c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Autonomic Nervous System', N'Autonomic Nervous System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'07c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Kidneys', N'Kidneys');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'08c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Liver', N'Liver');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'09c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Respiratory System', N'Respiratory System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0ac9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Lungs', N'Lungs');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0bc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Central Nervous System', N'Central Nervous System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0cc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Blood', N'Blood');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0dc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Heart', N'Heart');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0ec9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Reproductive System', N'Reproductive System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0fc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Cardiovascular System', N'Cardiovascular System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'd6fdf6b9-6014-e711-815c-080027f9bf3f', N'TargetOrgans', N'TEST_ONE', N'TEST_ONE');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'5a8c5533-6114-e711-815c-080027f9bf3f', N'TargetOrgans', N'TEST_TWO', N'TEST_TWO')
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'801a12da-6214-e711-815c-080027f9bf3f', N'TargetOrgans', N'TEST_THREE', N'TEST_THREE');
</code>```

The last three records inserted have [Id] values that were NOT generated by the table's newsequentialid() function and are out of sync with the other records.

This query will return all 15 records, including the records that have "out of sequence" id's

```<code>SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
</code>```

The next 3 queries are the ones that don't make sense to me. They include an ORDER BY [Type] which is NOT unique, and do NOT include any explicit [Id] ordering

This query does NOT show records that have "out of sequence" id's

```<code>SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
    OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY
</code>```

This query does NOT show records that have "out of sequence" id's even though the result count is still 15???

```<code>SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY
</code>```

This query shows all 15 records including rows that have "out of sequence" id's

```<code>SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
    OFFSET 0 ROWS
    FETCH NEXT 15 ROWS ONLY
</code>```

The "fix" is to add a truly unique sort using the [Id] column.

```<code>SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type], [Id]
    OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type], [Id]
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY
</code>```

My question really surrounds the inaccuracy of the queries that do not have truly unique sort. Why do the queries seemingly recognize the records with an "out of sequence id" in the paged row count, but those records are not shown in the query results? Does the Index created in conjunction with the Primary Key affect the sort behavior of the previous queries in any way?

Thank you for any assistance and clarification that you can provide.

答:
Sql server does not guarantee the order of the results when the order by clause is missing, or when the columns specified in the order by clause contains duplicated values.   This does not mean that the order of the rows is random, It just means it is not something you can trust being consistant. This is true, btw, to any relational database. Tables are un ordered by nature.

It's also the reason why you must specify the order by clause when you are using the offset...fetch next clause, and why you can't use order by in views, derived tables or a cte without using top or offset...fetch next.

Body:
Synopsis:

When querying a table that uses a UNIQUEIDENTIFIER (populated using newsequentialid()) for its primary key, OFFSET / FETCH seems to return inaccurate results if records are inserted that have out of order keys.

I recently implemented a solution using an Entity Attribute Value pattern for a SQL Server table. I created a data layer utilizing the Entity Framework for paged data access. The only relevance of mentioning the Entity Framework is that it is what is responsible for creating the OFFSET / FETCH SQL statements that I will be discussing. I'm aware of alternative solutions that could be implemented that work without using OFFSET / FETCH, however, this is not the intent of my post. The intent of this post is to understand exactly what is happening with the OFFSET / FETCH query.

I'm including the necessary SQL required to replicate this issue.

The following SQL statement will create a Table that implements the EAV pattern:

CREATE TABLE [dbo].[OptionalValues]
(
     [Id] [uniqueidentifier] NOT NULL
         CONSTRAINT [DF_OptionalValues_Id] DEFAULT (newsequentialid()),
     [Type] [nvarchar](450) NOT NULL,
     [Name] [nvarchar](450) NOT NULL,
     [Value] [nvarchar](450) NOT NULL,

     CONSTRAINT [PK_OptionalValues]
         PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY]

The following statements will insert test data into the table:

INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'04c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Eyes', N'Eyes');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'05c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Skin', N'Skin');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'06c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Autonomic Nervous System', N'Autonomic Nervous System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'07c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Kidneys', N'Kidneys');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'08c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Liver', N'Liver');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'09c9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Respiratory System', N'Respiratory System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0ac9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Lungs', N'Lungs');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0bc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Central Nervous System', N'Central Nervous System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0cc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Blood', N'Blood');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0dc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Heart', N'Heart');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0ec9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Reproductive System', N'Reproductive System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'0fc9f78a-5114-e711-90c2-005056a9316b', N'TargetOrgans', N'Cardiovascular System', N'Cardiovascular System');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'd6fdf6b9-6014-e711-815c-080027f9bf3f', N'TargetOrgans', N'TEST_ONE', N'TEST_ONE');
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'5a8c5533-6114-e711-815c-080027f9bf3f', N'TargetOrgans', N'TEST_TWO', N'TEST_TWO')
INSERT [dbo].[OptionalValues] ([Id], [Type], [Name], [Value])
VALUES (N'801a12da-6214-e711-815c-080027f9bf3f', N'TargetOrgans', N'TEST_THREE', N'TEST_THREE');

The last three records inserted have [Id] values that were NOT generated by the table's newsequentialid() function and are out of sync with the other records.

This query will return all 15 records, including the records that have "out of sequence" id's

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]

The next 3 queries are the ones that don't make sense to me. They include an ORDER BY [Type] which is NOT unique, and do NOT include any explicit [Id] ordering

This query does NOT show records that have "out of sequence" id's

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
    OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY

This query does NOT show records that have "out of sequence" id's even though the result count is still 15???

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY

This query shows all 15 records including rows that have "out of sequence" id's

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type]
    OFFSET 0 ROWS
    FETCH NEXT 15 ROWS ONLY

The "fix" is to add a truly unique sort using the [Id] column.

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type], [Id]
    OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY

SELECT *
FROM [dbo].[OptionalValues]
ORDER BY [Type], [Id]
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY

My question really surrounds the inaccuracy of the queries that do not have truly unique sort. Why do the queries seemingly recognize the records with an "out of sequence id" in the paged row count, but those records are not shown in the query results? Does the Index created in conjunction with the Primary Key affect the sort behavior of the previous queries in any way?

Thank you for any assistance and clarification that you can provide.


问:
Retrieving variables from a text file through a hashmap
I am creating a school program for a project in which I a writing words and translations to a file, (separated by a character). I have read that I can read them via a hash map into an array. I was just wondering if someone could point me in the right direction as how to do this.

If anyone has a better idea of how to store and retrieve the words I would love to learn. The reason I am writing to a file is so the user can store as many words as they want.

Thank-you so much :D

答:
Here's a reference for learning how to use BufferedReader: BufferedReader

Here's a reference for learning how to use FileReader: FileReader

```<code>import java.io.*;
class YourClass
{
    public static void main() throws IOException
    {
        File f = new File("FilePath"); // Replace every '\' with '/' in the file path
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        String FileString = "";
        while((line = br.readLine()) != null)
        {
            // Now 'line' contains each line of the file
            // If you want, you can store the entire file in a String, like this:
            FileString += line + "\n"; // '\n' to register each new line
        }

        System.out.println(FileString);
    }
} // End of class
</code>```

I'm still a newbie, and don't understand much about HashMap, but I can tell you how to store it in a String array:

```<code>FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");
</code>```

FileString.replaceAll("\\s+", " ") - Replaces 1 or more spaces with 1 space, so as to avoid any logical errors.

FileString.split(" ") - Returns a String array of each String separated by a space.

Body:
Here's a reference for learning how to use BufferedReader: BufferedReader

Here's a reference for learning how to use FileReader: FileReader

import java.io.*;
class YourClass
{
    public static void main() throws IOException
    {
        File f = new File("FilePath"); // Replace every '\' with '/' in the file path
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);
        String line = "";
        String FileString = "";
        while((line = br.readLine()) != null)
        {
            // Now 'line' contains each line of the file
            // If you want, you can store the entire file in a String, like this:
            FileString += line + "\n"; // '\n' to register each new line
        }

        System.out.println(FileString);
    }
} // End of class

I'm still a newbie, and don't understand much about HashMap, but I can tell you how to store it in a String array:

FileString = FileString.replaceAll("\\s+", " ");
String[] Words = FileString.split(" ");

FileString.replaceAll("\\s+", " ") - Replaces 1 or more spaces with 1 space, so as to avoid any logical errors.

FileString.split(" ") - Returns a String array of each String separated by a space.


问:
Group html between heading tags in javascript
I have an html page with headings. I want to group the content (html) which is under the heading using javascript or any native library. How can I do that?
Example is below </p>

```<code><div>
  <h2>Main</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main2</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main3</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
</div>
</code>```

<p>Output should be </p>

```<code><div>
  <div>
    <h2>Main</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
  <div>
    <h2>Main2</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
  <div>
    <h2>Main3</h2>
    <p> Content goes here</p>
    <img src="someimg.jpg"/>
  </div>
</div>
</code>```

答:
Try this:

$("h2").each(function(){
    $(this).nextUntil("h2").addBack().wrapAll("
");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
  border-bottom:1px solid red;
}</code>```

Main

 Content goes here

Main2

 Content goes here

Main3

 Content goes here

```

Body:
I have an html page with headings. I want to group the content (html) which is under the heading using javascript or any native library. How can I do that?
Example is below

Main

 Content goes here

Main2

 Content goes here

Main3

 Content goes here

Output should be

Main

 Content goes here

Main2

 Content goes here

Main3

 Content goes here

Body:
Try this:

$("h2").each(function(){
    $(this).nextUntil("h2").addBack().wrapAll("<div class='wrapper'>");
});

.wrapper{
  border-bottom:1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div>
  <h2>Main</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main2</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
  <h2>Main3</h2>
  <p> Content goes here</p>
  <img src="someimg.jpg"/>
</div>


答:
So you're trying to get 40 days from the day provided in milliseconds?

```<code>Calendar date = Calendar.getInstance();
date.setTimeInMillis(date_in_mil);
date.add(Calendar.DAY_OF_YEAR, 40);
</code>```

Alternatively (from your comments):
    Calendar date = Calendar.getInstance(); //This is already the current day
    date.add(Calendar.DAY_OF_YEAR, 40);

Your problem is that you're using DAY_OF_WEEK_IN_MONTH instead of DAY_OF_WEEK

Title: How to find due date from selected date?

Body:
I want to find due date from select date but it does't get. So please help me how to get due date. Here is my code below.

Calendar date = Calendar.getInstance();
date.setTimeInMillis(date_in_mil);
date.add(Calendar.DAY_OF_WEEK_IN_MONTH, 40);

This is for a pregnancy app I am creating.

Body:
So you're trying to get 40 days from the day provided in milliseconds?

Calendar date = Calendar.getInstance();
date.setTimeInMillis(date_in_mil);
date.add(Calendar.DAY_OF_YEAR, 40);

Alternatively (from your comments):
    Calendar date = Calendar.getInstance(); //This is already the current day
    date.add(Calendar.DAY_OF_YEAR, 40);

Your problem is that you're using DAY_OF_WEEK_IN_MONTH instead of DAY_OF_WEEK


答:
to get latest record you use max() function, as for each customer and location you use group by
check the bellow:

```<code>select max(date) , CUSTOMER, LOCATION from table GROUP BY CUSTOMER , LOCATION
</code>```

edit. if the date is varchar(logically wrong) you can do at the below.

```<code> select Max(cast(date as Date)) , CUSTOMER, LOCATION from table GROUP BY CUSTOMER , LOCATION
</code>```

Body:
to get latest record you use max() function, as for each customer and location you use group by
check the bellow:

select max(date) , CUSTOMER, LOCATION from table GROUP BY CUSTOMER , LOCATION

edit. if the date is varchar(logically wrong) you can do at the below.

 select Max(cast(date as Date)) , CUSTOMER, LOCATION from table GROUP BY CUSTOMER , LOCATION


答:
You need to function statement:

```<code><?php

class db_connector{
    var $db_dsn="mysql:host=localhost;dbname=erp5_temp2";
    var $db_username = "root";
    var $db_password = "";
    var $dbh ="";

    public function db_connector(){
        $dbh = new PDO($this->$db_dsn,$this->$db_username,$this->$db_password);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
    }
    public function get_db_handler(){
        return $dbh;
    }
}

?>
</code>```

Title: I can't connect to mysql?

Body:
You need to function statement:

<?php

class db_connector{
    var $db_dsn="mysql:host=localhost;dbname=erp5_temp2";
    var $db_username = "root";
    var $db_password = "";
    var $dbh ="";

    public function db_connector(){
        $dbh = new PDO($this->$db_dsn,$this->$db_username,$this->$db_password);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
    }
    public function get_db_handler(){
        return $dbh;
    }
}

?>


问:
Branching conversation in Amazon Lex
Is there a way to branch a conversation depending on a user input on an intent?

For example: Consider a binary intent such as "isRent" with an utterance "Are you renting right now?". The user is likely to answer either "yes" or "no". At this point, I have some more slots to ask the user. How do I update the prompt to ask for slots after this depending on the user's answer?

isRent

yes - What is your monthly rent? (collecting a value for slot {payment})

no  - What is your monthly mortgage payment? (collecting the value for same slot as above)

答:
The accepted answer provides very good details that helped me branch my conversation flow. I would like to add specifically that this particular part of documentation is helpful: ElicitSlot.

Using ElicitSlot can effectively ask for a specific slot and replace the prompt that you define on the GUI console. This can be combined with a state management (having a state session attributes in my case) to know when to switch state.

Title: Branching conversation in Amazon Lex


问:
Is it possible to call Automation test class from main activity for to launch test class through intents programatially?
I want to call automation test class from main activity through intents in android .i want to launch the test class programatically.if it is possible means please anybody suggest how to write code programatically launching test class in android..</p>

答: @DerKingsten.. it is not possible to call testclass programaticlly from main activity class?</p>


问:
Click expand on html
I want to do Expand/collapse on click (See pic below).

When a person clicks on the PLUS(+) sign, it expands and the signs change itself to Minus(-) sign and when a person clicks on Minus Sign it Collapse and again changes to Plus Sign.

Here is the Image,

答:
I found this jsfiddle with nice implementation of what you are looking for.

var data = [{
    "id": "1",
    "name": "Corporate Headquarters",
    "budget": "1230000",
    "location": "Las Vegas",
        "children": [{
        "id": "2",
        "name": "Finance Division",
        "budget": "423000",
        "location": "San Antonio",
            "children": [{
            "id": "3",
            "name": "Accounting Department",
            "budget": "113000",
            "location": "San Antonio"
        }, {
            "id": "4",
            "name": "Investment Department",
            "budget": "310000",
            "location": "San Antonio",
            children: [{
                "id": "5",
                "name": "Banking Office",
                "budget": "240000",
                "location": "San Antonio"
            }, {
                "id": "6",
                "name": "Bonds Office",
                "budget": "70000",
                "location": "San Antonio"
            }, ]
        }]
    }, {
        "id": "7",
        "name": "Operations Division",
        "budget": "600000",
        "location": "Miami",
            "children": [{
            "id": "8",
            "name": "Manufacturing Department",
            "budget": "300000",
            "location": "Miami"
        }, {
            "id": "9",
            "name": "Public Relations Department",
            "budget": "200000",
            "location": "Miami"
        }, {
            "id": "10",
            "name": "Sales Department",
            "budget": "100000",
            "location": "Miami"
        }]
    }, {
        "id": "11",
        "name": "Research Division",
        "budget": "200000",
        "location": "Boston"
    }]
}];

var source = {
    dataType: "json",
    dataFields: [{
        name: "name",
        type: "string"
    }, {
        name: "budget",
        type: "number"
    }, {
        name: "id",
        type: "number"
    }, {
        name: "children",
        type: "array"
    }, {
        name: "location",
        type: "string"
    }],
    hierarchy: {
        root: "children"
    },
    localData: data,
    id: "id"
};

var dataAdapter = new $.jqx.dataAdapter(source, {
    loadComplete: function () {

    }
});
// create jqxTreeGrid.
$("#treeGrid").jqxTreeGrid({
    source: dataAdapter,
    altRows: true,
    width: 680,
    theme:'energyblue',
    checkboxes: true,
    ready: function () {
        $("#treeGrid").jqxTreeGrid('expandRow', '1');
        $("#treeGrid").jqxTreeGrid('expandRow', '2');
    },
    columns: [{
        text: "Name",
        align: "center",
        dataField: "name",
        width: 300
    }, {
        text: "Budget",
        cellsAlign: "center",
        align: "center",
        dataField: "budget",
        cellsFormat: "c2",
        width: 250
    }, {
        text: "Location",
        dataField: "location",
        cellsAlign: "center",
        align: "center"
    }]
});
$("#jqxbutton").jqxButton({
    theme: 'energyblue',
    height: 30
});
$('#jqxbutton').click(function () {
    $("#treeGrid").jqxTreeGrid('checkRow',2);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet"/>
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>

<div id="treeGrid"></div>
<input type="button" style="margin: 20px;" id="jqxbutton" value="Check a row" /></code>```

Title: Click expand on html

Body:
I found this jsfiddle with nice implementation of what you are looking for.

var data = [{
    "id": "1",
    "name": "Corporate Headquarters",
    "budget": "1230000",
    "location": "Las Vegas",
        "children": [{
        "id": "2",
        "name": "Finance Division",
        "budget": "423000",
        "location": "San Antonio",
            "children": [{
            "id": "3",
            "name": "Accounting Department",
            "budget": "113000",
            "location": "San Antonio"
        }, {
            "id": "4",
            "name": "Investment Department",
            "budget": "310000",
            "location": "San Antonio",
            children: [{
                "id": "5",
                "name": "Banking Office",
                "budget": "240000",
                "location": "San Antonio"
            }, {
                "id": "6",
                "name": "Bonds Office",
                "budget": "70000",
                "location": "San Antonio"
            }, ]
        }]
    }, {
        "id": "7",
        "name": "Operations Division",
        "budget": "600000",
        "location": "Miami",
            "children": [{
            "id": "8",
            "name": "Manufacturing Department",
            "budget": "300000",
            "location": "Miami"
        }, {
            "id": "9",
            "name": "Public Relations Department",
            "budget": "200000",
            "location": "Miami"
        }, {
            "id": "10",
            "name": "Sales Department",
            "budget": "100000",
            "location": "Miami"
        }]
    }, {
        "id": "11",
        "name": "Research Division",
        "budget": "200000",
        "location": "Boston"
    }]
}];

var source = {
    dataType: "json",
    dataFields: [{
        name: "name",
        type: "string"
    }, {
        name: "budget",
        type: "number"
    }, {
        name: "id",
        type: "number"
    }, {
        name: "children",
        type: "array"
    }, {
        name: "location",
        type: "string"
    }],
    hierarchy: {
        root: "children"
    },
    localData: data,
    id: "id"
};

var dataAdapter = new $.jqx.dataAdapter(source, {
    loadComplete: function () {

    }
});
// create jqxTreeGrid.
$("#treeGrid").jqxTreeGrid({
    source: dataAdapter,
    altRows: true,
    width: 680,
    theme:'energyblue',
    checkboxes: true,
    ready: function () {
        $("#treeGrid").jqxTreeGrid('expandRow', '1');
        $("#treeGrid").jqxTreeGrid('expandRow', '2');
    },
    columns: [{
        text: "Name",
        align: "center",
        dataField: "name",
        width: 300
    }, {
        text: "Budget",
        cellsAlign: "center",
        align: "center",
        dataField: "budget",
        cellsFormat: "c2",
        width: 250
    }, {
        text: "Location",
        dataField: "location",
        cellsAlign: "center",
        align: "center"
    }]
});
$("#jqxbutton").jqxButton({
    theme: 'energyblue',
    height: 30
});
$('#jqxbutton').click(function () {
    $("#treeGrid").jqxTreeGrid('checkRow',2);
});

<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet"/>
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>

<div id="treeGrid"></div>
<input type="button" style="margin: 20px;" id="jqxbutton" value="Check a row" />


问:
Removing superfluos layers from DXFwrite
I use the python package DXFwrite to construct solar cell grids. Unfortunately my simulation program is confused by additional layers introduced by DXFwrite. Their names are:

DIMENSIONS

TABLECONTENT

TABLEGRID

TABLEBACKGROUND

VIEWPORTS

Is there a simple way to prevent DXFwrite from creating these layers? I have not found any command to remove layers.

Best Regards,

Thorsten Rissom

答:
No there is no method to delete layers and you can not prevent dxfwrite from creating this layers.

Alternative 1:

Use ezdxf (https://pypi.python.org/pypi/ezdxf/), but there are also some predefined layers (DEFPOINTS, VIEW_PORT), but you can delete entries from the
layer table: dwg.layers.remove('layername'), this removes only the layer table entry, a layer is only deleted if not entity references this layer. And maybe there are some unexpected side effects.

Alternative 2:

Use ezdxf.r12writer: this module can be used without the ezdxf package, just copy r12writer.py into your project. The module writes very basic DXF12 files, see docs: http://pythonhosted.org/ezdxf/r12writer.html.

Supported entities: LINE, CIRCLE, ARC, TEXT, POINT, SOLID, 3DFACE and POLYLINE

Block references are not supported!

additional advantage: r12writer is very fast