问:
scala timing problems with add stuff to a seq
I've got a question that concerns scoping in scala. I have a function like this:

```<code>def getElements(id: Int): Seq[Element] = {
    var test = ""
    dto.getElementIds(id).map {
      elementIds => {
        test += " hello "
        elementIds.foreach(elementId => dto.getElement(elementId).map {
          case Some(element) => test += " hi "
                println("ThirdPrint: " + test)
        })
        println("SecondPrint: " + test)
      }
    }
    println("FirstPrint: " + test)
}
</code>```

Lets say "elementsIds" has a lenght of 2.
The console says:
FirstPrint:
SecondPrint: hello
ThirdPrint: hello hi
ThirdPrint: hello hi hi
Why is scala doing that? I would assume that third print is executed first. By the time I get to the "FirstPrint" the "hi"'s are gone. Why is the last line of code executed first?
I'm working with slick and Futures, does this have something to do with it? Thanks!

UPDATE

Thanks, works fine.
Is it possible to return a seq instead? Like this:

```<code> def getElements(id: Int): Future[Seq[Element]] = {
    var mySequence: Seq[Element] = Seq()
    val elementsIds: Future[Seq[Int]] = dto.getElementIds(id)
    var test = ""
    val elementsF = elementsIds.flatMap {
      elementIds => {
        test += " hello "
        val idsAsElements: Seq[Future[Element]] = elementIds.map(elementId => dto.getElement(elementId).collect {
          case Some(element) => mySequence = mySequence :+ element
        })
        val idsAsElementsF: Future[Seq[Element]] = Future.sequence(idsAsElements)
        idsAsElementsF.onComplete(_ => println("SecondPrint: " + test))
        idsAsElementsF
      }
    }
    elementsF.onComplete(_ => println("FirstPrint: " + test))
    elementsF
  }
</code>```

Is it possible to return "mySequence" whenever idsAsElements is "onComplete"?

答:
```<code> object X {
  import scala.concurrent.ExecutionContext.Implicits.global
  case class Element()
  object dto{

    def getElementIds(i: Int):  Future[Seq[Int]] = Future(Seq(1,2,3))
    def getElement(i: Int):  Future[Option[Element]] = Future(Some(Element()))

  }

  def main(args: Array[String]): Unit = {
    getElements(0)
    Thread.sleep(10000) // waiting logs
  }
  def getElements(id: Int): Future[Seq[Element]] = {
    val elementsIds: Future[Seq[Int]] = dto.getElementIds(id)
    var test = ""
    val elementsF = elementsIds.flatMap {
      elementIds => {
        test += " hello "
        val idsAsElements: Seq[Future[Element]] = elementIds.map(elementId => dto.getElement(elementId).collect {
          case Some(element) => test += " hi "
            println("ThirdPrint: " + test)
            element
        })
        val idsAsElementsF: Future[Seq[Element]] = Future.sequence(idsAsElements)
        idsAsElementsF.onComplete(_ => println("SecondPrint: " + test))
        idsAsElementsF
      }
    }
    elementsF.onComplete(_ => println("FirstPrint: " + test))
    elementsF
  }
}
</code>```

output:

ThirdPrint:  hello  hi

ThirdPrint:  hello  hi  hi

ThirdPrint:  hello  hi  hi  hi

SecondPrint:  hello  hi  hi  hi

FirstPrint:  hello  hi  hi  hi

Body:
I've got a question that concerns scoping in scala. I have a function like this:

def getElements(id: Int): Seq[Element] = {
    var test = ""
    dto.getElementIds(id).map {
      elementIds => {
        test += " hello "
        elementIds.foreach(elementId => dto.getElement(elementId).map {
          case Some(element) => test += " hi "
                println("ThirdPrint: " + test)
        })
        println("SecondPrint: " + test)
      }
    }
    println("FirstPrint: " + test)
}

Lets say "elementsIds" has a lenght of 2.
The console says:
FirstPrint:
SecondPrint: hello
ThirdPrint: hello hi
ThirdPrint: hello hi hi
Why is scala doing that? I would assume that third print is executed first. By the time I get to the "FirstPrint" the "hi"'s are gone. Why is the last line of code executed first?
I'm working with slick and Futures, does this have something to do with it? Thanks!

UPDATE

Thanks, works fine.
Is it possible to return a seq instead? Like this:

 def getElements(id: Int): Future[Seq[Element]] = {
    var mySequence: Seq[Element] = Seq()
    val elementsIds: Future[Seq[Int]] = dto.getElementIds(id)
    var test = ""
    val elementsF = elementsIds.flatMap {
      elementIds => {
        test += " hello "
        val idsAsElements: Seq[Future[Element]] = elementIds.map(elementId => dto.getElement(elementId).collect {
          case Some(element) => mySequence = mySequence :+ element
        })
        val idsAsElementsF: Future[Seq[Element]] = Future.sequence(idsAsElements)
        idsAsElementsF.onComplete(_ => println("SecondPrint: " + test))
        idsAsElementsF
      }
    }
    elementsF.onComplete(_ => println("FirstPrint: " + test))
    elementsF
  }

Is it possible to return "mySequence" whenever idsAsElements is "onComplete"?

Body:
 object X {
  import scala.concurrent.ExecutionContext.Implicits.global
  case class Element()
  object dto{

    def getElementIds(i: Int):  Future[Seq[Int]] = Future(Seq(1,2,3))
    def getElement(i: Int):  Future[Option[Element]] = Future(Some(Element()))

  }

  def main(args: Array[String]): Unit = {
    getElements(0)
    Thread.sleep(10000) // waiting logs
  }
  def getElements(id: Int): Future[Seq[Element]] = {
    val elementsIds: Future[Seq[Int]] = dto.getElementIds(id)
    var test = ""
    val elementsF = elementsIds.flatMap {
      elementIds => {
        test += " hello "
        val idsAsElements: Seq[Future[Element]] = elementIds.map(elementId => dto.getElement(elementId).collect {
          case Some(element) => test += " hi "
            println("ThirdPrint: " + test)
            element
        })
        val idsAsElementsF: Future[Seq[Element]] = Future.sequence(idsAsElements)
        idsAsElementsF.onComplete(_ => println("SecondPrint: " + test))
        idsAsElementsF
      }
    }
    elementsF.onComplete(_ => println("FirstPrint: " + test))
    elementsF
  }
}

output:

ThirdPrint:  hello  hi

ThirdPrint:  hello  hi  hi

ThirdPrint:  hello  hi  hi  hi

SecondPrint:  hello  hi  hi  hi

FirstPrint:  hello  hi  hi  hi


来源: stackexchange

问:
How to obtain an instance of ServiceState?
I'm trying to obtain an instance of ServiceState in my Activity. But how am I supposed to do this? There is no static method to obtain an instance or any method on any service that returns an ServiceState instance.

There is the TelephonyManager.listen() call. But I want to get the ServiceState instance when I want, not when Android calls my listener because something changed.

The documentation of ServiceState can be found here: http://developer.android.com/reference/android/telephony/ServiceState.html

答:
In Android 8 you have the following:

```<code>tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.getServiceState();
</code>```

don't forget to add permission:

```<code><uses-permission android:name="android.permission.READ_PHONE_STATE" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Android 8 you have the following:

tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.getServiceState();

don't forget to add permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />


问:
UITableView's tableHeaderView height property is changed to strange values during load and rotation
I have a custom UIView which I set to the tableHeaderView property of a UITableView during loadView:

```<code>headerView = [[MYViewClass alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
[headerView sizeToFit];

self.tableView.tableHeaderView = headerView;
</code>```

The view draws incorrectly, with part of the view clipped and white space above the table.  When rotating the device the view almost disappears. On rotating back the view is now bigger that the space for the header and obscures some of the cells in the table.

To troubleshoot I have overrode the setFrame method in my custom view class:

```<code>- (void) setFrame:(CGRect)frame {
    [super setFrame:frame];
    NSLog(@"%@ - %@", NSStringFromSelector(_cmd), NSStringFromCGRect(frame));
}
</code>```

I also put a break point on the NSLog statement so I could see what called the setFrame and I get some odd results that I can't explain and hope someone can shed some light on what is happening and why.

During loadView

```<code>1. initWithFrame calls: setFrame: - {{0, 0}, {320, 120}}
2. sizeToFit calls: setFrame: - {{0, 0}, {320, 109}}
3. setTableHeaderView calls:  setFrame: - {{0, 0}, {320, 109}}
4. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 109}}
5. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {320, 65}}
6. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 65}}
7. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 65}}
</code>```

Rotating the device left

```<code>1. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {480, 0}}
2. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {480, 0}}
3. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {480, 12}}
4. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {480, 12}}
</code>```

Rotating the device right

```<code>1. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {320, 172}}
2. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 172}}
3. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {320, 160}}
4. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 160}}
</code>```

Which explains why my view looks truncated initially, then almost disappears and finally ends up overlapping the cells.  It appears that _resizeWithOldSuperviewSize is the culprit and what I don't understand is why it is being called and where it is getting these odd values from.

I have a really rubbish work around by calling [self.tableView.tableHeaderView sizeToFit] in viewDidAppear: and didRotateFromInterfaceOrientation: which puts the frame back to the correct size but the redrawing is awful as both happen after the view is visible or after the rotation animation.  Trying to set this anytime before the view is visible causes _resizeWithOldSuperViewSize to set the frame back to these odd sizes.

答:
You need to get the intrinsic size and autoresizingMask right. Once you do that, UITableView will stop screwing with your tableHeaderView.

For example, if you want your header to have a fixed height which depends on its contents, but you want your header to use the entire table width, this is what you would do:

1.Create your view with the following Autoresizing mask configuration (so the table won't try to increase the header view height):

2. Add your subviews using AutoLayout so the top/bottom anchors match your view (this is so your subviews define the height of your header view)

3. Add your header view like so:

```<code>let headerView : CustomView? = CustomView.fromNib()
headerView?.sizeToFit()

