问:
Tips and tricks to increase productivity / efficiency with Team Foundation Server
I have to use Team Foundation Server 2010 at my company and I'm not very happy with it.
There are so many features or just default behavior I'd expect from a CVS that TFS seems to lack (compared to svn, git or perforce, which I have experience with), so my question is: which tricks do you know, which hidden features are out there to make TFS easier to use / more convenient?

Perhaps I should elaborate a bit and list what I think could be better:

The default check-in action when associated with a task is "resolve", though in 99% of all check-ins, I only want to "associate" my commit with the task. There's only 1 commit (the last) that "resolves" the task, so why is that the default? Can I change that?

In the check-in dialog, when double-clicking a file, Notepad is launched and shows the contents of the file. Notepad. Seriously? What about the Visual Studio editor? Anyway, I'd like to see the differences to review the changes I've made, not the contents of the file. The diff tool is hidden in a submenu. This might seem trivial, but when I have to check 10+ files it's just annoying to always right-click, open submenu, click to diff.

The diff tool. Merging with it isn't really straightforward, also the conflict detection mechanism is somewhat lacking. The (Tortoise-)SVN / Git merge tools or that of Perforce are way better here.

Speed. Creating a new file, opening a file for the first time, comparing a file with a previous version etc takes forever (that is, 3-10+ seconds). Our TFS server is in-house and has absolutely no load - also why does Visual Studio have to contact the TFS server when I just create a new file (which I might not even check in)? Is there perhaps an option to turn that off?

Readonly files. All files are read-only when checked-in and become writeable when edited for the first time. This is really annyoing when the application crashes because of that. Windows Azure for example modifies a web.config file and fails whenever I check out because the file is read-only then.

These are just the most prominent things that I think are really annoying and unnecessary.
I didn't have the pleasure to branch and merge yet, but from what I've heard so far it won't be very enjoyable as well...

So again: If you know some tricks, settings, featuers that make working with TFS less inconvenient, please share them.

答:
1) is customizable if you reconfigure the work items.  (You can also change any combination of fields/states/available values/etc.)

2) is a pain, but if you use the dockable "Pending Changes" window instead then it'll open the file in the editor.  I suspect this is a drawback of the Checkin dialogue being modal.

3) you can customize - the option's a little tucked away, but it's on  Tools/Options dialogue under Source Control/Visual Studio Team Foundation Server/Configure User Tools.  Some third party tools (like BeyondCompare) have pages on their website with details of how to configure them with VS.

4) I've not seen the speed problems, although I do agree about the overhead on creating a file.  Not sure if that's configurable.


来源: stackexchange

问:
Facebook Messaging API login permissions
What are Item for simple chat bot developed Facebook messaging API?  My app just respond to the text message send by a Facebook user. I want to make my chatbot public but Facebook requires to add some items (permissions). Could you please help me out</p>

答: You need manage_pages and pages_messaging permissions. You also need to submit your bot for approval in the 'Messenger' tab of your app console.

ContentLicense: CC BY-SA 3.0


问:
How to set working directory in R using command prompt?
I am trying to set working directory of R as the newly made folder by my project!
So I want to run a command through cmd(command prompt) to make it happen.

Already tried
$Rscript setwd("path")
but didn't work!!!!!!

答:
Two ways:

A) Set the environment variable R_HOME

In Ubuntu:

sudo nano /etc/environment

Add the line: R_HOME="my/working/directory"

B) Put it in the file ~/.Rprofile which runs when R starts up

sudo nano ~/.Rprofile

Add the line setwd("/my/working/directory")


问:
Find the position inside this Yii 2 query
I have this following Yii 2 query

```<code>$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();
</code>```

So imagine this query was an array. Everything found by this query has an "id" attribute.

Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.

Currently, I'm using this code.

```<code>foreach ($find as $t) {
    $arr[] = $t->id;

    if ($t->id == $id) {
        break;
    }
}

$key = count($arr);

return $key;
</code>```

However, this code is vany wayow on a 100k+ result query.

Is there anyway to speed this up?

答:
You could get the result as an array  (instead of object) as

```<code>$find = People::find()->where(['c_id' => $c_id])
        ->orderBy('totals DESC, id DESC')
        ->asArray()
        ->all();
</code>```

then you could find your value using array_search()

```<code>$my_index =  array_search($id,$find);
</code>```

but for 100k+  you should find using a direct select in db...instead tha looping on php or load all in php and scan with array_search()

ContentLicense: CC BY-SA 4.0

Body:
I have this following Yii 2 query

$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();

So imagine this query was an array. Everything found by this query has an "id" attribute.

Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.

Currently, I'm using this code.

foreach ($find as $t) {
    $arr[] = $t->id;

    if ($t->id == $id) {
        break;
    }
}

$key = count($arr);

return $key;

However, this code is vany wayow on a 100k+ result query.

Is there anyway to speed this up?

Body:
You could get the result as an array  (instead of object) as

$find = People::find()->where(['c_id' => $c_id])
        ->orderBy('totals DESC, id DESC')
        ->asArray()
        ->all();

then you could find your value using array_search()

$my_index =  array_search($id,$find);

but for 100k+  you should find using a direct select in db...instead tha looping on php or load all in php and scan with array_search()


问:
What is the difference between USPS label and postage paid label

Is getting label using USPS api such as "USPS TRACKING (https://www.usps.com/business/web-tools-apis/usps-tracking-v3-3.htm)" any different than postage paid label obtained from 3rd parties such as endicia.com, stamps.com?

Is it possible to purchase prepaid postage on usps.com website, then calling the USPS label api to generate postage paid label? I mean when we call the API to generate the label, appropriate amount to be deducted from my USPS account.

