问:
asp repeater template conditional validation javascript
I have an asp repeater which has some item information, an accept button, a cancel button and a reason for cancellation text box. I want the cancel button to validate that there is some text in the cancel (and if there isn't pop up a "you need to enter a reason"). I want the accept button to just submit the item on the page. This is my attempt, but the function does not want to find (bind) txtReason

```<code><asp:UpdatePanel runat="server" ID="updatePanelAcceptOrReject">
    <ContentTemplate>
        <asp:Repeater runat="server" ID="AcceptOrRejectRepeater" OnItemDataBound="AcceptOrRejectRepeater_ItemDataBound">
            <ItemTemplate>
                <asp:Label ID="lblDescription" runat="server" Text='<%# Bind("ItemDescription")%>'></asp:Label
                <asp:Label ID="lblReasonForCancelling" runat="server" Text="Reason for rejection"></asp:Label>
                <asp:TextBox runat="server" ID="txtReason"></asp:TextBox>
                <script type="text/javascript">
                    function fnCheckforCancelReason() {
                        var pgng = document.getElementById('<%=txtReason.ClientID%>').value.trim();
                        if (pgnd == "") {
                            alert('The textbox should not be empty...');
                            document.getElementById(txtReason).focus();
                            return false;
                        }
                    }
               </script>
               <asp:Button ID="btnReject" runat="server" Text="Reject" CommandArgument='<%# Bind("ItemID") %>' OnClientClick="javascript:return fnCheckforCancelReason()" OnClick="btnReject_Click" />
                <asp:Button ID="btnAccept" runat="server" Text="Accept" CommandArgument='<%# Bind("ItemID") %>' OnClick="btnAccept_Click" />
            </ItemTemplate>
        </asp:Repeater>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

but the function does not want to find (bind) txtReason and I cant set a break point (chronme or ie)

I want to be able to put a break point in to debug the fnCheckforCancelReason

答:
typo on pgng:</p>

```<code>var pgng = document.getElementById(...
if (pgnd == "") {
</code>```

Body:
I have an asp repeater which has some item information, an accept button, a cancel button and a reason for cancellation text box. I want the cancel button to validate that there is some text in the cancel (and if there isn't pop up a "you need to enter a reason"). I want the accept button to just submit the item on the page. This is my attempt, but the function does not want to find (bind) txtReason

<asp:UpdatePanel runat="server" ID="updatePanelAcceptOrReject">
    <ContentTemplate>
        <asp:Repeater runat="server" ID="AcceptOrRejectRepeater" OnItemDataBound="AcceptOrRejectRepeater_ItemDataBound">
            <ItemTemplate>
                <asp:Label ID="lblDescription" runat="server" Text='<%# Bind("ItemDescription")%>'></asp:Label
                <asp:Label ID="lblReasonForCancelling" runat="server" Text="Reason for rejection"></asp:Label>
                <asp:TextBox runat="server" ID="txtReason"></asp:TextBox>

               <asp:Button ID="btnReject" runat="server" Text="Reject" CommandArgument='<%# Bind("ItemID") %>' OnClientClick="javascript:return fnCheckforCancelReason()" OnClick="btnReject_Click" />
                <asp:Button ID="btnAccept" runat="server" Text="Accept" CommandArgument='<%# Bind("ItemID") %>' OnClick="btnAccept_Click" />
            </ItemTemplate>
        </asp:Repeater>
    </ContentTemplate>
</asp:UpdatePanel>

but the function does not want to find (bind) txtReason and I cant set a break point (chronme or ie)

I want to be able to put a break point in to debug the fnCheckforCancelReason

Body:
typo on pgng:

var pgng = document.getElementById(...
if (pgnd == "") {


来源: stackexchange

问:
How to convert 2 numbers to 2 parts of a decimal number [C#]
Im trying to convert 2 user inputed numbers (for example):

```<code>double number = 5;
double number2 = 23;
</code>```

into this:

```<code>decimalnumber = 5.23;
</code>```

答:
As to your actual problem about physical calculator - do not store it as numeric at all! Just use it like this:

```<code>var userInput = new StringBuilder();
....
userInput.Append(getUserNextChar());
....
</code>```

Then just parse this input when it is actually needed as numeric:

```<code>decimal numeric;
if(!decimal.TryParse(userInput.ToString(), out numeric))
{
    throw new Exception("Invalid user input!");
}
//use your 'numeric' here
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im trying to convert 2 user inputed numbers (for example):

double number = 5;
double number2 = 23;

into this:

decimalnumber = 5.23;

Body:
As to your actual problem about physical calculator - do not store it as numeric at all! Just use it like this:

var userInput = new StringBuilder();
....
userInput.Append(getUserNextChar());
....

Then just parse this input when it is actually needed as numeric:

decimal numeric;
if(!decimal.TryParse(userInput.ToString(), out numeric))
{
    throw new Exception("Invalid user input!");
}
//use your 'numeric' here


问:
How can I make a numpy ndarray from bytes?
I can convert a numpy ndarray to bytes using myndarray.tobytes() Now how can I get it back to an ndarray?

Using the example from the .tobytes() method docs:

```<code>>>> x = np.array([[0, 1], [2, 3]])
>>> bytes = x.tobytes()
>>> bytes
b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'

>>> np.some_magic_function_here(bytes)
array([[0, 1], [2, 3]])
</code>```

答:
After your edit it seems you are going into the wrong direction!

You can't use np.tobytes() to store a complete array containing all informations like shapes and types when reconstruction from these bytes only is needed! It will only save the raw data (cell-values) and flatten these in C or Fortran-order.

Now we don't know your task. But you will need something based on serialization. There are tons of approaches, the easiest being the following based on python's pickle (example here: python3!):

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

x = np.array([[0, 1], [2, 3]])
print(x)

x_as_bytes = pickle.dumps(x)
print(x_as_bytes)
print(type(x_as_bytes))

y = pickle.loads(x_as_bytes)
print(y)
</code>```

Output:

```<code>[[0 1]
 [2 3]]
 b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K\x02K\x02\x86q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00i8q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00<q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89C \x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00q\rtq\x0eb.'
<class 'bytes'>
[[0 1]
 [2 3]]
</code>```

The better alternative would be joblib's pickle with specialized pickling for large arrays. joblib's functions are file-object based and can be used in-memory with byte-strings too using python's BytesIO.

Body:
I can convert a numpy ndarray to bytes using myndarray.tobytes() Now how can I get it back to an ndarray?

Using the example from the .tobytes() method docs:

>>> x = np.array([[0, 1], [2, 3]])
>>> bytes = x.tobytes()
>>> bytes
b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00'

>>> np.some_magic_function_here(bytes)
array([[0, 1], [2, 3]])

Body:
After your edit it seems you are going into the wrong direction!

You can't use np.tobytes() to store a complete array containing all informations like shapes and types when reconstruction from these bytes only is needed! It will only save the raw data (cell-values) and flatten these in C or Fortran-order.

Now we don't know your task. But you will need something based on serialization. There are tons of approaches, the easiest being the following based on python's pickle (example here: python3!):

import pickle
import numpy as np

x = np.array([[0, 1], [2, 3]])
print(x)

x_as_bytes = pickle.dumps(x)
print(x_as_bytes)
print(type(x_as_bytes))

y = pickle.loads(x_as_bytes)
print(y)

Output:

[[0 1]
 [2 3]]
 b'\x80\x03cnumpy.core.multiarray\n_reconstruct\nq\x00cnumpy\nndarray\nq\x01K\x00\x85q\x02C\x01bq\x03\x87q\x04Rq\x05(K\x01K\x02K\x02\x86q\x06cnumpy\ndtype\nq\x07X\x02\x00\x00\x00i8q\x08K\x00K\x01\x87q\tRq\n(K\x03X\x01\x00\x00\x00<q\x0bNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\x0cb\x89C \x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00q\rtq\x0eb.'
<class 'bytes'>
[[0 1]
 [2 3]]

The better alternative would be joblib's pickle with specialized pickling for large arrays. joblib's functions are file-object based and can be used in-memory with byte-strings too using python's BytesIO.


问:
How to use map to dig out data from api in angular 5
Hello everyone I need your help please, I am using angular 5 and i'm new to angular I am unable to get data out of what my api service is returning

according to my html code I did this

```<code><ul>
 <li *ngFor="let cat of categories">
<span class="badge">{{cat.id}}</span> {{cat.name}}
 </li>
</ul>
</code>```

The li tag repeat the exact number of data in my Db but I cant see the data all I see is repitition of the li tag

Here is my code

The same structure with my server code

```<code>export class Category
   {
    id: number;
    name: string;
   }
</code>```

I called the server like this

```<code>product.service code:

       getCategories (): Observable<Category[]>
         {
       return this.http.get<Category[]>
        ('http://localhost:56757/api/product/categories')
        .pipe(
         tap(categories` => this.log(`fetched categories`)),
         catchError(this.handleError('getCategories', []))
          );
         }
</code>```

Category.component.ts code

```<code>       products:Product[];

          constructor(private productService: ProductService,
          private route: ActivatedRoute,
          private location: Location) { }
           ngOnInit() {
           getCategories(): void {
           this.productService.getCategories()
           .subscribe(products => this.products = products);
           }
</code>```

HTML :

```<code>        <ul>
         <li *ngFor="let cat of categories">
          <span class="badge">{{cat.id}}</span> {{cat.name}}
         </li>
         </ul>
</code>```

According to Angular Documentation that goes like this,
"Other APIs may bury the data that you want within an object.
You might have to dig that data out by processing the Observable result with the RxJS map operator."

Please can someone help me with how to use map to dig the data out. Thanks in advance.

答:
Thanks Brendan here is the asp.net server side codes

Model :

```<code>           public class Category
            {
           public int Id { get; set; }

           public string Name { get; set; }
             }

         [HttpGet]
         [Route("categories")]
         public async Task<List<Category>> GetCategory() => await
         db.Categories.ToListAsync();
</code>```

Body:
Hello everyone I need your help please, I am using angular 5 and i'm new to angular I am unable to get data out of what my api service is returning

according to my html code I did this

{{cat.id}} {{cat.name}}

The li tag repeat the exact number of data in my Db but I cant see the data all I see is repitition of the li tag

Here is my code

The same structure with my server code

export class Category
   {
    id: number;
    name: string;
   }

I called the server like this

product.service code:

       getCategories (): Observable<Category[]>
         {
       return this.http.get<Category[]>
        ('http://localhost:56757/api/product/categories')
        .pipe(
         tap(categories` => this.log(`fetched categories`)),
         catchError(this.handleError('getCategories', []))
          );
         }

Category.component.ts code

       products:Product[];

          constructor(private productService: ProductService,
          private route: ActivatedRoute,
          private location: Location) { }
           ngOnInit() {
           getCategories(): void {
           this.productService.getCategories()
           .subscribe(products => this.products = products);
           }

HTML :

          {{cat.id}} {{cat.name}}

According to Angular Documentation that goes like this,
"Other APIs may bury the data that you want within an object.
You might have to dig that data out by processing the Observable result with the RxJS map operator."

Please can someone help me with how to use map to dig the data out. Thanks in advance.

Body:
Thanks Brendan here is the asp.net server side codes

Model :

           public class Category
            {
           public int Id { get; set; }

           public string Name { get; set; }
             }

         [HttpGet]
         [Route("categories")]
         public async Task<List<Category>> GetCategory() => await
         db.Categories.ToListAsync();


问:
Trouble running a VBA macro from VBS
I'm writing a script in VBS to run a macro on many excel files in a directory.  I'm new to VBS and macros.

The root directory has a number of folders in it.  Inside each folder is a number of sub folders.  I'm looking for folders at this level called "inspection".  Inside of those folders I'm looking for files that match the pattern .050. or .120..  If those files are found I want to run an Excel macro on them to modify the footer.

I've managed to set up all of the logic to search for the files and that seems to be working.  I've got a macro recorded in my PERSONAL.XLSB file and I can open files individually and run the macro successfully.

The problem: When I try to call the macro from code I get the following error:

Cannot run the macro

     The macro may not be available in this workbook or all macros may be disabled.

I have macros enabled in Excel.  I've tried a number of methods for running the macro but haven't been able to get any to work.

My VBS script:

```<code>DIM FSO, rootFolder, subFolders, subFolder, inspectionFolders, inspectionFolder, inspectionFiles, inspectionFile, wb

Set FSO = CreateObject("Scripting.FileSystemObject")
Set rootFolder = FSO.GetFolder("N:\ENGINEERING-Test")

Set subFolders = rootFolder.SubFolders

For Each subFolder in subFolders
    WScript.Echo "in " + rootFolder
    WScript.Echo "found folder " + subFolder.Name
    Set inspectionFolders = subFolder.SubFolders
    For Each inspectionFolder in inspectionFolders
        WScript.Echo "found folder " + inspectionFolder.name
        If InStr(1, inspectionFolder.Name, "Inspection", vbTextCompare) Then
            WScript.Echo "In inspection Folder"
            Set inspectionFiles = inspectionFolder.files
            For Each inspectionFile in inspectionFiles
                WScript.Echo "Checking File " + inspectionFile.name
                If InStr(1, inspectionFile.Name, ".050.", vbTextCompare) > 0 Or InStr(1, inspectionFile.Name, ".120.", vbTextCompare) > 0 Then
                    WScript.Echo "Found file " + inspectionFile.name

                    Set xlApp = CreateObject("Excel.application")
                    Set xlBook = xlApp.Workbooks.Open(inspectionFolder & "\" & inspectionFile.name, 0, False)
                    xlApp.Application.Visible = False
                    xlApp.Application.Run "C:\Users\Nick\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB!Module1.ModifyHeaderFooter"
                    xlApp.ActiveWindow.close
                    xlApp.Quit

                Else
                End If
            Next
        Else
        End If
    Next
Next
</code>```

My macro:

```<code>Sub ModifyHeaderFooter()
'
' ModifyHeaderFooter Macro
'

'
    With ActiveSheet.PageSetup
        .PrintTitleRows = "$1:$3"
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = "Company, LLC"
        .RightFooter = "Page &P of  &N&8" & Chr(10) & ""
        .LeftMargin = Application.InchesToPoints(0.45)
        .RightMargin = Application.InchesToPoints(0)
        .TopMargin = Application.InchesToPoints(0)
        .BottomMargin = Application.InchesToPoints(0.58)
        .HeaderMargin = Application.InchesToPoints(0)
        .FooterMargin = Application.InchesToPoints(0)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 300
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = False
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
End Sub
</code>```

At this point I'm able to find the files I'm looking for, and the script attempts to execute the macro, but I get an error.  Can anyone see what I'm doing wrong?

答:
In the end I moved

Set xlApp = CreateObject("Excel.application")

outside of my loops and changed

xlApp.Application.Run "C:\Users\Nick\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB!Module1.ModifyHeaderFooter"

to

xlApp.Run("PERSONAL.XLSB!ModifyHeaderFooter")

and my error was resolved.  I also added

xlApp.Workbooks.Open("C:\Users\Nick\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB")

at the point just before I called the macro.  I may have been doing something else wrong, but when I opened it once outside of the loops it only worked for one iteration.  Thanks to Scott and Garbb for the contributions and thanks to Scott for the additional efficiency tips.

Title: Trouble running a VBA macro from VBS

Body:
I'm writing a script in VBS to run a macro on many excel files in a directory.  I'm new to VBS and macros.

The root directory has a number of folders in it.  Inside each folder is a number of sub folders.  I'm looking for folders at this level called "inspection".  Inside of those folders I'm looking for files that match the pattern .050. or .120..  If those files are found I want to run an Excel macro on them to modify the footer.

I've managed to set up all of the logic to search for the files and that seems to be working.  I've got a macro recorded in my PERSONAL.XLSB file and I can open files individually and run the macro successfully.

The problem: When I try to call the macro from code I get the following error:

Cannot run the macro

     The macro may not be available in this workbook or all macros may be disabled.

I have macros enabled in Excel.  I've tried a number of methods for running the macro but haven't been able to get any to work.

My VBS script:

DIM FSO, rootFolder, subFolders, subFolder, inspectionFolders, inspectionFolder, inspectionFiles, inspectionFile, wb

Set FSO = CreateObject("Scripting.FileSystemObject")
Set rootFolder = FSO.GetFolder("N:\ENGINEERING-Test")

Set subFolders = rootFolder.SubFolders

For Each subFolder in subFolders
    WScript.Echo "in " + rootFolder
    WScript.Echo "found folder " + subFolder.Name
    Set inspectionFolders = subFolder.SubFolders
    For Each inspectionFolder in inspectionFolders
        WScript.Echo "found folder " + inspectionFolder.name
        If InStr(1, inspectionFolder.Name, "Inspection", vbTextCompare) Then
            WScript.Echo "In inspection Folder"
            Set inspectionFiles = inspectionFolder.files
            For Each inspectionFile in inspectionFiles
                WScript.Echo "Checking File " + inspectionFile.name
                If InStr(1, inspectionFile.Name, ".050.", vbTextCompare) > 0 Or InStr(1, inspectionFile.Name, ".120.", vbTextCompare) > 0 Then
                    WScript.Echo "Found file " + inspectionFile.name

                    Set xlApp = CreateObject("Excel.application")
                    Set xlBook = xlApp.Workbooks.Open(inspectionFolder & "\" & inspectionFile.name, 0, False)
                    xlApp.Application.Visible = False
                    xlApp.Application.Run "C:\Users\Nick\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB!Module1.ModifyHeaderFooter"
                    xlApp.ActiveWindow.close
                    xlApp.Quit

                Else
                End If
            Next
        Else
        End If
    Next
Next

My macro:

Sub ModifyHeaderFooter()
'
' ModifyHeaderFooter Macro
'

'
    With ActiveSheet.PageSetup
        .PrintTitleRows = "$1:$3"
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = ""
    With ActiveSheet.PageSetup
        .LeftHeader = ""
        .CenterHeader = ""
        .RightHeader = ""
        .LeftFooter = ""
        .CenterFooter = "Company, LLC"
        .RightFooter = "Page &P of  &N&8" & Chr(10) & ""
        .LeftMargin = Application.InchesToPoints(0.45)
        .RightMargin = Application.InchesToPoints(0)
        .TopMargin = Application.InchesToPoints(0)
        .BottomMargin = Application.InchesToPoints(0.58)
        .HeaderMargin = Application.InchesToPoints(0)
        .FooterMargin = Application.InchesToPoints(0)
        .PrintHeadings = False
        .PrintGridlines = False
        .PrintComments = xlPrintNoComments
        .PrintQuality = 300
        .CenterHorizontally = False
        .CenterVertically = False
        .Orientation = xlLandscape
        .Draft = False
        .PaperSize = xlPaperLetter
        .FirstPageNumber = xlAutomatic
        .Order = xlDownThenOver
        .BlackAndWhite = False
        .Zoom = 100
        .PrintErrors = xlPrintErrorsDisplayed
        .OddAndEvenPagesHeaderFooter = False
        .DifferentFirstPageHeaderFooter = False
        .ScaleWithDocHeaderFooter = True
        .AlignMarginsHeaderFooter = False
        .EvenPage.LeftHeader.Text = ""
        .EvenPage.CenterHeader.Text = ""
        .EvenPage.RightHeader.Text = ""
        .EvenPage.LeftFooter.Text = ""
        .EvenPage.CenterFooter.Text = ""
        .EvenPage.RightFooter.Text = ""
        .FirstPage.LeftHeader.Text = ""
        .FirstPage.CenterHeader.Text = ""
        .FirstPage.RightHeader.Text = ""
        .FirstPage.LeftFooter.Text = ""
        .FirstPage.CenterFooter.Text = ""
        .FirstPage.RightFooter.Text = ""
    End With
End Sub

At this point I'm able to find the files I'm looking for, and the script attempts to execute the macro, but I get an error.  Can anyone see what I'm doing wrong?


问:
javascript escape problem with unicode characters
I use the following jquery code to load some date on a specific event from external file:

```<code>$("#container").load("/include/data.php?name=" + escape(name));
</code>```

if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1

How can I deal with this encoded symbols? I need to convert them back to readable one.

When I remove the escape function and leave just "name" variable the code doesn't work any more...

Can anyone please help?

答:
This may help you.

javascript - how to convert unicode string to ascii

ContentLicense: CC BY-SA 2.5

Body:
I use the following jquery code to load some date on a specific event from external file:

$("#container").load("/include/data.php?name=" + escape(name));

if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1

How can I deal with this encoded symbols? I need to convert them back to readable one.

When I remove the escape function and leave just "name" variable the code doesn't work any more...

Can anyone please help?


问:
How update TSL 1.0 to TLS 1.2 version in a Cpanel/WHM server
One of our payment team has mentioned us to upgrade the TLs 1.0 version to TLS 1.2 as they are making the security measures. If we haven't updated we will be facing the issues with the payment in our website. Please let us know how this is done from a Cpanel/WHM server. </p>

<p>Thanks </p>

答:
I encountered the same problem, and found the solution...

In WHM, search for "cPanel Web Services Configuration" located under "Service Configuration".

You'll want to add :!TLSv1 at the end of the protocol string. This forces it to use newer version.

Ideally you'll want to test this on a development server 1st, as it may break your SSL/payment processing if the server is not up to date and cannot use the newer version. There is fallbacks, but it's always best to test 1st!

While you are here as well, you can harden your ciphers. Great tutorial on this can be found here:
https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/

cPanel Official Documentation:
https://documentation.cpanel.net/display/CKB/How+to+Adjust+Cipher+Protocols

Body:
One of our payment team has mentioned us to upgrade the TLs 1.0 version to TLS 1.2 as they are making the security measures. If we haven't updated we will be facing the issues with the payment in our website. Please let us know how this is done from a Cpanel/WHM server.

Thanks


问:
Missing Data in Excel between 2 columns
I'm working with a fairly large data set, I have a list of names which appear more than once in column B and in column C i have the team they are part of.

In column C which displays there team name most the data is there but I do have a few 1000 where no team name is not present. Is excel smart enough to go for example Jamie@soso is part of design because it case in "B36" "C36" and then assign design to the missing field?

Here is an example of the data with the missing team names

And here is a view with what im looking for end result wise.

If I need to explain this better please let me know and thank you in advance.

答:
On the assumption that there are no ambiguous entries, you could do the following:

if the order of the data is important, add an index column and insert ascending numbers for all rows of data (hint: enter the first two values manually, then select the first two cells and double click the fill handle to fill all the way down to the end of the data)

Sort the data by name and then by team as secondary sort

select column B

hit F5 to open the Go To dialog

click Special button

tick the option Blanks and click OK

now all blank cells in column B are selected

without changing the selection start typing a = sign, then hit the up arrow on your keyboard.

hold down the Ctrl key on your keyboard and hit Enter

now each previously blank cell in column B will have a formula that references the cell above.

copy column B

paste special on column B and paste values to get rid of the formulas

use the index column created in the first step to return to the original sort order

If you want this exercise to be repeatable, you could also use Power Query. Load the data into the Power Query editor, sort by name (ascending) and team (descending), select the Team column and click Transform > Fill > Fill down. The screenshot shows the result

Title: Missing Data in Excel between 2 columns


答:
Try </p>

```<code>df['Date']=pd.to_datetime(df.Date)
df.sort_values(['Date'])
</code>```

Title: How can I sort DataFrame by date in Python?

Body:
I try to sort dataframe shown below by date using df.sort_values(by='date') however it doesn't work. Any ideas how can I do this to be sure that it is sorted properly?

     symbol        date     open    close     high      low
0      GOOG  2007-01-03   232.77   233.56   238.09   230.32
1      GOOG  2007-01-05   241.01   243.35   243.51   238.82
2      GOOG  2007-01-04   234.27   241.39   241.73   233.94

...
2692   GOOG  2017-11-30  1022.37  1021.41  1028.49  1015.00
2693   GOOG  2017-11-29  1042.68  1021.66  1044.08  1015.65
2694   GOOG  2017-12-01  1015.80  1010.17  1022.49  1002.02

Body:
Try

df['Date']=pd.to_datetime(df.Date)
df.sort_values(['Date'])


问:
EF6.1.2 code first with 2 navigation properties both are one to zero to one, one works, but the other does not work
I have 3 tables, one is kind of the base table and is big.
Then I have an extension table which is also big
Then I have a tiny table with only one attribute except for the PK

In essence the primary key for all 3 tables is the same, except for the name
first table :

```<code>[Table("KLANTEN")]
public class Klant
{
    public Klant()
    {
        this.ContactPersonen = new HashSet<ContactPersoon>();
        this.Afleveringen = new HashSet<Aflever>();
    }

    [Key]
    [StringLength(8000)]
    public string NUMMER { get; set; }

    .... removed for brevity

    #region Navigation Properties
    public virtual Aanspreking Aanspreking { get; set; }
    public virtual PuntenKlant PuntenKlant { get; set; } // fail
    public virtual ExtraVeldenKlant ExtraVeldenKlant { get; set; } //ok
    public virtual ICollection<ContactPersoon> ContactPersonen { get; set; }
    public virtual ICollection<Aflever> Afleveringen { get; set; }
    #endregion
}
</code>```

second table:

```<code>[Table("EXVKLA")]
public class ExtraVeldenKlant
{
    [Key]
    [StringLength(8000)]
    public string NUMMER { get; set; }

    ... removed for brevity

    #region Navigation Properties
    public virtual Klant Klant { get; set; }
    #endregion
}
</code>```

third table:

```<code>[Table("[_CTPUNT]")]
public class PuntenKlant
{
    [Key]
    [StringLength(8000)]
    public string KODE { get; set; }

    [StringLength(8000)]
    public string OMSCHR { get; set; }

    #region Navigation Properties
    public virtual Klant Klant { get; set; }
    #endregion
}
</code>```

As you see the key is defined alsways on the first column not using the fluent api. I like it that way and the way I understood it, fluent api and attribute syntax can be mixed right ?

So for the configuration i am doing this :

```<code>class KlantConfiguration : EntityTypeConfiguration<Klant>
{
    public KlantConfiguration()
    {
        .... removed for brevity

        this.HasMany(e => e.ContactPersonen)
            .WithRequired(e => e.Klant)
            .HasForeignKey(e => e.KLANTCODE)
            .WillCascadeOnDelete(false);

        this.HasMany(e => e.Afleveringen)
            .WithRequired(e => e.Klant)
            .HasForeignKey(e => e.KLANTCODE)
            .WillCascadeOnDelete(false);

        this.HasOptional(e => e.PuntenKlant)
            .WithRequired(f => f.Klant);

        this.HasOptional(e => e.ExtraVeldenKlant)
            .WithRequired(e => e.Klant);
    }
}
</code>```

executing following SQL statement just to verify everything is in place :

```<code>select klanten.nummer,P.KODE,E.NUMMER,p.OMSCHR from klanten
inner join "_CTPUNT" P on P.KODE=klanten.nummer
inner join exvkla E on E.NUMMER=klanten.nummer
where klanten.nummer='000002'
</code>```

results in :

```<code>NUMMER     KODE     NUMMER     OMSCHR
========   ======   ========   ========================================
000002     000002   000002     571
</code>```

So this proves that they key is present in all three tables

Now if I try this using the real stuff in EF :

```<code>var puntenquery =
      from p in repoKlant.Queryable().Include("PuntenKlant").Include("ExtraVeldenKlant")
      where p.NUMMER == "000002"
      select p;
</code>```

then i get the weird result that the navigation property PuntenKlant is null
But the navigation property ExtraVeldenKlant is properly filled in.
I fail the see where i am going wrong.
Debugging EF shows that the query is in fact correctly executed but it is quite large, but the fields from that particular navigation property are int the query that is generated by EF. Though it looks as if through the materialisation process it does not work.

What am i doing wrong or is there a bug in EF, or in the pervasive ADO.NET driver, this is not SQL Server

答:
OK it seems I had to change the underlying database a bit.
the lenght of the keyfield in one of the tables was shorter.
Man I had a hell of a time today to solve this freeking problem.

And this link is the perfect solution :
How can I configure Entity Framework to automatically trim values retrieved for specific columns mapped to char(N) fields?

So I don't have to change anything in the database.

Body:
I have 3 tables, one is kind of the base table and is big.
Then I have an extension table which is also big
Then I have a tiny table with only one attribute except for the PK

In essence the primary key for all 3 tables is the same, except for the name
first table :

[Table("KLANTEN")]
public class Klant
{
    public Klant()
    {
        this.ContactPersonen = new HashSet<ContactPersoon>();
        this.Afleveringen = new HashSet<Aflever>();
    }

    [Key]
    [StringLength(8000)]
    public string NUMMER { get; set; }

    .... removed for brevity

    #region Navigation Properties
    public virtual Aanspreking Aanspreking { get; set; }
    public virtual PuntenKlant PuntenKlant { get; set; } // fail
    public virtual ExtraVeldenKlant ExtraVeldenKlant { get; set; } //ok
    public virtual ICollection<ContactPersoon> ContactPersonen { get; set; }
    public virtual ICollection<Aflever> Afleveringen { get; set; }
    #endregion
}

second table:

[Table("EXVKLA")]
public class ExtraVeldenKlant
{
    [Key]
    [StringLength(8000)]
    public string NUMMER { get; set; }

    ... removed for brevity

    #region Navigation Properties
    public virtual Klant Klant { get; set; }
    #endregion
}

third table:

[Table("[_CTPUNT]")]
public class PuntenKlant
{
    [Key]
    [StringLength(8000)]
    public string KODE { get; set; }

    [StringLength(8000)]
    public string OMSCHR { get; set; }

    #region Navigation Properties
    public virtual Klant Klant { get; set; }
    #endregion
}

As you see the key is defined alsways on the first column not using the fluent api. I like it that way and the way I understood it, fluent api and attribute syntax can be mixed right ?

So for the configuration i am doing this :

class KlantConfiguration : EntityTypeConfiguration<Klant>
{
    public KlantConfiguration()
    {
        .... removed for brevity

        this.HasMany(e => e.ContactPersonen)
            .WithRequired(e => e.Klant)
            .HasForeignKey(e => e.KLANTCODE)
            .WillCascadeOnDelete(false);

        this.HasMany(e => e.Afleveringen)
            .WithRequired(e => e.Klant)
            .HasForeignKey(e => e.KLANTCODE)
            .WillCascadeOnDelete(false);

        this.HasOptional(e => e.PuntenKlant)
            .WithRequired(f => f.Klant);

        this.HasOptional(e => e.ExtraVeldenKlant)
            .WithRequired(e => e.Klant);
    }
}

executing following SQL statement just to verify everything is in place :

select klanten.nummer,P.KODE,E.NUMMER,p.OMSCHR from klanten
inner join "_CTPUNT" P on P.KODE=klanten.nummer
inner join exvkla E on E.NUMMER=klanten.nummer
where klanten.nummer='000002'

results in :

NUMMER     KODE     NUMMER     OMSCHR
========   ======   ========   ========================================
000002     000002   000002     571

So this proves that they key is present in all three tables

Now if I try this using the real stuff in EF :

var puntenquery =
      from p in repoKlant.Queryable().Include("PuntenKlant").Include("ExtraVeldenKlant")
      where p.NUMMER == "000002"
      select p;

then i get the weird result that the navigation property PuntenKlant is null
But the navigation property ExtraVeldenKlant is properly filled in.
I fail the see where i am going wrong.
Debugging EF shows that the query is in fact correctly executed but it is quite large, but the fields from that particular navigation property are int the query that is generated by EF. Though it looks as if through the materialisation process it does not work.

What am i doing wrong or is there a bug in EF, or in the pervasive ADO.NET driver, this is not SQL Server


问:
How do I run "adb shell" commands in a terminal emulator locally on an Android device?
From a shell on my PC, I can run adb shell cmd package list packages, and get a list of all installed packages. I would like to run this and similar commands locally on my Android phone (Nexus 6P) in a terminal emulator (currently using Termux).

If I open the same shell with /system/bin/sh, and then try to run /system/bin/cmd package list packages, nothing happens (no errors, just outputs nothing and reloads the prompt).

If I run /system/bin/cmd -l the list of options appears as expected. $PATH and $LD_LIBRARY_PATH are the same in both environments. One major difference is that echo $USER returns "shell" from adb shell, but returns my local username from /system/bin/sh launched from Termux.

Is there any way to replicate the behavior of commands run from adb shell in a terminal emulator locally on Android?

Edit:
My device is rooted, and I am OK with root only solutions.

答:
I don't have a rooted Nougat device handy, but something like the following may be a close enough approximation to adb shell (assuming you are using SuperSU):

```<code>env -i USER=shell "$(PATH=/system/xbin:/system/bin:/su/bin:/sbin:/magisk/.core/bin which su)" shell --context u:r:shell:s0 --shell /system/bin/sh --command COMMAND
</code>```

I (very briefly) tested it from Termux on a rooted Marshmallow device.

To elaborate:

the -i flag is used to start with an empty environment

USER=shell isn't specifically required, but for some reason su refuses to run with a completely empty environment

$(PATH=/system/xbin:/system/bin:/su/bin:/sbin:/magisk/.core/bin which su) points to the full path of the su binary on your device and can be hardcoded if you prefer

shell instructs the su binary to login as the shell user (the same as adb shell)

--context u:r:shell:s0 sets the appropriate SELinux context

--shell /system/bin/sh instructs SuperSU to use the system shell rather than it's own sush shell

Another option would be to actually run adb from the device, connecting to itself over TCP. If you need some functionality that is only available via adb (e.g. in my case it was adb forward) then this may be your only option. Unfortunately this isn't particularly convenient.

I wasn't able to find success with any publicly available adb binaries, so I build it myself with a few minor changes. You can see the sources I used and the changes I made at https://github.com/shakalaca/fastboot-adb-android and https://github.com/brbsix/fastboot-adb-android, respectively.

Once you have adb installed, here's an abbreviated list of commands I used to connect to the device:

```<code># Add iptables rules to block external connections to port 9999'
su root iptables -N adbd
su root iptables -A adbd -i lo -p tcp -m tcp --dport 9999 -j ACCEPT
su root iptables -A adbd -p tcp -m tcp --dport 9999 -j DROP
su root iptables -A INPUT -j adbd

# Necessary in order to display authorization prompt
su shell setprop ro.debuggable 1

su shell setprop service.adb.tcp.port 9999

su root start adbd

adb connect 127.0.0.1:9999

adb wait-for-local-device
</code>```

To shut down:

```<code>adb kill-server
su root stop adbd
su shell setprop ro.debuggable 0
su shell setprop service.adb.tcp.port 0
su root iptables -D INPUT -j adbd
su root iptables -F adbd
su root iptables -X adbd
</code>```

Body:
I don't have a rooted Nougat device handy, but something like the following may be a close enough approximation to adb shell (assuming you are using SuperSU):

env -i USER=shell "$(PATH=/system/xbin:/system/bin:/su/bin:/sbin:/magisk/.core/bin which su)" shell --context u:r:shell:s0 --shell /system/bin/sh --command COMMAND

I (very briefly) tested it from Termux on a rooted Marshmallow device.

To elaborate:

the -i flag is used to start with an empty environment

USER=shell isn't specifically required, but for some reason su refuses to run with a completely empty environment

$(PATH=/system/xbin:/system/bin:/su/bin:/sbin:/magisk/.core/bin which su) points to the full path of the su binary on your device and can be hardcoded if you prefer

shell instructs the su binary to login as the shell user (the same as adb shell)

--context u:r:shell:s0 sets the appropriate SELinux context

--shell /system/bin/sh instructs SuperSU to use the system shell rather than it's own sush shell

Another option would be to actually run adb from the device, connecting to itself over TCP. If you need some functionality that is only available via adb (e.g. in my case it was adb forward) then this may be your only option. Unfortunately this isn't particularly convenient.

I wasn't able to find success with any publicly available adb binaries, so I build it myself with a few minor changes. You can see the sources I used and the changes I made at https://github.com/shakalaca/fastboot-adb-android and https://github.com/brbsix/fastboot-adb-android, respectively.

Once you have adb installed, here's an abbreviated list of commands I used to connect to the device:

# Add iptables rules to block external connections to port 9999'
su root iptables -N adbd
su root iptables -A adbd -i lo -p tcp -m tcp --dport 9999 -j ACCEPT
su root iptables -A adbd -p tcp -m tcp --dport 9999 -j DROP
su root iptables -A INPUT -j adbd

# Necessary in order to display authorization prompt
su shell setprop ro.debuggable 1

su shell setprop service.adb.tcp.port 9999

su root start adbd

adb connect 127.0.0.1:9999

adb wait-for-local-device

To shut down:

adb kill-server
su root stop adbd
su shell setprop ro.debuggable 0
su shell setprop service.adb.tcp.port 0
su root iptables -D INPUT -j adbd
su root iptables -F adbd
su root iptables -X adbd

ContentLicense: CC BY-SA 4.0


问:
Multiple bundles of CSS files in ASP.NET MVC
I'm building this website in ASP.Net MVC that basically will have a default look.
Depending of the institution entering the portal the color, banner and greetings will change.

Example:
www.portal.com/Institution1

Color: Blue

Banner: Photo1

www.portal.com/Institution2

Color: Green

Banner: Photo2

I'm trying to accomplish this in the BundleConfig.cs file but I haven't found a solution.

If somebody enter the portal using www.portal.com I will use:

```<code>bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
</code>```

If somebody enter the portal using www.portal.com/Institution1 I want to use:

```<code>bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Institution1/Institution1.css",
"~/Content/site.css"));
</code>```

If somebody enter the portal using www.portal.com/Institution2 I want to use:

```<code>bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Institution2/Institution2.css",
"~/Content/site.css"));
</code>```

Is there any way of accomplished this?

答:
There is not one specific way to do this. I did something similar a few years back. You can define a set of themes and associate users or organizations with a known theme. The bundle name could be used like an identifier. If you layout your content in a manageable way then you can associated a user or organization with a style or theme from wherever you pull your content. After a user is authenticated generically, you could set a property on an IndexModel, or whatever, so that when the main page loads you can access the needed style using something like:

```<code>@Styles.Render(@Model.CurrentSyle.BundleName)
</code>```

I would do something like:

```<code>public static void RegisterBundles(BundleCollection bundles)
{
    //perhaps something like.
    foreach (MyTheme theme in ThemeController.SelectAll())
       AddThemeStyleBundle(bundles, theme.BundleName, theme.ThemeName);
}

private static void AddThemeStyleBundle(BundleCollection bundles,string bundleName, string themeName)
    bundles.Add(new StyleImagePathBundle(bundlename).Include(
        "~/Content/bootstrap.css",
        String.Format("~/Content/{0}/Institution.css",themeName),
        "~/Content/site.css"));
}
</code>```

Body:
I'm building this website in ASP.Net MVC that basically will have a default look.
Depending of the institution entering the portal the color, banner and greetings will change.

Example:
www.portal.com/Institution1

Color: Blue

Banner: Photo1

www.portal.com/Institution2

Color: Green

Banner: Photo2

I'm trying to accomplish this in the BundleConfig.cs file but I haven't found a solution.

If somebody enter the portal using www.portal.com I will use:

bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));

If somebody enter the portal using www.portal.com/Institution1 I want to use:

bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Institution1/Institution1.css",
"~/Content/site.css"));

If somebody enter the portal using www.portal.com/Institution2 I want to use:

bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/Institution2/Institution2.css",
"~/Content/site.css"));

Is there any way of accomplished this?

Body:
There is not one specific way to do this. I did something similar a few years back. You can define a set of themes and associate users or organizations with a known theme. The bundle name could be used like an identifier. If you layout your content in a manageable way then you can associated a user or organization with a style or theme from wherever you pull your content. After a user is authenticated generically, you could set a property on an IndexModel, or whatever, so that when the main page loads you can access the needed style using something like:

@Styles.Render(@Model.CurrentSyle.BundleName)

I would do something like:

public static void RegisterBundles(BundleCollection bundles)
{
    //perhaps something like.
    foreach (MyTheme theme in ThemeController.SelectAll())
       AddThemeStyleBundle(bundles, theme.BundleName, theme.ThemeName);
}

private static void AddThemeStyleBundle(BundleCollection bundles,string bundleName, string themeName)
    bundles.Add(new StyleImagePathBundle(bundlename).Include(
        "~/Content/bootstrap.css",
        String.Format("~/Content/{0}/Institution.css",themeName),
        "~/Content/site.css"));
}


问:
BizTalk WCF SQL adapter receiving timeout trying to get a connection from the pool
I have an extremely simple BizTalk orchestration that takes a HIPAA 837 file in, breaks it into its individual claims, and saves the complete xml message to the database. I have a WCF SQL send port that calls a stored procedure to do this... the proc just does an insert with no return value. The problem is that I keep (randomly) getting the timeout error:

Details:"Microsoft.ServiceModel.Channels.Common.InvalidUriException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

I just tried this with a small file - only 5 individual claims in it (so I should only need 5 connections from the pool, right?). The BT server has been doing nothing else for the past 10 hours (no messages processed). Yet I still received this error... My MaxConnectionPoolSize is set to 100, so that means 100 connections have been held open and idle for at least 10 hours ?? What's going on here?

Thanks.

答:
I would take a look here or here.  To be honest the WCF SQL adapter is very picky and quirky as to what SQL it works well with and what it doesn't.  I typically look for a custom solution for inserting into SQL to have more control over the inserts or updates without having to write my SQL specific for the SQL adapter.  I find if I'm inserting or updating more than one table or returning a complex records, I avoid the WCF SQL adapter.

If that's not an option, look at re-writing your SQL.


问:
How to configure guava cache to remove item after a read?
I would like to remove (invalidate) an item after it was read from a cache.

So item should be present in a cache until a first read.

I've tried adding expireAfterAccess(0, TimeUnit.NANOSECONDS) but then cache is not populated.

Is there any way to use guava cache in such manner or do I need to invalidate item manually after a read?

答:
In my example nonce are created twice:

```<code>LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(0, TimeUnit.NANOSECONDS)
    .build(new CacheLoader<String, String>() {
        @Override
        public String load(String key) throws Exception {
            return createNonce();
        }
    });

@Test
public void test_cache_eviction() throws Exception {
    String nonce1 = cache.getUnchecked("key");
    String nonce2 = cache.getUnchecked("key");
}

public String createNonce() {
    String createdNonce = "createdNonce";
    System.out.println(createdNonce);
    return createdNonce;
}
</code>```

In logs "createdNonce" are printed twice.

Body:
In my example nonce are created twice:

LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(0, TimeUnit.NANOSECONDS)
    .build(new CacheLoader<String, String>() {
        @Override
        public String load(String key) throws Exception {
            return createNonce();
        }
    });

@Test
public void test_cache_eviction() throws Exception {
    String nonce1 = cache.getUnchecked("key");
    String nonce2 = cache.getUnchecked("key");
}

public String createNonce() {
    String createdNonce = "createdNonce";
    System.out.println(createdNonce);
    return createdNonce;
}

In logs "createdNonce" are printed twice.


问:
Change URL parameters and specify defaults using JavaScript
I have this URL:

```<code>site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
</code>```

what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).

答:
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.</p>

```<code>                      function addOrUpdateQueryParam(param, newval, search) {

                        var questionIndex = search.indexOf('?');

                        if (questionIndex < 0) {
                            search = search + '?';
                            search = search + param + '=' + newval;
                            return search;
                        }

                        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
                        var query = search.replace(regex, "$1").replace(/&$/, '');

                        var indexOfEquals = query.indexOf('=');

                        return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
                    }
</code>```

Body:
I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).

Body:
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.

                      function addOrUpdateQueryParam(param, newval, search) {

                        var questionIndex = search.indexOf('?');

                        if (questionIndex < 0) {
                            search = search + '?';
                            search = search + param + '=' + newval;
                            return search;
                        }

                        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
                        var query = search.replace(regex, "$1").replace(/&$/, '');

                        var indexOfEquals = query.indexOf('=');

                        return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
                    }


问:
CVS - grabbing only the latest change
foo.C  has been updated 5 times since the tag I checked out.  I want to only grab the very last change made to foo - how can I do that?</p>

答:
'cvs -q update foo.c' gets the latest version</p>

<p>'cvs -n -q update' shows the diff from local against remote. </p>

Title: CVS - grabbing only the latest change

Body:
'cvs -q update foo.c' gets the latest version

'cvs -n -q update' shows the diff from local against remote.


问:
Can't get my code to work in c
I've written a code as an assignment for my class at the university. The code is supposed to be executing newton's method to find a root for an equation (in close proximity at least) by entering the starting point and a limit. The code compiles but after i enter the necessary data the program finishes without doing anything else! Thanks for the help in advance! Here is the code:

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

double f(double x)
{
    return 4 * log10(x - 1) + 3 * pow(x,2);
}
double der_f (double x)
{
    return 4 / (x - 1) + 6 * x;
}
int main()
{
    assert(f(2) == 12);
    assert(der_f(2) == 16);
    double x;
    double e;
    printf("Please give the initial estimation of the root(bigger than one) (x(0)) as well as the limit(e)\n");
    scanf("%lf %lf", &x, &e);
    while (x <= 1)
    {
        printf("Please give the initial estimation of the root(bigger than one)(x(0))\n");
        scanf("%lf", &x);
    }
    int n = 1;
    while (fabs(f(x)) < e)
    {
        x = x -  f(x) / der_f(x);
        n ++;
        printf("x(%d) = %lf\t", n, x);
    }
    return 0;
}
</code>```

P.S: code runs until line 27

答: fabs(f(x)) < e should be fabs(f(x)) > e. You want to keep running while the value of the function is too far from zero, not while it is near zero.

Title: Can't get my code to work in c

Body:
I've written a code as an assignment for my class at the university. The code is supposed to be executing newton's method to find a root for an equation (in close proximity at least) by entering the starting point and a limit. The code compiles but after i enter the necessary data the program finishes without doing anything else! Thanks for the help in advance! Here is the code:

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

double f(double x)
{
    return 4 * log10(x - 1) + 3 * pow(x,2);
}
double der_f (double x)
{
    return 4 / (x - 1) + 6 * x;
}
int main()
{
    assert(f(2) == 12);
    assert(der_f(2) == 16);
    double x;
    double e;
    printf("Please give the initial estimation of the root(bigger than one) (x(0)) as well as the limit(e)\n");
    scanf("%lf %lf", &x, &e);
    while (x <= 1)
    {
        printf("Please give the initial estimation of the root(bigger than one)(x(0))\n");
        scanf("%lf", &x);
    }
    int n = 1;
    while (fabs(f(x)) < e)
    {
        x = x -  f(x) / der_f(x);
        n ++;
        printf("x(%d) = %lf\t", n, x);
    }
    return 0;
}

P.S: code runs until line 27


问:
Sticky top navbar without having the logo resize
I have the following code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

TEAM

SERVICES

GALLERY

LOCATION

```

For the life of me I can't understand why the logo is displaying at full size and not being contained in the Navbar. I basically want the logo on the left and my menu items on the right. Moreover, I want them to always be on the samle line, i.e. when I resize the windows (or on a smaller screen like an iPhone for example), it scales down. Maybe I have tunnel vision but can anyone perhaps point out the problem?

答:
Can't say for sure without looking at your css, but images will only be resized if the logo class is configured correctly. You may want to look at this example https://codepen.io/bootstrapped/pen/KwYGwq on how to configure css properly.

For what concerns wrapping, the default behaviour is to wrap especially as you are dividing the screen in 2 columns when small. An option is to play around with CSS (see How to make bootstrap 3 navbar not wrap). Alternatively, play with column sizing so that a small logo doesn't take half screen real estate and the menu items are scaled correctly. For very small screen, the best option is to collapse and show a vertical menu.

This code from bootply should do what you need:

```<code>    <div class="container example2">
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar2">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="http://disputebills.com"><img src="https://res.cloudinary.com/candidbusiness/image/upload/v1455406304/dispute-bills-chicago.png" alt="Dispute Bills">
        </a>
      </div>
      <div id="navbar2" class="navbar-collapse collapse">
        <ul class="nav navbar-nav navbar-right">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Contact</a></li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
              <li><a href="#">Action</a></li>
              <li><a href="#">Another action</a></li>
              <li><a href="#">Something else here</a></li>
              <li class="divider"></li>
              <li class="dropdown-header">Nav header</li>
              <li><a href="#">Separated link</a></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
        </ul>
      </div>
      <!--/.nav-collapse -->
    </div>
    <!--/.container-fluid -->
  </nav>
</div>
</code>```

and this is the CSS

```<code>.navbar-brand {
  padding: 0px;
}
.navbar-brand>img {
  height: 100%;
  padding: 15px;
  width: auto;
}

/* EXAMPLE 2 (larger logo) - simply adjust top bottom padding to make logo larger */

.example2 .navbar-brand>img {
  padding: 7px 15px;
}

/* CSS Transform Align Navbar Brand Text ... This could also be achieved with table / table-cells */
.navbar-alignit .navbar-header {
      -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
  height: 50px;
}
.navbar-alignit .navbar-brand {
    top: 50%;
    display: block;
    position: relative;
    height: auto;
    transform: translate(0,-50%);
    margin-right: 15px;
  margin-left: 15px;
}

.navbar-nav>li>.dropdown-menu {
    z-index: 9999;
}

body {
  font-family: "Lato";
}
</code>```

Body:
I have the following code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

TEAM

SERVICES

GALLERY

LOCATION

For the life of me I can't understand why the logo is displaying at full size and not being contained in the Navbar. I basically want the logo on the left and my menu items on the right. Moreover, I want them to always be on the samle line, i.e. when I resize the windows (or on a smaller screen like an iPhone for example), it scales down. Maybe I have tunnel vision but can anyone perhaps point out the problem?

Body:
Can't say for sure without looking at your css, but images will only be resized if the logo class is configured correctly. You may want to look at this example https://codepen.io/bootstrapped/pen/KwYGwq on how to configure css properly.

For what concerns wrapping, the default behaviour is to wrap especially as you are dividing the screen in 2 columns when small. An option is to play around with CSS (see How to make bootstrap 3 navbar not wrap). Alternatively, play with column sizing so that a small logo doesn't take half screen real estate and the menu items are scaled correctly. For very small screen, the best option is to collapse and show a vertical menu.

This code from bootply should do what you need:

    <div class="container example2">
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar2">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="http://disputebills.com"><img src="https://res.cloudinary.com/candidbusiness/image/upload/v1455406304/dispute-bills-chicago.png" alt="Dispute Bills">
        </a>
      </div>
      <div id="navbar2" class="navbar-collapse collapse">
        <ul class="nav navbar-nav navbar-right">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Contact</a></li>
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
              <li><a href="#">Action</a></li>
              <li><a href="#">Another action</a></li>
              <li><a href="#">Something else here</a></li>
              <li class="divider"></li>
              <li class="dropdown-header">Nav header</li>
              <li><a href="#">Separated link</a></li>
              <li><a href="#">One more separated link</a></li>
            </ul>
          </li>
        </ul>
      </div>
      <!--/.nav-collapse -->
    </div>
    <!--/.container-fluid -->
  </nav>
</div>

and this is the CSS

.navbar-brand {
  padding: 0px;
}
.navbar-brand>img {
  height: 100%;
  padding: 15px;
  width: auto;
}

/* EXAMPLE 2 (larger logo) - simply adjust top bottom padding to make logo larger */

.example2 .navbar-brand>img {
  padding: 7px 15px;
}

/* CSS Transform Align Navbar Brand Text ... This could also be achieved with table / table-cells */
.navbar-alignit .navbar-header {
      -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
  height: 50px;
}
.navbar-alignit .navbar-brand {
    top: 50%;
    display: block;
    position: relative;
    height: auto;
    transform: translate(0,-50%);
    margin-right: 15px;
  margin-left: 15px;
}

.navbar-nav>li>.dropdown-menu {
    z-index: 9999;
}

body {
  font-family: "Lato";
}


问:
Text input with IF statements
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

```<code><!DOCTYPE HTML>
<html>

<head>
<script type="text/javascript" src="gamescript.js"></script>
</head>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<script>
function myFunction(){
    var door = document.getElementById("myInput").value;
    if (door == "Door 1", "door 1"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else if (door == "Door 2", "door 2"){
        document.getElementById("door").innerHTML = "You have entered" + door;
    }else{
        document.getElementById("door").innerHTML = "You must enter a door!"
    }
}

</script>

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

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

答:
Rather than execute the same line of code in separate conditions, why not utilize a simple switch?

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

```

Title: Text input with IF statements

Body:
I am creating a very simple story based "game" where there is a question with choices (not radio buttons etc) and the user has to type in the choices that's been given to them. I am not very good with JavaScript as you will see...

<!DOCTYPE HTML>

 Which door do you wish to enter? Door 1 or Door 2?

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

I am not getting any errors but when I type in something random/or leave blank, it's meant to say "Choose a door" but it's displaying anything i type into the text box. This code might be wrong, i'm guessing it most likely is..I didn't want to come online for help but have no one else to ask. All help is appreciated. Thank you.

Body:
Rather than execute the same line of code in separate conditions, why not utilize a simple switch?

<!DOCTYPE HTML>
<html>

<body>

<p id ="door"> Which door do you wish to enter? Door 1 or Door 2? </p>

<input id="myInput" type="text">

<button onclick="myFunction()">Enter</button>

<script>
    function myFunction(){
        var door = document.getElementById("myInput").value;
        switch(door.toLowerCase()) {
            case 'door 1':
            case 'door 2':
                document.getElementById("door").innerHTML = "You have entered" + door;
                break;
            default:
                document.getElementById("door").innerHTML = "You must enter a door!"
        }
    }

</script>

</body>
</html>


问:
How to use FirebaseApp.initializeApp for FirebaseRemoteConfig
I am trying to use FirebaseApp.initializeApp, but its not working. I have the right library, but I cannot use the JSON file to initialize the app

This is my code:

Imports

```<code>import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
</code>```

Variables

```<code>private FirebaseRemoteConfig mFirebaseRemoteConfig;

private String projectID;
private String apiKey;
private String appID;
</code>```

How I initialize the app

```<code>public void Initialize() {
    FirebaseOptions mFirebaseOptions = new FirebaseOptions.Builder()
        .setApplicationId(this.appID)
        .setApiKey(this.apiKey)
        .build();
    FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
}
</code>```

The app crashed on startup this is the logcat error:

```<code>12-04 22:11:42.217 12566 12566 E AndroidRuntime: FATAL EXCEPTION: main
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Process: com.makeroid.sanderjochems.FirebaseRemoteConfig, PID: 12566
12-04 22:11:42.217 12566 12566 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzby;
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.FirebaseRemoteConfiguration.<init>(FirebaseRemoteConfiguration.java:67)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance0(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.expr.PrimProcedure.apply(PrimProcedure.java:272)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilDone(CallContext.java:234)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilValue(CallContext.java:298)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.kawa.reflect.Invoke.applyN(Invoke.java:209)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.ProcedureN.apply2(ProcedureN.java:39)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.makeroid.sanderjochems.FirebaseRemoteConfig.Screen1.$define(Screen1.yail:10182)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreateFinish(Form.java:389)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreate(Form.java:336)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6942)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.-wrap14(ActivityThread.java)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6682)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzby" on path: DexPathList[[zip file "/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/base.apk"],nativeLibraryDirectories=[/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/lib/arm64, /system/lib64, /vendor/lib64]]
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        ... 25 more
</code>```

答: Disable the instant-run while generating application and make sure you have added google-services.json file to your project.

Body:
I am trying to use FirebaseApp.initializeApp, but its not working. I have the right library, but I cannot use the JSON file to initialize the app

This is my code:

Imports

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;

Variables

private FirebaseRemoteConfig mFirebaseRemoteConfig;

private String projectID;
private String apiKey;
private String appID;

How I initialize the app

public void Initialize() {
    FirebaseOptions mFirebaseOptions = new FirebaseOptions.Builder()
        .setApplicationId(this.appID)
        .setApiKey(this.apiKey)
        .build();
    FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
}

The app crashed on startup this is the logcat error:

12-04 22:11:42.217 12566 12566 E AndroidRuntime: FATAL EXCEPTION: main
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Process: com.makeroid.sanderjochems.FirebaseRemoteConfig, PID: 12566
12-04 22:11:42.217 12566 12566 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzby;
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.FirebaseRemoteConfiguration.<init>(FirebaseRemoteConfiguration.java:67)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance0(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.expr.PrimProcedure.apply(PrimProcedure.java:272)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilDone(CallContext.java:234)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilValue(CallContext.java:298)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.kawa.reflect.Invoke.applyN(Invoke.java:209)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.ProcedureN.apply2(ProcedureN.java:39)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.makeroid.sanderjochems.FirebaseRemoteConfig.Screen1.$define(Screen1.yail:10182)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreateFinish(Form.java:389)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreate(Form.java:336)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6942)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.-wrap14(ActivityThread.java)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6682)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzby" on path: DexPathList[[zip file "/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/base.apk"],nativeLibraryDirectories=[/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/lib/arm64, /system/lib64, /vendor/lib64]]
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        ... 25 more


问:
inline css style width not able to override computed css style's width value
I'm seeing a strange behaviour which i'm not able to figure out.

The webpage that i'm working on has a lot of css styles. So for one of my div's i'm using inline css to make the width as per my requirement (which shows up in the source code just fine). But when i'm inspecting the element in Google Chrome i see that the computed width as slightly less than my value. How do i override the computed value.

Thanks

答:
Try with !important to override any value.</p>

```<code>#div {width:500px !important;}
</code>```

Body:
Try with !important to override any value.

#div {width:500px !important;}


问:
How to optimise large loops for debug mode
I have implemented a pixel mask class used for checking for perfect collision. I am using SFML so the implementation is fairly straight forward:

Loop through each pixel of the image and decide whether its true or false based on its transparency value. Here is the code I have used:

```<code>// Create an Image from the given texture
    sf::Image image(texture.copyToImage());

    // measure the time this function takes
    sf::Clock clock;
    sf::Time time = sf::Time::Zero;
    clock.restart();

    // Reserve memory for the pixelMask vector to avoid repeating allocation
    pixelMask.reserve(image.getSize().x);

    // Loop through every pixel of the texture
    for (unsigned int i = 0; i < image.getSize().x; i++)
    {
        // Create the mask for one line
        std::vector<bool> tempMask;
        // Reserve memory for the pixelMask vector to avoid repeating allocation
        tempMask.reserve(image.getSize().y);

        for (unsigned int j = 0; j < image.getSize().y; j++)
        {
            // If the pixel is not transparrent
            if (image.getPixel(i, j).a > 0)
                // Some part of the texture is there --> push back true
                tempMask.push_back(true);
            else
                // The user can't see this part of the texture --> push back false
                tempMask.push_back(false);
        }
        pixelMask.push_back(tempMask);
    }

    time = clock.restart();
    std::cout << std::endl << "The creation of the pixel mask took: " << time.asMicroseconds() << " microseconds (" << time.asSeconds() << ")";
</code>```

I have used the an instance of the sf::Clock to meassure time.

My problem is that this function takes ages (e.g. 15 seconds) for larger images(e.g. 1280x720). Interestingly, only in debug mode. When compiling the release version the same texture/image only takes 0.1 seconds or less.

I have tried to reduce memory allocations by using the resize() method but it didn't change much. I know that looping through almost 1 million pixels is slow but it should not be 15 seconds slow should it?

Since I want to test my code in debug mode (for obvious reasons) and I don't want  to wait 5 min till all the pixel masks have been created, what I am looking for is basically a way to:

Either optimise the code / have I missed somthing obvious?

Or get something similar to the release performance in debug mode

Thanks for your help!

答:
Loops are faster if working with costants:
1. for (unsigned int i = 0; i < image.getSize().x; i++) get this image.getSize() before the loop.
2. get the mask for one line out of the loop and reuse it. Lines are of the same length I assume.      std::vector tempMask;
This shall speed you up a bit.
Note that the compilation for debugging gives way more different machine code.</p>

Body:
I have implemented a pixel mask class used for checking for perfect collision. I am using SFML so the implementation is fairly straight forward:

Loop through each pixel of the image and decide whether its true or false based on its transparency value. Here is the code I have used:

// Create an Image from the given texture
    sf::Image image(texture.copyToImage());

    // measure the time this function takes
    sf::Clock clock;
    sf::Time time = sf::Time::Zero;
    clock.restart();

    // Reserve memory for the pixelMask vector to avoid repeating allocation
    pixelMask.reserve(image.getSize().x);

    // Loop through every pixel of the texture
    for (unsigned int i = 0; i < image.getSize().x; i++)
    {
        // Create the mask for one line
        std::vector<bool> tempMask;
        // Reserve memory for the pixelMask vector to avoid repeating allocation
        tempMask.reserve(image.getSize().y);

        for (unsigned int j = 0; j < image.getSize().y; j++)
        {
            // If the pixel is not transparrent
            if (image.getPixel(i, j).a > 0)
                // Some part of the texture is there --> push back true
                tempMask.push_back(true);
            else
                // The user can't see this part of the texture --> push back false
                tempMask.push_back(false);
        }
        pixelMask.push_back(tempMask);
    }

    time = clock.restart();
    std::cout << std::endl << "The creation of the pixel mask took: " << time.asMicroseconds() << " microseconds (" << time.asSeconds() << ")";

I have used the an instance of the sf::Clock to meassure time.

My problem is that this function takes ages (e.g. 15 seconds) for larger images(e.g. 1280x720). Interestingly, only in debug mode. When compiling the release version the same texture/image only takes 0.1 seconds or less.

I have tried to reduce memory allocations by using the resize() method but it didn't change much. I know that looping through almost 1 million pixels is slow but it should not be 15 seconds slow should it?

Since I want to test my code in debug mode (for obvious reasons) and I don't want  to wait 5 min till all the pixel masks have been created, what I am looking for is basically a way to:

Either optimise the code / have I missed somthing obvious?

Or get something similar to the release performance in debug mode

Thanks for your help!


问:
Git stash pop Auto merged after the following done
I'm trying to restore my unsaved files (stashed files)

I had to make a small code change for that first my remote is one commit a head with 1 file change(file1). I need to update my local first with remote and push my changes, for that I have to stash my changes in my local as I have the same file modified (file1) in my local. So I have done the following.

```<code>$git stash
  Saved working directory and index state WIP on dev: 4eb5499

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git add file2 //this is different file.
$git commit
$git push

//with this done on my dev branch I also want to update my master branch with remote

So

$git checkout master
  Switched to branch 'master'
  Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git merge dev //to update my changes on master
$git push

  with this done my remote is updated with my changes. both on dev/master branch.

  Now I have switched my branch again.

$git checkout dev
$git stash pop
  Auto-merging **file1**
  CONFLICT (content): Merge conflict in **file1**

  As i have done
$git status

  On branch dev
  Your branch is up-to-date with 'origin/dev'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

   So I have performed the following
$ git reset HEAD

$ git status
  On branch dev
  Your branch is up-to-date with 'origin/dev'.

  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)

$ git stash list
  stash@{0}: WIP on dev: 4eb5499 //I want the changes which are here.
  stash@{1}: WIP on master: 9dac6b5

$ git stash pop
  error: Your local changes to the following files would be overwritten by merge:
</code>```

I just want my stashed files to be used again.

答:
This occurs because the stash commit that you are attempting to apply via git stash pop conflicts with the current work-tree.

Many people run git stash instead of git commit in the mistaken belief that git stash does not make a commit.  This is not the case: in fact, git stash makes at least two commits.  (Depending on the flags you give git stash, it may make three commits instead of two.)  The thing that is the most special about the commits that git stash makes is that they are on no branch at all.

Nonetheless, they are still commits, just like other commits.  When you go to "pop" a stash, this simply means git stash apply && git stash drop.  That is, you are telling Git to apply the stash to your current work-tree contents.  If Git believes this went well, you then tell Git to drop the stash, i.e., discard the stash commits.

In some cases, the stash commits will not apply cleanly, and you will get a merge conflict, just as you would if you were running git merge or git cherry-pick.  You must resolve this merge conflict, just as you would any other merge conflict.  Note that in this case Git has not dropped the stash: git stash list will still show it.

For more about resolving stash conflicts, see How to resolve git stash conflict without commit?

Body:
I'm trying to restore my unsaved files (stashed files)

I had to make a small code change for that first my remote is one commit a head with 1 file change(file1). I need to update my local first with remote and push my changes, for that I have to stash my changes in my local as I have the same file modified (file1) in my local. So I have done the following.

$git stash
  Saved working directory and index state WIP on dev: 4eb5499

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git add file2 //this is different file.
$git commit
$git push

//with this done on my dev branch I also want to update my master branch with remote

So

$git checkout master
  Switched to branch 'master'
  Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git merge dev //to update my changes on master
$git push

  with this done my remote is updated with my changes. both on dev/master branch.

  Now I have switched my branch again.

$git checkout dev
$git stash pop
  Auto-merging **file1**
  CONFLICT (content): Merge conflict in **file1**

  As i have done
$git status

  On branch dev
  Your branch is up-to-date with 'origin/dev'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

   So I have performed the following
$ git reset HEAD

$ git status
  On branch dev
  Your branch is up-to-date with 'origin/dev'.

  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)

$ git stash list
  stash@{0}: WIP on dev: 4eb5499 //I want the changes which are here.
  stash@{1}: WIP on master: 9dac6b5

$ git stash pop
  error: Your local changes to the following files would be overwritten by merge:

I just want my stashed files to be used again.


问:
Custom attributes lead to errors when binding Angular templates
We are binding model data in component template markup which works until we attempt to bind data to custom attributes. We see errors such as Can't bind to 'x-version' since it isn't a known property of 'section' and different errors if we apply the bracketed pattern.

Essentially we are placing hidden data in the markup for other scripts to use within their processes. Can someone clarify what is happening and suggest ways to accomplish this?

We have attempted to apply the following two patterns and get errors on each. We are using Angular 2+

```<code><section x-version="{{item?.version}}">
...
</section>

<section [x-version]="item?.version">
...
</section>
</code>```

答:
Try this:</p>

```<code><section attr.x-version="{{item?.version}}">
...
</section>

<section [attr.x-version]="item?.version">
...
</section>
</code>```

Body:
We are binding model data in component template markup which works until we attempt to bind data to custom attributes. We see errors such as Can't bind to 'x-version' since it isn't a known property of 'section' and different errors if we apply the bracketed pattern.

Essentially we are placing hidden data in the markup for other scripts to use within their processes. Can someone clarify what is happening and suggest ways to accomplish this?

We have attempted to apply the following two patterns and get errors on each. We are using Angular 2+

...

...

Body:
Try this:

<section attr.x-version="{{item?.version}}">
...
</section>

<section [attr.x-version]="item?.version">
...
</section>


答:
If you have a dataframe like this below:

```<code>df = pd.DataFrame({'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'],
'col2' : [2, 1, 9, 8, 7, 4],
'col3': [0, 1, 9, 4, 2, 3], })
</code>```

This is how you sort it:

```<code>df = df.sort_values(by=['col1'])
</code>```

Similar problem with solution on stackoverflow:
how to sort pandas dataframe from one column
Panda reference :
http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.sort.html

Body:
I try to sort dataframe shown below by date using df.sort_values(by='date') however it doesn't work. Any ideas how can I do this to be sure that it is sorted properly?

     symbol        date     open    close     high      low
0      GOOG  2007-01-03   232.77   233.56   238.09   230.32
1      GOOG  2007-01-05   241.01   243.35   243.51   238.82
2      GOOG  2007-01-04   234.27   241.39   241.73   233.94

...
2692   GOOG  2017-11-30  1022.37  1021.41  1028.49  1015.00
2693   GOOG  2017-11-29  1042.68  1021.66  1044.08  1015.65
2694   GOOG  2017-12-01  1015.80  1010.17  1022.49  1002.02

Body:
If you have a dataframe like this below:

df = pd.DataFrame({'col1' : ['A', 'A', 'B', np.nan, 'D', 'C'],
'col2' : [2, 1, 9, 8, 7, 4],
'col3': [0, 1, 9, 4, 2, 3], })

This is how you sort it:

df = df.sort_values(by=['col1'])

Similar problem with solution on stackoverflow:
how to sort pandas dataframe from one column
Panda reference :
http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.sort.html


问:
How do I import an ActiveX control in BCB5 with tlibimp?
What are the required flags for tlibimp.exe to properly mimic choosing
'Component -> Import ActiveX Control -> Install'
in the Borland C++ Builder 5 IDE?  I currently pass tlibimp an ocx and -L-, but there is a loss in funcionality when compared with results of importing it manually.</p>

答:
The command line depends on what the IDE is attempting..for example install a component as active x.

-A TypeLibrary file suffix (defaults to '_TLB', -A- : no
suffix)
  -D Output directory

-F TypeLibrary Output filename (extension ignored)

-N C++ namespace name
  -X OCX Wrappers Output filename (extension ignored - C++
only)

Switches: - (defaults are shown below)

-C- Generate C++ import file

-E+ Generate wrapper class for dispinterfaces (C++ only)

-G+ Expose namespace with 'using' statement

-H+ Generate IDE component wrappers for ActiveX Controls

-J- Generate CORBA IDL source file

-K- Generate Pascal CORBA Stubs and Skeletons

-L- Generate IDE component wrappers for OLE Servers

-O+ Generate CoClass Creator wrappers

-P+ Generate Pascal import file

-Q+ Generate 'Register' function for IDE components wrappers

-R+ Generate files for dependent typelibraries

-S+ Map HRESULT stdcall to safecall on dual interfaces (Delphi only)

-T- Map HRESULT stdcall to safecall on all interfaces (Delphi only)

-V- Generate Event wrappers for Server (C++ only)

-W+ Warnings in import file

-Yh Ignore the [Hidden] flag when importing

-Yr Ignore the [Restricted] flag when importing

-Yp Ignore the [PreDeclID] flag when importing

-Ya Combined -Yh -Yr -Yp

--

Michael

OwnerDisplayName: Michael


问:
Allowed compiler optimizations on loops in C++11
Is a C++11-compliant compiler allowed to optimize/transform this code from:

```<code>bool x = true; // *not* an atomic type, but suppose bool can be read/written atomically
/*...*/
{
    while (x); // spins until another thread changes the value of x
}
</code>```

to anything equivalent to an infinite loop:

```<code>{
    while (true); // infinite loop
}
</code>```

The above conversion is certainly valid from the point of view of a single-thread program, but this is not the general case.

Also, was that optimization allowed in pre-C++11?

答:
The compiler is allowed go do anything to those two loops. Including terminating the program. Because infinite loops have undefined behaviour if they do not perform a synchronization-like operation (do something that requires synchronization with another thread or I/O), according to the C++ memory model:

Note that it means that a program with endless recursion or endless loop (whether implemented as a for-statement or by looping goto or otherwise) has undefined behavior.

Body:
Is a C++11-compliant compiler allowed to optimize/transform this code from:

bool x = true; // *not* an atomic type, but suppose bool can be read/written atomically
/*...*/
{
    while (x); // spins until another thread changes the value of x
}

to anything equivalent to an infinite loop:

{
    while (true); // infinite loop
}

The above conversion is certainly valid from the point of view of a single-thread program, but this is not the general case.

Also, was that optimization allowed in pre-C++11?


问:
Having trouble creating an object within a switch statement, "Object cannot be resolved" in later code (java)
I am writing a method that takes in a string variable type that is used to determine which list class to implement. The method uses a switch statement to create the appropriate type of list using the variable name newList.

The switch statement looks like this:

```<code>switch (type) {
    case "unsorted": {
        UnsortedList newList = new UnsortedList();
        break;
    }
    case "sorted": {
        SortedList newList = new SortedList();
        break;
    }
    case "new sorted": {
        NewSortedList newList = new NewSortedList();
        break;
    }
    default: {
        System.out.print("Something went wrong! List type unrecognized. I have initialized newList to be an unsorted list.");
        UnsortedList newList = new UnsortedList();
    }
}
</code>```

According to this, I believe that newList will always be instantiated due to the default case of the switch statement. However I receive the compile error "newList cannot be resolved".

Is there anything I can do to prevent this?

答:
Both of the prior comments answered the question. You create several different local newList fields that immediately go out of scope.

The solution is to create List newList outside the switch. Note that it will be limited, however, to the methods specified by list, so you won't be able to access sorting methods.

Body:
I am writing a method that takes in a string variable type that is used to determine which list class to implement. The method uses a switch statement to create the appropriate type of list using the variable name newList.

The switch statement looks like this:

switch (type) {
    case "unsorted": {
        UnsortedList newList = new UnsortedList();
        break;
    }
    case "sorted": {
        SortedList newList = new SortedList();
        break;
    }
    case "new sorted": {
        NewSortedList newList = new NewSortedList();
        break;
    }
    default: {
        System.out.print("Something went wrong! List type unrecognized. I have initialized newList to be an unsorted list.");
        UnsortedList newList = new UnsortedList();
    }
}

According to this, I believe that newList will always be instantiated due to the default case of the switch statement. However I receive the compile error "newList cannot be resolved".

Is there anything I can do to prevent this?


问:
How to check if ios is using private browsing
One of my jquery plugins is having issues, and the issue occurs when private browsing is turned on in ios.

Is there a way to check this?

答:
I've found an Answear at GitHub and tested it: Working on IOS 11!

```<code>var isPrivate = false;
try {
  window.openDatabase(null, null, null, null);
} catch (_) {
  isPrivate = true;
}
alert((isPrivate ? 'You\'re' : 'You aren\'t')  + ' in private browsing mode');
</code>```

Body:
I've found an Answear at GitHub and tested it: Working on IOS 11!

var isPrivate = false;
try {
  window.openDatabase(null, null, null, null);
} catch (_) {
  isPrivate = true;
}
alert((isPrivate ? 'You\'re' : 'You aren\'t')  + ' in private browsing mode');


答:
When you place an attribute on an html tag, Angular will try to find a corresponding Input element on the corresponding component, or a directive that is expecting that same attribute.
in short, you need to create a Directive XVersion like so :

```<code>import { Directive, ElementRef,Renderer,Input} from '@angular/core';
@Directive({
    selector: '[x-version]'
})

export class XVersion {
    @Input versions;
    constructor(elementRef: ElementRef, renderer: Renderer) {
        //Use elementRef, renderer, and this.version to manipulate the Dom here
    }
}
</code>```

then use the attribute with square braquets.

Alternatively, you can try @DeborahK's solution, but I'm afraid the - in x-version will be a problem

Title: Custom attributes lead to errors when binding Angular templates

Body:
When you place an attribute on an html tag, Angular will try to find a corresponding Input element on the corresponding component, or a directive that is expecting that same attribute.
in short, you need to create a Directive XVersion like so :

import { Directive, ElementRef,Renderer,Input} from '@angular/core';
@Directive({
    selector: '[x-version]'
})

export class XVersion {
    @Input versions;
    constructor(elementRef: ElementRef, renderer: Renderer) {
        //Use elementRef, renderer, and this.version to manipulate the Dom here
    }
}

then use the attribute with square braquets.

Alternatively, you can try @DeborahK's solution, but I'm afraid the - in x-version will be a problem