问:
RegEx for identifying alphanumeric patterns with special chars and boundaries
I am attempting to return one of these strings (depends on input):

```<code>f23/24  /or/  f23-24   /or/  f23+24
</code>```

(Ideally, it would be great if it ALWAYS returned format f23-24), regardless of input

from this type of string:

```<code>build-f23/24 1st pass demo (50:50)   #Should output f23-24 or f23/24
build-f17-22 1st pass demo (50:50)   #Should output f17-22
build-f-1 +14 1st pass demo (50:50)  #Should output f1-14 or f1+14
</code>```

Exception:

Some of the strings will not have the second set of numbers:

```<code>build-f45 1st pass demo (50:50)      #Should output f45
</code>```

Where I am currently at:

Thus far, I have this regex, but it always fails if the separator char is a slash:

```<code>regex = r"(\s?)(\-?)(f)(\s?)([\+\-\/]?)(\d\d*)(-?)(\d?\d*)"
tmp = re.search(regex, val)[0]
</code>```

答:
For your test data, you can try the following regular expression -(f)-?(\d+)(?:\s*([-+/]\d+))?.

```<code>import re

val = '''
build-f23/24 1st pass demo (50:50)
build-f17-22 1st pass demo (50:50)
build-f-1 +14 1st pass demo (50:50)
build-f45 1st pass demo (50:50)
'''

expected = [['f23-24', 'f23/24'], ['f17-22'], ['f1-14', 'f1+14'], ['f45']]

for m, x in zip(re.findall(r'-(f)-?(\d+)(?:\s*([-+/]\d+))?', val), expected):
  result = ''.join(m)
  print(result in x, ':', result)
</code>```

Output:

```<code>True : f23/24
True : f17-22
True : f1+14
True : f45
</code>```

Body:
I am attempting to return one of these strings (depends on input):

f23/24  /or/  f23-24   /or/  f23+24

(Ideally, it would be great if it ALWAYS returned format f23-24), regardless of input

from this type of string:

build-f23/24 1st pass demo (50:50)   #Should output f23-24 or f23/24
build-f17-22 1st pass demo (50:50)   #Should output f17-22
build-f-1 +14 1st pass demo (50:50)  #Should output f1-14 or f1+14

Exception:

Some of the strings will not have the second set of numbers:

build-f45 1st pass demo (50:50)      #Should output f45

Where I am currently at:

Thus far, I have this regex, but it always fails if the separator char is a slash:

regex = r"(\s?)(\-?)(f)(\s?)([\+\-\/]?)(\d\d*)(-?)(\d?\d*)"
tmp = re.search(regex, val)[0]

Body:
For your test data, you can try the following regular expression -(f)-?(\d+)(?:\s*([-+/]\d+))?.

import re

val = '''
build-f23/24 1st pass demo (50:50)
build-f17-22 1st pass demo (50:50)
build-f-1 +14 1st pass demo (50:50)
build-f45 1st pass demo (50:50)
'''

expected = [['f23-24', 'f23/24'], ['f17-22'], ['f1-14', 'f1+14'], ['f45']]

for m, x in zip(re.findall(r'-(f)-?(\d+)(?:\s*([-+/]\d+))?', val), expected):
  result = ''.join(m)
  print(result in x, ':', result)

Output:

True : f23/24
True : f17-22
True : f1+14
True : f45


来源: stackexchange

问:
How do I get file creation and modification date/times?
What's the best cross-platform way to get file creation and modification dates/times, that works on both Linux and Windows?</p>

答:
It may worth taking a look at the crtime library which implements cross-platform access to the file creation time.

```<code>from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019
</code>```

OwnerDisplayName: Mark Biek

ContentLicense: CC BY-SA 4.0

Body:
It may worth taking a look at the crtime library which implements cross-platform access to the file creation time.

from crtime import get_crtimes_in_dir

for fname, date in get_crtimes_in_dir(".", raise_on_error=True, as_epoch=False):
    print(fname, date)
    # file_a.py Mon Mar 18 20:51:18 CET 2019


问:
Converting array iteration to lambda function using Java8
I am trying to convert to Lambda function

So far I am able to convert the above code to lambda function like as shown below

```<code>Stream.of(acceptedDetails, rejectedDetails)
.filter(list -> !isNull(list) && list.length > 0)
.forEach(new Consumer<Object>() {
    public void accept(Object acceptedOrRejected) {
        String id;
        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            id = ((EmployeeValidationAccepted) acceptedOrRejected).getId();
        } else {
            id = ((EmployeeValidationRejected) acceptedOrRejected).getAd().getId();
        }

        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            dates1.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds1.add(empId);
        } else {
            dates2.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds2.add(empId);
        }
    }
});
</code>```

But still my goal was to avoid repeating the same logic and also to convert to Lambda function, still in my converted lambda function I feel its not clean and efficient.

This is just for my learning aspect I am doing this stuff by taking one existing code snippet.

Can anyone please tell me how can I improvise the converted Lambda function

答:
How about this:

```<code> class EmployeeValidationResult {
    //constructor + getters omitted for brevity
    private final BigInteger date;
    private final Integer employeeId;
}

List<EmployeeValidationResult> accepted = Stream.of(acceptedDetails)
    .filter(Objects:nonNull)
    .map(this::extractValidationResult)
    .collect(Collectors.toList());

List<EmployeeValidationResult> rejected = Stream.of(rejectedDetails)
    .filter(Objects:nonNull)
    .map(this::extractValidationResult)
    .collect(Collectors.toList());

EmployeeValidationResult extractValidationResult(EmployeeValidationAccepted accepted) {
    return extractValidationResult(accepted.getId());
}

EmployeeValidationResult extractValidationResult(EmployeeValidationRejected rejected) {
    return extractValidationResult(rejected.getAd().getId());
}

EmployeeValidationResult extractValidationResult(String id) {
    String[] empIdList = id.split("-");
    BigInteger date = extractDate(empIdList[1])
    Integer empId = extractId(empIdList[2]);

    return new EmployeeValidationResult(date, employeeId);
}
</code>```

Repeating the filter or map operations is good style and explicit about what is happening. Merging the two lists of objects into one and using instanceof clutters the implementation and makes it less readable / maintainable.

Body:
I am trying to convert to Lambda function

So far I am able to convert the above code to lambda function like as shown below

Stream.of(acceptedDetails, rejectedDetails)
.filter(list -> !isNull(list) && list.length > 0)
.forEach(new Consumer<Object>() {
    public void accept(Object acceptedOrRejected) {
        String id;
        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            id = ((EmployeeValidationAccepted) acceptedOrRejected).getId();
        } else {
            id = ((EmployeeValidationRejected) acceptedOrRejected).getAd().getId();
        }

        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            dates1.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds1.add(empId);
        } else {
            dates2.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds2.add(empId);
        }
    }
});

But still my goal was to avoid repeating the same logic and also to convert to Lambda function, still in my converted lambda function I feel its not clean and efficient.

This is just for my learning aspect I am doing this stuff by taking one existing code snippet.

Can anyone please tell me how can I improvise the converted Lambda function

Body:
How about this:

 class EmployeeValidationResult {
    //constructor + getters omitted for brevity
    private final BigInteger date;
    private final Integer employeeId;
}

List<EmployeeValidationResult> accepted = Stream.of(acceptedDetails)
    .filter(Objects:nonNull)
    .map(this::extractValidationResult)
    .collect(Collectors.toList());

List<EmployeeValidationResult> rejected = Stream.of(rejectedDetails)
    .filter(Objects:nonNull)
    .map(this::extractValidationResult)
    .collect(Collectors.toList());

EmployeeValidationResult extractValidationResult(EmployeeValidationAccepted accepted) {
    return extractValidationResult(accepted.getId());
}

EmployeeValidationResult extractValidationResult(EmployeeValidationRejected rejected) {
    return extractValidationResult(rejected.getAd().getId());
}

EmployeeValidationResult extractValidationResult(String id) {
    String[] empIdList = id.split("-");
    BigInteger date = extractDate(empIdList[1])
    Integer empId = extractId(empIdList[2]);

    return new EmployeeValidationResult(date, employeeId);
}

Repeating the filter or map operations is good style and explicit about what is happening. Merging the two lists of objects into one and using instanceof clutters the implementation and makes it less readable / maintainable.


问:
Sudzc iPhone SOAP - How can I handle a SOAP fault using this library auto-generated data?
I have a response, which returns SOAP fault in case of exception. I want to handle this SOAP Fault. But, the response I get by deserializing the SOAP response does not have a SOAP Fault.

I have used Sudzc Library to generate the objective C code for my web services.

Help will be appreciated.

Thanks,

Priya

答:
There seems to be a bug in the SoapRequest.m that is bundled with Sudzc.

Specifically, if you take a look at the

```<code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
</code>```

method and navigate to the following bit of code:

```<code>id output = nil;
SoapFault* fault = [SoapFault faultWithXMLDocument: doc];

if([fault hasFault]) {
    if(self.action == nil) {
        [self handleFault: fault];
    } else {
        if(self.handler != nil && [self.handler respondsToSelector: self.action]) {
            [self.handler performSelector: self.action withObject: output];
        } else {
            NSLog(@"SOAP Fault: %@", fault);
        }
    }
}
</code>```

You can see that output will always be nil when returned to the handler.

To fix this issue, you can simply return the SoapFault instead of the output to your handler like so:

```<code>...
[self.handler performSelector: self.action withObject: fault];
...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There seems to be a bug in the SoapRequest.m that is bundled with Sudzc.

Specifically, if you take a look at the

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

method and navigate to the following bit of code:

id output = nil;
SoapFault* fault = [SoapFault faultWithXMLDocument: doc];

if([fault hasFault]) {
    if(self.action == nil) {
        [self handleFault: fault];
    } else {
        if(self.handler != nil && [self.handler respondsToSelector: self.action]) {
            [self.handler performSelector: self.action withObject: output];
        } else {
            NSLog(@"SOAP Fault: %@", fault);
        }
    }
}

You can see that output will always be nil when returned to the handler.

To fix this issue, you can simply return the SoapFault instead of the output to your handler like so:

...
[self.handler performSelector: self.action withObject: fault];
...

ContentLicense: CC BY-SA 3.0


问:
React Native iOS show Downloading JavaScript bundle
When I launch app on iPhone, I get this message

Downloading JavaScript bundle...

on top of screen. It take about 2 minutes. (see image below)

How can i hide this message and improve performance of this step ?

答:
Change Build Configuration solve this issue.

For iOS open your project in Xcode and select Product → Scheme → Edit Scheme... (or press ⌘ + <). Next, select Run from the menu on the left and change the Build Configuration to Release.
  From :
  https://stackoverflow.com/a/34426258/6470308


问:
Can't generate a router-link button on a b-table
On my index page I have a b-table that loads some data. One of the columns is for a button that should lead to a page containing more information about the object displaying in a given row. So I thought I needed to use v-html method, this way:

```<code><template>
  <div>
    <b-table striped outlined hover :items="items" :fields="fields">
        <span slot="info" slot-scope="data" v-html="data.value"></span>
    </b-table>
  </div>