I dont understand the use of the label generated by USPS API. I mean, I have activated my account at USPS and now working on production server. Now if I generate any label using the API (https://www.usps.com/business/web-tools-apis/usps-tracking-v3-3.htm), and generate a label. I didn't see any data in my history at online account. I mean, this generated label is of no value? or still my account is not activated? as I think, i have not yet done this -

reference pdf:Development-Guide-v3-1d.pdf

Step 7: Receive Printer Approval from ICCC Implementing the Delivery
Confirmation and Electronic Merchandise Return Service with Delivery
Confirmation APIs requires this additional interim step. The NCSC will
review your labels within two business days. If the labels fail the
certification test, the NCSC will contact the person listed on the
submission form directly. If the labels pass, you will be notified by
the Internet Customer Care Center and you will be able to send XML
transactions using your “live” data and receive “live” responses. Once
you are approved to generate “live” labels from the production server,
and you need to print additional test labels for any reason, be sure
to use the “Sample” XML request. Otherwise, the USPS will send a
manifest of the PIC numbers issued to the USPS Postal Tracking System
and will be looking for the Delivery Confirmation labels to scan.

Does, receiving "Printer Approval" will solve my issue?

答:
Labels generated using the API DeliveryConfirmationV4 do not include postage.  Per the documentation,

Please note that the API labels are printed without postage. Postage
  must be purchased and applied separately.

See https://www.usps.com/business/web-tools-apis/delivery-confirmation-domestic-shipping-label-api.pdf


问:
Vertical align of different buttons inside a div
I have a bar with some buttons:

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
      margin-bottom: 10px;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>

<div class="Languages">
    <button class="Type1" data-id="1">English</button>
    <button class="Type1" data-id="1">French</button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>
</div>

 <div class="Languages">
    <button class="Type1" data-id="1"></button>
    <button class="Type1" data-id="1"></button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>
</div>  </code>```

The first buttons fill the vertical space, and I want the second ones to be vertically centered. But I can't.

This has something to do with the text inside the buttons and the vertical align, with texts the buttons have a different vertical align that without them.

Does anyone know how to center vertically the second ones, with or without text, and without using flexbox?

答:
Just use display: flex on container:

```<code>.Languages {
  position: relative;
  padding-left: 40px;
  width: 100%;
  height: 62px;
  background-color: turquoise;

  /*Use flex and its property align-items to vertical-center*/
  display: flex;
  align-items: center;
}
</code>```

I think this is one of my favourite flex guide.

Body:
I have a bar with some buttons:

    .Languages {
      position: relative;
      padding-left: 40px;
      width: 100%;
      height: 62px;
      background-color: turquoise;
      margin-bottom: 10px;
    }
    .Type1 {
      position: relative;
      height: 100%;
      width: 100px;
      font-size: 18px;
      margin-right: 10px;
      line-height: 62px;
      box-sizing: border-box;
      background-color: tomato;
      border: 0;
      padding: 0;
    }

    .Type2 {
      position: relative;
      width: 10px;
      border-bottom: 1px solid green;
      margin-left: 5px;
      cursor: pointer;
      background-color: tomato;
      border: 0;
      padding: 0;
      vertical-align: middle;
    }

    .a {
      height: 5px;
    }

    .b {
      height: 25px;
    }

    .c {
      height: 45px;
    }

    .d {
      height: 60px;
    }

    <button class="Type1" data-id="1">English</button>
    <button class="Type1" data-id="1">French</button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>

    <button class="Type1" data-id="1"></button>
    <button class="Type1" data-id="1"></button>
    <button class="Type2 a"></button>
    <button class="Type2 b"></button>
    <button class="Type2 c"></button>
    <button class="Type2 d"></button>

The first buttons fill the vertical space, and I want the second ones to be vertically centered. But I can't.

This has something to do with the text inside the buttons and the vertical align, with texts the buttons have a different vertical align that without them.

Does anyone know how to center vertically the second ones, with or without text, and without using flexbox?

Body:
Just use display: flex on container:

.Languages {
  position: relative;
  padding-left: 40px;
  width: 100%;
  height: 62px;
  background-color: turquoise;

  /*Use flex and its property align-items to vertical-center*/
  display: flex;
  align-items: center;
}

I think this is one of my favourite flex guide.


问:
How do I get the size of a directory in C?
Is there a POSIX function that will give me the size of a directory (including all sub-folders), roughly equivalent to "du -s somepath"?

答:
There is no ready-made function, so you will have to make your own. You may look at the source code of the GNU implemenation of du as an example (see http://www.gnu.org/prep/ftp.html for a list of places to download from). It is in the coreutils package.

The crucial Posix calls are probably opendir, readdir, closedir, and stat.

OwnerDisplayName: therefromhere

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: therefromhere


问:
VBScript to shutdown Windows when a process ends?
I have a program that scans through data at the end of the night on some occasions.  On those occasions, I would like to run a VBScript that will watch for that program to close, and when it does, will shut down Windows.

I created a .BAT file that runs the program and then shuts Windows down, but I don't always need to shutdown when I finish using the program.

So I would like to use the scanning program, and if, at the end of the night, I am ready to leave, but the program is still scanning, I would to open the VBScript that will watch for my scanning program to close.

Is this possible?

```<code>Windows 7 Ultimate
x64 UAC = ON
</code>```

答:
Well, I figured out how to do this via this post at Techimo.com.</p>

```<code>Dim isRunning, wasRunningAtStart, strComputer, strShutdown, objWMIService
Dim objcolProcesses, objShell, strProcesses, strProcessName

'boolean condition for the loop
isRunning = True
wasRunningAtStart = True

'-----Specify the computer name on which to watch a process:
strComputer = "." '>>> "." for this computer

'-----Specify the process to watch.  Must be enclosed in Single Quotes:
strProcessName = "'processname.exe'" '>>> Example: "'notepad.exe'"

Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\cimv2")
strProcesses = "SELECT * FROM Win32_Process WHERE Name = "
strShutdown = "shutdown -s -t 0 -f -m \\" & strComputer
Set objShell = CreateObject("WScript.Shell")

'Check the process once, no need to run if the process
'isn't already running
'Query WMI for the running processes matching our process name
Set objColProcesses = objWMIService.ExecQuery ( _
    strProcesses & strProcessName)

'If the process is running, the count will be greater than 0,
'so we switch our boolean here to exit the loop.
If objcolProcesses.Count = 0 Then
    wasRunningAtStart = False
    isRunning = False
End If
Set objColProcesses = Nothing

Do While isRunning
    'Wait 2 seconds, prevents this script from using the CPU
    WScript.Sleep 2000

    'Query WMI for the running processes matching our process name
    Set objColProcesses = objWMIService.ExecQuery ( _
        strProcesses & strProcessName)

    'If the process is running, the count will be greater than 0,
    'so we switch our boolean here to exit the loop.
    If objColProcesses.Count = 0 Then
        isRunning = False
    End If
Loop

If wasRunningAtStart Then
    'MsgBox "Would shutdown here"
    objShell.Run strShutdown
Else
    MsgBox "The specified program is not already running."
End If

Set objColProcesses = Nothing
Set objShell = Nothing
Set objWMIService = Nothing
</code>```

Body:
I have a program that scans through data at the end of the night on some occasions.  On those occasions, I would like to run a VBScript that will watch for that program to close, and when it does, will shut down Windows.

I created a .BAT file that runs the program and then shuts Windows down, but I don't always need to shutdown when I finish using the program.

So I would like to use the scanning program, and if, at the end of the night, I am ready to leave, but the program is still scanning, I would to open the VBScript that will watch for my scanning program to close.

Is this possible?

Windows 7 Ultimate
x64 UAC = ON

Body:
Well, I figured out how to do this via this post at Techimo.com.

Dim isRunning, wasRunningAtStart, strComputer, strShutdown, objWMIService
Dim objcolProcesses, objShell, strProcesses, strProcessName

'boolean condition for the loop
isRunning = True
wasRunningAtStart = True

'-----Specify the computer name on which to watch a process:
strComputer = "." '>>> "." for this computer

'-----Specify the process to watch.  Must be enclosed in Single Quotes:
strProcessName = "'processname.exe'" '>>> Example: "'notepad.exe'"

Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\cimv2")
strProcesses = "SELECT * FROM Win32_Process WHERE Name = "
strShutdown = "shutdown -s -t 0 -f -m \\" & strComputer
Set objShell = CreateObject("WScript.Shell")

'Check the process once, no need to run if the process
'isn't already running
'Query WMI for the running processes matching our process name
Set objColProcesses = objWMIService.ExecQuery ( _
    strProcesses & strProcessName)

'If the process is running, the count will be greater than 0,
'so we switch our boolean here to exit the loop.
If objcolProcesses.Count = 0 Then
    wasRunningAtStart = False
    isRunning = False
End If
Set objColProcesses = Nothing

Do While isRunning
    'Wait 2 seconds, prevents this script from using the CPU
    WScript.Sleep 2000

    'Query WMI for the running processes matching our process name
    Set objColProcesses = objWMIService.ExecQuery ( _
        strProcesses & strProcessName)

    'If the process is running, the count will be greater than 0,
    'so we switch our boolean here to exit the loop.
    If objColProcesses.Count = 0 Then
        isRunning = False
    End If
Loop

If wasRunningAtStart Then
    'MsgBox "Would shutdown here"
    objShell.Run strShutdown
Else
    MsgBox "The specified program is not already running."
End If

Set objColProcesses = Nothing
Set objShell = Nothing
Set objWMIService = Nothing


问:
Closing libUV Handles Correctly
I'm trying to find out how to fix these memory leaks I'm getting while running this program with Valgrind. The leaks occur with the two allocations in nShell_client_main. But I'm not
sure how to properly free them.

I've tried freeing them at nShell_Connect, but it's causing libUV to abort the program. I've tried freeing them at the end of nShell_client_main, but then I get read/write errors when closing the loop. Does anyone know how I'm supposed to close these handles? I've read this, which got me started. But, it seams out-dated because uv_ip4_addr has a different prototype in the latest version.

(nShell_main is the "entry" point)

```<code>#include "nPort.h"
#include "nShell-main.h"

void nShell_Close(
    uv_handle_t * term_handle
){
}

void nShell_Connect(uv_connect_t * term_handle, int status){
    uv_close((uv_handle_t *) term_handle, 0);
}

nError * nShell_client_main(nShell * n_shell, uv_loop_t * n_shell_loop){

    int uv_error = 0;

    nError * n_error = 0;

    uv_tcp_t * n_shell_socket = 0;
    uv_connect_t * n_shell_connect = 0;

    struct sockaddr_in dest_addr;

    n_shell_socket = malloc(sizeof(uv_tcp_t));

    if (!n_shell_socket){
        // handle error
    }

    uv_error = uv_tcp_init(n_shell_loop, n_shell_socket);

    if (uv_error){
        // handle error
    }

    uv_error = uv_ip4_addr("127.0.0.1", NPORT, &dest_addr);

    if (uv_error){
        // handle error
    }

    n_shell_connect = malloc(sizeof(uv_connect_t));

    if (!n_shell_connect){
        // handle error
    }

    uv_error = uv_tcp_connect(n_shell_connect, n_shell_socket, (struct sockaddr *) &dest_addr, nShell_Connect);

    if (uv_error){
        // handle error
    }

    uv_error = uv_run(n_shell_loop, UV_RUN_DEFAULT);

    if (uv_error){
        // handle error
    }

    return 0;
}

nError * nShell_loop_main(nShell * n_shell){

    int uv_error = 0;

    nError * n_error = 0;

    uv_loop_t * n_shell_loop = 0;

    n_shell_loop = malloc(sizeof(uv_loop_t));

    if (!n_shell_loop){
        // handle error
    }

    uv_error = uv_loop_init(n_shell_loop);

    if (uv_error){
        // handle error
    }

    n_error = nShell_client_main(n_shell, n_shell_loop);

    if (n_error){
        // handle error
    }

    uv_loop_close(n_shell_loop);
    free(n_shell_loop);

    return 0;
}
</code>```

The assertion is happening at the end of the switch statement in this excerpt of code (taken from Joyent's libUV page on Github):

```<code>void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));

  handle->flags |= UV_CLOSING;
  handle->close_cb = close_cb;

  switch (handle->type) {
  case UV_NAMED_PIPE:
    uv__pipe_close((uv_pipe_t*)handle);
    break;

  case UV_TTY:
    uv__stream_close((uv_stream_t*)handle);
    break;

  case UV_TCP:
    uv__tcp_close((uv_tcp_t*)handle);
    break;

  case UV_UDP:
    uv__udp_close((uv_udp_t*)handle);
    break;

  case UV_PREPARE:
    uv__prepare_close((uv_prepare_t*)handle);
    break;

  case UV_CHECK:
    uv__check_close((uv_check_t*)handle);
    break;

  case UV_IDLE:
    uv__idle_close((uv_idle_t*)handle);
    break;

  case UV_ASYNC:
    uv__async_close((uv_async_t*)handle);
    break;

  case UV_TIMER:
    uv__timer_close((uv_timer_t*)handle);
    break;

  case UV_PROCESS:
    uv__process_close((uv_process_t*)handle);
    break;

  case UV_FS_EVENT:
    uv__fs_event_close((uv_fs_event_t*)handle);
    break;

  case UV_POLL:
    uv__poll_close((uv_poll_t*)handle);
    break;

  case UV_FS_POLL:
    uv__fs_poll_close((uv_fs_poll_t*)handle);
    break;

  case UV_SIGNAL:
    uv__signal_close((uv_signal_t*) handle);
    /* Signal handles may not be closed immediately. The signal code will */
    /* itself close uv__make_close_pending whenever appropriate. */
    return;

  default:
    assert(0); // assertion is happening here
  }

  uv__make_close_pending(handle);
}
</code>```

I could call uv__tcp_close manually, but it's not in the public headers (and probably not the right solution anyway).

答:
I finally figured out how to stop a loop and clean up all handles.
I created a bunch of handles and SIGINT signal handle:

```<code>uv_signal_t *sigint = new uv_signal_t;
uv_signal_init(uv_default_loop(), sigint);
uv_signal_start(sigint, on_sigint_received, SIGINT);
</code>```

When SIGINT is received (Ctrl+C in console is pressed) the on_sigint_received callback is called.
The on_sigint_received looks like:

```<code>void on_sigint_received(uv_signal_t *handle, int signum)
{
    int result = uv_loop_close(handle->loop);
    if (result == UV_EBUSY)
    {
        uv_walk(handle->loop, on_uv_walk, NULL);
    }
}
</code>```

It triggers a call back function on_uv_walk:

```<code>void on_uv_walk(uv_handle_t* handle, void* arg)
{
    uv_close(handle, on_uv_close);
}
</code>```

It tries to close each opened libuv handle.
Note: that I do not call uv_stop before uv_walk, as mentioned saghul.
After on_sigint_received function is called libuv loop continuous the execution and on the next iteration calls on_uv_close for each opened handle. If you call the uv_stop function, then the on_uv_close callback will not be called.

```<code>void on_uv_close(uv_handle_t* handle)
{
    if (handle != NULL)
    {
        delete handle;
    }
}
</code>```

After that libuv do not have opened handles and finishes the loop (exits from uv_run):

```<code>uv_run(uv_default_loop(), UV_RUN_DEFAULT);
int result = uv_loop_close(uv_default_loop());
if (result)
{
    cerr << "failed to close libuv loop: " << uv_err_name(result) << endl;
}
else
{
    cout << "libuv loop is closed successfully!\n";
}
</code>```

Title: Closing libUV Handles Correctly

Body:
I'm trying to find out how to fix these memory leaks I'm getting while running this program with Valgrind. The leaks occur with the two allocations in nShell_client_main. But I'm not
sure how to properly free them.

I've tried freeing them at nShell_Connect, but it's causing libUV to abort the program. I've tried freeing them at the end of nShell_client_main, but then I get read/write errors when closing the loop. Does anyone know how I'm supposed to close these handles? I've read this, which got me started. But, it seams out-dated because uv_ip4_addr has a different prototype in the latest version.

(nShell_main is the "entry" point)

#include "nPort.h"
#include "nShell-main.h"

void nShell_Close(
    uv_handle_t * term_handle
){
}

void nShell_Connect(uv_connect_t * term_handle, int status){
    uv_close((uv_handle_t *) term_handle, 0);
}

nError * nShell_client_main(nShell * n_shell, uv_loop_t * n_shell_loop){

    int uv_error = 0;

    nError * n_error = 0;

    uv_tcp_t * n_shell_socket = 0;
    uv_connect_t * n_shell_connect = 0;

    struct sockaddr_in dest_addr;

    n_shell_socket = malloc(sizeof(uv_tcp_t));

    if (!n_shell_socket){
        // handle error
    }

    uv_error = uv_tcp_init(n_shell_loop, n_shell_socket);

    if (uv_error){
        // handle error
    }

    uv_error = uv_ip4_addr("127.0.0.1", NPORT, &dest_addr);

    if (uv_error){
        // handle error
    }

    n_shell_connect = malloc(sizeof(uv_connect_t));

    if (!n_shell_connect){
        // handle error
    }

    uv_error = uv_tcp_connect(n_shell_connect, n_shell_socket, (struct sockaddr *) &dest_addr, nShell_Connect);

    if (uv_error){
        // handle error
    }

    uv_error = uv_run(n_shell_loop, UV_RUN_DEFAULT);

    if (uv_error){
        // handle error
    }

    return 0;
}

nError * nShell_loop_main(nShell * n_shell){

    int uv_error = 0;

    nError * n_error = 0;

    uv_loop_t * n_shell_loop = 0;

    n_shell_loop = malloc(sizeof(uv_loop_t));

    if (!n_shell_loop){
        // handle error
    }

    uv_error = uv_loop_init(n_shell_loop);

    if (uv_error){
        // handle error
    }

    n_error = nShell_client_main(n_shell, n_shell_loop);

    if (n_error){
        // handle error
    }

    uv_loop_close(n_shell_loop);
    free(n_shell_loop);

    return 0;
}

The assertion is happening at the end of the switch statement in this excerpt of code (taken from Joyent's libUV page on Github):

void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));

  handle->flags |= UV_CLOSING;
  handle->close_cb = close_cb;

  switch (handle->type) {
  case UV_NAMED_PIPE:
    uv__pipe_close((uv_pipe_t*)handle);
    break;

  case UV_TTY:
    uv__stream_close((uv_stream_t*)handle);
    break;

  case UV_TCP:
    uv__tcp_close((uv_tcp_t*)handle);
    break;

  case UV_UDP:
    uv__udp_close((uv_udp_t*)handle);
    break;

  case UV_PREPARE:
    uv__prepare_close((uv_prepare_t*)handle);
    break;

  case UV_CHECK:
    uv__check_close((uv_check_t*)handle);
    break;

  case UV_IDLE:
    uv__idle_close((uv_idle_t*)handle);
    break;

  case UV_ASYNC:
    uv__async_close((uv_async_t*)handle);
    break;

  case UV_TIMER:
    uv__timer_close((uv_timer_t*)handle);
    break;

  case UV_PROCESS:
    uv__process_close((uv_process_t*)handle);
    break;

  case UV_FS_EVENT:
    uv__fs_event_close((uv_fs_event_t*)handle);
    break;

  case UV_POLL:
    uv__poll_close((uv_poll_t*)handle);
    break;

  case UV_FS_POLL:
    uv__fs_poll_close((uv_fs_poll_t*)handle);
    break;

  case UV_SIGNAL:
    uv__signal_close((uv_signal_t*) handle);
    /* Signal handles may not be closed immediately. The signal code will */
    /* itself close uv__make_close_pending whenever appropriate. */
    return;

  default:
    assert(0); // assertion is happening here
  }

  uv__make_close_pending(handle);
}

I could call uv__tcp_close manually, but it's not in the public headers (and probably not the right solution anyway).

Body:
I finally figured out how to stop a loop and clean up all handles.
I created a bunch of handles and SIGINT signal handle:

uv_signal_t *sigint = new uv_signal_t;
uv_signal_init(uv_default_loop(), sigint);
uv_signal_start(sigint, on_sigint_received, SIGINT);

When SIGINT is received (Ctrl+C in console is pressed) the on_sigint_received callback is called.
The on_sigint_received looks like:

void on_sigint_received(uv_signal_t *handle, int signum)
{
    int result = uv_loop_close(handle->loop);
    if (result == UV_EBUSY)
    {
        uv_walk(handle->loop, on_uv_walk, NULL);
    }
}

It triggers a call back function on_uv_walk:

void on_uv_walk(uv_handle_t* handle, void* arg)
{
    uv_close(handle, on_uv_close);
}

It tries to close each opened libuv handle.
Note: that I do not call uv_stop before uv_walk, as mentioned saghul.
After on_sigint_received function is called libuv loop continuous the execution and on the next iteration calls on_uv_close for each opened handle. If you call the uv_stop function, then the on_uv_close callback will not be called.

void on_uv_close(uv_handle_t* handle)
{
    if (handle != NULL)
    {
        delete handle;
    }
}

After that libuv do not have opened handles and finishes the loop (exits from uv_run):

uv_run(uv_default_loop(), UV_RUN_DEFAULT);
int result = uv_loop_close(uv_default_loop());
if (result)
{
    cerr << "failed to close libuv loop: " << uv_err_name(result) << endl;
}
else
{
    cout << "libuv loop is closed successfully!\n";
}


问:
react-google-maps multiple markers breaks on open
My app loads all my markers just fine, but crashes when I try and click a marker. I get the following error:
"React.Children.only expected to receive a single React element child."

In the main map component I build the map and bring in all the markers from Firebase. I wanted to componentize the markers and build them in a separate file just to keep things a bit straighter in my head.

Here is my Map component

```<code>const MyMapComponent = compose(
withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=xxxxx&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `500px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
    defaultZoom={15}
    defaultCenter={{ lat: 34.6781445, lng: -82.8455519 }}
>
    {props.markers.map(marker => (
        <LotMarker key={marker.key} index={marker.key} lat={marker.latitude} lng={marker.longitude} />
    ))}
</GoogleMap>
);

class TheMap extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            test:'test',
            lots: [],
            isOpen: false
        };
    }

    componentWillMount() {
        base.bindToState('lots', {
            context: this,
            state: 'lots',
            asArray: true,
        });
    }

    handleMarkerClick = (key) => {
        console.log(key);
    }

    render() {
        return (
            <MyMapComponent
            isMarkerShown={this.state.isMarkerShown}
            onMarkerClick={this.handleMarkerClick}
            markers={this.state.lots}
            />
        )
    }
}
export default TheMap;
</code>```

Here I put the marker together. I've housed the InfoWindow component inside the marker and then ask it to show when the marker is clicked. However, when I do click a marker it just crashes the whole app and white screens.

This is my LotMarker component:

```<code>class LotMarker extends React.Component {

// Constructor.
constructor(props) {
    // Super Props.
    super(props);
    // State.
    this.state = {
        isOpen: false
    }
}

onToggleOpen = () => {
    console.log(this);
    this.setState({isOpen: !this.state.isOpen});
}

// Render.
render() {

// console.log(this);

    // Extract Props.
    const {
        props: {
            index,
            lat,
            lng,
            open
        }
    } = this

return (
    <Marker key={index} position={{ lat: lat, lng: lng }} onClick={this.onToggleOpen}>
        {this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}>{index}</InfoWindow>}
    </Marker>
    )
}
}

export default LotMarker;
</code>```

答:
Alright, it turns out there was a really simple fix here. The content inside the InfoWindow has to be wrapped in a JSX compliant element.

Rather than this:

```<code><InfoWindow onCloseClick={this.onToggleOpen}>{index}</InfoWindow>
</code>```

I had to have this:

```<code><InfoWindow onCloseClick={this.onToggleOpen}><span>{index}</span></InfoWindow>
</code>```

Body:
My app loads all my markers just fine, but crashes when I try and click a marker. I get the following error:
"React.Children.only expected to receive a single React element child."

In the main map component I build the map and bring in all the markers from Firebase. I wanted to componentize the markers and build them in a separate file just to keep things a bit straighter in my head.

Here is my Map component

const MyMapComponent = compose(
withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=xxxxx&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `500px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
    defaultZoom={15}
    defaultCenter={{ lat: 34.6781445, lng: -82.8455519 }}
>
    {props.markers.map(marker => (
        <LotMarker key={marker.key} index={marker.key} lat={marker.latitude} lng={marker.longitude} />
    ))}
</GoogleMap>
);

class TheMap extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            test:'test',
            lots: [],
            isOpen: false
        };
    }

    componentWillMount() {
        base.bindToState('lots', {
            context: this,
            state: 'lots',
            asArray: true,
        });
    }

    handleMarkerClick = (key) => {
        console.log(key);
    }

    render() {
        return (
            <MyMapComponent
            isMarkerShown={this.state.isMarkerShown}
            onMarkerClick={this.handleMarkerClick}
            markers={this.state.lots}
            />
        )
    }
}
export default TheMap;

Here I put the marker together. I've housed the InfoWindow component inside the marker and then ask it to show when the marker is clicked. However, when I do click a marker it just crashes the whole app and white screens.

This is my LotMarker component:

class LotMarker extends React.Component {

// Constructor.
constructor(props) {
    // Super Props.
    super(props);
    // State.
    this.state = {
        isOpen: false
    }
}

onToggleOpen = () => {
    console.log(this);
    this.setState({isOpen: !this.state.isOpen});
}

// Render.
render() {

// console.log(this);

    // Extract Props.
    const {
        props: {
            index,
            lat,
            lng,
            open
        }
    } = this

return (
    <Marker key={index} position={{ lat: lat, lng: lng }} onClick={this.onToggleOpen}>
        {this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}>{index}</InfoWindow>}
    </Marker>
    )
}
}

export default LotMarker;

Body:
Alright, it turns out there was a really simple fix here. The content inside the InfoWindow has to be wrapped in a JSX compliant element.

Rather than this:

<InfoWindow onCloseClick={this.onToggleOpen}>{index}</InfoWindow>

I had to have this:

<InfoWindow onCloseClick={this.onToggleOpen}><span>{index}</span></InfoWindow>


问:
populate listview dynamically with data from an array
I'm trying to populate a ListView dynamically like this:

```<code>'for testing, arrPassed has two values("Ford" and "Chevy")
    Dim arrPassed = New String() {"Ford", "Chevy"}
    Dim colcount As New ListViewItem
    colcount.Text = "count"
    Dim colcar As New ListViewItem
    colcar.Text = "car"
    Dim intCount As Int32 = 1

    For Each car As String In arrPassed
        colcount.SubItems.Add(intCount)
        colcar.SubItems.Add(car)
        intCount = intCount + 1
    Next
    carList.Items.Add(colcount)
    carList.Items.Add(colcar)
</code>```

All I see are:

count    car

When I want to see:

```<code>count    car
1        Ford
2        Chevy
</code>```

Is there a way to do this dynamically?

Thanks!

答: In order for a ListView to show columns, you need to set the View property to Details view, and add some column definitions to the Columns property. Both of these can be done in the properties pane in design view of the form with the ListView control selected.</p>

Body:
I'm trying to populate a ListView dynamically like this:

'for testing, arrPassed has two values("Ford" and "Chevy")
    Dim arrPassed = New String() {"Ford", "Chevy"}
    Dim colcount As New ListViewItem
    colcount.Text = "count"
    Dim colcar As New ListViewItem
    colcar.Text = "car"
    Dim intCount As Int32 = 1

    For Each car As String In arrPassed
        colcount.SubItems.Add(intCount)
        colcar.SubItems.Add(car)
        intCount = intCount + 1
    Next
    carList.Items.Add(colcount)
    carList.Items.Add(colcar)

All I see are:

count    car

When I want to see:

count    car
1        Ford
2        Chevy

Is there a way to do this dynamically?

Thanks!


问:
Complex SQL Query laravel Build
How would I use query builder in Laravel to generate the following SQL statement:</p>

```<code>    SELECT MAX(QTE) FROM (SELECT SUM(activity_sale_report.quantity_sold)
    AS QTE FROM activity_sale_report
    GROUP BY activity_sale_report.activity_id) AS T
</code>```

答:
If you are just using the query builder and not models you can use raw queries

```<code>$query = DB::select( DB::raw("SELECT MAX(QTE) FROM (SELECT SUM(activity_sale_report.quantity_sold) AS QTE FROM activity_sale_report GROUP BY activity_sale_report.activity_id) AS T);
</code>```

I would recommend using the eloquent models, it's easier.

Title: Complex SQL Query laravel Build

Body:
How would I use query builder in Laravel to generate the following SQL statement:

    SELECT MAX(QTE) FROM (SELECT SUM(activity_sale_report.quantity_sold)
    AS QTE FROM activity_sale_report
    GROUP BY activity_sale_report.activity_id) AS T

Body:
If you are just using the query builder and not models you can use raw queries

$query = DB::select( DB::raw("SELECT MAX(QTE) FROM (SELECT SUM(activity_sale_report.quantity_sold) AS QTE FROM activity_sale_report GROUP BY activity_sale_report.activity_id) AS T);

I would recommend using the eloquent models, it's easier.


问:
What stages would be involved in compiling Assembly language to Machine Code
I'm trying to write a compiler to take an assembler file which will output raw machine code instructions.

I've found lots of tutorials on how to write a compiler, but I'm wondering if all the stages are relevant to assembler mnemonics. For instance, is lexical analysis necessary at all given the simplified stage-by-stage format of assembler, or will it still be necessary but in a simpler format?

答: I'd say you could apply almost every stage of compilers to assemblers, of course what applies to you depends on what your going to do. If your making a 1-to-1 mapping you need syntactical analysis to check for errors and a lexer and/or parser to process the text for specifiers to the assembly, such as sectioning, memory protection on .data (or even macros!). There is also size 'optimization' that can be a applied by funneling immediate constants into the smallest size possible. Of course you can go all out and perform deep analysis to do instruction reordering and fusing. You'd might also want a static analysis stage to check for invalid(illegal) sequences(LOCK CMPXCHG EDX,EDX would be an example of syntactical correct but invalid assembly iirc)


问:
iOS UILabel.appearance().textColor is not available
I am trying to change default text color for all labels in my app. I have tried to use UILabel.appearance().textColor, but it's not available for me. Can somebody advise what am I doing wrong? I have checked a lot of questions on SO, the latest one is this. And as per description it's available.

If I changed background color - it works. Tried to change tintColor - no effect. Why? Was it removed from UIAppearance protocol?

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?
    var smStore: SMStore?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // UIAppearance configuring
            let tintColor = UIColor.white
            //let backgroundColor = UIColor(red: 5, green: 72, blue: 149, alpha: 1)
            let backgroundColor = UIColor.black

            // Global tintColor
            window?.tintColor = tintColor

            // UIViews
            UIView.appearance().tintColor = tintColor
            UIView.appearance().backgroundColor = backgroundColor

            // UINavigationBars
            UINavigationBar.appearance().tintColor = tintColor
            UINavigationBar.appearance().backgroundColor = tintColor

            // UITableViews
            UITableView.appearance().backgroundColor = backgroundColor
            UITableViewCell.appearance().backgroundColor = backgroundColor
            UITableViewCell.appearance().tintColor = tintColor

            // UILabels
            UILabel.appearance().backgroundColor = UIColor.green
            ...
        }
</code>```

Xcode 9, Swift 4.

答:
Just type it in. It compiles.</p>

```<code>UILabel.appearance().textColor = .red
</code>```

Body:
I am trying to change default text color for all labels in my app. I have tried to use UILabel.appearance().textColor, but it's not available for me. Can somebody advise what am I doing wrong? I have checked a lot of questions on SO, the latest one is this. And as per description it's available.

If I changed background color - it works. Tried to change tintColor - no effect. Why? Was it removed from UIAppearance protocol?

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?
    var smStore: SMStore?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        // UIAppearance configuring
            let tintColor = UIColor.white
            //let backgroundColor = UIColor(red: 5, green: 72, blue: 149, alpha: 1)
            let backgroundColor = UIColor.black

            // Global tintColor
            window?.tintColor = tintColor

            // UIViews
            UIView.appearance().tintColor = tintColor
            UIView.appearance().backgroundColor = backgroundColor

            // UINavigationBars
            UINavigationBar.appearance().tintColor = tintColor
            UINavigationBar.appearance().backgroundColor = tintColor

            // UITableViews
            UITableView.appearance().backgroundColor = backgroundColor
            UITableViewCell.appearance().backgroundColor = backgroundColor
            UITableViewCell.appearance().tintColor = tintColor

            // UILabels
            UILabel.appearance().backgroundColor = UIColor.green
            ...
        }

Xcode 9, Swift 4.

Body:
Just type it in. It compiles.

UILabel.appearance().textColor = .red


问:
Button from Fragment is Crashing the app
I put a Button in fragment with the corresponding listener. Every time I call on this activity the app crashes. Logcat show a null pointer exception. The code below is a snippet from the Fragment class.

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        recyclerView.setAdapter(new MyCarProfileRecyclerViewAdapter(carProfileContent.ITEMS, mListener));
    }

    Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
    imgbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getActivity(),ReserveActivity.class));
        }
    });

    return view;
}
</code>```

Logcat shows:

```<code>FATAL EXCEPTION: main
Process: com.example.app, PID: 13571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.CarProfileListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mikepuno.parkeazy.CarProfileFragment.onCreateView(CarProfileFragment.java:78)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5353)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2340)
</code>```

I've been looking at multiple similar issues here but it just don't seem to work for me. Am I missing anything from the way I added the Button and the listener?

fragment_carprofile_list.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.mikepuno.parkeazy.CarProfileFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.mikepuno.parkeazy.CarProfileFragment"
    tools:listitem="@layout/fragment_carprofile" />
</code>```

