问:
One messenger bot on many pages
Currently I can use messenger bot on my pages only, but is it possible to create such a bot which can be installed on other's pages?
At this moment I only see my pages on app subscription page.</p>

答:
Yes, you can use your application on many pages.
You need to subscribe your app to another Page via POST me/subscribed_apps. (with Page access token)

After subscribing, your application will receive messages sent to other Page and you'll be able to send back message.

Check out fb documentation about Webhook subscription.

Title: One messenger bot on many pages


来源: stackexchange

问:
How does django's RegexURLPattern __init__ work
I am trying to understand the inner workings of the django framework.  Specifically, how URL requests and views function. I'm stuck in understanding how the init method in the RegexURLPattern class works. I'm a beginner with Python as well as django, and I'm not sure what to call this behavior in order to Google it. I'm using the pycharm debugger to step through the code as the django server is starting up and initializing it.From what I understand the initialization process is as follows.

Step 1: To begin the process of initializing the URL pattern the as_view class method is first initialized, it returns the view function

```<code>url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        PasswordResetConfirmView.as_view(
            template_name='passreset/pmp_password_reset_confirm.html',
        ), name='password_reset_confirm')
</code>```

Step 2: In django.conf.urls init this function receives the url, regex, reference to the view function from step 1 and possibly other arguments

```<code>def url(regex, view, kwargs=None, name=None):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        urlconf_module, app_name, namespace = view
        return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)
    else:
        raise TypeError('view must be a callable or a list/tuple in the case of include().')
</code>```

Step 3 In the elif block above a RegexURLPattern object is instantiated. Hitting F7 on the debugger and diving into the object as it is being instantiated drops me into this init block

```<code>class RegexURLPattern(LocaleRegexProvider):
    def __init__(self, regex, callback, default_args=None, name=None):
        LocaleRegexProvider.__init__(self, regex)
        self.callback = callback  # the view
        self.default_args = default_args or {}
        self.name = name
</code>```

Step 4 and Question 1 : Expanding the properties of self in the debugger I do not see a "callback" attribute, nor is it located int he LocaleRegexProvider mixin. In fact default_args, and name are also not prsent. Only a "lookup_str" and "regex" string property are present. Where does it come from? Does this call create it?

```<code>self = {RegexURLPattern} Unable to get repr for <class ...
 lookup_str = {str} 'Traceback (most recent call last):\n  File
 regex = {str} 'Traceback (most recent call last):\n  File
</code>```

Step 5 As i step through the init block and execute self.callback the lookup_str property is magically updated with the string name of the associated view class and a new regex object is added to Self

```<code>lookup_str = {str} 'django.contrib.auth.views.PasswordResetConfirmView'
regex = {SRE_Pattern} re.compile('^reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?
</code>```

Step 6 and Question 2: What about self.callback = callback makes the changes described in step 5 possible?

答:
All objects in Python are dynamic. There is nothing specific about the URL pattern classes here. The reason why you don't see the callback property when you enumerate the properties of the class at the start of the __init__ method is that it simply hasn't been defined yet: as you can see, that definition happens at the end of the method. If you stepped through to the end and enumerated the properties again, you would see that attribute.

The reason that lookup_str fails with an exception at first is that it is a property rather than an attribute; the underlying method relies on the existence of self.callback which again doesn't exist until the end of __init__.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to understand the inner workings of the django framework.  Specifically, how URL requests and views function. I'm stuck in understanding how the init method in the RegexURLPattern class works. I'm a beginner with Python as well as django, and I'm not sure what to call this behavior in order to Google it. I'm using the pycharm debugger to step through the code as the django server is starting up and initializing it.From what I understand the initialization process is as follows.

Step 1: To begin the process of initializing the URL pattern the as_view class method is first initialized, it returns the view function

url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        PasswordResetConfirmView.as_view(
            template_name='passreset/pmp_password_reset_confirm.html',
        ), name='password_reset_confirm')

Step 2: In django.conf.urls init this function receives the url, regex, reference to the view function from step 1 and possibly other arguments

def url(regex, view, kwargs=None, name=None):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        urlconf_module, app_name, namespace = view
        return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)
    else:
        raise TypeError('view must be a callable or a list/tuple in the case of include().')

Step 3 In the elif block above a RegexURLPattern object is instantiated. Hitting F7 on the debugger and diving into the object as it is being instantiated drops me into this init block

class RegexURLPattern(LocaleRegexProvider):
    def __init__(self, regex, callback, default_args=None, name=None):
        LocaleRegexProvider.__init__(self, regex)
        self.callback = callback  # the view
        self.default_args = default_args or {}
        self.name = name

Step 4 and Question 1 : Expanding the properties of self in the debugger I do not see a "callback" attribute, nor is it located int he LocaleRegexProvider mixin. In fact default_args, and name are also not prsent. Only a "lookup_str" and "regex" string property are present. Where does it come from? Does this call create it?

self = {RegexURLPattern} Unable to get repr for <class ...
 lookup_str = {str} 'Traceback (most recent call last):\n  File
 regex = {str} 'Traceback (most recent call last):\n  File

Step 5 As i step through the init block and execute self.callback the lookup_str property is magically updated with the string name of the associated view class and a new regex object is added to Self