</template>

<script>
  export default {
    name: 'Blocks',
    data() {
      return {
        fields: ['first_name', 'last_name', 'age','info'],
        items: [
          { isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald', info:
          '<router-link to="/blocks/0"><b-button>Go to first block</b-button></router-link>'},
          { isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw', info:
          '<router-link to="/blocks/1"><b-button>Go to second block</b-button></router-link>'},
          { isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson', info:
          '<router-link to="/blocks/2"><b-button>Go to third block</b-button></router-link>'},
          { isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney', info:
          '<router-link to="/blocks/3"><b-button>Go to fourth block</b-button></router-link>'}
        ]
      }
    }
  }
</script>
</code>```

(I'm currently only using static data just for testing, and don't worry about the variable names)

The thing is: the b-button won't appear. It works with ordinary button though. Not only that but the worst part is the router-link won't do anything. So:

Expected: a button in each row that would lead me to an infos page from a certain row.

Got: just the labels from the button, that hasn't been linked to an infos page.

答:
The problem is that router-link and b-button are Vue components, not HTML elements, and you can't include Vue templates in a v-html directive, it just inserts the string as raw HTML.

You'll need to do something like:

```<code><b-table striped outlined hover :items="items" :fields="fields">
    <span slot="info" slot-scope="data">
        <router-link :to="'/blocks/' + data.value.block_id"><b-button>{{ data.value.description }}/b-button></router-link>
    </span>
</b-table>
</code>```

You'll need to rejig your variables to match that format, but that should work for you.

Body:
On my index page I have a b-table that loads some data. One of the columns is for a button that should lead to a page containing more information about the object displaying in a given row. So I thought I needed to use v-html method, this way:

<template>

</template>

(I'm currently only using static data just for testing, and don't worry about the variable names)

The thing is: the b-button won't appear. It works with ordinary button though. Not only that but the worst part is the router-link won't do anything. So:

Expected: a button in each row that would lead me to an infos page from a certain row.

Got: just the labels from the button, that hasn't been linked to an infos page.

Body:
The problem is that router-link and b-button are Vue components, not HTML elements, and you can't include Vue templates in a v-html directive, it just inserts the string as raw HTML.

You'll need to do something like:

<b-table striped outlined hover :items="items" :fields="fields">
    <span slot="info" slot-scope="data">
        <router-link :to="'/blocks/' + data.value.block_id"><b-button>{{ data.value.description }}/b-button></router-link>
    </span>
</b-table>

You'll need to rejig your variables to match that format, but that should work for you.


问:
Save userform controls layour after user creates it on button click event
I have setup a dynamic userform in Excel VBA which allows the user to choose how many rows they want in a combination of comboboxes and textboxes. Once the user creates there form, I want to be able to process calculations as they choose items from drop down lists and enter numerical values.

I am able to create the form without issue but can not seem to work with the created controls as they do not appear to be saved in memory in which I can access them.

My control creation loop predefines the names sequentially however my change code doesn't seem to reference them as they normally do when saved as part of the starting userform.

I've been trying to export the created form after it has been created but that does not seem to work and is not really a viable option as multiple users will be using their own instance of the forms.

Here is the code of what successfully creates the list along with the correct properties and source data.

```<code>'Create new door list based on user number input
Private Sub btnds1dl1CreatDoorList_Click()

Dim i As Long, x As Integer, number As Long
Dim txtB1, cmbB1 As Control

number = InputBox("Enter # or door list rows to create", "Enter number between 1 and 100")
number = number + 1

With UForm
    For i = 2 To number

        'Add each row from left to right starting at control 1 and ending at 11.

        '<<=========================  ADD 2 COMBO BOXES
        'ADD CABINET
        Set cmbB1 = Controls.Add("Forms.ComboBox.1", "cmdboxs1dlcab" & i)
        With cmbB1
            '.Name = "cmdboxs1dlcab" & i
            .Height = 18
            .Width = 72
            .Left = 18
            .Top = 24 * (i - 1) + 228
            .RowSource = "CABINET_TYPE"
            .Value = "Select"
            .BackStyle = 0
        End With

        'ADD SINGLE OR PAIR
        Set cmbB1 = Controls.Add("Forms.ComboBox.1", "cmdboxs1dlsp" & i)
        With cmbB1
            '.Name = "cmdboxs1dlsp" & i
            .Height = 18
            .Width = 72
            .Left = 96
            .Top = 24 * (i - 1) + 228
             .RowSource = "SINGLE_PAIR"
            .Value = "Select"
            .BackStyle = 0
        End With

        '<<=========================  ADD 9 TEXT BOXES
        'ADD QTY OPENINGS
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1qo" & i
            .Height = 18
            .Width = 43
            .Left = 186
            .Top = 24 * (i - 1) + 228
        End With

        'ADD OPENING WIDTH
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1ow" & i
            .Height = 18
            .Width = 43
            .Left = 246
            .Top = 24 * (i - 1) + 228
        End With

        'ADD OPENING HEIGHT
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1oh" & i
            .Height = 18
            .Width = 43
            .Left = 306
            .Top = 24 * (i - 1) + 228
        End With

        'ADD FINISH NET WIDTH
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1fnw" & i
            .Height = 18
            .Width = 43
            .Left = 378
            .Top = 24 * (i - 1) + 228
        End With

        'ADD FINISH NET HEIGHT
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1fnh" & i
            .Height = 18
            .Width = 43
            .Left = 444
            .Top = 24 * (i - 1) + 228
        End With

        'ADD QUANTITY
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1q" & i
            .Height = 18
            .Width = 43
            .Left = 522
            .Top = 24 * (i - 1) + 228
        End With

        'ADD WIDTH
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1w" & i
            .Height = 18
            .Width = 43
            .Left = 575
            .Top = 24 * (i - 1) + 228
        End With

        'ADD HEIGHT
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1h" & i
            .Height = 18
            .Width = 43
            .Left = 627
            .Top = 24 * (i - 1) + 228
        End With

         'ADD AREA (SQ FT.)
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1a" & i
            .Height = 18
            .Width = 43
            .Left = 678
            .Top = 24 * (i - 1) + 228
        End With

        Call AdjustScrollBar ' Adjust scroll bar to account for new rows

    Next i

    Call AdjustFormHeight ' Adjust form height to account for new rows

End With

End Sub
</code>```

The result I am hoping for is after this code is triggered, the form is saved to memory and used as if the form started that way. I want to be able to make various changes automatically based on the users input and have the full ability to monitor and refence any controls changed.

Thanks for your help

答:
Here's a very simple example which just links controls to worksheet cells: in this form it could arguably be more-easily handled by setting ControlSource (https://www.ozgrid.com/Excel/free-training/ExcelVBA2/excelvba2lesson15.htm) but if you want it to be more flexible (ie. be able to validate inputs) then you will need to handle events and do it this way.

Code for event-handling class "clsControl":

```<code>Option Explicit

Public linkedCell As Range
Public WithEvents cbo As MSForms.ComboBox
Public WithEvents txt As MSForms.TextBox

Private Sub cbo_Change()
    'here you handle the change in a combo box
    Me.linkedCell.Value = cbo.Value
End Sub

Private Sub txt_Change()
    'here you handle the change in a text box
    Me.linkedCell.Value = txt.Value
End Sub
</code>```

Code in the userform:

```<code>Option Explicit

Private ControlsCollection As Collection