fragment_carprofile.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/plateNumberTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textAppearance="?attr/textAppearanceListItem" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/brandTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/modelTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/colorTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <Button
            android:id="@+id/editCarProfileButton"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:text="Edit" />

    </LinearLayout>
</LinearLayout>
</code>```

Adapter Class

```<code>public class MyCarProfileRecyclerViewAdapter extends RecyclerView.Adapter<MyCarProfileRecyclerViewAdapter.ViewHolder> {

    private final List<CarProfile> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyCarProfileRecyclerViewAdapter(List<CarProfile> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_carprofile, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.mPlateNumberTextView.setText(mValues.get(position).getPlateNumber());
        holder.mBrandTextView.setText(mValues.get(position).getBrand());
        holder.mModelTextView.setText(mValues.get(position).getModel());
        holder.mColorTextView.setText(mValues.get(position).getColor());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(holder.mItem);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mPlateNumberTextView;
        public final TextView mBrandTextView;
        public final TextView mModelTextView;
        public final TextView mColorTextView;
        public CarProfile mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mPlateNumberTextView = (TextView) view.findViewById(R.id.plateNumberTextView);
            mBrandTextView = (TextView) view.findViewById(R.id.brandTextView);
            mModelTextView = (TextView) view.findViewById(R.id.modelTextView);
            mColorTextView = (TextView) view.findViewById(R.id.colorTextView);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mPlateNumberTextView.getText() + "'";
        }
    }
}
</code>```

答:
```<code>View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);
</code>```

You are inflating fragment_carprofile_list.xml, which contains the RecyclerView. There is no mention of Button in that XML, which is why you are getting a NullPointerException

Body:
I put a Button in fragment with the corresponding listener. Every time I call on this activity the app crashes. Logcat show a null pointer exception. The code below is a snippet from the Fragment class.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();
        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        recyclerView.setAdapter(new MyCarProfileRecyclerViewAdapter(carProfileContent.ITEMS, mListener));
    }

    Button imgbtn = (Button) view.findViewById(R.id.editCarProfileButton);
    imgbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(getActivity(),ReserveActivity.class));
        }
    });

    return view;
}

Logcat shows:

FATAL EXCEPTION: main
Process: com.example.app, PID: 13571
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.CarProfileListActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.mikepuno.parkeazy.CarProfileFragment.onCreateView(CarProfileFragment.java:78)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1174)
at android.app.Activity.performStart(Activity.java:5353)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2340)

I've been looking at multiple similar issues here but it just don't seem to work for me. Am I missing anything from the way I added the Button and the listener?

fragment_carprofile_list.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="com.mikepuno.parkeazy.CarProfileFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="com.mikepuno.parkeazy.CarProfileFragment"
    tools:listitem="@layout/fragment_carprofile" />

fragment_carprofile.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/plateNumberTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textAppearance="?attr/textAppearanceListItem" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/brandTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/modelTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <TextView
            android:id="@+id/colorTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:textAppearance="?attr/textAppearanceListItem" />

        <Button
            android:id="@+id/editCarProfileButton"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:text="Edit" />

    </LinearLayout>
</LinearLayout>

Adapter Class

public class MyCarProfileRecyclerViewAdapter extends RecyclerView.Adapter<MyCarProfileRecyclerViewAdapter.ViewHolder> {

    private final List<CarProfile> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MyCarProfileRecyclerViewAdapter(List<CarProfile> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_carprofile, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.mPlateNumberTextView.setText(mValues.get(position).getPlateNumber());
        holder.mBrandTextView.setText(mValues.get(position).getBrand());
        holder.mModelTextView.setText(mValues.get(position).getModel());
        holder.mColorTextView.setText(mValues.get(position).getColor());

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(holder.mItem);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mPlateNumberTextView;
        public final TextView mBrandTextView;
        public final TextView mModelTextView;
        public final TextView mColorTextView;
        public CarProfile mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mPlateNumberTextView = (TextView) view.findViewById(R.id.plateNumberTextView);
            mBrandTextView = (TextView) view.findViewById(R.id.brandTextView);
            mModelTextView = (TextView) view.findViewById(R.id.modelTextView);
            mColorTextView = (TextView) view.findViewById(R.id.colorTextView);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mPlateNumberTextView.getText() + "'";
        }
    }
}

Body:
View view = inflater.inflate(R.layout.fragment_carprofile_list, container, false);

You are inflating fragment_carprofile_list.xml, which contains the RecyclerView. There is no mention of Button in that XML, which is why you are getting a NullPointerException


答:
Just add vertical-align: middle; to all button elements:

.Languages {
  position: relative;
  padding-left: 40px;
  width: 100%;
  height: 62px;
  background-color: turquoise;
}

.Type1 {
  position: relative;
  height: 100%;
  width: 100px;
  font-size: 18px;
  margin-right: 10px;
  line-height: 62px;
  box-sizing: border-box;
  background-color: tomato;
  border: 0;
  padding: 0;
}

.Type2 {
  position: relative;
  width: 10px;
  border-bottom: 1px solid green;
  margin-left: 5px;
  cursor: pointer;
  background-color: tomato;
  border: 0;
  padding: 0;
  vertical-align: middle;
}

.a {
  height: 5px;
}

.b {
  height: 25px;
}

.c {
  height: 45px;
}

.d {
  height: 60px;
}

button {
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Languages">
  <button class="Type1" data-id="1">English</button>
  <button class="Type1" data-id="1">French</button>
  <button class="Type2 a"></button>
  <button class="Type2 b"></button>
  <button class="Type2 c"></button>
  <button class="Type2 d"></button>
</div></code>```

