问:
How to get/find domain sid from machine sid
I can get machine Sid like below:

```<code>var dir = new DirectoryEntry($"WinNT://{Environment.MachineName},Computer");
var objSid = dir.Children.Cast<DirectoryEntry>().First().InvokeGet("objectSID");
var secId = new SecurityIdentifier((byte[])objSid, 0);
var machineSid = secId.AccountDomainSid.ToString();
</code>```

I tried to find computer Sid from machine Sid but it is always NULL.

```<code>using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "AbcDomain", "userName", "password"))
{
    var pc01 = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Sid, machineSid);
    //output: pc01 = null
    var pc02 = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Name, "PC-JACKML5291");
    //output: pc02...

}
</code>```

I want to check duplicate machine sid before calling JoinDomainOrWorkgroup.
Can I get the Computer SID (joined domain) from machine SID ?

答:
The machine SID is not the same as the SID of the computer object on the domain. They are different.

According to this article,

in order to assure uniqueness, the SID that Setup generates has one fixed subauthority value (21) and three randomly-generated subauthority values (the numbers following “S-1-5-21” in the output).

If you want the SID of the computer object on the domain, you will have to search for the object by the computer name.

Body:
I can get machine Sid like below:

var dir = new DirectoryEntry($"WinNT://{Environment.MachineName},Computer");
var objSid = dir.Children.Cast<DirectoryEntry>().First().InvokeGet("objectSID");
var secId = new SecurityIdentifier((byte[])objSid, 0);
var machineSid = secId.AccountDomainSid.ToString();

I tried to find computer Sid from machine Sid but it is always NULL.

using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "AbcDomain", "userName", "password"))
{
    var pc01 = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Sid, machineSid);
    //output: pc01 = null
    var pc02 = ComputerPrincipal.FindByIdentity(principalContext, IdentityType.Name, "PC-JACKML5291");
    //output: pc02...

}

I want to check duplicate machine sid before calling JoinDomainOrWorkgroup.
Can I get the Computer SID (joined domain) from machine SID ?


来源: stackexchange

问:
C# WinForm KeyPress Enter key not fire after link clicked
Here is simple code in windowsForm

```<code>    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
       MessageBox.Show("LOLOLO");
       if (e.KeyChar == 13)
       {
         panel3.Visible = true;
       }
    }
</code>```

And i have Panel control with link which close this panel

```<code>private void linkLabel2_Click(object sender, EventArgs e)
{
   panel3.Visible = false;
}
</code>```

I'ts work When i press any key it show me MessageBox but when i press ENTER my Panel is open.
Problem is when i mouse clicked linkLabel2 to close Panel, any keys fire keyPress event, except ENTER key. When i press ENTER nothing to do, keyPress event not fire

How to fix it?

答:
First of all you have to enable key Form.KeyPreview Property in form1.

At the end, when you click linkLabel2, it got focus and stay there. You have to leave focus. I've added and event to leave focus from linkLable2, just when you press Enter, it does not call linkLabel2 again. If it works, please mark as read and vote up. Thanks

```<code>private void linkLabel2_Leave(object sender, EventArgs e)
        {

        }

private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            panel3.Visible = false;

            linkLabel2_Leave(linkLabel2, null);
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is simple code in windowsForm

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
       MessageBox.Show("LOLOLO");
       if (e.KeyChar == 13)
       {
         panel3.Visible = true;
       }
    }

And i have Panel control with link which close this panel

private void linkLabel2_Click(object sender, EventArgs e)
{
   panel3.Visible = false;
}

I'ts work When i press any key it show me MessageBox but when i press ENTER my Panel is open.
Problem is when i mouse clicked linkLabel2 to close Panel, any keys fire keyPress event, except ENTER key. When i press ENTER nothing to do, keyPress event not fire

How to fix it?

Body:
First of all you have to enable key Form.KeyPreview Property in form1.

At the end, when you click linkLabel2, it got focus and stay there. You have to leave focus. I've added and event to leave focus from linkLable2, just when you press Enter, it does not call linkLabel2 again. If it works, please mark as read and vote up. Thanks

private void linkLabel2_Leave(object sender, EventArgs e)
        {

        }

private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            panel3.Visible = false;

            linkLabel2_Leave(linkLabel2, null);
        }


问:
Uncaught Error: Packager is not running at http://192.168.0.100.19001
I ran an app in a normal way in React-Native (EXPO):

expo init Myproject

cd Myproject

start of wire

However, next to running the app, the following message appears:

_ Something went wrong. (I.e.
_ ** The marshaler is not running at http: //192.168.100.19001**_

What do I do?

答: I found that this error message could arise for a very simple reason, make sure your smartphone running Expo is connected to the same subnetwork as your computer on which your dev server is running.</p>


问:
Add text to the shape in center
I have created a view that looks like this :

I want to add a text label to each segment in the view such that it aligns in the center. Each of the segment is a customized button that also responds when in the layer specified. When I try to do button.setTitle, since the frame for the button is different, it doesn't align with the shape layer. Can anyone advise as to how to achieve the same.

I tried creating another function and calling it while creating the shape and the buttons.

```<code>func addText(_ stringValue: String, to shapeLayer: CAShapeLayer) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let textlayer = CATextLayer()
            if let rect = shapeLayer.path?.boundingBox {
//                print(rect)
                textlayer.frame = CGRect(x: rect.origin.x + rect.size.width/2, y:rect.origin.y + rect.size.height/2, width: 20, height: 20)
                textlayer.fontSize = 12
                textlayer.alignmentMode = .center
                textlayer.string = stringValue
                textlayer.backgroundColor = UIColor.clear.cgColor
                textlayer.foregroundColor = UIColor.black.cgColor
                shapeLayer.addSublayer(textlayer)
            }
        }
    }
</code>```

But this doesn't work as the text is getting overlapped to the layer. Can anyone suggest a way to achieve the same?

EDIT :

Each segment has text, I just added a few of them to give an idea.

EDIT 2 :

The code to create the view :

```<code>        for segment in outerSegments {
            let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
            let shape = CAShapeLayer()
            let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: viewCenter)
            path.close()
            shape.path = path.cgPath
            shape.fillColor = segment.color.cgColor
            shape.strokeColor = UIColor.black.cgColor
            shape.borderWidth = 1.0
            shape.borderColor = UIColor.black.cgColor
            shape.name = "\(i)"
            datamap[shape.name ?? ""] = data[i]
            let label = CATextLayer()

            //addText(data[i], to: shape)
            let b = MyButton(type: .custom)
            b.path = path
            b.backgroundColor = UIColor.clear
            b.tag = Int(data[i].asciiValues[0])
            b.backgroundColor = UIColor.clear
            self.layer.addSublayer(shape)
            let frameRect = shape.bounds
            b.frame = frameRect
            let sine = sin(startAngle)
            let cosine = cos(startAngle)
            print("\(sine)  \(data[i])")
            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInside)
            self.addSubview(b)
            self.bringSubviewToFront(b)
            self.isUserInteractionEnabled = true
            //layer.addSublayer(shape)
            startAngle = endAngle
            i += 1
        }
        valueCount = innerSegments.reduce(0, {$0 + $1.value})
        startAngle = 0
        i = 100
        for segment in innerSegments {
            let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
            let shape = CAShapeLayer()
            let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: 2*radius/3, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: viewCenter)
            path.close()
            shape.path = path.cgPath
            shape.strokeColor = UIColor.black.cgColor
            shape.fillColor = segment.color.cgColor
            shape.borderWidth = 1.0
            shape.borderColor = UIColor.black.cgColor
            shape.name = "\(i)"
            datamap[shape.name ?? ""] = data[i-100]
            addText(data[i-100], to: shape)
            let b = MyButton(type: .custom)
            b.path = path
            b.backgroundColor = UIColor.clear
            self.layer.addSublayer(shape)
            let frameRect = shape.bounds
            b.frame = frameRect
            b.tag = Int(data[i-100].asciiValues[0])

            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInside)
            self.addSubview(b)
            self.bringSubviewToFront(b)

            self.isUserInteractionEnabled = true
            //layer.addSublayer(shape)
            startAngle = endAngle
            i += 1
        }
        valueCount = innerMostSegments.reduce(0, {$0 + $1.value})
        startAngle = 0
        i = 1000
        for segment in innerMostSegments {
            let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
            let shape = CAShapeLayer()
            let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: radius/3, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: viewCenter)
            path.close()
            shape.path = path.cgPath
            shape.fillColor = segment.color.cgColor
            shape.strokeColor = UIColor.black.cgColor
            shape.borderWidth = 1.0
            shape.borderColor = UIColor.black.cgColor
            shape.name = "\(i)"
            datamap[shape.name ?? ""] = data[i-1000]
            addText(data[i-1000], to: shape)
            let b = MyButton(type: .custom)
            b.path = path
            b.backgroundColor = UIColor.clear
            self.layer.addSublayer(shape)
            let frameRect = shape.bounds
            b.frame = frameRect
            b.tag = Int(data[i-1000].asciiValues[0])
            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInsid)
            self.addSubview(b)
            self.bringSubviewToFront(b)
            self.isUserInteractionEnabled = true
            startAngle = endAngle
            i += 1
        }
    }