tableView.tableHeaderView = headerView
</code>```

Body:
I have a custom UIView which I set to the tableHeaderView property of a UITableView during loadView:

headerView = [[MYViewClass alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
[headerView sizeToFit];

self.tableView.tableHeaderView = headerView;

The view draws incorrectly, with part of the view clipped and white space above the table.  When rotating the device the view almost disappears. On rotating back the view is now bigger that the space for the header and obscures some of the cells in the table.

To troubleshoot I have overrode the setFrame method in my custom view class:

- (void) setFrame:(CGRect)frame {
    [super setFrame:frame];
    NSLog(@"%@ - %@", NSStringFromSelector(_cmd), NSStringFromCGRect(frame));
}

I also put a break point on the NSLog statement so I could see what called the setFrame and I get some odd results that I can't explain and hope someone can shed some light on what is happening and why.

During loadView

1. initWithFrame calls: setFrame: - {{0, 0}, {320, 120}}
2. sizeToFit calls: setFrame: - {{0, 0}, {320, 109}}
3. setTableHeaderView calls:  setFrame: - {{0, 0}, {320, 109}}
4. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 109}}
5. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {320, 65}}
6. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 65}}
7. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 65}}

Rotating the device left

1. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {480, 0}}
2. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {480, 0}}
3. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {480, 12}}
4. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {480, 12}}

Rotating the device right

1. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {320, 172}}
2. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 172}}
3. _resizeWithOldSuperviewSize calls: setFrame: - {{0, 0}, {320, 160}}
4. _adjustTableHeaderAndFooterViews calls: setFrame: - {{0, 0}, {320, 160}}

Which explains why my view looks truncated initially, then almost disappears and finally ends up overlapping the cells.  It appears that _resizeWithOldSuperviewSize is the culprit and what I don't understand is why it is being called and where it is getting these odd values from.

I have a really rubbish work around by calling [self.tableView.tableHeaderView sizeToFit] in viewDidAppear: and didRotateFromInterfaceOrientation: which puts the frame back to the correct size but the redrawing is awful as both happen after the view is visible or after the rotation animation.  Trying to set this anytime before the view is visible causes _resizeWithOldSuperViewSize to set the frame back to these odd sizes.

Body:
You need to get the intrinsic size and autoresizingMask right. Once you do that, UITableView will stop screwing with your tableHeaderView.

For example, if you want your header to have a fixed height which depends on its contents, but you want your header to use the entire table width, this is what you would do:

1.Create your view with the following Autoresizing mask configuration (so the table won't try to increase the header view height):

2. Add your subviews using AutoLayout so the top/bottom anchors match your view (this is so your subviews define the height of your header view)

3. Add your header view like so:

let headerView : CustomView? = CustomView.fromNib()
headerView?.sizeToFit()

tableView.tableHeaderView = headerView


问:
How can I debug "undefined instruction" faults for an LPC1788 in IAR Embedded Workbench?
I'm developing an application for an LPC1788 (Cortex-M3) microcontroller. This application involves sending and receiving CAN messages, and I find that when I subject it to heavy load and twiddle my thumbs for 30-60 minutes, a hardfault will occur.

I'm debugging the firmware through IAR Embedded Workbench 6.60.1.5104, and when this hardfault occurs it breaks at a weakly-linked default hardfault handler defined in startup_LPC177x_8x.s:

```<code>        PUBWEAK HardFault_Handler
        SECTION .text:CODE:REORDER(1)
HardFault_Handler
        B HardFault_Handler
</code>```

Unfortunately, the call stack only contains the address of this handler and not whichever part of code called into it (where the error occurred).

The only useful information I've been able to gather is from the UNDEFINSTR bit being set in the NVIC:CFSR register. From the documentation:

When this bit is set, the PC value stacked for the exception return
  points to the undefined instruction. An undefined instruction is an
  instruction that the processor cannot decode. Potential reasons:

a) Use of instructions not supported in the Cortex-M device.

  b) Bad or corrupted memory contents.

I've read that the value of the program counter at the point the instruction was executed is stored in one of the exception stack registers, but I'm not sure how to access these from IAR.

In case it's any help, I've included a screenshot containing some of the debugging details (right click -> view image for a larger version):

答:
I found a solution by adapting code I found from this blog.

The user "Ramon" there helpfully posted code that led me on the right track to getting something that compiled in IAR (I've never tried writing raw assembly in IAR Embedded Workbench before).

This is the hardfault handling code I used:

#include "lpc177x_8x.h"

static volatile unsigned long stacked_r0 = 0;
static volatile unsigned long stacked_r1 = 0;
static volatile unsigned long stacked_r2 = 0;
static volatile unsigned long stacked_r3 = 0;
static volatile unsigned long stacked_r12 = 0;
static volatile unsigned long stacked_lr = 0;
static volatile unsigned long stacked_pc = 0;
static volatile unsigned long stacked_psr = 0;
static volatile unsigned long _cfsr = 0;
static volatile unsigned long _hfsr = 0;
static volatile unsigned long _dfsr = 0;
static volatile unsigned long _afsr = 0;
static volatile unsigned long _bfar = 0;
static volatile unsigned long _mmar = 0;

void hardfault_handler( void )
{
  __asm("tst lr, #4");
  __asm("ite eq \n"
        "mrseq r0, msp \n"
        "mrsne r0, psp");
  __asm("b hard_fault_handler_c");
}

void hard_fault_handler_c(unsigned long *hardfault_args){
  stacked_r0 = ((unsigned long)hardfault_args[0]);
  stacked_r1 = ((unsigned long)hardfault_args[1]);
  stacked_r2 = ((unsigned long)hardfault_args[2]);
  stacked_r3 = ((unsigned long)hardfault_args[3]);
  stacked_r12 = ((unsigned long)hardfault_args[4]);
  stacked_lr = ((unsigned long)hardfault_args[5]);
  stacked_pc = ((unsigned long)hardfault_args[6]);
  stacked_psr = ((unsigned long)hardfault_args[7]);

  // configurable fault status register
  // consists of mmsr, bfsr and ufsr
  _cfsr = (*((volatile unsigned long *)(0xe000ed28)));

  // hard fault status register
  _hfsr = (*((volatile unsigned long *)(0xe000ed2c)));

  // debug fault status register
  _dfsr = (*((volatile unsigned long *)(0xe000ed30)));

  // auxiliary fault status register
  _afsr = (*((volatile unsigned long *)(0xe000ed3c)));

  // read the fault address registers. these may not contain valid values.
  // check bfarvalid/mmarvalid to see if they are valid values
  // memmanage fault address register
  _mmar = (*((volatile unsigned long *)(0xe000ed34)));
  // bus fault address register
  _bfar = (*((volatile unsigned long *)(0xe000ed38)));

  __asm("bkpt #0\n"); // break into the debugger
}
```

<p>To test this, I created the following function to ensure that "division by zero" usage errors would be captured, but that usage errors would automatically be elevated to hard faults:</p>

<pre class="lang-c prettyprint-override"><code>void configureFaultHandling()
{
  // Catch all possible faults.

//  SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk
//    | SCB_SHCSR_BUSFAULTENA_Msk
//    | SCB_SHCSR_USGFAULTENA_Msk;

  SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk
    | SCB_CCR_UNALIGN_TRP_Msk;
}
</code>```

I added the following to the start of main:

void main()
{
  configureFaultHandling();

  int a = 5 / 0;
}
```

Running this, the program very quickly braked at void hardfault_handler( void ), and I could step through this into hard_fault_handler_c and inspect the values of the registers.

What I found is that these values corresponded to the values shown in IAR's View -> Stack -> Stack 1 pane. This makes sense in hindsight as the documentation states that the values of certain registers get pushed onto the stack when faults occur. However, writing this function helped me figure out which values in the stack corresponded to which registers.

For reference to myself and others that might have similar issues, I found the 7th value in "stack 1" (i.e. index 6) corresponded to the program counter value at the time the exception occurred. This is what it looked like for me (right click -> view image to enlarge):

Doing it this way allows you to find the source of hardfaults without needing to overwrite the default hardfault handler, so long as the debugger automatically breaks when hardfaults occur.

Hopefully this will also help in pinning down the "undefined instruction" faults.

Body:
I'm developing an application for an LPC1788 (Cortex-M3) microcontroller. This application involves sending and receiving CAN messages, and I find that when I subject it to heavy load and twiddle my thumbs for 30-60 minutes, a hardfault will occur.

I'm debugging the firmware through IAR Embedded Workbench 6.60.1.5104, and when this hardfault occurs it breaks at a weakly-linked default hardfault handler defined in startup_LPC177x_8x.s:

        PUBWEAK HardFault_Handler
        SECTION .text:CODE:REORDER(1)
HardFault_Handler
        B HardFault_Handler

Unfortunately, the call stack only contains the address of this handler and not whichever part of code called into it (where the error occurred).

The only useful information I've been able to gather is from the UNDEFINSTR bit being set in the NVIC:CFSR register. From the documentation:

When this bit is set, the PC value stacked for the exception return
  points to the undefined instruction. An undefined instruction is an
  instruction that the processor cannot decode. Potential reasons:

a) Use of instructions not supported in the Cortex-M device.

  b) Bad or corrupted memory contents.

I've read that the value of the program counter at the point the instruction was executed is stored in one of the exception stack registers, but I'm not sure how to access these from IAR.

In case it's any help, I've included a screenshot containing some of the debugging details (right click -> view image for a larger version):

Body:
I found a solution by adapting code I found from this blog.