Title: Vertical align of different buttons inside a div

Body:
Just add vertical-align: middle; to all button elements:

.Languages {
  position: relative;
  padding-left: 40px;
  width: 100%;
  height: 62px;
  background-color: turquoise;
}

.Type1 {
  position: relative;
  height: 100%;
  width: 100px;
  font-size: 18px;
  margin-right: 10px;
  line-height: 62px;
  box-sizing: border-box;
  background-color: tomato;
  border: 0;
  padding: 0;
}

.Type2 {
  position: relative;
  width: 10px;
  border-bottom: 1px solid green;
  margin-left: 5px;
  cursor: pointer;
  background-color: tomato;
  border: 0;
  padding: 0;
  vertical-align: middle;
}

.a {
  height: 5px;
}

.b {
  height: 25px;
}

.c {
  height: 45px;
}

.d {
  height: 60px;
}

button {
  vertical-align: middle;
}

<div class="Languages">
  <button class="Type1" data-id="1">English</button>
  <button class="Type1" data-id="1">French</button>
  <button class="Type2 a"></button>
  <button class="Type2 b"></button>
  <button class="Type2 c"></button>
  <button class="Type2 d"></button>
</div>


问:
How to include one header for every page in different folders
How can I use one header.php file for every html page in different folders?

For example:

