问:
Get the value from an Array
I have some code I need help with:

```<code>var bob = [10,30,50,20,8];

// Call the function

foo(bob);

var foo = function(bob){

 var max = 0,
 min = 0,
 average = 0,
 sum = 0;

 max = Math.max.apply( null, bob); // Get the max value.
 min = Math.min.apply( null, bob); // Get the min value.

 for( var i = 0; i < bob.length; i++ ){
  sum += bob[ i ];
 }

 average = sum / l;

 var resultArr = [];

 resultArr[0] = average;
 resultArr[1] = min;
 resultArr[2] = max;

 return resultArr;
}

document.getElementById('max').innerHTML = "Max value: "; // i want to print the max value here.
</code>```

This function returns an array with max, min and average values. How can I choose which value to print in different divs?

答:
You already have the answer:</p>

```<code>var resultArr = foo(bob);
document.getElementById('max').innerHTML = resultArr[2];
document.getElementById('min').innerHTML = resultArr[1];
// etc
</code>```

Title: Get the value from an Array

Body:
I have some code I need help with:

var bob = [10,30,50,20,8];

// Call the function

foo(bob);

var foo = function(bob){

 var max = 0,
 min = 0,
 average = 0,
 sum = 0;

 max = Math.max.apply( null, bob); // Get the max value.
 min = Math.min.apply( null, bob); // Get the min value.

 for( var i = 0; i < bob.length; i++ ){
  sum += bob[ i ];
 }

 average = sum / l;

 var resultArr = [];

 resultArr[0] = average;
 resultArr[1] = min;
 resultArr[2] = max;

 return resultArr;
}

document.getElementById('max').innerHTML = "Max value: "; // i want to print the max value here.

This function returns an array with max, min and average values. How can I choose which value to print in different divs?

Body:
You already have the answer:

var resultArr = foo(bob);
document.getElementById('max').innerHTML = resultArr[2];
document.getElementById('min').innerHTML = resultArr[1];
// etc


来源: stackexchange

问:
Select last entry and offset by 1 row then paste value not working
I'm having Run time error 1004 with this code.

```<code>Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and     perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
  .Title = "Select A Target Folder"
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

    'Loop through each Excel file in folder
  Do While myFile <> ""
'Set variable equal to opened workbook
  Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
  DoEvents

Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")

With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"
' paste
.Range("E" & LastRow + 1) = rng1
End With

'Save and Close Workbook
  wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
  DoEvents

'Get next file name
  myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
</code>```

I'm using this segment of code to extract data from B15 to E81 from all the excel workbook in the folder.

Upon copying, it will activate the workbook where this code lie

Select last entry from column E

Offset by 1 row

Paste selection to column activated cell

Appreciate all the help I could find. Thanks in advance.

答:
Your code snippet runs without errors for me. You may want to rethink the approach, though. Code that uses Activate and Select is slow and inefficient. In most cases Activate and Select are not required. The objects can be addressed directly.

See this question for techniques to avoid Select and Activate.

ContentLicense: CC BY-SA 3.0

Body:
I'm having Run time error 1004 with this code.

Sub LoopAllExcelFilesInFolder()
'PURPOSE: To loop through all Excel files in a user specified folder and     perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

With FldrPicker
  .Title = "Select A Target Folder"
  .AllowMultiSelect = False
    If .Show <> -1 Then GoTo NextCode
    myPath = .SelectedItems(1) & "\"
End With

   'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xls*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

    'Loop through each Excel file in folder
  Do While myFile <> ""
'Set variable equal to opened workbook
  Set wb = Workbooks.Open(Filename:=myPath & myFile)

'Ensure Workbook has opened before moving on to next line of code
  DoEvents

Dim LastRow As Long
Dim rng1 As Range
wb.Worksheets(1).Activate
Set rng1 = Range("B15:E81,N15:O81")

With ThisWorkbook.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name
LastRow = .Cells(.Rows.Count, "E").End(xlUp).Row ' get last row with data in column "E"
' paste
.Range("E" & LastRow + 1) = rng1
End With

'Save and Close Workbook
  wb.Close SaveChanges:=True

'Ensure Workbook has closed before moving on to next line of code
  DoEvents

'Get next file name
  myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

I'm using this segment of code to extract data from B15 to E81 from all the excel workbook in the folder.

Upon copying, it will activate the workbook where this code lie

Select last entry from column E

Offset by 1 row

Paste selection to column activated cell

Appreciate all the help I could find. Thanks in advance.


问:
Is there an addon for firefox that when you look at the source code xml it formats it with appropriate formatting (newlines, indentation..etc)
Any help greatly appreciated thanks.</p>

答: Html Validator

ContentLicense: CC BY-SA 2.5

Body: Any help greatly appreciated thanks.

Body: Html Validator


问:
Check if a location exists in a route in Map API
I'm using MapBox iOS SDK for showing route between two locations. I would like to know if there is any possibility to check whether a location lies in a route.

I need this functionality so that if any incident happen one location and if that location lies in the route, I need to alert the user about this and need to show the alternate route.

For e.g.:- Say I have plotted a route between location A and location B. I want to check if location C lies in the route between A and B. Any suggestion from MapBox Api or google maps Api is welcomed.

答: you can get a list of coordinate from mapbox route, then i think calculate distance from points to your interested point. it can yield an acceptable result</p>


问:
Missing xxx.dll when performing built executives in visual studio
The system warned that missing opencv_core331.dll

However, I have added the path of directory that include opencv_core331.dll to the environment variables of Windows:

Who can help?

答:
This is a run-time issue, the libraries path has nothing to do with it. You need to either edit the global PATH variable  or the executable directories in the project properties. I would personally recommend the global PATH variable because that way your program will run outside of VS as well as from it.

To do so, in the start menu search box type "environment" and select the ""Edit system environment variables" if you want to make the change for all accounts.environment variables for your account" or (


问:
consume free space of reportviewer body to reduce total number of pages
I've two columns report, when exporting or printing the result is multiple pages, each one have table with just two columns and the rest of the page (more than 60% is blank). Is there way to let the reportviewer append the rest of table to the next of existing table in the same page rather than make new page?
as image describe]1

答:
I solved this problem by change the underlying SQL query.
I joined the table with itself like:

```<code>select n1.number, n1.remarks, n2.number, n2.remarks
from numbers as n1 left join numbers as n2 on n2.id = n1.id + 1
where n1.id % 2 =1
</code>```

this may inspire you to solve your problem!
there are two remarks:

1) the id values MUST began with 1 and be sequential (1,2,3...)

2) I've used left join to include the last odd id number -if exists.

   I'll explain: if there are three numbers with ids 1,2 and 3, if you use inner join the third number will not appear in query result!

Body:
I solved this problem by change the underlying SQL query.
I joined the table with itself like:

select n1.number, n1.remarks, n2.number, n2.remarks
from numbers as n1 left join numbers as n2 on n2.id = n1.id + 1
where n1.id % 2 =1

this may inspire you to solve your problem!
there are two remarks:

1) the id values MUST began with 1 and be sequential (1,2,3...)

2) I've used left join to include the last odd id number -if exists.

   I'll explain: if there are three numbers with ids 1,2 and 3, if you use inner join the third number will not appear in query result!


问:
Should pointer comparisons be signed or unsigned in 64-bit x86?
When writing x86-64 user-space assembly and comparing two pointer values, should we use signed conditions such as jl and jge or unsigned conditions such as jb and jae?

Intuitively I think of pointers as unsigned, running from 0 to 2^64-1 in the case of a 64-bit process, and I think this model is accurate for 32-bit code. I guess that's how most people think about them.

In 64-bit code however I don't think you can ever validly cross over the signed discontinuity at 0x7FFFFFFFFFFFFFFF (2^63 - 1), and many interesting memory regions tend to clustered near signed 0 (for code and static data often, and sometimes heap depending on the implementation), and near the maximum address on the lower half of the canonical address space (something like of 0x00007fffffffffff on most systems today) for stack locations and the heap on some implementations1.

So I'm not sure which way they should be treated: signed has the advantage that it is safe around 0 since there is no discontinuity there, and unsigned has the same advantage near 2^63 since there is no discontinuity there. However in practice you don't see any addresses anywhere close to 2^63 since the virtual address space of current commodity hardware is limited to less than 50 bits. Does that point towards signed?

1 ... and sometimes the heap and other mapped regions are not close to either the bottom or top of the address space.

答:
TL:DR: intptr_t might be best in some cases because the signed-overflow boundary is in the middle of the "non-canonical hole".  Treating a value as negative instead of huge may be better if wrapping from zero to 0xFF...FF or vice versa is possible, but pointer+size for any valid size can't wrap a value from INT64_MAX to INT64_MIN.

Otherwise you probably want unsigned for the "high half" (high bit set) to compare as above the low half.

It depends exactly what you want to know about two pointers!

A previous edit of your question gave ptrA < ptrB - C as the use-case you're interested in.  e.g. an overlap check with ptrA < ptrB - sizeA, or maybe an unrolled SIMD loop condition with current < endp - loop_stride.  Discussion in comments has been about this kind of thing, too.

So what you're really doing is forming ptrB - C as a pointer that's potentially outside the object you were interested in, and which may have wrapped around (unsigned).  (Good observation that stuff like this may be why C and C++ make it UB to form pointers outside of objects, but they do allow one-past-the-end which has unsigned wrapping at the end of the highest page, if the kernel even lets you map it.)  Anyway, you want to use a signed comparison so it "still works" without having to check for wraparound, or check the sign of C or any of that stuff.  This is still a lot more specific than most of the question.