The user "Ramon" there helpfully posted code that led me on the right track to getting something that compiled in IAR (I've never tried writing raw assembly in IAR Embedded Workbench before).

This is the hardfault handling code I used:

#include "lpc177x_8x.h"

static volatile unsigned long stacked_r0 = 0;
static volatile unsigned long stacked_r1 = 0;
static volatile unsigned long stacked_r2 = 0;
static volatile unsigned long stacked_r3 = 0;
static volatile unsigned long stacked_r12 = 0;
static volatile unsigned long stacked_lr = 0;
static volatile unsigned long stacked_pc = 0;
static volatile unsigned long stacked_psr = 0;
static volatile unsigned long _cfsr = 0;
static volatile unsigned long _hfsr = 0;
static volatile unsigned long _dfsr = 0;
static volatile unsigned long _afsr = 0;
static volatile unsigned long _bfar = 0;
static volatile unsigned long _mmar = 0;

void hardfault_handler( void )
{
  __asm("tst lr, #4");
  __asm("ite eq \n"
        "mrseq r0, msp \n"
        "mrsne r0, psp");
  __asm("b hard_fault_handler_c");
}

void hard_fault_handler_c(unsigned long *hardfault_args){
  stacked_r0 = ((unsigned long)hardfault_args[0]);
  stacked_r1 = ((unsigned long)hardfault_args[1]);
  stacked_r2 = ((unsigned long)hardfault_args[2]);
  stacked_r3 = ((unsigned long)hardfault_args[3]);
  stacked_r12 = ((unsigned long)hardfault_args[4]);
  stacked_lr = ((unsigned long)hardfault_args[5]);
  stacked_pc = ((unsigned long)hardfault_args[6]);
  stacked_psr = ((unsigned long)hardfault_args[7]);

  // configurable fault status register
  // consists of mmsr, bfsr and ufsr
  _cfsr = (*((volatile unsigned long *)(0xe000ed28)));

  // hard fault status register
  _hfsr = (*((volatile unsigned long *)(0xe000ed2c)));

  // debug fault status register
  _dfsr = (*((volatile unsigned long *)(0xe000ed30)));

  // auxiliary fault status register
  _afsr = (*((volatile unsigned long *)(0xe000ed3c)));

  // read the fault address registers. these may not contain valid values.
  // check bfarvalid/mmarvalid to see if they are valid values
  // memmanage fault address register
  _mmar = (*((volatile unsigned long *)(0xe000ed34)));
  // bus fault address register
  _bfar = (*((volatile unsigned long *)(0xe000ed38)));

  __asm("bkpt #0\n"); // break into the debugger
}

To test this, I created the following function to ensure that "division by zero" usage errors would be captured, but that usage errors would automatically be elevated to hard faults:

void configureFaultHandling()
{
  // Catch all possible faults.

//  SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk
//    | SCB_SHCSR_BUSFAULTENA_Msk
//    | SCB_SHCSR_USGFAULTENA_Msk;

  SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk
    | SCB_CCR_UNALIGN_TRP_Msk;
}

I added the following to the start of main:

void main()
{
  configureFaultHandling();

  int a = 5 / 0;
}

Running this, the program very quickly braked at void hardfault_handler( void ), and I could step through this into hard_fault_handler_c and inspect the values of the registers.

What I found is that these values corresponded to the values shown in IAR's View -> Stack -> Stack 1 pane. This makes sense in hindsight as the documentation states that the values of certain registers get pushed onto the stack when faults occur. However, writing this function helped me figure out which values in the stack corresponded to which registers.

For reference to myself and others that might have similar issues, I found the 7th value in "stack 1" (i.e. index 6) corresponded to the program counter value at the time the exception occurred. This is what it looked like for me (right click -> view image to enlarge):

Doing it this way allows you to find the source of hardfaults without needing to overwrite the default hardfault handler, so long as the debugger automatically breaks when hardfaults occur.

Hopefully this will also help in pinning down the "undefined instruction" faults.


问:
How to find object type from URL SharePoint online (o365)?
I found out  how to determine the object type from URL for SharePoint on prem:

https://blogs.msdn.microsoft.com/sanjaynarang/2009/04/06/find-sharepoint-object-type-from-url/

But I didn't find anything for SharePoint Online (CSOM).

Is it possible for SharePoint online?

答:
For the most scenarios such as:

folder url, e.g. https://contoso.sharepoint.com//Documents/Forms/AllItems.aspx?RootFolder=%2FDocuments%2FArchive

list item url, e.g. https://contoso.sharepoint.com/Lists/ShoppingCart/DispForm.aspx?ID=9

list/library url, e.g. https://contoso.sharepoint.com/Lists/Announcements

page url, e.g. https://contoso.sharepoint.com/Lists/Announcements/Newsletter.aspx

the following example demonstrates how to determine client object type:

```<code>using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web;
using Microsoft.SharePoint.Client;

namespace O365Console
{
    static class ClientObjectExtensions
    {
        public static ClientObject ResolveClientObjectFromUrl(string resourceUrl, ICredentials credentials)
        {
            ClientObject targetObject = null;
            var resourceUri = new Uri(resourceUrl);
            using (var rootCtx = new ClientContext(resourceUri.Scheme + Uri.SchemeDelimiter + resourceUri.Host))
            {
                rootCtx.Credentials = credentials;
                var webUrl = Web.WebUrlFromPageUrlDirect(rootCtx, resourceUri);
                using (var ctx = new ClientContext(webUrl.ToString()))
                {
                    ctx.Credentials = credentials;

                    var queryBag = System.Web.HttpUtility.ParseQueryString(resourceUri.Query);
                    if (queryBag["Id"] != null)
                    {
                        var listUrl = string.Join(string.Empty,
                            resourceUri.Segments.Take(resourceUri.Segments.Length - 1));
                        var list = ctx.Web.GetList(listUrl);
                        targetObject = TryRetrieve(() => list.GetItemById(Convert.ToInt32(queryBag["Id"])));
                    }
                    else if (queryBag["RootFolder"] != null)
                    {
                        var folderUrl = HttpUtility.UrlDecode(queryBag["RootFolder"]);
                        targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(folderUrl));
                    }
                    else if (queryBag.Count > 0)
                    {
                        throw new Exception("Unsupported query string parameter found");
                    }
                    else
                    {

                        targetObject = TryRetrieve(() => ctx.Web.GetFileByServerRelativeUrl(resourceUri.AbsolutePath));
                        if (targetObject == null)
                        {
                            targetObject = TryRetrieve(() => ctx.Web.GetList(resourceUri.AbsolutePath),list => list.RootFolder);
                            if (targetObject == null || ((List)targetObject).RootFolder.ServerRelativeUrl != resourceUri.AbsolutePath)
                                targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(resourceUri.AbsolutePath));
                        }
                    }
                }
            }
            return targetObject;
        }

        private static T TryRetrieve<T>(Func<T> loadMethod, params  Expression<Func<T,object>>[] retrievals) where T : ClientObject
        {
            try
            {
                var targetObject = loadMethod();
                targetObject.Context.Load(targetObject, retrievals);
                targetObject.Context.ExecuteQuery();
                return targetObject;
            }
            catch
            {
            }
            return default(T);
        }
    }
}
</code>```

Usage

```<code> var credentials = GetCredentials(userName, password);
 var clientObj = ClientObjectExtensions.ResolveClientObjectFromUrl("https://contoso.sharepoint.com/Lists/Announcements", credentials);
 Console.WriteLine(clientObj.GetType().Name);
</code>```

where

```<code> static ICredentials GetCredentials(string userName,string password)
 {
        var securePassword = new SecureString();
        foreach (var c in password)
        {
            securePassword.AppendChar(c);
        }
        return new SharePointOnlineCredentials(userName, securePassword);
 }
</code>```

Body:
For the most scenarios such as:

folder url, e.g. https://contoso.sharepoint.com//Documents/Forms/AllItems.aspx?RootFolder=%2FDocuments%2FArchive

list item url, e.g. https://contoso.sharepoint.com/Lists/ShoppingCart/DispForm.aspx?ID=9

list/library url, e.g. https://contoso.sharepoint.com/Lists/Announcements

page url, e.g. https://contoso.sharepoint.com/Lists/Announcements/Newsletter.aspx

the following example demonstrates how to determine client object type:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Web;
using Microsoft.SharePoint.Client;

namespace O365Console
{
    static class ClientObjectExtensions
    {
        public static ClientObject ResolveClientObjectFromUrl(string resourceUrl, ICredentials credentials)
        {
            ClientObject targetObject = null;
            var resourceUri = new Uri(resourceUrl);
            using (var rootCtx = new ClientContext(resourceUri.Scheme + Uri.SchemeDelimiter + resourceUri.Host))
            {
                rootCtx.Credentials = credentials;
                var webUrl = Web.WebUrlFromPageUrlDirect(rootCtx, resourceUri);
                using (var ctx = new ClientContext(webUrl.ToString()))
                {
                    ctx.Credentials = credentials;

                    var queryBag = System.Web.HttpUtility.ParseQueryString(resourceUri.Query);
                    if (queryBag["Id"] != null)
                    {
                        var listUrl = string.Join(string.Empty,
                            resourceUri.Segments.Take(resourceUri.Segments.Length - 1));
                        var list = ctx.Web.GetList(listUrl);
                        targetObject = TryRetrieve(() => list.GetItemById(Convert.ToInt32(queryBag["Id"])));
                    }
                    else if (queryBag["RootFolder"] != null)
                    {
                        var folderUrl = HttpUtility.UrlDecode(queryBag["RootFolder"]);
                        targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(folderUrl));
                    }
                    else if (queryBag.Count > 0)
                    {
                        throw new Exception("Unsupported query string parameter found");
                    }
                    else
                    {

                        targetObject = TryRetrieve(() => ctx.Web.GetFileByServerRelativeUrl(resourceUri.AbsolutePath));
                        if (targetObject == null)
                        {
                            targetObject = TryRetrieve(() => ctx.Web.GetList(resourceUri.AbsolutePath),list => list.RootFolder);
                            if (targetObject == null || ((List)targetObject).RootFolder.ServerRelativeUrl != resourceUri.AbsolutePath)
                                targetObject = TryRetrieve(() => ctx.Web.GetFolderByServerRelativeUrl(resourceUri.AbsolutePath));
                        }
                    }
                }
            }
            return targetObject;
        }

        private static T TryRetrieve<T>(Func<T> loadMethod, params  Expression<Func<T,object>>[] retrievals) where T : ClientObject
        {
            try
            {
                var targetObject = loadMethod();
                targetObject.Context.Load(targetObject, retrievals);
                targetObject.Context.ExecuteQuery();
                return targetObject;
            }
            catch
            {
            }
            return default(T);
        }
    }
}

Usage

 var credentials = GetCredentials(userName, password);
 var clientObj = ClientObjectExtensions.ResolveClientObjectFromUrl("https://contoso.sharepoint.com/Lists/Announcements", credentials);
 Console.WriteLine(clientObj.GetType().Name);

where

 static ICredentials GetCredentials(string userName,string password)
 {
        var securePassword = new SecureString();
        foreach (var c in password)
        {
            securePassword.AppendChar(c);
        }
        return new SharePointOnlineCredentials(userName, securePassword);
 }


问:
Android encoding/decoding issues
Need your help again.I am getting byte[] from onPreviewFrame(byte[] data, Camera arg1).Now i am transferring each frame through TCP to my System and then write a JPG file with that byte[].But when i open this JPG file it says that invalid JPG file.Moreover,when i send the same byte [] from PictureCallback jpegCallback = new PictureCallback() method and then write a JPG file on my PC ,it works fine.

I know its a kind of encoding issue,actually byte[] which i get from onPreviewFrame is byte array of compressed image data.

I can only transfer this byte array of compressed image data through TCP from my Phone to PC.But i want to decode this data once i get this on PC.Can you guys please help me how should i proceed.

I would be very grateful for any kind of help.

Best regards,
ZAI