My header.php file is in homepage/includes folder.

And i include like this include "includes/header.php";

up to now, everything is okay.

And i have a diffent folder on my homepage called "users"

And i wanna include my header.php file, which is on homepage/includes folder, on homepage/users/index.php file.

And i include like this "include "../includes/header.php", but I have errors.

Cause on my header.php file I call my css files like <link href="assets/css/demo.css"/>

So I need to copy my header.php file to users folder.

And I need to change href="assets/...." like href="../assets/...."

Isn't there any way to solve it?? Thank you.

答:
append the line to all php files which require the header

Note: please use the correct path in file_location/header.php

```<code><?php
include_once('header.php');
?>
</code>```

Body:
append the line to all php files which require the header

Note: please use the correct path in file_location/header.php

<?php
include_once('header.php');
?>


问:
ATTiny 13 wake up from sleep mode
I'm trying to put my ATTiny into sleep mode and than wake it up. I use this code to put it to sleep:

```<code>void go_to_sleep(){
is_sleeping = true;
RED_HIGH;
YELLOW_HIGH;
GREEN_HIGH;
sleep_enable();
sei();
sleep_cpu();
sleep_disable();
</code>```

}

Than I use external interrupt but nothing happens.

```<code>ISR(INT0_vect)
{
    if(is_sleeping){
        awake();
    }
    if(BUTTON_LOW){ // przycisk wciśnięty?
        _delay_ms(80);
        if(BUTTON_LOW){ // nadal wciśnięty?
            do_thing();
        }
    }
}
void awake(){
    is_sleeping = false;
    RED_LOW;
    YELLOW_HIGH;
    GREEN_HIGH;
}
</code>```