Private Sub UserForm_Activate()

    Dim n As Long, t As Long, rngCombo As Range, rngTxt As Range
    Dim con As Object

    Set ControlsCollection = New Collection

    t = 20 'top position
    'start positions for linked cells
    Set rngCombo = Sheet2.Range("A2")
    Set rngTxt = Sheet2.Range("C2")

    For n = 1 To 10

        Set con = Me.Controls.Add("Forms.ComboBox.1", "cmbo_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 18
            .top = t + (n - 1) * 25
            .RowSource = "Some_List"
        End With
        ControlsCollection.Add ControlWrapper(con, rngCombo.Offset(n - 1, 0))

        Set con = Me.Controls.Add("Forms.TextBox.1", "txt_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 100
            .top = t + (n - 1) * 25
        End With
        ControlsCollection.Add ControlWrapper(con, rngTxt.Offset(n - 1, 0))

    Next n

End Sub

'Create an instance of our event-handling class, and assign a control
'   and a linked cell
Private Function ControlWrapper(con As Object, rng As Range) As clsControl
    Dim rv As New clsControl
    'assign to the appropriate control type in the calss instance
    Select Case TypeName(con)
        Case "ComboBox": Set rv.cbo = con
        Case "TextBox": Set rv.txt = con
    End Select
    Set rv.linkedCell = rng
    Set ControlWrapper = rv
End Function
</code>```

The resulting forn and the linked cells, after filling in a few values:

EDIT 6/4/2019

Here's something a little different - each instance of the class represents a row on the userform.  I've removed any linked cell references to keep the code brief.

The class module:

```<code>Option Explicit

'each item is a control on a "row" of the userform
'here we just havce two combos and a textbox
'   but could be more...
Public WithEvents cbo1 As MSForms.ComboBox
Public WithEvents cbo2 As MSForms.ComboBox
Public WithEvents txt As MSForms.TextBox

Private Sub cbo1_Change()
    'handle the change in a combo box
    Me.txt.Value = cbo1.Value & ":" & cbo2.Value
End Sub

Private Sub cbo2_Change()
    'handle the change in a combo box
    Me.txt.Value = cbo1.Value & ":" & cbo2.Value
End Sub

Private Sub txt_Change()
    'here you handle the change in a text box
End Sub
</code>```

The userform code:

```<code>Private Sub UserForm_Activate()

    Dim n As Long, t As Long
    Dim con As Object, obj As clsControl

    Set ControlsCollection = New Collection

    t = 20 'top position

    For n = 1 To 10

        Set obj = New clsControl

        Set con = Me.Controls.Add("Forms.ComboBox.1", "cmbo_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 18
            .Top = t + (n - 1) * 25
            .RowSource = "Some_List"
        End With
        Set obj.cbo1 = con

        Set con = Me.Controls.Add("Forms.ComboBox.1", "cmbo_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 100
            .Top = t + (n - 1) * 25
            .RowSource = "Some_List"
        End With
        Set obj.cbo2 = con

        Set con = Me.Controls.Add("Forms.TextBox.1", "txt_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 200
            .Top = t + (n - 1) * 25
        End With
        Set obj.txt = con

        ControlsCollection.Add obj

    Next n

End Sub
</code>```

Body:
I have setup a dynamic userform in Excel VBA which allows the user to choose how many rows they want in a combination of comboboxes and textboxes. Once the user creates there form, I want to be able to process calculations as they choose items from drop down lists and enter numerical values.

I am able to create the form without issue but can not seem to work with the created controls as they do not appear to be saved in memory in which I can access them.

My control creation loop predefines the names sequentially however my change code doesn't seem to reference them as they normally do when saved as part of the starting userform.

I've been trying to export the created form after it has been created but that does not seem to work and is not really a viable option as multiple users will be using their own instance of the forms.

Here is the code of what successfully creates the list along with the correct properties and source data.

'Create new door list based on user number input
Private Sub btnds1dl1CreatDoorList_Click()

Dim i As Long, x As Integer, number As Long
Dim txtB1, cmbB1 As Control

number = InputBox("Enter # or door list rows to create", "Enter number between 1 and 100")
number = number + 1

With UForm
    For i = 2 To number

        'Add each row from left to right starting at control 1 and ending at 11.

        '<<=========================  ADD 2 COMBO BOXES
        'ADD CABINET
        Set cmbB1 = Controls.Add("Forms.ComboBox.1", "cmdboxs1dlcab" & i)
        With cmbB1
            '.Name = "cmdboxs1dlcab" & i
            .Height = 18
            .Width = 72
            .Left = 18
            .Top = 24 * (i - 1) + 228
            .RowSource = "CABINET_TYPE"
            .Value = "Select"
            .BackStyle = 0
        End With

        'ADD SINGLE OR PAIR
        Set cmbB1 = Controls.Add("Forms.ComboBox.1", "cmdboxs1dlsp" & i)
        With cmbB1
            '.Name = "cmdboxs1dlsp" & i
            .Height = 18
            .Width = 72
            .Left = 96
            .Top = 24 * (i - 1) + 228
             .RowSource = "SINGLE_PAIR"
            .Value = "Select"
            .BackStyle = 0
        End With

        '<<=========================  ADD 9 TEXT BOXES
        'ADD QTY OPENINGS
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1qo" & i
            .Height = 18
            .Width = 43
            .Left = 186
            .Top = 24 * (i - 1) + 228
        End With

        'ADD OPENING WIDTH
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1ow" & i
            .Height = 18
            .Width = 43
            .Left = 246
            .Top = 24 * (i - 1) + 228
        End With

        'ADD OPENING HEIGHT
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1oh" & i
            .Height = 18
            .Width = 43
            .Left = 306
            .Top = 24 * (i - 1) + 228
        End With

        'ADD FINISH NET WIDTH
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1fnw" & i
            .Height = 18
            .Width = 43
            .Left = 378
            .Top = 24 * (i - 1) + 228
        End With

        'ADD FINISH NET HEIGHT
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1fnh" & i
            .Height = 18
            .Width = 43
            .Left = 444
            .Top = 24 * (i - 1) + 228
        End With

        'ADD QUANTITY
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1q" & i
            .Height = 18
            .Width = 43
            .Left = 522
            .Top = 24 * (i - 1) + 228
        End With

        'ADD WIDTH
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1w" & i
            .Height = 18
            .Width = 43
            .Left = 575
            .Top = 24 * (i - 1) + 228
        End With

        'ADD HEIGHT
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1h" & i
            .Height = 18
            .Width = 43
            .Left = 627
            .Top = 24 * (i - 1) + 228
        End With

         'ADD AREA (SQ FT.)
        Set txtB1 = Controls.Add("Forms.TextBox.1")
        With txtB1
            .Name = "txtboxds1dl1a" & i
            .Height = 18
            .Width = 43
            .Left = 678
            .Top = 24 * (i - 1) + 228
        End With

        Call AdjustScrollBar ' Adjust scroll bar to account for new rows

    Next i

    Call AdjustFormHeight ' Adjust form height to account for new rows

End With

End Sub

The result I am hoping for is after this code is triggered, the form is saved to memory and used as if the form started that way. I want to be able to make various changes automatically based on the users input and have the full ability to monitor and refence any controls changed.

Thanks for your help

Body:
Here's a very simple example which just links controls to worksheet cells: in this form it could arguably be more-easily handled by setting ControlSource (https://www.ozgrid.com/Excel/free-training/ExcelVBA2/excelvba2lesson15.htm) but if you want it to be more flexible (ie. be able to validate inputs) then you will need to handle events and do it this way.

Code for event-handling class "clsControl":

Option Explicit

Public linkedCell As Range
Public WithEvents cbo As MSForms.ComboBox
Public WithEvents txt As MSForms.TextBox

Private Sub cbo_Change()
    'here you handle the change in a combo box
    Me.linkedCell.Value = cbo.Value
End Sub

Private Sub txt_Change()
    'here you handle the change in a text box
    Me.linkedCell.Value = txt.Value
End Sub

Code in the userform:

Option Explicit

Private ControlsCollection As Collection

Private Sub UserForm_Activate()

    Dim n As Long, t As Long, rngCombo As Range, rngTxt As Range
    Dim con As Object

    Set ControlsCollection = New Collection

    t = 20 'top position
    'start positions for linked cells
    Set rngCombo = Sheet2.Range("A2")
    Set rngTxt = Sheet2.Range("C2")

    For n = 1 To 10

        Set con = Me.Controls.Add("Forms.ComboBox.1", "cmbo_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 18
            .top = t + (n - 1) * 25
            .RowSource = "Some_List"
        End With
        ControlsCollection.Add ControlWrapper(con, rngCombo.Offset(n - 1, 0))

        Set con = Me.Controls.Add("Forms.TextBox.1", "txt_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 100
            .top = t + (n - 1) * 25
        End With
        ControlsCollection.Add ControlWrapper(con, rngTxt.Offset(n - 1, 0))

    Next n

End Sub

'Create an instance of our event-handling class, and assign a control
'   and a linked cell
Private Function ControlWrapper(con As Object, rng As Range) As clsControl
    Dim rv As New clsControl
    'assign to the appropriate control type in the calss instance
    Select Case TypeName(con)
        Case "ComboBox": Set rv.cbo = con
        Case "TextBox": Set rv.txt = con
    End Select
    Set rv.linkedCell = rng
    Set ControlWrapper = rv
End Function

The resulting forn and the linked cells, after filling in a few values:

EDIT 6/4/2019

Here's something a little different - each instance of the class represents a row on the userform.  I've removed any linked cell references to keep the code brief.

The class module:

Option Explicit

'each item is a control on a "row" of the userform
'here we just havce two combos and a textbox
'   but could be more...
Public WithEvents cbo1 As MSForms.ComboBox
Public WithEvents cbo2 As MSForms.ComboBox
Public WithEvents txt As MSForms.TextBox

Private Sub cbo1_Change()
    'handle the change in a combo box
    Me.txt.Value = cbo1.Value & ":" & cbo2.Value
End Sub

Private Sub cbo2_Change()
    'handle the change in a combo box
    Me.txt.Value = cbo1.Value & ":" & cbo2.Value
End Sub

Private Sub txt_Change()
    'here you handle the change in a text box
End Sub

The userform code:

Private Sub UserForm_Activate()

    Dim n As Long, t As Long
    Dim con As Object, obj As clsControl

    Set ControlsCollection = New Collection

    t = 20 'top position

    For n = 1 To 10

        Set obj = New clsControl

        Set con = Me.Controls.Add("Forms.ComboBox.1", "cmbo_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 18
            .Top = t + (n - 1) * 25
            .RowSource = "Some_List"
        End With
        Set obj.cbo1 = con

        Set con = Me.Controls.Add("Forms.ComboBox.1", "cmbo_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 100
            .Top = t + (n - 1) * 25
            .RowSource = "Some_List"
        End With
        Set obj.cbo2 = con

        Set con = Me.Controls.Add("Forms.TextBox.1", "txt_" & n)
        With con
            .Height = 18
            .Width = 72
            .Left = 200
            .Top = t + (n - 1) * 25
        End With
        Set obj.txt = con

        ControlsCollection.Add obj

    Next n

End Sub


问:
Redirect the user to a specific page after signIn
Main issue is checking if user has a child in the Firebase database so that I know if he is signing up or logging in.

Part 1: Part 1 (Child Database (this works) and making that a user default (I'm not sure how to check it that worked)

Part 2: in different .Swift file (Check if the User Default (aka Education Child) exists. I have pretty much nothing, except I know it must go into viewDidAppear

Part 1

```<code>@IBAction func SubmitPressed(_ sender: Any) {
let databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
databaseRef.child("Education").child(uid).setValue(self.Education.text!)
UserDefaults.standard.set("Education", forKey: "Education")
</code>```

Part 2
    func viewDidAppear(_ animated: String) {

    ??????
}

No error for part 1, though not sure if it created the user default. For part 2, I have tried a bunch of stuff, but hasn't worked.

Here is the updated code after first answer:

```<code>import Foundation
import UIKit
import SwiftKeychainWrapper
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase

var educationCache : String {
    get {
        return (UserDefaults.standard.string(forKey: "Education")!)
    } set {
        UserDefaults.standard.set(newValue, forKey: "Education")
    }
}
</code>```

relavant part of education/personal info enter page

```<code>@IBAction func SubmitPressed(_ sender: Any) {

    let databaseRef = Database.database().reference()
    let uid = Auth.auth().currentUser!.uid
    databaseRef.child("Education").child(uid).setValue(self.Education.text!)
    // The following line will save it in userDefault itself. And you dont have to call the whole UserDefault Everywhere
    educationCache = "Education"

    self.performSegue(withIdentifier: "tohome", sender: nil)
         }
</code>```

homepage

```<code>import Foundation
import UIKit
import SwiftKeychainWrapper
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase

class homepage:UITableViewController {

override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if educationCache.count < 0 {
        self.performSegue(withIdentifier: "toFeed", sender: nil)
    }

    }

 override func viewDidLoad() {

  navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut))
   super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@objc func signOut (_sender: AnyObject) {

    KeychainWrapper.standard.removeObject(forKey: "uid")
    do {
        try Auth.auth().signOut()
    } catch let signOutError as NSError {
        print ("Error signing out: %@", signOutError)
    }

    dismiss(animated: true, completion: nil)

     }

 }
</code>```

答:
You dont want to check the condition is the viewController where you are performing specific actions. Also checking the userDefaults everytime is just putting extra views in heirarchy. Firebase provides .addStateDidChangeListener function to keep a check of it. Add the following code to your delegate. It will automatically switch between the users if there are any or not.

```<code>AppDelegate.swift

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

        FirebaseApp.configure()
        observeUser()
        return true
    }

    func observeUser(){
        Auth.auth().addStateDidChangeListener { (auth, user) in
            if (user != nil) {
                // If the user is not nil. Perform this block
                self.showInitController(with identifier: "<add_your_storyboard_reusableID_for_homepage>", animated: false)
                // The storyboard Id belongs to the HOMEPAGE/FEED, the view where user goes on signIn
            } else {
                //If there is no user. This block will perform
                self.showInitController(with identifier: "<add_your_storyboard_reusableID_for_loginpage>", animated: false)
                // The storyboard Id belongs to the SIGNUP PAGE, the view where user goes on signIn
            }
        }
    }

   func showInitController(with identifier: String, animated: Bool = false) {
        DispatchQueue.main.async {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: identifier)
            var topRootViewController: UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!
            while((topRootViewController.presentedViewController) != nil){
                topRootViewController = topRootViewController.presentedViewController!
            }
            topRootViewController.present(vc, animated: animated, completion: nil)
        }
    }
</code>```

In your swift file one. do the following and never look back. You can automatically redirect to view if you applied the other functions.

```<code>@IBAction func SubmitPressed(_ sender: Any) {
        let databaseRef = Database.database().reference()
        let uid = Auth.auth().currentUser!.uid
        databaseRef.child("Education").child(uid).setValue(self.Education.text!)
        self.performSegue(withIdentifier: "tohome", sender: nil)
    }
</code>```

In the second view dont bother to do anything anywhere. Just leave it, if nothing in that view is required again.

Body:
Main issue is checking if user has a child in the Firebase database so that I know if he is signing up or logging in.

Part 1: Part 1 (Child Database (this works) and making that a user default (I'm not sure how to check it that worked)

Part 2: in different .Swift file (Check if the User Default (aka Education Child) exists. I have pretty much nothing, except I know it must go into viewDidAppear

Part 1

@IBAction func SubmitPressed(_ sender: Any) {
let databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
databaseRef.child("Education").child(uid).setValue(self.Education.text!)
UserDefaults.standard.set("Education", forKey: "Education")

Part 2
    func viewDidAppear(_ animated: String) {

    ??????
}

No error for part 1, though not sure if it created the user default. For part 2, I have tried a bunch of stuff, but hasn't worked.

Here is the updated code after first answer:

import Foundation
import UIKit
import SwiftKeychainWrapper
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase

var educationCache : String {
    get {
        return (UserDefaults.standard.string(forKey: "Education")!)
    } set {
        UserDefaults.standard.set(newValue, forKey: "Education")
    }
}

relavant part of education/personal info enter page

@IBAction func SubmitPressed(_ sender: Any) {

    let databaseRef = Database.database().reference()
    let uid = Auth.auth().currentUser!.uid
    databaseRef.child("Education").child(uid).setValue(self.Education.text!)
    // The following line will save it in userDefault itself. And you dont have to call the whole UserDefault Everywhere
    educationCache = "Education"

    self.performSegue(withIdentifier: "tohome", sender: nil)
         }

homepage

import Foundation
import UIKit
import SwiftKeychainWrapper
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase

class homepage:UITableViewController {

override func viewDidAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if educationCache.count < 0 {
        self.performSegue(withIdentifier: "toFeed", sender: nil)
    }

    }

 override func viewDidLoad() {

  navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut))
   super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@objc func signOut (_sender: AnyObject) {

    KeychainWrapper.standard.removeObject(forKey: "uid")
    do {
        try Auth.auth().signOut()
    } catch let signOutError as NSError {
        print ("Error signing out: %@", signOutError)
    }

    dismiss(animated: true, completion: nil)

     }

 }

Body:
You dont want to check the condition is the viewController where you are performing specific actions. Also checking the userDefaults everytime is just putting extra views in heirarchy. Firebase provides .addStateDidChangeListener function to keep a check of it. Add the following code to your delegate. It will automatically switch between the users if there are any or not.

AppDelegate.swift

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

        FirebaseApp.configure()
        observeUser()
        return true
    }

    func observeUser(){
        Auth.auth().addStateDidChangeListener { (auth, user) in
            if (user != nil) {
                // If the user is not nil. Perform this block
                self.showInitController(with identifier: "<add_your_storyboard_reusableID_for_homepage>", animated: false)
                // The storyboard Id belongs to the HOMEPAGE/FEED, the view where user goes on signIn
            } else {
                //If there is no user. This block will perform
                self.showInitController(with identifier: "<add_your_storyboard_reusableID_for_loginpage>", animated: false)
                // The storyboard Id belongs to the SIGNUP PAGE, the view where user goes on signIn
            }
        }
    }

   func showInitController(with identifier: String, animated: Bool = false) {
        DispatchQueue.main.async {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: identifier)
            var topRootViewController: UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!
            while((topRootViewController.presentedViewController) != nil){
                topRootViewController = topRootViewController.presentedViewController!
            }
            topRootViewController.present(vc, animated: animated, completion: nil)
        }
    }

In your swift file one. do the following and never look back. You can automatically redirect to view if you applied the other functions.

@IBAction func SubmitPressed(_ sender: Any) {
        let databaseRef = Database.database().reference()
        let uid = Auth.auth().currentUser!.uid
        databaseRef.child("Education").child(uid).setValue(self.Education.text!)
        self.performSegue(withIdentifier: "tohome", sender: nil)
    }

In the second view dont bother to do anything anywhere. Just leave it, if nothing in that view is required again.


问:
How to convert from Varbinary(MAX) into Video or Audio format in c# WPF
i am using Visual studio 2010, and used LINq to SQL to upload both videos or audios to the database in datatype Varbinary(max).   I now need to retrieve these files and display on xaml screen.  Can anyone help?   Here is  how i retrieve it from database and so far i added it to a byte [] array..  (assuming this is what you do??)

var fileValue = from s in context.Stimulis
              where s.stimID == 1
              select s.stimFile;

byte[] file = fileValue.Single().ToArray();

I've read that using File.WriteAllBytes() or something like this but i dont know if this is what i need to do.
Thanks Emma.

答:
In general it is not considered a good practice to store big images or videos inside a database. It is much better to organize them in a structured folder in the disk, and store in the database the paths to the files.

If you really need to store them in the database, your question depends on the files format and the API's you use. If you need to read them from disk, your approach is correct:

```<code>File.WriteAllBytes (strng path, byte[] bytes)
</code>```

then you can access the file to load it with the API's you're using.

Still I recommend to store the big files outside the database.

EDIT: I think I went too far saying it's not a good practice to store them on database :). But I still think is useful to have them outside the database.

SECOND EDIT: From your comment of converting any media to one file type... this is not possible. You can convert between different audio types, or between different image types, but not any media type into a single file type. I thought your question was more focused on storing and retrieving blobs to/from database, hence my answer.

Images can be viewed in XAML, but audios and videos are another thing...
I would start by taking a look into embedding Windows Media Player into your application:
Windows Media Player SDK
so you can reproduce anything that WMP can play :)

Body:
In general it is not considered a good practice to store big images or videos inside a database. It is much better to organize them in a structured folder in the disk, and store in the database the paths to the files.

If you really need to store them in the database, your question depends on the files format and the API's you use. If you need to read them from disk, your approach is correct:

File.WriteAllBytes (strng path, byte[] bytes)

then you can access the file to load it with the API's you're using.

Still I recommend to store the big files outside the database.

EDIT: I think I went too far saying it's not a good practice to store them on database :). But I still think is useful to have them outside the database.

SECOND EDIT: From your comment of converting any media to one file type... this is not possible. You can convert between different audio types, or between different image types, but not any media type into a single file type. I thought your question was more focused on storing and retrieving blobs to/from database, hence my answer.

Images can be viewed in XAML, but audios and videos are another thing...
I would start by taking a look into embedding Windows Media Player into your application:
Windows Media Player SDK
so you can reproduce anything that WMP can play :)


问:
Prevent input checkbox from toggling
I have an <input type="checkbox"> tag inside of a  inside a , which unfortunately toggles the  to open or close when it is checked or unchecked, not unlike this question concerning space toggling details, but unfortunately can't be fixed with the same method for me in my version of Firefox.

See below snippet:

$('input').change(function(e) {
  e.stopPropagation();
  e.preventDefault();
  return false;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<details>
  <summary>
    <input type="checkbox">
  </summary>
  <div>
 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse finibus bibendum lorem, vitae efficitur felis mattis vitae. Sed mattis tristique rutrum. Morbi a placerat purus, et pulvinar risus. Vivamus accumsan sapien et nisi vulputate blandit. Aenean nec consectetur nulla. Nunc efficitur tincidunt placerat. Vivamus blandit est lectus, ut fermentum velit vulputate ut. Morbi elementum sem massa, eleifend laoreet dui tristique quis. Nulla mi dolor, consectetur blandit fermentum quis, tempor id nisi. Phasellus vel lobortis enim, id blandit turpis. Nullam dapibus feugiat risus eu pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam enim justo, pharetra sit amet urna sed, ultricies tempor nibh.
  </div>
</details></code>```

How do I prevent the  getting opened/closed by checking or unchecking the checkbox? (Other than the obvious answer of moving the <input> tag outside the . I am curious as to why this happens)

Edit

As mentioned by @Terry and then confirmed by me, this issue does not affect either Safari or Chrome, and even Firefox on Windows seems to act differently (it just ignores clicks on the checkbox entirely). Confirmed affects Firefox 66.0.2-3 on OS X Mojave 10.14.4.

Also if you capture the click event on the  and return false; the checkbox still toggles the , even though clicking elsewhere in the  doesn't.

Edit 2

This was a Firefox bug and has been fixed in version 67.

答:
This issue has been fixed in Firefox 67.

See https://bugzilla.mozilla.org/show_bug.cgi?id=1524893.

(https://bugzilla.mozilla.org/show_bug.cgi?id=1554691 and https://bugzilla.mozilla.org/show_bug.cgi?id=1539490) are duplicates of the issue.

Title: Prevent input checkbox from toggling <details>

Body:
I have an <input type="checkbox"> tag inside of a  inside a , which unfortunately toggles the  to open or close when it is checked or unchecked, not unlike this question concerning space toggling details, but unfortunately can't be fixed with the same method for me in my version of Firefox.

See below snippet:

$('input').change(function(e) {
  e.stopPropagation();
  e.preventDefault();
  return false;
});

    <input type="checkbox">

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse finibus bibendum lorem, vitae efficitur felis mattis vitae. Sed mattis tristique rutrum. Morbi a placerat purus, et pulvinar risus. Vivamus accumsan sapien et nisi vulputate blandit. Aenean nec consectetur nulla. Nunc efficitur tincidunt placerat. Vivamus blandit est lectus, ut fermentum velit vulputate ut. Morbi elementum sem massa, eleifend laoreet dui tristique quis. Nulla mi dolor, consectetur blandit fermentum quis, tempor id nisi. Phasellus vel lobortis enim, id blandit turpis. Nullam dapibus feugiat risus eu pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam enim justo, pharetra sit amet urna sed, ultricies tempor nibh.

How do I prevent the  getting opened/closed by checking or unchecking the checkbox? (Other than the obvious answer of moving the <input> tag outside the . I am curious as to why this happens)

Edit

As mentioned by @Terry and then confirmed by me, this issue does not affect either Safari or Chrome, and even Firefox on Windows seems to act differently (it just ignores clicks on the checkbox entirely). Confirmed affects Firefox 66.0.2-3 on OS X Mojave 10.14.4.

Also if you capture the click event on the  and return false; the checkbox still toggles the , even though clicking elsewhere in the  doesn't.

Edit 2

This was a Firefox bug and has been fixed in version 67.


问:
Cypher : Union between queries, with an initial node retrieval
I am trying to write a Cypher query which is kind of a "union" query, basically something like :

```<code>MATCH (myNodeUsedInAllSubQueries)
WITH myNodeUsedInAllSubQueries
MATCH (a)-[...]->(myNodeUsedInAllSubQueries)
RETURN a
UNION
MATCH (b)-[...]->(myNodeUsedInAllSubQueries)
RETURN b
...
</code>```

I want to match (myNodeUsedInAllSubQueries) once at the beginning because this node is used in all subqueries.
Of course, the retrieval of this node in my example is not just as simple as this (it involves relationships and a WHERE clause, but I'll keep it simple here).

I'll try to explain this with a simple example and what I've tried so far.

Example

Graphically, the graph structure is the following :

```<code>(John: Person) ----------[LIKES]----------> (pizza: Food)
                                               ^
        (Developers: Group) ------[LIKES]------┘

(Jim: Person) --[BELONGS_TO]--> (Business: Group) --[LIKES]--> (apple: Food)
</code>```

The example is accessible here in Neo4J console. The import script is here (in case you want to reproduce the issue locally) :

```<code>CREATE (john: Person{name: "John"});
CREATE (jim: Person{name: "Jim"});

CREATE (devs: Group{name: "Developers"});
CREATE (business: Group{name: "Business"});

CREATE (pizza: Food{name: "pizza"});
CREATE (apple: Food{name: "apple"});

MATCH (john: Person{name: "John"}), (pizza: Food{name: "pizza"})
CREATE (john)-[:LIKES]->(pizza);

MATCH (jim: Person{name: "Jim"}), (business: Group{name: "Business"})
CREATE (jim)-[:BELONGS_TO]->(business);

MATCH (devs: Group{name: "Developers"}), (pizza: Food{name: "pizza"})
CREATE (devs)-[:LIKES]->(pizza);

MATCH (business: Group{name: "Business"}), (apple: Food{name: "apple"})
CREATE (business)-[:LIKES]->(apple);
</code>```

For that particular example, my question is : how to retrieve all Person nodes who likes pizza? Knowing that :

A Person can like Food (direct relation)

A Group can like Food, and transitively if person A BELONGS_TO a group,
he LIKES also the food that the group LIKES (but there is no direct relation
between Person and Food in that case)

I'd also like to retrieve the pizza node once. As I said in introduction, in my real example, the retrieval of pizza could be quite complicated, so I don't want to duplicate the MATCH in each case.

What I've tried

Using UNION

```<code>MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN p
</code>```

This query returns surprinsingly 2 nodes : John and Jim. After investigating, I have understood that
this is because (pizza) in the 2nd UNION clause does not refer to the pizza node
returned by the first MATCH, but rather any node. We can confirm that by running :

```<code>MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(anything)
WHERE anything = pizza
RETURN p
</code>```

This returns an error :

```<code>Neo.ClientError.Statement.SyntaxError: Variable `pizza` not defined (line 7, column 18 (offset: 184))
"WHERE anything = pizza"
</code>```

, validating the fact that pizza node is not propagated to the second MATCH.

Using WITH and COLLECT

This fixes the problem of the pizza node that cannot be passed from the first MATCH to the 3nd MATCH.

```<code>MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
WITH pizza, COLLECT(p) AS people
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN people + COLLECT(p) AS people
</code>```

But this query does not return anything : this is because the 3nd MATCH does not return anything
(there are no Person in a Group that LIKES pizza).

If I add a Person in the Developers Group :

```<code>MATCH (devs: Group{name: "Developers"})
CREATE (emma: Person{name: "Emma"})-[:BELONGS_TO]->(devs)
</code>```

The previous query returns successfully John and Emma because the last MATCH returns at least one Person.
But in my case, it is possible that this MATCH does not return anything, so that does not work.

I hope this example is simple and clear. In this case, the query I'm looking for should return only John, because he's the only Person here who likes pizza.

答:
[UPDATED]

This should work for your simple use case:

```<code>MATCH (p:Person)-[:BELONGS_TO|LIKES*..2]->(food:Food {name:"pizza"})
RETURN food, COLLECT(p) AS people;
</code>```

Body:
I am trying to write a Cypher query which is kind of a "union" query, basically something like :

MATCH (myNodeUsedInAllSubQueries)
WITH myNodeUsedInAllSubQueries
MATCH (a)-[...]->(myNodeUsedInAllSubQueries)
RETURN a
UNION
MATCH (b)-[...]->(myNodeUsedInAllSubQueries)
RETURN b
...

I want to match (myNodeUsedInAllSubQueries) once at the beginning because this node is used in all subqueries.
Of course, the retrieval of this node in my example is not just as simple as this (it involves relationships and a WHERE clause, but I'll keep it simple here).

I'll try to explain this with a simple example and what I've tried so far.

Example

Graphically, the graph structure is the following :

(John: Person) ----------[LIKES]----------> (pizza: Food)
                                               ^
        (Developers: Group) ------[LIKES]------┘

(Jim: Person) --[BELONGS_TO]--> (Business: Group) --[LIKES]--> (apple: Food)

The example is accessible here in Neo4J console. The import script is here (in case you want to reproduce the issue locally) :

CREATE (john: Person{name: "John"});
CREATE (jim: Person{name: "Jim"});

CREATE (devs: Group{name: "Developers"});
CREATE (business: Group{name: "Business"});

CREATE (pizza: Food{name: "pizza"});
CREATE (apple: Food{name: "apple"});

MATCH (john: Person{name: "John"}), (pizza: Food{name: "pizza"})
CREATE (john)-[:LIKES]->(pizza);

MATCH (jim: Person{name: "Jim"}), (business: Group{name: "Business"})
CREATE (jim)-[:BELONGS_TO]->(business);

MATCH (devs: Group{name: "Developers"}), (pizza: Food{name: "pizza"})
CREATE (devs)-[:LIKES]->(pizza);

MATCH (business: Group{name: "Business"}), (apple: Food{name: "apple"})
CREATE (business)-[:LIKES]->(apple);

For that particular example, my question is : how to retrieve all Person nodes who likes pizza? Knowing that :

A Person can like Food (direct relation)

A Group can like Food, and transitively if person A BELONGS_TO a group,
he LIKES also the food that the group LIKES (but there is no direct relation
between Person and Food in that case)

I'd also like to retrieve the pizza node once. As I said in introduction, in my real example, the retrieval of pizza could be quite complicated, so I don't want to duplicate the MATCH in each case.

What I've tried

Using UNION

MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN p

This query returns surprinsingly 2 nodes : John and Jim. After investigating, I have understood that
this is because (pizza) in the 2nd UNION clause does not refer to the pizza node
returned by the first MATCH, but rather any node. We can confirm that by running :

MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
RETURN p
UNION
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(anything)
WHERE anything = pizza
RETURN p

This returns an error :

Neo.ClientError.Statement.SyntaxError: Variable `pizza` not defined (line 7, column 18 (offset: 184))
"WHERE anything = pizza"

, validating the fact that pizza node is not propagated to the second MATCH.

Using WITH and COLLECT

This fixes the problem of the pizza node that cannot be passed from the first MATCH to the 3nd MATCH.

MATCH (pizza: Food{name: "pizza"})
WITH pizza
MATCH (p: Person)-[:LIKES]->(pizza)
WITH pizza, COLLECT(p) AS people
MATCH (p: Person)-[:BELONGS_TO]->(g: Group)-[:LIKES]->(pizza)
RETURN people + COLLECT(p) AS people

But this query does not return anything : this is because the 3nd MATCH does not return anything
(there are no Person in a Group that LIKES pizza).

If I add a Person in the Developers Group :

MATCH (devs: Group{name: "Developers"})
CREATE (emma: Person{name: "Emma"})-[:BELONGS_TO]->(devs)

The previous query returns successfully John and Emma because the last MATCH returns at least one Person.
But in my case, it is possible that this MATCH does not return anything, so that does not work.

I hope this example is simple and clear. In this case, the query I'm looking for should return only John, because he's the only Person here who likes pizza.

Body:
[UPDATED]

This should work for your simple use case:

MATCH (p:Person)-[:BELONGS_TO|LIKES*..2]->(food:Food {name:"pizza"})
RETURN food, COLLECT(p) AS people;


问:
Plotting data of a mysql database by date
I created a mysql-database to save the humidity, temperature and several other datas with a timestamp. I can plot the data, but the x-axis is not labeled.

I tried to set the label of the ticks, which did not labeled them correctly. It was not possible to see on which date which data was saved. The type of the dates is datetime.datetime()

```<code>result = cursor.fetchall()

for r in result:
    dates.append(r[1])
    humidity.append(r[2])
    temperature.append(r[3])
    pm25.append(r[4])
    pm10.append(r[5])

fig, ax = plt.subplots()

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

ax.plot(dates, humidity, color = 'b')
ax.plot(dates, temperature, color = 'r')
ax.plot(dates, pm25, color = 'orange')
ax.plot(dates, pm10, color = 'g')

plt.show()
</code>```

I want the dates to label the x-axis and if it is possible to mark every new day with a bigger tick.

答:
I have not been able to reproduce your problem without an example of your data, but I wrote some code using mine. My database is sqlite3, but that doesn't really matter.

Getting the data

Pandas have a read_sql_query method which you might find useful. I'm using its parse_dates and index_col to read the data straight into a pandas dataframe with a datetime index.

```<code># read_sql_query
with sqlite3.connect(my_db) as con:
    query = "SELECT humidity, ground_temp, ambient_temp, reading_timestamp from Measurements WHERE Measurements.stations_id = 591441"
    to_plot = pd.read_sql_query(sql=query, con=con, parse_dates=['reading_timestamp'], index_col='reading_timestamp')
</code>```

If you prefer fetchall() I can achieve the same result like this:

```<code># fetchall
with sqlite3.connect(my_db) as con:
    query = "SELECT humidity, ground_temp, ambient_temp, reading_timestamp from Measurements WHERE Measurements.stations_id = 591441"
    to_plot = con.execute(query).fetchall()
    to_plot = pd.DataFrame(to_plot, columns=['humidity', 'ground_temp', 'ambient_temp', 'reading_timestamp']).set_index('reading_timestamp')
</code>```

Here is my data:

```<code>                           humidity  ground_temp  ambient_temp
reading_timestamp
2019-05-21 14:55:02+00:00     70.66        14.31         16.33
2019-05-22 10:25:02+00:00     42.08        14.56         15.37
2019-05-23 12:25:02+00:00     55.07        15.75         17.49
2019-05-24 03:25:02+00:00     65.10        16.88         21.25
2019-05-27 13:55:02+00:00     57.46        18.50         25.12
</code>```

Index is datetime:

```<code>to_plot.index

DatetimeIndex(['2019-05-21 14:55:02+00:00', '2019-05-22 10:25:02+00:00',
               '2019-05-23 12:25:02+00:00', '2019-05-24 03:25:02+00:00',
               '2019-05-27 13:55:02+00:00'],
              dtype='datetime64[ns, UTC]', name='reading_timestamp', freq=None)
</code>```

Now I have a range of options how to plot.

1. Plot the whole DataFrame

The easiest and the quickest, but less customizable.

```<code>fig, ax = plt.subplots()
plt.plot(to_plot)
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
</code>```

2. Plot individual Series

More control, assigns labels automatically so I can easily add a legend.

```<code>fig, ax = plt.subplots()
ax.plot(to_plot['ambient_temp'], 'orange')
ax.plot(to_plot['ground_temp'], 'red')
ax.plot(to_plot['humidity'], 'blue')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()
</code>```

3. Plotting lists should work as well

But I don't see any benefit in this use case. Plotting Series gives the same result with less typing.

```<code># Convert to lists
dates = list(to_plot.index)
ambient_temp = list(to_plot['ambient_temp'])
ground_temp = list(to_plot['ground_temp'])
humidity = list(to_plot['humidity'])
# Plot lists
fig, ax = plt.subplots()
ax.plot(dates, ambient_temp, 'orange', label='ambient_temp')
ax.plot(dates, ground_temp, 'red', label='ground_temp')
ax.plot(dates, humidity, 'blue', label='humidity')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()
</code>```

Days in a bigger font

Now to get days to display in a bigger font, I would suggest that you set days as major ticks using matplotlib.dates and then format them the way you want.

```<code>fig, ax = plt.subplots()
ax.plot(to_plot['ambient_temp'], 'orange')
ax.plot(to_plot['ground_temp'], 'red')
ax.plot(to_plot['humidity'], 'blue')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

import matplotlib.dates as mdates
# mdates detects days
days = mdates.DayLocator()
# format for days
days_fmt = mdates.DateFormatter('%Y-%m-%d')
# days are major ticks
ax.xaxis.set_major_locator(days)
# format major ticks as days
ax.xaxis.set_major_formatter(days_fmt)
# give major ticks on x-axis a large font
ax.tick_params(axis='x', which='major', labelsize=13)
</code>```

Body:
I created a mysql-database to save the humidity, temperature and several other datas with a timestamp. I can plot the data, but the x-axis is not labeled.

I tried to set the label of the ticks, which did not labeled them correctly. It was not possible to see on which date which data was saved. The type of the dates is datetime.datetime()

result = cursor.fetchall()

for r in result:
    dates.append(r[1])
    humidity.append(r[2])
    temperature.append(r[3])
    pm25.append(r[4])
    pm10.append(r[5])

fig, ax = plt.subplots()

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

ax.plot(dates, humidity, color = 'b')
ax.plot(dates, temperature, color = 'r')
ax.plot(dates, pm25, color = 'orange')
ax.plot(dates, pm10, color = 'g')

plt.show()

I want the dates to label the x-axis and if it is possible to mark every new day with a bigger tick.

Body:
I have not been able to reproduce your problem without an example of your data, but I wrote some code using mine. My database is sqlite3, but that doesn't really matter.

Getting the data

Pandas have a read_sql_query method which you might find useful. I'm using its parse_dates and index_col to read the data straight into a pandas dataframe with a datetime index.

# read_sql_query
with sqlite3.connect(my_db) as con:
    query = "SELECT humidity, ground_temp, ambient_temp, reading_timestamp from Measurements WHERE Measurements.stations_id = 591441"
    to_plot = pd.read_sql_query(sql=query, con=con, parse_dates=['reading_timestamp'], index_col='reading_timestamp')

If you prefer fetchall() I can achieve the same result like this:

# fetchall
with sqlite3.connect(my_db) as con:
    query = "SELECT humidity, ground_temp, ambient_temp, reading_timestamp from Measurements WHERE Measurements.stations_id = 591441"
    to_plot = con.execute(query).fetchall()
    to_plot = pd.DataFrame(to_plot, columns=['humidity', 'ground_temp', 'ambient_temp', 'reading_timestamp']).set_index('reading_timestamp')

Here is my data:

                           humidity  ground_temp  ambient_temp
reading_timestamp
2019-05-21 14:55:02+00:00     70.66        14.31         16.33
2019-05-22 10:25:02+00:00     42.08        14.56         15.37
2019-05-23 12:25:02+00:00     55.07        15.75         17.49
2019-05-24 03:25:02+00:00     65.10        16.88         21.25
2019-05-27 13:55:02+00:00     57.46        18.50         25.12

Index is datetime:

to_plot.index

DatetimeIndex(['2019-05-21 14:55:02+00:00', '2019-05-22 10:25:02+00:00',
               '2019-05-23 12:25:02+00:00', '2019-05-24 03:25:02+00:00',
               '2019-05-27 13:55:02+00:00'],
              dtype='datetime64[ns, UTC]', name='reading_timestamp', freq=None)

Now I have a range of options how to plot.

1. Plot the whole DataFrame

The easiest and the quickest, but less customizable.

fig, ax = plt.subplots()
plt.plot(to_plot)
for tick in ax.get_xticklabels():
    tick.set_rotation(45)

2. Plot individual Series

More control, assigns labels automatically so I can easily add a legend.

fig, ax = plt.subplots()
ax.plot(to_plot['ambient_temp'], 'orange')
ax.plot(to_plot['ground_temp'], 'red')
ax.plot(to_plot['humidity'], 'blue')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

3. Plotting lists should work as well

But I don't see any benefit in this use case. Plotting Series gives the same result with less typing.

# Convert to lists
dates = list(to_plot.index)
ambient_temp = list(to_plot['ambient_temp'])
ground_temp = list(to_plot['ground_temp'])
humidity = list(to_plot['humidity'])
# Plot lists
fig, ax = plt.subplots()
ax.plot(dates, ambient_temp, 'orange', label='ambient_temp')
ax.plot(dates, ground_temp, 'red', label='ground_temp')
ax.plot(dates, humidity, 'blue', label='humidity')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

Days in a bigger font

Now to get days to display in a bigger font, I would suggest that you set days as major ticks using matplotlib.dates and then format them the way you want.

fig, ax = plt.subplots()
ax.plot(to_plot['ambient_temp'], 'orange')
ax.plot(to_plot['ground_temp'], 'red')
ax.plot(to_plot['humidity'], 'blue')
for tick in ax.get_xticklabels():
    tick.set_rotation(45)
ax.legend()

import matplotlib.dates as mdates
# mdates detects days
days = mdates.DayLocator()
# format for days
days_fmt = mdates.DateFormatter('%Y-%m-%d')
# days are major ticks
ax.xaxis.set_major_locator(days)
# format major ticks as days
ax.xaxis.set_major_formatter(days_fmt)
# give major ticks on x-axis a large font
ax.tick_params(axis='x', which='major', labelsize=13)


问:
Resize tables based on number of records in SSRS
I have two table having data like below:

```<code>            SELECT *
              FROM [dbo].[TestTable_1]
            ID  Value
            ----------
            1   gjha
            2   dc
            3   d
            4   ds
            5   dg
            6   hn
</code>```

2nd table:

```<code>            SELECT *
              FROM [dbo].[TestTable_2]
            Value
            -----
            jklsa
            dfv
            b
            grt
            trj
            h
            muik
            rg
            kuu
            wd
            gb
            nm
            wef
</code>```

I'm fetching the data in SSRS report as below:

Question is:

How can I maintain the table size same? That is, if small table in SSRS report has 6 records (which is in this case),
the bigger one should adjust same size as small and the extra (/more) records that are coming in the large table should shift to right.

Here is the expected output from SSRS

```<code>            Value           Value
            --------  -----------------
            gjha      jklsa |muik | wef
            dc        dfv   |rg   |
            d         b     |kuu  |
            ds        grt   |wd   |
            dg        trj   |gb   |
            hn        h     |nm   |
</code>```

Note: The above details are just example, however, the number of records are really dynamic.

答:
This is not a full answer as it's just what came to mind and is completely untested.

First thing is to search SO for ways to create a multi-column table, there are plenty of answers already so I won't explain in detail here. They usually involve adding RowNumber to each row which you can then use to calculate a matrix row and matrix column number, the column number can be used in a matrix as the column group. (e.g. if the row limit is 6 and the row number is 14, that will have a final row number of 2  (14 mod 6 = 2) and a column number of 3 as Floor(14/6)+1 = 3.

Next, create dataset that just gets the highest row count from each of your tables. Something like

```<code>DECLARE @a int
DECLARE @b int
SELECT @a = COUNT(*) FROM myTableA
SELECT @b = COUNT(*) FROM myTableA

SELECT CASE WHEN @a<=@b THEN @a ELSE @b END AS maxRows
</code>```

Now you have the size of the smallest table, you can pass that as a parameter to the proc that gets the actual data from the two tables (this would be 6 in our example above)

Body:
I have two table having data like below:

            SELECT *
              FROM [dbo].[TestTable_1]
            ID  Value
            ----------
            1   gjha
            2   dc
            3   d
            4   ds
            5   dg
            6   hn

2nd table:

            SELECT *
              FROM [dbo].[TestTable_2]
            Value
            -----
            jklsa
            dfv
            b
            grt
            trj
            h
            muik
            rg
            kuu
            wd
            gb
            nm
            wef

I'm fetching the data in SSRS report as below:

Question is:

How can I maintain the table size same? That is, if small table in SSRS report has 6 records (which is in this case),
the bigger one should adjust same size as small and the extra (/more) records that are coming in the large table should shift to right.

Here is the expected output from SSRS

            Value           Value
            --------  -----------------
            gjha      jklsa |muik | wef
            dc        dfv   |rg   |
            d         b     |kuu  |
            ds        grt   |wd   |
            dg        trj   |gb   |
            hn        h     |nm   |

Note: The above details are just example, however, the number of records are really dynamic.

Body:
This is not a full answer as it's just what came to mind and is completely untested.

First thing is to search SO for ways to create a multi-column table, there are plenty of answers already so I won't explain in detail here. They usually involve adding RowNumber to each row which you can then use to calculate a matrix row and matrix column number, the column number can be used in a matrix as the column group. (e.g. if the row limit is 6 and the row number is 14, that will have a final row number of 2  (14 mod 6 = 2) and a column number of 3 as Floor(14/6)+1 = 3.

Next, create dataset that just gets the highest row count from each of your tables. Something like

DECLARE @a int
DECLARE @b int
SELECT @a = COUNT(*) FROM myTableA
SELECT @b = COUNT(*) FROM myTableA

SELECT CASE WHEN @a<=@b THEN @a ELSE @b END AS maxRows

Now you have the size of the smallest table, you can pass that as a parameter to the proc that gets the actual data from the two tables (this would be 6 in our example above)


问:
THREE.js FBXLoader treats .png as if it is a .psd, and doesn't load the material
When using the THREE.js FBXLoader to load a .fbx file, it is loading the model partially, with the alpha textured parts of the model not being loaded.

I am getting the error:

FBXLoader: PSD textures are not supported, creating empty placeholder texture for pinebranchColor.psd

Despite there being no .psd files in the materials folder. As you can see from the below screenshot, it seems to think that in the material alphaMap, the texture name is pinebranchColor.psd.

This is what the FBX model is being rendered as:

And this is what it renders as if I load the GLTF version (note: the transparent parts for the leaves are not picked up as transparent) - which is closer to how it should look, but not fully.

This is how the model is supposed to look, according to sketchfab :

Why do you think it says the alpha material is a .psd? Could this be as referenced in the .fbx file itself? The original problem was how do I get the alpha/transparency for the leaves to render correctly, rather than as block colour. Maybe I could set a property in the THREE.js material of the GLTF version and that would work?

This is the first model I have ever imported into THREE.js as I have just started learning, so please explain as best you can.

EDIT:
In dev tools I found a material for the leaves, and set transparent to true. This worked! To an extent. But there are still some rendering issues. So I think this is the route to go down.

答:
I'm not sure why the FBX alpha material could not be loaded, but I solved the transparency problem with the GLTF version by using the THREE.js scene.traverse function, and setting the material transparent property to true, for all leaf materials in the scene.

This solved the core issue, but there were still some artifacts as seen in this picture, where leaves behind are blacked out:

The solution was to also set alphaTest to 0.5 on the material, giving this result:

Here is the code:

```<code>gltf.scene.traverse(child => {
  if (child.isMesh && child.name.includes('leaf')) {
    child.material.alphaTest = 0.5;
    child.material.transparent = true;
  }
});
</code>```

Body:
I'm not sure why the FBX alpha material could not be loaded, but I solved the transparency problem with the GLTF version by using the THREE.js scene.traverse function, and setting the material transparent property to true, for all leaf materials in the scene.

This solved the core issue, but there were still some artifacts as seen in this picture, where leaves behind are blacked out:

The solution was to also set alphaTest to 0.5 on the material, giving this result:

Here is the code:

gltf.scene.traverse(child => {
  if (child.isMesh && child.name.includes('leaf')) {
    child.material.alphaTest = 0.5;
    child.material.transparent = true;
  }
});


问:
Findopenssl.cmake fails to find OpenSSL, compiling restbed, C++
I'm trying to use cmake 3.7.2 on Debian 9.7 to compile restbed, a C++ framework for web services.

I follow the readme instructions. they're straight forward.

```<code>git clone --recursive https://github.com/corvusoft/restbed.git
mkdir restbed/build
cd restbed/build
cmake [-DBUILD_SSL=NO] ..
make install
make test
</code>```

But i get the following error when running cmake:

```<code>-- Found ASIO include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/asio/asio/include
-- Found Catch include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/catch/single_include
CMake Error at cmake/Findopenssl.cmake:23 (message):
  Failed to locate OpenSSL dependency.  see restbed/dependency/openssl;
  ./config shared; make all
Call Stack (most recent call first):
  CMakeLists.txt:47 (find_package)
</code>```

So I check Findopenssl.cmake, and find that it's looking in a number of places for the libraries.

```<code>find_library( ssl_LIBRARY_STATIC libssl.a  ssleay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_STATIC libcrypto.a libeay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_library( ssl_LIBRARY_SHARED libssl.so libssl.dylib ssleay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_SHARED libcrypto.so libcrypto.dylib libeay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_path( ssl_INCLUDE openssl/ssl.h HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/inc32" "${PROJECT_SOURCE_DIR}/dependency/openssl/include" "/usr/local/opt/openssl/include" "/usr/include" "/usr/local/include" "/opt/local/include" )

if ( ssl_LIBRARY_STATIC AND ssl_LIBRARY_SHARED AND crypto_LIBRARY_STATIC AND crypto_LIBRARY_SHARED )
    set( OPENSSL_FOUND TRUE )
    add_definitions( -DBUILD_SSL=TRUE )

    if ( APPLE AND BUILD_SSL )
        set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations" )
    endif( )

    message( STATUS "Found OpenSSL include at: ${ssl_INCLUDE}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_STATIC}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_SHARED}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_STATIC}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_SHARED}" )
else ( )
    message( FATAL_ERROR "Failed to locate OpenSSL dependency. see restbed/dependency/openssl; ./config shared; make all" )
endif ( )
</code>```

I can't find these file either. I have openssl installed, version 1.1.0

What obvious thing am I missing here?

Thanks

答:
Try using the cmake command without brackets:

```<code>cmake -DBUILD_SSL=NO ..
</code>```

Body:
I'm trying to use cmake 3.7.2 on Debian 9.7 to compile restbed, a C++ framework for web services.

I follow the readme instructions. they're straight forward.

git clone --recursive https://github.com/corvusoft/restbed.git
mkdir restbed/build
cd restbed/build
cmake [-DBUILD_SSL=NO] ..
make install
make test

But i get the following error when running cmake:

-- Found ASIO include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/asio/asio/include
-- Found Catch include at: /home/ben/Workspaces/C_Experiments/restbed/dependency/catch/single_include
CMake Error at cmake/Findopenssl.cmake:23 (message):
  Failed to locate OpenSSL dependency.  see restbed/dependency/openssl;
  ./config shared; make all
Call Stack (most recent call first):
  CMakeLists.txt:47 (find_package)

So I check Findopenssl.cmake, and find that it's looking in a number of places for the libraries.

find_library( ssl_LIBRARY_STATIC libssl.a  ssleay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_STATIC libcrypto.a libeay32.lib HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_library( ssl_LIBRARY_SHARED libssl.so libssl.dylib ssleay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY_SHARED libcrypto.so libcrypto.dylib libeay32.dll HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )

find_path( ssl_INCLUDE openssl/ssl.h HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/inc32" "${PROJECT_SOURCE_DIR}/dependency/openssl/include" "/usr/local/opt/openssl/include" "/usr/include" "/usr/local/include" "/opt/local/include" )

if ( ssl_LIBRARY_STATIC AND ssl_LIBRARY_SHARED AND crypto_LIBRARY_STATIC AND crypto_LIBRARY_SHARED )
    set( OPENSSL_FOUND TRUE )
    add_definitions( -DBUILD_SSL=TRUE )

    if ( APPLE AND BUILD_SSL )
        set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations" )
    endif( )

    message( STATUS "Found OpenSSL include at: ${ssl_INCLUDE}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_STATIC}" )
    message( STATUS "Found OpenSSL library at: ${ssl_LIBRARY_SHARED}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_STATIC}" )
    message( STATUS "Found Crypto library at: ${crypto_LIBRARY_SHARED}" )
else ( )
    message( FATAL_ERROR "Failed to locate OpenSSL dependency. see restbed/dependency/openssl; ./config shared; make all" )
endif ( )

I can't find these file either. I have openssl installed, version 1.1.0

What obvious thing am I missing here?

Thanks

Body:
Try using the cmake command without brackets:

cmake -DBUILD_SSL=NO ..


问:
asp.net mvc Testing Model Returned by controller ActionResult
From controller Action:

```<code>return PartialView("Page1",obj);
</code>```

Now in the MVC testing I have to test whether obj is an instance of CLASS: ClassObj

I am trying

```<code>var actualResult=controller.getObj();
Assert.IsInstanceOf(ClassObj,actualResult,"Fail");
</code>```

but problem is actualResult is PartialViewResult.
How can i get model from it?
Thanks.

答:
You can look at the ViewData property of the result object.

from controller:

```<code>ViewData["data"] = obj;
</code>```

in the test:

```<code>var result = controller.Action();
Assert.IsOfType<PartialViewResult>(result);

var data = ((PartialViewResult)result).ViewData["data"];
</code>```

Or if the view is typed, then you might access the model directly. (I'm not exactly sure about the code, you need to test it).

```<code>var data =  (ViewPage<ModelType>((PartialViewResult)result).View).Model;
</code>```

Body:
From controller Action:

return PartialView("Page1",obj);

Now in the MVC testing I have to test whether obj is an instance of CLASS: ClassObj

I am trying

var actualResult=controller.getObj();
Assert.IsInstanceOf(ClassObj,actualResult,"Fail");

but problem is actualResult is PartialViewResult.
How can i get model from it?
Thanks.

Body:
You can look at the ViewData property of the result object.

from controller:

ViewData["data"] = obj;

in the test:

var result = controller.Action();
Assert.IsOfType<PartialViewResult>(result);

var data = ((PartialViewResult)result).ViewData["data"];

Or if the view is typed, then you might access the model directly. (I'm not exactly sure about the code, you need to test it).

var data =  (ViewPage<ModelType>((PartialViewResult)result).View).Model;


问:
How do I predict new data's cluster after clustering training data?
I have already trained my clustering model using hclust:

```<code> model=hclust(distances,method="ward”)
</code>```

And the result looks good:

Now I get some new data records, I want to predict which cluster every one of them belongs to. How do I get it done ?

答:
As already mentioned, you can use a classifier such as class :: knn, to determine which cluster a new individual belongs to.

The KNN or k-nearest neighbors algorithm is one of the simplest machine learning algorithms and is an example of instance-based learning, where new data are classified based on stored, labeled instances. More specifically, the distance between the stored data and the new instance is calculated by means of some kind of a similarity measure. This similarity measure is typically expressed by a distance measure such as the Euclidean distance.

Next I leave a code as an example for the iris data.

```<code>library(scorecard)
library(factoextra)
library(class)

df_iris <- split_df(iris, ratio = 0.75, seed = 123)
d_iris <- dist(scale(df_iris$train[,-5]))

hc_iris <- hclust(d_iris, method = "ward.D2")
fviz_dend(hc_iris, k = 3,cex = 0.5,k_colors = c("#00AFBB","#E7B800","#FC4E07"),
          color_labels_by_k = TRUE, ggtheme = theme_minimal())
groups <- cutree(hc_iris, k = 3)
table(groups)
</code>```

Predict new data

```<code>knnClust <- knn(train = df_iris$train[,-5], test = df_iris$test[,-5] , k = 1, cl = groups)
knnClust
 [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 2 3 3 3 2 2 2 2 2 3 3 2 2 3 2 2 2 2 2 2 2 2 2
Levels: 1 2 3

# p1 <- fviz_cluster(list(data = df_iris$train[,-5], cluster = groups), stand = F) + xlim(-11.2,-4.8) + ylim(-3,3) + ggtitle("train")
# p2 <- fviz_cluster(list(data = df_iris$test[,-5], cluster = knnClust),stand = F) + xlim(-11.2,-4.8) + ylim(-3,3) + ggtitle("test")
# gridExtra::grid.arrange(p1,p2,nrow = 2)

pca1 <- data.frame(prcomp(df_iris$train[,-5], scale. = T)$x[,1:2], cluster = as.factor(groups), factor = "train")
pca2 <- data.frame(prcomp(df_iris$test[,-5], scale. = T)$x[,1:2], cluster = as.factor(knnClust), factor = "test")
pca <- as.data.frame(rbind(pca1,pca2))
</code>```

Plot train and test data

```<code>ggplot(pca, aes(x = PC1, y = PC2, color = cluster, size = 1, alpha = factor)) +
  geom_point(shape = 19) + theme_bw()
</code>```

Body:
I have already trained my clustering model using hclust:

 model=hclust(distances,method="ward”)

And the result looks good:

Now I get some new data records, I want to predict which cluster every one of them belongs to. How do I get it done ?

Body:
As already mentioned, you can use a classifier such as class :: knn, to determine which cluster a new individual belongs to.

The KNN or k-nearest neighbors algorithm is one of the simplest machine learning algorithms and is an example of instance-based learning, where new data are classified based on stored, labeled instances. More specifically, the distance between the stored data and the new instance is calculated by means of some kind of a similarity measure. This similarity measure is typically expressed by a distance measure such as the Euclidean distance.

Next I leave a code as an example for the iris data.

library(scorecard)
library(factoextra)
library(class)

df_iris <- split_df(iris, ratio = 0.75, seed = 123)
d_iris <- dist(scale(df_iris$train[,-5]))

hc_iris <- hclust(d_iris, method = "ward.D2")
fviz_dend(hc_iris, k = 3,cex = 0.5,k_colors = c("#00AFBB","#E7B800","#FC4E07"),
          color_labels_by_k = TRUE, ggtheme = theme_minimal())
groups <- cutree(hc_iris, k = 3)
table(groups)

Predict new data

knnClust <- knn(train = df_iris$train[,-5], test = df_iris$test[,-5] , k = 1, cl = groups)
knnClust
 [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 3 2 3 3 3 2 2 2 2 2 3 3 2 2 3 2 2 2 2 2 2 2 2 2
Levels: 1 2 3

# p1 <- fviz_cluster(list(data = df_iris$train[,-5], cluster = groups), stand = F) + xlim(-11.2,-4.8) + ylim(-3,3) + ggtitle("train")
# p2 <- fviz_cluster(list(data = df_iris$test[,-5], cluster = knnClust),stand = F) + xlim(-11.2,-4.8) + ylim(-3,3) + ggtitle("test")
# gridExtra::grid.arrange(p1,p2,nrow = 2)

pca1 <- data.frame(prcomp(df_iris$train[,-5], scale. = T)$x[,1:2], cluster = as.factor(groups), factor = "train")
pca2 <- data.frame(prcomp(df_iris$test[,-5], scale. = T)$x[,1:2], cluster = as.factor(knnClust), factor = "test")
pca <- as.data.frame(rbind(pca1,pca2))

Plot train and test data

ggplot(pca, aes(x = PC1, y = PC2, color = cluster, size = 1, alpha = factor)) +
  geom_point(shape = 19) + theme_bw()


问:
How can I extract clusters from an igraph network?
I have a data.frame  which looks like this (there are 1135 rows) :

```<code>         var1   var2  corr
590   OTU3902 K00021 0.832
624   OTU2457 K00076 0.847
770   OTU0939 K00184 0.842
774   OTU0939 K00185 0.818
792   OTU3902 K00209 0.828
1053  OTU2859 K00299 0.803
1127  OTU0001 K00320 0.845
1128  OTU0041 K00320 0.819
1129  OTU1364 K00320 0.850
1130  OTU1891 K00320 0.803
1131  OTU2859 K00320 0.841
1137  OTU2457 K00329 0.845
1409  OTU0939 K00349 0.806
1465  OTU1531 K00366 0.840
1470  OTU1531 K00367 0.847
1474  OTU0001 K00368 0.840
1475  OTU0095 K00368 0.829
1544  OTU3041 K00395 0.820
1729  OTU0939 K00496 0.830
1750  OTU0735 K00508 0.835
</code>```

I use :

```<code>
g <- graph.data.frame(data, directed=FALSE)
plot(g)
</code>```

The network is well created. However, it creates some clusters and I would like to extract each cluster seperately. Is there an option with igraph to get different dataframes (or another kind of vector) : one dataframe will correspond to one cluster?

This is my network. It's a mess I guess, but you can see there are some sub-networks. So, I would like to isolate these sub-networks and get the components of each one in a list/data.frame if it is possible.

答:
It seems like you wish to find the isolated components of the graph. That can be done with components as in

```<code>components(g)
# $membership
# OTU3902 OTU2457 OTU0939 OTU2859 OTU0001 OTU0041 OTU1364 OTU1891 OTU1531 OTU0095 OTU3041 OTU0735
#       1       2       3       4       4       4       4       4       5       4       6       7
#  K00021  K00076  K00184  K00185  K00209  K00299  K00320  K00329  K00349  K00366  K00367  K00368
#       1       2       3       3       1       4       4       2       3       5       5       4
#  K00395  K00496  K00508
#       6       3       7
#
# $csize
# [1] 3 3 5 9 3 2 2
#
# $no
# [1] 7
</code>```

showing which vertex belongs to which components, sizes of those components, and the number of components.

Now as to just get a list of vertices by component, we may do

```<code>split(V(g), components(g)$membership)
# $`1`
# + 3/27 vertices, named, from 7eee8fa:
# [1] OTU3902 K00021  K00209
#
# $`2`
# + 3/27 vertices, named, from 7eee8fa:
# [1] OTU2457 K00076  K00329
# ...
</code>```

Or even cleaner,

```<code>split(names(V(g)), components(g)$membership)
# $`1`
# [1] "OTU3902" "K00021"  "K00209"
#
# $`2`
# [1] "OTU2457" "K00076"  "K00329"
#
# $`3`
# [1] "OTU0939" "K00184"  "K00185"  "K00349"  "K00496"
# ...
</code>```

Body:
I have a data.frame  which looks like this (there are 1135 rows) :

         var1   var2  corr
590   OTU3902 K00021 0.832
624   OTU2457 K00076 0.847
770   OTU0939 K00184 0.842
774   OTU0939 K00185 0.818
792   OTU3902 K00209 0.828
1053  OTU2859 K00299 0.803
1127  OTU0001 K00320 0.845
1128  OTU0041 K00320 0.819
1129  OTU1364 K00320 0.850
1130  OTU1891 K00320 0.803
1131  OTU2859 K00320 0.841
1137  OTU2457 K00329 0.845
1409  OTU0939 K00349 0.806
1465  OTU1531 K00366 0.840
1470  OTU1531 K00367 0.847
1474  OTU0001 K00368 0.840
1475  OTU0095 K00368 0.829
1544  OTU3041 K00395 0.820
1729  OTU0939 K00496 0.830
1750  OTU0735 K00508 0.835

I use :

g <- graph.data.frame(data, directed=FALSE)
plot(g)

The network is well created. However, it creates some clusters and I would like to extract each cluster seperately. Is there an option with igraph to get different dataframes (or another kind of vector) : one dataframe will correspond to one cluster?

This is my network. It's a mess I guess, but you can see there are some sub-networks. So, I would like to isolate these sub-networks and get the components of each one in a list/data.frame if it is possible.

Body:
It seems like you wish to find the isolated components of the graph. That can be done with components as in

components(g)
# $membership
# OTU3902 OTU2457 OTU0939 OTU2859 OTU0001 OTU0041 OTU1364 OTU1891 OTU1531 OTU0095 OTU3041 OTU0735
#       1       2       3       4       4       4       4       4       5       4       6       7
#  K00021  K00076  K00184  K00185  K00209  K00299  K00320  K00329  K00349  K00366  K00367  K00368
#       1       2       3       3       1       4       4       2       3       5       5       4
#  K00395  K00496  K00508
#       6       3       7
#
# $csize
# [1] 3 3 5 9 3 2 2
#
# $no
# [1] 7

showing which vertex belongs to which components, sizes of those components, and the number of components.

Now as to just get a list of vertices by component, we may do

split(V(g), components(g)$membership)
# $`1`
# + 3/27 vertices, named, from 7eee8fa:
# [1] OTU3902 K00021  K00209
#
# $`2`
# + 3/27 vertices, named, from 7eee8fa:
# [1] OTU2457 K00076  K00329
# ...

Or even cleaner,

split(names(V(g)), components(g)$membership)
# $`1`
# [1] "OTU3902" "K00021"  "K00209"
#
# $`2`
# [1] "OTU2457" "K00076"  "K00329"
#
# $`3`
# [1] "OTU0939" "K00184"  "K00185"  "K00349"  "K00496"
# ...