Yes, for "related" pointers derived from the same object with reasonable sizes, signed compare is safe on current hardware, and could only break on unlikely / distant-future machines with hardware support for full 64-bit virtual addresses.  Overlap checks are also safe with unsigned if both pointers are in the low half of the canonical range, which I think is the case for user-space addresses on all the mainstream x86-64 OSes.

As you point out, unsigned ptrA < ptrB - C can "fail" if ptrB - C wraps (unsigned wraparound).  This can happen in practice for static addresses that are closer to 0 than the size of C.

Usually the low 64kiB is not mapable (e.g. on Linux, most distros ship with the sysctl vm.mmap_min_addr = 65536, or at least 4096.  But some systems have it =0 for WINE).  Still, I think it's normal for kernels to not give you a zero page unless you request that address specifically, because it stops NULL deref from faulting (which is normally highly desirable for security and debugability reasons).

This means the loop_stride case is usually not a problem.  The sizeA version can usually be done with ptrA + sizeA < ptrB, and as a bonus you can use LEA to add instead of copy + subtract.  ptrA+sizeA is guaranteed not to wrap unless you have objects that wrap their pointer from 2^64-1 to zero (which works even with a page-split load at the wraparound, but you'll never see it in a "normal" system because addresses are normally treated as unsigned.)

So when can it fail with a signed compare?  When ptrB - C has signed wraparound on overflow.  Or if you ever have pointers to high-half objects (e.g. into Linux's vDSO pages), a compare between a high-half and low-half address might give you an unexpected result: you will see "high-half" addresses as less than "low-half" addresses.  This happens even though the ptrB - C calculation doesn't wrap.

(We're only talking about asm directly, not C, so there's no UB, I'm just using C notation for sub or lea / cmp / jl.)

Signed wraparound can only happen near the boundary between 0x7FFF... and 0x8000....  But that boundary is extremely far from any canonical address.  I'll reproduce a diagram of x86-64 address space (for current implementations where virtual address are 48 bits) from another answer.  See also Why in 64bit the virtual address are 4 bits short (48bit long) compared with the physical address (52 bit long)?.

Remember, x86-64 faults on non-canonical addresses.  That means it checks that 48-bit virtual address are properly sign-extended to 64 bits, i.e. that bits [63:48] match bit 47 (numbering from 0).

```<code>+----------+
| 2^64-1   |   0xffffffffffffffff
| ...      |                       high half of canonical address range
| 2^64-2^47|   0xffff800000000000
+----------+
|          |
| unusable |   Not to scale: this is 2^15 times larger than the top/bottom ranges.
|          |
+----------+
| 2^47-1   |   0x00007fffffffffff
| ...      |                       low half of canonical range
| 0        |   0x0000000000000000
+----------+
</code>```

Intel has proposed a 5-level page-table extension for 57-bit virtual addresses (i.e. another 9-bit level of tables), but that still leaves most of the address space non-canonical.  i.e. any canonical address would still be 2^63 - 2^57 away from signed wraparound.

Depending on the OS, all your addresses might be in the low half or the high half.  e.g. on x86-64 Linux, high ("negative") addresses are kernel addresses, while low (signed positive) addresses are user-space.  But note that Linux maps the kernel vDSO / vsyscall pages into user space very near the top of virtual address space.  (But it leaves pages unmapped at the top, e.g. ffffffffff600000-ffffffffff601000  [vsyscall] in a 64-bit process on my desktop, but the vDSO pages are near the top of the bottom-half canonical range, 0x00007fff....  Even in a 32-bit process where in theory the whole 4GiB is usable by user-space, the vDSO is a page below the highest page, and mmap(MAP_FIXED) didn't work on that highest page.  Perhaps because C allows one-past-the-end pointers?)

If you ever take the address of a function or variable in the vsyscall page, you can have a mix of positive and negative addresses.  (I don't think anyone ever does that, but it's possible.)

So signed address comparison could be dangerous if you don't have a kernel/user split separating signed positive from signed negative, and your code is running in the distant future when/if x86-64 has been extended to full 64-bit virtual addresses, so an object can span the boundary.  The latter seems unlikely, and if you can get a speedup from assuming it won't happen, it's probably a good idea.

This means signed-compare already is dangerous with 32-bit pointers, because 64-bit kernels leave the whole 4GiB usable by user-space.  (And 32-bit kernels can be configured with a 3:1 kernel/user split).  There's no unusable canonical range.  In 32-bit mode, an object can span the signed-wraparound boundary.  (Or in the ILP32 x32 ABI: 32-bit pointers in long mode.)

Performance advantages:

Unlike 32-bit mode, there are no CPU where jge is faster than jae in 64-bit mode, or other combo.  (And different conditions for setcc / cmovcc never matter).  So any perf diff is only from surrounding code, unless you can do something clever with adc or sbb instead of a cmov or setcc.

Sandybridge-family can macro-fuse test / cmp (and sub, add, and various other non-read-only instructions) with signed or unsigned compares (not all JCC, but this isn't a factor).  Bulldozer-family can fuse cmp / test with any JCC.

Core2 can only macro-fuse cmp with unsigned compares, not signed, but Core2 can't macro-fuse at all in 64-bit mode.  (It can macro-fuse test with signed-compares in 32-bit mode, BTW.)

Nehalem can macro-fuse test or cmp with signed or unsigned compares (including in 64-bit mode).

Source: Agner Fog's microarch pdf.

ContentLicense: CC BY-SA 4.0

Body:
TL:DR: intptr_t might be best in some cases because the signed-overflow boundary is in the middle of the "non-canonical hole".  Treating a value as negative instead of huge may be better if wrapping from zero to 0xFF...FF or vice versa is possible, but pointer+size for any valid size can't wrap a value from INT64_MAX to INT64_MIN.

Otherwise you probably want unsigned for the "high half" (high bit set) to compare as above the low half.

It depends exactly what you want to know about two pointers!

A previous edit of your question gave ptrA < ptrB - C as the use-case you're interested in.  e.g. an overlap check with ptrA < ptrB - sizeA, or maybe an unrolled SIMD loop condition with current < endp - loop_stride.  Discussion in comments has been about this kind of thing, too.

So what you're really doing is forming ptrB - C as a pointer that's potentially outside the object you were interested in, and which may have wrapped around (unsigned).  (Good observation that stuff like this may be why C and C++ make it UB to form pointers outside of objects, but they do allow one-past-the-end which has unsigned wrapping at the end of the highest page, if the kernel even lets you map it.)  Anyway, you want to use a signed comparison so it "still works" without having to check for wraparound, or check the sign of C or any of that stuff.  This is still a lot more specific than most of the question.

Yes, for "related" pointers derived from the same object with reasonable sizes, signed compare is safe on current hardware, and could only break on unlikely / distant-future machines with hardware support for full 64-bit virtual addresses.  Overlap checks are also safe with unsigned if both pointers are in the low half of the canonical range, which I think is the case for user-space addresses on all the mainstream x86-64 OSes.

As you point out, unsigned ptrA < ptrB - C can "fail" if ptrB - C wraps (unsigned wraparound).  This can happen in practice for static addresses that are closer to 0 than the size of C.

Usually the low 64kiB is not mapable (e.g. on Linux, most distros ship with the sysctl vm.mmap_min_addr = 65536, or at least 4096.  But some systems have it =0 for WINE).  Still, I think it's normal for kernels to not give you a zero page unless you request that address specifically, because it stops NULL deref from faulting (which is normally highly desirable for security and debugability reasons).

This means the loop_stride case is usually not a problem.  The sizeA version can usually be done with ptrA + sizeA < ptrB, and as a bonus you can use LEA to add instead of copy + subtract.  ptrA+sizeA is guaranteed not to wrap unless you have objects that wrap their pointer from 2^64-1 to zero (which works even with a page-split load at the wraparound, but you'll never see it in a "normal" system because addresses are normally treated as unsigned.)

So when can it fail with a signed compare?  When ptrB - C has signed wraparound on overflow.  Or if you ever have pointers to high-half objects (e.g. into Linux's vDSO pages), a compare between a high-half and low-half address might give you an unexpected result: you will see "high-half" addresses as less than "low-half" addresses.  This happens even though the ptrB - C calculation doesn't wrap.

(We're only talking about asm directly, not C, so there's no UB, I'm just using C notation for sub or lea / cmp / jl.)

Signed wraparound can only happen near the boundary between 0x7FFF... and 0x8000....  But that boundary is extremely far from any canonical address.  I'll reproduce a diagram of x86-64 address space (for current implementations where virtual address are 48 bits) from another answer.  See also Why in 64bit the virtual address are 4 bits short (48bit long) compared with the physical address (52 bit long)?.

Remember, x86-64 faults on non-canonical addresses.  That means it checks that 48-bit virtual address are properly sign-extended to 64 bits, i.e. that bits [63:48] match bit 47 (numbering from 0).

+----------+
| 2^64-1   |   0xffffffffffffffff
| ...      |                       high half of canonical address range
| 2^64-2^47|   0xffff800000000000
+----------+
|          |
| unusable |   Not to scale: this is 2^15 times larger than the top/bottom ranges.
|          |
+----------+
| 2^47-1   |   0x00007fffffffffff
| ...      |                       low half of canonical range
| 0        |   0x0000000000000000
+----------+

Intel has proposed a 5-level page-table extension for 57-bit virtual addresses (i.e. another 9-bit level of tables), but that still leaves most of the address space non-canonical.  i.e. any canonical address would still be 2^63 - 2^57 away from signed wraparound.

Depending on the OS, all your addresses might be in the low half or the high half.  e.g. on x86-64 Linux, high ("negative") addresses are kernel addresses, while low (signed positive) addresses are user-space.  But note that Linux maps the kernel vDSO / vsyscall pages into user space very near the top of virtual address space.  (But it leaves pages unmapped at the top, e.g. ffffffffff600000-ffffffffff601000  [vsyscall] in a 64-bit process on my desktop, but the vDSO pages are near the top of the bottom-half canonical range, 0x00007fff....  Even in a 32-bit process where in theory the whole 4GiB is usable by user-space, the vDSO is a page below the highest page, and mmap(MAP_FIXED) didn't work on that highest page.  Perhaps because C allows one-past-the-end pointers?)

If you ever take the address of a function or variable in the vsyscall page, you can have a mix of positive and negative addresses.  (I don't think anyone ever does that, but it's possible.)

So signed address comparison could be dangerous if you don't have a kernel/user split separating signed positive from signed negative, and your code is running in the distant future when/if x86-64 has been extended to full 64-bit virtual addresses, so an object can span the boundary.  The latter seems unlikely, and if you can get a speedup from assuming it won't happen, it's probably a good idea.

This means signed-compare already is dangerous with 32-bit pointers, because 64-bit kernels leave the whole 4GiB usable by user-space.  (And 32-bit kernels can be configured with a 3:1 kernel/user split).  There's no unusable canonical range.  In 32-bit mode, an object can span the signed-wraparound boundary.  (Or in the ILP32 x32 ABI: 32-bit pointers in long mode.)

Performance advantages:

Unlike 32-bit mode, there are no CPU where jge is faster than jae in 64-bit mode, or other combo.  (And different conditions for setcc / cmovcc never matter).  So any perf diff is only from surrounding code, unless you can do something clever with adc or sbb instead of a cmov or setcc.

Sandybridge-family can macro-fuse test / cmp (and sub, add, and various other non-read-only instructions) with signed or unsigned compares (not all JCC, but this isn't a factor).  Bulldozer-family can fuse cmp / test with any JCC.

Core2 can only macro-fuse cmp with unsigned compares, not signed, but Core2 can't macro-fuse at all in 64-bit mode.  (It can macro-fuse test with signed-compares in 32-bit mode, BTW.)

Nehalem can macro-fuse test or cmp with signed or unsigned compares (including in 64-bit mode).

Source: Agner Fog's microarch pdf.


问:
Get Request HttpUrlConnection - Incorrect response
I am working on an Android App, App is using GET Request to connect with server.
The code I have written to connect with server is working perfectly on many devices.
But its not giving good response on LENOVO YOGA TAB3, It returns Html tags instead of JSON text, Firstly I was confused that there may be some issue in the API URL but I checked URL using browser, Its returning good response so I am sure URL is correct.

Here are API URL and its response :

API URL

```<code>[http://www.xyz.in/xyzapi/?building=on&address=Assotech Sandal Suites, Sector 135, Noida, Uttar Pradesh 201304, India&bill_amount=12500&type=R&fullstatename=Uttar Pradesh&lat=28.496171099999998&lng=77.4027049&state=UP&country=IN&district=Gautam Buddha Nagar&sublocality=Sector 135&calc-sess=59d4beba305f3&netmetering=1][1]
</code>```

Response on Many Android Phones:

```<code>{"lifetimesaving":"25.0 Lacs","proposed_pv_capacity":10,"billWithSolar":3872,"bill_amount":"12500","sanction":10,"project_cost":"6.0 Lacs","return_oninevstment":"20.8","roi_image":"solar_score6_6.png","treeadded":"346 ","treeofftheroad":"9 "}
</code>```

Response on Lenovo Yoga Tab3:

```<code><head/><style>.personal-details h2{font-size:34px}.netmetering-tgle{position:absolute;left:0;right:0;bottom:5px;width:211px}.netmetering-tgle .wnm{float:left;position:relative;padding:0 10px 0 0;min-width:130px;text-align:center}.netmetering-tgle .wnm a{color:#c97511;background:none}#radioBtn .btn{border:1px solid transparent;border-radius:0!important;font-family:"Din-Bold"}#radioBtn .notActive{color:#c97511;background-color:#e0e1e2;padding:2px 0;width:38px;background-size:100% 100%;border-color:transparent;font-family:"Din-Bold";border-radius:5px}#radioBtn .active{color:#fff;background-color:#addc6f;border-color:transparent;padding:2px 5px;width:38px;cursor:auto;pointer-events:none;border-radius:5px;box-shadow:inset 0 0 10px rgba(0,0,0,.8)}#radioBtn .notActive[data-
</code>```

So response is incorrect on Yoga Tab3.

Here is the code I am using to connect with Server :

```<code>    public static String connectToServerUsingGETMethod(String API_COMPLETE_URL){

    URL url;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(API_COMPLETE_URL);

        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = urlConnection.getInputStream();

        InputStreamReader isr = new InputStreamReader(in);

        String line = "";
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        //get the string version of the response data
        return sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    return "";
}
</code>```

Suggest me If I can add something in this code so that it can work on Yoga Tab 3 too.

答:
I think you should set static content type when making request to make sure the response sent back is JSON. Similarly, it looks like below:

```<code>HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
</code>```

Hope it works for you.

Body:
I am working on an Android App, App is using GET Request to connect with server.
The code I have written to connect with server is working perfectly on many devices.
But its not giving good response on LENOVO YOGA TAB3, It returns Html tags instead of JSON text, Firstly I was confused that there may be some issue in the API URL but I checked URL using browser, Its returning good response so I am sure URL is correct.

Here are API URL and its response :

API URL

[http://www.xyz.in/xyzapi/?building=on&address=Assotech Sandal Suites, Sector 135, Noida, Uttar Pradesh 201304, India&bill_amount=12500&type=R&fullstatename=Uttar Pradesh&lat=28.496171099999998&lng=77.4027049&state=UP&country=IN&district=Gautam Buddha Nagar&sublocality=Sector 135&calc-sess=59d4beba305f3&netmetering=1][1]

Response on Many Android Phones:

{"lifetimesaving":"25.0 Lacs","proposed_pv_capacity":10,"billWithSolar":3872,"bill_amount":"12500","sanction":10,"project_cost":"6.0 Lacs","return_oninevstment":"20.8","roi_image":"solar_score6_6.png","treeadded":"346 ","treeofftheroad":"9 "}

Response on Lenovo Yoga Tab3:

Body:
I think you should set static content type when making request to make sure the response sent back is JSON. Similarly, it looks like below:

HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

Hope it works for you.


问:
adjust AppCompatEditText style
I have a CustomEditText extends EmojiEditText which extends AppCompatEditText and deriving https://github.com/vanniktech/Emoji library.

I used to ComposeEditText style for CustomEditText. But if I add this style, app is crashing. Please help me.

My edittext style:

```<code>        <style name="ComposeEditText" parent="@style/Widget.AppCompat.EditText">
        <item name="android:padding">2dp</item>
        <item name="android:background">@null</item>
        <item name="android:maxLines">4</item>
        <item name="android:maxLength">2000</item>
        <item name="android:capitalize">sentences</item>
        <item name="android:autoText">true</item>
        <item name="android:gravity">center_vertical</item>
        <item name="android:imeOptions">flagNoEnterAction</item>
        <item name="android:inputType">textAutoCorrect|textCapSentences|textMultiLine</item>
        </style>
</code>```

My edittext in xml:

```<code>         <com.android.android.util.view.CustomEditText
            android:id="@+id/editText"
            style="@style/ComposeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            app:emojiSize="@dimen/emojiSize" />
</code>```

in code:

```<code>public class CustomEditText extends EmojiEditText {

    public CustomEditText(Context context) {
        super(context);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
}
</code>```

Error log:

```<code>    java.lang.RuntimeException: Unable to start activity
        ComponentInfo{com.android.android/com.android.android.conversation.a.PRofile}:
    android.view.InflateException: Binary XML file line #0:
       Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: java.lang.reflect.InvocationTargetException
</code>```

答: Seeing your CustomEditText which is EmojiEditText, please try to set the parent of your style to EmojiEditText's style. I think the issue is your style is inheriting from wrong style

Title: adjust AppCompatEditText style

Body:
I have a CustomEditText extends EmojiEditText which extends AppCompatEditText and deriving https://github.com/vanniktech/Emoji library.

I used to ComposeEditText style for CustomEditText. But if I add this style, app is crashing. Please help me.

My edittext style:

My edittext in xml:

         <com.android.android.util.view.CustomEditText
            android:id="@+id/editText"
            style="@style/ComposeEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            app:emojiSize="@dimen/emojiSize" />

in code:

public class CustomEditText extends EmojiEditText {

    public CustomEditText(Context context) {
        super(context);
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
}

Error log:

    java.lang.RuntimeException: Unable to start activity
        ComponentInfo{com.android.android/com.android.android.conversation.a.PRofile}:
    android.view.InflateException: Binary XML file line #0:
       Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
                                                                                at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class com.android.android.util.view.CustomEditText
                                                                              Caused by: java.lang.reflect.InvocationTargetException


问:
Form validation in spring with thymeleaf
I'm skilling in form validation with spring boot and thymeleaf and i have problem: i can't do validation in form with two @ModelAttribute fields. The example like form validation om spring official site works correctly, but when I added two @model Attribute in post i get only error at webpage and no hints at form like in spring example.

Controller class:

```<code>@Controller
public class MyController {

    @Autowired
    InstructorRepository instructorRepository;

    @Autowired
    DetailRepository detailRepository;

    @GetMapping("/index")
    public String mainController(){
        return "index";
    }

    @GetMapping("/add")
    public String addInstructorForm(Model model){
        model.addAttribute("instructor", new Instructor());
        model.addAttribute("detail", new InstructorDetail());
        return "addInstructor";
    }

    @PostMapping("/add")
    public String submitForm(@Valid @ModelAttribute Instructor instructor, @ModelAttribute InstructorDetail instructorDetail, BindingResult bindingResult1){
       /* if (bindingResult.hasErrors()) {
            return "instructorsList";
        }
        instructor.setInstructorDetail(instructorDetail);
        instructorRepository.save(instructor);*/

        if (bindingResult1.hasErrors()) {
            return "addInstructor";
        }
        return "redirect:/instructorsList";
    }

    @GetMapping("/instructorsList")
    public String getList(Model model){
        Map map = new HashMap<>();
        List list = new ArrayList<Instructor>();
        list = instructorRepository.findAll();
        List resultList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Instructor instructor = (Instructor)list.get(i);
            InstructorDetail detail = detailRepository.getInstructorDetailById(instructor.getId());
            InstructorAndDetail iid = new InstructorAndDetail(instructor, detail);
            resultList.add(iid);
        }
        model.addAttribute("instructors", resultList);
        return "instructorsList";
    }

}
</code>```

html form snippet:

```<code><form action="#" data-th-action="@{/add}" data-th-object="${instructor}" method="post">
   <div class="form-group">
        <label for="1">First name</label>
        <input class="form-control" id="1" type="text" data-th-field="${instructor.firstName}" placeholder="John"/>
        <div data-th-if="${#fields.hasErrors('firstName')}" data-th-errors="${instructor.firstName}">name error</div>
   </div>
</code>```

答:
There was next problem: then I add entity to thymeleaf form I passed only 2 fields (or one field after), but there was 3 fields with

```<code>@NotNull
@Size(min=2, max=30)
</code>```

So when I commented them in my code the single field validation begin to work :).
 If you stucked at the same problem check that all you fields in class that marked @Valid annotation are mirrored in your form.
(or have default valid values? UPD: dont work with valid defaults if they have no form mirroring)

Body:
I'm skilling in form validation with spring boot and thymeleaf and i have problem: i can't do validation in form with two @ModelAttribute fields. The example like form validation om spring official site works correctly, but when I added two @model Attribute in post i get only error at webpage and no hints at form like in spring example.

Controller class:

@Controller
public class MyController {

    @Autowired
    InstructorRepository instructorRepository;

    @Autowired
    DetailRepository detailRepository;

    @GetMapping("/index")
    public String mainController(){
        return "index";
    }

    @GetMapping("/add")
    public String addInstructorForm(Model model){
        model.addAttribute("instructor", new Instructor());
        model.addAttribute("detail", new InstructorDetail());
        return "addInstructor";
    }

    @PostMapping("/add")
    public String submitForm(@Valid @ModelAttribute Instructor instructor, @ModelAttribute InstructorDetail instructorDetail, BindingResult bindingResult1){
       /* if (bindingResult.hasErrors()) {
            return "instructorsList";
        }
        instructor.setInstructorDetail(instructorDetail);
        instructorRepository.save(instructor);*/

        if (bindingResult1.hasErrors()) {
            return "addInstructor";
        }
        return "redirect:/instructorsList";
    }

    @GetMapping("/instructorsList")
    public String getList(Model model){
        Map map = new HashMap<>();
        List list = new ArrayList<Instructor>();
        list = instructorRepository.findAll();
        List resultList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Instructor instructor = (Instructor)list.get(i);
            InstructorDetail detail = detailRepository.getInstructorDetailById(instructor.getId());
            InstructorAndDetail iid = new InstructorAndDetail(instructor, detail);
            resultList.add(iid);
        }
        model.addAttribute("instructors", resultList);
        return "instructorsList";
    }

}

html form snippet:

<form action="#" data-th-action="@{/add}" data-th-object="${instructor}" method="post">

        First name
        <input class="form-control" id="1" type="text" data-th-field="${instructor.firstName}" placeholder="John"/>

name error

Body:
There was next problem: then I add entity to thymeleaf form I passed only 2 fields (or one field after), but there was 3 fields with

@NotNull
@Size(min=2, max=30)

So when I commented them in my code the single field validation begin to work :).
 If you stucked at the same problem check that all you fields in class that marked @Valid annotation are mirrored in your form.
(or have default valid values? UPD: dont work with valid defaults if they have no form mirroring)


问:
Python: ValueError: invalid literal for int() with base 10: '"'
I'm creating code to get the average score in a CSV file.

CSV file looks like this:

```<code>5 Ser15

4 Ser15

3 Ser15
</code>```

1st column are the scores, the second are the usernames.

This is my code so far:

```<code>   def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        for row in f:
            column = row.split(',')
            i=(int(column[0]))
            Sum += i
            row_count += 1
        average = Sum / row_count
        return 'The average is:', average
  av()
</code>```

But this error appears...

```<code>  i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'
</code>```

When I print the whole row to check, this appears:

```<code>def av():
with open("SciMedreport.csv","r") as f:
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        print(row)
av()
</code>```

This is the result:

```<code>5,Ser15
""

5,Ser15

""

4,Ser15
</code>```

Anyone know of a way to fix this, or an alternative way to work out the average??

答:
```<code>def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        divisor = 0
        for row in f:
            row_count += 1
            if row_count%2 == 0: # if it doesn't work, try changing to 1
                # print(row.split(','))
                divisor += 1
                # write rest of the code here, Sum += i etc.
                columns_list = row.split(',')
                i = int(columns_list[0])
                Sum += i
        average = Sum / divisor
</code>```

Thank you to user3903448!

Body:
I'm creating code to get the average score in a CSV file.

CSV file looks like this:

5 Ser15

4 Ser15

3 Ser15

1st column are the scores, the second are the usernames.

This is my code so far:

   def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        for row in f:
            column = row.split(',')
            i=(int(column[0]))
            Sum += i
            row_count += 1
        average = Sum / row_count
        return 'The average is:', average
  av()

But this error appears...

  i=int(column[0])
ValueError: invalid literal for int() with base 10: '"'

When I print the whole row to check, this appears:

def av():
with open("SciMedreport.csv","r") as f:
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        print(row)
av()

This is the result:

5,Ser15
""

5,Ser15

""

4,Ser15

Anyone know of a way to fix this, or an alternative way to work out the average??

Body:
def av():
    with open("SciMedreport.csv","r") as f:
        average = 0
        Sum = 0
        row_count = 0
        divisor = 0
        for row in f:
            row_count += 1
            if row_count%2 == 0: # if it doesn't work, try changing to 1
                # print(row.split(','))
                divisor += 1
                # write rest of the code here, Sum += i etc.
                columns_list = row.split(',')
                i = int(columns_list[0])
                Sum += i
        average = Sum / divisor

Thank you to user3903448!


问:
How to hide or disable buttons?
In my project I have two buttons called sign-in and sign-up button on my header.

What I want to achieve is,after successful sign-in i want to disable sign-in button and hide sign-up button.

答: You can use to *ngIf="isLoggedIn" to hide any component</p>

Title: How to hide or disable buttons?


问:
Is there a way to override inline CSS for `overflow`?
If I want override inline css i must use !important or javascript.

But if I want to override, for example, inline width without important I can use max-width or min-width

Is there some way to override inline

```<code>  overflow:hidden
</code>```

答:
You can override the inline style using !important keyword

.overwrite_css{
  background-color: blue !important;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="overwrite_css" style="background-color: red;font-size: 25px;">
 <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
</h2>
</div></code>```

Still not able to override it then try this one

Note: Using !important ONLY will work here, but I've used  overwrite_css[style]
  selector to specifically select div having style attribute

The example uses [style] (the attribute selector) to show us that the CSS is targetting the div with the “style” attribute.

.overwrite_css[style]{
  background-color: blue !important;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="overwrite_css" style="background-color: red;font-size: 25px;">
 <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
</h2>
</div></code>```

Body:
If I want override inline css i must use !important or javascript.

But if I want to override, for example, inline width without important I can use max-width or min-width

Is there some way to override inline

  overflow:hidden

Body:
You can override the inline style using !important keyword

.overwrite_css{
  background-color: blue !important;
 }

<div class="overwrite_css" style="background-color: red;font-size: 25px;">
 <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
</h2>
</div>

Still not able to override it then try this one

Note: Using !important ONLY will work here, but I've used  overwrite_css[style]
  selector to specifically select div having style attribute

The example uses [style] (the attribute selector) to show us that the CSS is targetting the div with the “style” attribute.

.overwrite_css[style]{
  background-color: blue !important;
 }

<div class="overwrite_css" style="background-color: red;font-size: 25px;">
 <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
</h2>
</div>


问:
Setting the value of an unsigned char * in c++
I've got a function that takes an unsigned char * as a parameter, but the data I'm being sent is throwing a type mismatch error.

```<code>int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

void addByteToQueue (Queue * queue, unsigned char * byte)
  {
  // stuff
  }
</code>```

Visual studio is counting the 1/2/3 in the function calls as integers, which makes sense to me.  As a test, I also tried doing this:

```<code>unsigned char * a = 1;
</code>```

Similar error.  Now, I can't change the function prototype.  Assuming I'm being sent bad data in the call, how would one go about assigning the value of an unsigned char pointer?  Alternatively, is there some other crucial thing I'm missing that would make this work the way it is?

答:
I don't think you're using that how it's intended.

Try something like this

```<code>int main()
{
  Queue * queue = newQueue ();
  unsigned char data[] = { 1, 2, 3 };
  for (auto&& byte : data)
  {
      addByteToQueue (queue, &byte);
  }
  return 0;
}

void addByteToQueue (Queue * queue, unsigned char *)
{
  // stuff
}
</code>```

Basically, the char* wants to be pointing into some data blob. You can't pass literals into a function that takes pointers directly.

Body:
I've got a function that takes an unsigned char * as a parameter, but the data I'm being sent is throwing a type mismatch error.

int main()
  {
  Queue * queue = newQueue ();
  addByteToQueue (queue, 1);
  addByteToQueue (queue, 2);
  addByteToQueue (queue, 3);
  return 0;
  }

void addByteToQueue (Queue * queue, unsigned char * byte)
  {
  // stuff
  }

Visual studio is counting the 1/2/3 in the function calls as integers, which makes sense to me.  As a test, I also tried doing this:

unsigned char * a = 1;

Similar error.  Now, I can't change the function prototype.  Assuming I'm being sent bad data in the call, how would one go about assigning the value of an unsigned char pointer?  Alternatively, is there some other crucial thing I'm missing that would make this work the way it is?

Body:
I don't think you're using that how it's intended.

Try something like this

int main()
{
  Queue * queue = newQueue ();
  unsigned char data[] = { 1, 2, 3 };
  for (auto&& byte : data)
  {
      addByteToQueue (queue, &byte);
  }
  return 0;
}

void addByteToQueue (Queue * queue, unsigned char *)
{
  // stuff
}

Basically, the char* wants to be pointing into some data blob. You can't pass literals into a function that takes pointers directly.


问:
Linq with optional WHERE options
I have a .Net function that accepts 3 parameters, all optional. Something like this:

```<code>public List<MyObject> Search(string colour, string size, string name)
{
     var result = (from c in MyTable where .... select c).ToList();
}
</code>```

My question is, what is the best way to do the where part. Would the best be to create dynamic linq? What's the best pattern, within linq, to have optional where parameters?

So, in SQL, something like this:

```<code>SELECT *
FROM MyTable
WHERE (@colour <> '' AND colour = @colour)
  AND (@size <> '' AND size = @size)
  AND (@name <> '' AND name = @name)
</code>```

But I am hoping there a neater, more acceptable pattern for doing this within linq.

答:
Here you have 1 query with all conditions:</p>

```<code>public List<object> Search(string colour, string size, string name)
{
    var query = from c in MyTable
        where
            (string.IsNullOrEmpty(colour) || c.colour == colour) &&
            (string.IsNullOrEmpty(size) || c.size == size) &&
            (string.IsNullOrEmpty(name) || c.name == name)
        select c;

    return query.ToList();
}
</code>```

Title: Linq with optional WHERE options

Body:
I have a .Net function that accepts 3 parameters, all optional. Something like this:

public List<MyObject> Search(string colour, string size, string name)
{
     var result = (from c in MyTable where .... select c).ToList();
}

My question is, what is the best way to do the where part. Would the best be to create dynamic linq? What's the best pattern, within linq, to have optional where parameters?

So, in SQL, something like this:

SELECT *
FROM MyTable
WHERE (@colour <> '' AND colour = @colour)
  AND (@size <> '' AND size = @size)
  AND (@name <> '' AND name = @name)

But I am hoping there a neater, more acceptable pattern for doing this within linq.

Body:
Here you have 1 query with all conditions:

public List<object> Search(string colour, string size, string name)
{
    var query = from c in MyTable
        where
            (string.IsNullOrEmpty(colour) || c.colour == colour) &&
            (string.IsNullOrEmpty(size) || c.size == size) &&
            (string.IsNullOrEmpty(name) || c.name == name)
        select c;

    return query.ToList();
}


问:
responseData gives an error ReactNative
```<code>fetch(loginApi, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    Password: password,
    UserName: username
  })
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData); //// <--- getting error at this line
  })
  .catch(error => {
    console.error(error);
  });
</code>```

enter image description here

Any idea how to solve it??? Thanks in advance.

答:
maybe response data is not in json format try this</p>

```<code>fetch(loginApi, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    Password: password,
    UserName: username
  })
}).then((e)=>{
 console.log(e) //see what you get, if promise then use another then
})
</code>```

Title: responseData gives an error ReactNative

Body:
fetch(loginApi, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    Password: password,
    UserName: username
  })
})
  .then(response => response.json())
  .then(responseData => {
    console.log(responseData); //// <--- getting error at this line
  })
  .catch(error => {
    console.error(error);
  });

enter image description here

Any idea how to solve it??? Thanks in advance.

Body:
maybe response data is not in json format try this

fetch(loginApi, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    Password: password,
    UserName: username
  })
}).then((e)=>{
 console.log(e) //see what you get, if promise then use another then
})


问:
How to get the above input value when changing another input
I have two inputs those are bootstrap time pickers from time and to time, when i change the end time i need to get the start time.

Here from time and to time will be there in one row for the first time and next onwards when click on add new destination those will be dynamically append to the first row

Here I have to get the From Time and To Time when i change the To Time

I have tried below

```<code>$(document).on('change','.departure_time_picker',function(){

  var departure_time  = $(this).val();
  var arrival_time    = $(this).prev().find('input.arrival_time_picker');
  console.log(arrival_time);
});
</code>```

My inputs are

```<code><div class="col-md-3" style="padding-left:5px;padding-right:5px;">
   <label>From Time</label>
   <div class="form-group">
      <div class="input-group bootstrap-timepicker timepicker arrival_time">
           <input name="wayPoints[0][arrival_time]" type="text" class="form-control input-small arrival_time_picker">
           <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
      </div>
   </div>
 </div>
 <div class="col-md-3" style="padding-left:5px;padding-right:5px;">
     <label>To Time</label>
     <div class="form-group">
        <div class="input-group bootstrap-timepicker timepicker departure_time">
             <input name="wayPoints[0][departure_time]" type="text" class="form-control input-small departure_time_picker">
             <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
        </div>
     </div>
  </div>
</code>```

When i'm trying to get the Start Time when changing the To Time im getting as 'undefined'.
Please suggest me where i'm doing wrong.

答:
With prev() you'll find the previous sibling (so, on the same level as that element). It won't search up the tree for parents. So you need to understand how jQuery works.

Your DOM tree looks like this

```<code>col-md-3
|
|---label
|---.form-group
|  |
|  |--.input-group
|    |
|    |---.arrival_time_picker
|
|
col-md-3
|
|---label
|---.form-group
   |
   |---.input-group
     |
     |---.departure_time_picker
</code>```

You can move up the tree, but you can't move up and then search inside a sibling, at least, not with just one function,

So first, you need to get up in the tree, by using

```<code>.closest('.col-md-3')
</code>```

This finds the parent element of .departure_time_picker.

Then you can find the previous sibling (on the same level)

```<code>.prev()
/* or */
.prev('.col-md-3')
</code>```

And then you can look inside that element for the element you are looking for:

```<code>.find('.arrival_time_picker')
</code>```

All together:

$(document).on('change','.departure_time_picker',function(){

  var departure_time  = $(this).val();
  var arrival_time    = $(this).closest('.col-md-3').prev().find('.arrival_time_picker').val();
  console.log( arrival_time );

}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3" style="padding-left:5px;padding-right:5px;">
   <label>From Time</label>
   <div class="form-group">
      <div class="input-group bootstrap-timepicker timepicker arrival_time">
           <input name="wayPoints[0][arrival_time]" type="text" class="form-control input-small arrival_time_picker">
           <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
      </div>
   </div>
 </div>
 <div class="col-md-3" style="padding-left:5px;padding-right:5px;">
     <label>To Time</label>
     <div class="form-group">
        <div class="input-group bootstrap-timepicker timepicker departure_time">
             <input name="wayPoints[0][departure_time]" type="text" class="form-control input-small departure_time_picker">
             <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
        </div>
     </div>
  </div></code>```

Body:
I have two inputs those are bootstrap time pickers from time and to time, when i change the end time i need to get the start time.

Here from time and to time will be there in one row for the first time and next onwards when click on add new destination those will be dynamically append to the first row

Here I have to get the From Time and To Time when i change the To Time

I have tried below

$(document).on('change','.departure_time_picker',function(){

  var departure_time  = $(this).val();
  var arrival_time    = $(this).prev().find('input.arrival_time_picker');
  console.log(arrival_time);
});

My inputs are

   From Time

           <input name="wayPoints[0][arrival_time]" type="text" class="form-control input-small arrival_time_picker">

     To Time

             <input name="wayPoints[0][departure_time]" type="text" class="form-control input-small departure_time_picker">

When i'm trying to get the Start Time when changing the To Time im getting as 'undefined'.
Please suggest me where i'm doing wrong.

Body:
With prev() you'll find the previous sibling (so, on the same level as that element). It won't search up the tree for parents. So you need to understand how jQuery works.

Your DOM tree looks like this

col-md-3
|
|---label
|---.form-group
|  |
|  |--.input-group
|    |
|    |---.arrival_time_picker
|
|
col-md-3
|
|---label
|---.form-group
   |
   |---.input-group
     |
     |---.departure_time_picker

You can move up the tree, but you can't move up and then search inside a sibling, at least, not with just one function,

So first, you need to get up in the tree, by using

.closest('.col-md-3')

This finds the parent element of .departure_time_picker.

Then you can find the previous sibling (on the same level)

.prev()
/* or */
.prev('.col-md-3')

And then you can look inside that element for the element you are looking for:

.find('.arrival_time_picker')

All together:

$(document).on('change','.departure_time_picker',function(){

  var departure_time  = $(this).val();
  var arrival_time    = $(this).closest('.col-md-3').prev().find('.arrival_time_picker').val();
  console.log( arrival_time );

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3" style="padding-left:5px;padding-right:5px;">
   <label>From Time</label>
   <div class="form-group">
      <div class="input-group bootstrap-timepicker timepicker arrival_time">
           <input name="wayPoints[0][arrival_time]" type="text" class="form-control input-small arrival_time_picker">
           <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
      </div>
   </div>
 </div>
 <div class="col-md-3" style="padding-left:5px;padding-right:5px;">
     <label>To Time</label>
     <div class="form-group">
        <div class="input-group bootstrap-timepicker timepicker departure_time">
             <input name="wayPoints[0][departure_time]" type="text" class="form-control input-small departure_time_picker">
             <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
        </div>
     </div>
  </div>


问:
Find href attributes with find_elements_by_class_name in Selenium with Python
Using Selenium with Python.

I've got pages full of links with a class called item-title. I'm trying to iterate through the pages and compile a list of all the link texts and the href attributes that go with them. I want to output the titles and links to a csv file.  Here is my code:

```<code>myLinks=driver.find_elements_by_class_name("item-title")
for link in myLinks:
    out.write(link.text)
    out.write (",")
    out.write(link.get_attribute("href"))
    out.write("\n")
</code>```

The line that outputs the href value gives the following error:

TypeError: expected a character buffer object

Tried the following:

```<code>myLinks=driver.find_elements_by_class_name("item-title")
for link in myLinks:
    out.write(link.text)
    out.write (",")
    out.write(str(link.get_attribute("href")))
    out.write("\n")
</code>```

Error went away, link text is coming through okay, but now the href is coming through as 'None'

Edit to add the HTML

```<code><div class="item-title">
    <span class="icons-pinned"></span>
    <span class="icons-solved"></span>
    <span class="icons-locked"></span>
    <span class="icons-moved"></span>
    <span class="icons-type"></span>
    <span class="icons-reply"></span>
    <a href="/mylink">My title</a>
</div>
</code>```

I think I see the issue now. The  is a child element of the div, I need to target that, don't I?

答:
As per the HTML you have shared, the link texts and the href attributes are not within the node identified as find_elements_by_class_name("item-title"). Rather they are within the decendent  tag. Hence instead of using find_elements_by_class_name("item-title") we have to use either find_elements_by_xpath or find_elements_by_css_selector as follows :

Using find_elements_by_css_selector :

```<code>myLinks=driver.find_elements_by_css_selector("div.item-title > a")
for link in myLinks:
    out.write(link.get_attribute("innerHTML"))
    out.write (",")
    out.write(link.get_attribute("href"))
    out.write("\n")
</code>```

Using find_elements_by_xpath :

```<code>myLinks=driver.find_elements_by_xpath("//div[@class='item-title']/a")
for link in myLinks:
    out.write(link.get_attribute("innerHTML"))
    out.write (",")
    out.write(link.get_attribute("href"))
    out.write("\n")
</code>```

Body:
Using Selenium with Python.

I've got pages full of links with a class called item-title. I'm trying to iterate through the pages and compile a list of all the link texts and the href attributes that go with them. I want to output the titles and links to a csv file.  Here is my code:

myLinks=driver.find_elements_by_class_name("item-title")
for link in myLinks:
    out.write(link.text)
    out.write (",")
    out.write(link.get_attribute("href"))
    out.write("\n")

The line that outputs the href value gives the following error:

TypeError: expected a character buffer object

Tried the following:

myLinks=driver.find_elements_by_class_name("item-title")
for link in myLinks:
    out.write(link.text)
    out.write (",")
    out.write(str(link.get_attribute("href")))
    out.write("\n")

Error went away, link text is coming through okay, but now the href is coming through as 'None'

Edit to add the HTML

    My title

I think I see the issue now. The  is a child element of the div, I need to target that, don't I?

Body:
As per the HTML you have shared, the link texts and the href attributes are not within the node identified as find_elements_by_class_name("item-title"). Rather they are within the decendent <a> tag. Hence instead of using find_elements_by_class_name("item-title") we have to use either find_elements_by_xpath or find_elements_by_css_selector as follows :

Using find_elements_by_css_selector :

myLinks=driver.find_elements_by_css_selector("div.item-title > a")
for link in myLinks:
    out.write(link.get_attribute("innerHTML"))
    out.write (",")
    out.write(link.get_attribute("href"))
    out.write("\n")

Using find_elements_by_xpath :

myLinks=driver.find_elements_by_xpath("//div[@class='item-title']/a")
for link in myLinks:
    out.write(link.get_attribute("innerHTML"))
    out.write (",")
    out.write(link.get_attribute("href"))
    out.write("\n")


问:
Getting attributes from XML using c#
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

```<code>  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>
</code>```

Anyone please suggest some ideas to find this.
my expected output is like

```<code>   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com
</code>```

答:
To achieve the required output you can use XMLDocument , XMLNode and XMLNodeList as follows</p>

```<code>string sb = "<query xmlns=\"http://jabber.org/protocol/muc#admin\">" +
                         "  <item affiliation=\"member\" jid=\"a@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"b@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"c@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"d@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"e@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"f@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"g@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"h@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"i@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"j@something.com\" />" +
                         "  </query>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sb);

            XmlNodeList allXmlNode = doc.GetElementsByTagName("item");
            if (allXmlNode.Count >= 1)
            {
                foreach (XmlNode node in allXmlNode)
                {
                    System.Console.WriteLine(node.Attributes[1].InnerText);
                }
            }
</code>```

Title: Getting attributes from XML using c#

Body:
I have the following xml contents inside a string variable. i want to get the value of each attribute (JID) in the form of string.

Below is my xml

  <query xmlns="http://jabber.org/protocol/muc#admin">
  <item affiliation="member" jid="a@something.com" />
  <item affiliation="member" jid="b@something.com" />
  <item affiliation="member" jid="c@something.com" />
  <item affiliation="member" jid="d@something.com" />
  <item affiliation="member" jid="e@something.com" />
  <item affiliation="member" jid="f@something.com" />
  <item affiliation="member" jid="g@something.com" />
  <item affiliation="member" jid="h@something.com" />
  <item affiliation="member" jid="i@something.com" />
  <item affiliation="member" jid="j@something.com" />
  </query>

Anyone please suggest some ideas to find this.
my expected output is like

   a@something.com
   b@something.com
   c@something.com
   d@something.com
   e@something.com
   f@something.com

Body:
To achieve the required output you can use XMLDocument , XMLNode and XMLNodeList as follows

string sb = "<query xmlns=\"http://jabber.org/protocol/muc#admin\">" +
                         "  <item affiliation=\"member\" jid=\"a@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"b@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"c@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"d@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"e@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"f@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"g@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"h@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"i@something.com\" />" +
                         "  <item affiliation=\"member\" jid=\"j@something.com\" />" +
                         "  </query>";

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sb);

            XmlNodeList allXmlNode = doc.GetElementsByTagName("item");
            if (allXmlNode.Count >= 1)
            {
                foreach (XmlNode node in allXmlNode)
                {
                    System.Console.WriteLine(node.Attributes[1].InnerText);
                }
            }


问:
Add filter for user email on Zimbra server
I want to add a filter, based on regural expression, for body message for user on my Zimbra email server.

If the filter is triggered, email must be forward on specific address.

For example:

```<code>regex: /[0-9]/
User: test_user
Specific address: test_address@zimbra.com
</code>```

答:
Regular expressions aren't supported, but you can use filespec-style wildcards like "?" for one character and "*" for zero or more characters.

Check this zimbra community forums

Body:
I want to add a filter, based on regural expression, for body message for user on my Zimbra email server.

If the filter is triggered, email must be forward on specific address.

For example:

regex: /[0-9]/
User: test_user
Specific address: test_address@zimbra.com


问:
Passing UI objects as Constructor Parameters
public ContactsPanel(Activity activity,GoogleMap mGoogleMap)

I have a Class with this Constructor. This class basically inflates a UI on "activity" with Marker details when a marker is clicked on mGoogleMaps. My questions for the community are:

If I am creating 1st instance of ContactsPanel then am I forcing OS to duplicate memory allocation for the objects activity and mGoogleMap?

And what if I have 10 instances of ContactsPanel? Will that mean 10 Google Maps in memory and 10 Activities in memory? Or will all the objects will be referring to same object, that was originally created?

Thanks!

答:
you can pass activity and map in your constructor it will just pass the reference, it will not going to duplicate any of the object.

So you can say all the object reference to same object.


问:
C++ Iterator declare from typedef std::map as template argument
How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

```<code>template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}
</code>```

答:
```<code>typename Container::iterator iter = ...;
</code>```

The compiler defaults to seeing template members as variables, if it's a type you have to say so with "typename".

Body:
How can I declare an iterator for template argument map?

I know I could pass it as argument from main function as another template argument, but if I don't, how can I declare it?

template< typename container >
int print_data( container map )
{
    map::iterator iter; // this is wrong
    return 0;
}

int main()
{
    typedef std::map< int, double > Map;
    Map new_map;

    print_data< Map >( new_map );
}

Body:
typename Container::iterator iter = ...;

The compiler defaults to seeing template members as variables, if it's a type you have to say so with "typename".


问:
Solve Linear equation with variables in JavaScript
I am trying to use JavaScript to solve the linear equation with variables.

So my try is this:

```<code>            var CE = parseFloat(document.getElementById("CE").value)
            var CF = parseFloat(document.getElementById("CF").value)
            var EF = parseFloat(document.getElementById("EF").value)
            var x1=algebra.parse("CE^2+2*EF*x-EF^2");
            var x2=algebra.parse("CF^2");
            var eq= new Equation(x1,x2);

            var h=eq.solveFor("x");
</code>```

I know I should not put the valuable in "" mark, but I do not know where I should put them.

Please help me. Thank you!

答:
You can use template String in ES-6 to simplify writing these complicated string.</p>

```<code>var x1=algebra.parse(`${CE}^2+2*${EF}*x-${EF}^2`);
var x2=algebra.parse(`${CF}^2`);
var eq= new Equation(x1,x2);
var h=eq.solveFor("x");
</code>```

Body:
I am trying to use JavaScript to solve the linear equation with variables.

So my try is this:

            var CE = parseFloat(document.getElementById("CE").value)
            var CF = parseFloat(document.getElementById("CF").value)
            var EF = parseFloat(document.getElementById("EF").value)
            var x1=algebra.parse("CE^2+2*EF*x-EF^2");
            var x2=algebra.parse("CF^2");
            var eq= new Equation(x1,x2);

            var h=eq.solveFor("x");

I know I should not put the valuable in "" mark, but I do not know where I should put them.

Please help me. Thank you!

Body:
You can use template String in ES-6 to simplify writing these complicated string.

var x1=algebra.parse(`${CE}^2+2*${EF}*x-${EF}^2`);
var x2=algebra.parse(`${CF}^2`);
var eq= new Equation(x1,x2);
var h=eq.solveFor("x");


问:
Instant App, What's the actual minimum sdk
As per the android developers site, minimum sdk for Instant app is 21, ie 5.0.
link

The site clearly  states : Android Instant Apps are available on the majority of devices running Android 5.0 (API level 21) and higher.

But when we create a new project as per the guideline given in this link
which states that we need to have minimum sdk of 23, to get instant app support.

And does not allow me to create a support for 5.0.

as shown in below image which I tried :

答:
That requirement might be due to android run-time permission support  Requesting Permissions at Run Time as official document mention

Note: Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level. You should test your app to verify that it behaves properly when it's missing a needed permission, regardless of what API level your app targets.

Currently it has been fixed with android studio 3.1 Canary 5


问:
How do I change background colour programmatically in swift using SpriteKit
I have this game and I have a function for when each different game mode is called, I want to change the colour of the background when a mode is clicked, but when I do It nothing happens. Could you please tell me how to do it, Thanks</p>

```<code>override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    switch currentGameType {
    case .easy:
        enemy.run(SKAction.moveTo(x: ball.position.x, duration: 1.3))
        break
    case .medium:
        enemy.run(SKAction.moveTo(x: ball.position.x, duration: 1.0))
        self.view?.backgroundColor = UIColor.white //I TRY IT HERE
        break
    case .hard:
        enemy.run(SKAction.moveTo(x: ball.position.x, duration: 0.7))
        break
    case .player2:

        break
    }
</code>```

答:
Your scene's background has nothing to do with the view's background.

You should set the scene's background color instead. The scene, in this case, is self:

```<code>self.backgroundColor = .white
</code>```

However, if you want to use an image for the background, you need to add a new node covering the whole scene and set the texture of the node to be your image.

Body:
I have this game and I have a function for when each different game mode is called, I want to change the colour of the background when a mode is clicked, but when I do It nothing happens. Could you please tell me how to do it, Thanks

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    switch currentGameType {
    case .easy:
        enemy.run(SKAction.moveTo(x: ball.position.x, duration: 1.3))
        break
    case .medium:
        enemy.run(SKAction.moveTo(x: ball.position.x, duration: 1.0))
        self.view?.backgroundColor = UIColor.white //I TRY IT HERE
        break
    case .hard:
        enemy.run(SKAction.moveTo(x: ball.position.x, duration: 0.7))
        break
    case .player2:

        break
    }

Body:
Your scene's background has nothing to do with the view's background.

You should set the scene's background color instead. The scene, in this case, is self:

self.backgroundColor = .white

However, if you want to use an image for the background, you need to add a new node covering the whole scene and set the texture of the node to be your image.


问:
date time format null values return default time in PHP
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

```<code>  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format
</code>```

. when i print this column it returns like this

```<code>payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40
</code>```

but i need to return as NULL not default time format.

答:
This code is just to give you an idea. I can help you precisely if you post your PHP code in question.

Before you get the date variable and print it with date("Y-m-d", strtotime($payment_date)) function, you must check if it is having NULL value or not.

```<code>if($payment_date != NULL)
{
    date("Y-m-d H:i:s", strtotime($payment_date));
}
</code>```

Body:
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format

. when i print this column it returns like this

payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40

but i need to return as NULL not default time format.

Body:
This code is just to give you an idea. I can help you precisely if you post your PHP code in question.

Before you get the date variable and print it with date("Y-m-d", strtotime($payment_date)) function, you must check if it is having NULL value or not.

if($payment_date != NULL)
{
    date("Y-m-d H:i:s", strtotime($payment_date));
}


问:
View doesn't load
I want to ask about view
here I have controller like this: (api.php)

```<code>public function export_excel() {
    $date = new DateTime($this->input->post('date_fil'));
    $curr_date = $date->format('Y-m-d ');
    $user = $this->input->post('sales_name');
    $checked = $this->input->post('cb_month');
    $month = date('m');

    if ((int) $checked == 1) {
        $this->form_validation->set_rules('sales_name', 'Sales Name', 'required');
        if ($this->form_validation->run() == false) {
            $this->output->set_output(json_encode([
                'result' => 0,
                'error' => $this->form_validation->error_array()
            ]));
            return false;
        }

        $this->db->select('t1.act_id, t2.login, t1.cust_name, t1.act_type, t1.act_detail, t1.date_added, t1.date_modified, t1.act_notes')
                ->from('activity as t1')
                ->join('user as t2', 't1.user_id = t2.user_id', 'LEFT')
                ->where('t2.login', $user)
                ->where('MONTH(t1.date_added)', $month);
        $query = $this->db->get();
        $result = $query->result_array();

        $data = array('title' => 'Sales Report',
            'user' => $result);

        $this->load->view('report/vw_excel', $data);
        // Selecting data by Date ----------------------------------------------
    } else {

        $this->form_validation->set_rules('sales_name', 'Sales Name', 'required');
        $this->form_validation->set_rules('date_fil', 'Date', 'required');

        if ($this->form_validation->run() == false) {
            $this->output->set_output(json_encode([
                'result' => 0,
                'error' => $this->form_validation->error_array()
            ]));
            return false;
        }

        $this->db->select('t1.act_id, t2.login, t1.cust_name, t1.act_type, t1.act_detail, t1.date_added, t1.date_modified, t1.act_notes')
                ->from('activity as t1')
                ->join('user as t2', 't1.user_id = t2.user_id', 'LEFT')
                ->where('t2.login', $user)
                ->where('DATE(t1.date_added)', $curr_date);
        $query = $this->db->get();
        $result = $query->result_array();

        $data = array('title' => 'Sales Report',
            'user' => $result);
        $this->load->view('report/vw_excel', $data);
    }
</code>```

and here's the view I want to load it's under folder (report/vw_excel)

```<code><body>
  <main>
       <h1>Excel Report</h1>
       <p><a href="<?php echo base_url('report/export_excel') ?>">Export to Excel</a></p>
       <table border="1" width="100%">
            <thead>
                 <tr>
                      <th>ID</th>
                      <th>Sales Name</th>
                      <th>Customer Name</th>
                      <th>Activity</th>
                      <th>Detail</th>
                      <th>Start Time</th>
                      <th>Finish Time</th>
                      <th>Note</th>
                 </tr>
            </thead>
            <tbody>
                 <?php $i=1; foreach($user as $xuser) { ?>
                 <tr>
                      <td><?php echo $xuser['act_id']; ?></td>
                      <td><?php echo $xuser['login']; ?></td>
                      <td><?php echo $xuser['cust_name']; ?></td>
                      <td><?php echo $xuser['act_type']; ?></td>
                      <td><?php echo $xuser['act_detail']; ?></td>
                      <td><?php echo $xuser['date_added']; ?></td>
                      <td><?php echo $xuser['date_modified']; ?></td>
                      <td><?php echo $xuser['act_notes']; ?></td>
                 </tr>
                 <?php $i++; } ?>
            </tbody>
       </table>
  </main>
</code>```

when I call it from other view folder(admin/admin_view)
onsubmit = 'api/export_excel',
this "$this->load->view('report/vw_excel', $data);" wont load the view.

the result are showing in the browser's network, but the view doesn't load.
network view

any idea? thanks.

答:
Do a right click on the screen - inspect element. In the elements panel, select the table that was supposed to be there on screen. Check in the Style panel if the same is not turned off from being displayed for some reason.

You may also check its position (if in case it is visible) on screen for you to be able to diagnose whether the element is actually in screen dimensions.

Title: View doesn't load

Body:
I want to ask about view
here I have controller like this: (api.php)

public function export_excel() {
    $date = new DateTime($this->input->post('date_fil'));
    $curr_date = $date->format('Y-m-d ');
    $user = $this->input->post('sales_name');
    $checked = $this->input->post('cb_month');
    $month = date('m');

    if ((int) $checked == 1) {
        $this->form_validation->set_rules('sales_name', 'Sales Name', 'required');
        if ($this->form_validation->run() == false) {
            $this->output->set_output(json_encode([
                'result' => 0,
                'error' => $this->form_validation->error_array()
            ]));
            return false;
        }

        $this->db->select('t1.act_id, t2.login, t1.cust_name, t1.act_type, t1.act_detail, t1.date_added, t1.date_modified, t1.act_notes')
                ->from('activity as t1')
                ->join('user as t2', 't1.user_id = t2.user_id', 'LEFT')
                ->where('t2.login', $user)
                ->where('MONTH(t1.date_added)', $month);
        $query = $this->db->get();
        $result = $query->result_array();

        $data = array('title' => 'Sales Report',
            'user' => $result);

        $this->load->view('report/vw_excel', $data);
        // Selecting data by Date ----------------------------------------------
    } else {

        $this->form_validation->set_rules('sales_name', 'Sales Name', 'required');
        $this->form_validation->set_rules('date_fil', 'Date', 'required');

        if ($this->form_validation->run() == false) {
            $this->output->set_output(json_encode([
                'result' => 0,
                'error' => $this->form_validation->error_array()
            ]));
            return false;
        }

        $this->db->select('t1.act_id, t2.login, t1.cust_name, t1.act_type, t1.act_detail, t1.date_added, t1.date_modified, t1.act_notes')
                ->from('activity as t1')
                ->join('user as t2', 't1.user_id = t2.user_id', 'LEFT')
                ->where('t2.login', $user)
                ->where('DATE(t1.date_added)', $curr_date);
        $query = $this->db->get();
        $result = $query->result_array();

        $data = array('title' => 'Sales Report',
            'user' => $result);
        $this->load->view('report/vw_excel', $data);
    }

and here's the view I want to load it's under folder (report/vw_excel)

Excel Report

<a href="<?php echo base_url('report/export_excel') ?>">Export to Excel

                      ID
                      Sales Name
                      Customer Name
                      Activity
                      Detail
                      Start Time
                      Finish Time
                      Note

                 <?php $i=1; foreach($user as $xuser) { ?>

                      <?php echo $xuser['act_id']; ?>
                      <?php echo $xuser['login']; ?>
                      <?php echo $xuser['cust_name']; ?>
                      <?php echo $xuser['act_type']; ?>
                      <?php echo $xuser['act_detail']; ?>
                      <?php echo $xuser['date_added']; ?>
                      <?php echo $xuser['date_modified']; ?>
                      <?php echo $xuser['act_notes']; ?>

                 <?php $i++; } ?>

when I call it from other view folder(admin/admin_view)
onsubmit = 'api/export_excel',
this "$this->load->view('report/vw_excel', $data);" wont load the view.

the result are showing in the browser's network, but the view doesn't load.
network view

any idea? thanks.


问:
CORS / xhr.getRequestHeaders
Greetings,

I am trying to use CORS (http://www.w3.org/TR/2009/WD-cors-20090317/#access-control-allow-methods-header) for an application on Safari, and when I try to read the response headers from the XMLHTTPRequest, I only receive the Content-Type. None of the other quite standard headers gets through, and I cannot figure out how to get this to work.

Anyone would happen to know how to fix this issue? Could this be a WebKit bug?

Edit

here is the config i use with nGinx:

```<code>add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers Cache-Control,Pragma,Date;
add_header Access-Control-Allow-Methods GET,POST;
</code>```

答: Have you verified that your server is actually emitting the Cache-Control, Pragma and Date headers?  Perhaps set up a Wireshark trace on the client to see the actual HTTP headers that are being exchanged?</p>

Title: CORS / xhr.getRequestHeaders

Body:
Greetings,

I am trying to use CORS (http://www.w3.org/TR/2009/WD-cors-20090317/#access-control-allow-methods-header) for an application on Safari, and when I try to read the response headers from the XMLHTTPRequest, I only receive the Content-Type. None of the other quite standard headers gets through, and I cannot figure out how to get this to work.

Anyone would happen to know how to fix this issue? Could this be a WebKit bug?

Edit

here is the config i use with nGinx:

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers Cache-Control,Pragma,Date;
add_header Access-Control-Allow-Methods GET,POST;


问:
Typescript code not showing anything in the browser after transpiling
I am trying to write some very simple examples of Typescript code
In Atom editor.
The example consists of one main.ts and a very small module with only
one small class (myclasses.ts) . I import the module normally

The transpiling process goes without any errors and .js files
Are being created normally in the output folder.
I trans-pile using the CLI

```<code>tsc *.ts --target 'es6'
</code>```

And I do it also from within Atom, in both cases it finishes without
Any errors nor warnings.
When I run the main.js file from the CLI using:

```<code>node main.js
</code>```

It works just fine and I get the results and the output of every function
But when I Open the html file that calls the main.js nothhing
Happens! No errors no warnings nothing in the console, no output ...

this is the contents of tsconfig.json:

```<code>{
  "compilerOptions": {

    "target": "ES2015",
    "module": "umd",
    "outDir": "built",
    "strict": true

  },

  "exclude": [
      "node_modules"
  ]
}
</code>```

and this the main.js (after transpiling):

```<code>(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "./myclasses"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const myclasses_1 = require("./myclasses");
    var colors;
    (function (colors) {
        colors[colors["Red"] = 0] = "Red";
        colors[colors["Green"] = 1] = "Green";
        colors[colors["Blue"] = 2] = "Blue";
    })(colors || (colors = {}));
    ;
    let msg = 'Ameme tmena';
    let result = msg.toUpperCase();
    console.log(result);
    let aa = msg.endsWith('a');
    console.log(aa);
    function tryLoop(l) {
        for (let i = 0; i < l; i++) {
            let PowrOf2 = () => Math.pow(i, 2);
            console.log(i, PowrOf2());
        }
    }
    ;
    tryLoop(7);
    let test1;
    test1 = 'Amama Terr';
    let ThEnd = test1.endsWith('r');
    console.log(ThEnd);
    let p1 = new myclasses_1.Point(78, 89);
    p1.calcXY();
    p1.x = 8;
    p1.y = 90;
    p1.calcXY();
    p1.x = -8;
    p1.y = 0;
    p1.calcXY();
    console.log('Hiiiiiii');
    let testing;
    testing = 19;
    testing += (testing > 20) ? -2 : +2;
    console.log(testing);
});
</code>```

答:
You can just change the tsconfig not to create module:

```<code>{
  "compilerOptions": {

    "target": "ES2015",
    "module": "none",
    "outDir": "built",
    "strict": true

  },

  "exclude": [
      "node_modules"
  ]
}
</code>```

This should output clean JS code.

Body:
I am trying to write some very simple examples of Typescript code
In Atom editor.
The example consists of one main.ts and a very small module with only
one small class (myclasses.ts) . I import the module normally

The transpiling process goes without any errors and .js files
Are being created normally in the output folder.
I trans-pile using the CLI

tsc *.ts --target 'es6'

And I do it also from within Atom, in both cases it finishes without
Any errors nor warnings.
When I run the main.js file from the CLI using:

node main.js

It works just fine and I get the results and the output of every function
But when I Open the html file that calls the main.js nothhing
Happens! No errors no warnings nothing in the console, no output ...

this is the contents of tsconfig.json:

{
  "compilerOptions": {

    "target": "ES2015",
    "module": "umd",
    "outDir": "built",
    "strict": true

  },

  "exclude": [
      "node_modules"
  ]
}

and this the main.js (after transpiling):

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "./myclasses"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const myclasses_1 = require("./myclasses");
    var colors;
    (function (colors) {
        colors[colors["Red"] = 0] = "Red";
        colors[colors["Green"] = 1] = "Green";
        colors[colors["Blue"] = 2] = "Blue";
    })(colors || (colors = {}));
    ;
    let msg = 'Ameme tmena';
    let result = msg.toUpperCase();
    console.log(result);
    let aa = msg.endsWith('a');
    console.log(aa);
    function tryLoop(l) {
        for (let i = 0; i < l; i++) {
            let PowrOf2 = () => Math.pow(i, 2);
            console.log(i, PowrOf2());
        }
    }
    ;
    tryLoop(7);
    let test1;
    test1 = 'Amama Terr';
    let ThEnd = test1.endsWith('r');
    console.log(ThEnd);
    let p1 = new myclasses_1.Point(78, 89);
    p1.calcXY();
    p1.x = 8;
    p1.y = 90;
    p1.calcXY();
    p1.x = -8;
    p1.y = 0;
    p1.calcXY();
    console.log('Hiiiiiii');
    let testing;
    testing = 19;
    testing += (testing > 20) ? -2 : +2;
    console.log(testing);
});

Body:
You can just change the tsconfig not to create module:

{
  "compilerOptions": {

    "target": "ES2015",
    "module": "none",
    "outDir": "built",
    "strict": true

  },

  "exclude": [
      "node_modules"
  ]
}

This should output clean JS code.