Any ideas welcomed.

I add main to show that interrupt works fine, I've tested it without sleep mode:

```<code>int main(void)
{
MCUCR |= 1<<SE; // zezwolenie na sleep mode
GIMSK |= 1<<INT0; // int0 enable
MCUCR |= 0<<ISC00 | 1<<ISC01; //przerwanie zboczem opadającym
sei(); // zezwolenie na przerwania

//OUTPUTS
DDRB |= RED | YELLOW  | GREEN;
//INPUTS
DDRB &= ~BUTTON;
// Podciągnięcie przycisku do VCC
PORTB |= BUTTON;

set_sleep_mode(SLEEP_MODE_PWR_DOWN); // ustaw tryb sleep modu, ta linijka nie uruchamia go

//Stan początkowy
RED_LOW;
YELLOW_HIGH;
GREEN_HIGH;

timer0(TIMER_PRESCALER_1024,255);

while(1);
}
</code>```

答:
You must enable the INT0 interrupt in the General Interrupt Mask Register....

Add the line...

```<code>GIMSK |= _BV( PCIE );
</code>```

...before you go to sleep and activating the INT0 pin (by default having a low level) should wake the MCU from sleep.

Note that with your code as shown, I'm not sure that you would be able to tell that the CPU had woken up. Try having an output on a pin for high just before you sleep, and then have it go low when you wake so you will know it happened.

Title: ATTiny 13 wake up from sleep mode

Body:
I'm trying to put my ATTiny into sleep mode and than wake it up. I use this code to put it to sleep:

void go_to_sleep(){
is_sleeping = true;
RED_HIGH;
YELLOW_HIGH;
GREEN_HIGH;
sleep_enable();
sei();
sleep_cpu();
sleep_disable();

}

Than I use external interrupt but nothing happens.

ISR(INT0_vect)
{
    if(is_sleeping){
        awake();
    }
    if(BUTTON_LOW){ // przycisk wciśnięty?
        _delay_ms(80);
        if(BUTTON_LOW){ // nadal wciśnięty?
            do_thing();
        }
    }
}
void awake(){
    is_sleeping = false;
    RED_LOW;
    YELLOW_HIGH;
    GREEN_HIGH;
}

Any ideas welcomed.

I add main to show that interrupt works fine, I've tested it without sleep mode:

int main(void)
{
MCUCR |= 1<<SE; // zezwolenie na sleep mode
GIMSK |= 1<<INT0; // int0 enable
MCUCR |= 0<<ISC00 | 1<<ISC01; //przerwanie zboczem opadającym
sei(); // zezwolenie na przerwania

//OUTPUTS
DDRB |= RED | YELLOW  | GREEN;
//INPUTS
DDRB &= ~BUTTON;
// Podciągnięcie przycisku do VCC
PORTB |= BUTTON;

set_sleep_mode(SLEEP_MODE_PWR_DOWN); // ustaw tryb sleep modu, ta linijka nie uruchamia go

//Stan początkowy
RED_LOW;
YELLOW_HIGH;
GREEN_HIGH;

timer0(TIMER_PRESCALER_1024,255);

while(1);
}

Body:
You must enable the INT0 interrupt in the General Interrupt Mask Register....

Add the line...

GIMSK |= _BV( PCIE );

...before you go to sleep and activating the INT0 pin (by default having a low level) should wake the MCU from sleep.

Note that with your code as shown, I'm not sure that you would be able to tell that the CPU had woken up. Try having an output on a pin for high just before you sleep, and then have it go low when you wake so you will know it happened.


问:
Chartjs - Graphics Value type float
I have two graphs of the Chartjs and I need the values of both graphs to have broken values, for example (20,15);

Follow the graphics codes:

```<code>vm.chart = () => {
        vm.labels = ["D1", "VC1", "Internacional", "À cobrar", "0300", "Gratuita", "Locais"];
        vm.colors = [ '#f36e20', '#8aca7b', '#0bc4df', '#272343', '#389223', '#f1a80a', '#1e75eb'];
        vm.data = [10, 10, 20, 10, 10, 10, 30];
        vm.options = {
          data: [

            ]
        }
    }
</code>```

html:

```<code><canvas class="chart chart-doughnut"
        chart-data="vm.data"
        chart-labels="vm.labels"
        chart-colors="vm.colors"
        chart-options="vm.options"
        ng-init="vm.chart()">
</canvas>
</code>```

Second chart:

```<code>  vm.chart_gasto = () => {
        vm.data_labels = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","21","23","24","25","26","27","28","29","30","31"];
        vm.data_gasto = [85,55,85,105,55,85,35,95,85,64,25,85,25,55,85,25,85,64,85,25,64,35,85,35,55,85,35,85,35,85,105];
        vm.data_colors = ['#8aacdf', '#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf'];
        vm.data_options = {
            scales:{
                yAxes:[{
                    display: false
                }],
                xAxes:[{
                    display: true,
                    gridLines: {
                        color: 'rgba(255,255,255,.35)'
                    },
                    ticks: {
                        fontColor: '#9d9d9c'
                    }
                }]
            }
        }
    }
</code>```

html:

```<code>  <canvas class="chart chart-bar" height="250px"
          chart-data="vm.data_gasto"
          chart-colors="vm.data_colors"
          chart-labels="vm.data_labels"
          chart-options="vm.data_options"
          ng-init="vm.chart_gasto()">
  </canvas>
</code>```

In addition to "broken" numbers, is there a possibility for the% value next to them?

Has anyone ever had to do something similar?

答:
Based on ChartJS documentation:

The tooltip label configuration is nested below the tooltip
  configuration using the callbacks key. The tooltip has the following
  callbacks for providing text. For all functions, 'this' will be the
  tooltip object created from the Chart.Tooltip constructor.

All functions are called with the same arguments: a tooltip item and
  the data object passed to the chart. All functions must return either
  a string or an array of strings. Arrays of strings are treated as
  multiple lines of text.

In your case if I am not mistaken this applies to something like this:

```<code>  vm.options = {
    tooltips: {
      callbacks: {
        label: (tooltipItem, chart) => {
          const realValue = chart.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]
          const customValue = realValue.toFixed(2).replace(".", ",") + '%';
          const label = chart.labels[tooltipItem.index] + ':';
          return label + customValue;
        }
      }
    }
  }
</code>```

Here's a working fiddle with the code you shared.

Title: Chartjs - Graphics Value type float

Body:
I have two graphs of the Chartjs and I need the values of both graphs to have broken values, for example (20,15);

Follow the graphics codes:

vm.chart = () => {
        vm.labels = ["D1", "VC1", "Internacional", "À cobrar", "0300", "Gratuita", "Locais"];
        vm.colors = [ '#f36e20', '#8aca7b', '#0bc4df', '#272343', '#389223', '#f1a80a', '#1e75eb'];
        vm.data = [10, 10, 20, 10, 10, 10, 30];
        vm.options = {
          data: [

            ]
        }
    }

html:

<canvas class="chart chart-doughnut"
        chart-data="vm.data"
        chart-labels="vm.labels"
        chart-colors="vm.colors"
        chart-options="vm.options"
        ng-init="vm.chart()">
</canvas>

Second chart:

  vm.chart_gasto = () => {
        vm.data_labels = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","21","23","24","25","26","27","28","29","30","31"];
        vm.data_gasto = [85,55,85,105,55,85,35,95,85,64,25,85,25,55,85,25,85,64,85,25,64,35,85,35,55,85,35,85,35,85,105];
        vm.data_colors = ['#8aacdf', '#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf','#8aacdf'];
        vm.data_options = {
            scales:{
                yAxes:[{
                    display: false
                }],
                xAxes:[{
                    display: true,
                    gridLines: {
                        color: 'rgba(255,255,255,.35)'
                    },
                    ticks: {
                        fontColor: '#9d9d9c'
                    }
                }]
            }
        }
    }

html:

  <canvas class="chart chart-bar" height="250px"
          chart-data="vm.data_gasto"
          chart-colors="vm.data_colors"
          chart-labels="vm.data_labels"
          chart-options="vm.data_options"
          ng-init="vm.chart_gasto()">
  </canvas>

In addition to "broken" numbers, is there a possibility for the% value next to them?

Has anyone ever had to do something similar?

Body:
Based on ChartJS documentation:

The tooltip label configuration is nested below the tooltip
  configuration using the callbacks key. The tooltip has the following
  callbacks for providing text. For all functions, 'this' will be the
  tooltip object created from the Chart.Tooltip constructor.

All functions are called with the same arguments: a tooltip item and
  the data object passed to the chart. All functions must return either
  a string or an array of strings. Arrays of strings are treated as
  multiple lines of text.

In your case if I am not mistaken this applies to something like this:

  vm.options = {
    tooltips: {
      callbacks: {
        label: (tooltipItem, chart) => {
          const realValue = chart.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]
          const customValue = realValue.toFixed(2).replace(".", ",") + '%';
          const label = chart.labels[tooltipItem.index] + ':';
          return label + customValue;
        }
      }
    }
  }

