问:
Cannot kill process: "No process is associated with this object" error
In my program I try to start a new process (open video file in a default player). This part works OK. Later when I try to close the process (player) I get an error:

System.InvalidOperationException: No process is associated with this object.

My code:

```<code>string filename = "747225775.mp4";
var myProc = new Process()
{
    StartInfo = new ProcessStartInfo(filename)
};
myProc.Start();
Thread.Sleep(5000);
try
{
    myProc.Kill(); //Error is here
}
catch (Exception ex)
{
    Debug.WriteLine(ex);
    Debugger.Break();
}
</code>```

What is wrong?

答:
Process.Start associates the Process object with native process handle only when it spawns new process directly. When filename is used as an argument instead of executable name, Process searches registry for association settings via shell32.dll functions and the exact behavior depends on them.

When association is configured in traditional way, to call command line and transfer file name as 1st argument (such as for Notepad), Process.Start spawns new process directly and correctly associates object with native handle. However, when association is configured to execute COM-object (such as for Windows Media Player),  Process.Start only creates some RPC query to execute COM object method and returns without associating object with process handle. (The actual process spawn occurs in svchost.exe context, according to my tests)

This issue can be solved by following modified process start method:

```<code>using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace ProcessTest
{
    public partial class Form1 : Form
    {
        [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut);

        /*Modified Process.Start*/
        public static Process TrueProcessStart(string filename)
        {
            ProcessStartInfo psi;
            string ext = System.IO.Path.GetExtension(filename);//get extension

            var sb = new StringBuilder(500);//buffer for exe file path
            uint size = 500;//buffer size

            /*Get associated app*/
            uint res = AssocQueryString(AssocF.None, AssocStr.Executable, ext,null, sb, ref size);

            if (res != 0)
            {
                Debug.WriteLine("AssocQueryString returned error: " + res.ToString("X"));
                psi = new ProcessStartInfo(filename);//can't get app, use standard method
            }
            else
            {
                psi = new ProcessStartInfo(sb.ToString(), filename);
            }

            return Process.Start(psi);//actually start process
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string filename = "c:\\images\\clip.wmv";

            var myProc = TrueProcessStart(filename);
            if (myProc == null)
            {
                MessageBox.Show("Process can't be killed");
                return;
            }

            Thread.Sleep(5000);
            try
            {
                myProc.Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

    [Flags]
    enum AssocF : uint
    {
        None = 0,
        Init_NoRemapCLSID = 0x1,
        Init_ByExeName = 0x2,
        Open_ByExeName = 0x2,
        Init_DefaultToStar = 0x4,
        Init_DefaultToFolder = 0x8,
        NoUserSettings = 0x10,
        NoTruncate = 0x20,
        Verify = 0x40,
        RemapRunDll = 0x80,
        NoFixUps = 0x100,
        IgnoreBaseClass = 0x200,
        Init_IgnoreUnknown = 0x400,
        Init_FixedProgId = 0x800,
        IsProtocol = 0x1000,
        InitForFile = 0x2000,
    }

    enum AssocStr
    {
        Command = 1,
        Executable,
        FriendlyDocName,
        FriendlyAppName,
        NoOpen,
        ShellNewValue,
        DDECommand,
        DDEIfExec,
        DDEApplication,
        DDETopic,
        InfoTip,
        QuickTip,
        TileInfo,
        ContentType,
        DefaultIcon,
        ShellExtension,
        DropTarget,
        DelegateExecute,
        SupportedUriProtocols,
        Max,
    }

}
</code>```

Here we get the file type's associated application via AssocQueryString. The returned value is then passed to ProcessStartInfo. However it does not always work, so we sometimes have to resort to standart method. For example, image files does not have any associated exe, it's just dll being loaded into explorer's process. So we can't outright kill process in this case.

Body:
In my program I try to start a new process (open video file in a default player). This part works OK. Later when I try to close the process (player) I get an error:

System.InvalidOperationException: No process is associated with this object.

My code:

string filename = "747225775.mp4";
var myProc = new Process()
{
    StartInfo = new ProcessStartInfo(filename)
};
myProc.Start();
Thread.Sleep(5000);
try
{
    myProc.Kill(); //Error is here
}
catch (Exception ex)
{
    Debug.WriteLine(ex);
    Debugger.Break();
}

What is wrong?

Body:
Process.Start associates the Process object with native process handle only when it spawns new process directly. When filename is used as an argument instead of executable name, Process searches registry for association settings via shell32.dll functions and the exact behavior depends on them.

When association is configured in traditional way, to call command line and transfer file name as 1st argument (such as for Notepad), Process.Start spawns new process directly and correctly associates object with native handle. However, when association is configured to execute COM-object (such as for Windows Media Player),  Process.Start only creates some RPC query to execute COM object method and returns without associating object with process handle. (The actual process spawn occurs in svchost.exe context, according to my tests)

This issue can be solved by following modified process start method:

using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace ProcessTest
{
    public partial class Form1 : Form
    {
        [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint AssocQueryString(AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut);

        /*Modified Process.Start*/
        public static Process TrueProcessStart(string filename)
        {
            ProcessStartInfo psi;
            string ext = System.IO.Path.GetExtension(filename);//get extension

            var sb = new StringBuilder(500);//buffer for exe file path
            uint size = 500;//buffer size

            /*Get associated app*/
            uint res = AssocQueryString(AssocF.None, AssocStr.Executable, ext,null, sb, ref size);

            if (res != 0)
            {
                Debug.WriteLine("AssocQueryString returned error: " + res.ToString("X"));
                psi = new ProcessStartInfo(filename);//can't get app, use standard method
            }
            else
            {
                psi = new ProcessStartInfo(sb.ToString(), filename);
            }

            return Process.Start(psi);//actually start process
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string filename = "c:\\images\\clip.wmv";

            var myProc = TrueProcessStart(filename);
            if (myProc == null)
            {
                MessageBox.Show("Process can't be killed");
                return;
            }

            Thread.Sleep(5000);
            try
            {
                myProc.Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

    [Flags]
    enum AssocF : uint
    {
        None = 0,
        Init_NoRemapCLSID = 0x1,
        Init_ByExeName = 0x2,
        Open_ByExeName = 0x2,
        Init_DefaultToStar = 0x4,
        Init_DefaultToFolder = 0x8,
        NoUserSettings = 0x10,
        NoTruncate = 0x20,
        Verify = 0x40,
        RemapRunDll = 0x80,
        NoFixUps = 0x100,
        IgnoreBaseClass = 0x200,
        Init_IgnoreUnknown = 0x400,
        Init_FixedProgId = 0x800,
        IsProtocol = 0x1000,
        InitForFile = 0x2000,
    }

    enum AssocStr
    {
        Command = 1,
        Executable,
        FriendlyDocName,
        FriendlyAppName,
        NoOpen,
        ShellNewValue,
        DDECommand,
        DDEIfExec,
        DDEApplication,
        DDETopic,
        InfoTip,
        QuickTip,
        TileInfo,
        ContentType,
        DefaultIcon,
        ShellExtension,
        DropTarget,
        DelegateExecute,
        SupportedUriProtocols,
        Max,
    }

}

Here we get the file type's associated application via AssocQueryString. The returned value is then passed to ProcessStartInfo. However it does not always work, so we sometimes have to resort to standart method. For example, image files does not have any associated exe, it's just dll being loaded into explorer's process. So we can't outright kill process in this case.


来源: stackexchange

问:
Radiobutton only works on one form and other form can not
I am trying to modify the input style of the input type radio and I have the radio input in two different forms. but the radio input only works on the first form only while the second does not. I am still confused by the problem why not work on the second.

Please help me. Thanks in advance

ex : https://jsfiddle.net/devefrontend/vaqdsmjk/10/

```<code><input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
<label for="oneway">Oneway</label>
</code>```

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: '';
  width: 12px;
  height: 12px;
  background: #F87DA9;
  position: absolute;
  top: 4px;
  left: 4px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div role="tabpanel" class="tab-pane active" id="flights">
  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">
    <ul class="radio-list">
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
<div role="tabpanel" class="tab-pane" id="trains">
  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">
    <ul class="radio-list">
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div></code>```

答:
Id must be unique. So please give unique id in radio input.

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: '';
  width: 12px;
  height: 12px;
  background: #F87DA9;
  position: absolute;
  top: 3px;
  left: 3px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}
ul{
  list-style:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div role="tabpanel" class="tab-pane active" id="flights">
  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">
    <ul class="radio-list">
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
<div role="tabpanel" class="tab-pane" id="trains">
  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">
    <ul class="radio-list">
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="oneway2" value="oneway" checked="">
        <label for="oneway2">Oneway</label>
      </li>
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="return2" value="return">
        <label for="return2">Return</label>
      </li>
    </ul>
  </form>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to modify the input style of the input type radio and I have the radio input in two different forms. but the radio input only works on the first form only while the second does not. I am still confused by the problem why not work on the second.

Please help me. Thanks in advance

ex : https://jsfiddle.net/devefrontend/vaqdsmjk/10/

<input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
Oneway

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: '';
  width: 12px;
  height: 12px;
  background: #F87DA9;
  position: absolute;
  top: 4px;
  left: 4px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}

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

  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">

        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        Oneway

        <input type="radio" name="roundtrip" id="return" value="return">
        Return

  </form>

  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">

        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        Oneway

        <input type="radio" name="roundtrip" id="return" value="return">
        Return

  </form>

Body:
Id must be unique. So please give unique id in radio input.

[type="radio"]:checked,
[type="radio"]:not(:checked) {
  position: absolute;
  left: -9999px;
}

[type="radio"]:checked + label,
[type="radio"]:not(:checked) + label {
  position: relative;
  padding-left: 28px;
  cursor: pointer;
  line-height: 20px;
  display: inline-block;
  color: #666;
}

[type="radio"]:checked + label:before,
[type="radio"]:not(:checked) + label:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 18px;
  height: 18px;
  border: 1px solid #ddd;
  border-radius: 100%;
  background: #fff;
}

[type="radio"]:checked + label:after,
[type="radio"]:not(:checked) + label:after {
  content: '';
  width: 12px;
  height: 12px;
  background: #F87DA9;
  position: absolute;
  top: 3px;
  left: 3px;
  border-radius: 100%;
  -webkit-transition: all 0.2s ease;
  transition: all 0.2s ease;
}

[type="radio"]:not(:checked) + label:after {
  opacity: 0;
  -webkit-transform: scale(0);
  transform: scale(0);
}

[type="radio"]:checked + label:after {
  opacity: 1;
  -webkit-transform: scale(1);
  transform: scale(1);
}
ul{
  list-style:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div role="tabpanel" class="tab-pane active" id="flights">
  <form name="flight" method="GET" action="" id="searchFlights" class="form-inline">
    <ul class="radio-list">
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="oneway" value="oneway" checked="">
        <label for="oneway">Oneway</label>
      </li>
      <li id="radioFlights">
        <input type="radio" name="roundtrip" id="return" value="return">
        <label for="return">Return</label>
      </li>
    </ul>
  </form>
</div>
<div role="tabpanel" class="tab-pane" id="trains">
  <form name="train" method="GET" action="" id="searchTrains" class="form-inline">
    <ul class="radio-list">
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="oneway2" value="oneway" checked="">
        <label for="oneway2">Oneway</label>
      </li>
      <li id="radioTrains">
        <input type="radio" name="roundtrip" id="return2" value="return">
        <label for="return2">Return</label>
      </li>
    </ul>
  </form>
</div>


问:
How to have a line in Microsoft Word with multiple DIFFERENTLY formatted sections of text using vba
I'm trying to use a macro to expedite some LabVIEW code that needs to write a report automatically for a client, it needs to be formatted a certain way, though.  The issue I'm having is when I execute the code below with one format, and then execute it again using a different format, it reformats the previous line written, as well.  I've been able to solve this using a .TypeParagraph, but I don't always want a carriage return after a line of text is written to the document.  I've tried searching for how to break Word's selection, but have so far been unsuccessful.

Here's the code I'm executing:

```<code>Sub TextLineCreate(Text As String, Optional Style As String = "Title", Optional Bold As Boolean = True, Optional Italics As Boolean = False, Optional Underline As Boolean = False, Optional FontSize As Long = 16, Optional Alignment As String = "Center", Optional LineReturn As Long = 1)
'
' TextLineCreate Macro
' Creates a Formatted String with Text 'String'
'
Dim PreviousStyle As Style
Dim I As Long

Set PreviousStyle = Selection.Style ' Saves previous style configuration.

'Selection.EndKey Unit:=wdStory    ' Moves to the end of the document.

With Selection
    .Style = ActiveDocument.Styles(Style)

    Select Case (Alignment)
        Case ("Center"):
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
        Case ("Left"):
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
        Case ("Right"):
            .ParagraphFormat.Alignment = wdAlignParagraphRight
        Case Else
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
    End Select

    If (Underline) Then
        .Font.UnderlineColor = wdColorAutomatic
        .Font.Underline = wdUnderlineSingle
    Else
        .Font.Underline = wdUnderlineNone
    End If

    .Font.Bold = Bold               ' Sets the boldness

    If (Italics) Then
        .Font.Italic = True
    Else
        .Font.Italic = False
    End If
    ' Sets the Italicization

    .Font.Size = FontSize           ' Sets the font size.

    .TypeText Text:=Text

    .TypeParagraph

    If Bold Then .Font.Bold = False ' Restores previous bold setting
    .Style = PreviousStyle          ' Restores previous style configuration.

    For I = 1 To LineReturn
        .TypeParagraph                  ' Adds any desired white space
    Next I

End With

End Sub
</code>```

Here is a link to a picture of the problem: https://imgur.com/a/CEk4Q

Here is a link to a picture of the problem with the return characters visualized: https://imgur.com/a/NG0M8

[UPDATE] Okay, I've continued working on this, and I have narrowed down the problem

All I need to do, is to be able to produce one line of text that has a bold and underlined section title, and a normal text description after.  I have tried a couple different methods and even consulted my macro book for excel that has 1 chapter on automating excel. Here is the code that I have right now, along with pictures of what is happening upon execution.

```<code>Sub TextLineCreate(Text As String, _
               Optional Style As String = "Normal", _
               Optional Bold As Boolean = True, _
               Optional Italics As Boolean, _
               Optional Underline As Boolean, _
               Optional FontSize As Long = 16, _
               Optional Alignment As String, _
               Optional LineReturn As Long)

' TextLineCreate Macro
' Creates a Formatted String with Text 'String'

Dim Rng As Range
Dim TextRng As Range
Dim Align As Variant
Dim i As Long
Dim CharCount As Long
Dim StartIndex As Long
Dim EndIndex As Long

Set Rng = Selection.Range
With Rng

    .Style = ActiveDocument.Styles(Style)
    .Text = Text

    CharCount = ActiveDocument.Characters.Count                 ' Determines how many characters are on the sheet
    StartIndex = CharCount - Len(Text) - 1                          ' Determines the character index of where the Text's characters begin
    EndIndex = CharCount - 1                                    ' Determines the character index of where the Text's characters end

    Set TextRng = ActiveDocument.Range(StartIndex, EndIndex)    ' Determines the range of characters that the text will occupy
    TextRng.Select
    With Selection
        With .Font
            .Size = FontSize                                    ' Sets the font size
            .Bold = Bold                                        ' Sets the boldness
            .Italic = Italics                                   ' Sets the italics
            If (Underline) Then                                 ' Sets the Underline
                .UnderlineColor = wdColorAutomatic
                .Underline = wdUnderlineSingle
            Else
                .Underline = wdUnderlineNone
            End If
        End With
    End With

    Select Case (Alignment)
        Case ("Center"):
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
        Case ("Left"):
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
        Case ("Right"):
            .ParagraphFormat.Alignment = wdAlignParagraphRight
        Case Else
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
    End Select

    If LineReturn Then
        .Collapse wdCollapseEnd
        .Text = String(LineReturn, Chr(13)) ' Adds any desired white space
    End If

End With

Selection.EndKey Unit:=wdStory, Extend:=wdMove ' Moves to the end of the document.

End Sub

Sub HeaderTest()

TextLineCreate "Message:", Underline:=True, LineReturn:=0
TextLineCreate " Hello World", Style:="Normal", Bold:=False, FontSize:=12, LineReturn:=1

End Sub
</code>```

Updated Images: https://imgur.com/a/TQVYI

答:
```<code>Option Explicit

Enum Nft                        ' Index to Array 'Formats'
    NftPara
    NftFont
    NftNew = 0
    NftAlign
    NftSpace
    NftFontSize
    NftBold
    NftItalic
    NftUnderline
End Enum

Private Sub Call_InsertText()
    ' 03 Dec 2017

    ' ============================================================

    '   'InsertText' requires 2 arguments as follows.
    '   The two arguments are separated from each other by a comma.
    '   1. 'Text' is the text to be inserted.
    '      It must be provided but can be a null string.
    '   2. 'Arg' is a string, consisting of two parts as follows.
    '      A) Paragraph formatting codes
    '      B) Font formatting codes
    '      Either or both can be omitted but if part B is present
    '      it MUST be preceded by a semicolon,
    '      even if part A is omitted.

    ' ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    '   Formatting Codes can be partially or entirely omitted,
    '   can be written in any sequence, upper or lower case,
    '   with or without spaces between them.
    '   If omitted, no setting will be applied, for example,
    '   if Bold isn't specified the inserted text will not be bold,
    '   if no space is specified, no space will be added,
    '   if no new line is specified the text will be added to the
    '   last existing line.

    ' ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    '   Paragraph formatting codes
    '   - N = New paragraph (the text will be inserted in a new line)
    '   - L = Left (Default: text will be aligned at the left margin)
    '   - R = Right (text will be aligned at the right margin)
    '   - C = Centre (text will be aligned at the centre)
    '   - 1 = A multiple of 12 pt added above or below a paragraph.
    '         Can be positive or negative and include decimal fractions.
    '         The default = 0
    '         For example, 2.5 adds 2 and a half lines to the space already
    '         specified for insertion below the indicated paragraph,
    '         -0.5 reduces the space by half a line.
    '         If the space to be reduced is larger than available below the
    '         indicated paragraph, the space will be added above it.

    '   Paragraph formatting rules
    '   If N (=New paragraph) is specified the formatting will be applied
    '   to the new paragraph. Otherwise the format will be applied to
    '   the last existing paragraph. L, R or C will over-write previously
    '   specified settings. Specified space is added to existing.

    '   Font formatting codes
    '   - B = Bold (the default is Not Bold)
    '   - I = Italics (the default is Not Italic)
    '   - U = Underlined (Single line. The default is no underline)
    '   - 9 = A number expressing the font size.
    '         The default size is determined by the "Normal" style.

    '   Font formatting rules
    '   Font formatting is applied the the currently specified text.
    '   Formatting applied to previously inserted texts can't be changed
    '   by this program.

    '   Exception "Title"
    '   The program will apply the "Title" style to the first line in a document,
    '   formatting both the paragraph and the font with that style.
    '   Any different formatting specified for that line will over-ride
    '   the style's settings.
    '   The program will insert a new, blank line following the title, ignoring
    '   the N (= New line) instruction if given for the next line. If spacing
    '   use the spacing functinality for the paragraph format.

    '   Notes
    '   This program doesn't specify a font, for example, which is presumed to be
    '   the font provided by the "Normal" style. The "Normal" style is applied to
    '   all new paragraphs this program inserts.

    ' ============================================================

    ' Run the code below to create a new document using the specified formatting

    InsertText "Document title", "C ;iu 27"
    InsertText "First line", "N1.8;8i"              ' N will be ignored
    InsertText "Second line", "N"
    InsertText "Add Bold Large", "1.5;24Bi"
    InsertText "Add Tiny", "-1;6u"
    InsertText "Another line", "N"
    InsertText "Another new line, right aligned, without space", "NR;b"
    InsertText "Add a left aligned line", "Nl;iu"
End Sub

Sub InsertText(ByVal Text As String, _
               Optional ByVal Arg As String)
    ' 03 Dec 2017
    ' insert the specified text, in the specified format,
    ' at the end of the ActiveDocument

    ' TextLineCreate Macro
    ' Creates a Formatted String with String 'Text'

    Dim Formats() As Variant
    Dim Rng As Range
    Dim Para As Paragraph
    Dim Tmp As Single

    If GetArguments(Arg, Formats) Then
        Set Rng = ActiveDocument.Range
        With Rng
            .Collapse wdCollapseEnd
            Set Para = .Paragraphs(1)
            If .End <= 1 Then
                ' the document is blank:-
                ' insert the Text as Title and insert a blank paragraph below it
                .InsertParagraphBefore
                Set Para = .Paragraphs(1)
                Para.Style = "Title"
                .Collapse wdCollapseStart
            Else
                ' the 2nd para was inserted by the program together with the title
                If (ActiveDocument.Paragraphs.Count = 2) And _
                   (Len(Para.Range.Text) < 2) Then Formats(NftNew) = False
                If Formats(NftNew) = vbTrue Then
                    .InsertParagraphAfter
                    .Collapse wdCollapseEnd
                    Set Para = .Paragraphs(1)
                    Para.Style = wdStyleNormal
                End If
            End If

            ' add a space between components
            If (Len(Para.Range.Text) > 1) And _
               (Right(Para.Range.Text, 1) <> " ") And _
               (Asc(Text) <> 32) Then
               .InsertBefore " "
               .Collapse wdCollapseEnd
            End If
            .Text = Text

            With .Font                          ' format the Font
                If Formats(NftFontSize) <> wdUndefined Then
                    If .Size <> Formats(NftFontSize) Then .Size = Formats(NftFontSize)
                End If
                If Formats(NftBold) <> wdUndefined Then
                    If .Bold <> Formats(NftBold) Then .Bold = Formats(NftBold)
                End If
                If Formats(NftItalic) <> wdUndefined Then
                    If .Italic <> Formats(NftItalic) Then .Italic = Formats(NftItalic)
                End If
                If Formats(NftUnderline) <> wdUndefined Then
                    .UnderlineColor = wdColorAutomatic
                    .Underline = wdUnderlineSingle
                End If
            End With
        End With

        With Para                          ' format the paragraph
            If Formats(NftAlign) <> wdUndefined Then
                If .Alignment <> Formats(NftAlign) Then .Alignment = Formats(NftAlign)
            End If
            If Formats(NftSpace) <> wdUndefined Then
                Tmp = .SpaceAfter + Formats(NftSpace)
                If Tmp < 0 Then
                    .SpaceAfter = 0
                    .SpaceBefore = Abs(Tmp)
                Else
                    .SpaceAfter = Tmp
                End If
            End If
        End With
    End If
End Sub

Private Function GetArguments(ByVal Arg As String, _
                              Formats() As Variant) As Boolean
    ' 03 Dec 2017
    ' assign parameter values to Formats()
    ' return False if fault was found in Arg

    Dim Fun As Boolean                      ' function return value
    Dim Sp() As String                      ' split of Arg
    Dim Fmt() As Variant                    ' split of Sp
    Dim i As Long, n As Long

    ReDim Formats(NftUnderline)
    For i = LBound(Formats) To UBound(Formats)
        Formats(i) = wdUndefined
    Next i

    Arg = UCase(Replace(Arg, " ", ""))
    If Len(Arg) Then
        Sp = Split(Arg, ";")
    End If

    Fun = Not ((Not Sp) = -1)               ' not empty array
    If Fun Then
        ReDim Fmt(NftFont)
        For i = NftPara To NftFont
            If i <= UBound(Sp) Then
                Fmt(i) = SplitArg(Sp(i))
                n = 0
                Do While Len(Fmt(i)(n))
                    If IsNumeric(Fmt(i)(n)) Then
                        If i = NftPara Then
                            Formats(NftSpace) = Int(Val(Fmt(i)(n)) * 12)
                        Else
                            Formats(NftFontSize) = Val(Fmt(i)(n))
                        End If
                    Else
                        Select Case Fmt(i)(n)
                            Case "N"
                                Formats(NftNew) = vbTrue
                            Case "L", "C", "R"
                                Formats(NftAlign) = InStr("LCR", Fmt(i)(n)) - 1
                            Case "B"
                                Formats(NftBold) = vbTrue
                            Case "I"
                                Formats(NftItalic) = vbTrue
                            Case "U"
                                Formats(NftUnderline) = vbTrue
                            Case Else
                                MsgBox "The formatting argument """ & Fmt(i)(n) & _
                                       """ isn't recognised." & vbCr & _
                                       "Please review the instruction.", _
                                       vbInformation, "Invalid formatting code"
                                Fun = False
                                Exit Do
                        End Select
                    End If
                    n = n + 1
                    If n > UBound(Fmt(i)) Then Exit Do
                Loop
            End If
            If Not Fun Then Exit For
        Next i
    End If

    GetArguments = Fun
End Function

Private Function SplitArg(ByVal Arg As String) As Variant
    ' 03 Dec 2017

    Dim Fun() As String
    Dim Ch As String
    Dim i As Integer, n As Integer

    ReDim Fun(Len(Arg))
    For i = 1 To Len(Arg)
        Ch = Mid(Arg, i, 1)
        If IsNumeric(Ch) Or (InStr(".-", Ch) > 0) Then
            If Len(Fun(n)) Then
                If (Not IsNumeric(Fun(n))) And (Fun(n) <> ".") And _
                   (Fun(n) <> "-") And (Fun(n) <> "-.") Then n = n + 1
                End If
            Fun(n) = Fun(n) & Ch
        Else
            If Len(Fun(n)) Then n = n + 1
            Fun(n) = Ch
        End If
    Next i

    ReDim Preserve Fun(n)
    SplitArg = Fun
End Function
</code>```

Body:
I'm trying to use a macro to expedite some LabVIEW code that needs to write a report automatically for a client, it needs to be formatted a certain way, though.  The issue I'm having is when I execute the code below with one format, and then execute it again using a different format, it reformats the previous line written, as well.  I've been able to solve this using a .TypeParagraph, but I don't always want a carriage return after a line of text is written to the document.  I've tried searching for how to break Word's selection, but have so far been unsuccessful.

Here's the code I'm executing:

Sub TextLineCreate(Text As String, Optional Style As String = "Title", Optional Bold As Boolean = True, Optional Italics As Boolean = False, Optional Underline As Boolean = False, Optional FontSize As Long = 16, Optional Alignment As String = "Center", Optional LineReturn As Long = 1)
'
' TextLineCreate Macro
' Creates a Formatted String with Text 'String'
'
Dim PreviousStyle As Style
Dim I As Long

Set PreviousStyle = Selection.Style ' Saves previous style configuration.

'Selection.EndKey Unit:=wdStory    ' Moves to the end of the document.

With Selection
    .Style = ActiveDocument.Styles(Style)

    Select Case (Alignment)
        Case ("Center"):
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
        Case ("Left"):
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
        Case ("Right"):
            .ParagraphFormat.Alignment = wdAlignParagraphRight
        Case Else
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
    End Select

    If (Underline) Then
        .Font.UnderlineColor = wdColorAutomatic
        .Font.Underline = wdUnderlineSingle
    Else
        .Font.Underline = wdUnderlineNone
    End If

    .Font.Bold = Bold               ' Sets the boldness

    If (Italics) Then
        .Font.Italic = True
    Else
        .Font.Italic = False
    End If
    ' Sets the Italicization

    .Font.Size = FontSize           ' Sets the font size.

    .TypeText Text:=Text

    .TypeParagraph

    If Bold Then .Font.Bold = False ' Restores previous bold setting
    .Style = PreviousStyle          ' Restores previous style configuration.

    For I = 1 To LineReturn
        .TypeParagraph                  ' Adds any desired white space
    Next I

End With

End Sub

Here is a link to a picture of the problem: https://imgur.com/a/CEk4Q

Here is a link to a picture of the problem with the return characters visualized: https://imgur.com/a/NG0M8

[UPDATE] Okay, I've continued working on this, and I have narrowed down the problem

All I need to do, is to be able to produce one line of text that has a bold and underlined section title, and a normal text description after.  I have tried a couple different methods and even consulted my macro book for excel that has 1 chapter on automating excel. Here is the code that I have right now, along with pictures of what is happening upon execution.

Sub TextLineCreate(Text As String, _
               Optional Style As String = "Normal", _
               Optional Bold As Boolean = True, _
               Optional Italics As Boolean, _
               Optional Underline As Boolean, _
               Optional FontSize As Long = 16, _
               Optional Alignment As String, _
               Optional LineReturn As Long)

' TextLineCreate Macro
' Creates a Formatted String with Text 'String'

Dim Rng As Range
Dim TextRng As Range
Dim Align As Variant
Dim i As Long
Dim CharCount As Long
Dim StartIndex As Long
Dim EndIndex As Long

Set Rng = Selection.Range
With Rng

    .Style = ActiveDocument.Styles(Style)
    .Text = Text

    CharCount = ActiveDocument.Characters.Count                 ' Determines how many characters are on the sheet
    StartIndex = CharCount - Len(Text) - 1                          ' Determines the character index of where the Text's characters begin
    EndIndex = CharCount - 1                                    ' Determines the character index of where the Text's characters end

    Set TextRng = ActiveDocument.Range(StartIndex, EndIndex)    ' Determines the range of characters that the text will occupy
    TextRng.Select
    With Selection
        With .Font
            .Size = FontSize                                    ' Sets the font size
            .Bold = Bold                                        ' Sets the boldness
            .Italic = Italics                                   ' Sets the italics
            If (Underline) Then                                 ' Sets the Underline
                .UnderlineColor = wdColorAutomatic
                .Underline = wdUnderlineSingle
            Else
                .Underline = wdUnderlineNone
            End If
        End With
    End With

    Select Case (Alignment)
        Case ("Center"):
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
        Case ("Left"):
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
        Case ("Right"):
            .ParagraphFormat.Alignment = wdAlignParagraphRight
        Case Else
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
    End Select

    If LineReturn Then
        .Collapse wdCollapseEnd
        .Text = String(LineReturn, Chr(13)) ' Adds any desired white space
    End If

End With

Selection.EndKey Unit:=wdStory, Extend:=wdMove ' Moves to the end of the document.

End Sub

Sub HeaderTest()

TextLineCreate "Message:", Underline:=True, LineReturn:=0
TextLineCreate " Hello World", Style:="Normal", Bold:=False, FontSize:=12, LineReturn:=1

End Sub

Updated Images: https://imgur.com/a/TQVYI


问:
Django ImportError at /graphql
Just can't understand what's wrong at all: Could not import 'ss.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: type object 'Query' has no attribute '_meta'.

This is my Query class in application file "pages.schema.py":

```<code>class Query(graphene.AbstractType):
    user = graphene.relay.Node.Field(UserNode)
    users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter)
</code>```

This is the full content of root schema file "ss.schema.py::

```<code>import graphene

import pages.schema

class Query(pages.schema.Query, graphene.ObjectType):
    pass

class Mutation(pages.schema.Mutation, graphene.ObjectType):
    pass

schema = graphene.Schema(query=Query, mutation=Mutation)
</code>```

And here is full traceback:

```<code>Environment:

Request Method: GET
Request URL: http://95.213.203.11/graphql

Django Version: 1.11.5
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'corsheaders',
 'ws4redis',
 'graphene_django',
 'pages']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in import_from_string
  74.         module = importlib.import_module(module_path)

File "/root/ss/lib/python3.5/importlib/__init__.py" in import_module
  126.     return _bootstrap._gcd_import(name[level:], package, level)

File "./ss/schema.py" in <module>
  3. import pages.schema

File "./pages/schema.py" in <module>
  130. schema = graphene.Schema(query=Query, mutation=Mutation)

File "/root/ss/lib/python3.5/site-packages/graphene/types/schema.py" in __init__
  27.         ).format(query)

File "/root/ss/lib/python3.5/site-packages/graphene/utils/subclass_with_meta.py" in __repr__
  11.         return cls._meta.name

During handling of the above exception (type object 'Query' has no attribute '_meta'), another exception occurred:

File "/root/ss/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/root/ss/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/root/ss/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/root/ss/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/root/ss/lib/python3.5/site-packages/django/views/generic/base.py" in view
  62.             self = cls(**initkwargs)

File "/root/ss/lib/python3.5/site-packages/graphene_django/views.py" in __init__
  70.             schema = graphene_settings.SCHEMA

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in __getattr__
  116.             val = perform_import(val, attr)

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in perform_import
  60.         return import_from_string(val, setting_name)

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in import_from_string
  78.         raise ImportError(msg)

Exception Type: ImportError at /graphql
Exception Value: Could not import 'ss.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: type object 'Query' has no attribute '_meta'.
</code>```

Any suggestions how to fix it?

答:
The ease with which Graphene (and similar frameworks like Django and SQLAlchemy) let us build our
schema and incorporate program logic, without having to write a lot of boilerplate, has a dark side:
quite often the error messages and backtraces that they give do little to point us toward the actual
error.

Such is the case here. There's nothing wrong with you ss/schema.py, the problem has to be in
pages/schema.py. Since you've given us so little of that, I can't tell what, but here is slightly
fleshed-out example, based on your code, that works in Graphene 2.0:

ss/schema.py:

```<code>import graphene

import pages.schema

class Query(pages.schema.Query, graphene.ObjectType):
    pass

#class Mutation(pages.schema.Mutation, graphene.ObjectType):
#    pass

#schema = graphene.Schema(query=Query, mutation=Mutation)
schema = graphene.Schema(query=Query)
</code>```

pages/models.py:

```<code>from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
</code>```

pages/schema.py:

```<code>from django_filters import FilterSet
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

from .models import User

class UserNode(DjangoObjectType):
    class Meta:
        model = User
        interfaces = (relay.Node, )

class UserFilter(FilterSet):
    class Meta:
        model = User
        fields = ['name']

class Query(object):
    user = relay.Node.Field(UserNode)
    users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter)
</code>```

Tested with the following query:

```<code>{
  users {
    edges {
      node {
        id
        ... on UserNode {
          name
        }
      }
    }
  }
}
</code>```

Hopefully something in there will point you in the right direction. If not, please post more of your pages/schema.py, and we'll go from there.

Title: Django ImportError at /graphql

Body:
Just can't understand what's wrong at all: Could not import 'ss.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: type object 'Query' has no attribute '_meta'.

This is my Query class in application file "pages.schema.py":

class Query(graphene.AbstractType):
    user = graphene.relay.Node.Field(UserNode)
    users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter)

This is the full content of root schema file "ss.schema.py::

import graphene

import pages.schema

class Query(pages.schema.Query, graphene.ObjectType):
    pass

class Mutation(pages.schema.Mutation, graphene.ObjectType):
    pass

schema = graphene.Schema(query=Query, mutation=Mutation)

And here is full traceback:

Environment:

Request Method: GET
Request URL: http://95.213.203.11/graphql

Django Version: 1.11.5
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'corsheaders',
 'ws4redis',
 'graphene_django',
 'pages']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in import_from_string
  74.         module = importlib.import_module(module_path)

File "/root/ss/lib/python3.5/importlib/__init__.py" in import_module
  126.     return _bootstrap._gcd_import(name[level:], package, level)

File "./ss/schema.py" in <module>
  3. import pages.schema

File "./pages/schema.py" in <module>
  130. schema = graphene.Schema(query=Query, mutation=Mutation)

File "/root/ss/lib/python3.5/site-packages/graphene/types/schema.py" in __init__
  27.         ).format(query)

File "/root/ss/lib/python3.5/site-packages/graphene/utils/subclass_with_meta.py" in __repr__
  11.         return cls._meta.name

During handling of the above exception (type object 'Query' has no attribute '_meta'), another exception occurred:

File "/root/ss/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/root/ss/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/root/ss/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/root/ss/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/root/ss/lib/python3.5/site-packages/django/views/generic/base.py" in view
  62.             self = cls(**initkwargs)

File "/root/ss/lib/python3.5/site-packages/graphene_django/views.py" in __init__
  70.             schema = graphene_settings.SCHEMA

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in __getattr__
  116.             val = perform_import(val, attr)

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in perform_import
  60.         return import_from_string(val, setting_name)

File "/root/ss/lib/python3.5/site-packages/graphene_django/settings.py" in import_from_string
  78.         raise ImportError(msg)

Exception Type: ImportError at /graphql
Exception Value: Could not import 'ss.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: type object 'Query' has no attribute '_meta'.

Any suggestions how to fix it?

Body:
The ease with which Graphene (and similar frameworks like Django and SQLAlchemy) let us build our
schema and incorporate program logic, without having to write a lot of boilerplate, has a dark side:
quite often the error messages and backtraces that they give do little to point us toward the actual
error.

Such is the case here. There's nothing wrong with you ss/schema.py, the problem has to be in
pages/schema.py. Since you've given us so little of that, I can't tell what, but here is slightly
fleshed-out example, based on your code, that works in Graphene 2.0:

ss/schema.py:

import graphene

import pages.schema

class Query(pages.schema.Query, graphene.ObjectType):
    pass

#class Mutation(pages.schema.Mutation, graphene.ObjectType):
#    pass

#schema = graphene.Schema(query=Query, mutation=Mutation)
schema = graphene.Schema(query=Query)

pages/models.py:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)

pages/schema.py:

from django_filters import FilterSet
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

from .models import User

class UserNode(DjangoObjectType):
    class Meta:
        model = User
        interfaces = (relay.Node, )

class UserFilter(FilterSet):
    class Meta:
        model = User
        fields = ['name']

class Query(object):
    user = relay.Node.Field(UserNode)
    users = DjangoFilterConnectionField(UserNode, filterset_class=UserFilter)

Tested with the following query:

{
  users {
    edges {
      node {
        id
        ... on UserNode {
          name
        }
      }
    }
  }
}

Hopefully something in there will point you in the right direction. If not, please post more of your pages/schema.py, and we'll go from there.


问:
Primary key for a table where DATETIME col is used for almost all SELECT operations
I'm wondering what kind of PK I should be choosing for this table in MySQL. Almost all the SELECT operations will involve the DATETIME (date ranges, a specific date, etc.).

Is there a best practice for this?

答: Choose an autonumber in order to be on the safe side. You could have two or more rows with the same datetime.</p>

ContentLicense: CC BY-SA 2.5


问:
Cordova Firebase Social OAuth Not Utilizing Browser Sessions
In my Cordova/Angular/Firebase app, the social login redirect pages keep requiring me to enter credentials for the social platform, even though I'm logged in for these sites in Safari already.

I recently upgraded my Cordova app to AngularFire 2.x.x and Firebase 4.x.x and I'm trying to implement the social login functionality as described here: https://firebase.google.com/docs/auth/web/cordova

When I test on-device, the login opens in what looks like a Safari View Controller, but for Facebook, Twitter, & Google login, the pages require re-entering credentials. I was under the impression that the Safari View Controller would reuse session data from the Safari app itself. Is that incorrect?

答:
The comment by @bojeil above led me to this documentation:

https://blog.branch.io/ios-11-safari-view-controller-cookie-passthrough-and-the-future-of-mobile-web/

This is new expected behavior in iOS 11.


问:
Unable to get my three.js scene when deployed through react.js
I have been trying to setup my plain JavaScript three.js scene by loading .obj and .mtl files using ReactJS.

However, I'm facing an issue while loading .obj and .mtl files using  Facebook's create-react-app boilerplate.  It always throws an error stating:

unexpected line <!DOCTYPE html>

I have tried:

loading the scripts tags from componentWillMount.

importing the three.js scene and its associated files in the same folder.

答: Try to load the script tags from componentDidMount? Maybe when componentWillMount is executing, the element which your renderer.domElement will append to is not mounted yet.


问:
JSP send DTO file along with jsp modelAttribute to spring in Jquery
here am trying to send my form modelAttribute along with DTO file to spring controller, but the DTO is null in controller.
Actually my modelAttribute 'myForm' contains field values and along with I need to send few more data to controller hence instead of sending individually I set the values in DTO file and send it. Can you please help me on this. Thanks in Advance. Below are my code details,

```<code><form:form name="myForm" modelAttribute="item">

var values = $("#item").serialize();
var dto = $("customDto").serialize();
    dto = {
        type : "New Item",
        userId : userId,
        status : "New",
    };

    $.ajax({
        type : "post",
        data : values + "&dto=" + dto,
        url : "/myApp/submit.do",
        success : function(msg) {
            jQuery("#msg").html("Form submitted");
        }
    });
</code>```

Spring Controller:

```<code>@RequestMapping(value = "/submit")
public ModelAndView submitForm(
    @ModelAttribute("item") Item item,@ModelAttribute("dto") CustomDto customDto) {
    //Logic
  return model;
}
</code>```

答:
Use one ModelAttribute, For this create a mapper class
with the 2 objects inside (item and DTO), then put modelattribute for this mapper

```<code>     @RequestMapping(value = "/submit")
                    public ModelAndView submitForm(
                            @ModelAttribute MapperClass mapper) {
        ...

                    }

      Class MapperClass {
        //Put all fields here which is sending from UI to controller

    private Item item;
private CustomDto customDto;
//create getters and setters

        }
</code>```

Body:
here am trying to send my form modelAttribute along with DTO file to spring controller, but the DTO is null in controller.
Actually my modelAttribute 'myForm' contains field values and along with I need to send few more data to controller hence instead of sending individually I set the values in DTO file and send it. Can you please help me on this. Thanks in Advance. Below are my code details,

<form:form name="myForm" modelAttribute="item">

var values = $("#item").serialize();
var dto = $("customDto").serialize();
    dto = {
        type : "New Item",
        userId : userId,
        status : "New",
    };

    $.ajax({
        type : "post",
        data : values + "&dto=" + dto,
        url : "/myApp/submit.do",
        success : function(msg) {
            jQuery("#msg").html("Form submitted");
        }
    });

Spring Controller:

@RequestMapping(value = "/submit")
public ModelAndView submitForm(
    @ModelAttribute("item") Item item,@ModelAttribute("dto") CustomDto customDto) {
    //Logic
  return model;
}

Body:
Use one ModelAttribute, For this create a mapper class
with the 2 objects inside (item and DTO), then put modelattribute for this mapper

     @RequestMapping(value = "/submit")
                    public ModelAndView submitForm(
                            @ModelAttribute MapperClass mapper) {
        ...

                    }

      Class MapperClass {
        //Put all fields here which is sending from UI to controller

    private Item item;
private CustomDto customDto;
//create getters and setters

        }


问:
How to remove item from an array on condition using JavaScript
I have an an array which is mentioned below. I would like to remove an item from the array which has empty property value using JavaScript.

Actual array:

```<code>[
    {
        "href":"/client",
        "methods":[]
    },
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/about",
        "methods":[]
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]
</code>```

Expecting result:

```<code>[
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]
</code>```

答:
In the case of methods, you can easily walk the object and then call delete on the keys with values that are empty.... or empty arrays.  I expanded the answer to cover not only keys of methods where an array is empty, but all keys with what i would define as empty contents.

```<code>var l = [];
for (var i = 0; i < l.length; i++){
  var keys = Object.keys(l[i]);
  for ( var j = 0; j < keys.length; j++){
    var value = keys[j];
    // In your use case, you are only doing arrays so i coded it as such.
    if (value.length == 0){
      delete l[i][j];
    }
  }
}
</code>```

If you want to expand it to cover a variety of cases such as empty string, empty arrays, empty maps, or null values you can defined a function to do that.

```<code>function isValueDeletable(value){
  if (value == null) return true;
  if (value == "") return true;
  if (value instanceof Array && value.length == 0) return true;
  if (value instanceof Map && Object.keys(value).length == 0) return true;
  return false;
}
</code>```

and apply that instead of the value.length == 0;

```<code>if (isValueDeletable(value)){ delete l[i][j]; }
</code>```

Then l is modified to remove all keys with empty values.

Body:
I have an an array which is mentioned below. I would like to remove an item from the array which has empty property value using JavaScript.

Actual array:

[
    {
        "href":"/client",
        "methods":[]
    },
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/about",
        "methods":[]
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]

Expecting result:

[
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]

Body:
In the case of methods, you can easily walk the object and then call delete on the keys with values that are empty.... or empty arrays.  I expanded the answer to cover not only keys of methods where an array is empty, but all keys with what i would define as empty contents.

var l = [];
for (var i = 0; i < l.length; i++){
  var keys = Object.keys(l[i]);
  for ( var j = 0; j < keys.length; j++){
    var value = keys[j];
    // In your use case, you are only doing arrays so i coded it as such.
    if (value.length == 0){
      delete l[i][j];
    }
  }
}

If you want to expand it to cover a variety of cases such as empty string, empty arrays, empty maps, or null values you can defined a function to do that.

function isValueDeletable(value){
  if (value == null) return true;
  if (value == "") return true;
  if (value instanceof Array && value.length == 0) return true;
  if (value instanceof Map && Object.keys(value).length == 0) return true;
  return false;
}

and apply that instead of the value.length == 0;

if (isValueDeletable(value)){ delete l[i][j]; }

Then l is modified to remove all keys with empty values.


问:
Formatting City/State Information
I have an application which stores the user's home town, state, and country. I don't particularly need to do validation; no other part of the application relies on the data, but I would like the formatting to be consistent for vanity and to avoid later having "North Carolina", "NC", "north carolina" and so forth all in the database.

Does anyone know of a way to pass Bing maps (I would prefer Bing over Google since I've been using it on this project thus far) a search string and get given back an object with the address as interpreted by the service? (i.e. pass in "charlotte, nc" and be given back "Charlotte, North Carolina, United States")

I've looked at VEPlace (on MSDN), but I'm not sure how to ensure I get back the format I'm hoping for from the Name attribute. Anyone have an idea on how best to go about this?

Also, the back-end for the project is ASP.NET MVC, so if there's a way to do it in C# that involves a controller or something similar that's totally fine.

答:
I suspect that you will need to do the following:

Query Bing / Google maps to get the lat / lng for the city.

Use reverse geocode look up of the lat/lng to get a consistent naming convention. (looks like you found this already. here is a link using this: http://blog.bobcravens.com/2011/01/a-windows-phone-7-trip-recorder/)

If you broke it down like this, you may want to seed your #1 with the lat/lng you get from the browser's geolocation api.

Bob

Title: Formatting City/State Information


问:
While trying to post mptt model via django rest framework getting ValueError: Cannot use None as a query value
Here is the view I'm trying to write tests for:

```<code>class RestaurantsTreeView(generics.ListCreateAPIView):
    serializer_class = RestarauntsTreeSerializer

    def get_serializer_class(self):
        from rest_framework import serializers
        if self.request.method == 'GET':
            return RestarauntsTreeSerializer
        parent_choices = self.request.user.restaurants_set.filter(status=Restaurants.VISIBLE)

        class NestedRestaurantDetailSerializer(serializers.ModelSerializer):
            parent_id = serializers.RelatedField(queryset=parent_choices, allow_null=True, required=False)

            class Meta:
                model = Restaurants
                fields = ("id", "name", "parent_id")

        return NestedRestaurantDetailSerializer
</code>```

Here is the model I'm trying to create via POST request:

```<code>from mptt.models import MPTTModel, TreeForeignKey

class Restaurants(MPTTModel):
    name = models.CharField(max_length=255, blank=True, null=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

    class MPTTMeta:
        order_insertion_by = ['name']

    def __str__(self):
        return self.name
</code>```

And finally my test:

```<code>class CreateRestaurantTestCase(TestCase):
    def setUp(self):
        self.user = UserFactory.create()
        self.user.user_permissions.add(Permission.objects.get(codename='add_restaurants'))
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)

    def test_authorization_required(self):
        response = self.client.post(reverse('api_v1:restaurants_list'), data={
            "parent_id": None,
            "name": "fake restaurant",
        })
        self.assertEqual(response.status_code, 401)
</code>```

that returns that error:

```<code>Error
Traceback (most recent call last):
  File "project/cafe/tests/api/test_restaurants.py", line 26, in test_required_fields
    response = self.client.post(reverse('api_v1:restaurants_list'), data={})
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 299, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post
    return self.generic('POST', path, data, content_type, **extra)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 237, in generic
    method, path, data, content_type, secure, **extra)
  File "env/lib/python3.5/site-packages/django/test/client.py", line 416, in generic
    return self.request(**r)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 288, in request
    return super(APIClient, self).request(**kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 240, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "env/lib/python3.5/site-packages/django/test/client.py", line 501, in request
    six.reraise(*exc_info)
  File "env/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
    raise value
  File "env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "env/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "env/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "env/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "env/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/generics.py", line 244, in post
    return self.create(request, *args, **kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/mixins.py", line 21, in create
    self.perform_create(serializer)
  File "env/lib/python3.5/site-packages/rest_framework/mixins.py", line 26, in perform_create
    serializer.save()
  File "env/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "env/lib/python3.5/site-packages/rest_framework/serializers.py", line 913, in create
    instance = ModelClass.objects.create(**validated_data)
  File "env/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "env/lib/python3.5/site-packages/django/db/models/query.py", line 394, in create
    obj.save(force_insert=True, using=self.db)
  File "env/lib/python3.5/site-packages/mptt/models.py", line 977, in save
    right_sibling = opts.get_ordered_insertion_target(self, parent)
  File "env/lib/python3.5/site-packages/mptt/models.py", line 216, in get_ordered_insertion_target
    queryset = node.__class__._tree_manager.db_manager(node._state.db).filter(filters).order_by(*order_by)
  File "env/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "env/lib/python3.5/site-packages/django/db/models/query.py", line 784, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "env/lib/python3.5/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1250, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1270, in _add_q
    current_negated, allow_joins, split_subq)
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1160, in build_filter
    value, lookups, used_joins = self.prepare_lookup_value(value, lookups, can_reuse, allow_joins)
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 989, in prepare_lookup_value
    raise ValueError("Cannot use None as a query value")
ValueError: Cannot use None as a query value

Destroying test database for alias 'default'...

Process finished with exit code 1
</code>```

I want to be able to create restaurant with null parent field. It can be post without parent field or with nulled parent field. Thanks
django 1.11, drf 3.7, mptt 0.8.7

答:
Firstly, the fact that you place your serializer definition inside the view make your code not quite readable... You can modify the queryset of your parent_id field while overriding the get_serializer method in your view.

```<code># serializers.py
from rest_framework import serializers

class NestedRestaurantDetailSerializer(serializers.ModelSerializer):
    # We don't care about filtering the queryset here, we override it in the view
    parent_id = serializers.RelatedField(queryset=Restaurant.objects.all(), allow_null=True, required=False)

    class Meta:
        model = Restaurants
        fields = ("id", "name", "parent_id")

# views.py
from .serializers import (
    RestaurantsTreeSerializer,
    NestedRestaurantDetailSerializer
)

class RestaurantsTreeView(generics.ListCreateAPIView):
    def get_serializer(self, *args, **kwargs):
        if self.request.method == 'GET':
            kwargs['context'] = self.get_serializer_context()
            return RestaurantsTreeSerializer(*args, **kwargs)
        else:
            kwargs['context'] = self.get_serializer_context()
            nested_serializer = NestedRestaurantDetailSerializer(*args, **kwargs)

            # Here we modify the queryset of the `parent_id` field
            nested_serializer.fields['parent_id'].queryset = self.request.user.restaurants_set.filter(status=Restaurants.VISIBLE)

            return nested_serializer
</code>```

Secondly, concerning your exception, in the documentation of django-mptt, you can read the following:

order_insertion_by

A list of field names which should define ordering when new tree nodes are being inserted or existing nodes are being reparented, with the most significant ordering field name first. Defaults to [].

It is assumed that any field identified as defining ordering will never be NULL in the database.

The important line is above. In your model definition, you have:

```<code>name = models.CharField(max_length=255, blank=True, null=True)
</code>```

You define a nullable field as the parameter for the order_insertion_by attribute. The fact that your final exception is Cannot use None as a query value make me think it's linked...

The code of the test method at the origin of your exception is not shown, but I assume with a name like test_required_fields that you try to send an empty name parameter to your enpoint. Hence the Cannot use None as a query value. Since you defined your name field as nullable in your model, your serializer mark it at nullable too.

Body:
Here is the view I'm trying to write tests for:

class RestaurantsTreeView(generics.ListCreateAPIView):
    serializer_class = RestarauntsTreeSerializer

    def get_serializer_class(self):
        from rest_framework import serializers
        if self.request.method == 'GET':
            return RestarauntsTreeSerializer
        parent_choices = self.request.user.restaurants_set.filter(status=Restaurants.VISIBLE)

        class NestedRestaurantDetailSerializer(serializers.ModelSerializer):
            parent_id = serializers.RelatedField(queryset=parent_choices, allow_null=True, required=False)

            class Meta:
                model = Restaurants
                fields = ("id", "name", "parent_id")

        return NestedRestaurantDetailSerializer

Here is the model I'm trying to create via POST request:

from mptt.models import MPTTModel, TreeForeignKey

class Restaurants(MPTTModel):
    name = models.CharField(max_length=255, blank=True, null=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

    class MPTTMeta:
        order_insertion_by = ['name']

    def __str__(self):
        return self.name

And finally my test:

class CreateRestaurantTestCase(TestCase):
    def setUp(self):
        self.user = UserFactory.create()
        self.user.user_permissions.add(Permission.objects.get(codename='add_restaurants'))
        self.client = APIClient()
        self.client.force_authenticate(user=self.user)

    def test_authorization_required(self):
        response = self.client.post(reverse('api_v1:restaurants_list'), data={
            "parent_id": None,
            "name": "fake restaurant",
        })
        self.assertEqual(response.status_code, 401)

that returns that error:

Error
Traceback (most recent call last):
  File "project/cafe/tests/api/test_restaurants.py", line 26, in test_required_fields
    response = self.client.post(reverse('api_v1:restaurants_list'), data={})
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 299, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post
    return self.generic('POST', path, data, content_type, **extra)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 237, in generic
    method, path, data, content_type, secure, **extra)
  File "env/lib/python3.5/site-packages/django/test/client.py", line 416, in generic
    return self.request(**r)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 288, in request
    return super(APIClient, self).request(**kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/test.py", line 240, in request
    request = super(APIRequestFactory, self).request(**kwargs)
  File "env/lib/python3.5/site-packages/django/test/client.py", line 501, in request
    six.reraise(*exc_info)
  File "env/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
    raise value
  File "env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "env/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "env/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "env/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "env/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/views.py", line 489, in dispatch
    response = self.handle_exception(exc)
  File "env/lib/python3.5/site-packages/rest_framework/views.py", line 449, in handle_exception
    self.raise_uncaught_exception(exc)
  File "env/lib/python3.5/site-packages/rest_framework/views.py", line 486, in dispatch
    response = handler(request, *args, **kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/generics.py", line 244, in post
    return self.create(request, *args, **kwargs)
  File "env/lib/python3.5/site-packages/rest_framework/mixins.py", line 21, in create
    self.perform_create(serializer)
  File "env/lib/python3.5/site-packages/rest_framework/mixins.py", line 26, in perform_create
    serializer.save()
  File "env/lib/python3.5/site-packages/rest_framework/serializers.py", line 214, in save
    self.instance = self.create(validated_data)
  File "env/lib/python3.5/site-packages/rest_framework/serializers.py", line 913, in create
    instance = ModelClass.objects.create(**validated_data)
  File "env/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "env/lib/python3.5/site-packages/django/db/models/query.py", line 394, in create
    obj.save(force_insert=True, using=self.db)
  File "env/lib/python3.5/site-packages/mptt/models.py", line 977, in save
    right_sibling = opts.get_ordered_insertion_target(self, parent)
  File "env/lib/python3.5/site-packages/mptt/models.py", line 216, in get_ordered_insertion_target
    queryset = node.__class__._tree_manager.db_manager(node._state.db).filter(filters).order_by(*order_by)
  File "env/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "env/lib/python3.5/site-packages/django/db/models/query.py", line 784, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "env/lib/python3.5/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1250, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1270, in _add_q
    current_negated, allow_joins, split_subq)
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1276, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1160, in build_filter
    value, lookups, used_joins = self.prepare_lookup_value(value, lookups, can_reuse, allow_joins)
  File "env/lib/python3.5/site-packages/django/db/models/sql/query.py", line 989, in prepare_lookup_value
    raise ValueError("Cannot use None as a query value")
ValueError: Cannot use None as a query value

Destroying test database for alias 'default'...

Process finished with exit code 1

I want to be able to create restaurant with null parent field. It can be post without parent field or with nulled parent field. Thanks
django 1.11, drf 3.7, mptt 0.8.7

Body:
Firstly, the fact that you place your serializer definition inside the view make your code not quite readable... You can modify the queryset of your parent_id field while overriding the get_serializer method in your view.

# serializers.py
from rest_framework import serializers

class NestedRestaurantDetailSerializer(serializers.ModelSerializer):
    # We don't care about filtering the queryset here, we override it in the view
    parent_id = serializers.RelatedField(queryset=Restaurant.objects.all(), allow_null=True, required=False)

    class Meta:
        model = Restaurants
        fields = ("id", "name", "parent_id")

# views.py
from .serializers import (
    RestaurantsTreeSerializer,
    NestedRestaurantDetailSerializer
)

class RestaurantsTreeView(generics.ListCreateAPIView):
    def get_serializer(self, *args, **kwargs):
        if self.request.method == 'GET':
            kwargs['context'] = self.get_serializer_context()
            return RestaurantsTreeSerializer(*args, **kwargs)
        else:
            kwargs['context'] = self.get_serializer_context()
            nested_serializer = NestedRestaurantDetailSerializer(*args, **kwargs)

            # Here we modify the queryset of the `parent_id` field
            nested_serializer.fields['parent_id'].queryset = self.request.user.restaurants_set.filter(status=Restaurants.VISIBLE)

            return nested_serializer

Secondly, concerning your exception, in the documentation of django-mptt, you can read the following:

order_insertion_by

A list of field names which should define ordering when new tree nodes are being inserted or existing nodes are being reparented, with the most significant ordering field name first. Defaults to [].

It is assumed that any field identified as defining ordering will never be NULL in the database.

The important line is above. In your model definition, you have:

name = models.CharField(max_length=255, blank=True, null=True)

You define a nullable field as the parameter for the order_insertion_by attribute. The fact that your final exception is Cannot use None as a query value make me think it's linked...

The code of the test method at the origin of your exception is not shown, but I assume with a name like test_required_fields that you try to send an empty name parameter to your enpoint. Hence the Cannot use None as a query value. Since you defined your name field as nullable in your model, your serializer mark it at nullable too.


问:
How can I randomly choosing elements in character vector in R?
I want to choose elements randomly in character vector in R.

For example,
I have character vector including 36 alphabets.

```<code>f <- c('A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','f','g','h','i','j','k')
</code>```

I want to make random sampling in this character vector.
What I want to make as a result is like below.

```<code>     [,1]   [,2]   [,3]
 [1,] "a" "B" "C"
 [2,] "D" "E" "F"
 [3,] "H" "I" "J"
 [4,] "K" "L" "M"
         ...
[12,] "Z" "c" "m"
</code>```

The point is that I want to randomly select alphabets without replacement, and make matrix like above using chosen alphabets

```<code>i <- 1
a <- matrix(0,12,3)

for(i in 1:12){
    a_temp <- sample(f,3)

    while(any(a_temp==a)){
    idx <- which(f %in% a_temp)
    f <- f[-idx]
    a_temp <- sample(f,3)
    }
    a[i,] <- a_temp
    i+1
 }

> a
      [,1] [,2] [,3]
 [1,] "D"  "A"  "G"
 [2,] "S"  "f"  "W"
 [3,] "M"  "Q"  "O"
 [4,] "M"  "D"  "U"
 [5,] "K"  "C"  "F"
 [6,] "E"  "O"  "b"
 [7,] "h"  "V"  "c"
 [8,] "N"  "j"  "k"
 [9,] "j"  "a"  "R"
[10,] "B"  "H"  "f"
[11,] "L"  "i"  "A"
[12,] "E"  "R"  "X"
</code>```

However, I could only get the matrix which include duplicated alphabet.

(What I mean is that I want to make all of alphabets have eqaul opportunity to be chosen only once)

Body:
I want to choose elements randomly in character vector in R.

For example,
I have character vector including 36 alphabets.

f <- c('A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','f','g','h','i','j','k')

I want to make random sampling in this character vector.
What I want to make as a result is like below.

     [,1]   [,2]   [,3]
 [1,] "a" "B" "C"
 [2,] "D" "E" "F"
 [3,] "H" "I" "J"
 [4,] "K" "L" "M"
         ...
[12,] "Z" "c" "m"

The point is that I want to randomly select alphabets without replacement, and make matrix like above using chosen alphabets

i <- 1
a <- matrix(0,12,3)

for(i in 1:12){
    a_temp <- sample(f,3)

    while(any(a_temp==a)){
    idx <- which(f %in% a_temp)
    f <- f[-idx]
    a_temp <- sample(f,3)
    }
    a[i,] <- a_temp
    i+1
 }

> a
      [,1] [,2] [,3]
 [1,] "D"  "A"  "G"
 [2,] "S"  "f"  "W"
 [3,] "M"  "Q"  "O"
 [4,] "M"  "D"  "U"
 [5,] "K"  "C"  "F"
 [6,] "E"  "O"  "b"
 [7,] "h"  "V"  "c"
 [8,] "N"  "j"  "k"
 [9,] "j"  "a"  "R"
[10,] "B"  "H"  "f"
[11,] "L"  "i"  "A"
[12,] "E"  "R"  "X"

However, I could only get the matrix which include duplicated alphabet.

(What I mean is that I want to make all of alphabets have eqaul opportunity to be chosen only once)

Body:
You only need to sample once:

f <- c('A', 'B', 'C', 'D', 'E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','f','g','h','i','j','k')
a <- matrix(sample(f),12,3)

a
      [,1] [,2] [,3]
 [1,] "U"  "P"  "a"
 [2,] "Z"  "f"  "B"
 [3,] "b"  "I"  "N"
 [4,] "k"  "M"  "c"
 [5,] "V"  "Y"  "E"
 [6,] "F"  "K"  "D"
 [7,] "L"  "O"  "X"
 [8,] "J"  "A"  "H"
 [9,] "g"  "R"  "d"
[10,] "i"  "j"  "G"
[11,] "S"  "Q"  "T"
[12,] "C"  "h"  "W"


问:
Compile .java files or .class files in eclipse
I have done some changes in my .java files in eclipse...ie. I have passed one more parameter in a method..
but how to compile it so that the changes will be seen in .class files</p>

答: Its very simple clean build your project , clean removes the old class files and build creates new class files, Eclipse provides Build Automatically option , you set this check box , so that every time you change something class files are updated automatically . </p>


问:
XPATH Multiple Element Filters
I have the following sample XML structure:

```<code><SavingAccounts>
    <SavingAccount>
       <ServiceOnline>yes</ServiceOnline>
       <ServiceViaPhone>no</ServiceViaPhone>
    </SavingAccount>
    <SavingAccount>
       <ServiceOnline>no</ServiceOnline>
       <ServiceViaPhone>yes</ServiceViaPhone>
    </SavingAccount>
</SavingAccounts>
</code>```

What I need to do is filter the 'SavingAccount' nodes using XPATH where the value of 'ServiceOnline' is 'yes' or the value of 'ServiceViaPhone' is yes.

The XPATH should return me two rows!! I can filter 'SavingAccount' nodes where both of the element values are yes like the following XPATH sample, but what I want to do is an or element value comparison???

```<code>/SavingAccounts/SavingAccount/ServiceOnline[text()='yes']/../ServiceViaPhone[text()='yes']/..
</code>```

答:
Will

```<code>/SavingAccounts/SavingAccount[ServiceOnline/text()='yes' or ServiceViaPhone/text()='yes']
</code>```

do the trick?

I have no XPath evaluator handy at the moment.

EDIT:

If I remember correctly, you don't need the text(), so

```<code>[ServiceOnline='yes' or ServiceViaPhone='yes']
</code>```

should be sufficient, and more readable.

EDIT:

Yes, of course, 'or' for predicate expressions, my bad.

OwnerDisplayName: CroweMan

LastEditorDisplayName: Dimitre Novatchev

Title: XPATH Multiple Element Filters

Body:
I have the following sample XML structure:

<SavingAccounts>
    <SavingAccount>
       <ServiceOnline>yes</ServiceOnline>
       <ServiceViaPhone>no</ServiceViaPhone>
    </SavingAccount>
    <SavingAccount>
       <ServiceOnline>no</ServiceOnline>
       <ServiceViaPhone>yes</ServiceViaPhone>
    </SavingAccount>
</SavingAccounts>

What I need to do is filter the 'SavingAccount' nodes using XPATH where the value of 'ServiceOnline' is 'yes' or the value of 'ServiceViaPhone' is yes.

The XPATH should return me two rows!! I can filter 'SavingAccount' nodes where both of the element values are yes like the following XPATH sample, but what I want to do is an or element value comparison???

/SavingAccounts/SavingAccount/ServiceOnline[text()='yes']/../ServiceViaPhone[text()='yes']/..

Body:
Will

/SavingAccounts/SavingAccount[ServiceOnline/text()='yes' or ServiceViaPhone/text()='yes']

do the trick?

I have no XPath evaluator handy at the moment.

EDIT:

If I remember correctly, you don't need the text(), so

[ServiceOnline='yes' or ServiceViaPhone='yes']

should be sufficient, and more readable.

EDIT:

Yes, of course, 'or' for predicate expressions, my bad.

OwnerDisplayName: roe

LastEditorDisplayName: roe


问:
Trigger the keyboard event (enter key) in angular4
In my application I have a global search field which is used to filter the data in the list , list will have multiple column. From other component setting the filter value (setting to input value) it's happening but I have to trigger the manual keyboard event (enter key) action on the input.

I tried with viewChild decorator.

component.html

```<code><input #gb type="text" placeholder="Global search.." class="changeListComponent_inputSearch"  [(ngModel)]="jiraRef" />
</code>```

component.ts

```<code>@ViewChild('gb') gb:ElementRef;
this.jiraRef =  jiraRef;
const event = new KeyboardEvent("keypress",{ "which ": "13"});
this.gb.nativeElement.focus();
this.gb.nativeElement.dispatchEvent(event);
</code>```

using this I could set the value and make a focus but keyboard event is not triggering.

答:
You can simply use

```<code><input type=text (keypress)="eventHandler($event)">

eventHandler(event) {
   console.log(event, event.keyCode, event.keyIdentifier);
}
</code>```

Solution is based on this answer
Get which key pressed from (keypress) angular2

Body:
In my application I have a global search field which is used to filter the data in the list , list will have multiple column. From other component setting the filter value (setting to input value) it's happening but I have to trigger the manual keyboard event (enter key) action on the input.

I tried with viewChild decorator.

component.html

<input #gb type="text" placeholder="Global search.." class="changeListComponent_inputSearch"  [(ngModel)]="jiraRef" />

component.ts

@ViewChild('gb') gb:ElementRef;
this.jiraRef =  jiraRef;
const event = new KeyboardEvent("keypress",{ "which ": "13"});
this.gb.nativeElement.focus();
this.gb.nativeElement.dispatchEvent(event);

using this I could set the value and make a focus but keyboard event is not triggering.

Body:
You can simply use

<input type=text (keypress)="eventHandler($event)">

eventHandler(event) {
   console.log(event, event.keyCode, event.keyIdentifier);
}

Solution is based on this answer
Get which key pressed from (keypress) angular2


问:
codeigniter get data by selection of dropdown

How to get data by selecting the drop-down in CodeIgniter.

Below is my code it does not work. The below code is not working properly when I selecting an option in the drop down and when I submit page appearing empty. when click please help me to get data. I am doing it in CodeIgniter. I want to get data from the database . I think the code is perfect am new to CodeIgniter the below code is not working properly the page appearing empty when click please help me to get data. I am doing it in CodeIgniter. I want to get data from the database . I think the code is perfect am new to CodeIgniter.

view:

```<code><?php echo form_open('super_admin/believers_controller/view_believerr/' , array('class' => 'form-horizontal validatable', 'enctype' => 'multipart/form-data') ); ?>

<div class="form-group">
    <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> District Id</label>

    <div class="col-sm-9">
        <select name="report_type" >
            <option >Select  Id</option>
            <option value="believers">Believers</option>
            <option value="staff">staff</option>
            <option value="staff">committe members</option>

        </select>
    </div>
</div>
<div class="clearfix form-actions">
    <div class="col-md-offset-3 col-md-9">
        <input type="submit" name="Submit" class="btn btn-info" >
</code>```

controller:

```<code><?php
function view_believerr()
{
    $report_type = $this->input->get('report_type');
    if($report_type=='believers'){
        $this->load->model('believers/believers_model');
        $page_data['h']=$this->believers_model->view_believer();
        $page_data['page_name']  = 'believers/view_believer';
        $this->load->view('index', $page_data);
    }
}
?>
</code>```

model:

```<code><?php
function view_believer()
{
    $query = $this->db->get('tbl_believers');
    return $query;
}
?>
</code>```

I want to get data from database . I think the code is perfect am new to codeigniter the below code is not working properly the  page appearing empty when click please help me to get data. I am doing it in codeigniter. I want to get data from database . I think the code is perfect am new to codeignite

答: Use   $this->input->post('report_type');

Body:
How to get data by selecting the drop-down in CodeIgniter.

Below is my code it does not work. The below code is not working properly when I selecting an option in the drop down and when I submit page appearing empty. when click please help me to get data. I am doing it in CodeIgniter. I want to get data from the database . I think the code is perfect am new to CodeIgniter the below code is not working properly the page appearing empty when click please help me to get data. I am doing it in CodeIgniter. I want to get data from the database . I think the code is perfect am new to CodeIgniter.

view:

<?php echo form_open('super_admin/believers_controller/view_believerr/' , array('class' => 'form-horizontal validatable', 'enctype' => 'multipart/form-data') ); ?>

     District Id

        <select name="report_type" >
            <option >Select  Id</option>
            <option value="believers">Believers</option>
            <option value="staff">staff</option>
            <option value="staff">committe members</option>

        </select>

        <input type="submit" name="Submit" class="btn btn-info" >

controller:

<?php
function view_believerr()
{
    $report_type = $this->input->get('report_type');
    if($report_type=='believers'){
        $this->load->model('believers/believers_model');
        $page_data['h']=$this->believers_model->view_believer();
        $page_data['page_name']  = 'believers/view_believer';
        $this->load->view('index', $page_data);
    }
}
?>

model:

<?php
function view_believer()
{
    $query = $this->db->get('tbl_believers');
    return $query;
}
?>

I want to get data from database . I think the code is perfect am new to codeigniter the below code is not working properly the  page appearing empty when click please help me to get data. I am doing it in codeigniter. I want to get data from database . I think the code is perfect am new to codeignite

Body: Use   $this->input->post('report_type');


问:
how can I replace 2 dim array?
I want to replace array elements

```<code>arr1[n][m] to arr2[m][n]
</code>```

ex:

```<code>arr1[0]{a1,a2,a3}
arr1[1]{b1,b2,b3}
</code>```

change to:

```<code>arr2[0]{a1,b1}
arr2[1]{a2,b2}
arr2[2]{a3,b3}
</code>```

how can I do this?

答:
Basically you need to do the transpose of a given matrix.</p>

```<code>public T[,] TransposeMatrix(T[,] matrix)
{
    var rows = matrix.GetLength(0);
    var columns = matrix.GetLength(1);
    var result = new T[columns, rows];

    for (var c = 0; c < columns; ++c)
    {
        for (var r = 0; r < rows; ++r)
        {
            result[c, r] = matrix[r, c];
        }
    }

    return result;
}
</code>```

Title: how can I replace 2 dim array?

Body:
I want to replace array elements

arr1[n][m] to arr2[m][n]

ex:

arr1[0]{a1,a2,a3}
arr1[1]{b1,b2,b3}

change to:

arr2[0]{a1,b1}
arr2[1]{a2,b2}
arr2[2]{a3,b3}

how can I do this?

Body:
Basically you need to do the transpose of a given matrix.

public T[,] TransposeMatrix(T[,] matrix)
{
    var rows = matrix.GetLength(0);
    var columns = matrix.GetLength(1);
    var result = new T[columns, rows];

    for (var c = 0; c < columns; ++c)
    {
        for (var r = 0; r < rows; ++r)
        {
            result[c, r] = matrix[r, c];
        }
    }

    return result;
}