</code>```

答:
Presumably, you are using math to calculate the "spokes" and "arcs"?

For each segment, you probably need to bisect the angles that make up the sides (the yellow line), then calculate a point (the red dot) along that line midway between the arcs:

That point becomes the center of the label's frame.

Title: Add text to the shape in center

Body:
I have created a view that looks like this :

I want to add a text label to each segment in the view such that it aligns in the center. Each of the segment is a customized button that also responds when in the layer specified. When I try to do button.setTitle, since the frame for the button is different, it doesn't align with the shape layer. Can anyone advise as to how to achieve the same.

I tried creating another function and calling it while creating the shape and the buttons.

func addText(_ stringValue: String, to shapeLayer: CAShapeLayer) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            let textlayer = CATextLayer()
            if let rect = shapeLayer.path?.boundingBox {
//                print(rect)
                textlayer.frame = CGRect(x: rect.origin.x + rect.size.width/2, y:rect.origin.y + rect.size.height/2, width: 20, height: 20)
                textlayer.fontSize = 12
                textlayer.alignmentMode = .center
                textlayer.string = stringValue
                textlayer.backgroundColor = UIColor.clear.cgColor
                textlayer.foregroundColor = UIColor.black.cgColor
                shapeLayer.addSublayer(textlayer)
            }
        }
    }

But this doesn't work as the text is getting overlapped to the layer. Can anyone suggest a way to achieve the same?

EDIT :

Each segment has text, I just added a few of them to give an idea.

EDIT 2 :

The code to create the view :

        for segment in outerSegments {
            let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
            let shape = CAShapeLayer()
            let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: viewCenter)
            path.close()
            shape.path = path.cgPath
            shape.fillColor = segment.color.cgColor
            shape.strokeColor = UIColor.black.cgColor
            shape.borderWidth = 1.0
            shape.borderColor = UIColor.black.cgColor
            shape.name = "\(i)"
            datamap[shape.name ?? ""] = data[i]
            let label = CATextLayer()

            //addText(data[i], to: shape)
            let b = MyButton(type: .custom)
            b.path = path
            b.backgroundColor = UIColor.clear
            b.tag = Int(data[i].asciiValues[0])
            b.backgroundColor = UIColor.clear
            self.layer.addSublayer(shape)
            let frameRect = shape.bounds
            b.frame = frameRect
            let sine = sin(startAngle)
            let cosine = cos(startAngle)
            print("\(sine)  \(data[i])")
            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInside)
            self.addSubview(b)
            self.bringSubviewToFront(b)
            self.isUserInteractionEnabled = true
            //layer.addSublayer(shape)
            startAngle = endAngle
            i += 1
        }
        valueCount = innerSegments.reduce(0, {$0 + $1.value})
        startAngle = 0
        i = 100
        for segment in innerSegments {
            let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
            let shape = CAShapeLayer()
            let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: 2*radius/3, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: viewCenter)
            path.close()
            shape.path = path.cgPath
            shape.strokeColor = UIColor.black.cgColor
            shape.fillColor = segment.color.cgColor
            shape.borderWidth = 1.0
            shape.borderColor = UIColor.black.cgColor
            shape.name = "\(i)"
            datamap[shape.name ?? ""] = data[i-100]
            addText(data[i-100], to: shape)
            let b = MyButton(type: .custom)
            b.path = path
            b.backgroundColor = UIColor.clear
            self.layer.addSublayer(shape)
            let frameRect = shape.bounds
            b.frame = frameRect
            b.tag = Int(data[i-100].asciiValues[0])

            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInside)
            self.addSubview(b)
            self.bringSubviewToFront(b)

            self.isUserInteractionEnabled = true
            //layer.addSublayer(shape)
            startAngle = endAngle
            i += 1
        }
        valueCount = innerMostSegments.reduce(0, {$0 + $1.value})
        startAngle = 0
        i = 1000
        for segment in innerMostSegments {
            let endAngle = startAngle + 2 * .pi * (segment.value / valueCount)
            let shape = CAShapeLayer()
            let path: UIBezierPath = UIBezierPath(arcCenter: viewCenter, radius: radius/3, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: viewCenter)
            path.close()
            shape.path = path.cgPath
            shape.fillColor = segment.color.cgColor
            shape.strokeColor = UIColor.black.cgColor
            shape.borderWidth = 1.0
            shape.borderColor = UIColor.black.cgColor
            shape.name = "\(i)"
            datamap[shape.name ?? ""] = data[i-1000]
            addText(data[i-1000], to: shape)
            let b = MyButton(type: .custom)
            b.path = path
            b.backgroundColor = UIColor.clear
            self.layer.addSublayer(shape)
            let frameRect = shape.bounds
            b.frame = frameRect
            b.tag = Int(data[i-1000].asciiValues[0])
            b.addTarget(self, action: #selector(ButtonClicked(_:)), for: .touchUpInsid)
            self.addSubview(b)
            self.bringSubviewToFront(b)
            self.isUserInteractionEnabled = true
            startAngle = endAngle
            i += 1
        }
    }


问:
How do I combine information from multiple rows (concatrelated) without getting duplicate values in my report?
I have created a database that has these tables:

Student list

Student booklet numbers

Student needs

Teacher Information

In the Student Needs Table I have information entered similar to this:

```<code>Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary
123456             Mouse      Mickey      Extra Time
123456             Mouse      Mickey      Small group
123456             Mouse      Mickey      Type Answer Choices
654321             Duck       Daffy       Dictionary
654321             Duck       Daffy       Thesaurus
654321             Duck       Daffy       Small Group
</code>```

I need this to be pulled similar to this:

```<code>Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
</code>```

I used the concatrelated function in my report control source and it works to put all of the needs together, but because my query has the student listed multiple times, it is listing the student multiple times on the report.  Like this:

```<code>Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
</code>```

I have tried all that I can think of to fix this - to the point of exporting the report and deleting duplicates - but then the export cuts off at 255 characters- so that doesn't work.  Surely I am missing something that would be relatively easy- but I can't figure it out!

答:
I created a module called "Get List From Table Field" and in it I have the following code:

```<code>Public Function GetList(sTable As String, sField As String, Optional sWhere As String, Optional sDelimiter As String, Optional UniqueValues As Boolean) As String
'   compiles all the data from a single field in a table and returns them in a string.
'   has options for providing a sql crieria, a delimiter, and if unique values should be returned
    Dim rs As Recordset
    Dim sList As String
    Dim sChar As String

    If sDelimiter = "" Then
        sChar = ","
    Else
        sChar = sDelimiter
    End If
    Set rs = CurrentDb.OpenRecordset("Select " & IIf(UniqueValues, "Distinct ", "") & sField & " From " & sTable & IIf(sWhere <> "", " Where " & sWhere, ""))
    Do While Not rs.EOF
        sList = sList & sChar & rs.Fields(sField)
        rs.MoveNext
    Loop
    rs.Close
    Set rs = Nothing

    sList = Mid(sList, 2) & sChar
    GetList = sList

End Function
</code>```

In your select query, you can try:

```<code>SELECT [Student ID], [Last Name], [First Name],
GetList("[Student Needs]","[Reading Special Need]","[Student ID] = " & [Student ID]) AS [Reading Special Needs]
FROM [Student Needs]
GROUP BY [Student ID], [Last Name], [First Name];
</code>```

I also recommend that you use underscores or CamelCase instead of spaces on all your table and field names. That way you can avoid using brackets in your statements.  It's a better programming habit to get into.  For instance:

Underscore SELECT Student_ID, Last_Name, First_Name FROM Student_Needs

CamelCase SELECT StudentID, LastName, FirstName FROM StudentNeeds

Body:
I have created a database that has these tables:

Student list

Student booklet numbers

Student needs

Teacher Information

In the Student Needs Table I have information entered similar to this:

Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary
123456             Mouse      Mickey      Extra Time
123456             Mouse      Mickey      Small group
123456             Mouse      Mickey      Type Answer Choices
654321             Duck       Daffy       Dictionary
654321             Duck       Daffy       Thesaurus
654321             Duck       Daffy       Small Group

I need this to be pulled similar to this:

Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group

I used the concatrelated function in my report control source and it works to put all of the needs together, but because my query has the student listed multiple times, it is listing the student multiple times on the report.  Like this:

Student ID Column, Last Name, First Name, Reading Special Need

123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
123456             Mouse      Mickey      Dictionary, Extra time, Small group, type answer choices
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group
654321             Duck       Daffy       Dictionary, Thesaurus, Small Group

I have tried all that I can think of to fix this - to the point of exporting the report and deleting duplicates - but then the export cuts off at 255 characters- so that doesn't work.  Surely I am missing something that would be relatively easy- but I can't figure it out!

Body:
I created a module called "Get List From Table Field" and in it I have the following code:

Public Function GetList(sTable As String, sField As String, Optional sWhere As String, Optional sDelimiter As String, Optional UniqueValues As Boolean) As String
'   compiles all the data from a single field in a table and returns them in a string.
'   has options for providing a sql crieria, a delimiter, and if unique values should be returned
    Dim rs As Recordset
    Dim sList As String
    Dim sChar As String

    If sDelimiter = "" Then
        sChar = ","
    Else
        sChar = sDelimiter
    End If
    Set rs = CurrentDb.OpenRecordset("Select " & IIf(UniqueValues, "Distinct ", "") & sField & " From " & sTable & IIf(sWhere <> "", " Where " & sWhere, ""))
    Do While Not rs.EOF
        sList = sList & sChar & rs.Fields(sField)
        rs.MoveNext
    Loop
    rs.Close
    Set rs = Nothing

    sList = Mid(sList, 2) & sChar
    GetList = sList

End Function

In your select query, you can try:

SELECT [Student ID], [Last Name], [First Name],
GetList("[Student Needs]","[Reading Special Need]","[Student ID] = " & [Student ID]) AS [Reading Special Needs]
FROM [Student Needs]
GROUP BY [Student ID], [Last Name], [First Name];

I also recommend that you use underscores or CamelCase instead of spaces on all your table and field names. That way you can avoid using brackets in your statements.  It's a better programming habit to get into.  For instance:

Underscore SELECT Student_ID, Last_Name, First_Name FROM Student_Needs

CamelCase SELECT StudentID, LastName, FirstName FROM StudentNeeds


问:
add woocommerce optgroup selected value to email order an admin order
I read a few articles on the optgroup which is what i need, i manage to display it on the checkout page, but i need the selected option to be visible on email and the admin area where we view the order details.

Code comes from: "WooCommerce Select Dropdown With Optgroup On Checkout"

What I need: I'm creating a website where I need to add manually a few areas on the checkout page so the user can select his area so I can use it as validation and a way to limit the shipping, once the select area I need to be able to see this on the email order as well on the order that on Woocommerce zones doesn't fit in my case:

```<code>    <?php
  add_action('woocommerce_before_order_notes', 'custom_checkout_select_field_with_optgroup', 10, 1 );
function custom_checkout_select_field_with_optgroup( $checkout ) {

$domain  = 'woocommerce';
$title   = __("zona", $domain);
$slug    = zone_limit;
$default = __("Selecione su Zona", $domain);
$value   = $checkout->get_value($slug);

// Region option data array with optgroup
$options = array(
    __("North zone", $domain) => array(
        'region1' => __("Region 1", $domain),
        'region2' => __("Region 2", $domain),
    ),
    __("South zone", $domain) => array(
        'region3' => __("Region 3", $domain),
        'region4' => __("Region 4", $domain),
    )
      __("Middle zone", $domain) => array(
        'region3' => __("Region 5", $domain),
        'region4' => __("Region 6", $domain),
    )
);

// The field
echo '<p class="form-row form-row-wide '.$slug.'-dropdown" id="'.$slug.'_field" data-priority="">
<label for="'.$slug.'" class="">'.$title.'</label>
<span class="woocommerce-input-wrapper">
<select name="'.$slug.'" id="'.$slug.'" class="select " data-placeholder="" autocomplete="'.$slug.'">
<option value="">'.$default.'</option>';

// Loop through "optgroup"
foreach( $options as $optgroup_label => $optgroup_options ) {
    echo '<optgroup label="'.$optgroup_label.'">';
    // Loop through "options" in the "optgroup"
    foreach( $optgroup_options as $key => $label ) {
        $selected = $value === $key ? ' selected="selected"': '';
        echo '<option value="'.$key.'"'.$selected.'>'.$label.'</option>';
    }
    echo '</optgroup>';
}

echo '</select></span></p>';

}
</code>```

I've tried this but not lucky

```<code>add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

 function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