Here's a working fiddle with the code you shared.


问:
How to access variable inside Meteor.call()?
I’d like to access variable inside Meteor.call().

Here, I have numStudys inside Meteor.call(), and console.log() inside Meteor.call correctly shows the value of numStudys (in my case, 4, which is correct), but console.log() outside Meteor.call just keep showing “undefined”.

Is there any ways that I can access numStudys inside Meteor.call, and get the value (in my case, 4)?

export default class StudyPage extends React.Component {

  constructor(props) {
    super(props);

  }

  componentDidMount() {
    Tracker.autorun(() => {
      Meteor.call('studys.count', (error, result) => {
        numStudys = result;
        console.log("numStudys inside Meteor.call: ", numStudys);
      });
      console.log("numStudys outside Meteor.call: ", this.numStudys);
    });
  }
}```

My result

numStudys outside Meteor.call: undefined

numStudys inside Meteor.call: 4

答:
Meteor.Call() is a callback.

You can only access the result of a callback within the callback itself. result is scoped to the callback only. You cannot access that data anywhere outside the Meteor.Call()

See: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Body:
I’d like to access variable inside Meteor.call().

Here, I have numStudys inside Meteor.call(), and console.log() inside Meteor.call correctly shows the value of numStudys (in my case, 4, which is correct), but console.log() outside Meteor.call just keep showing “undefined”.

Is there any ways that I can access numStudys inside Meteor.call, and get the value (in my case, 4)?

export default class StudyPage extends React.Component {

  constructor(props) {
    super(props);

  }

  componentDidMount() {
    Tracker.autorun(() => {
      Meteor.call('studys.count', (error, result) => {
        numStudys = result;
        console.log("numStudys inside Meteor.call: ", numStudys);
      });
      console.log("numStudys outside Meteor.call: ", this.numStudys);
    });
  }
}

My result

numStudys outside Meteor.call: undefined

numStudys inside Meteor.call: 4


问:
Pass Parameters _ Shell Script - Octave Script
How can i pass two parameters (number vectors) from a Shell Script to a Octave Script ??

That's the idea..

In "prove.sh"

```<code> #!/bin/bash

 .... do something that processing vector1 vector2

./draw.m Vector1 Vector2
</code>```

In "draw.m"

```<code> plot(Vector1, Vector2)
</code>```

Thank you!!

答:
..And, if you allow me, i add a small variation for a Octave Script since the former was in Matlab ;)

Arrays.sh

```<code>#!/bin/bash
# create random data
for i in {1..10}; do v1[$i]=$RANDOM; done
for i in {1..10}; do v2[$i]=$RANDOM; done

# save data to file
echo ${v1[@]} > file.txt
echo ${v2[@]} >> file.txt

# call OCTAVE script
octave draw.m
</code>```

Draw.m

```<code>load ("-ascii", "file.txt")
plot(file(1,:), file(2,:))      %# if you want see the graphic
print('figure.ps', '-deps')     %# save the result of 'plot' into a postscript file
exit
</code>```

Body:
How can i pass two parameters (number vectors) from a Shell Script to a Octave Script ??

That's the idea..

In "prove.sh"

 #!/bin/bash

 .... do something that processing vector1 vector2

./draw.m Vector1 Vector2

In "draw.m"

 plot(Vector1, Vector2)

Thank you!!

Body:
..And, if you allow me, i add a small variation for a Octave Script since the former was in Matlab ;)

Arrays.sh

#!/bin/bash
# create random data
for i in {1..10}; do v1[$i]=$RANDOM; done
for i in {1..10}; do v2[$i]=$RANDOM; done

# save data to file
echo ${v1[@]} > file.txt
echo ${v2[@]} >> file.txt

# call OCTAVE script
octave draw.m

Draw.m

load ("-ascii", "file.txt")
plot(file(1,:), file(2,:))      %# if you want see the graphic
print('figure.ps', '-deps')     %# save the result of 'plot' into a postscript file
exit


问:
Java Swing window takes 15 seconds to show
I started writing a simple Hello world app with JFrame, and I noticed that the first window that I create (or the first reference to Swing libraries) takes 15 seconds to show. I also tested it with the compiled application launched from console to see if there is a difference, and there is none.

Here's my code:

```<code>public static void main(String args[]) {

    /* Create and display the form */
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            long start = System.currentTimeMillis();
            new Test().setVisible(true);
            System.out.println("FORM 1: " + (System.currentTimeMillis() - start));

            start = System.currentTimeMillis();
            new Test2().setVisible(true);
            System.out.println("FORM 2: " + (System.currentTimeMillis() - start));
        }
    });
}
</code>```

And here's output:

```<code>FORM 1: 15362
FORM 2: 203
</code>```

I've read about disabling D3D for Java2D but it's no use for me as I work on linux (openSUSE). I also tried switching from Oracle's JDK 1.8 to openJDK 1.8 but it still doesn't make any difference.

What can I do to speed that thing up?

答:
Try running something like this:

```<code>SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        long start = System.currentTimeMillis();
        new JFrame().setVisible(true);
        System.out.println("FORM 1: " + (System.currentTimeMillis() - start));
    }
});
</code>```

If it's still taking a long time, then you know it's definitely Swing - unfortunately though if you've tried the usual approaches, there's not a great deal you can do about it (aside from perhaps trying Java 7 and/or filing a bug report with details of your system.) This may be worth a read, but is heavily based around windows, so much of it won't apply.

If it's much faster running this code, then there's some other aspect of your code (or the IDE's auto-generated code) that's causing the issue.

Body:
I started writing a simple Hello world app with JFrame, and I noticed that the first window that I create (or the first reference to Swing libraries) takes 15 seconds to show. I also tested it with the compiled application launched from console to see if there is a difference, and there is none.

Here's my code:

public static void main(String args[]) {

    /* Create and display the form */
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            long start = System.currentTimeMillis();
            new Test().setVisible(true);
            System.out.println("FORM 1: " + (System.currentTimeMillis() - start));

            start = System.currentTimeMillis();
            new Test2().setVisible(true);
            System.out.println("FORM 2: " + (System.currentTimeMillis() - start));
        }
    });
}

And here's output:

FORM 1: 15362
FORM 2: 203

I've read about disabling D3D for Java2D but it's no use for me as I work on linux (openSUSE). I also tried switching from Oracle's JDK 1.8 to openJDK 1.8 but it still doesn't make any difference.

What can I do to speed that thing up?

Body:
Try running something like this:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        long start = System.currentTimeMillis();
        new JFrame().setVisible(true);
        System.out.println("FORM 1: " + (System.currentTimeMillis() - start));
    }
});

If it's still taking a long time, then you know it's definitely Swing - unfortunately though if you've tried the usual approaches, there's not a great deal you can do about it (aside from perhaps trying Java 7 and/or filing a bug report with details of your system.) This may be worth a read, but is heavily based around windows, so much of it won't apply.

If it's much faster running this code, then there's some other aspect of your code (or the IDE's auto-generated code) that's causing the issue.


问:
Only include grouped observations where event order is valid
I have a table of dates for eye exams and eye wear purchases for individuals. I only want to keep instances where individuals bought their eye wear following an eye exam. In the example below, I would want to keep person 1, events 2 and 3 for person 2, person 3, but not person 4. How can I do this in SQL server?

```<code>| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Eyewear|    1  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |
|    4   | Eyewear|    1  |
|    4   | Exam   |    2  |
</code>```

The final result would look like

```<code>| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |
</code>```

答:
Self join should work...</p>

```<code>select
    t.Person
    ,t.Event
    ,t.[Order]
from
    yourTable t
    inner join
    yourTable t2 on t2.Person = t.Person
    and t2.[Order] = (t.[Order] +1)
where
    t2.Event = 'Eyewear'
    and t.Event = 'Exam'