答:
It is likely that the byte array that is received in the onPreviewFrame(byte[] data, Camera arg1) is not in jpeg format. Please check your camera preview format settings and try to set jpeg as preview format (getSupportedPreviewFormats() + setPreviewFormat(int pixel_format)). However, I don't think the jpeg format is supported during camera preview mode as the compression overhead might just be too time consuming for a real-time video stream.

Jiri

ContentLicense: CC BY-SA 2.5

Title: Android encoding/decoding issues


问:
Slider vs window width
https://jsfiddle.net/57wm5dy7/3/

I first click "run" in jsfiddle and my base/start width is min-width:900px media query and here the slider works without issues...

...but then I resize the window MANUALLY WITH MY MOUSE into smaller max-width 700px media query

then I click next button (right arrow)

the slide width being offseted will be taken from min-width:900px media query (slide width 700px) even though I am inside smaller max-width 700px (slide width 500px).
I want to make the next/previous buttons when clicked to execute the width of the .c-testimonial of the media query I am currently in. No matter how many times I resize the window between 2 media queries.

```<code>@media screen and  (max-width:700px) {

  .c-testimonials {
        position: relative;
        max-width: 700px;
        margin-left: auto;
        margin-right: auto;
        text-align:center;
        padding:70px 0;
          &:before {
              content: '';
              position:absolute;
              top:0;
              bottom:0;
              z-index:-1;
              width:100vw;
              left: calc(-50vw + 50%);
              background-color: #f8f8f8;
          }
          &__mask {
              margin:0 auto;
              position: relative;
              overflow:hidden;
          }
    }
}
</code>```

答:
You have to be consistent with using the same media queries - you once use max-width and then min-width which causes the problems. One rule is reused for everything lower than 900px and another one for everything higher than 700px so you have a conflict in between these 200px :)

The recommended approach in my opinion would be:

Write a default behaviour

Write a specific code for max-width: 900px

Write a specific code for max-width: 700px that will overload previous one

Or another approach - the opposite one - starting with the smaller one and using min-width.

As a guide, you can check how the most popular grid libraries do it (e.g. Bootstrap grid system). Then tend not to mix max-width and min-width as these overlap each other and usually pose unexpected results.

Another thing - you have two breakpoints in your CSS (900px and 700px) but only one breakpoint in your code...

This is updated version of your code (still has some errors, but the containers is slided properly). It should be a good point for future improvements: https://jsfiddle.net/57wm5dy7/4/

Side note: please try to reuse your code in a better way - a lot of the code in the snippet was duplicated without need and hence was less readable - please check the blocks I moved to a global context.

Title: Slider vs window width

Body:
https://jsfiddle.net/57wm5dy7/3/

I first click "run" in jsfiddle and my base/start width is min-width:900px media query and here the slider works without issues...

...but then I resize the window MANUALLY WITH MY MOUSE into smaller max-width 700px media query

then I click next button (right arrow)

the slide width being offseted will be taken from min-width:900px media query (slide width 700px) even though I am inside smaller max-width 700px (slide width 500px).
I want to make the next/previous buttons when clicked to execute the width of the .c-testimonial of the media query I am currently in. No matter how many times I resize the window between 2 media queries.

@media screen and  (max-width:700px) {

  .c-testimonials {
        position: relative;
        max-width: 700px;
        margin-left: auto;
        margin-right: auto;
        text-align:center;
        padding:70px 0;
          &:before {
              content: '';
              position:absolute;
              top:0;
              bottom:0;
              z-index:-1;
              width:100vw;
              left: calc(-50vw + 50%);
              background-color: #f8f8f8;
          }
          &__mask {
              margin:0 auto;
              position: relative;
              overflow:hidden;
          }
    }
}


问:
Babel not Polyfilling Fetch when using babel-preset-env
I'm using Webpack and Babel to build and transpile my ES6 code. However I am missing important Polyfills when trying to support older browsers. e.g iOS8.

Here's my Webpack.config

```<code>const versions = {
  v1: './src/js/v1.js',
  v2: './src/js/v2.js',
  v3: './src/js/v3.js',
};

module.exports = {
  entry: versions,
  output: {
    path: __dirname + '/dist',
    filename: '[name].min.js'
  },
  externals: {
    'jquery': 'jQuery'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }, {
        test: /\.hbs$/,
        loader: 'handlebars-loader',
      }
    ]
  }
}
</code>```

And my .babelrc file:

```<code>{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 3 versions", "iOS >= 8"]
      }
    }]
  ]
}
</code>```

Firstly, why isn't this Polyfill being added? And secondly how do I add it? I attempted adding this to my .babelrc "plugins": ["whatwg-fetch"] with no luck.

I believe I can add it to the entry of my Webpack config, but that won't work in my instance as I have multiple scripts I am trying to build separately.

Thanks in advance for any help. My diminishing head of hair is especially thankful!

答:
You can add the resolution of fetch inside your webpack.config.js file.

```<code>new webpack.ProvidePlugin({
  'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
})
</code>```

Inside your plugins section.
After that, inside your code, just use fetch. You won't need to import it whatsoever. Of course, you need imports-loader and exports-loader.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Webpack and Babel to build and transpile my ES6 code. However I am missing important Polyfills when trying to support older browsers. e.g iOS8.

Here's my Webpack.config

const versions = {
  v1: './src/js/v1.js',
  v2: './src/js/v2.js',
  v3: './src/js/v3.js',
};

module.exports = {
  entry: versions,
  output: {
    path: __dirname + '/dist',
    filename: '[name].min.js'
  },
  externals: {
    'jquery': 'jQuery'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      }, {
        test: /\.hbs$/,
        loader: 'handlebars-loader',
      }
    ]
  }
}

And my .babelrc file:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 3 versions", "iOS >= 8"]
      }
    }]
  ]
}

Firstly, why isn't this Polyfill being added? And secondly how do I add it? I attempted adding this to my .babelrc "plugins": ["whatwg-fetch"] with no luck.

I believe I can add it to the entry of my Webpack config, but that won't work in my instance as I have multiple scripts I am trying to build separately.

Thanks in advance for any help. My diminishing head of hair is especially thankful!

Body:
You can add the resolution of fetch inside your webpack.config.js file.

new webpack.ProvidePlugin({
  'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
})

Inside your plugins section.
After that, inside your code, just use fetch. You won't need to import it whatsoever. Of course, you need imports-loader and exports-loader.


问:
How to get the current location in Google Maps Android API v2?
Using

```<code>mMap.setMyLocationEnabled(true)
</code>```

can set the myLocation layer enable.

But the problem is how to get the myLocation when the user clicks on the button?
I want to get the longitude and latitude.

答:
I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated.

First declare these 3 variables:

```<code>private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;
</code>```

Define methods:

```<code>private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
</code>```

initGoogleApiClient() is used to initialize GoogleApiClient object

setLocationListener() is used to setup location change listener

removeLocationListener() is used to remove the listener

Call initGoogleApiClient method to start the code working :)  Don't forget to remove the listener (mLocationListener) at the end to avoid memory leak issues.

Body:
Using

mMap.setMyLocationEnabled(true)

can set the myLocation layer enable.

But the problem is how to get the myLocation when the user clicks on the button?
I want to get the longitude and latitude.

Body:
I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated.

First declare these 3 variables:

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

Define methods:

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}

initGoogleApiClient() is used to initialize GoogleApiClient object

setLocationListener() is used to setup location change listener

removeLocationListener() is used to remove the listener

Call initGoogleApiClient method to start the code working :)  Don't forget to remove the listener (mLocationListener) at the end to avoid memory leak issues.


问:
Storing user input in variables
This is a method to get user input and store it in variables.
How should I create a second method to access these vars and print them to the console ?
String "who" is used to specify who is that person for example: Teacher or Student or Parent.</p>

```<code> static void GetInformation(string who)
  {
    Console.WriteLine("Enter the {0} first name: ",who);
    newStudent.firstName = Console.ReadLine();
    Console.WriteLine("Enter the {0} last name: ",who);
    string lastName = Console.ReadLine();
    Console.WriteLine("Enter the {0} birthdate: ",who);
    string birthdate = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 1: ",who);
    string addressLine1 = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 2: ",who);
    string addressLine2 = Console.ReadLine();
    Console.WriteLine("Enter the {0} city: ",who);
    string city = Console.ReadLine();
    Console.WriteLine("Enter the {0} state: ",who);
    string state = Console.ReadLine();
    Console.WriteLine("Enter the {0} post code: ",who);
    string postCode = Console.ReadLine();
    Console.WriteLine("Enter the {0} country: ",who);
    string country = Console.ReadLine();
}
</code>```

答:
As I can see, you're beginner and the thing you want can easily be done with a Class. However, there's another way.
In the beginning of GetInformation(string who) create a new list:

```<code>List<string> list = new List<string>();
</code>```

Then, you can add every string you read from the console in the list:

```<code>list.Add(stringName) //instead of stringName put the variable you want to add
</code>```

In the end of the method call the other method for printing which accepts List<string>

In that method use foreach and print the elements in the List<string>

Title: Storing user input in variables

Body:
This is a method to get user input and store it in variables.
How should I create a second method to access these vars and print them to the console ?
String "who" is used to specify who is that person for example: Teacher or Student or Parent.

 static void GetInformation(string who)
  {
    Console.WriteLine("Enter the {0} first name: ",who);
    newStudent.firstName = Console.ReadLine();
    Console.WriteLine("Enter the {0} last name: ",who);
    string lastName = Console.ReadLine();
    Console.WriteLine("Enter the {0} birthdate: ",who);
    string birthdate = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 1: ",who);
    string addressLine1 = Console.ReadLine();
    Console.WriteLine("Enter the {0} address line 2: ",who);
    string addressLine2 = Console.ReadLine();
    Console.WriteLine("Enter the {0} city: ",who);
    string city = Console.ReadLine();
    Console.WriteLine("Enter the {0} state: ",who);
    string state = Console.ReadLine();
    Console.WriteLine("Enter the {0} post code: ",who);
    string postCode = Console.ReadLine();
    Console.WriteLine("Enter the {0} country: ",who);
    string country = Console.ReadLine();
}

Body:
As I can see, you're beginner and the thing you want can easily be done with a Class. However, there's another way.
In the beginning of GetInformation(string who) create a new list:

List<string> list = new List<string>();

Then, you can add every string you read from the console in the list:

list.Add(stringName) //instead of stringName put the variable you want to add

In the end of the method call the other method for printing which accepts List<string>

In that method use foreach and print the elements in the List<string>


问:
MYSQL Query - Some results don't return
I have a problem im my sql query:

```<code>SELECT table_2.id, SUM(table_2.time + table_4.time + table_6.time + table_8.time + table_10.time + table_12.time) AS total_time, SUM(table_2.connects + table_4.connects + table_6.connects + table_8.connects + table_10.connects + table_12.connects) AS total_connects FROM table_2
  INNER JOIN table_4 ON table_2.id = table_4.id
  INNER JOIN table_6 ON table_2.id = table_6.id
  INNER JOIN table_8 ON table_2.id = table_8.id
  INNER JOIN table_10 ON table_2.id = table_10.id
  INNER JOIN table_12 ON table_2.id = table_12.id
GROUP BY table_2.authid ORDER BY total_time DESC
</code>```

Ok, I have a script that grabs the user IDS and the time they spent and then puts it in mysql tables depending on which forum they have entered. The query above seems to be working fine but only for the users that have entered all forums, because the others that haven't entered in all forums don't return any result.

The ID is always the same, it is the users ID and connects is the number of times the user enters the specific forum.

If you understand my problem and know the answear please let me know, otherwise I'll try to explain better

Thanks

答:
You will need to use outer joins and you will need to use IFNULL or something similar to map the "user wasn't in forum" nulls to zeroes.

```<code>SELECT t2.id,
       SUM(IFNULL(t2.time,      0) + IFNULL(t4.time,      0) +
           IFNULL(t6.time,      0) + IFNULL(t8.time,      0) +
           IFNULL(t10.time,     0) + IFNULL(t12.time,     0)) AS total_time,
       SUM(IFNULL(t2.connects,  0) + IFNULL(t4.connects,  0) +
           IFNULL(t6.connects,  0) + IFNULL(t8.connects,  0) +
           IFNULL(t10.connects, 0) + IFNULL(t12.connects, 0)) AS total_connects
  FROM table_2 AS t2
  LEFT JOIN table_4  AS t4  ON t2.id = t4.id
  LEFT JOIN table_6  AS 76  ON t2.id = t6.id
  LEFT JOIN table_8  AS t8  ON t2.id = t8.id
  LEFT JOIN table_10 AS t10 ON t2.id = t10.id
  LEFT JOIN table_12 AS t12 ON t2.id = t12.id
GROUP BY t2.id ORDER BY total_time DESC
</code>```

This almost works; it does work for all users that visit the forum for which the information is stored in table_2.  To make it work for people who don't visit the 'table_2 forum', the query needs to use the table that defines users and do the outer joins with that table:

```<code>SELECT u.id,
       SUM(IFNULL(t2.time,      0) + IFNULL(t4.time,      0) +
           IFNULL(t6.time,      0) + IFNULL(t8.time,      0) +
           IFNULL(t10.time,     0) + IFNULL(t12.time,     0)) AS total_time,
       SUM(IFNULL(t2.connects,  0) + IFNULL(t4.connects,  0) +
           IFNULL(t6.connects,  0) + IFNULL(t8.connects,  0) +
           IFNULL(t10.connects, 0) + IFNULL(t12.connects, 0)) AS total_connects
  FROM Users         AS u
  LEFT JOIN table_2  AS t2  ON u.id = t2.id
  LEFT JOIN table_4  AS t4  ON u.id = t4.id
  LEFT JOIN table_6  AS 76  ON u.id = t6.id
  LEFT JOIN table_8  AS t8  ON u.id = t8.id
  LEFT JOIN table_10 AS t10 ON u.id = t10.id
  LEFT JOIN table_12 AS t12 ON u.id = t12.id
GROUP BY u.id ORDER BY total_time DESC
</code>```

However, given the symmetry of the table_N tables, I think you should do as Spiny Norman
suggests and redesign your schema so that there is one table that stores the timing and connection values:

```<code>CREATE TABLE ForumUsage
(
    ForumID    INTEGER NOT NULL REFERENCES Forums,
    UserID     INTEGER NOT NULL REFERENCES Users,
    Time       INTEGER NOT NULL,
    Connects   INTEGER NOT NULL
);
</code>```

Then you sum over the entries in that table.

Title: MYSQL Query - Some results don't return

Body:
I have a problem im my sql query:

SELECT table_2.id, SUM(table_2.time + table_4.time + table_6.time + table_8.time + table_10.time + table_12.time) AS total_time, SUM(table_2.connects + table_4.connects + table_6.connects + table_8.connects + table_10.connects + table_12.connects) AS total_connects FROM table_2
  INNER JOIN table_4 ON table_2.id = table_4.id
  INNER JOIN table_6 ON table_2.id = table_6.id
  INNER JOIN table_8 ON table_2.id = table_8.id
  INNER JOIN table_10 ON table_2.id = table_10.id
  INNER JOIN table_12 ON table_2.id = table_12.id
GROUP BY table_2.authid ORDER BY total_time DESC

Ok, I have a script that grabs the user IDS and the time they spent and then puts it in mysql tables depending on which forum they have entered. The query above seems to be working fine but only for the users that have entered all forums, because the others that haven't entered in all forums don't return any result.

The ID is always the same, it is the users ID and connects is the number of times the user enters the specific forum.

If you understand my problem and know the answear please let me know, otherwise I'll try to explain better

Thanks

Body:
You will need to use outer joins and you will need to use IFNULL or something similar to map the "user wasn't in forum" nulls to zeroes.

SELECT t2.id,
       SUM(IFNULL(t2.time,      0) + IFNULL(t4.time,      0) +
           IFNULL(t6.time,      0) + IFNULL(t8.time,      0) +
           IFNULL(t10.time,     0) + IFNULL(t12.time,     0)) AS total_time,
       SUM(IFNULL(t2.connects,  0) + IFNULL(t4.connects,  0) +
           IFNULL(t6.connects,  0) + IFNULL(t8.connects,  0) +
           IFNULL(t10.connects, 0) + IFNULL(t12.connects, 0)) AS total_connects
  FROM table_2 AS t2
  LEFT JOIN table_4  AS t4  ON t2.id = t4.id
  LEFT JOIN table_6  AS 76  ON t2.id = t6.id
  LEFT JOIN table_8  AS t8  ON t2.id = t8.id
  LEFT JOIN table_10 AS t10 ON t2.id = t10.id
  LEFT JOIN table_12 AS t12 ON t2.id = t12.id
GROUP BY t2.id ORDER BY total_time DESC

This almost works; it does work for all users that visit the forum for which the information is stored in table_2.  To make it work for people who don't visit the 'table_2 forum', the query needs to use the table that defines users and do the outer joins with that table:

SELECT u.id,
       SUM(IFNULL(t2.time,      0) + IFNULL(t4.time,      0) +
           IFNULL(t6.time,      0) + IFNULL(t8.time,      0) +
           IFNULL(t10.time,     0) + IFNULL(t12.time,     0)) AS total_time,
       SUM(IFNULL(t2.connects,  0) + IFNULL(t4.connects,  0) +
           IFNULL(t6.connects,  0) + IFNULL(t8.connects,  0) +
           IFNULL(t10.connects, 0) + IFNULL(t12.connects, 0)) AS total_connects
  FROM Users         AS u
  LEFT JOIN table_2  AS t2  ON u.id = t2.id
  LEFT JOIN table_4  AS t4  ON u.id = t4.id
  LEFT JOIN table_6  AS 76  ON u.id = t6.id
  LEFT JOIN table_8  AS t8  ON u.id = t8.id
  LEFT JOIN table_10 AS t10 ON u.id = t10.id
  LEFT JOIN table_12 AS t12 ON u.id = t12.id
GROUP BY u.id ORDER BY total_time DESC

However, given the symmetry of the table_N tables, I think you should do as Spiny Norman
suggests and redesign your schema so that there is one table that stores the timing and connection values:

CREATE TABLE ForumUsage
(
    ForumID    INTEGER NOT NULL REFERENCES Forums,
    UserID     INTEGER NOT NULL REFERENCES Users,
    Time       INTEGER NOT NULL,
    Connects   INTEGER NOT NULL
);

Then you sum over the entries in that table.