$fields['meta_key'] = array(
    'label' => __( 'Label' ),
    'value' => get_post_meta( $order->id, 'meta_key', true ),
);
return $fields;
 }

  add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');

     function my_custom_order_meta_keys( $keys ) {

    $keys[] = $value ; // This will look for a custom field called 'Tracking Code' and add it to emails
 return $keys;
}

add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

 function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST[$value ] ) ) {
    update_post_meta( $order_id, 'region', sanitize_text_field( $_POST[$value ] ) );
}

}
</code>```

答:
I hope i don't be penalized for this, my initial question was adding the selected value to the email order and use the optgroup collapse effect, however i was told the question was to broad, so i removed the jquery tag and effect and limit my self just the the php and getting it on the email order.

the php was fine i just couln'd get it on the email plus i needed the optgroup.

I did something else, i just used jquery instead of full php only, i created text type field and get it to send answer to email, then i created a modal manually(not wanted to use bootstrap) then a regular html for the optgroup and use jquery get the selected value and insert into the text field. here is my code.

The html is a basic that you can find  here

And the css you can use this as example then bot css and html will need to be modify as you need

The php

```<code>add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );

 function my_custom_checkout_field( $checkout ) {

echo '<div id="myZoneLimit"><h2>' . __('valida tu zona') . '</h2>';

 woocommerce_form_field( 'my_field_limit', array(
    'type'          => 'text',
    'class'         => array('my-field-class form-row-wide'),
    'label'         => __('Fill in this field'),
    'placeholder'   => __('Enter something'),
    ), $checkout->get_value( 'my_field_limit' ));

echo '</div>';

  }

  add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

   function my_custom_checkout_field_process() {
  // Check if set, if its not set add an error.
   if ( ! $_POST['my_field_limit'] )

    wc_add_notice( __( 'Por favor seleccione su zona de envio.' ), 'error' );
   }

  add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');

   function my_custom_order_meta_keys( $keys ) {
 $keys[] = 'valida tu zona'; // This will look for a custom field called 'Tracking Code' and add it to emails
 return $keys;
    }

     add_action( 'woocommerce_checkout_update_order_meta',
   'my_custom_checkout_field_update_order_meta' );

  function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['my_field_limit'] ) ) {
    update_post_meta( $order_id, 'valida tu zona', sanitize_text_field( $_POST['my_field_limit'] ) );
}
     }

 add_action( 'woocommerce_admin_order_data_after_billing_address','my_custom_checkout_field_display_admin_order_meta', 10, 1 );

      function my_custom_checkout_field_display_admin_order_meta($order){
      echo '<p><strong>'.__('valida tu zona').':</strong> ' . get_post_meta( $order->id, 'valida tu zona', true ) . '</p>';
</code>```

My jquery

```<code>    /// button that opens the modal that was created the html
  $("#my_field_limit").click(function(){
   $("#myModalarea").show();
    });

       //// get the value from the selected option and place in into the the text field
       $('#coveredareas').change(function(){
        var areazone = $(this).val();
        $("#my_field_limit").val(areazone);
</code>```

Body:
I read a few articles on the optgroup which is what i need, i manage to display it on the checkout page, but i need the selected option to be visible on email and the admin area where we view the order details.

Code comes from: "WooCommerce Select Dropdown With Optgroup On Checkout"

What I need: I'm creating a website where I need to add manually a few areas on the checkout page so the user can select his area so I can use it as validation and a way to limit the shipping, once the select area I need to be able to see this on the email order as well on the order that on Woocommerce zones doesn't fit in my case:

    <?php
  add_action('woocommerce_before_order_notes', 'custom_checkout_select_field_with_optgroup', 10, 1 );
function custom_checkout_select_field_with_optgroup( $checkout ) {

$domain  = 'woocommerce';
$title   = __("zona", $domain);
$slug    = zone_limit;
$default = __("Selecione su Zona", $domain);
$value   = $checkout->get_value($slug);

// Region option data array with optgroup
$options = array(
    __("North zone", $domain) => array(
        'region1' => __("Region 1", $domain),
        'region2' => __("Region 2", $domain),
    ),
    __("South zone", $domain) => array(
        'region3' => __("Region 3", $domain),
        'region4' => __("Region 4", $domain),
    )
      __("Middle zone", $domain) => array(
        'region3' => __("Region 5", $domain),
        'region4' => __("Region 6", $domain),
    )
);

// The field
echo '

'.$title.'

<select name="'.$slug.'" id="'.$slug.'" class="select " data-placeholder="" autocomplete="'.$slug.'">
<option value="">'.$default.'</option>';

// Loop through "optgroup"
foreach( $options as $optgroup_label => $optgroup_options ) {
    echo '<optgroup label="'.$optgroup_label.'">';
    // Loop through "options" in the "optgroup"
    foreach( $optgroup_options as $key => $label ) {
        $selected = $value === $key ? ' selected="selected"': '';
        echo '<option value="'.$key.'"'.$selected.'>'.$label.'</option>';
    }
    echo '</optgroup>';
}

echo '</select>
';

}

I've tried this but not lucky

add_filter( 'woocommerce_email_order_meta_fields', 'custom_woocommerce_email_order_meta_fields', 10, 3 );

 function custom_woocommerce_email_order_meta_fields( $fields, $sent_to_admin, $order ) {
$fields['meta_key'] = array(
    'label' => __( 'Label' ),
    'value' => get_post_meta( $order->id, 'meta_key', true ),
);
return $fields;
 }

  add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');

     function my_custom_order_meta_keys( $keys ) {

    $keys[] = $value ; // This will look for a custom field called 'Tracking Code' and add it to emails
 return $keys;
}

add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

 function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST[$value ] ) ) {
    update_post_meta( $order_id, 'region', sanitize_text_field( $_POST[$value ] ) );
}

}

Body:
I hope i don't be penalized for this, my initial question was adding the selected value to the email order and use the optgroup collapse effect, however i was told the question was to broad, so i removed the jquery tag and effect and limit my self just the the php and getting it on the email order.

the php was fine i just couln'd get it on the email plus i needed the optgroup.

I did something else, i just used jquery instead of full php only, i created text type field and get it to send answer to email, then i created a modal manually(not wanted to use bootstrap) then a regular html for the optgroup and use jquery get the selected value and insert into the text field. here is my code.

The html is a basic that you can find  here

And the css you can use this as example then bot css and html will need to be modify as you need

The php

add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );

 function my_custom_checkout_field( $checkout ) {

echo '<div id="myZoneLimit"><h2>' . __('valida tu zona') . '</h2>';

 woocommerce_form_field( 'my_field_limit', array(
    'type'          => 'text',
    'class'         => array('my-field-class form-row-wide'),
    'label'         => __('Fill in this field'),
    'placeholder'   => __('Enter something'),
    ), $checkout->get_value( 'my_field_limit' ));

echo '</div>';

  }

  add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

   function my_custom_checkout_field_process() {
  // Check if set, if its not set add an error.
   if ( ! $_POST['my_field_limit'] )

    wc_add_notice( __( 'Por favor seleccione su zona de envio.' ), 'error' );
   }

  add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');

   function my_custom_order_meta_keys( $keys ) {
 $keys[] = 'valida tu zona'; // This will look for a custom field called 'Tracking Code' and add it to emails
 return $keys;
    }

     add_action( 'woocommerce_checkout_update_order_meta',
   'my_custom_checkout_field_update_order_meta' );

  function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['my_field_limit'] ) ) {
    update_post_meta( $order_id, 'valida tu zona', sanitize_text_field( $_POST['my_field_limit'] ) );
}
     }

 add_action( 'woocommerce_admin_order_data_after_billing_address','my_custom_checkout_field_display_admin_order_meta', 10, 1 );

      function my_custom_checkout_field_display_admin_order_meta($order){
      echo '<p><strong>'.__('valida tu zona').':</strong> ' . get_post_meta( $order->id, 'valida tu zona', true ) . '</p>';

My jquery

    /// button that opens the modal that was created the html
  $("#my_field_limit").click(function(){
   $("#myModalarea").show();
    });

       //// get the value from the selected option and place in into the the text field
       $('#coveredareas').change(function(){
        var areazone = $(this).val();
        $("#my_field_limit").val(areazone);


问:
Extract Numeric and Special Characters Separately
I have column in a table with values stored as

```<code>Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05
</code>```

Now, I need to store these values to another table like

```<code>Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05
</code>```

Plz let me the Query how to do this....

答:
```<code>insert DestinationTable(Cost, Currency)
select
    case when delimiterIndex > 0 then left(Cost, delimiterIndex) else 'RS' end as Currency,
    right(Cost, len(Cost) - delimiterIndex) as Cost
from
(
    select charindex(' ', Cost) delimiterIndex, *
    from SourceTable
) tt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have column in a table with values stored as

Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05

Now, I need to store these values to another table like

Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05

Plz let me the Query how to do this....


问:
MS Access multiple filter in the same field satisfying all of them
I am fairly new to access. I have a table similar to the following
enter image description here
I am trying to create a query that shows suppliers that are capable of BOTH Grinding and Milling.
This the outcome I am Hopping to get

```<code>A    Grinding
A    Milling
B    Grinding
B    Milling
</code>```

and Ignore the rest. Any help?

答:
If you want all the columns returned you can use EXISTS:

```<code>select t.*
from tablename as t
where exists (
  select 1 from tablename
  where supplier = t.supplier and capability <> t.capability
)
</code>```

or:

```<code>select * from tablename
where supplier in (
  select supplier from tablename
  group by supplier
  having count(*) = 2
)
</code>```

Body:
I am fairly new to access. I have a table similar to the following
enter image description here
I am trying to create a query that shows suppliers that are capable of BOTH Grinding and Milling.
This the outcome I am Hopping to get

A    Grinding
A    Milling
B    Grinding
B    Milling

and Ignore the rest. Any help?

Body:
If you want all the columns returned you can use EXISTS:

select t.*
from tablename as t
where exists (
  select 1 from tablename
  where supplier = t.supplier and capability <> t.capability
)

or:

select * from tablename
where supplier in (
  select supplier from tablename
  group by supplier
  having count(*) = 2
)


问:
Adding Lottie Animation in iOS
I'm new to Lottie library and trying to integrate a simple animation. I have my animated json at folder Resources->Json->LottieAnimations->checkMark.json

I have installed Lottie via pod install and its current version is 3.1.0.
In my storyboard I have added a view and gave the class name as AnimationView and in the interface builder gave the Animation Name as "checkMark".

This is the outlet

```<code>@IBOutlet weak var checkMarkAnimationView: AnimationView!
</code>```

And on viewDidLoad I just call

```<code>checkMarkAnimationView.play()
</code>```

But nothing happens here. Am I missing something?

答:
```<code>let animationSubView = AnimationView(name: "jsonAnimationFileName")
animationSubView.frame = self.checkMarkAnimationView.bounds
animationSubView.contentMode = .scaleAspectFit

self.checkMarkAnimationView.addSubview(animationSubView)
animationSubView.play()
</code>```

Add this to viewDidLoad()

Title: Adding Lottie Animation in iOS

Body:
I'm new to Lottie library and trying to integrate a simple animation. I have my animated json at folder Resources->Json->LottieAnimations->checkMark.json

I have installed Lottie via pod install and its current version is 3.1.0.
In my storyboard I have added a view and gave the class name as AnimationView and in the interface builder gave the Animation Name as "checkMark".

This is the outlet

@IBOutlet weak var checkMarkAnimationView: AnimationView!

And on viewDidLoad I just call

checkMarkAnimationView.play()

But nothing happens here. Am I missing something?

Body:
let animationSubView = AnimationView(name: "jsonAnimationFileName")
animationSubView.frame = self.checkMarkAnimationView.bounds
animationSubView.contentMode = .scaleAspectFit

self.checkMarkAnimationView.addSubview(animationSubView)
animationSubView.play()

Add this to viewDidLoad()


问:
Find next / previous number in mysql table
Given this table:

```<code>contractnumber | itemnumber
1234           | 100151
1234           | 100152
1235           | 100127
1235           | 100128
1236           | 100001
1236           | 100002
</code>```

How can I get the next (or previous) itemnumber from the table after a given itemnumber with the table order is contractnumber ASC, itemnumber ASC?

For example I'd like to get the next itemnumber after 100128 (100128) or the previous itemnumber to 100001 (100128).

答:
In MySQL 5.x you cannot use LEAD() or LAG(). However, you can order the rows and limit the result set to 1 row. See below

For the next element of 100128 you can use:

```<code>select *
from t
where (contractnumber, itemnumber) > (
  select contractnumber, itemnumber from t where itemnumber = 100128
)
order by contractnumber, itemnumber
limit 1;
</code>```

Result:

```<code>contractnumber  itemnumber
--------------  ----------
          1236      100001
</code>```

For the previous element of 100128 you can use:

```<code>select *
from t
where (contractnumber, itemnumber) < (
  select contractnumber, itemnumber from t where itemnumber = 100128
)
order by contractnumber desc, itemnumber desc
limit 1;
</code>```

Result:

```<code>contractnumber  itemnumber
--------------  ----------
          1235      100127
</code>```

See running example at DB Fiddle.

Body:
Given this table:

contractnumber | itemnumber
1234           | 100151
1234           | 100152
1235           | 100127
1235           | 100128
1236           | 100001
1236           | 100002

How can I get the next (or previous) itemnumber from the table after a given itemnumber with the table order is contractnumber ASC, itemnumber ASC?

For example I'd like to get the next itemnumber after 100128 (100128) or the previous itemnumber to 100001 (100128).

Body:
In MySQL 5.x you cannot use LEAD() or LAG(). However, you can order the rows and limit the result set to 1 row. See below

For the next element of 100128 you can use:

select *
from t
where (contractnumber, itemnumber) > (
  select contractnumber, itemnumber from t where itemnumber = 100128
)
order by contractnumber, itemnumber
limit 1;

Result:

contractnumber  itemnumber
--------------  ----------
          1236      100001

For the previous element of 100128 you can use:

select *
from t
where (contractnumber, itemnumber) < (
  select contractnumber, itemnumber from t where itemnumber = 100128
)
order by contractnumber desc, itemnumber desc
limit 1;

Result:

contractnumber  itemnumber
--------------  ----------
          1235      100127

See running example at DB Fiddle.


问:
why custom allocator for std::string does not work
I define a new allocator like this:

```<code>template <class T>
class CodecAlloc: public std::allocator<T> {
public:
  typedef size_t    size_type;
  typedef ptrdiff_t difference_type;
  typedef T*        pointer;
  typedef const T*  const_pointer;
  typedef T&        reference;
  typedef const T&  const_reference;
  typedef T         value_type;

  CodecAlloc() {}
  CodecAlloc(const CodecAlloc&) {}

  pointer allocate(size_type n, const void * = 0) {
              T* t = (T*) malloc(n * sizeof(T));
              std::cout
              << "  used CodecAlloc to allocate   at address "
              << t << " (+)" << std::endl;
              return t;
            }

  void deallocate(void* p, size_type) {
              if (p) {
                free(p);
                std::cout
                << "  used CodecAlloc to deallocate at address "
                << p << " (-)" <<
                std::endl;
              }
            }

  template <class U>
  struct rebind { typedef CodecAlloc<U> other; };
};
</code>```

if I typedef a new type:

```<code>typedef std::basic_string<char, std::char_traits<char>, CodecAlloc<char>> String;
</code>```

it work well，CodecAlloc::allocate has been called.  but now there is a interface like this:

```<code>void SetBinary(const std::string&)
</code>```

it's parameter is a std::string, the type String does not match. So I use this way to construct std::string

```<code>std::string str = std::string("Hello !!", CodecAlloc<char>);
SetBinary(str)
</code>```

but the CodecAlloc allocator does not been called!! why? and how should i solve this problem. the SetBinary interface can not be changed. thks

答:
```<code>std::string str = std::string("Hello !!", CodecAlloc<char>);
</code>```

Assuming that you actually created a temporary like CodecAlloc<char>() (because otherwise it wouldn't compile) what happens is that you call the constructor taking a const std::allocator<char>& (because that's what std::string::allocator_type is) and your object has that as a base class. So the reference binds to the base subobject of your CodecAlloc<char> temporary, and then that base subobject gets copied into the string's internal allocator object.

You can't make std::string use a different allocator type just by passing it to the constructor, the allocator type is a static property of the string.

Body:
I define a new allocator like this:

template <class T>
class CodecAlloc: public std::allocator<T> {
public:
  typedef size_t    size_type;
  typedef ptrdiff_t difference_type;
  typedef T*        pointer;
  typedef const T*  const_pointer;
  typedef T&        reference;
  typedef const T&  const_reference;
  typedef T         value_type;

  CodecAlloc() {}
  CodecAlloc(const CodecAlloc&) {}

  pointer allocate(size_type n, const void * = 0) {
              T* t = (T*) malloc(n * sizeof(T));
              std::cout
              << "  used CodecAlloc to allocate   at address "
              << t << " (+)" << std::endl;
              return t;
            }

  void deallocate(void* p, size_type) {
              if (p) {
                free(p);
                std::cout
                << "  used CodecAlloc to deallocate at address "
                << p << " (-)" <<
                std::endl;
              }
            }

  template <class U>
  struct rebind { typedef CodecAlloc other; };
};

if I typedef a new type:

typedef std::basic_string<char, std::char_traits<char>, CodecAlloc<char>> String;

it work well，CodecAlloc::allocate has been called.  but now there is a interface like this:

void SetBinary(const std::string&)

it's parameter is a std::string, the type String does not match. So I use this way to construct std::string

std::string str = std::string("Hello !!", CodecAlloc<char>);
SetBinary(str)

but the CodecAlloc allocator does not been called!! why? and how should i solve this problem. the SetBinary interface can not be changed. thks

Body:
std::string str = std::string("Hello !!", CodecAlloc<char>);

Assuming that you actually created a temporary like CodecAlloc<char>() (because otherwise it wouldn't compile) what happens is that you call the constructor taking a const std::allocator<char>& (because that's what std::string::allocator_type is) and your object has that as a base class. So the reference binds to the base subobject of your CodecAlloc<char> temporary, and then that base subobject gets copied into the string's internal allocator object.

You can't make std::string use a different allocator type just by passing it to the constructor, the allocator type is a static property of the string.


问:
WTForms Regexp validator: How to match white space within html tags using regex
I have a form with a textarea field and wonder if I could use WTForms Regexp validator to prevent the form submitting when the textarea contains only blank spaces.
Is there a way?

This is my form:

```<code>class AddReviewForm(FlaskForm):
    review = TextAreaField("Review", validators=[DataRequired())
    submit = SubmitField("Post Review")
</code>```

I was hoping Regexp would allow me to prevent only spaces.
My textarea fields include CKEditor, which adds
 (or other tags) to the input in order to display it as WYSIWYG.

So in the database the whitespaces look like this:

```<code>"<p>     </p>"
</code>```

And that shouldn't validate.

答:
You can create a custom validator.

Import ValidationError:

from wtforms import ValidationError
```

<p>Custom validator:</p>

<pre class="lang-py prettyprint-override"><code>def validate_review(self, field):
    text = field.data.replace('<p>','')
                     .replace('</p>','')
                     .replace(' ','')
                     .replace(' ','')
                     .replace(' ','')
                     .replace('<br>','')
    if not text:
        raise ValidationError('This field should not contain only white spaces')
</code>```

Make sure that, this custom validator is method of AddReviewForm class. Also note that, the custom validator's method name should be in the form of validate_<field_name>.

Body:
I have a form with a textarea field and wonder if I could use WTForms Regexp validator to prevent the form submitting when the textarea contains only blank spaces.
Is there a way?

This is my form:

class AddReviewForm(FlaskForm):
    review = TextAreaField("Review", validators=[DataRequired())
    submit = SubmitField("Post Review")

I was hoping Regexp would allow me to prevent only spaces.
My textarea fields include CKEditor, which adds
 (or other tags) to the input in order to display it as WYSIWYG.

So in the database the whitespaces look like this:

"

"

And that shouldn't validate.

Body:
You can create a custom validator.

Import ValidationError:

from wtforms import ValidationError

Custom validator:

def validate_review(self, field):
    text = field.data.replace('<p>','')
                     .replace('</p>','')
                     .replace('&nbsp;','')
                     .replace('&ensp;','')
                     .replace('&emsp;','')
                     .replace('<br>','')
    if not text:
        raise ValidationError('This field should not contain only white spaces')

Make sure that, this custom validator is method of AddReviewForm class. Also note that, the custom validator's method name should be in the form of validate_<field_name>.


问:
Is it possible to read php code from other sites?
Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites. </p>

答: yes you can do that but it is not recommended see http://php.net/manual/en/function.include.php</p>


问:
allow less secure app access in Yahoo mail
I need to allow less secure app access in Yahoo but I can't find the button :(

Any ideas ?

Regards,

答:
Finally found it,

Go to ‘Generate App Password’ then select MacMail(in my case I use it) then copy past the generated code instead of your password.


问:
'x' is not defined in custom decimal conversion function
```<code>def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    if n>0:
        if 2<=radix<=16:
            while int(n/radix) == 0:
                converted_number.append(n % radix)
                converted_number.reverse()
                x = ''.join(str(i) for i in converted_number)
                x.replace('10', 'A')
                x.replace('11', 'B')
                x.replace('12', 'C')
                x.replace('13', 'D')
                x.replace('14', 'E')
                x.replace('15', 'F')
                x.replace('16', 'G')
            else:
                converted_number.append(n % radix)
        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")

    print("%d in base 10 is %d in base %d" % (n1,x,radix1))

deci_to_any_list()
</code>```

```<code>Enter a number : 10
Enter a radix : 2
</code>```

I want to create a decimal transformation function. I want to create this function using the append, reverse, join, and replace functions. If I type with the code above, it says name 'x' is not defined. How should I handle this?

答:
There are many inconsistencies in your code.

You are printing x without updating it.

python strings are immutable, once you apply replace you must catch the copy with another variable.

your logic for base conversion is also wrong.

The corrected code:

```<code>def replace_base(x):
    x = x.replace('10', 'A')
    x = x.replace('11', 'B')
    x = x.replace('12', 'C')
    x = x.replace('13', 'D')
    x = x.replace('14', 'E')
    x = x.replace('15', 'F')
    x = x.replace('16', 'G')
    return x

def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    x = None # initialize
    if n>0:
        if 2<=radix<=16:
            while n>0:
                # conversion part
                converted_number.append(n % radix)
                n = n//radix

            # once the conversion is done
            converted_number.reverse()
            x = ''.join(replace_base(str(i)) for i in converted_number)

        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")
    print(converted_number)
    print(x)

deci_to_any_list()
</code>```

Body:
def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    if n>0:
        if 2<=radix<=16:
            while int(n/radix) == 0:
                converted_number.append(n % radix)
                converted_number.reverse()
                x = ''.join(str(i) for i in converted_number)
                x.replace('10', 'A')
                x.replace('11', 'B')
                x.replace('12', 'C')
                x.replace('13', 'D')
                x.replace('14', 'E')
                x.replace('15', 'F')
                x.replace('16', 'G')
            else:
                converted_number.append(n % radix)
        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")

    print("%d in base 10 is %d in base %d" % (n1,x,radix1))

deci_to_any_list()

Enter a number : 10
Enter a radix : 2

I want to create a decimal transformation function. I want to create this function using the append, reverse, join, and replace functions. If I type with the code above, it says name 'x' is not defined. How should I handle this?

Body:
There are many inconsistencies in your code.

You are printing x without updating it.

python strings are immutable, once you apply replace you must catch the copy with another variable.

your logic for base conversion is also wrong.

The corrected code:

def replace_base(x):
    x = x.replace('10', 'A')
    x = x.replace('11', 'B')
    x = x.replace('12', 'C')
    x = x.replace('13', 'D')
    x = x.replace('14', 'E')
    x = x.replace('15', 'F')
    x = x.replace('16', 'G')
    return x

def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    x = None # initialize
    if n>0:
        if 2<=radix<=16:
            while n>0:
                # conversion part
                converted_number.append(n % radix)
                n = n//radix

            # once the conversion is done
            converted_number.reverse()
            x = ''.join(replace_base(str(i)) for i in converted_number)

        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")
    print(converted_number)
    print(x)

deci_to_any_list()


问:
data.table equivalent for: case_when - Invalid regex when using emails on it?
I've a list of emails, I want to compare against a DB column, named correo (spanish for email).

So, let's say this is the list of emails to use:

```<code>users_emails <-"18maryalma@gmail.com|2013311097@edu.pe|40491118@cotal.edu.pe|956145120jh@gmail.com|975625735o@gmail.com"
</code>```

When using case_when and grepl to match them to the data base, I get:

```<code>Error in grepl(users_emails, correo, ignore.case = TRUE) :
  invalid regular expression '18maryalma@gmail.com|2013311097@edu.pe...
</code>```

Code:

```<code>db <- db %>%
            mutate(
              secciones = case_when(
                grepl(users_emails,
                      correo, ignore.case = TRUE) ~ TRUE)
              )
</code>```

data:

```<code>db <- structure(list(idusuario = c(2L, 3L, 6L, 8L, 10L, 11L), ecoid = c(47L,
1878686L, 355078L, 2667803L, 2680290L, 2680842L), facebookid = c(0,
0, 0, 0, 0, 0), twitterid = c(0L, 0L, 0L, 0L, 0L, 0L), googleid = c(0L,
0L, 0L, 0L, 0L, 0L), nombres = c("carlos", "Max", "Estibens Manuel",
"Hernan", "angie", "Dennys Dante"), apellidos = c("gdrab", "Palomino",
"' or 1=1", "Galvez", "cotaquispe palomino", "Angeles"), correo = c("cfrasan@gmail.com",
"maxpalominomendoza@gmail.com", "estibensmanchego@gmail.com",
"hgb2431@gmail.com", "patito_luz_07@hotmail.com", "dangeles@americatv.com.pe"
), nickname = c("cfrasan666", NA, "estibensmancheg", NA, NA,
NA), genero = c("M", "M", "M", "M", NA, "M"), avatar = c("http://peruid.e3.pe/ima/0/0/0/0/0/thumb/1338410240_47.jpg",
"http://peruid.pe/f/i/gadget/avatar-4.jpg", "http://peruid.pe/f/i/gadget/avatar-6.jpg",
"http://s.elcomercio.pe/uploads/default.jpg", "http://s.elcomercio.pe/uploads/default.jpg",
"http://s.elcomercio.pe/uploads/default.jpg"), avatar_url = c("http://peruid.e3.pe/ima/0/0/0/0/0/thumb/avatar/1338410240_47.jpg",
"http://peruid.pe/f/i/gadget/avatar-4.jpg", "http://peruid.pe/f/i/gadget/avatar-6.jpg",
"http://s.elcomercio.pe/uploads/default.jpg", "http://s.elcomercio.pe/uploads/default.jpg",
"http://s.elcomercio.pe/uploads/default.jpg"), status = c(0L,
0L, 0L, 0L, 0L, 0L), fecha = c("1997-03-01", "1986-02-02", "1986-04-22",
"1984-03-15", "0000-00-00", "1984-05-28"), version = c(34L, 49L,
99L, 11L, 1L, 2L), pais = c("PE", "PE", "PE", "PE", "PE", "PE"
), suscriptor = c(0L, 0L, 0L, 0L, NA, 0L), telefono = c("95286265",
"965312230", "014274434", "976926796", NA, "981306661"), ciudad = c("Lima y Callao",
"Lima y Callao", "Lima y Callao", "Lima y Callao", NA, "Lima"
), acceso = c(NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_), clave = c("sha256:1024:OT9jxBY0cGm+hC3ZQqx+HqE12uAuaqzG:rYTfX",
"sha256:1024:ddreAcaw8oRPeoE/s5rO/+eMpypBjYyv:MqAYX", "sha256:1024:GqbedkIqtC/ersJvwCPnn78ztIj0CJMR:jOrp+",
"sha256:1024:7P6+L6h/nQawwFXs9q/Ri9gDzOOstWKk:JwsVX", "sha256:1024:jdrS3ctfG1aa9sNY4csqo/f306T6yyqy:LQtMu",
"sha256:1024:lbiQYFd668n2E+5zg5bLk0QpeULUJ+Xn:fUtYv"), nueva_clave_key = c(NA,
"", "2cc9b4cf343011eb94b3cc685f1c91b87f1974db", "", NA, NA),
    nueva_clave_requested = c(NA, "2016-01-29 17:45:34", "2015-08-02 18:57:44",
    "2015-07-08 12:30:17", NA, NA), acepto_politicas = c(1L,
    1L, 1L, 1L, NA, 1L), fecha_registro = c("0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00", "0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00"), fecha_actualizado = structure(c(1485147600,
    1535950800, 1498280400, 1498798800, 1481346000, 1488517200
    ), class = c("POSIXct", "POSIXt"), tzone = ""), dni = c("41764577",
    "41773997", "44548862", "42311024", "", "42381593"), direccion = c("jose mariategui S/n",
    "Calle rosacruces 270 San Gregorio are vitarte", "Av. Emancipacion 153 int. 304",
    "Carlos alayza y roel 2331", "", "Av Jose Leguia y Melendez 1837"
    ), apellido_ma = c("rinjo", "Mendoza", "Melendez", "Bellido",
    "", "Fuentes"), envio = c("", "", "", "", "", ""), envio_fecha = c("0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00", "0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00"), paquete_suscriptor = c("0",
    "1", "0", "1", "0", "0"), paquete_suscriptor_fecha = c("2016-12-23 12:45:18",
    "2017-02-16 15:10:37", "0000-00-00 00:00:00", "2016-10-21 10:08:05",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00"), departamento = c(15L,
    15L, 15L, 15L, 0L, 15L), provincia = c(6L, 1L, 1L, 1L, 0L,
    1L), distrito = c(2L, 3L, 1L, 16L, 0L, 21L), ga_userid_is_in_db = c(NA,
    NA, NA, NA, NA, NA), secciones = c(NA_character_, NA_character_,
    NA_character_, NA_character_, NA_character_, NA_character_
    )), row.names = c(NA, 6L), class = "data.frame")
</code>```

UPDATE 1:

Still getting errors, it wasn't the emails but also happens when using numbers (as strings).

Does anyone know how to do this with data.table?

UPDATE 2:

Should work with number ids also:

```<code>users_ids <- dput(head(users_ids))
c(996683L, 996177L, 994826L, 991164L, 991L, 990744L)
</code>```

Code:

```<code>setDT(db)[Reduce(`|`, lapply(users_ids, function(es)
  grepl(es, idusuario, ignore.case = TRUE))), ga_usersids_in_db := TRUE][]
</code>```

答:
We can use fcase from data.table

```<code>library(data.table)
setDT(db)[, secciones := fcase(grepl(users_emails, correo, ignore.case = TRUE), TRUE)]
</code>```

Or without any fcase

```<code>setDT(db)[grepl(users_emails, correo, ignore.case = TRUE), secciones := TRUE][]
</code>```

If there are many emails, it may be better to loop and Reduce

```<code>emails <- strsplit(users_emails, "|", fixed = TRUE)[[1]]
setDT(db)[Reduce(`|`, lapply(emails, function(es)
    grepl(es, correo, ignore.case = TRUE))), secciones := TRUE][]
</code>```

Body:
I've a list of emails, I want to compare against a DB column, named correo (spanish for email).

So, let's say this is the list of emails to use:

users_emails <-"18maryalma@gmail.com|2013311097@edu.pe|40491118@cotal.edu.pe|956145120jh@gmail.com|975625735o@gmail.com"

When using case_when and grepl to match them to the data base, I get:

Error in grepl(users_emails, correo, ignore.case = TRUE) :
  invalid regular expression '18maryalma@gmail.com|2013311097@edu.pe...

Code:

db <- db %>%
            mutate(
              secciones = case_when(
                grepl(users_emails,
                      correo, ignore.case = TRUE) ~ TRUE)
              )

data:

db <- structure(list(idusuario = c(2L, 3L, 6L, 8L, 10L, 11L), ecoid = c(47L,
1878686L, 355078L, 2667803L, 2680290L, 2680842L), facebookid = c(0,
0, 0, 0, 0, 0), twitterid = c(0L, 0L, 0L, 0L, 0L, 0L), googleid = c(0L,
0L, 0L, 0L, 0L, 0L), nombres = c("carlos", "Max", "Estibens Manuel",
"Hernan", "angie", "Dennys Dante"), apellidos = c("gdrab", "Palomino",
"' or 1=1", "Galvez", "cotaquispe palomino", "Angeles"), correo = c("cfrasan@gmail.com",
"maxpalominomendoza@gmail.com", "estibensmanchego@gmail.com",
"hgb2431@gmail.com", "patito_luz_07@hotmail.com", "dangeles@americatv.com.pe"
), nickname = c("cfrasan666", NA, "estibensmancheg", NA, NA,
NA), genero = c("M", "M", "M", "M", NA, "M"), avatar = c("http://peruid.e3.pe/ima/0/0/0/0/0/thumb/1338410240_47.jpg",
"http://peruid.pe/f/i/gadget/avatar-4.jpg", "http://peruid.pe/f/i/gadget/avatar-6.jpg",
"http://s.elcomercio.pe/uploads/default.jpg", "http://s.elcomercio.pe/uploads/default.jpg",
"http://s.elcomercio.pe/uploads/default.jpg"), avatar_url = c("http://peruid.e3.pe/ima/0/0/0/0/0/thumb/avatar/1338410240_47.jpg",
"http://peruid.pe/f/i/gadget/avatar-4.jpg", "http://peruid.pe/f/i/gadget/avatar-6.jpg",
"http://s.elcomercio.pe/uploads/default.jpg", "http://s.elcomercio.pe/uploads/default.jpg",
"http://s.elcomercio.pe/uploads/default.jpg"), status = c(0L,
0L, 0L, 0L, 0L, 0L), fecha = c("1997-03-01", "1986-02-02", "1986-04-22",
"1984-03-15", "0000-00-00", "1984-05-28"), version = c(34L, 49L,
99L, 11L, 1L, 2L), pais = c("PE", "PE", "PE", "PE", "PE", "PE"
), suscriptor = c(0L, 0L, 0L, 0L, NA, 0L), telefono = c("95286265",
"965312230", "014274434", "976926796", NA, "981306661"), ciudad = c("Lima y Callao",
"Lima y Callao", "Lima y Callao", "Lima y Callao", NA, "Lima"
), acceso = c(NA_character_, NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_), clave = c("sha256:1024:OT9jxBY0cGm+hC3ZQqx+HqE12uAuaqzG:rYTfX",
"sha256:1024:ddreAcaw8oRPeoE/s5rO/+eMpypBjYyv:MqAYX", "sha256:1024:GqbedkIqtC/ersJvwCPnn78ztIj0CJMR:jOrp+",
"sha256:1024:7P6+L6h/nQawwFXs9q/Ri9gDzOOstWKk:JwsVX", "sha256:1024:jdrS3ctfG1aa9sNY4csqo/f306T6yyqy:LQtMu",
"sha256:1024:lbiQYFd668n2E+5zg5bLk0QpeULUJ+Xn:fUtYv"), nueva_clave_key = c(NA,
"", "2cc9b4cf343011eb94b3cc685f1c91b87f1974db", "", NA, NA),
    nueva_clave_requested = c(NA, "2016-01-29 17:45:34", "2015-08-02 18:57:44",
    "2015-07-08 12:30:17", NA, NA), acepto_politicas = c(1L,
    1L, 1L, 1L, NA, 1L), fecha_registro = c("0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00", "0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00"), fecha_actualizado = structure(c(1485147600,
    1535950800, 1498280400, 1498798800, 1481346000, 1488517200
    ), class = c("POSIXct", "POSIXt"), tzone = ""), dni = c("41764577",
    "41773997", "44548862", "42311024", "", "42381593"), direccion = c("jose mariategui S/n",
    "Calle rosacruces 270 San Gregorio are vitarte", "Av. Emancipacion 153 int. 304",
    "Carlos alayza y roel 2331", "", "Av Jose Leguia y Melendez 1837"
    ), apellido_ma = c("rinjo", "Mendoza", "Melendez", "Bellido",
    "", "Fuentes"), envio = c("", "", "", "", "", ""), envio_fecha = c("0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00", "0000-00-00 00:00:00",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00"), paquete_suscriptor = c("0",
    "1", "0", "1", "0", "0"), paquete_suscriptor_fecha = c("2016-12-23 12:45:18",
    "2017-02-16 15:10:37", "0000-00-00 00:00:00", "2016-10-21 10:08:05",
    "0000-00-00 00:00:00", "0000-00-00 00:00:00"), departamento = c(15L,
    15L, 15L, 15L, 0L, 15L), provincia = c(6L, 1L, 1L, 1L, 0L,
    1L), distrito = c(2L, 3L, 1L, 16L, 0L, 21L), ga_userid_is_in_db = c(NA,
    NA, NA, NA, NA, NA), secciones = c(NA_character_, NA_character_,
    NA_character_, NA_character_, NA_character_, NA_character_
    )), row.names = c(NA, 6L), class = "data.frame")

UPDATE 1:

Still getting errors, it wasn't the emails but also happens when using numbers (as strings).

Does anyone know how to do this with data.table?

UPDATE 2:

Should work with number ids also:

users_ids <- dput(head(users_ids))
c(996683L, 996177L, 994826L, 991164L, 991L, 990744L)

Code:

setDT(db)[Reduce(`|`, lapply(users_ids, function(es)
  grepl(es, idusuario, ignore.case = TRUE))), ga_usersids_in_db := TRUE][]

Body:
We can use fcase from data.table

library(data.table)
setDT(db)[, secciones := fcase(grepl(users_emails, correo, ignore.case = TRUE), TRUE)]

Or without any fcase

setDT(db)[grepl(users_emails, correo, ignore.case = TRUE), secciones := TRUE][]

If there are many emails, it may be better to loop and Reduce

emails <- strsplit(users_emails, "|", fixed = TRUE)[[1]]
setDT(db)[Reduce(`|`, lapply(emails, function(es)
    grepl(es, correo, ignore.case = TRUE))), secciones := TRUE][]


问:
Error in eval() when using randomForest in R
I am trying to use the randomForest command

I have a sparse matrix, called counts, of single-cell expression data, and another variable, identity, which has the type of cell

```<code>counts <- t(as.matrix(CountsMatrix))

names(counts) <- make.names(names(counts))

smp_size <- floor(nrow(counts)*0.7)
train_ind <- sample(c(1:nrow(counts)), smp_size)

x_train <- counts[train_ind,]
x_test <- counts[-train_ind,]

y_train <- identity[train_ind]
y_test <- identity[-train_ind]

train_set <- cbind(data.frame(Identity = y_train), as.data.frame(x_train))
forest <- randomForest(Identity ~., data = train_set)
</code>```

I have put all the data together in a data frame, and the line names(counts) <- make.names(names(counts)) was added from my attempts to fix my error.

When running this code I get the error:

```<code>Error in eval(predvars, data, env) : object '0610005C13Rik' not found
</code>```

My data has 16519 columns each with a name similar to 0610005C13Rik, and I do not know how to rename all of them if this is the problem.

答:
Let's try with some example dataset, avoiding using function names as a variable, identity is a function, so:

```<code>library(randomForest)
library(Seurat)
CountsMatrix = pbmc_small[["RNA"]]@data
ident = factor(as.numeric(Idents(pbmc_small)==1))
</code>```

Just fit it:

```<code>fit = randomForest(ident ~ .,data=cbind(ident,counts))
Error in eval(predvars, data, env) : object 'HLA-DRA' not found
</code>```

Here we use make.names like you did:

```<code>counts <- t(as.matrix(CountsMatrix))
names(counts) <- make.names(names(counts))
</code>```

You have a matrix, names() does not work. We can look at it:

```<code>head(names(counts))
[1] NA NA NA NA NA NA
</code>```

It's the column names you need to fix:

```<code>colnames(counts) <- make.names(colnames(counts))

smp_size <- floor(nrow(counts)*0.7)
train_ind <- sample(c(1:nrow(counts)), smp_size)

x_train <- counts[train_ind,]
x_test <- counts[-train_ind,]

y_train <- ident[train_ind]
y_test <- ident[-train_ind]

train_set <- cbind(data.frame(Identity = y_train), as.data.frame(x_train))
forest <- randomForest(Identity ~., data = train_set)
</code>```

Or you can simply do:

```<code>forest <- randomForest(x=x_train,y=y_train)
</code>```

Body:
I am trying to use the randomForest command

I have a sparse matrix, called counts, of single-cell expression data, and another variable, identity, which has the type of cell

counts <- t(as.matrix(CountsMatrix))

names(counts) <- make.names(names(counts))

smp_size <- floor(nrow(counts)*0.7)
train_ind <- sample(c(1:nrow(counts)), smp_size)

x_train <- counts[train_ind,]
x_test <- counts[-train_ind,]

y_train <- identity[train_ind]
y_test <- identity[-train_ind]

train_set <- cbind(data.frame(Identity = y_train), as.data.frame(x_train))
forest <- randomForest(Identity ~., data = train_set)

I have put all the data together in a data frame, and the line names(counts) <- make.names(names(counts)) was added from my attempts to fix my error.

When running this code I get the error:

Error in eval(predvars, data, env) : object '0610005C13Rik' not found

My data has 16519 columns each with a name similar to 0610005C13Rik, and I do not know how to rename all of them if this is the problem.

Body:
Let's try with some example dataset, avoiding using function names as a variable, identity is a function, so:

library(randomForest)
library(Seurat)
CountsMatrix = pbmc_small[["RNA"]]@data
ident = factor(as.numeric(Idents(pbmc_small)==1))

Just fit it:

fit = randomForest(ident ~ .,data=cbind(ident,counts))
Error in eval(predvars, data, env) : object 'HLA-DRA' not found

Here we use make.names like you did:

counts <- t(as.matrix(CountsMatrix))
names(counts) <- make.names(names(counts))

You have a matrix, names() does not work. We can look at it:

head(names(counts))
[1] NA NA NA NA NA NA

It's the column names you need to fix:

colnames(counts) <- make.names(colnames(counts))

smp_size <- floor(nrow(counts)*0.7)
train_ind <- sample(c(1:nrow(counts)), smp_size)

x_train <- counts[train_ind,]
x_test <- counts[-train_ind,]

y_train <- ident[train_ind]
y_test <- ident[-train_ind]

train_set <- cbind(data.frame(Identity = y_train), as.data.frame(x_train))
forest <- randomForest(Identity ~., data = train_set)

Or you can simply do:

forest <- randomForest(x=x_train,y=y_train)


问:
Preserving content of source blocks when exporting literate program to HTML with ReadTheOrg

Minimal example

I wrote a program in org-mode using literate programming technique with :noweb extension(?). Typical piece of code looks like this:

```<code>* Section

In order to do foo with bar, we define a function ~do_foo~, which initializes object of a class ~BarParser~ with a value of parameter of the type ~bar_t~.

#+name: section_function_blockname
#+begin_src cpp
void do_foo
( bar_t bar
, <<additional_parameter_to_do_foo>>
) {
  BarParser barParser(bar);

  <<section_function_do_fooBody>>
}
#+end_src

The function will require additional parameter for the purposes of the /FizzBazz/ module. We will discuss them in a [[*Decoding FizzBazz messages][later_section]].
</code>```

Entire content of the program is stored in a single file, which at the top has #+SETUP: theme-readtheorg.setup. The setup file is not the problem, because the HTML generates correctly, only with not the content I want.

Problem

To generate the code, I use (org-babel-tangle). This produces all the files I'd expect for all the blocks with :tangle parameter. The files have the content I expect them to have and code compiles and runs the way it should.

To generate the documentation I'd like to publish along the code, I use (org-html-export-to-html). What I expected to happen was that either:

the <<tags>> will get substituted with their expected value, which wouldn't be ideal but at least acceptable, or

the <<tags>> will be left untouched the way they are presented,when editing the org-file with Emacs.

However the output to (org-html-export-to-html) is quite different and unexpected - all the <<tags>> are replaced with a newline character. This leaves me with all the code blocks having incorrect content that cannot be understood without either looking at the generated code or original org-file which completely defeats the purpose of the documentation being in the separate file. I cannot force everyone I work with to switch to Emacs to let them browse the documentation!

Question

As stated above, the problem is with noweb <> being procesed by some call inside (org-html-export-to-html). The question I have regarding this issue is:

How can I force (org-html-export-to-html) to leave the contents of source blocks as they are, without stripping away the noweb <<tags>>?

答:
IIUC, you need to specify an appropriate :noweb header. Try this:

```<code>#+begin_src cpp :noweb no-export
</code>```

and refer to the noweb section in the manual for other values and more details.

Body:
Minimal example

I wrote a program in org-mode using literate programming technique with :noweb extension(?). Typical piece of code looks like this:

* Section

In order to do foo with bar, we define a function ~do_foo~, which initializes object of a class ~BarParser~ with a value of parameter of the type ~bar_t~.

#+name: section_function_blockname
#+begin_src cpp
void do_foo
( bar_t bar
, <<additional_parameter_to_do_foo>>
) {
  BarParser barParser(bar);

  <<section_function_do_fooBody>>
}
#+end_src

The function will require additional parameter for the purposes of the /FizzBazz/ module. We will discuss them in a [[*Decoding FizzBazz messages][later_section]].

Entire content of the program is stored in a single file, which at the top has #+SETUP: theme-readtheorg.setup. The setup file is not the problem, because the HTML generates correctly, only with not the content I want.

Problem

To generate the code, I use (org-babel-tangle). This produces all the files I'd expect for all the blocks with :tangle parameter. The files have the content I expect them to have and code compiles and runs the way it should.

To generate the documentation I'd like to publish along the code, I use (org-html-export-to-html). What I expected to happen was that either:

the <<tags>> will get substituted with their expected value, which wouldn't be ideal but at least acceptable, or

the <<tags>> will be left untouched the way they are presented,when editing the org-file with Emacs.

However the output to (org-html-export-to-html) is quite different and unexpected - all the <<tags>> are replaced with a newline character. This leaves me with all the code blocks having incorrect content that cannot be understood without either looking at the generated code or original org-file which completely defeats the purpose of the documentation being in the separate file. I cannot force everyone I work with to switch to Emacs to let them browse the documentation!

Question

As stated above, the problem is with noweb <> being procesed by some call inside (org-html-export-to-html). The question I have regarding this issue is:

How can I force (org-html-export-to-html) to leave the contents of source blocks as they are, without stripping away the noweb <<tags>>?

Body:
IIUC, you need to specify an appropriate :noweb header. Try this:

#+begin_src cpp :noweb no-export

and refer to the noweb section in the manual for other values and more details.


问:
Adding user to Active Directory Group .net core: A referral was returned from the server
I'm building a .net core 3 website where I'm trying to add a user to an Active Directory security group. The below code works fine in my development environment but once it's deployed to IIS I receive:

System.DirectoryServices.DirectoryServicesCOMException (0x8007202B):
  A referral was returned from the server.

The error occurs at "group.Save();"

```<code>    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "ad.xxx.com:389",
    "DC=ad,DC=xxx,DC=com", svcAccountUsername, svcAccountPw))
    {
       GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, groupName);
       group.Members.Add(pc, IdentityType.SamAccountName, username);
       group.Save();
    }
</code>```

Again, this works locally in my development environment but not once deployed to IIS. Any suggestions on how to fix?

答:
A referral means that you aren't talking to the right server, but the server knows who you should be talking to. If you look into the exception object more, you might even find which server it wants to send you to.

This can happen if the group is not on the same domain that you passed to the PrincipalContext.

Body:
I'm building a .net core 3 website where I'm trying to add a user to an Active Directory security group. The below code works fine in my development environment but once it's deployed to IIS I receive:

System.DirectoryServices.DirectoryServicesCOMException (0x8007202B):
  A referral was returned from the server.

The error occurs at "group.Save();"

    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "ad.xxx.com:389",
    "DC=ad,DC=xxx,DC=com", svcAccountUsername, svcAccountPw))
    {
       GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, groupName);
       group.Members.Add(pc, IdentityType.SamAccountName, username);
       group.Save();
    }

Again, this works locally in my development environment but not once deployed to IIS. Any suggestions on how to fix?


问:
PUT request not updating JSON when using a GET request, though it says it's successful?
(FYI, I'm using Jsonbin.io)

I have this code:

```<code>// #1
var req2 = new XMLHttpRequest();
req2.onreadystatechange = () => {
  if (req2.readyState == XMLHttpRequest.DONE) {
    alert(req2.responseText);
  }
};

req2.open("GET", "https://api.jsonbin.io/b/5ed1530b79382f568bcf5662", true);
req2.setRequestHeader("secret-key", "ProbablyNoProblemInTheAPIkey");
req2.send();

// #2

let req = new XMLHttpRequest();

req.onreadystatechange = () => {
  if (req.readyState == XMLHttpRequest.DONE) {
  alert(req.responseText);
  }
};

req.open("PUT", "https://api.jsonbin.io/b/5ed1530b79382f568bcf5662", true);

req.setRequestHeader("secret-key", "ProbablyNoProblemInTheAPIkey");
req.setRequestHeader("Content-Type", "application/json");
req.send('{"Sample": "Hello World"}');

</code>```

Here is an example of my code functioning:

```

The PUT request is supposedly successful, but when making a GET request to access the updated version, the JSON seems the same. What is going wrong?

It seems like the PUT request was done successfully, as req.status was 200, so I don't think you should focus on that.

答:
onreadystatechange executes asynchrnously. So, first there's no guarantee that your GETexecutes only after PUT has been successfully completed.

Second, PUT anyway has been written after the GET request in your code.

So, You can try putting req2.send();of the GET request inside the 'Success' of PUT

```<code> req.onreadystatechange = () => {
      if (req.readyState == XMLHttpRequest.DONE) {
          req2.send(); //Try making the GET request once PUT is completed
        //This is gonna execute asynchronously in both the cases
      }
    };
</code>```

Body:
(FYI, I'm using Jsonbin.io)

I have this code:

// #1
var req2 = new XMLHttpRequest();
req2.onreadystatechange = () => {
  if (req2.readyState == XMLHttpRequest.DONE) {
    alert(req2.responseText);
  }
};

req2.open("GET", "https://api.jsonbin.io/b/5ed1530b79382f568bcf5662", true);
req2.setRequestHeader("secret-key", "ProbablyNoProblemInTheAPIkey");
req2.send();

// #2

let req = new XMLHttpRequest();

req.onreadystatechange = () => {
  if (req.readyState == XMLHttpRequest.DONE) {
  alert(req.responseText);
  }
};

req.open("PUT", "https://api.jsonbin.io/b/5ed1530b79382f568bcf5662", true);

req.setRequestHeader("secret-key", "ProbablyNoProblemInTheAPIkey");
req.setRequestHeader("Content-Type", "application/json");
req.send('{"Sample": "Hello World"}');

Here is an example of my code functioning:

The PUT request is supposedly successful, but when making a GET request to access the updated version, the JSON seems the same. What is going wrong?

It seems like the PUT request was done successfully, as req.status was 200, so I don't think you should focus on that.

Body:
onreadystatechange executes asynchrnously. So, first there's no guarantee that your GETexecutes only after PUT has been successfully completed.

Second, PUT anyway has been written after the GET request in your code.

So, You can try putting req2.send();of the GET request inside the 'Success' of PUT

 req.onreadystatechange = () => {
      if (req.readyState == XMLHttpRequest.DONE) {
          req2.send(); //Try making the GET request once PUT is completed
        //This is gonna execute asynchronously in both the cases
      }
    };


问:
Why is the input box in my popup editor of my KendoUI grid not populating?
I'm using the KendoUI for ASP.NET Core to work with data within my web application.  I have a grid that uses a custom popup editr.  This is accomplished with the following code:

```<code> @(Html.Kendo().Grid<Sale>()
                    .Name("salesGrid")
                    .Columns(columns =>
                    {
                        columns.Bound(p => p.CreatedDate).Format("{0:dd/MM/yyyy}");
                        columns.Bound(p => p.Status).Width(180);
                        columns.Bound(p => p.Seller).Width(150);
                    })
                    .ToolBar(toolBar =>
                    {
                        toolBar.Create().Text("Add Transaction");
                    })
                    .Editable(editable => editable.Mode(GridEditMode.PopUp).AdditionalViewData(new { vid = vesselid}).TemplateName("EditSalePopup"))
                    .Pageable()
                    .Sortable()
                    .DataSource(dataSource => dataSource
                        .Ajax()
                        .PageSize(20)
                        .ServerOperation(false)
                        .Model(model =>
                        {
                            model.Id(p => p.Id);
                            model.Field(p => p.Id).Editable(false);
                            model.Field(p => p.CreatedDate).Editable(false);
                        })
                        .Read(read => read.Action("ReadSales", "Vessel").Data("GetVesselId"))
                        .Update(update => update.Action("UpdateSale", "Vessel"))
                        .Create(create => create.Action("CreateSale", "Vessel").Data("GetVesselId"))
                        .Destroy(destroy => destroy.Action("DeleteSale", "Vessel"))
                    ))
</code>```

You'll notice that the edit code has both an additional value to be passed defined and the name of the editor template itself

```<code>.Editable(editable => editable.Mode(GridEditMode.PopUp).AdditionalViewData(new { vid = vesselid}).TemplateName("EditSalePopup"))
</code>```

The vesselId is taken from viewdata at the top of my page, the value is confirmed and can be seen.

```<code>@model Vessel
@{
    string vesselid = Model.Id.ToString();
}
</code>```

Here is the code for my custom editor which lives in the Shared/EditorTemplates folder

```<code>@model Sale

<div class="container-fluid">
    <div class="row">
        <div class="col">
            <div class="md-form form-group">
                <p>@ViewData["vid"]</p>
                <input type="text" asp-for="VesselId" value="@ViewData["vid"]" />
            </div>
        </div>
    </div>
</div>
</code>```

The idea is that when you click on the add transaction on the grid, you get this custom editor with the vesselid input box populated with the id of the vessel.  To test that the value is passed to the editor correclty I added a
 with the viewdata["vid"] and I can clearly see that the ID is passed correctly, however, the input below it doesn't populate itself with the ID from ViewData it always shows 0.

To investigate this I look at the input as it was rendered in the browser and it looks like this:

```<code><input type="text" value="10577" data-val="true" data-val-required="The VesselId field is required." id="VesselId" name="VesselId" data-bind="value:VesselId">
</code>```

As you can see from the rendered code the value is there and correct but the input still shows 0.  Can anyone help me with understanding what's going wrong here and why I can't use the Id as defined?

答:
What you need to understand regarding popup editors is that they are serialized once on the server with a model that has the default values and after that it is reused on the client by plugging the values of the grid's model in.

So one thing you could do is add that field to the grid model. Another thing you can do is handle the grid's edit event and update the model or DOM at edit time:

```<code>...
.Events(ev =>
{
   ev.Edit("onGridEdit");
})
...

<script type="text/javascript">

    function onGridEdit(e) {
        // Update the grid's model or set the value of a hidden, etc.
        var uid = $(".k-edit-form-container").closest("[data-role=window]").data("uid");
        var model = $("#salesGrid").data("kendoGrid").dataSource.getByUid(uid);
        model.set("VesselId", vesselid);
    }

</script>
</code>```

Yet another way is to use MVVM binding.

Body:
I'm using the KendoUI for ASP.NET Core to work with data within my web application.  I have a grid that uses a custom popup editr.  This is accomplished with the following code:

 @(Html.Kendo().Grid<Sale>()
                    .Name("salesGrid")
                    .Columns(columns =>
                    {
                        columns.Bound(p => p.CreatedDate).Format("{0:dd/MM/yyyy}");
                        columns.Bound(p => p.Status).Width(180);
                        columns.Bound(p => p.Seller).Width(150);
                    })
                    .ToolBar(toolBar =>
                    {
                        toolBar.Create().Text("Add Transaction");
                    })
                    .Editable(editable => editable.Mode(GridEditMode.PopUp).AdditionalViewData(new { vid = vesselid}).TemplateName("EditSalePopup"))
                    .Pageable()
                    .Sortable()
                    .DataSource(dataSource => dataSource
                        .Ajax()
                        .PageSize(20)
                        .ServerOperation(false)
                        .Model(model =>
                        {
                            model.Id(p => p.Id);
                            model.Field(p => p.Id).Editable(false);
                            model.Field(p => p.CreatedDate).Editable(false);
                        })
                        .Read(read => read.Action("ReadSales", "Vessel").Data("GetVesselId"))
                        .Update(update => update.Action("UpdateSale", "Vessel"))
                        .Create(create => create.Action("CreateSale", "Vessel").Data("GetVesselId"))
                        .Destroy(destroy => destroy.Action("DeleteSale", "Vessel"))
                    ))

You'll notice that the edit code has both an additional value to be passed defined and the name of the editor template itself

.Editable(editable => editable.Mode(GridEditMode.PopUp).AdditionalViewData(new { vid = vesselid}).TemplateName("EditSalePopup"))

The vesselId is taken from viewdata at the top of my page, the value is confirmed and can be seen.

@model Vessel
@{
    string vesselid = Model.Id.ToString();
}

Here is the code for my custom editor which lives in the Shared/EditorTemplates folder

@model Sale

@ViewData["vid"]

                <input type="text" asp-for="VesselId" value="@ViewData["vid"]" />

The idea is that when you click on the add transaction on the grid, you get this custom editor with the vesselid input box populated with the id of the vessel.  To test that the value is passed to the editor correclty I added a
 with the viewdata["vid"] and I can clearly see that the ID is passed correctly, however, the input below it doesn't populate itself with the ID from ViewData it always shows 0.

To investigate this I look at the input as it was rendered in the browser and it looks like this:

<input type="text" value="10577" data-val="true" data-val-required="The VesselId field is required." id="VesselId" name="VesselId" data-bind="value:VesselId">

As you can see from the rendered code the value is there and correct but the input still shows 0.  Can anyone help me with understanding what's going wrong here and why I can't use the Id as defined?

Body:
What you need to understand regarding popup editors is that they are serialized once on the server with a model that has the default values and after that it is reused on the client by plugging the values of the grid's model in.

So one thing you could do is add that field to the grid model. Another thing you can do is handle the grid's edit event and update the model or DOM at edit time:

...
.Events(ev =>
{
   ev.Edit("onGridEdit");
})
...

<script type="text/javascript">

    function onGridEdit(e) {
        // Update the grid's model or set the value of a hidden, etc.
        var uid = $(".k-edit-form-container").closest("[data-role=window]").data("uid");
        var model = $("#salesGrid").data("kendoGrid").dataSource.getByUid(uid);
        model.set("VesselId", vesselid);
    }

</script>

Yet another way is to use MVVM binding.


问:
Why does this std::map not display in a useable way in the watch window of Visual C++?
I'm unable to view certain std::map in the watch window. Looking into the .natvis file, there are multiple implementations for std::map. Is there a way to select one or the other?

https://developercommunity.visualstudio.com/content/problem/1056550/im-unable-to-inspect-a-variable-of-type-stdmap-in.html

```<code>#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <memory>

typedef std::shared_ptr<std::string> PTR_STRING;
typedef std::map<PTR_STRING, std::size_t> accessFunction2Order;
typedef std::set<accessFunction2Order> setOfAccessFunction2Order;
typedef std::map<std::vector<std::size_t>, setOfAccessFunction2Order> A2B;
typedef std::map<PTR_STRING, std::shared_ptr<A2B> > MAP;

int main()
{   MAP s{
        {    std::make_shared<std::string>("asdasdasdasdasdasdasdasdasdasd"),
            std::make_shared<A2B>()
        }
    };
    const auto &r1 = *s.begin();
}
</code>```

The map s cannot be watched (something regarding std::_Tree<> being displayed). Curiously a reference to the first element can.

答:
The problem is caused by a (I think hardcoded) limit in the visual studio debugger.
In order to display one variable, the debugger is adapting what he finds in the .natvis file -- but he gives up after some fixed number of attempts to resolve a type.

The solution to this problem is to use something like std::any

(or boost::any for those of us not blessed with being able to use an uptodate C++ version)

to break this STL type into chunks the debugger can deal with.
This is of course only a workaround.
Let's hope that this problem will be solved soon.

```<code>#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <any>
#include <memory>

typedef std::shared_ptr<std::string> PTR_STRING;
typedef std::map<PTR_STRING, long> accessFunction2Order;
typedef std::set<accessFunction2Order> setOfAccessFunction2Order;
#if 1
typedef std::map<std::vector<std::size_t>, std::any> A2B;
#else
typedef std::map<std::vector<std::size_t>, setOfAccessFunction2Order> A2B;
#endif
typedef std::map<PTR_STRING, std::shared_ptr<A2B> > MAP;
typedef std::shared_ptr<std::size_t> PTR_INT;

int main()
{   const MAP s{
        {        std::make_shared<std::string>("asdasdasdasdasdasdasdasdasdasd"),
             std::make_shared<A2B>()
        }
    };
}
</code>```

Body:
I'm unable to view certain std::map in the watch window. Looking into the .natvis file, there are multiple implementations for std::map. Is there a way to select one or the other?

https://developercommunity.visualstudio.com/content/problem/1056550/im-unable-to-inspect-a-variable-of-type-stdmap-in.html

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <memory>

typedef std::shared_ptr<std::string> PTR_STRING;
typedef std::map<PTR_STRING, std::size_t> accessFunction2Order;
typedef std::set<accessFunction2Order> setOfAccessFunction2Order;
typedef std::map<std::vector<std::size_t>, setOfAccessFunction2Order> A2B;
typedef std::map<PTR_STRING, std::shared_ptr<A2B> > MAP;

int main()
{   MAP s{
        {    std::make_shared<std::string>("asdasdasdasdasdasdasdasdasdasd"),
            std::make_shared<A2B>()
        }
    };
    const auto &r1 = *s.begin();
}

The map s cannot be watched (something regarding std::_Tree<> being displayed). Curiously a reference to the first element can.

Body:
The problem is caused by a (I think hardcoded) limit in the visual studio debugger.
In order to display one variable, the debugger is adapting what he finds in the .natvis file -- but he gives up after some fixed number of attempts to resolve a type.

The solution to this problem is to use something like std::any

(or boost::any for those of us not blessed with being able to use an uptodate C++ version)

to break this STL type into chunks the debugger can deal with.
This is of course only a workaround.
Let's hope that this problem will be solved soon.

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <any>
#include <memory>

typedef std::shared_ptr<std::string> PTR_STRING;
typedef std::map<PTR_STRING, long> accessFunction2Order;
typedef std::set<accessFunction2Order> setOfAccessFunction2Order;
#if 1
typedef std::map<std::vector<std::size_t>, std::any> A2B;
#else
typedef std::map<std::vector<std::size_t>, setOfAccessFunction2Order> A2B;
#endif
typedef std::map<PTR_STRING, std::shared_ptr<A2B> > MAP;
typedef std::shared_ptr<std::size_t> PTR_INT;

int main()
{   const MAP s{
        {        std::make_shared<std::string>("asdasdasdasdasdasdasdasdasdasd"),
             std::make_shared<A2B>()
        }
    };
}