</code>```

Body:
I have a table of dates for eye exams and eye wear purchases for individuals. I only want to keep instances where individuals bought their eye wear following an eye exam. In the example below, I would want to keep person 1, events 2 and 3 for person 2, person 3, but not person 4. How can I do this in SQL server?

| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Eyewear|    1  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |
|    4   | Eyewear|    1  |
|    4   | Exam   |    2  |

The final result would look like

| Person | Event  | Order |
|    1   |  Exam  |    1  |
|    1   | Eyewear|    2  |
|    2   | Exam   |    2  |
|    2   | Eyewear|    3  |
|    3   | Exam   |    1  |
|    3   | Eyewear|    2  |

Body:
Self join should work...

select
    t.Person
    ,t.Event
    ,t.[Order]
from
    yourTable t
    inner join
    yourTable t2 on t2.Person = t.Person
    and t2.[Order] = (t.[Order] +1)
where
    t2.Event = 'Eyewear'
    and t.Event = 'Exam'


问:
Filter Not Filtering Records
I'm trying to find records in $scope.employeesthat do not have a matching record in $scope.allEmployeeGroups, but the filter is not Filtering records, even though I know for sure that there should only be a few unmatched, it returns all of the records.  For each record, the indexOf == -1 when I know that it should not.  I can't figure out what I am doing wrong.  Here is my code:

```<code>    function getNonGroupEmployees() {
    var arr = $scope.employees.filter(function (item) {
        return $scope.allEmployeeGroups.indexOf(item.EmployeeId) === -1;
    })
    return arr;
}
</code>```

Employee Object:

```<code>public System.Guid EmployeeId { get; set; }
    public Nullable<System.Guid> SiteId { get; set; }
    public string SiteName { get; set; }
    public string DisplayName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Suffix { get; set; }
    public string Alias { get; set; }
    public Nullable<System.DateTime> DOB { get; set; }
    public string SsnLastFour { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool IsActive { get; set; }
    public bool IsLoginEnabled { get; set; }
    public Nullable<System.DateTime> LastLogin { get; set; }
    public Nullable<System.Guid> SignatureTypeId { get; set; }
    public string SignatureType { get; set; }
    public string NumberHome { get; set; }
    public string NumberCell { get; set; }
    public bool IsSuperUser { get; set; }
    public bool IsDeleted { get; set; }
    public System.DateTime Created { get; set; }
    public System.DateTime LastModified { get; set; }
    public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
    public string ApiKey { get; set; }
</code>```

Group Object:

```<code>            public Guid EmployeeGroupId { get; set; }
        public Guid SiteId { get; set; }
        public Guid EmployeeId { get; set; }
        public Guid SiteGroupId { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public Guid? ModifiedByEmployeeId { get; set; }
        public string SiteName { get; set; }
        public string EmployeeName { get; set; }
        public string SiteGroupName { get; set; }
        public string ModifiedByEmployeeName { get; set; }
</code>```

Any assistance is greatly appreciated.

答:
Instead of searching object with .IndexOf(), use property matching. Object will not match if two objects do not have same reference.

Try with following code block:

```<code>function getNonGroupEmployees() {
        var arr = $scope.employees.filter(function (item) {
            return $scope.allEmployeeGroups.find(function(p){
                return p.EmployeeId == item.EmployeeId
            })=== null;
        })
        return arr;
}
</code>```

AS requested here are data structures:

Employee:

```<code>public System.Guid EmployeeId { get; set; }
        public Nullable<System.Guid> SiteId { get; set; }
        public string SiteName { get; set; }
        public string DisplayName { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string Suffix { get; set; }
        public string Alias { get; set; }
        public Nullable<System.DateTime> DOB { get; set; }
        public string SsnLastFour { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool IsActive { get; set; }
        public bool IsLoginEnabled { get; set; }
        public Nullable<System.DateTime> LastLogin { get; set; }
        public Nullable<System.Guid> SignatureTypeId { get; set; }
        public string SignatureType { get; set; }
        public string NumberHome { get; set; }
        public string NumberCell { get; set; }
        public bool IsSuperUser { get; set; }
        public bool IsDeleted { get; set; }
        public System.DateTime Created { get; set; }
        public System.DateTime LastModified { get; set; }
        public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
        public string ApiKey { get; set; }
</code>```

Employee Group

```<code>            public Guid EmployeeGroupId { get; set; }
        public Guid SiteId { get; set; }
        public Guid EmployeeId { get; set; }
        public Guid SiteGroupId { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public Guid? ModifiedByEmployeeId { get; set; }
        public string SiteName { get; set; }
        public string EmployeeName { get; set; }
        public string SiteGroupName { get; set; }
        public string ModifiedByEmployeeName { get; set; }
</code>```

Title: Filter Not Filtering Records

Body:
I'm trying to find records in $scope.employeesthat do not have a matching record in $scope.allEmployeeGroups, but the filter is not Filtering records, even though I know for sure that there should only be a few unmatched, it returns all of the records.  For each record, the indexOf == -1 when I know that it should not.  I can't figure out what I am doing wrong.  Here is my code:

    function getNonGroupEmployees() {
    var arr = $scope.employees.filter(function (item) {
        return $scope.allEmployeeGroups.indexOf(item.EmployeeId) === -1;
    })
    return arr;
}

Employee Object:

public System.Guid EmployeeId { get; set; }
    public Nullable<System.Guid> SiteId { get; set; }
    public string SiteName { get; set; }
    public string DisplayName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Suffix { get; set; }
    public string Alias { get; set; }
    public Nullable<System.DateTime> DOB { get; set; }
    public string SsnLastFour { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public bool IsActive { get; set; }
    public bool IsLoginEnabled { get; set; }
    public Nullable<System.DateTime> LastLogin { get; set; }
    public Nullable<System.Guid> SignatureTypeId { get; set; }
    public string SignatureType { get; set; }
    public string NumberHome { get; set; }
    public string NumberCell { get; set; }
    public bool IsSuperUser { get; set; }
    public bool IsDeleted { get; set; }
    public System.DateTime Created { get; set; }
    public System.DateTime LastModified { get; set; }
    public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
    public string ApiKey { get; set; }

Group Object:

            public Guid EmployeeGroupId { get; set; }
        public Guid SiteId { get; set; }
        public Guid EmployeeId { get; set; }
        public Guid SiteGroupId { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public Guid? ModifiedByEmployeeId { get; set; }
        public string SiteName { get; set; }
        public string EmployeeName { get; set; }
        public string SiteGroupName { get; set; }
        public string ModifiedByEmployeeName { get; set; }

Any assistance is greatly appreciated.

Body:
Instead of searching object with .IndexOf(), use property matching. Object will not match if two objects do not have same reference.

Try with following code block:

function getNonGroupEmployees() {
        var arr = $scope.employees.filter(function (item) {
            return $scope.allEmployeeGroups.find(function(p){
                return p.EmployeeId == item.EmployeeId
            })=== null;
        })
        return arr;
}

AS requested here are data structures:

Employee:

public System.Guid EmployeeId { get; set; }
        public Nullable<System.Guid> SiteId { get; set; }
        public string SiteName { get; set; }
        public string DisplayName { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string Suffix { get; set; }
        public string Alias { get; set; }
        public Nullable<System.DateTime> DOB { get; set; }
        public string SsnLastFour { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool IsActive { get; set; }
        public bool IsLoginEnabled { get; set; }
        public Nullable<System.DateTime> LastLogin { get; set; }
        public Nullable<System.Guid> SignatureTypeId { get; set; }
        public string SignatureType { get; set; }
        public string NumberHome { get; set; }
        public string NumberCell { get; set; }
        public bool IsSuperUser { get; set; }
        public bool IsDeleted { get; set; }
        public System.DateTime Created { get; set; }
        public System.DateTime LastModified { get; set; }
        public Nullable<System.Guid> ModifiedByEmployeeId { get; set; }
        public string ApiKey { get; set; }

Employee Group

            public Guid EmployeeGroupId { get; set; }
        public Guid SiteId { get; set; }
        public Guid EmployeeId { get; set; }
        public Guid SiteGroupId { get; set; }
        public bool IsDeleted { get; set; }
        public DateTime Created { get; set; }
        public DateTime LastModified { get; set; }
        public Guid? ModifiedByEmployeeId { get; set; }
        public string SiteName { get; set; }
        public string EmployeeName { get; set; }
        public string SiteGroupName { get; set; }
        public string ModifiedByEmployeeName { get; set; }


问:
How convert varchar2 to number(15,4) with arithmetic operations in Oracle
I have a table with VARCHAR2 datatypes and have to create view by casting varchar to number(15,4).But Varchar2 column contains data like [100 10/50], so the expected decimail value is 100.2.
Table

```<code>CREATE table test1
(
  id Varchar2(50)  ,
  Least Varchar(50));
</code>```

View:VW_test1

```<code>CREATE VIEW VW_test1
    AS
        (SELECT
id,
CAST(Least as Number(15,4))
 FROM test1).
</code>```

Can some one tell how to do this conversion.

答:
The solution below identifies one or three substrings that represent numbers (depending on whether there is a space in the input or not). It converts these substrings to numbers, and performs a division and an addition when needed. It also detects whether there is a minus sign and applies it after the other computations are finished.

I didn't cast the end result as NUMBER(15,4) - you can do that too, if needed.

LEAST is the name of an Oracle SQL function, and shouldn't be used as column name.

```<code>create or replace view vw_test1 as
(
  select id,
         case when instr(least, '-') = 0 then 1 else -1 end
         *
         (
           to_number(regexp_substr(least, '\[-?([^ ]+)( |\])', 1, 1, null, 1))
           + case when instr(least, ' ') = 0 then 0
                  else
                  to_number(regexp_substr(least, ' (.*)/', 1, 1, null, 1))
                     / to_number(regexp_substr(least, '/(.*)]', 1, 1, null, 1))
             end
         ) as least
  from   test1
)
;
</code>```

Body:
I have a table with VARCHAR2 datatypes and have to create view by casting varchar to number(15,4).But Varchar2 column contains data like [100 10/50], so the expected decimail value is 100.2.
Table

CREATE table test1
(
  id Varchar2(50)  ,
  Least Varchar(50));

View:VW_test1

CREATE VIEW VW_test1
    AS
        (SELECT
id,
CAST(Least as Number(15,4))
 FROM test1).

Can some one tell how to do this conversion.

Body:
The solution below identifies one or three substrings that represent numbers (depending on whether there is a space in the input or not). It converts these substrings to numbers, and performs a division and an addition when needed. It also detects whether there is a minus sign and applies it after the other computations are finished.

I didn't cast the end result as NUMBER(15,4) - you can do that too, if needed.

LEAST is the name of an Oracle SQL function, and shouldn't be used as column name.

create or replace view vw_test1 as
(
  select id,
         case when instr(least, '-') = 0 then 1 else -1 end
         *
         (
           to_number(regexp_substr(least, '\[-?([^ ]+)( |\])', 1, 1, null, 1))
           + case when instr(least, ' ') = 0 then 0
                  else
                  to_number(regexp_substr(least, ' (.*)/', 1, 1, null, 1))
                     / to_number(regexp_substr(least, '/(.*)]', 1, 1, null, 1))
             end
         ) as least
  from   test1
)
;