lookup_str = {str} 'django.contrib.auth.views.PasswordResetConfirmView'
regex = {SRE_Pattern} re.compile('^reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?

Step 6 and Question 2: What about self.callback = callback makes the changes described in step 5 possible?


问:
How to crop a selected picture in Outlook mail body with VBA
I need VBA Code for crop picture in outlook mail body
Does anyone have code please share with me</p>

答:
After a 5 minute search on Google I found the following link https://www.experts-exchange.com/questions/27768384/Outlook-macro-to-resize-picture-s.html

to summarise though this should help you (untested):

This macro will resize all pictures, including those in your signature (if any), in the currently open message to 75% of their height and width.

Follow these instructions to add the code to Outlook.

Start Outlook

Press ALT+F11 to open the Visual Basic Editor

If not already expanded, expand Microsoft Office Outlook Objects

If not already expanded, expand Modules

Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module.

Copy the code from the code snippet box and paste it into the right-hand pane of Outlook's VB Editor window

Click the diskette icon on the toolbar to save the changes

Close the VB Editor

Here's how to add a button to the QAT for running the macro with a single click.
Outlook 2010.  http://www.howto-outlook.com/howto/macrobutton.htm#qat

```<code>Sub ResizeAllPicsTo75Pct()
    Const wdInlineShapePicture = 3
    Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object
    Set olkMsg = Application.ActiveInspector.CurrentItem
    Set wrdDoc = olkMsg.GetInspector.WordEditor
    For Each wrdShp In wrdDoc.InlineShapes
        If wrdShp.Type = wdInlineShapePicture Then
            wrdShp.ScaleHeight = 75
            wrdShp.ScaleWidth = 75
        End If
    Next
    Set olkMsg = Nothing
    Set wrdDoc = Nothing
    Set wrdShp = Nothing
End Sub
</code>```

Body:
After a 5 minute search on Google I found the following link https://www.experts-exchange.com/questions/27768384/Outlook-macro-to-resize-picture-s.html

to summarise though this should help you (untested):

This macro will resize all pictures, including those in your signature (if any), in the currently open message to 75% of their height and width.

Follow these instructions to add the code to Outlook.

Start Outlook

Press ALT+F11 to open the Visual Basic Editor

If not already expanded, expand Microsoft Office Outlook Objects

If not already expanded, expand Modules

Select an existing module (e.g. Module1) by double-clicking on it or create a new module by right-clicking Modules and selecting Insert > Module.

Copy the code from the code snippet box and paste it into the right-hand pane of Outlook's VB Editor window

Click the diskette icon on the toolbar to save the changes

Close the VB Editor

Here's how to add a button to the QAT for running the macro with a single click.
Outlook 2010.  http://www.howto-outlook.com/howto/macrobutton.htm#qat

Sub ResizeAllPicsTo75Pct()
    Const wdInlineShapePicture = 3
    Dim olkMsg As Outlook.MailItem, wrdDoc As Object, wrdShp As Object
    Set olkMsg = Application.ActiveInspector.CurrentItem
    Set wrdDoc = olkMsg.GetInspector.WordEditor
    For Each wrdShp In wrdDoc.InlineShapes
        If wrdShp.Type = wdInlineShapePicture Then
            wrdShp.ScaleHeight = 75
            wrdShp.ScaleWidth = 75
        End If
    Next
    Set olkMsg = Nothing
    Set wrdDoc = Nothing
    Set wrdShp = Nothing
End Sub


问:
Filtering a string from email body with Python
I am attempting to filter out only the text in the body of the email message using Python.
I need to get that "Needed Content" part of the mail.
Here's a string that I get when receiving a mail:

```<code>'--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/plain; charset="UTF-8"

Needed Content

--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/html; charset="UTF-8"

<div dir="ltr">Off</div>

--001a1144b8cc8e9a67055ddfb9ec--
'
</code>```

I have tried something like that but failed:

```<code>re.findall(r'/\r/\n(.+?)/\r/\n', body)
</code>```

To filter out between the line breaks but failed..
Thanks in advance!

答:
If you want to match \r\n, just use [\r\n] like so:

```<code>re.findall(r'(?<=[\r\n]).+(?=[\r\n])', body)
</code>```

But python re.findall has a flag to treat each line separately, which makes your code easier to read:

```<code>re.findall(r'^.+$', body, re.MULTILINE)
</code>```

Body:
I am attempting to filter out only the text in the body of the email message using Python.
I need to get that "Needed Content" part of the mail.
Here's a string that I get when receiving a mail:

'--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/plain; charset="UTF-8"

Needed Content

--001a1144b8cc8e9a67055ddfb9ec
Content-Type: text/html; charset="UTF-8"

Off

--001a1144b8cc8e9a67055ddfb9ec--
'

I have tried something like that but failed:

re.findall(r'/\r/\n(.+?)/\r/\n', body)

To filter out between the line breaks but failed..
Thanks in advance!

Body:
If you want to match \r\n, just use [\r\n] like so:

re.findall(r'(?<=[\r\n]).+(?=[\r\n])', body)

But python re.findall has a flag to treat each line separately, which makes your code easier to read:

re.findall(r'^.+$', body, re.MULTILINE)


问:
scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?
Consider the following code:

```<code>#include <stdio.h>

int main (void)
{
  char str1[128], str2[128], str3[128];

  printf ("\nEnter str1: ");
  scanf ("%[^\n]", str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf ("%[^\n]", str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf ("%[^\n]", str3);
  printf ("\nstr3 = %s", str3);

  printf ("\n");
  return 0;
}
</code>```

When it is executed only the first scanf stops for the prompt. The program does not stop for the next scanf s. But if the format string is changed from "%[^\n]" to " %[^\n]" (note the blank space before %), then it works okay. Does some existing newline character from the previous input buffer is automatically accepted ? But flushing stdin does not solve this.

What is the cause of this.

答:
Just adding a bit further to above answer-
If we want to remove some specific pattern, suppose numbers 0-9, from input stream then we will have to use getchar() for flushing buffer.

```<code>scanf("%[^0-9\n]", str1);
while(getchar() != '\n'); // this approach is much better bcz it will
                         // remove any number of left characters in buffer.
scanf("%c", &ch);
</code>```

So here if you pass ashish019 then only ashish will be copied to str and 019 would be left in buffer so for clearing that you need getchar() multiple times.

Body:
Consider the following code:

#include <stdio.h>

int main (void)
{
  char str1[128], str2[128], str3[128];

  printf ("\nEnter str1: ");
  scanf ("%[^\n]", str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf ("%[^\n]", str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf ("%[^\n]", str3);
  printf ("\nstr3 = %s", str3);

  printf ("\n");
  return 0;
}

When it is executed only the first scanf stops for the prompt. The program does not stop for the next scanf s. But if the format string is changed from "%[^\n]" to " %[^\n]" (note the blank space before %), then it works okay. Does some existing newline character from the previous input buffer is automatically accepted ? But flushing stdin does not solve this.

What is the cause of this.

Body:
Just adding a bit further to above answer-
If we want to remove some specific pattern, suppose numbers 0-9, from input stream then we will have to use getchar() for flushing buffer.

scanf("%[^0-9\n]", str1);
while(getchar() != '\n'); // this approach is much better bcz it will
                         // remove any number of left characters in buffer.
scanf("%c", &ch);

So here if you pass ashish019 then only ashish will be copied to str and 019 would be left in buffer so for clearing that you need getchar() multiple times.


问:
Countifs across BO Webi merge like correlated subquery
I'd like to do a countifs across a merge in BusinessObjects webi. I have two different data sets, which are merged on dimension SID. One data source which would be the source for the outer query, known as "Contacts", has the following columns:

SID (number, dimension)

Contact Date (date, dimension)

Contact Type (string, dimension)

The other data source, known as "Incidents", has the following columns:

SID (number, dimension)

Incident Date (date, dimension)

I would like to create a report in Webi based on the "Contacts" data source (maybe using merge, detail variables) with the following columns:

SID (number, dimension)

Contact Date (date, dimension)

Contact Type (string, dimension)

Incidents Influenced (VARIABLE countifs of records in "Incidents" where the following is true:)

```<code>[Incidents].[SID] = [Contacts].[SID]

[Incidents].[Incident Date]<=([Contact].[Contact Date]+7)

[Incidents].[Incident Date]>=[Contact].[Contact Date]
</code>```

Any thoughts? I've been trying to do a detail variable with count() where, but this doesn't seem to be working. I am using BI Platform 4.2, Webi. I have researched many websites external to Stack overflow, such as Variable to count Merged dimensions and count formula in webi report.

I have also looked at these two Stack Overflow articles, Business Objects CountIf by cell reference and Business Objects WEBI 3 universes in one report. However, none of these show how, at least in a way I am able to understand, how to overcome a context error that seems to occur whenever I create detail variables and measures across the SID merge.

Here are what the two data sources would look like, as well as the desired output on the report:

```<code>CONTACTS
SID     Contact Date     Contact Type
1        8/1/2017        ONB
1        8/15/2017       SCB
2        8/14/2017       ONB
3        8/19/2017       ONB
4        9/1/2017        SCB

INCIDENTS
SID     Incident Date
1       8/1/2017
1       8/7/2017
1       8/9/2017
1       8/21/2017
1       9/1/2017
1       10/1/2017
2       8/15/2017
4       9/2/2017

**DESIRED OUTPUT ON REPORT
SID     Contact Date     Contact Type     Incidents Influenced
1        8/1/2017        ONB               2
1        8/15/2017       SCB               1
2        8/14/2017       ONB               1
3        8/19/2017       ONB               0
4        9/1/2017        SCB               1
</code>```

答:
Amit Kumar from SAP answered my question here. Here is the solution he provided.

« Merge the SID objects and drag in the final table.

Drag Contact Date & Contact Type objects in the final table.

Create detail variable for Contact date as "V Contact Date" and for Incident date as "V Incident Date".

Right click on the table->Format table-> checked the checkbox "Show rows with empty dimensions"

Drag below formula for calculated column and see. »

=Sum(If([V Incident Date]<=RelativeDate([ V Contact Date];7) And ([V Incident Date]>=[ V Contact Date])) Then 1 Else 0)

ContentLicense: CC BY-SA 4.0

Body:
I'd like to do a countifs across a merge in BusinessObjects webi. I have two different data sets, which are merged on dimension SID. One data source which would be the source for the outer query, known as "Contacts", has the following columns:

SID (number, dimension)

Contact Date (date, dimension)

Contact Type (string, dimension)

The other data source, known as "Incidents", has the following columns:

SID (number, dimension)

Incident Date (date, dimension)

I would like to create a report in Webi based on the "Contacts" data source (maybe using merge, detail variables) with the following columns:

SID (number, dimension)

Contact Date (date, dimension)

Contact Type (string, dimension)

Incidents Influenced (VARIABLE countifs of records in "Incidents" where the following is true:)

[Incidents].[SID] = [Contacts].[SID]

[Incidents].[Incident Date]<=([Contact].[Contact Date]+7)

[Incidents].[Incident Date]>=[Contact].[Contact Date]

Any thoughts? I've been trying to do a detail variable with count() where, but this doesn't seem to be working. I am using BI Platform 4.2, Webi. I have researched many websites external to Stack overflow, such as Variable to count Merged dimensions and count formula in webi report.

I have also looked at these two Stack Overflow articles, Business Objects CountIf by cell reference and Business Objects WEBI 3 universes in one report. However, none of these show how, at least in a way I am able to understand, how to overcome a context error that seems to occur whenever I create detail variables and measures across the SID merge.

Here are what the two data sources would look like, as well as the desired output on the report:

CONTACTS
SID     Contact Date     Contact Type
1        8/1/2017        ONB
1        8/15/2017       SCB
2        8/14/2017       ONB
3        8/19/2017       ONB
4        9/1/2017        SCB

INCIDENTS
SID     Incident Date
1       8/1/2017
1       8/7/2017
1       8/9/2017
1       8/21/2017
1       9/1/2017
1       10/1/2017
2       8/15/2017
4       9/2/2017

**DESIRED OUTPUT ON REPORT
SID     Contact Date     Contact Type     Incidents Influenced
1        8/1/2017        ONB               2
1        8/15/2017       SCB               1
2        8/14/2017       ONB               1
3        8/19/2017       ONB               0
4        9/1/2017        SCB               1


问:
Full page images on click
I am sorry for not trying anything yet but I can't seem to find what I am looking for. I have this menu:

```<code><div class="overlay-navigation">
    <nav role="navigation">
        <ul class="test">
            <li>
                <a href="#" data-content=""></a>
            </li>
            <li><a href="#three" class="scrollTo" data-content="">tutorials</li>
            <li><a href="" target="_blank" data-content="">my creations</a>
            </li>
            <li><a href="#four" class="scroll" data-content="">contact</a>
            </li>
            <li>
                <a href="#" data-content=""></a>
            </li>
        </ul>
    </nav>
</div>
</code>```

When I click on my creations, I want a simple full screen image caroussel, gallery or flexbox to appear (whatever looks better, the menu opens at full screen) that's easy to close. I would appreciate any code examples so I can style it to my liking, I will only have about 4 images.

答: I think Magnific Popup or lightbox can help you out.</p>

Title: Full page images on click

Body:
I am sorry for not trying anything yet but I can't seem to find what I am looking for. I have this menu:

tutorials

my creations

contact

When I click on my creations, I want a simple full screen image caroussel, gallery or flexbox to appear (whatever looks better, the menu opens at full screen) that's easy to close. I would appreciate any code examples so I can style it to my liking, I will only have about 4 images.


问:
MySQL cache and date functions
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?

example:

```<code>$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
</code>```

vs

```<code>$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
</code>```

答:
Any function containing CURDATE() will not be cached. Source

Hardcoding the date should still be cached as far as I can tell. Though you might want to consider using the prepare functionality instead of splicing strings into your query (for sanity and security sake).

ContentLicense: CC BY-SA 2.5

Title: MySQL cache and date functions

Body:
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?

example:

$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';

vs

$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';


问:
Ruby/Rails ternary and range
I want to filter a parameter if it falls within a range of 1 to 100.

Controller:

```<code>@range = search_range(params[:range])
</code>```

Helper:

```<code>def search_range(range)
  range = range.to_i
  range == 1..100 ? range : 30
end
</code>```

But it's always returns 30... tried many things and normal "if/else" but want ternary operator.
Thanks

答:
If your params[:range] returns a number, I think you might need something like the following:

```<code>def search_range(range)
  range = range.to_i
  range == (1..100).include?(range) ? range : 30
end
</code>```

Is that what you mean? I.E. if the 'range' variable is within 1 to 100 return it, else 30?

Update:

I've done a quick benchmark on the options on the page, and between? comes up quickest:

```<code>              user     system      total        real
include?  0.230000   0.000000   0.230000 (  0.239637)
between?  0.130000   0.000000   0.130000 (  0.129158)
===       0.290000   0.000000   0.290000 (  0.293817)
</code>```

Title: Ruby/Rails ternary and range

Body:
I want to filter a parameter if it falls within a range of 1 to 100.

Controller:

@range = search_range(params[:range])

Helper:

def search_range(range)
  range = range.to_i
  range == 1..100 ? range : 30
end

But it's always returns 30... tried many things and normal "if/else" but want ternary operator.
Thanks

Body:
If your params[:range] returns a number, I think you might need something like the following:

def search_range(range)
  range = range.to_i
  range == (1..100).include?(range) ? range : 30
end

Is that what you mean? I.E. if the 'range' variable is within 1 to 100 return it, else 30?

Update:

I've done a quick benchmark on the options on the page, and between? comes up quickest:

              user     system      total        real
include?  0.230000   0.000000   0.230000 (  0.239637)
between?  0.130000   0.000000   0.130000 (  0.129158)
===       0.290000   0.000000   0.290000 (  0.293817)


问:
Are there any standard for JavaFX directory/package structure?
I'm just starting to develop a javafx application, and i'm reading some tutorials. In those tutorials there are no mentions to good practices or propper (standard) ways to structure your app. Even though FXML documents provide a separation of the presentation layer, .fxml and .css files are stored in the same directory as .java files, and since I come from developing using frameworks like django and rails, the lack of a standard structure or layer separation disturbs me.

Is there any propper (more MVCish) way to structure a project? or is the one proposed by those tutorials the propper way?

thanks for your help, and notice that I'm not implying that that way is not correct. It's only that I'm used to the kind of structure proposed by popular web frameworks, and I would like to work like that with this new app (which is my grade project, btw).

答:
I usually have two packages: one for the FXML, CSS and controller files (ui) and another for the underlying Java code (could be named core, or something specific to the app like analysis or evaluator).

However, having all the UI files lumped into one package could become unwieldly, so one could (instead or additionally) split these files by type (into separate FXML, CSS and controller packages) as in Marcel's answer. Similarly, one could split the package containing the underlying Java code further too.


问:
How to add new column from list column value
How to unlist list column and add new column from unlist column value in data frame.Can you please find my df below.

My data Frame.

```<code>Status       AuditResult                                               Deship                                        Item

Active    list(DDID=c("2","First"),Dvalue=c("Bpin","67"))  list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=9,Deship =list(list(IDesc ="A",vendor=5)))

Inactive  list(DDID=c("Second","8"),Dvalue=c("CA","98"))   list(UserID=2,Add="Stet,Bpin")  list(Menu=1,Bill=8,Deship =list(list(IDesc ="B,N,O",vendor=4)))

OnHold    list(DDID=c("78","8",NA),Dvalue=c("UK","76"))   list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=7,Deship =list(list(IDesc ="L,q",vendor=2)))
</code>```

Expected data frame.

```<code>Status   DDID          Dvalue         UserID    Add         Menu  Bill  IDesc    vendor

Active   "2","First"   "Bpin","67"    1       "Stet,Bpin"    1     9     "A"        5

Inactive "Second","8"  "CA","98"      2       "Stet,Bpin"    1     8     "B,N,O"    4

OnHold   "78","8",NA   "UK","76"      1       "Stet,Bpin"    1     7     "L,q"      2
</code>```

please suggest me if any unstructured code.

Dput.

```<code>structure(list(Status = c("Active", "Inactive", "OnHold"), AuditResult = list(
    structure(list(DDID = c(2, "First"), Dvalue = c("Bpin",
    67)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("Second", 8), Dvalue = c("CA",
    98)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("78","8",NA), Dvalue = c("UK",
    76)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2)),
    Deship = list(structure(list(UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 2, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L)), Item = list(
structure(list(Menu = 1, Bill = 9.0, Deship = list(
            structure(list(IDesc = "A", vendor = 5), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 8.0, Deship = list(
            structure(list(IDesc = "B,N,O", vendor = 4), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 7.0, Deship = list(
            structure(list(IDesc = "L,q", vendor = 2), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L))), .Names = c("Status",
"AuditResult", "Deship", "Item"), row.names = c(NA,
3L), class = "data.frame")
</code>```

答:
Assuming that the name of your data frame is called dt, here is an option.

```<code>library(tidyverse)

dt2 <- dt %>%
  select(Status, AuditResult) %>%
  mutate(DDID = map(AuditResult, ~.$DDID),
         Dvalue = map(AuditResult, ~.$Dvalue)) %>%
  mutate(DDID = map_chr(DDID, ~toString(.)),
         Dvalue = map_chr(Dvalue, ~toString(.))) %>%
  select(-AuditResult)

dt3 <- dt %>%
  select(Status, Deship) %>%
  unnest()

dt4 <- dt %>%
  select(Status, Item) %>%
  unnest() %>%
  unnest()

dt_final <- reduce(list(dt2, dt3, dt4), left_join, by = "Status")
dt_final
#     Status      DDID   Dvalue UserID        Add Menu Bill IDesc vendor
# 1   Active  2, First Bpin, 67      1 Stet, Bpin    1    9     A      5
# 2 Inactive Second, 8   CA, 98      2 Stet, Bpin    1    8 B,N,O      4
# 3   OnHold 78, 8, NA   UK, 76      1 Stet, Bpin    1    7   L,q      2
</code>```

Body:
How to unlist list column and add new column from unlist column value in data frame.Can you please find my df below.

My data Frame.

Status       AuditResult                                               Deship                                        Item

Active    list(DDID=c("2","First"),Dvalue=c("Bpin","67"))  list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=9,Deship =list(list(IDesc ="A",vendor=5)))

Inactive  list(DDID=c("Second","8"),Dvalue=c("CA","98"))   list(UserID=2,Add="Stet,Bpin")  list(Menu=1,Bill=8,Deship =list(list(IDesc ="B,N,O",vendor=4)))

OnHold    list(DDID=c("78","8",NA),Dvalue=c("UK","76"))   list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=7,Deship =list(list(IDesc ="L,q",vendor=2)))

Expected data frame.

Status   DDID          Dvalue         UserID    Add         Menu  Bill  IDesc    vendor

Active   "2","First"   "Bpin","67"    1       "Stet,Bpin"    1     9     "A"        5

Inactive "Second","8"  "CA","98"      2       "Stet,Bpin"    1     8     "B,N,O"    4

OnHold   "78","8",NA   "UK","76"      1       "Stet,Bpin"    1     7     "L,q"      2

please suggest me if any unstructured code.

Dput.

structure(list(Status = c("Active", "Inactive", "OnHold"), AuditResult = list(
    structure(list(DDID = c(2, "First"), Dvalue = c("Bpin",
    67)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("Second", 8), Dvalue = c("CA",
    98)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("78","8",NA), Dvalue = c("UK",
    76)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2)),
    Deship = list(structure(list(UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 2, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L)), Item = list(
structure(list(Menu = 1, Bill = 9.0, Deship = list(
            structure(list(IDesc = "A", vendor = 5), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 8.0, Deship = list(
            structure(list(IDesc = "B,N,O", vendor = 4), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 7.0, Deship = list(
            structure(list(IDesc = "L,q", vendor = 2), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L))), .Names = c("Status",
"AuditResult", "Deship", "Item"), row.names = c(NA,
3L), class = "data.frame")

Body:
Assuming that the name of your data frame is called dt, here is an option.

library(tidyverse)

dt2 <- dt %>%
  select(Status, AuditResult) %>%
  mutate(DDID = map(AuditResult, ~.$DDID),
         Dvalue = map(AuditResult, ~.$Dvalue)) %>%
  mutate(DDID = map_chr(DDID, ~toString(.)),
         Dvalue = map_chr(Dvalue, ~toString(.))) %>%
  select(-AuditResult)

dt3 <- dt %>%
  select(Status, Deship) %>%
  unnest()

dt4 <- dt %>%
  select(Status, Item) %>%
  unnest() %>%
  unnest()

dt_final <- reduce(list(dt2, dt3, dt4), left_join, by = "Status")
dt_final
#     Status      DDID   Dvalue UserID        Add Menu Bill IDesc vendor
# 1   Active  2, First Bpin, 67      1 Stet, Bpin    1    9     A      5
# 2 Inactive Second, 8   CA, 98      2 Stet, Bpin    1    8 B,N,O      4
# 3   OnHold 78, 8, NA   UK, 76      1 Stet, Bpin    1    7   L,q      2


问:
Visual studio equivalent of java System.out
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

```<code>var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);
</code>```

答: You can use Console.WriteLine() to write out any native type. To see the output you must write console application (like in Java), then the output will be displayed in the Command Prompt, or if you are developing a windows GUI application, in Visual Studio you must turn on "Output" panel (under View) to see the commands output.

Body:
What do I use in Visual Studio (C#) to perform the equivalent of Java's System.out.println( /*stuff*/ ) ?

Does the output from the command show in the Output window in the IDE?

I have a button on a webpage that calls a service which returns a string. I want to see what's in the string and have tried all the variations below and nothing ever shows up in the output. It also doesn't stop on the breakpoint so I can check if there are any results.

var service = new OTest.TylerAPI.APIWebServiceSoapClient();
results = service.OdysseyMsgExecution("<Message MessageType='FindCaseByCaseNumber' Source='APIMessage' ReferenceNumber='1' NodeID='1' UserID='1'> <CaseNumber>T4CV0043212010</CaseNumber></Message>", "NMODYSSEYMETRO");
System.Diagnostics.Debug.Write(results);


问:
Yii2 right join only returning 2 columns
Working on an API and I have this query:

```<code>$query = CallerIdentity::findNonGeo()->join( 'RIGHT JOIN', 'ehadata', 'caller_ids.cidref = ehadata.cidref')
            ->select('ehadata.*')
            ->where(['caller_ids.cidref' => $id]);

        echo $query->getSQL();die;
</code>```

The output of the ->getSQL() function is:

```<code>SELECT `ehadata`.* FROM `caller_ids` RIGHT JOIN `ehadata` ON caller_ids.cidref = ehadata.cidref WHERE `caller_ids`.`cidref`='256'
</code>```

and the result of running the query through the function in postman returns:

```<code>{
"cidref": 256,
"status": 0
}
</code>```

However when I run the query in adminer the result is:

Has anyone got any idea why this might be? I am well and truly confused. Any help is massively appreciated.

EhaData model

```<code>class EHAData extends \yii\db\ActiveRecord
{
/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'ehadata';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['cidref', 'status', 'name', 'premesis', 'thoroughfare', 'locality', 'postcode'], 'required'],
        [['cidref', 'status'], 'integer'],
        [['modified'], 'safe'],
        [['title', 'forename', 'postcode'], 'string', 'max' => 20],
        [['name', 'bussuffix'], 'string', 'max' => 50],
        [['premesis'], 'string', 'max' => 60],
        [['thoroughfare'], 'string', 'max' => 55],
        [['locality'], 'string', 'max' => 30],
        [['cidref'], 'exist', 'skipOnError' => true, 'targetClass' => CallerIdentity::className(), 'targetAttribute' => ['cidref' => 'cidref']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'ehaid' => 'Ehaid',
        'cidref' => 'Cidref',
        'status' => 'Status',
        'title' => 'Title',
        'forename' => 'Forename',
        'name' => 'Name',
        'bussuffix' => 'Bussuffix',
        'premesis' => 'Premesis',
        'thoroughfare' => 'Thoroughfare',
        'locality' => 'Locality',
        'postcode' => 'Postcode',
        'modified' => 'Modified',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getCallerIdentity()
{
    return $this->hasOne(CallerIdentity::className(), ['cidref' => 'cidref']);
}
}
</code>```

Caller Identity model

```<code>class CallerIdentity extends \yii\db\ActiveRecord
{

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'caller_ids';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['custref', 'caller_id', 'start_date'], 'required'],
        [['custref', 'status', 'target_index'], 'integer'],
        [['type', 'conf_call', 'magrathea', 'outbound_only', 'callrec_outbound', 'callrec_inbound'], 'string'],
        [['start_date', 'last_polled', 'last_modified', 'created'], 'safe'],
        [['caller_id'], 'string', 'max' => 15],
        [['location', 'destination', 'redirect'], 'string', 'max' => 120],
        [['country_code'], 'string', 'max' => 3],
        [['details'], 'string', 'max' => 180],
        [['expiry'], 'string', 'max' => 18],
        [['custref'], 'exist', 'skipOnError' => true, 'targetClass' => Customer::className(), 'targetAttribute' => ['custref' => 'custref']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'cidref' => 'Cidref',
        'custref' => 'Custref',
        'caller_id' => 'Caller ID',
        'location' => 'Location',
        'destination' => 'Destination',
        'redirect' => 'Redirect',
        'type' => 'Type',
        'conf_call' => 'Conf Call',
        'magrathea' => 'Magrathea',
        'outbound_only' => 'Outbound Only',
        'callrec_outbound' => 'Callrec Outbound',
        'callrec_inbound' => 'Callrec Inbound',
        'country_code' => 'Country Code',
        'details' => 'Details',
        'status' => 'Status',
        'start_date' => 'Start Date',
        'expiry' => 'Expiry',
        'target_index' => 'Target Index',
        'last_polled' => 'Last Polled',
        'last_modified' => 'Last Modified',
        'created' => 'Created',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getCustref()
{
    return $this->hasOne(Customer::className(), ['custref' => 'custref']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getEhadata()
{
    return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}

/**
 * @inheritdoc
 * @return BanQuery the active query used by this AR class.
 */
public static function find()
{
    $query = new CallerIdentityQuery(get_called_class());

    $query->select([
        'caller_ids.cidref','custref', 'caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'caller_ids.status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE caller_ids.status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->with('ehadata')->asArray()->all();

    return $query;
}
public static function findNonGeo()
{
    $query = new CallerIdentityQuery(get_called_class());
    $query->select([
        'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->where(['caller_ids.status' => '1'])
        ->andWhere(['type' => 'N']);
    return $query;
}
public static function findFax()
{
    $query = new CallerIdentityQuery(get_called_class());

    $query->select([
        'cidref', 'custref','caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->where(['status' => '1'])
        ->andWhere(['type' => 'F']);
    return $query;
}
public static function findConference()
{
    $query = new CallerIdentityQuery(get_called_class());

    $query->select([
        'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->where(['status' => '1'])
        ->andWhere(['conf_call' => 'y']);
    return $query;
}

}
</code>```

答:
Solved by adding this in to the CallerIdentity model. </p>

```<code>public function fields()
{
    $fields = parent::fields();
    $fields[] = 'ehadata'; //name of relation
    return $fields;
}
</code>```

<p>Output: </p>

```<code> {
    "cidref": 1234,
    "custref": 288,
    "caller_id": "01758364762",
    "expiry": null,
    "conf_call": "n",
    "type": "S",
    "redirect": null,
    "destination": "846285845@sip.example.co.uk",
    "status": 1,
    "start_date": "2011-11-01",
    "last_polled": "2011-11-01 13:59:51",
    "ehadata": [
        {
            "status": 0,
            "name": "Blah blah blah",
            "bussuffix": "Ltd",
            "premesis": "Blah House",
            "thoroughfare": "Blah Road",
            "locality": "Blahbach",
            "postcode": "BLAH BLAH"
        }
    ]
},
</code>```

Body:
Working on an API and I have this query:

$query = CallerIdentity::findNonGeo()->join( 'RIGHT JOIN', 'ehadata', 'caller_ids.cidref = ehadata.cidref')
            ->select('ehadata.*')
            ->where(['caller_ids.cidref' => $id]);

        echo $query->getSQL();die;

The output of the ->getSQL() function is:

SELECT `ehadata`.* FROM `caller_ids` RIGHT JOIN `ehadata` ON caller_ids.cidref = ehadata.cidref WHERE `caller_ids`.`cidref`='256'

and the result of running the query through the function in postman returns:

{
"cidref": 256,
"status": 0
}

However when I run the query in adminer the result is:

Has anyone got any idea why this might be? I am well and truly confused. Any help is massively appreciated.

EhaData model

class EHAData extends \yii\db\ActiveRecord
{
/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'ehadata';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['cidref', 'status', 'name', 'premesis', 'thoroughfare', 'locality', 'postcode'], 'required'],
        [['cidref', 'status'], 'integer'],
        [['modified'], 'safe'],
        [['title', 'forename', 'postcode'], 'string', 'max' => 20],
        [['name', 'bussuffix'], 'string', 'max' => 50],
        [['premesis'], 'string', 'max' => 60],
        [['thoroughfare'], 'string', 'max' => 55],
        [['locality'], 'string', 'max' => 30],
        [['cidref'], 'exist', 'skipOnError' => true, 'targetClass' => CallerIdentity::className(), 'targetAttribute' => ['cidref' => 'cidref']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'ehaid' => 'Ehaid',
        'cidref' => 'Cidref',
        'status' => 'Status',
        'title' => 'Title',
        'forename' => 'Forename',
        'name' => 'Name',
        'bussuffix' => 'Bussuffix',
        'premesis' => 'Premesis',
        'thoroughfare' => 'Thoroughfare',
        'locality' => 'Locality',
        'postcode' => 'Postcode',
        'modified' => 'Modified',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getCallerIdentity()
{
    return $this->hasOne(CallerIdentity::className(), ['cidref' => 'cidref']);
}
}

Caller Identity model

class CallerIdentity extends \yii\db\ActiveRecord
{

/**
 * @inheritdoc
 */
public static function tableName()
{
    return 'caller_ids';
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['custref', 'caller_id', 'start_date'], 'required'],
        [['custref', 'status', 'target_index'], 'integer'],
        [['type', 'conf_call', 'magrathea', 'outbound_only', 'callrec_outbound', 'callrec_inbound'], 'string'],
        [['start_date', 'last_polled', 'last_modified', 'created'], 'safe'],
        [['caller_id'], 'string', 'max' => 15],
        [['location', 'destination', 'redirect'], 'string', 'max' => 120],
        [['country_code'], 'string', 'max' => 3],
        [['details'], 'string', 'max' => 180],
        [['expiry'], 'string', 'max' => 18],
        [['custref'], 'exist', 'skipOnError' => true, 'targetClass' => Customer::className(), 'targetAttribute' => ['custref' => 'custref']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'cidref' => 'Cidref',
        'custref' => 'Custref',
        'caller_id' => 'Caller ID',
        'location' => 'Location',
        'destination' => 'Destination',
        'redirect' => 'Redirect',
        'type' => 'Type',
        'conf_call' => 'Conf Call',
        'magrathea' => 'Magrathea',
        'outbound_only' => 'Outbound Only',
        'callrec_outbound' => 'Callrec Outbound',
        'callrec_inbound' => 'Callrec Inbound',
        'country_code' => 'Country Code',
        'details' => 'Details',
        'status' => 'Status',
        'start_date' => 'Start Date',
        'expiry' => 'Expiry',
        'target_index' => 'Target Index',
        'last_polled' => 'Last Polled',
        'last_modified' => 'Last Modified',
        'created' => 'Created',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getCustref()
{
    return $this->hasOne(Customer::className(), ['custref' => 'custref']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getEhadata()
{
    return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}

/**
 * @inheritdoc
 * @return BanQuery the active query used by this AR class.
 */
public static function find()
{
    $query = new CallerIdentityQuery(get_called_class());

    $query->select([
        'caller_ids.cidref','custref', 'caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'caller_ids.status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE caller_ids.status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->with('ehadata')->asArray()->all();

    return $query;
}
public static function findNonGeo()
{
    $query = new CallerIdentityQuery(get_called_class());
    $query->select([
        'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->where(['caller_ids.status' => '1'])
        ->andWhere(['type' => 'N']);
    return $query;
}
public static function findFax()
{
    $query = new CallerIdentityQuery(get_called_class());

    $query->select([
        'cidref', 'custref','caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->where(['status' => '1'])
        ->andWhere(['type' => 'F']);
    return $query;
}
public static function findConference()
{
    $query = new CallerIdentityQuery(get_called_class());

    $query->select([
        'cidref', 'custref', 'caller_id', 'expiry', 'conf_call',
        'type', 'redirect', 'destination', 'status', 'start_date',
        'statusDesc' => new \yii\db\Expression("CASE status
            WHEN 0 THEN 'Deactivated'
            WHEN 1 THEN 'Active'
            WHEN 2 THEN 'Inactive'
            WHEN 3 THEN 'Unregistered'
            ELSE 'Permanently Deleted' END")])
        ->where(['status' => '1'])
        ->andWhere(['conf_call' => 'y']);
    return $query;
}

}

Body:
Solved by adding this in to the CallerIdentity model.

public function fields()
{
    $fields = parent::fields();
    $fields[] = 'ehadata'; //name of relation
    return $fields;
}

Output:

 {
    "cidref": 1234,
    "custref": 288,
    "caller_id": "01758364762",
    "expiry": null,
    "conf_call": "n",
    "type": "S",
    "redirect": null,
    "destination": "846285845@sip.example.co.uk",
    "status": 1,
    "start_date": "2011-11-01",
    "last_polled": "2011-11-01 13:59:51",
    "ehadata": [
        {
            "status": 0,
            "name": "Blah blah blah",
            "bussuffix": "Ltd",
            "premesis": "Blah House",
            "thoroughfare": "Blah Road",
            "locality": "Blahbach",
            "postcode": "BLAH BLAH"
        }
    ]
},


问:
Limiting fields on $lookup mongo
I have a Mongo object with the below schema.

```<code>{
    "_id" : "59fffda313d02500116e83bf::5a059c67f3ff3b001105c509",
    "quizzes" : [
        {
            "topics" : [
                ObjectId("5a05a1e1fc698f00118470e2")
            ],
            "isCorrect" : true,
            "status" : 2,
            "isUsed" : true,
            "askBack" : false,
            "isRestricted" : false,
            "rejected" : false,
            "createdAt" : ISODate("2017-11-10T12:56:01.273Z"),
            "updatedAt" : ISODate("2017-11-10T12:56:02.808Z"),
            "answerRead" : false,
            "participantAnswer" : "5a054210d74fe90011d5f5e2",
            "correctAnswer" : "5a054210d74fe90011d5f5e2",
            "question" : ObjectId("5a054210d74fe90011d5f5e0"),
            "participant" : ObjectId("59fffda313d02500116e83bf"),
            "author" : ObjectId("5a059c67f3ff3b001105c509"),
            "_id" : ObjectId("5a05a1e1fc698f00118470e1")
        },
        {
            "topics" : [
                ObjectId("5a054210d74fe90011d5f5e1")
            ],
            "isCorrect" : false,
            "status" : 2,
            "isUsed" : true,
            "askBack" : true,
            "isRestricted" : false,
            "rejected" : false,
            "createdAt" : ISODate("2017-11-10T12:57:33.910Z"),
            "updatedAt" : ISODate("2017-11-10T12:57:33.910Z"),
            "answerRead" : true,
            "correctAnswer" : "5a054210d74fe90011d5f5e2",
            "question" : ObjectId("5a054210d74fe90011d5f5e0"),
            "participant" : ObjectId("5a059c67f3ff3b001105c509"),
            "author" : ObjectId("59fffda313d02500116e83bf"),
            "_id" : ObjectId("5a05a23dfc698f00118470f5")
        }
    ],
    "participants" : [
        ObjectId("5a059c67f3ff3b001105c509"),
        ObjectId("59fffda313d02500116e83bf")
    ],
    "__v" : 0,
    "skippedQuestionIds" : []
}
</code>```

The 'author' and 'participant' fields are foreign key references to another collection with the below schema.

```<code>{
"_id" : ObjectId("5739bcdd4fb7d8030050bc04"),
"password" : "$2a$06$4Rmiya6Vh9aENXxKoD56UOIG3ZiGNzH.Ed5lgY8aiJ4OidQPAf6wq",
"email" : "m@m.com",
"username" : "mm",
"birthday" : ISODate("2016-05-03T18:30:00.000Z"),
"lastName" : "m",
"firstName" : "m",
"devices" : [],
"role" : "user",
"updatedAt" : ISODate("2017-08-01T13:26:43.510Z"),
"createdAt" : ISODate("2016-05-16T12:28:13.063Z"),
"lastUpdated" : ISODate("2017-08-02T07:39:02.960Z"),
"active" : false,
"points" : 0,
"topicLocked" : [
    "flirty",
    "dirty",
    "mahesh_test"
],
"hashfriends" : [],
"blockedList" : [],
"friends" : [
    {
        "user" : ObjectId("586b6fd12631000004812a68"),
        "_id" : ObjectId("58e60399ca9a180004072089"),
        "topicExhausted" : [],
        "scoreInPercentage" : 0,
        "totalQuizAnswered" : 1,
        "isCrew" : false,
        "isFriendo" : false,
        "scoreRank" : "You’re tied 1 to 1",
        "score" : 1,
        "lastPlayed" : ISODate("2017-04-06T09:37:48.843Z")
    }
],
"meta" : {
    "totalInvites" : -3,
    "totalFriends" : 1
},
"isDeleted" : false,
"__v" : 3,
"androidDevices" : [],
"iosDevices" : [],
"isAgeRestrictedCategories" : [
    ObjectId("571727dde30aef0300a95725")
],
"usernameAsEntered" : "mm",
"platform" : "ios",
"celebParticipants" : [],
"lastActivity" : ISODate("2017-04-06T09:30:34.054Z"),
"lastNudged" : ISODate("2016-04-25T06:46:38.267Z")
}
</code>```

I need to run an aggregate on the first collection and limit the number of objects in the quizzes subdocument, and also sort it on the updatedAt timestamp.

I also want to populate author and participant inside each element in quizzes array, from the users collection. However, I'm having a hard time retrieving the fields I need, i.e only username, firstName, lastName, _id, meta and active.

I managed upto this point.

```<code>db.getCollection('usergames').aggregate([{$match: {_id: "5a059c56f3ff3b001105c508::5a059c67f3ff3b001105c509"}},
{$unwind: '$quizzes'},
{$lookup: {
    "from":'users',
    "localField":'quizzes.author',
    'foreignField': '_id',
    "as": 'quizzes.author'
}},
{$unwind: '$quizzes.author'},
{$sort: {'quizzes.updatedAt': -1}},
{$group: {_id: '$_id', quizzes: {$push: '$quizzes'}}},
{$project: {
  _id: 1,
  'quizzes': {
            $slice:['$quizzes', 0, 3]
  }}
}
])
</code>```

However, this is the response I desire.

```<code>{
"_id" : "59fffda313d02500116e83bf::5a059c67f3ff3b001105c509",
"quizzes" : [
    {
        "topics" : [
            ObjectId("5a054210d74fe90011d5f5e1")
        ],
        "isCorrect" : false,
        "status" : 2,
        "isUsed" : true,
        "askBack" : true,
        "isRestricted" : false,
        "rejected" : false,
        "createdAt" : ISODate("2017-11-10T12:57:33.910Z"),
        "updatedAt" : ISODate("2017-11-10T12:57:33.910Z"),
        "answerRead" : true,
        "correctAnswer" : "5a054210d74fe90011d5f5e2",
        "question" : ObjectId("5a054210d74fe90011d5f5e0"),
        "author" :{
                    "_id": "59fffda313d02500116e83bf",
                    "username": "f2",
                    "lastName": "2",
                    "firstName": "f",
                    "active": false,
                    "meta": {
                         "totalInvites": 0,
                         "totalFriends": 1
                   }
          },
        "participant": {
                  "_id": "5a059c67f3ff3b001105c509",
                  "username": "chandan",
                  "lastName": "kumar",
                  "firstName": "chandan",
                  "active": false,
                  "meta": {
                     "totalInvites": 0,
                     "totalFriends": 16
                  }

     "_id" : ObjectId("5a05a23dfc698f00118470f5")
    }
],
"participants" : [
    ObjectId("5a059c67f3ff3b001105c509"),
    ObjectId("59fffda313d02500116e83bf")
],
"__v" : 0,
"skippedQuestionIds" : []
}
</code>```

Can the lookup be done after the initial projection, and how do I limit fields. Any help will be appreciated. Thanks

答:
I won't familiarize myself enough with your schema to work out the entire pipeline, but If I could generalize a bit:

Yes, the $lookup can be done after a $project operation.  You can have multiple $project operations (indeed multiple of any operation) in an aggregation.

A $lookup operation could be followed by a $project operation to normalize your results in the following fashion:

```<code>{$lookup: {
    "from":'users',
    "localField":'quizzes.author',
    'foreignField': '_id',
    "as": 'authors'
}},
{$project: {
    'author._id': { $arrayElemAt: ['$authors._id', 0] },
    'author.username': { $arrayElemAt: ['$authors.username', 0] },
    // other fields can be projected as needed
}},
</code>```

Since $lookup returns results in an array, the above example uses $arrayElemAt to get the first element and project the desired properties one by one.

Title: Limiting fields on $lookup mongo

Body:
I have a Mongo object with the below schema.

{
    "_id" : "59fffda313d02500116e83bf::5a059c67f3ff3b001105c509",
    "quizzes" : [
        {
            "topics" : [
                ObjectId("5a05a1e1fc698f00118470e2")
            ],
            "isCorrect" : true,
            "status" : 2,
            "isUsed" : true,
            "askBack" : false,
            "isRestricted" : false,
            "rejected" : false,
            "createdAt" : ISODate("2017-11-10T12:56:01.273Z"),
            "updatedAt" : ISODate("2017-11-10T12:56:02.808Z"),
            "answerRead" : false,
            "participantAnswer" : "5a054210d74fe90011d5f5e2",
            "correctAnswer" : "5a054210d74fe90011d5f5e2",
            "question" : ObjectId("5a054210d74fe90011d5f5e0"),
            "participant" : ObjectId("59fffda313d02500116e83bf"),
            "author" : ObjectId("5a059c67f3ff3b001105c509"),
            "_id" : ObjectId("5a05a1e1fc698f00118470e1")
        },
        {
            "topics" : [
                ObjectId("5a054210d74fe90011d5f5e1")
            ],
            "isCorrect" : false,
            "status" : 2,
            "isUsed" : true,
            "askBack" : true,
            "isRestricted" : false,
            "rejected" : false,
            "createdAt" : ISODate("2017-11-10T12:57:33.910Z"),
            "updatedAt" : ISODate("2017-11-10T12:57:33.910Z"),
            "answerRead" : true,
            "correctAnswer" : "5a054210d74fe90011d5f5e2",
            "question" : ObjectId("5a054210d74fe90011d5f5e0"),
            "participant" : ObjectId("5a059c67f3ff3b001105c509"),
            "author" : ObjectId("59fffda313d02500116e83bf"),
            "_id" : ObjectId("5a05a23dfc698f00118470f5")
        }
    ],
    "participants" : [
        ObjectId("5a059c67f3ff3b001105c509"),
        ObjectId("59fffda313d02500116e83bf")
    ],
    "__v" : 0,
    "skippedQuestionIds" : []
}

The 'author' and 'participant' fields are foreign key references to another collection with the below schema.

{
"_id" : ObjectId("5739bcdd4fb7d8030050bc04"),
"password" : "$2a$06$4Rmiya6Vh9aENXxKoD56UOIG3ZiGNzH.Ed5lgY8aiJ4OidQPAf6wq",
"email" : "m@m.com",
"username" : "mm",
"birthday" : ISODate("2016-05-03T18:30:00.000Z"),
"lastName" : "m",
"firstName" : "m",
"devices" : [],
"role" : "user",
"updatedAt" : ISODate("2017-08-01T13:26:43.510Z"),
"createdAt" : ISODate("2016-05-16T12:28:13.063Z"),
"lastUpdated" : ISODate("2017-08-02T07:39:02.960Z"),
"active" : false,
"points" : 0,
"topicLocked" : [
    "flirty",
    "dirty",
    "mahesh_test"
],
"hashfriends" : [],
"blockedList" : [],
"friends" : [
    {
        "user" : ObjectId("586b6fd12631000004812a68"),
        "_id" : ObjectId("58e60399ca9a180004072089"),
        "topicExhausted" : [],
        "scoreInPercentage" : 0,
        "totalQuizAnswered" : 1,
        "isCrew" : false,
        "isFriendo" : false,
        "scoreRank" : "You’re tied 1 to 1",
        "score" : 1,
        "lastPlayed" : ISODate("2017-04-06T09:37:48.843Z")
    }
],
"meta" : {
    "totalInvites" : -3,
    "totalFriends" : 1
},
"isDeleted" : false,
"__v" : 3,
"androidDevices" : [],
"iosDevices" : [],
"isAgeRestrictedCategories" : [
    ObjectId("571727dde30aef0300a95725")
],
"usernameAsEntered" : "mm",
"platform" : "ios",
"celebParticipants" : [],
"lastActivity" : ISODate("2017-04-06T09:30:34.054Z"),
"lastNudged" : ISODate("2016-04-25T06:46:38.267Z")
}

I need to run an aggregate on the first collection and limit the number of objects in the quizzes subdocument, and also sort it on the updatedAt timestamp.

I also want to populate author and participant inside each element in quizzes array, from the users collection. However, I'm having a hard time retrieving the fields I need, i.e only username, firstName, lastName, _id, meta and active.

I managed upto this point.

db.getCollection('usergames').aggregate([{$match: {_id: "5a059c56f3ff3b001105c508::5a059c67f3ff3b001105c509"}},
{$unwind: '$quizzes'},
{$lookup: {
    "from":'users',
    "localField":'quizzes.author',
    'foreignField': '_id',
    "as": 'quizzes.author'
}},
{$unwind: '$quizzes.author'},
{$sort: {'quizzes.updatedAt': -1}},
{$group: {_id: '$_id', quizzes: {$push: '$quizzes'}}},
{$project: {
  _id: 1,
  'quizzes': {
            $slice:['$quizzes', 0, 3]
  }}
}
])

However, this is the response I desire.

{
"_id" : "59fffda313d02500116e83bf::5a059c67f3ff3b001105c509",
"quizzes" : [
    {
        "topics" : [
            ObjectId("5a054210d74fe90011d5f5e1")
        ],
        "isCorrect" : false,
        "status" : 2,
        "isUsed" : true,
        "askBack" : true,
        "isRestricted" : false,
        "rejected" : false,
        "createdAt" : ISODate("2017-11-10T12:57:33.910Z"),
        "updatedAt" : ISODate("2017-11-10T12:57:33.910Z"),
        "answerRead" : true,
        "correctAnswer" : "5a054210d74fe90011d5f5e2",
        "question" : ObjectId("5a054210d74fe90011d5f5e0"),
        "author" :{
                    "_id": "59fffda313d02500116e83bf",
                    "username": "f2",
                    "lastName": "2",
                    "firstName": "f",
                    "active": false,
                    "meta": {
                         "totalInvites": 0,
                         "totalFriends": 1
                   }
          },
        "participant": {
                  "_id": "5a059c67f3ff3b001105c509",
                  "username": "chandan",
                  "lastName": "kumar",
                  "firstName": "chandan",
                  "active": false,
                  "meta": {
                     "totalInvites": 0,
                     "totalFriends": 16
                  }

     "_id" : ObjectId("5a05a23dfc698f00118470f5")
    }
],
"participants" : [
    ObjectId("5a059c67f3ff3b001105c509"),
    ObjectId("59fffda313d02500116e83bf")
],
"__v" : 0,
"skippedQuestionIds" : []
}

Can the lookup be done after the initial projection, and how do I limit fields. Any help will be appreciated. Thanks

Body:
I won't familiarize myself enough with your schema to work out the entire pipeline, but If I could generalize a bit:

Yes, the $lookup can be done after a $project operation.  You can have multiple $project operations (indeed multiple of any operation) in an aggregation.

A $lookup operation could be followed by a $project operation to normalize your results in the following fashion:

{$lookup: {
    "from":'users',
    "localField":'quizzes.author',
    'foreignField': '_id',
    "as": 'authors'
}},
{$project: {
    'author._id': { $arrayElemAt: ['$authors._id', 0] },
    'author.username': { $arrayElemAt: ['$authors.username', 0] },
    // other fields can be projected as needed
}},

Since $lookup returns results in an array, the above example uses $arrayElemAt to get the first element and project the desired properties one by one.


问:
Error installing minqa in a non-standard location in Scientific Linux 6.6
I would ultimately like to install lme4 for R-3.2.5 on a system with Scientific Linux 6.6.  I'm on a shared system (I'm compiling R packages for a distributed computing problem), so I need to install all the packages to a non-standard location (/a/lot/of/subdirectories/R-3.2.5 instead of the usual /usr/local/).

I've already encountered a lot of trouble installing the lme4 dependency, nloptr, which would not install using the usual install.packages command in R.  I ended up downloading nlopt-2.4.2.tar.gz, installing it, and then linking to the installed libraries when invoking install.packages in R.  I'm now having trouble installing the minqa library, which is another lme4 dependency.  Here's the error message when I attempt to install minqa the following command in R: install.packages("minqa")

```<code>trying URL 'http://cran.revolutionanalytics.com/src/contrib/minqa_1.2.4.tar.gz'
Content type 'application/octet-stream' length 53548 bytes (52 KB)
==================================================
downloaded 52 KB

* installing *source* package ‘minqa’ ...
** package ‘minqa’ successfully unpacked and MD5 sums checked
** libs
gfortran   -fpic  -g -O2  -c altmov.f -o altmov.o
gfortran   -fpic  -g -O2  -c bigden.f -o bigden.o
gfortran   -fpic  -g -O2  -c biglag.f -o biglag.o
gfortran   -fpic  -g -O2  -c bobyqa.f -o bobyqa.o
gfortran   -fpic  -g -O2  -c bobyqb.f -o bobyqb.o
gfortran   -fpic  -g -O2  -c lagmax.f -o lagmax.o
g++ -I/var/lib/condor/execute/slot1/dir_20833/R-3.2.5/lib64/R/include -DNDEBUG  -I/usr/local/include -I"/var/lib/condor/execute/slot1/dir_20833/R-3.2.5/lib64/R/library/Rcpp/include"   -fpic  -g -O2  -c minqa.cpp -o minqa.o
gfortran   -fpic  -g -O2  -c newuoa.f -o newuoa.o
gfortran   -fpic  -g -O2  -c newuob.f -o newuob.o
gfortran   -fpic  -g -O2  -c prelim.f -o prelim.o
gfortran   -fpic  -g -O2  -c rescue.f -o rescue.o
gfortran   -fpic  -g -O2  -c trsapp.f -o trsapp.o
gfortran   -fpic  -g -O2  -c trsbox.f -o trsbox.o
gfortran   -fpic  -g -O2  -c trstep.f -o trstep.o
gfortran   -fpic  -g -O2  -c uobyqa.f -o uobyqa.o
gfortran   -fpic  -g -O2  -c uobyqb.f -o uobyqb.o
gfortran   -fpic  -g -O2  -c update.f -o update.o
gfortran   -fpic  -g -O2  -c updatebobyqa.f -o updatebobyqa.o
g++ -shared -L/usr/local/lib64 -o minqa.so altmov.o bigden.o biglag.o bobyqa.o bobyqb.o lagmax.o minqa.o newuoa.o newuob.o prelim.o rescue.o trsapp.o trsbox.o trstep.o uobyqa.o uobyqb.o update.o updatebobyqa.o Fatal error: creating temporary file for '-e' failed -lgfortran -lm
g++: Fatal: No such file or directory
g++: error:: No such file or directory
g++: creating: No such file or directory
g++: temporary: No such file or directory
g++: file: No such file or directory
g++: for: No such file or directory
g++: '-e': No such file or directory
g++: failed: No such file or directory
make: *** [minqa.so] Error 1
ERROR: compilation failed for package ‘minqa’
* removing ‘/var/lib/condor/execute/slot1/dir_20833/R-3.2.5/lib64/R/library/minqa’

The downloaded source packages are in
        ‘/var/lib/condor/execute/slot1/dir_20833/RtmpruzdgN/downloaded_packages’
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done
Warning message:
In install.packages("minqa") :
  installation of package ‘minqa’ had non-zero exit status
</code>```

It looks like g++ from install.packages is trying to reference the location /usr/local/lib64 instead of the actual location where I have R installed.  Any ideas of how to resolve this?  Is there an argument I can pass to install.packages (ex, with the configure.args option) to tell g++ what to do?

答:
The solution was multipronged:

Install nloptr from Github using install_github from the devtools package. The issue, I discovered, was that due to the workaround I had used to install nloptr, minqa was looking in the wrong place for the various nloptr libraries. The development version of nloptr on Github seems to use a different method for installing the nlopt libraries, which didn't throw an error

When invoking install.packages, use lib=.libPaths()[2] to set the right library path

When encountering errors using install.packages within R, try using R CMD INSTALL from outside R instead

Combined, these various methods seem to have solved all my issues.

Body:
I would ultimately like to install lme4 for R-3.2.5 on a system with Scientific Linux 6.6.  I'm on a shared system (I'm compiling R packages for a distributed computing problem), so I need to install all the packages to a non-standard location (/a/lot/of/subdirectories/R-3.2.5 instead of the usual /usr/local/).

I've already encountered a lot of trouble installing the lme4 dependency, nloptr, which would not install using the usual install.packages command in R.  I ended up downloading nlopt-2.4.2.tar.gz, installing it, and then linking to the installed libraries when invoking install.packages in R.  I'm now having trouble installing the minqa library, which is another lme4 dependency.  Here's the error message when I attempt to install minqa the following command in R: install.packages("minqa")

trying URL 'http://cran.revolutionanalytics.com/src/contrib/minqa_1.2.4.tar.gz'
Content type 'application/octet-stream' length 53548 bytes (52 KB)
==================================================
downloaded 52 KB

* installing *source* package ‘minqa’ ...
** package ‘minqa’ successfully unpacked and MD5 sums checked
** libs
gfortran   -fpic  -g -O2  -c altmov.f -o altmov.o
gfortran   -fpic  -g -O2  -c bigden.f -o bigden.o
gfortran   -fpic  -g -O2  -c biglag.f -o biglag.o
gfortran   -fpic  -g -O2  -c bobyqa.f -o bobyqa.o
gfortran   -fpic  -g -O2  -c bobyqb.f -o bobyqb.o
gfortran   -fpic  -g -O2  -c lagmax.f -o lagmax.o
g++ -I/var/lib/condor/execute/slot1/dir_20833/R-3.2.5/lib64/R/include -DNDEBUG  -I/usr/local/include -I"/var/lib/condor/execute/slot1/dir_20833/R-3.2.5/lib64/R/library/Rcpp/include"   -fpic  -g -O2  -c minqa.cpp -o minqa.o
gfortran   -fpic  -g -O2  -c newuoa.f -o newuoa.o
gfortran   -fpic  -g -O2  -c newuob.f -o newuob.o
gfortran   -fpic  -g -O2  -c prelim.f -o prelim.o
gfortran   -fpic  -g -O2  -c rescue.f -o rescue.o
gfortran   -fpic  -g -O2  -c trsapp.f -o trsapp.o
gfortran   -fpic  -g -O2  -c trsbox.f -o trsbox.o
gfortran   -fpic  -g -O2  -c trstep.f -o trstep.o
gfortran   -fpic  -g -O2  -c uobyqa.f -o uobyqa.o
gfortran   -fpic  -g -O2  -c uobyqb.f -o uobyqb.o
gfortran   -fpic  -g -O2  -c update.f -o update.o
gfortran   -fpic  -g -O2  -c updatebobyqa.f -o updatebobyqa.o
g++ -shared -L/usr/local/lib64 -o minqa.so altmov.o bigden.o biglag.o bobyqa.o bobyqb.o lagmax.o minqa.o newuoa.o newuob.o prelim.o rescue.o trsapp.o trsbox.o trstep.o uobyqa.o uobyqb.o update.o updatebobyqa.o Fatal error: creating temporary file for '-e' failed -lgfortran -lm
g++: Fatal: No such file or directory
g++: error:: No such file or directory
g++: creating: No such file or directory
g++: temporary: No such file or directory
g++: file: No such file or directory
g++: for: No such file or directory
g++: '-e': No such file or directory
g++: failed: No such file or directory
make: *** [minqa.so] Error 1
ERROR: compilation failed for package ‘minqa’
* removing ‘/var/lib/condor/execute/slot1/dir_20833/R-3.2.5/lib64/R/library/minqa’

The downloaded source packages are in
        ‘/var/lib/condor/execute/slot1/dir_20833/RtmpruzdgN/downloaded_packages’
Updating HTML index of packages in '.Library'
Making 'packages.html' ... done
Warning message:
In install.packages("minqa") :
  installation of package ‘minqa’ had non-zero exit status

It looks like g++ from install.packages is trying to reference the location /usr/local/lib64 instead of the actual location where I have R installed.  Any ideas of how to resolve this?  Is there an argument I can pass to install.packages (ex, with the configure.args option) to tell g++ what to do?


问:
Prevent qtip from showing
How can I prevent qtip from showing on grid cells with "large" data that does not fit inside its width? (on ExtJS 6.5.2 - Modern Toolkit)

Example

Add this to a sencha fiddle:

```<code> Ext.application({
    name : 'Fiddle',

    launch : function() {
        var store = Ext.create('Ext.data.Store', {
    fields: ['name', 'email', 'phone'],
    data: [
        { 'name': 'Lisaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',  "email":"lisa@simpsons.com",  "phone":"555-111-1224"  },
        { 'name': 'Bart',  "email":"bart@simpsons.com",  "phone":"555-222-1234" },
        { 'name': 'Homer', "email":"home@simpsons.com",  "phone":"555-222-1244" },
        { 'name': 'Marge', "email":"marge@simpsons.com", "phone":"555-222-1254" }
    ]
    });

    Ext.create('Ext.grid.Grid', {
    title: 'Simpsons',

    store: store,

    columns: [
        {
            text: 'Name',
            dataIndex: 'name',
            minWidth: 200,
            //flex: 1,
            //cellWrap: true,
            cell: {
                bodyStyle: {
                    whiteSpace: 'normal'
                }
            }
        },
        { text: 'Email', dataIndex: 'email', flex: 2, minWidth: 250 },
        { text: 'Phone', dataIndex: 'phone', flex: 1,  minWidth: 120 }
    ],

    //height: 200,
    //layout: 'fit',
    fullscreen: true
    });
    }
    });
</code>```

答:
Grid without tooltip

Default wrapping behaviour but no tooltip, demo: https://fiddle.sencha.com/#view/editor&fiddle/29ii

Grid with wrapping capabilities

Demo: https://fiddle.sencha.com/#view/editor&fiddle/29if

In short you need to set these rules to wrap content:

```<code>white-space: normal;
word-break: break-word;
</code>```

And set grid's "variableHeights" to true: http://docs.sencha.com/extjs/6.5.1/modern/Ext.grid.Grid.html#cfg-variableHeights

Note: in the fiddle the CSS rules are applied using grid's "cls" config param, and styles are placed inside index.html

Title: Prevent qtip from showing

Body:
How can I prevent qtip from showing on grid cells with "large" data that does not fit inside its width? (on ExtJS 6.5.2 - Modern Toolkit)

Example

Add this to a sencha fiddle:

 Ext.application({
    name : 'Fiddle',

    launch : function() {
        var store = Ext.create('Ext.data.Store', {
    fields: ['name', 'email', 'phone'],
    data: [
        { 'name': 'Lisaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',  "email":"lisa@simpsons.com",  "phone":"555-111-1224"  },
        { 'name': 'Bart',  "email":"bart@simpsons.com",  "phone":"555-222-1234" },
        { 'name': 'Homer', "email":"home@simpsons.com",  "phone":"555-222-1244" },
        { 'name': 'Marge', "email":"marge@simpsons.com", "phone":"555-222-1254" }
    ]
    });

    Ext.create('Ext.grid.Grid', {
    title: 'Simpsons',

    store: store,

    columns: [
        {
            text: 'Name',
            dataIndex: 'name',
            minWidth: 200,
            //flex: 1,
            //cellWrap: true,
            cell: {
                bodyStyle: {
                    whiteSpace: 'normal'
                }
            }
        },
        { text: 'Email', dataIndex: 'email', flex: 2, minWidth: 250 },
        { text: 'Phone', dataIndex: 'phone', flex: 1,  minWidth: 120 }
    ],

    //height: 200,
    //layout: 'fit',
    fullscreen: true
    });
    }
    });

Body:
Grid without tooltip

Default wrapping behaviour but no tooltip, demo: https://fiddle.sencha.com/#view/editor&fiddle/29ii

Grid with wrapping capabilities

Demo: https://fiddle.sencha.com/#view/editor&fiddle/29if

In short you need to set these rules to wrap content:

white-space: normal;
word-break: break-word;

And set grid's "variableHeights" to true: http://docs.sencha.com/extjs/6.5.1/modern/Ext.grid.Grid.html#cfg-variableHeights

Note: in the fiddle the CSS rules are applied using grid's "cls" config param, and styles are placed inside index.html


问:
running mongoDB in a web hosting
Is there any way to run the mongoDB in goddady or any other hosting websites except for mongoHQ and so on?

and if I use mongoHQ , is that safe for the data and fast ?

I'm right now using it in the localhost server as a windows service .

答:
If you want to run software like MongoDB in a web environment, you'll need a Virtual Private Server (VPS). This is like having an entire machine that you can install anything on and do anything with. The downside is that you have to install and configure all the software on it, including backups and disaster recovery, which a shared host will usually do for you instead. The upside is that you have more system resources, so you can do more, and you can install any software you want, so you have more flexibility. My personal recommendation is Linode or Amazon EC2.

Shared hosting services generally don't allow you to install your own services, so you'll have to use what they provide for you. Most provide an RDBMS, like MySQL, but there aren't many providing MongoDB for you.

Title: running mongoDB in a web hosting


问:
What component is used in the Twitter Bootstrap's docs for sidebar?
I'm wondering what is the easiest way to build this kind of sidebar with Bootstrap 4.

To me, it looks like a custom component they built for the docs page, not being included in the framework. I'm not sure if I'm right.

```<code><ul class="nav bd-sidenav">
  <li class="active bd-sidenav-active">
    <a href="/docs/4.0/getting-started/introduction/">
      Introduction
    </a>
  </li>
  <li>
    <a href="/docs/4.0/getting-started/download/">
      Download
    </a>
  </li>
   ...
</ul>
</code>```

The closest I got was by creating something like this:

```<code><ul class="nav">
  <li class="w-100">
    <a href="#">
      Item 1
    </a>
  </li>
   ...
</ul>
</code>```

But I think there should be a better way.

What is the right way to build such a sidebar/table of contents with Bootstrap 4?

答:
Here's a simple nav sidebar with content at the right:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

        Active
        Link
        Link
        Disabled

      Here's your content! Added class bg-light for a light gray background.

```

Basically we're making a grid with the nav taking 1/4th (3/12) of the screen and the content using the rest of the screen.

If you want the nav to stack on smaller screens, you can replace col-3 with col-sm-3 for example. In this case the nav will stack under the sm breakpoint.

You can read more about vertical navs here, and the grid system here.

Body:
I'm wondering what is the easiest way to build this kind of sidebar with Bootstrap 4.

To me, it looks like a custom component they built for the docs page, not being included in the framework. I'm not sure if I'm right.

      Introduction

      Download

   ...

The closest I got was by creating something like this:

      Item 1

   ...

But I think there should be a better way.

What is the right way to build such a sidebar/table of contents with Bootstrap 4?

Body:
Here's a simple nav sidebar with content at the right:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<div class="container-fluid">
  <div class="row">
    <div class="col-3">
      <nav class="nav flex-column">
        <a class="p-1 nav-link active" href="#">Active</a>
        <a class="p-1 nav-link" href="#">Link</a>
        <a class="p-1 nav-link" href="#">Link</a>
        <a class="p-1 nav-link disabled" href="#">Disabled</a>
      </nav>
    </div>
    <div class="col bg-light">
      Here's your content! Added class bg-light for a light gray background.
    </div>
  </div>
</div>

Basically we're making a grid with the nav taking 1/4th (3/12) of the screen and the content using the rest of the screen.

If you want the nav to stack on smaller screens, you can replace col-3 with col-sm-3 for example. In this case the nav will stack under the sm breakpoint.

You can read more about vertical navs here, and the grid system here.


问:
Laravel/Lumen PSR-4: If I put classes into subdirectories do I have to use different namespaces then?
Look at the following part of my application structure:

```<code>App
-Events
-Http
--Controllers
---Rest
-Services
--Base
--Primary
</code>```

What I would like to do is to use the namespace App\Services for all services and the namespace App\Http\Controller for all controllers.

This is how my application is loaded with Composer:

```<code>"autoload": {
    "psr-4": {
        "App\\": "app/"
    } }
</code>```

This is the Exception I get:

(1/1) FatalThrowableError Class 'App\Services\CapabilityService' not
  found

CapabilityService exists for sure, but it is within the subfolder Primary. Is there a way to autoload files from subdirectories into one namespace together? If yes how and is there any important reason not to do it?

This is the CapabilityService:

```<code>namespace App\Services;
</code>```

This is the location:

```<code>App/Services/Primary/CapabilityService
</code>```

答:
Nvm I figured it out - just do arrays in within composer.json, where you specify all subfolders:

```<code> "autoload": {
        "psr-4": {
            "App\\": "app/",
            "App\\Services\\": ["app/services","app/services/base","app/services/primary"],
            "App\\Models\\": ["app/models","app/models/traits"],
            "App\\Http\\Controllers\\": ["app/http/controllers","app/http/controllers/base","app/http/controllers/rest","app/http/controllers/rest/base"]
        },
</code>```

Better solutions still welcome.

Body:
Look at the following part of my application structure:

App
-Events
-Http
--Controllers
---Rest
-Services
--Base
--Primary

What I would like to do is to use the namespace App\Services for all services and the namespace App\Http\Controller for all controllers.

This is how my application is loaded with Composer:

"autoload": {
    "psr-4": {
        "App\\": "app/"
    } }

This is the Exception I get:

(1/1) FatalThrowableError Class 'App\Services\CapabilityService' not
  found

CapabilityService exists for sure, but it is within the subfolder Primary. Is there a way to autoload files from subdirectories into one namespace together? If yes how and is there any important reason not to do it?

This is the CapabilityService:

namespace App\Services;

This is the location:

App/Services/Primary/CapabilityService

Body:
Nvm I figured it out - just do arrays in within composer.json, where you specify all subfolders:

 "autoload": {
        "psr-4": {
            "App\\": "app/",
            "App\\Services\\": ["app/services","app/services/base","app/services/primary"],
            "App\\Models\\": ["app/models","app/models/traits"],
            "App\\Http\\Controllers\\": ["app/http/controllers","app/http/controllers/base","app/http/controllers/rest","app/http/controllers/rest/base"]
        },

Better solutions still welcome.


问:
Accessing PHP Class Constants
The PHP manual says

Like static members, constant values can not be accessed from an instance of the object.

which explains why you can't do this

```<code>$this->inst = new Classname();
echo $this->inst::someconstant;
</code>```

but then why does this work?

```<code>$this->inst = new Classname();
$inst = $this->inst;
echo $inst::someconstant;
</code>```

答:
php supports accessing class constants from an object instance. Code below is working (checked in phpv5.5.5):

```<code><?php
class superheroes{
    const kal_el = 'Superman';
}

$instance = new superheroes;
echo $instance::kal_el;
</code>```

Source: http://dwellupper.io/post/48/defining-class-constants-in-php

Title: Accessing PHP Class Constants

Body:
The PHP manual says

Like static members, constant values can not be accessed from an instance of the object.

which explains why you can't do this

$this->inst = new Classname();
echo $this->inst::someconstant;

but then why does this work?

$this->inst = new Classname();
$inst = $this->inst;
echo $inst::someconstant;

Body:
php supports accessing class constants from an object instance. Code below is working (checked in phpv5.5.5):

<?php
class superheroes{
    const kal_el = 'Superman';
}

$instance = new superheroes;
echo $instance::kal_el;

Source: http://dwellupper.io/post/48/defining-class-constants-in-php


问:
How to apply code, userform and button to many other files?
Fairly new to VBA. I've written a code which does a variety of things and I'm fairly happy with where it's at.

It's triggered through a button in an excel sheet which calls a subfunction.

The issue I'm having is that the excel sheet I've written the code for is a sheet which we use at work often and save copies of. It's a quote form and we have ~5,000+ copies of different quotes, all in one folder.

Since I've only written the code in one of the copies, is there a way to create a program or something which copies the button and code/userform from the "Source" workbook, to all the others in a specified folder?

I'd like to have the button in the same location so it's consistent.

答:
Alternatively this code will import a code module saved as a .bas file into all the spreadsheets in a folder

```<code> Sub Demo()

    Dim s As String
    Dim wb As Workbook
    s = Dir("\\yourfolderpath\yourdoldername\*.xlsm")
    Do While s <> ""
        Set wb = Workbooks.Open("\\yourfolderpath\yourdoldername\" & s)

        Dim VBComps As VBIDE.VBComponents
        Dim VBComp As VBIDE.VBComponent

        Set VBComps = wb.VBProject.VBComponents
        For Each VBComp In VBComps
            If VBComp.Name = "Your module name" Then
                VBComps.Remove VBComp
                Exit For
            End If
        Next VBComp

        VBComps.Import "C:\your dir\your module name.bas"
        wb.Close True
        s = Dir()
    Loop

 End Sub
</code>```

But - you must have "Trust access to the VBA project model" ticked in your security centre, and have set a reference to "Microsoft Visual Basic for Applications Extensibility " in Tools,references in the vb editor

Body:
Alternatively this code will import a code module saved as a .bas file into all the spreadsheets in a folder

 Sub Demo()

    Dim s As String
    Dim wb As Workbook
    s = Dir("\\yourfolderpath\yourdoldername\*.xlsm")
    Do While s <> ""
        Set wb = Workbooks.Open("\\yourfolderpath\yourdoldername\" & s)

        Dim VBComps As VBIDE.VBComponents
        Dim VBComp As VBIDE.VBComponent

        Set VBComps = wb.VBProject.VBComponents
        For Each VBComp In VBComps
            If VBComp.Name = "Your module name" Then
                VBComps.Remove VBComp
                Exit For
            End If
        Next VBComp

        VBComps.Import "C:\your dir\your module name.bas"
        wb.Close True
        s = Dir()
    Loop

 End Sub

But - you must have "Trust access to the VBA project model" ticked in your security centre, and have set a reference to "Microsoft Visual Basic for Applications Extensibility " in Tools,references in the vb editor


问:
Correctly parsing through a JSON array with multiple objects using Alamofire and SwiftyJSON
I am able to print out the response. However I am unable to loop through the array and initialise it. This is how I am requesting the data:

```<code>Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { (response) in

    print(response.value!)

    guard let data = response.data else { return }
    let json = JSON(data: data)

    for r in json.arrayValue {
        let person = Person(json: r)
    }
}
</code>```

I have added breakpoints but I am unable to understand as to why the loop does not happen?

Update:

response.value! example:

```<code>{
  "pagination": {
    "object_count": 1,
    "page_number": 1
  },
  "attendees": [
    {
      "id": "818060297",
      "quantity": 1,
      "profile": {
        "first_name": "John",
        "last_name": "Doe",
        "company": "Apple",
        "name": "John Doe",
        "email": "john_doe@testmail.com",
        "job_title": "CEO"
      },
      "status": "Attending"
    }
  ]
}
</code>```

Update 2

Here is my AttendeesProfile class:

```<code>class AttendeesProfile {

    var name: String?

    init(json: JSON) {
        self.name = json["name"].stringValue
    }

}
</code>```

Now I am not sure how to get the Attendee class to work properly:

```<code>class Attendees {

    var attendees = [String]()
    var attendeesProfile: AttendeesProfile!

    init(json: JSON) {
        // Something here
    }
}
</code>```

答:
I suspect your guard statement stopping your code flow before you loop through your array : guard let data = response.data else { return }

With this line, you are saying if data has something then the code flow can continue. If not, please stop it and return. So, you never reach your loop statement.

Are you sure that your response.data has something and is different from nil ? Your print(response.value!) shows something ?

Body:
I am able to print out the response. However I am unable to loop through the array and initialise it. This is how I am requesting the data:

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { (response) in

    print(response.value!)

    guard let data = response.data else { return }
    let json = JSON(data: data)

    for r in json.arrayValue {
        let person = Person(json: r)
    }
}

I have added breakpoints but I am unable to understand as to why the loop does not happen?

Update:

response.value! example:

{
  "pagination": {
    "object_count": 1,
    "page_number": 1
  },
  "attendees": [
    {
      "id": "818060297",
      "quantity": 1,
      "profile": {
        "first_name": "John",
        "last_name": "Doe",
        "company": "Apple",
        "name": "John Doe",
        "email": "john_doe@testmail.com",
        "job_title": "CEO"
      },
      "status": "Attending"
    }
  ]
}

Update 2

Here is my AttendeesProfile class:

class AttendeesProfile {

    var name: String?

    init(json: JSON) {
        self.name = json["name"].stringValue
    }

}

Now I am not sure how to get the Attendee class to work properly:

class Attendees {

    var attendees = [String]()
    var attendeesProfile: AttendeesProfile!

    init(json: JSON) {
        // Something here
    }
}


问:
Stopping video playing in webview, navigation controller
I have built a navigation controller that on the final page displays a video relating to previous choices. This part works fine. The video is embed from youtube onto a webpage and displayed via a webview.

```<code><iframe type="text/html" id="video" width="100%" height="50%" src="http://www.youtube.com/embed/VIDEOID" frameborder="0"><br/></iframe>
</code>```

The problem I'm having is when I click back through the navigation controller the video (well sound) continues to play in the background. This only happens on the iPad as the video is played in the window, where as on the iPhone it is played in a new modal window.

How can I stop this? any help welcome, thanks in advance.

答:
You need to load a blank page into the UIWebView to stop the audio:

[yourWebView loadHTMLString:@"" baseURL:nil];

Body:
I have built a navigation controller that on the final page displays a video relating to previous choices. This part works fine. The video is embed from youtube onto a webpage and displayed via a webview.

The problem I'm having is when I click back through the navigation controller the video (well sound) continues to play in the background. This only happens on the iPad as the video is played in the window, where as on the iPhone it is played in a new modal window.

How can I stop this? any help welcome, thanks in advance.


问:
SQL Finding most spoken language in a country
I am trying to get the most spoken language in a country based on percentage. I am joining 2 tables:

```<code>Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)
</code>```

Joining those 2 gives me

```<code>Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8
</code>```

I tried to get the most spoken language by saying

```<code>SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name
</code>```

This gives me the right percentage but wrong language, where did I go wrong?

```<code>Afghanistan  Balochi    52.4
Aruba        Dutch      76.7
</code>```

答:
First of all, please join with inner join...on.

Your query won't work as it will get max(percentage) but display any of language for given country.

If I understood your schema properly, then following query should work as expected:

```<code>SELECT co.Name, cl.language, cl.Percentage as percentage
from Country co
inner join CountryLanguage cl
on co.Code = cl.CountryCode
where (cl.CountryCode,cl.Percentage) in (select CountryCode,max(Percentage)
                                         from CountryLanguage
                                         group by CountryCode)
group by co.Name
</code>```

Body:
I am trying to get the most spoken language in a country based on percentage. I am joining 2 tables:

Country(NAME,CODE)
CountryLanguage(Percentage, CountryCode, Language)

Joining those 2 gives me

Aruba           Dutch       5.3
Aruba           English     9.5
Aruba           Papiamento  76.7
Aruba           Spanish     7.4
Afghanistan     Balochi     0.9
Afghanistan     Dari        32.1
Afghanistan     Pashto      52.4
Afghanistan     Turkmenian  1.9
Afghanistan     Uzbek       8.8

I tried to get the most spoken language by saying

SELECT co.Name, cl.language, max(cl.Percentage)
from Country co, CountryLanguage cl
where co.Code = cl.CountryCode
group by co.Name

This gives me the right percentage but wrong language, where did I go wrong?

Afghanistan  Balochi    52.4
Aruba        Dutch      76.7

Body:
First of all, please join with inner join...on.

Your query won't work as it will get max(percentage) but display any of language for given country.

If I understood your schema properly, then following query should work as expected:

SELECT co.Name, cl.language, cl.Percentage as percentage
from Country co
inner join CountryLanguage cl
on co.Code = cl.CountryCode
where (cl.CountryCode,cl.Percentage) in (select CountryCode,max(Percentage)
                                         from CountryLanguage
                                         group by CountryCode)
group by co.Name


问:
How to center text in a row using Bootstrap 4
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

```<code><div class="container">
  <div class="row" id="appSummary">
    <h1>Why This App Is Awesome</h1>
    <p class="lead">Summary, once again, of your app's awesomeness</p>
  </div>
</div>
</code>```

CSS

```<code>#appSummary{
  text-align:center;
}
</code>```

答:
You can use margin: auto for centering item, rather than text-align: center
why?

margin: 0 auto; affects the container directly, and when the container
  is block-level (display: block).

text-align: center; center affects text, inline, and inline-block level
  children of a container - not the container itself.

reference

i created example in jsfiddle

Body:
The problem is that
 and
 are appearing on same line and no matter what I do they can't be centered.

HTML

Why This App Is Awesome

Summary, once again, of your app's awesomeness

CSS

#appSummary{
  text-align:center;
}


问:
Shuffling biased random numbers
While thinking about this question and conversing with the participants, the idea came up that shuffling a finite set of clearly biased random numbers makes them random because you don't know the order in which they were chosen.  Is this true and if so can someone point to some resources?

EDIT:  I think I might have been a little unclear. Suppose a bad random numbers generator. Take n values. These are biased(the rng is bad). Is there a way through shuffling to make the output of the rng over multiple trials statistically match the output of a known good rng?

答:
It's not true. In the other question the problem is to select 30 random numbers in [1..9] with a sum of 200. After choosing about on average 20 of them randomly, you reach a point where you can't select nines anymore because this would make the total sum go over 200. Of the remaining 10 numbers, most will be ones and twos. So in the end, ones and twos are very overrepresented in the selected numbers. Shuffling doesn't change that. But it's not clear how the random distribution really should look like, so one could say this is as good a solution as any.

In general, if your "random" numbers will be biased to, say, low numbers, they will be biased that way no matter the ordering.

OwnerDisplayName: JPunyon

Title: Shuffling biased random numbers

LastEditorDisplayName: JPunyon

OwnerDisplayName: sth

LastEditorDisplayName: sth