问:
AttributeError: 'Tensor' object has no attribute '_keras_history'
I looked for all the "'Tensor' object has no attribute ***" but none seems related to Keras (except for TensorFlow: AttributeError: 'Tensor' object has no attribute 'log10' which didn't help)...

I am making a sort of GAN (Generative Adversarial Networks). Here you can find the structure.

```<code>Layer (type)                     Output Shape          Param #         Connected to
_____________________________________________________________________________
input_1 (InputLayer)             (None, 30, 91)        0
_____________________________________________________________________________
model_1 (Model)                  (None, 30, 1)         12558           input_1[0][0]
_____________________________________________________________________________
model_2 (Model)                  (None, 30, 91)        99889           input_1[0][0]
                                                                       model_1[1][0]
_____________________________________________________________________________
model_3 (Model)                  (None, 1)             456637          model_2[1][0]
_____________________________________________________________________________
</code>```

I pretrained model_2, and model_3. The thing is I pretrained model_2 with list made of 0 and 1, but model_1 return approached values. So i considered rounding the model1_output, with the following code : the K.round() on model1_out.

```<code>import keras.backend as K
[...]
def make_gan(GAN_in, model1, model2, model3):
    model1_out = model1(GAN_in)
    model2_out = model2([GAN_in, K.round(model1_out)])
    GAN_out = model3(model2_out)
    GAN = Model(GAN_in, GAN_out)
    GAN.compile(loss=loss, optimizer=model1.optimizer, metrics=['binary_accuracy'])
    return GAN
[...]
</code>```

I have the following error :

AttributeError: 'Tensor' object has no attribute '_keras_history'

Full traceback :

```<code>Traceback (most recent call last):
  File "C:\Users\Asmaa\Documents\BillyValuation\GFD.py", line 88, in <module>
GAN = make_gan(inputSentence, G, F, D)
  File "C:\Users\Asmaa\Documents\BillyValuation\GFD.py", line 61, in make_gan
GAN = Model(GAN_in, GAN_out)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 88, in wrapper
return func(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1705, in __init__
build_map_of_graph(x, finished_nodes, nodes_in_progress)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1695, in build_map_of_graph
layer, node_index, tensor_index)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1695, in build_map_of_graph
layer, node_index, tensor_index)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1665, in build_map_of_graph
layer, node_index, tensor_index = tensor._keras_history
AttributeError: 'Tensor' object has no attribute '_keras_history'
</code>```

I'm using Python 3.6, with Spyder 3.1.4, on Windows 7. I upgraded TensorFlow and Keras with pip last week.
Thank you for any help provided !

答:
Try this:</p>
```<code>def make_gan(GAN_in, model1, model2, model3):
    model1_out = model1(GAN_in)
    model1_out = Lambda(lambda x: K.round(x), output_shape=...)(model1_out)
    model2_out = model2([GAN_in, model1_out])
    GAN_out = model3(model2_out)
    GAN = Model(GAN_in, GAN_out)
    GAN.compile(loss=loss, optimizer=model1.optimizer,
                metrics=['binary_accuracy'])
    return GAN
</code>```

Body:
I looked for all the "'Tensor' object has no attribute ***" but none seems related to Keras (except for TensorFlow: AttributeError: 'Tensor' object has no attribute 'log10' which didn't help)...

I am making a sort of GAN (Generative Adversarial Networks). Here you can find the structure.

Layer (type)                     Output Shape          Param #         Connected to
_____________________________________________________________________________
input_1 (InputLayer)             (None, 30, 91)        0
_____________________________________________________________________________
model_1 (Model)                  (None, 30, 1)         12558           input_1[0][0]
_____________________________________________________________________________
model_2 (Model)                  (None, 30, 91)        99889           input_1[0][0]
                                                                       model_1[1][0]
_____________________________________________________________________________
model_3 (Model)                  (None, 1)             456637          model_2[1][0]
_____________________________________________________________________________

I pretrained model_2, and model_3. The thing is I pretrained model_2 with list made of 0 and 1, but model_1 return approached values. So i considered rounding the model1_output, with the following code : the K.round() on model1_out.

import keras.backend as K
[...]
def make_gan(GAN_in, model1, model2, model3):
    model1_out = model1(GAN_in)
    model2_out = model2([GAN_in, K.round(model1_out)])
    GAN_out = model3(model2_out)
    GAN = Model(GAN_in, GAN_out)
    GAN.compile(loss=loss, optimizer=model1.optimizer, metrics=['binary_accuracy'])
    return GAN
[...]

I have the following error :

AttributeError: 'Tensor' object has no attribute '_keras_history'

Full traceback :

Traceback (most recent call last):
  File "C:\Users\Asmaa\Documents\BillyValuation\GFD.py", line 88, in <module>
GAN = make_gan(inputSentence, G, F, D)
  File "C:\Users\Asmaa\Documents\BillyValuation\GFD.py", line 61, in make_gan
GAN = Model(GAN_in, GAN_out)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 88, in wrapper
return func(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1705, in __init__
build_map_of_graph(x, finished_nodes, nodes_in_progress)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1695, in build_map_of_graph
layer, node_index, tensor_index)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1695, in build_map_of_graph
layer, node_index, tensor_index)
  File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\topology.py", line 1665, in build_map_of_graph
layer, node_index, tensor_index = tensor._keras_history
AttributeError: 'Tensor' object has no attribute '_keras_history'

I'm using Python 3.6, with Spyder 3.1.4, on Windows 7. I upgraded TensorFlow and Keras with pip last week.
Thank you for any help provided !

Body:
Try this:

def make_gan(GAN_in, model1, model2, model3):
    model1_out = model1(GAN_in)
    model1_out = Lambda(lambda x: K.round(x), output_shape=...)(model1_out)
    model2_out = model2([GAN_in, model1_out])
    GAN_out = model3(model2_out)
    GAN = Model(GAN_in, GAN_out)
    GAN.compile(loss=loss, optimizer=model1.optimizer,
                metrics=['binary_accuracy'])
    return GAN


问:
Check condition in if statement
I have seen code like this:

```<code>$result1 = someFunction();

if ($result1) {
    /* some follow up logic */
}
</code>```

I am not quite sure what does if ($result1) mean, normally when we check condition in if statement, it should be something that can be generated true or false explicitly, so the syntax should be if (true) or if (false), for example, if (1==1) is equivalent to if (true), so how about if ($result1)? $result1 itself doesn't generate true or false.

答:
Have a look at:

PHP: Expressions

PHP: if

PHP: Type Juggling

Excerpt about if statement from documentation:

```<code>if (expr)
    statement
</code>```

Expression (expr) is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

And again from the documentation about expressions:

The simplest yet most accurate way to define an expression is "anything that has a value".

Now, $result1 is an expression, which has a value. So, the expression $result1 will be converted to a boolean value and will be used in the if statement.

Title: Check condition in if statement

Body:
I have seen code like this:

$result1 = someFunction();

if ($result1) {
    /* some follow up logic */
}

I am not quite sure what does if ($result1) mean, normally when we check condition in if statement, it should be something that can be generated true or false explicitly, so the syntax should be if (true) or if (false), for example, if (1==1) is equivalent to if (true), so how about if ($result1)? $result1 itself doesn't generate true or false.

Body:
Have a look at:

PHP: Expressions

PHP: if

PHP: Type Juggling

Excerpt about if statement from documentation:

if (expr)
    statement

Expression (expr) is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

And again from the documentation about expressions:

The simplest yet most accurate way to define an expression is "anything that has a value".

Now, $result1 is an expression, which has a value. So, the expression $result1 will be converted to a boolean value and will be used in the if statement.


问:
Create columns based on the level on another table
This is similar to the question i created

Split table into different level columns

I have two tables one which indicates the level of SETTLUNIT and one the raw data. By comparing one table i have to create 3 new columns .

like

Table 1 :

Table 2 :

By seeing the level from table 1 i need to add 3 columns in table 2.

If it is level 2 i need to bring level 1 and level 2 and so on.

Output: Row 1 has only level 1 and level 2 because it has level as 2 in master level table.

Could you please help me how to create a query . I tried with UNION but some how not getting the required output

答:
You cannot - you do not have any way of knowing how the hierarchy is organised and which parent is associated with which children.

Is it:

```<code>SU_DC_1
 ├ SU_SP_1
 │ ├ SU_PZ_012
 │ └ SU_PZ_1
 └ SU_SP_2
</code>```

or:

```<code>SU_DC_1
 ├ SU_SP_1
 │ └ SU_PZ_012
 └ SU_SP_2
   └ SU_PZ_1
</code>```

or:

```<code>SU_DC_1
 ├ SU_SP_1
 │ └ SU_PZ_1
 └ SU_SP_2
   └ SU_PZ_012
</code>```

or:

```<code>SU_DC_1
 ├ SU_SP_1
 └ SU_SP_2
   ├ SU_PZ_012
   └ SU_PZ_1
</code>```

And with more identifiers the number of possible hierarchical relationships is just going to increase exponentially.

You need to store the hierarchical relationship between the levels and then you could get the output you require - at the moment there is not enough information to do this.

Body:
You cannot - you do not have any way of knowing how the hierarchy is organised and which parent is associated with which children.

Is it:

SU_DC_1
 ├ SU_SP_1
 │ ├ SU_PZ_012
 │ └ SU_PZ_1
 └ SU_SP_2

or:

SU_DC_1
 ├ SU_SP_1
 │ └ SU_PZ_012
 └ SU_SP_2
   └ SU_PZ_1

or:

SU_DC_1
 ├ SU_SP_1
 │ └ SU_PZ_1
 └ SU_SP_2
   └ SU_PZ_012

or:

SU_DC_1
 ├ SU_SP_1
 └ SU_SP_2
   ├ SU_PZ_012
   └ SU_PZ_1

And with more identifiers the number of possible hierarchical relationships is just going to increase exponentially.

You need to store the hierarchical relationship between the levels and then you could get the output you require - at the moment there is not enough information to do this.


答:
you can use:

```<code>x = map(lambda x: float(x), str.split(<line>, ',\t')
</code>```

To describe this:

split the line of string by tab (or whatever)

feed the subsequent array into a map function, which applies the function in the first argument to every item in the second

the first argument to the map function is a lambda function which simply takes a string in and returns a float

Title: Convert a list of strings to array of floats numpy Python

Body:
This is a list in which every line contains one string. For example '1,         -40.,          -3.' is one string. i want to firstly divide the list to columns with numpy and then convert the strings to floats or vice versa. Is that possible? I tried removing the spaces but with no luck.
The end result will be a matrix with 3 columns and x lines in which all elements are floats. Is something like that possible?

  1,         -40.,          -3.
  2,         -40.,          -6.
  3,         -40.,          -9.
  4,         -40.,         -12.
  5,         -40.,         -15.
  6,         -40.,         -18.
  7,         -40.,         -21.
  8,         -40.,         -24.
  9,         -40.,         -27.
 10,         -40.,           0.
 11,         -40.,         -30.
 12,         -36.,         -30.
 13,         -34.,         -30.
 14,         -30.,         -30.
 15,         -28.,         -30.
 16,         -24.,         -30.
 17,         -22.,         -30.
 18,         -18.,         -30.
 19,         -16.,         -30.
 20,         -12.,         -30.
 21,         -10.,         -30.
 22,          -6.,         -30.
 23,          -4.,         -30.
 24,           0.,         -30.
 25,           4.,         -30.
 26,           6.,         -30.
 27,          10.,         -30.
 28,          12.,         -30.
 29,          16.,         -30.
 30,          18.,         -30.
 31,          22.,         -30.
 32,          24.,         -30.
 33,          28.,         -30.
 34,          30.,         -30.
 35,          34.,         -30.
 36,          36.,         -30.
 37,          40.,         -30.
 38,          40.,         -27.
 39,          40.,         -24.
 40,          40.,         -21.
 41,          40.,         -18.
 42,          40.,         -15.
 43,          40.,         -12.
 44,          40.,          -9.
 45,          40.,          -6.
 46,          40.,          -3.
 47,          40.,           0.
 48,  -37.0502472,  -3.57497835
 49,  -34.6275177,  -6.06847525
 50,  -31.1389275,  -9.11990738
 51,  -27.3827724,  -11.8351984
 52,  -24.4094028,  -13.6369238
 53,  -20.2638969,  -15.7096758
 54,   -17.038496,  -17.0073357
 55,  -12.6125698,  -18.3830872
 56,    -8.078269,  -19.3431015
 57,  -4.62983418,  -19.7851849
 58,           0.,         -20.
 59,   4.62983418,  -19.7851849
 60,     8.078269,  -19.3431015
 61,   12.6125698,  -18.3830872

Body:
you can use:

x = map(lambda x: float(x), str.split(<line>, ',\t')

To describe this:

split the line of string by tab (or whatever)

feed the subsequent array into a map function, which applies the function in the first argument to every item in the second

the first argument to the map function is a lambda function which simply takes a string in and returns a float


问:
How to set text-decoration: underline only for specific content
I have a input tag and where I am getting input value like this.

```<code>input.value += " " + value + ";" ;
</code>```

In my css I have text-decoration: underline; but here underline is coming in "space" and ";" both the place. Is there any way I can decorate only text part.

My Code is like :

```<code>var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '<div id="triggers">' + '<img class="trigger" onclick ="deleteValue()" src="css/clearT.png" id="cross" />' + '<img class="trigger" src="css/combo_arrow.png" onclick = "openingList()" id="arrow" />' + '</div>' +
    '<ul id="myUL" hidden=true>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";
}
</code>```

Current it is coming like this.

What exactly I want here

答:
PURE CSS

For example:

```<code>text-decoration-skip: none;
text-decoration-skip: objects;
text-decoration-skip: spaces;
// etc ...
</code>```

Full documentation here:
MDN - text-decoration-skip

Body:
I have a input tag and where I am getting input value like this.

input.value += " " + value + ";" ;

In my css I have text-decoration: underline; but here underline is coming in "space" and ";" both the place. Is there any way I can decorate only text part.

My Code is like :

var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '
' + '' + '' + '
' +
    '
' + '
' + '' + '
' + '
';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";
}

Current it is coming like this.

What exactly I want here

Body:
PURE CSS

For example:

text-decoration-skip: none;
text-decoration-skip: objects;
text-decoration-skip: spaces;
// etc ...

Full documentation here:
MDN - text-decoration-skip


问:
Return value after successful assert
I have a little problem with a function used for testing. Here is my test method:

```<code>public static List<FieldError> proofFields(final List<String> fieldNames, final List<FieldError> errors, boolean fieldsAbsent){
    List<FieldError> foundFields = errors.stream().filter(fieldError -> fieldNames.contains(fieldError.getField())).collect(toList());
    if(fieldsAbsent){
        assertTrue(foundFields.isEmpty());
    } else {
        assertTrue(fieldNames.size() == foundFields.size());
    }
    return foundFields;
}
</code>```

It should check, if one list is (partially) contained in the other.

I would like to return the result, no matter if the test was successful or not. Is there a way to do this or does assertTrue/assertFalse always exit immediately?

答:
You can't have it both ways. You can't have your cake and eat it.

Either you are using one of the many JUnit 'asserts` - or you have code that doesn't throw exceptions.

Meaning: it is the nature of assert() to throw when its condition is not met.

Thus the answer: you have to get clear on your requirements. If you want that test to throw in certain situations, then keep the asserts in. If you want to return results always, then you remove those calls.

Title: Return value after successful assert

Body:
I have a little problem with a function used for testing. Here is my test method:

public static List<FieldError> proofFields(final List<String> fieldNames, final List<FieldError> errors, boolean fieldsAbsent){
    List<FieldError> foundFields = errors.stream().filter(fieldError -> fieldNames.contains(fieldError.getField())).collect(toList());
    if(fieldsAbsent){
        assertTrue(foundFields.isEmpty());
    } else {
        assertTrue(fieldNames.size() == foundFields.size());
    }
    return foundFields;
}

It should check, if one list is (partially) contained in the other.

I would like to return the result, no matter if the test was successful or not. Is there a way to do this or does assertTrue/assertFalse always exit immediately?


问:
Clash when exporting excel file using "xlsx" and "openxlsx" packages in R
I have a data which has a size similar to "a" below

```<code>library(openxlsx)
a <- list()
names(a) <- paste("sheet", seq_along(fulldata), sep="_")  ### name for each sheet
for (i in 1:172) {
a[[i]] <- matrix(i,30,60)
}

write.xlsx(a, "a.xlsx")
</code>```

If I run the code above, few seconds later, R closes automatically.

```<code>library(xlsx)
options(java.parameters = "-Xmx4000m")
a <- list()
for (i in 1:172) {
a[[i]] <- matrix(i,30,60)
}
n <- paste("sheet", seq_along(fulldata), sep="_") ### name for each sheet

for (i in 1:172) {
write.xlsx(a[[i]], "c.xlsx", sheetName=n[[i]], append=TRUE)
}
</code>```

If I run the code above, after 10 minutes, it returns an error about lack of memory.
I used

```<code>options(java.parameters = "-Xmx4000m")
</code>```

to increase the memory to be used but still, it says lack of memory.

Both of them works fine with small data but it doens't work when I try to export 172 sheets all at once. I need all the 172 sheets to be included in one excel file.

答:
Creating the sheets using lapply may help alleviate the memory issue.</p>

```<code>library(xlsx)

# Create the list of matrices
a <- list()
for (i in 1:172) {
  a[[i]] <- matrix(i,30,60)
}

# Set names for the matrices
names(a) <- seq_along(a)

# Create a workbook object
wb <- createWorkbook()

# Add each matrix to it's own worksheet inside of the workbook
lapply(seq_along(a), function(matrices, matrix.names, i){
                       ws <- createSheet(wb, matrix.names[[i]])
                       addDataFrame(matrices[[i]], ws)
                     }, matrices = a, matrix.names = names(a))

# Set the file path to save the workbook to
(output.path <- file.path(tempdir(), "output.xlsx"))

# Save the workbook
saveWorkbook(wb, output.path)
</code>```

Body:
I have a data which has a size similar to "a" below

library(openxlsx)
a <- list()
names(a) <- paste("sheet", seq_along(fulldata), sep="_")  ### name for each sheet
for (i in 1:172) {
a[[i]] <- matrix(i,30,60)
}

write.xlsx(a, "a.xlsx")

If I run the code above, few seconds later, R closes automatically.

library(xlsx)
options(java.parameters = "-Xmx4000m")
a <- list()
for (i in 1:172) {
a[[i]] <- matrix(i,30,60)
}
n <- paste("sheet", seq_along(fulldata), sep="_") ### name for each sheet

for (i in 1:172) {
write.xlsx(a[[i]], "c.xlsx", sheetName=n[[i]], append=TRUE)
}

If I run the code above, after 10 minutes, it returns an error about lack of memory.
I used

options(java.parameters = "-Xmx4000m")

to increase the memory to be used but still, it says lack of memory.

Both of them works fine with small data but it doens't work when I try to export 172 sheets all at once. I need all the 172 sheets to be included in one excel file.

Body:
Creating the sheets using lapply may help alleviate the memory issue.

library(xlsx)

# Create the list of matrices
a <- list()
for (i in 1:172) {
  a[[i]] <- matrix(i,30,60)
}

# Set names for the matrices
names(a) <- seq_along(a)

# Create a workbook object
wb <- createWorkbook()

# Add each matrix to it's own worksheet inside of the workbook
lapply(seq_along(a), function(matrices, matrix.names, i){
                       ws <- createSheet(wb, matrix.names[[i]])
                       addDataFrame(matrices[[i]], ws)
                     }, matrices = a, matrix.names = names(a))

# Set the file path to save the workbook to
(output.path <- file.path(tempdir(), "output.xlsx"))

# Save the workbook
saveWorkbook(wb, output.path)


问:
Create Window larger than desktop (display resolution)
I need to resize a window larger than screen resolution or size of desktop, programmatically & preferably also manually.

Since MS-Windows XP/Vista disallows a window size larger than screen, does anybody have any ideas to work around this limitation?

I trying to make pan effect on a laptop to give me more space to work. An older laptop with a smaller LCD size did have such a feature.

See this:
http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Windows/98/Q_21832063.html

答:
ok, I did try use keystrokes to move, resize windows. But system will automatically move windows back to visible region of desktop in my XP.
I also tried SetWindowPos API, and no helps.
The best chance will be to write a Video driver, but it may need more study.
The 360 desktop claims you can expand desktop horizontally.
But actually it just pan the current desktop in a virtual wider space. Any windows inside still have the size limitation of no larger than your screen resolution.

Video driver set the screen resolution(yes, have to compatibile to lcd/crt screen capability), and Windows did limit window-size by this thresholds.
I just want to work around in user space API.

OwnerDisplayName: Nelson


问:
Notification system jQuery, PHP, and MySQL
I'm trying to develop a notification system using jQuery and PHP. So I've created a new table in the database where I'm going to store all the new notifications. Using jQuery I've been able to show an alert (bubble icon) showing the number of new lines added to the database, but I'm now stuck because I don't really know how to update the database (fire update.php file) when I click the icon (.icon-bell) which does activate a drop-down menu.

This is the jQuery script I've added to the index page

```<code><script type="text/javascript">
    $(document).ready(function(){
        $("#datacount").load("select.php");
        setInterval(function(){
            $("#datacount").load('select.php')
        }, 20000);
    });
</script>
</code>```

This is the HTML code in the index page

```<code><li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
        <i class="icon-bell">
        </i>
        <span class="badge badge-success"><div id="datacount">
            </div>
        </span>
    </a>
    <ul class="dropdown-menu" >
        <li class="external">
            <h3>
                <span class="bold">12 pending</span>
                notifications
            </h3>
            <a href="page_user_profile_1.html">view all</a>
        </li>
        <li>
            <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
                <li>
                    <a href="javascript:;">
                        <span class="time">just now</span>
                        <span class="details">
                            <span class="label label-sm label-icon label-success">
                                <i class="fa fa-plus">
                                </i>
                            </span> New user registered. </span>
                    </a>
                </li>
            </ul>
        </li>
    </ul>
</li>
</code>```

This is the select.php file

```<code><?php
$sql = "SELECT * from tbl_noti where status = 'unread'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>
</code>```

This is the update.php file

```<code><?php
$sql = "update tbl_noti set status = 'read'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>
</code>```

答:
You can use PHP + Ajax to accomplish this task. I have created a simple notification system and you can easily clone it from GitHub(https://github.com/shahroznawaz/php-notifications).

let's create an index.php file and put the following code. it will create a form. all the data will get by ajax call and updated in the view.

```<code><!DOCTYPE html>

<html>

<head>

 <title>Notification using PHP Ajax Bootstrap</title>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

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

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>

 <br /><br />

 <div class="container">

  <nav class="navbar navbar-inverse">

   <div class="container-fluid">

    <div class="navbar-header">

     <a class="navbar-brand" href="#">PHP Notification Tutorial</a>

    </div>

    <ul class="nav navbar-nav navbar-right">

     <li class="dropdown">

      <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="label label-pill label-danger count" style="border-radius:10px;"></span> <span class="glyphicon glyphicon-bell" style="font-size:18px;"></span></a>

      <ul class="dropdown-menu"></ul>

     </li>

    </ul>

   </div>

  </nav>

  <br />

  <form method="post" id="comment_form">

   <div class="form-group">

    <label>Enter Subject</label>

    <input type="text" name="subject" id="subject" class="form-control">

   </div>

   <div class="form-group">

    <label>Enter Comment</label>

    <textarea name="comment" id="comment" class="form-control" rows="5"></textarea>

   </div>

   <div class="form-group">

    <input type="submit" name="post" id="post" class="btn btn-info" value="Post" />

   </div>

  </form>

 </div>

</body>

</html>
</code>```

Now create ajax calls like this:

```<code><script>

$(document).ready(function(){

// updating the view with notifications using ajax

function load_unseen_notification(view = '')

{

 $.ajax({

  url:"fetch.php",
  method:"POST",
  data:{view:view},
  dataType:"json",
  success:function(data)

  {

   $('.dropdown-menu').html(data.notification);

   if(data.unseen_notification > 0)
   {
    $('.count').html(data.unseen_notification);
   }

  }

 });

}

load_unseen_notification();

// submit form and get new records

$('#comment_form').on('submit', function(event){
 event.preventDefault();

 if($('#subject').val() != '' && $('#comment').val() != '')

 {

  var form_data = $(this).serialize();

  $.ajax({

   url:"insert.php",
   method:"POST",
   data:form_data,
   success:function(data)

   {

    $('#comment_form')[0].reset();
    load_unseen_notification();

   }

  });

 }

 else

 {
  alert("Both Fields are Required");
 }

});

// load new notifications

$(document).on('click', '.dropdown-toggle', function(){

 $('.count').html('');

 load_unseen_notification('yes');

});

setInterval(function(){

 load_unseen_notification();;

}, 5000);

});

</script>
</code>```

You also need to fetch all the records from database and update the status for the notification viewd. create fetch.php file and add the following code:

```<code><?php

include('connect.php');

if(isset($_POST['view'])){

// $con = mysqli_connect("localhost", "root", "", "notif");

if($_POST["view"] != '')

{
   $update_query = "UPDATE comments SET comment_status = 1 WHERE comment_status=0";
   mysqli_query($con, $update_query);
}

$query = "SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5";
$result = mysqli_query($con, $query);
$output = '';

if(mysqli_num_rows($result) > 0)
{

while($row = mysqli_fetch_array($result))

{

  $output .= '
  <li>
  <a href="#">
  <strong>'.$row["comment_subject"].'</strong><br />
  <small><em>'.$row["comment_text"].'</em></small>
  </a>
  </li>

  ';
}
}

else{
    $output .= '<li><a href="#" class="text-bold text-italic">No Noti Found</a></li>';
}

$status_query = "SELECT * FROM comments WHERE comment_status=0";
$result_query = mysqli_query($con, $status_query);
$count = mysqli_num_rows($result_query);

$data = array(
   'notification' => $output,
   'unseen_notification'  => $count
);

echo json_encode($data);
}
?>
</code>```

Now you will be able to see the notification in navigation bar like this:

when you click the dropdown the status of views notification will update and count will disappear.

Body:
I'm trying to develop a notification system using jQuery and PHP. So I've created a new table in the database where I'm going to store all the new notifications. Using jQuery I've been able to show an alert (bubble icon) showing the number of new lines added to the database, but I'm now stuck because I don't really know how to update the database (fire update.php file) when I click the icon (.icon-bell) which does activate a drop-down menu.

This is the jQuery script I've added to the index page

This is the HTML code in the index page

                12 pending
                notifications

            view all

                        just now

                             New user registered.

This is the select.php file

<?php
$sql = "SELECT * from tbl_noti where status = 'unread'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>

This is the update.php file

<?php
$sql = "update tbl_noti set status = 'read'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>

Body:
You can use PHP + Ajax to accomplish this task. I have created a simple notification system and you can easily clone it from GitHub(https://github.com/shahroznawaz/php-notifications).

let's create an index.php file and put the following code. it will create a form. all the data will get by ajax call and updated in the view.

<!DOCTYPE html>

<html>

<head>

 <title>Notification using PHP Ajax Bootstrap</title>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

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

 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>

 <br /><br />

 <div class="container">

  <nav class="navbar navbar-inverse">

   <div class="container-fluid">

    <div class="navbar-header">

     <a class="navbar-brand" href="#">PHP Notification Tutorial</a>

    </div>

    <ul class="nav navbar-nav navbar-right">

     <li class="dropdown">

      <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="label label-pill label-danger count" style="border-radius:10px;"></span> <span class="glyphicon glyphicon-bell" style="font-size:18px;"></span></a>

      <ul class="dropdown-menu"></ul>

     </li>

    </ul>

   </div>

  </nav>

  <br />

  <form method="post" id="comment_form">

   <div class="form-group">

    <label>Enter Subject</label>

    <input type="text" name="subject" id="subject" class="form-control">

   </div>

   <div class="form-group">

    <label>Enter Comment</label>

    <textarea name="comment" id="comment" class="form-control" rows="5"></textarea>

   </div>

   <div class="form-group">

    <input type="submit" name="post" id="post" class="btn btn-info" value="Post" />

   </div>

  </form>

 </div>

</body>

</html>

Now create ajax calls like this:

<script>

$(document).ready(function(){

// updating the view with notifications using ajax

function load_unseen_notification(view = '')

{

 $.ajax({

  url:"fetch.php",
  method:"POST",
  data:{view:view},
  dataType:"json",
  success:function(data)

  {

   $('.dropdown-menu').html(data.notification);

   if(data.unseen_notification > 0)
   {
    $('.count').html(data.unseen_notification);
   }

  }

 });

}

load_unseen_notification();

// submit form and get new records

$('#comment_form').on('submit', function(event){
 event.preventDefault();

 if($('#subject').val() != '' && $('#comment').val() != '')

 {

  var form_data = $(this).serialize();

  $.ajax({

   url:"insert.php",
   method:"POST",
   data:form_data,
   success:function(data)

   {

    $('#comment_form')[0].reset();
    load_unseen_notification();

   }

  });

 }

 else

 {
  alert("Both Fields are Required");
 }

});

// load new notifications

$(document).on('click', '.dropdown-toggle', function(){

 $('.count').html('');

 load_unseen_notification('yes');

});

setInterval(function(){

 load_unseen_notification();;

}, 5000);

});

</script>

You also need to fetch all the records from database and update the status for the notification viewd. create fetch.php file and add the following code:

<?php

include('connect.php');

if(isset($_POST['view'])){

// $con = mysqli_connect("localhost", "root", "", "notif");

if($_POST["view"] != '')

{
   $update_query = "UPDATE comments SET comment_status = 1 WHERE comment_status=0";
   mysqli_query($con, $update_query);
}

$query = "SELECT * FROM comments ORDER BY comment_id DESC LIMIT 5";
$result = mysqli_query($con, $query);
$output = '';

if(mysqli_num_rows($result) > 0)
{

while($row = mysqli_fetch_array($result))

{

  $output .= '
  <li>
  <a href="#">
  <strong>'.$row["comment_subject"].'</strong><br />
  <small><em>'.$row["comment_text"].'</em></small>
  </a>
  </li>

  ';
}
}

else{
    $output .= '<li><a href="#" class="text-bold text-italic">No Noti Found</a></li>';
}

$status_query = "SELECT * FROM comments WHERE comment_status=0";
$result_query = mysqli_query($con, $status_query);
$count = mysqli_num_rows($result_query);

$data = array(
   'notification' => $output,
   'unseen_notification'  => $count
);

echo json_encode($data);
}
?>

Now you will be able to see the notification in navigation bar like this:

when you click the dropdown the status of views notification will update and count will disappear.


问:
performance with left join and include max in the query with values null
The data of the table exceeds 7 billion.
I want to display the max of entryDate affiliation for each participant and i want to include the null values so i used left join but the query takes long minute. Anyway it gives me the expected results.
Could anyone has a better idea or another better solution to fix the performance?</p>

```<code>Select ParticipantID,MaxDate
    From dbo.Participant Par
    LEFT JOIN dbo.Affiliation Aff
    ON AFF.ParticipantID=Par.ParticipantID
    LEFT JOIN (
                               SELECT              AFF.AffiliationID,
                                                      MAX(EntryDate) as MaxDate
                               FROM                dbo.Affiliation

                               GROUP BY            AFF.AffiliationID

                    )AS AFF1
           ON           AFF1.AffiliationID = AFF.AffiliationID
                        AND AFF1.MaxDate = AFF.EntryDate
</code>```

答:
@llyas There could be lot more considerations if you have xml show plan on or include actual execution plan and check for subtree cost

Anyways, you can use this query by using row_num function

```<code>WITH par
AS (
    SELECT ParticipantID
        ,EntryDate AS MaxDate
        ,ROW_NUMBER() OVER (
            PARTITION BY AffiliationID ORDER BY ENTRYDATE DESC
            ) rn
    FROM dbo.Participant Par
    LEFT JOIN dbo.Affiliation Aff
        ON AFF.ParticipantID = Par.ParticipantID
    )
SELECT Participantid
    ,Maxdate
WHERE rn = 1
</code>```

Body:
The data of the table exceeds 7 billion.
I want to display the max of entryDate affiliation for each participant and i want to include the null values so i used left join but the query takes long minute. Anyway it gives me the expected results.
Could anyone has a better idea or another better solution to fix the performance?

Select ParticipantID,MaxDate
    From dbo.Participant Par
    LEFT JOIN dbo.Affiliation Aff
    ON AFF.ParticipantID=Par.ParticipantID
    LEFT JOIN (
                               SELECT              AFF.AffiliationID,
                                                      MAX(EntryDate) as MaxDate
                               FROM                dbo.Affiliation

                               GROUP BY            AFF.AffiliationID

                    )AS AFF1
           ON           AFF1.AffiliationID = AFF.AffiliationID
                        AND AFF1.MaxDate = AFF.EntryDate

Body:
@llyas There could be lot more considerations if you have xml show plan on or include actual execution plan and check for subtree cost

Anyways, you can use this query by using row_num function

WITH par
AS (
    SELECT ParticipantID
        ,EntryDate AS MaxDate
        ,ROW_NUMBER() OVER (
            PARTITION BY AffiliationID ORDER BY ENTRYDATE DESC
            ) rn
    FROM dbo.Participant Par
    LEFT JOIN dbo.Affiliation Aff
        ON AFF.ParticipantID = Par.ParticipantID
    )
SELECT Participantid
    ,Maxdate
WHERE rn = 1