问:
Automatically close application when i call intent.createChooser to send mail?
In my android application having one button to send mail, When I click that send button using startActivity(Intent.createChooser(emailIntent, "Send Mail...")); this line Gmail will open and then I click send mail. Mail will sent successfully at the same time my application get closed why ? I need to stay in that same page ?

```<code>try
{
        String extpath=Environment.getExternalStorageDirectory() +"/NewFolder/DBName";
        File pathp=new File(extpath);
        Log.d("New Path", pathp.toString());

        long fileSize = pathp.length();
        if(fileSize > 0)
        {

            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

            String address = "mailid@yourmail.com";
            String subject = "Database";
            String emailtext = "Please check the attached database and save it";

            emailIntent.setType("application/octet-stream");

            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { address });

            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + pathp));

            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);

            startActivity(Intent.createChooser(emailIntent, "Send Mail..."));
        }
        else
        {
            Log.d("Error", "Attachment didn't attach ");
        }
    }
    catch (Throwable t)
    {
        Log.d("Error on sending mail", t.toString());
    }
</code>```

When i run this code mail sent and then application will get close. I don't want to close application. Help me thanks in advance.

答:
You Can Use This Code: </p>

```<code>Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT   , "body of email");
try {
    startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
</code>```

Body:
In my android application having one button to send mail, When I click that send button using startActivity(Intent.createChooser(emailIntent, "Send Mail...")); this line Gmail will open and then I click send mail. Mail will sent successfully at the same time my application get closed why ? I need to stay in that same page ?

try
{
        String extpath=Environment.getExternalStorageDirectory() +"/NewFolder/DBName";
        File pathp=new File(extpath);
        Log.d("New Path", pathp.toString());

        long fileSize = pathp.length();
        if(fileSize > 0)
        {

            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

            String address = "mailid@yourmail.com";
            String subject = "Database";
            String emailtext = "Please check the attached database and save it";

            emailIntent.setType("application/octet-stream");

            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { address });

            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);

            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + pathp));

            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext);

            startActivity(Intent.createChooser(emailIntent, "Send Mail..."));
        }
        else
        {
            Log.d("Error", "Attachment didn't attach ");
        }
    }
    catch (Throwable t)
    {
        Log.d("Error on sending mail", t.toString());
    }

When i run this code mail sent and then application will get close. I don't want to close application. Help me thanks in advance.

Body:
You Can Use This Code:

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT   , "body of email");
try {
    startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}


来源: stackexchange

问:
Redimensioning array of ranges into a single array containing only the values of each range element
I have multiple worksheets with ranges which I collect into an array of ranges, and I cant do Union since it does not work across worksheets.
Since I want to create a chart where the time-series or FullSeriesCollection are based on the elements of my combined ranges, I thought that redimensioning the array of ranges into a single array might serve as my solution.
Perhaps there is an easier solution that I am not seeing.

I tried to outline the general case below. The ranges are dynamic in my code, but here I just set them arbitrarily.

```<code>Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            ReDim Preserve arrDate(j)
            arrDate(j) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub
</code>```

When I use this code I get an array with 22 elements corresponding to the range of rng_3. What I want to end up with after the nested loop is an array that contains the elements from all ranges in 1 single array with 1 dimension.

The reason I want this in the end is I want to create chart using the array values.

答:
You can use the following to combine all arrays into one

```<code>Sub Collection()

    Dim arrDate() As Variant
    Dim arrRngTotal As Variant
    Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
    Dim ws_1 As Worksheet, ws_2 As Worksheet
    Dim j As Long, k As Long, arrCounter As Long

    Set ws_1 = ThisWorkbook.Sheets(1)
    Set ws_2 = ThisWorkbook.Sheets(2)

    ' Example of ranges, not static in the original code.
    Set rng_1 = ws_1.Range("A2:A10")
    Set rng_2 = ws_1.Range("A11:A22")
    Set rng_3 = ws_2.Range("A2:A22")

    With Application
        arrRngTotal = Array(.Transpose(rng_1.Value), .Transpose(rng_2.Value), .Transpose(rng_3.Value))
    End With

    For k = LBound(arrRngTotal) To UBound(arrRngTotal)
        On Error Resume Next
        arrCounter = IIf(IsNumeric(UBound(arrDate)), UBound(arrDate), 0)
        arrCounter = arrCounter + GetArraySize(arrRngTotal(k))
        On Error GoTo 0
        ReDim Preserve arrDate(1 To arrCounter)

        For j = LBound(arrRngTotal(k)) To UBound(arrRngTotal(k))
            Debug.Print UBound(arrDate) - (UBound(arrRngTotal(k)) - j), arrRngTotal(k)(j)
            arrDate(UBound(arrDate) - (UBound(arrRngTotal(k)) - j)) = arrRngTotal(k)(j)
        Next j
    Next k

End Sub
</code>```

```<code>Private Function GetArraySize(arr As Variant) As Long
    GetArraySize = UBound(arr) - LBound(arr) + 1
End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have multiple worksheets with ranges which I collect into an array of ranges, and I cant do Union since it does not work across worksheets.
Since I want to create a chart where the time-series or FullSeriesCollection are based on the elements of my combined ranges, I thought that redimensioning the array of ranges into a single array might serve as my solution.
Perhaps there is an easier solution that I am not seeing.

I tried to outline the general case below. The ranges are dynamic in my code, but here I just set them arbitrarily.

Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            ReDim Preserve arrDate(j)
            arrDate(j) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub

When I use this code I get an array with 22 elements corresponding to the range of rng_3. What I want to end up with after the nested loop is an array that contains the elements from all ranges in 1 single array with 1 dimension.

The reason I want this in the end is I want to create chart using the array values.

Body:
You can use the following to combine all arrays into one

Sub Collection()

    Dim arrDate() As Variant
    Dim arrRngTotal As Variant
    Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
    Dim ws_1 As Worksheet, ws_2 As Worksheet
    Dim j As Long, k As Long, arrCounter As Long

    Set ws_1 = ThisWorkbook.Sheets(1)
    Set ws_2 = ThisWorkbook.Sheets(2)

    ' Example of ranges, not static in the original code.
    Set rng_1 = ws_1.Range("A2:A10")
    Set rng_2 = ws_1.Range("A11:A22")
    Set rng_3 = ws_2.Range("A2:A22")

    With Application
        arrRngTotal = Array(.Transpose(rng_1.Value), .Transpose(rng_2.Value), .Transpose(rng_3.Value))
    End With

    For k = LBound(arrRngTotal) To UBound(arrRngTotal)
        On Error Resume Next
        arrCounter = IIf(IsNumeric(UBound(arrDate)), UBound(arrDate), 0)
        arrCounter = arrCounter + GetArraySize(arrRngTotal(k))
        On Error GoTo 0
        ReDim Preserve arrDate(1 To arrCounter)

        For j = LBound(arrRngTotal(k)) To UBound(arrRngTotal(k))
            Debug.Print UBound(arrDate) - (UBound(arrRngTotal(k)) - j), arrRngTotal(k)(j)
            arrDate(UBound(arrDate) - (UBound(arrRngTotal(k)) - j)) = arrRngTotal(k)(j)
        Next j
    Next k

End Sub

Private Function GetArraySize(arr As Variant) As Long
    GetArraySize = UBound(arr) - LBound(arr) + 1
End Function


问:
Text formatting distorted
In Visual Studio 2019
While Preforming text formatting (CTRL + K + D) everything looks fine except for the style attribute in html document.

Before formatting:

```<code><form style="display: flex;flex-direction: column; height: 100%; justify-content: space-between;" [formGroup]="SystemForm">
</code>```

And after:

```<code><form style="    display: flex;
flex-direction: column;
height: 100%;
justify-content: space-between;" [formGroup]="SystemForm">
</code>```

How can i correct that?

答:
I recommend you to use popular VSCode extension called Prettier - Code formatter, You can also further customise it.

This will format your code as below :

```<code><form
  style="display: flex;flex-direction: column; height: 100%; justify-content: space-between;"
  [formGroup]="SystemForm"
></form>
</code>```

Title: Text formatting distorted

Body:
In Visual Studio 2019
While Preforming text formatting (CTRL + K + D) everything looks fine except for the style attribute in html document.

Before formatting:

<form style="display: flex;flex-direction: column; height: 100%; justify-content: space-between;" [formGroup]="SystemForm">

And after:

<form style="    display: flex;
flex-direction: column;
height: 100%;
justify-content: space-between;" [formGroup]="SystemForm">

How can i correct that?

Body:
I recommend you to use popular VSCode extension called Prettier - Code formatter, You can also further customise it.

This will format your code as below :

<form
  style="display: flex;flex-direction: column; height: 100%; justify-content: space-between;"
  [formGroup]="SystemForm"
></form>


问:
Processing/Bluetooth to Arduino
I want to light up a LED wirelessly through processing.

what I have so far.

I can (wirelessly) turn on my LED using a serial terminal called "Bluterm".

I can turn on my LED by pressing 1 or 0 to switch LED on and off in processing.

How can I leave Bluterm out of my equation and use processing to send the 1 and 0 through bluetooth.

Here is my code for processing:

```<code>import processing.serial.*;

Serial port;

String string;
void setup(){
    String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port
    port = new Serial(this, portName, 9600);
    port.bufferUntil('\n');
}

void draw() {

  printArray(string);
}

void keyPressed() {
  if (key =='1'){port.write('1');}
    if (key=='0') {port.write('0');}
    }

    void serialEvent(Serial port) {
      string = port.readStringUntil('\n');}

</code>```

and the Arduino code

```<code>
char data;
int led = 13;

void setup() {
  pinMode(led, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  if (Serial.available()>0){
    data = Serial.read();
  }

  if (data=='1'){
    Serial.println("HELLO");
    digitalWrite(led, HIGH);

    }

    else if (data=='0'){
      digitalWrite(led, LOW);
      Serial.println("BYE");}
    }

</code>```

I'm kind of lost, can processing talk to bluetooth or do I always need a terminal?

If something isn't clear pls don't hesitate to ask,

Thank you for your time,

Juriaan

答: i see u are using a hc05 bluetooth device i have this myself but i dont really get what u want to use for sending the 1 and 0 to your hc05 and are you only using a led becouse if it is i would be able to help on (if you wanna send the bluetooth signals with a mobile app try the blynk app fron app store or google play store) </p>

Title: Processing/Bluetooth to Arduino

Body:
I want to light up a LED wirelessly through processing.

what I have so far.

I can (wirelessly) turn on my LED using a serial terminal called "Bluterm".

I can turn on my LED by pressing 1 or 0 to switch LED on and off in processing.

How can I leave Bluterm out of my equation and use processing to send the 1 and 0 through bluetooth.

Here is my code for processing:

import processing.serial.*;

Serial port;

String string;
void setup(){
    String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port
    port = new Serial(this, portName, 9600);
    port.bufferUntil('\n');
}

void draw() {

  printArray(string);
}

void keyPressed() {
  if (key =='1'){port.write('1');}
    if (key=='0') {port.write('0');}
    }

    void serialEvent(Serial port) {
      string = port.readStringUntil('\n');}

and the Arduino code

char data;
int led = 13;

void setup() {
  pinMode(led, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  if (Serial.available()>0){
    data = Serial.read();
  }

  if (data=='1'){
    Serial.println("HELLO");
    digitalWrite(led, HIGH);

    }

    else if (data=='0'){
      digitalWrite(led, LOW);
      Serial.println("BYE");}
    }

I'm kind of lost, can processing talk to bluetooth or do I always need a terminal?

If something isn't clear pls don't hesitate to ask,

Thank you for your time,

Juriaan


问:
How to center a Node in Graphviz
I have this graph:

```<code>digraph Database {
graph [bb="0 0 180 96",
    fontname="Verdana-Bold",
    fontsize=14,
    labeljust=r,
    labelloc=t,
    margin=12,
    nodesep=0.5555555555555556,
    pad=0.5,
    rankdir=RL,
    ranksep=0.3472222222222222,
    sep=0.05,
    splines=spline
];
node [fixedsize=true,
    fontname=Verdana,
    fontsize=11,
    height=40,
    label="correct me",
    labelloc=c,
    margin=0,
    shape=box,
    style=rounded,
    width=100
];
Node1   [fontsize=14.0,
    height=1.3333333333333333,
    label="Here a long enough
example of a node.
Unfortunately, the text
won't remain in the box",
        width=2.4944932725694446];
}
</code>```

which produces this output:

Why is that so? (not sure why picture itself is so small)
The text/label should be centered (labelloc=c) but isn't.

答:
You are using fixedsize=true:

If true, the node size is specified by the values of the width and
  height attributes only and is not expanded to contain the text label.

Therefore, if you want to be sure that the label is contained within the node shape, do not use fixedsize=true.

However, this doesn't explain why the label isn't centered, and makes me wonder about the version of graphviz you are using. Tools like http://viz-js.com/ display the label centered (select png output).

On a side note, labelloc=c is for vertical alignment of the label.

Title: How to center a Node in Graphviz

Body:
I have this graph:

digraph Database {
graph [bb="0 0 180 96",
    fontname="Verdana-Bold",
    fontsize=14,
    labeljust=r,
    labelloc=t,
    margin=12,
    nodesep=0.5555555555555556,
    pad=0.5,
    rankdir=RL,
    ranksep=0.3472222222222222,
    sep=0.05,
    splines=spline
];
node [fixedsize=true,
    fontname=Verdana,
    fontsize=11,
    height=40,
    label="correct me",
    labelloc=c,
    margin=0,
    shape=box,
    style=rounded,
    width=100
];
Node1   [fontsize=14.0,
    height=1.3333333333333333,
    label="Here a long enough
example of a node.
Unfortunately, the text
won't remain in the box",
        width=2.4944932725694446];
}

which produces this output:

Why is that so? (not sure why picture itself is so small)
The text/label should be centered (labelloc=c) but isn't.


问:
Setting value of Date Picker on single onChange
I am trying to set the date for two of my different input types. I tried calling different functions for both input event handler, and it worked. But I want to use more concise way to manage input date. The different approach I tried calling single onChange(), doesn't seem to change my input box value.

Here is my code:

```<code>import React, { Component } from "react";
import axios from "axios";

export default class DatePage extends Component {
  constructor() {
    super();
    this.state = {
      startDate: '',
      endDate: '',
      clicked: false
    };
  }

  componentDidMount() {

    this.setDate();

    this.setState({
        clicked: true
      });
  }

  setDate = (e) => {

    if (this.state.clicked !== true)
    {
      var date = new Date();

      var newdate =
        date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)) + "-" + date.getDate();

      this.setState({
        startDate: newdate,
        endDate: newdate,
        clicked: false
      });
    }

    else
    {

        this.setState({
            [e.target.name]: e.target.value
        });
    }
  };

  render() {
    return (
      <div>

        <label>From</label>
        <input
          type="date"
          name="startdate"
          value={this.state.startDate}
          onChange={this.setDate}

        />

        <label>To</label>
        <input
          type="date"
          name="enddate"
          value={this.state.endDate}
          onChange={this.setDate}
        />
      </div>
    );
  }
}
</code>```

By default,  I am setting the current date and onChange the date selected

答:
It seems the case is wrong. I cleaned up the code.

startdate to startDate
enddate to endDate. It seems to work well if you change this part.

```<code>import React, { Component } from "react";

export default class Datepage extends Component {
  constructor() {
    super();
    var date = new Date();
    var newdate =
      date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)) + "-" + date.getDate();

    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }

  componentDidMount() {
  }

  setDate = (e) => {
      this.setState({
          [e.target.name]: e.target.value
      });
  };

  render() {
    return (
      <div>

        <label>From</label>
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setDate.bind(this)}

        />

        <label>To</label>
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setDate.bind(this)}
        />
      </div>
    );
  }
}
</code>```

Body:
I am trying to set the date for two of my different input types. I tried calling different functions for both input event handler, and it worked. But I want to use more concise way to manage input date. The different approach I tried calling single onChange(), doesn't seem to change my input box value.

Here is my code:

import React, { Component } from "react";
import axios from "axios";

export default class DatePage extends Component {
  constructor() {
    super();
    this.state = {
      startDate: '',
      endDate: '',
      clicked: false
    };
  }

  componentDidMount() {

    this.setDate();

    this.setState({
        clicked: true
      });
  }

  setDate = (e) => {

    if (this.state.clicked !== true)
    {
      var date = new Date();

      var newdate =
        date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)) + "-" + date.getDate();

      this.setState({
        startDate: newdate,
        endDate: newdate,
        clicked: false
      });
    }

    else
    {

        this.setState({
            [e.target.name]: e.target.value
        });
    }
  };

  render() {
    return (

        From
        <input
          type="date"
          name="startdate"
          value={this.state.startDate}
          onChange={this.setDate}

        />

        To
        <input
          type="date"
          name="enddate"
          value={this.state.endDate}
          onChange={this.setDate}
        />

    );
  }
}

By default,  I am setting the current date and onChange the date selected

Body:
It seems the case is wrong. I cleaned up the code.

startdate to startDate
enddate to endDate. It seems to work well if you change this part.

import React, { Component } from "react";

export default class Datepage extends Component {
  constructor() {
    super();
    var date = new Date();
    var newdate =
      date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)) + "-" + date.getDate();

    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }

  componentDidMount() {
  }

  setDate = (e) => {
      this.setState({
          [e.target.name]: e.target.value
      });
  };

  render() {
    return (
      <div>

        <label>From</label>
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setDate.bind(this)}

        />

        <label>To</label>
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setDate.bind(this)}
        />
      </div>
    );
  }
}


问:
How to capture keypress in View added by WindowManager
I would like to add a custom view for my application. For this I use WindowsManager:

```<code>        final WindowManager wm = getWindowManager();
        final View view = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.game_menu, null);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND | WindowManager.LayoutParams.FLAG_FULLSCREEN;
        lp.dimAmount = (float) 0.6;
        lp.format = PixelFormat.TRANSPARENT;
        lp.windowAnimations = android.R.style.Animation_Dialog;
        view.setOnKeyListener(new OnKeyListener()
        {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                Log.d("12", "12");
                if (keyCode == KeyEvent.KEYCODE_BACK)
                {
                    wm.removeView(view); // This I need to hide my menu
                }
                return false;
            }
        });
        wm.addView(view, lp); // I add menu like in Angry Birds and other games
</code>```

But I cannot capture device key events for hiding this view.

Why my key listener not invoked in view added by WindowsManager? What must I do to hide my view by device back key pressed?

答:
I'm still fairly new at this, but I'm trying to get similar functionality working. Here's what got it working for me (in Kotlin):</p>

```<code>mOverlayView = LayoutInflater.from(this).inflate(R.layout.overlay_layout, null)

val params = WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
    // This was the piece I was missing
    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
        or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
    PixelFormat.TRANSLUCENT
)

mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
mWindowManager!!.addView(mOverlayView, params)

mOverlayView!!.isFocusableInTouchMode = true
mOverlayView!!.setOnKeyListener(object : View.OnKeyListener {
    override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
        // Custom code here...
        return true
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to add a custom view for my application. For this I use WindowsManager:

        final WindowManager wm = getWindowManager();
        final View view = ((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.game_menu, null);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND | WindowManager.LayoutParams.FLAG_FULLSCREEN;
        lp.dimAmount = (float) 0.6;
        lp.format = PixelFormat.TRANSPARENT;
        lp.windowAnimations = android.R.style.Animation_Dialog;
        view.setOnKeyListener(new OnKeyListener()
        {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                Log.d("12", "12");
                if (keyCode == KeyEvent.KEYCODE_BACK)
                {
                    wm.removeView(view); // This I need to hide my menu
                }
                return false;
            }
        });
        wm.addView(view, lp); // I add menu like in Angry Birds and other games

But I cannot capture device key events for hiding this view.

Why my key listener not invoked in view added by WindowsManager? What must I do to hide my view by device back key pressed?

Body:
I'm still fairly new at this, but I'm trying to get similar functionality working. Here's what got it working for me (in Kotlin):

mOverlayView = LayoutInflater.from(this).inflate(R.layout.overlay_layout, null)

val params = WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
    // This was the piece I was missing
    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
        or WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
    PixelFormat.TRANSLUCENT
)

mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
mWindowManager!!.addView(mOverlayView, params)

mOverlayView!!.isFocusableInTouchMode = true
mOverlayView!!.setOnKeyListener(object : View.OnKeyListener {
    override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
        // Custom code here...
        return true
    }
}


问:
How to choose the environment in a python chunk in rmarkdown
I try to get familiar with python in R.
I made it work using reticulate along the following lines:

```<code>library(reticulate)
py_install("pandas")
</code>```

Then I can always get back to the enviroment where I installed that to using

```<code>use_condaenv("r-reticulate")
</code>```

How can I use this in a python chunk of the following form

```<code>```{python}
import pandas as pd
```
</code>```

pandas can be found in the first version above (using reticulate) but not in the version with the python chunk. How can I tell it to use the "r-reticulate" environment? Setting it in an R set-up chunk in the following form does not work for me

```<code>```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
use_condaenv("r-reticulate")
```
</code>```

答:
I had the same issue, it was fixed by setting the required keyword to TRUE.

use_condaenv(condaenv='env-name', required = TRUE)

Body:
I try to get familiar with python in R.
I made it work using reticulate along the following lines:

library(reticulate)
py_install("pandas")

Then I can always get back to the enviroment where I installed that to using

use_condaenv("r-reticulate")

How can I use this in a python chunk of the following form

```{python}
import pandas as pd
```

pandas can be found in the first version above (using reticulate) but not in the version with the python chunk. How can I tell it to use the "r-reticulate" environment? Setting it in an R set-up chunk in the following form does not work for me

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(reticulate)
use_condaenv("r-reticulate")
```


问:
This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version of Xcode
I getting the following error when I run the app into device.

This iPhone 7 (Model 1660, 1778, 1779, 1780) is running iOS 12.3.1 (16F203), which may not be supported by this version of Xcode.

my Xcode is 10.1

答: Temporary solution for this change folder named 12.3.1.its working for me once we get 12.3.1 package content we will move corresponding place</p>


问:
How to implement Grandchild (Enkel1) into Family-Tree with graphviz?
I´m building a Family tree with Grandparents, Parents, Children and Grandchildren (Children with Ex-Partners are possible too). Its working perfect, but there is a Problem with the grandchilds. When i try to connect v1 with Enkel1, i´m getting Problems with the layout. I don`t understand this Problem because its working exactly with "Ex-Kind" and Point c1. Can you please give me a tipp?

Thank you so much,

Peter

```<code>digraph G {
edge [dir=none];
node [shape=box];
graph [splines=ortho compound=true, pad="0.4", nodesep="0.2",          ranksep="0.2"];
mindist=1

"Max\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maxi\nTestermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Moritz\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Nina\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Volker\nVersuch" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Veronika\nVersuch" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maximilian\nMustermann"[shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maxima\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Bart" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Lisa" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maggie" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Ex\nPartner" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Schwiegertochter" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Enkel1" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Ex-Kind" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;

a1 [shape=circle,label="",height=0.01,width=0.01];
b1 [shape=circle,label="",height=0.01,width=0.01];
b2 [shape=circle,label="",height=0.01,width=0.01];
b3 [shape=circle,label="",height=0.01,width=0.01];

{rank=same; "Maximilian\nMustermann" -> a1 -> "Maxima\nMustermann"};
{rank=same; b1 -> b2 -> b3};
a1 -> b2;
b1 -> "Max\nMustermann";
b2 -> "Maxi\nTestermann";
b3 -> "Moritz\nMustermann";

c1 [shape=circle,label="",height=0.01,width=0.01];
{rank=same; "Ex\nPartner" -> c1 -> "Moritz\nMustermann"};

c1->"Ex-Kind";

x1 [shape=circle,label="",height=0.01,width=0.01];
{rank=same; "Volker\nVersuch" -> x1 -> "Veronika\nVersuch"};
{rank=same"Maxima\nMustermann"; "Volker\nVersuch" }
x1 ->  "Nina\nMustermann";

p1 [shape=circle,label="",height=0.01,width=0.01];
p2 [shape=circle,label="",height=0.01,width=0.01];
p3 [shape=circle,label="",height=0.01,width=0.01];
q1 [shape=circle,label="",height=0.01,width=0.01];
q2 [shape=circle,label="",height=0.01,width=0.01];
q3 [shape=circle,label="",height=0.01,width=0.01];

{rank=same; "Moritz\nMustermann" -> p1 -> "Nina\nMustermann"};
{rank=same;q1 -> q2 -> q3};
{rank=same;"Bart";"Lisa";"Maggie"};

p1 -> p2 -> p3 ->q2;
q1 -> Bart;
q2 -> Lisa;
q3 -> Maggie;

v1 [shape=circle,label="",height=0.01,width=0.01];
{rank=same; "Bart" -> v1 -> "Schwiegertochter"};

}
</code>```

答:
You need to force the order of the last (Bart) row with invisible edges; I have added

```<code>{ rank = same; Schwiegertochter -> Lisa -> Maggie[ style = invis ] }
</code>```

at the bottom; I also have (more for my own pleasure than for real need) cleaned up the code, coming up with

```<code>digraph G
{
    graph[ splines=ortho, pad="0.4", nodesep="0.2", ranksep="0.2" ];
    mindist=1

    node[ shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10 ];
    "Max\nMustermann", "Maxi\nTestermann", "Moritz\nMustermann", "Nina\nMustermann";
    "Volker\nVersuch", "Veronika\nVersuch", "Maximilian\nMustermann", "Maxima\nMustermann";
    "Bart", "Lisa", "Maggie", "Ex\nPartner", "Schwiegertochter", "Enkel1", "Ex-Kind";

    node[ shape=circle,label="",height=0.01,width=0.01 ];
    a1, b1, b2, b3, c1, x1, p1, p2, p3, q1, q2, q3, v1;

    edge[ dir=none ];

    { rank=same; "Maximilian\nMustermann" -> a1 -> "Maxima\nMustermann" }
    { rank=same; b1 -> b2 -> b3 }
    a1 -> b2;
    b1 -> "Max\nMustermann";
    b2 -> "Maxi\nTestermann";
    b3 -> "Moritz\nMustermann";

    { rank=same; "Ex\nPartner" -> c1 -> "Moritz\nMustermann" }

    c1->"Ex-Kind";

    { rank=same; "Volker\nVersuch" -> x1 -> "Veronika\nVersuch" }
    { rank=same"Maxima\nMustermann"; "Volker\nVersuch" }
    x1 ->  "Nina\nMustermann";

    { rank=same; "Moritz\nMustermann" -> p1 -> "Nina\nMustermann"}
    { rank=same;q1 -> q2 -> q3}
    { rank=same;"Bart";"Lisa";"Maggie" }

    p1 -> p2 -> p3 ->q2;
    q1 -> Bart;
    q2 -> Lisa;
    q3 -> Maggie;

    { rank=same; "Bart" -> v1 -> "Schwiegertochter" }
    { rank = same; Schwiegertochter -> Lisa -> Maggie[ style = invis ] }
    v1 -> Enkel1;
}
</code>```

which gives you

Body:
I´m building a Family tree with Grandparents, Parents, Children and Grandchildren (Children with Ex-Partners are possible too). Its working perfect, but there is a Problem with the grandchilds. When i try to connect v1 with Enkel1, i´m getting Problems with the layout. I don`t understand this Problem because its working exactly with "Ex-Kind" and Point c1. Can you please give me a tipp?

Thank you so much,

Peter

digraph G {
edge [dir=none];
node [shape=box];
graph [splines=ortho compound=true, pad="0.4", nodesep="0.2",          ranksep="0.2"];
mindist=1

"Max\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maxi\nTestermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Moritz\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Nina\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Volker\nVersuch" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Veronika\nVersuch" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maximilian\nMustermann"[shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maxima\nMustermann" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Bart" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Lisa" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Maggie" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Ex\nPartner" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Schwiegertochter" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Enkel1" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;
"Ex-Kind" [shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10] ;

a1 [shape=circle,label="",height=0.01,width=0.01];
b1 [shape=circle,label="",height=0.01,width=0.01];
b2 [shape=circle,label="",height=0.01,width=0.01];
b3 [shape=circle,label="",height=0.01,width=0.01];

{rank=same; "Maximilian\nMustermann" -> a1 -> "Maxima\nMustermann"};
{rank=same; b1 -> b2 -> b3};
a1 -> b2;
b1 -> "Max\nMustermann";
b2 -> "Maxi\nTestermann";
b3 -> "Moritz\nMustermann";

c1 [shape=circle,label="",height=0.01,width=0.01];
{rank=same; "Ex\nPartner" -> c1 -> "Moritz\nMustermann"};

c1->"Ex-Kind";

x1 [shape=circle,label="",height=0.01,width=0.01];
{rank=same; "Volker\nVersuch" -> x1 -> "Veronika\nVersuch"};
{rank=same"Maxima\nMustermann"; "Volker\nVersuch" }
x1 ->  "Nina\nMustermann";

p1 [shape=circle,label="",height=0.01,width=0.01];
p2 [shape=circle,label="",height=0.01,width=0.01];
p3 [shape=circle,label="",height=0.01,width=0.01];
q1 [shape=circle,label="",height=0.01,width=0.01];
q2 [shape=circle,label="",height=0.01,width=0.01];
q3 [shape=circle,label="",height=0.01,width=0.01];

{rank=same; "Moritz\nMustermann" -> p1 -> "Nina\nMustermann"};
{rank=same;q1 -> q2 -> q3};
{rank=same;"Bart";"Lisa";"Maggie"};

p1 -> p2 -> p3 ->q2;
q1 -> Bart;
q2 -> Lisa;
q3 -> Maggie;

v1 [shape=circle,label="",height=0.01,width=0.01];
{rank=same; "Bart" -> v1 -> "Schwiegertochter"};

}

Body:
You need to force the order of the last (Bart) row with invisible edges; I have added

{ rank = same; Schwiegertochter -> Lisa -> Maggie[ style = invis ] }

at the bottom; I also have (more for my own pleasure than for real need) cleaned up the code, coming up with

digraph G
{
    graph[ splines=ortho, pad="0.4", nodesep="0.2", ranksep="0.2" ];
    mindist=1

    node[ shape=box, regular=0,color="black", style="filled" fillcolor="grey", width=1.5, height = 0.5, fontsize=10 ];
    "Max\nMustermann", "Maxi\nTestermann", "Moritz\nMustermann", "Nina\nMustermann";
    "Volker\nVersuch", "Veronika\nVersuch", "Maximilian\nMustermann", "Maxima\nMustermann";
    "Bart", "Lisa", "Maggie", "Ex\nPartner", "Schwiegertochter", "Enkel1", "Ex-Kind";

    node[ shape=circle,label="",height=0.01,width=0.01 ];
    a1, b1, b2, b3, c1, x1, p1, p2, p3, q1, q2, q3, v1;

    edge[ dir=none ];

    { rank=same; "Maximilian\nMustermann" -> a1 -> "Maxima\nMustermann" }
    { rank=same; b1 -> b2 -> b3 }
    a1 -> b2;
    b1 -> "Max\nMustermann";
    b2 -> "Maxi\nTestermann";
    b3 -> "Moritz\nMustermann";

    { rank=same; "Ex\nPartner" -> c1 -> "Moritz\nMustermann" }

    c1->"Ex-Kind";

    { rank=same; "Volker\nVersuch" -> x1 -> "Veronika\nVersuch" }
    { rank=same"Maxima\nMustermann"; "Volker\nVersuch" }
    x1 ->  "Nina\nMustermann";

    { rank=same; "Moritz\nMustermann" -> p1 -> "Nina\nMustermann"}
    { rank=same;q1 -> q2 -> q3}
    { rank=same;"Bart";"Lisa";"Maggie" }

    p1 -> p2 -> p3 ->q2;
    q1 -> Bart;
    q2 -> Lisa;
    q3 -> Maggie;

    { rank=same; "Bart" -> v1 -> "Schwiegertochter" }
    { rank = same; Schwiegertochter -> Lisa -> Maggie[ style = invis ] }
    v1 -> Enkel1;
}

which gives you


问:
Postgres Database Exception
Exception (Database Exception) 'yii\db\Exception' with message</p>

```<code>SQLSTATE[42601]: Syntax error: 7
ERROR: a column definition list is required for functions returning "record"
</code>```

答:
If you have a function that is defined as RETURNS [SETOF] record, you have to specify a column list when you call it. This is because the return type has to be known at query parse time.

An example:

```<code>SELECT * FROM myfun() AS myfun(a integer, b text);
</code>```

Title: Postgres Database Exception

Body:
Exception (Database Exception) 'yii\db\Exception' with message

SQLSTATE[42601]: Syntax error: 7
ERROR: a column definition list is required for functions returning "record"

Body:
If you have a function that is defined as RETURNS [SETOF] record, you have to specify a column list when you call it. This is because the return type has to be known at query parse time.

An example:

SELECT * FROM myfun() AS myfun(a integer, b text);


问:
Moving from IIS6 to IIS7.5 - Custom Handlers
I am moving a site from IIS6 on one server to IIS7.5 on another.
This site was not writen by me, and from what I can tell, they use custom handlers to get around the AJAX limitations of the day.
I copied the code from the old server to the new (pre-compieled) and everything works except the "AJAX" stuff. There are several calls in the code to ashx files. These calls return .js files. On the old server this works great. Does not work on the new server.
In the web.config file I found the following lines:

```<code><httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
</code>```

For some reason this is not working in IIS7.5
Any suggestions are welcome.

Thank you!

答:
I suspect this could be down to the configuration of the application pool managed pipeline mode. You can easily confirm this by changing the Managed Pipeline Mode for the application pool the site runs under to Classic. If this works and you want to continue to run in Integrated mode then you will need to add a handlers section to the web.config. This is different from the httpHandlers information you noted above.

The new handlers section should be in the system.webServer section. I'm sorry I do not know the exact setting for the item you note but you will need to include the preCondition="integratedMode" if you wish to run in integrated mode.

Body:
I am moving a site from IIS6 on one server to IIS7.5 on another.
This site was not writen by me, and from what I can tell, they use custom handlers to get around the AJAX limitations of the day.
I copied the code from the old server to the new (pre-compieled) and everything works except the "AJAX" stuff. There are several calls in the code to ashx files. These calls return .js files. On the old server this works great. Does not work on the new server.
In the web.config file I found the following lines:

<httpHandlers>
<add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>

For some reason this is not working in IIS7.5
Any suggestions are welcome.

Thank you!


问:
Laravel 5: Check if event date range is not already taken
I'm creating calendar for few days events and the events can not overlap. But event can start/end when another event starts/ends.

In Laravel, in my event model table I am storing start and end date of events.
How can I check before storing new event do database, if it is valid (is not overlapping with existing events, excluding margin/boundary days) ?

In advance thank You very much for Your help.

答:
Use it for all variants intersections date ranges. It help for me</p>

```<code>$rangeCount = TransferSchedule::where(function ($query) use ($from, $to) {
                $query->where(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $from)
                        ->where('date_to', '>=', $from);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $to)
                        ->where('date_to', '>=', $to);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '>=', $from)
                        ->where('date_to', '<=', $to);
                });
            })->count();
</code>```

Body:
Use it for all variants intersections date ranges. It help for me

$rangeCount = TransferSchedule::where(function ($query) use ($from, $to) {
                $query->where(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $from)
                        ->where('date_to', '>=', $from);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $to)
                        ->where('date_to', '>=', $to);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '>=', $from)
                        ->where('date_to', '<=', $to);
                });
            })->count();


问:
Is Slice<Results> still lazy loaded in Realm?
I'm trying to limit the results of my Realm query. If I have a million records and I call Swift prefix function, does it touch all million records?

Here's what I'm trying to do:

```<code>let objects = realm.objects(BookRealmObject.self)
    .sorted(byKeyPath: "createdAt", ascending: false)

let items: [BookType] = {
    guard let limit = request.limit, limit > 0 else {
        return objects.map { Book(from: $0) }
    }

    return objects.prefix(limit).map { Book(from: $0) }
}()
</code>```

The type returned from prefix is Slice<Results<Element>>. Whether a limit is requested by the caller or not, I need to convert it to a plain object to pass to different threads.

Is this the proper way to handle this, or is there a more optimized, concise way to do this?

答:
As we can find in docs:

Since queries in Realm are lazy, performing this sort of paginating behavior isn’t necessary at all, as Realm will only load objects from the results of the query once they are explicitly accessed.

So, when you get the prefix of objects it still should be lazy, but when you access objects using map you lose the lazy feature.

Body:
I'm trying to limit the results of my Realm query. If I have a million records and I call Swift prefix function, does it touch all million records?

Here's what I'm trying to do:

let objects = realm.objects(BookRealmObject.self)
    .sorted(byKeyPath: "createdAt", ascending: false)

let items: [BookType] = {
    guard let limit = request.limit, limit > 0 else {
        return objects.map { Book(from: $0) }
    }

    return objects.prefix(limit).map { Book(from: $0) }
}()

The type returned from prefix is Slice<Results<Element>>. Whether a limit is requested by the caller or not, I need to convert it to a plain object to pass to different threads.

Is this the proper way to handle this, or is there a more optimized, concise way to do this?


问:
Trying to save timeStamp recorded in jmeter results from csv to MSSQL server
I am not able to save proper timeStamp from JMeter to CSV and same CSV to MSSQL server.

I am saving results right now but they appear in a wierd manner like 1559087654 etc

I want proper format of the timeStamp at what time and date exact results were recorded.

答:
The default items to be saved can be defined in the jmeter.properties (or user.properties) file located under bin folder. Give preference to user.properties. Find the below line in jmeter properties and copy paste it in user.properties in the end of the file. Remove the hash in front. Restart jmeter.

jmeter.save.saveservice.timestamp_format=yyyy/MM/dd HH:mm:ss.SSS

Check default configuration for more info.

Hope this helps.


问:
Is using enums safe in all compilers?
In a discussion, a colleague told me that he never uses enum because he experienced that some C-compilers don't cope with the enum statement correctly.

He couldn't remember which compiler exactly had problems but among the problems, there were errors when doing something like

```<code>enum my_enum{
  my_enum_first  = 5;
  my_enum_second = 10;
};
</code>```

i.e. initializing enum values instead of letting the compiler do the automatic assignment. Another one was that the compiler decides for itself how big the enum is and therefore you could have unpredictable behavior for sizeof my_enum when compiling your code under various platforms.

To get around that, he told me to better use #defines to define the constant elements. But especially for using doxygen it's quite handy to have an enum (e.g. as function parameter) because in the generated documentation, you could simply click on my_enum and directly jump to the description of my_enum.

Another example would be code completion, where your IDE tells you what you could specify as valid parameters for functions. I know that – as long as you're compiling the code as C-code – that there's no type-safety (i.e. I could also specify 5 instead of my_enum_first), so the use of an enum seems to be a more cosmetic thing.

The question is: do you know any compilers that have limitations regarding the usage of enum?

Edit 1:

Regarding the environment: we are developing for various embedded platforms, so there could also be a compiler for some obscure micro-controller...

Edit 2:

He could tell me that the KEIL C51 compiler didn't play well with enums. Are there any experiences with current versions of the C51 compiler?

答:
Compilers are free to choose the size of an enum based on its range of possible values. This only really becomes an issue if you're exposing enums in your API, and users of your code may be using a different compiler or build options.

In this case, confusion can be caused by the calling code passing in a 16-bit value, for example, and the receiving code expecting it to be 32 bits. If the top 16 bits of the passed-in value are left uninitialized, then bad things will happen.

You can work around this kind of issue by including a dummy entry in your enum to enforce a minimum size.

For example:

```<code>typedef enum {
    FirstValue = 12,
    SecondValue = 25,

    DummyValue = 65536  // force enum to be greater than 16 bits
} MyEnum;
</code>```

Title: Is using enums safe in all compilers?

Body:
In a discussion, a colleague told me that he never uses enum because he experienced that some C-compilers don't cope with the enum statement correctly.

He couldn't remember which compiler exactly had problems but among the problems, there were errors when doing something like

enum my_enum{
  my_enum_first  = 5;
  my_enum_second = 10;
};

i.e. initializing enum values instead of letting the compiler do the automatic assignment. Another one was that the compiler decides for itself how big the enum is and therefore you could have unpredictable behavior for sizeof my_enum when compiling your code under various platforms.

To get around that, he told me to better use #defines to define the constant elements. But especially for using doxygen it's quite handy to have an enum (e.g. as function parameter) because in the generated documentation, you could simply click on my_enum and directly jump to the description of my_enum.

Another example would be code completion, where your IDE tells you what you could specify as valid parameters for functions. I know that – as long as you're compiling the code as C-code – that there's no type-safety (i.e. I could also specify 5 instead of my_enum_first), so the use of an enum seems to be a more cosmetic thing.

The question is: do you know any compilers that have limitations regarding the usage of enum?

Edit 1:

Regarding the environment: we are developing for various embedded platforms, so there could also be a compiler for some obscure micro-controller...

Edit 2:

He could tell me that the KEIL C51 compiler didn't play well with enums. Are there any experiences with current versions of the C51 compiler?

Body:
Compilers are free to choose the size of an enum based on its range of possible values. This only really becomes an issue if you're exposing enums in your API, and users of your code may be using a different compiler or build options.

In this case, confusion can be caused by the calling code passing in a 16-bit value, for example, and the receiving code expecting it to be 32 bits. If the top 16 bits of the passed-in value are left uninitialized, then bad things will happen.

You can work around this kind of issue by including a dummy entry in your enum to enforce a minimum size.

For example:

typedef enum {
    FirstValue = 12,
    SecondValue = 25,

    DummyValue = 65536  // force enum to be greater than 16 bits
} MyEnum;


问:
How google oauth tokens can use to sign user in Nodejs RESTapi
We have a project.

Nodejs RESTapi

React native mobile app

I followed a tutorial about Google oAuth signin / signup in Nodejs. There basically front end sends and access token to the back-end and the back-end verify that token with the Google, If that token is valid back-end generates a JWT token and pass to the front-end.

I think this follow will nicely working with the Single page applications,
but I don't know how this gonna be work with react native mobile apps. Because, according to the tutorial that access token get expired.

I have no idea what should I do after that token expired?

答:
Usually you also get a refresh_token that it is used to renew the main access_token.
The access_token has a limited lifetime, but the refresh_token never expires unless you remove the authorization on Google's side. In that case you need to ask the client to login via Google's OAuth once again.</p>


问:
How to upload and read PDF files in Django
I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename))

TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile

index.html

```<code><input type="file" name="fupload" multiple>
</code>```

view.py

```<code>if request.method == 'POST':
        files = request.FILES.getlist('fupload')

        pdf_data = []
        for filename in files:
            read_pdf = PyPDF2.PdfFileReader(open(filename))
            page = read_pdf.getPage(0)
            page_content = page.extractText()
            pdf_data.append(page_content)
</code>```

Can any body tell me what I am doing wrong. Thanks in advance

答:
You need to modify your views.py to this:</p>

```<code>if request.method == 'POST' and request.FILES['myfile']:

        pdfFileObj = request.FILES['myfile'].read()
        pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
        NumPages = pdfReader.numPages
        i = 0
        content = []
        while (i<NumPages):
            text = pdfReader.getPage(i)
            content.append(text.extractText())
            i +=1
</code>```

Body:
I am trying to create a simple django application which takes some PDF files from user and then read its contents. So far I have written the code as mentioned below, But it doesn't seem to work. It's producing an error at this line PyPDF2.PdfFileReader(open(filename))

TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile

index.html

<input type="file" name="fupload" multiple>

view.py

if request.method == 'POST':
        files = request.FILES.getlist('fupload')

        pdf_data = []
        for filename in files:
            read_pdf = PyPDF2.PdfFileReader(open(filename))
            page = read_pdf.getPage(0)
            page_content = page.extractText()
            pdf_data.append(page_content)

Can any body tell me what I am doing wrong. Thanks in advance

Body:
You need to modify your views.py to this:

if request.method == 'POST' and request.FILES['myfile']:

        pdfFileObj = request.FILES['myfile'].read()
        pdfReader = PyPDF2.PdfFileReader(io.BytesIO(pdfFileObj))
        NumPages = pdfReader.numPages
        i = 0
        content = []
        while (i<NumPages):
            text = pdfReader.getPage(i)
            content.append(text.extractText())
            i +=1


问:
TSQL copy table data to another table with custom values
I have 2 tables with identical columns expect one which is userId. I want to copy all the data from the first table into the second one and add custom userId to the column that is missing. Thus far without success.

The query is shown below. Insert Quality, Quantity, Supplier and UserId (which doesn't exist in the table im getting data)

```<code>`DECLARE @UserId int = 5611; -- add this to all the data from dbo.GasStation

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT * FROM dbo.GasStation -- UserId doesn't exist in this table
-- Add somehow @UserId to all the data i'm getting from GasStation in order to satisfy the column UserId in the NewGasStation`
</code>```

All the data i'm getting from dbo.GasStation to be inserted to dbo.NewGasStation adding this custom UserId to all the results.

答:
You also don't need to discriminate the columns if you just want to copy them all. Just use the *.

Something like this:

```<code>DECLARE @UserId integer = 5611;

INSERT INTO [Target]
SELECT *, @UserId FROM [Source]
</code>```

Body:
I have 2 tables with identical columns expect one which is userId. I want to copy all the data from the first table into the second one and add custom userId to the column that is missing. Thus far without success.

The query is shown below. Insert Quality, Quantity, Supplier and UserId (which doesn't exist in the table im getting data)

`DECLARE @UserId int = 5611; -- add this to all the data from dbo.GasStation

INSERT INTO dbo.NewGasStation (Quality, Quantity, Supplier, UserId)
SELECT * FROM dbo.GasStation -- UserId doesn't exist in this table
-- Add somehow @UserId to all the data i'm getting from GasStation in order to satisfy the column UserId in the NewGasStation`

All the data i'm getting from dbo.GasStation to be inserted to dbo.NewGasStation adding this custom UserId to all the results.

Body:
You also don't need to discriminate the columns if you just want to copy them all. Just use the *.

Something like this:

DECLARE @UserId integer = 5611;

INSERT INTO [Target]
SELECT *, @UserId FROM [Source]


问:
Strings in 2D lists in Python
This is a normal 2D list in python containing what supposed to be white spaces:

```<code>shape = [
["", "", ""],
["", "", ""],
["", "", ""]]
</code>```

but when printing this array using for loop that's what happens:

```<code>['', '', '']
['', '', '']
['', '', '']
</code>```

isn't it supposed to show only white space ? How do I remove these single quot marks but leave the commas ?

答:
If it's just about printing something to the screen, you don't need to first create a list, just create a string like this:

```<code>print("[ , , ]\n[ , , ]\n[ , , ]")
</code>```

Or even

```<code>print("[ | | ]\n[ | | ]\n[ | | ]")
</code>```

Which I think looks better:

```<code>[ , , ]
[ , , ]
[ , , ]

[ | | ]
[ | | ]
[ | | ]
</code>```

Title: Strings in 2D lists in Python

Body:
This is a normal 2D list in python containing what supposed to be white spaces:

shape = [
["", "", ""],
["", "", ""],
["", "", ""]]

but when printing this array using for loop that's what happens:

['', '', '']
['', '', '']
['', '', '']

isn't it supposed to show only white space ? How do I remove these single quot marks but leave the commas ?

Body:
If it's just about printing something to the screen, you don't need to first create a list, just create a string like this:

print("[ , , ]\n[ , , ]\n[ , , ]")

Or even

print("[ | | ]\n[ | | ]\n[ | | ]")

Which I think looks better:

[ , , ]
[ , , ]
[ , , ]

[ | | ]
[ | | ]
[ | | ]


问:
Dialog-like activity
I am looking to display a Dialog with a list of data.
I came across this article: http://wiresareobsolete.com/wordpress/2010/01/android-dialog-or-is-it/
It claims that it is better to define it as an activity and then use the Theme.Dialog.

Is this correct?

I am not expecting any feedback from the user - it is an info-only screen.

答:
Hey you can create a custom dialog and then you can create your separate layout or XML file ,inflate that XML to that dialog and then you can show anything in the dialog that you have in that XML.

Or you can even use this techniques, custom dialog with list

Title: Dialog-like activity


问:
How to use own copy of static library in each shared library
I have some static library that I can't change or rebuild. The library uses global variables. Something like this:

```<code>//lib A
#include <iostream>

static int i = 0;

void printA(){
    std::cout << i++ << std::endl;
}
</code>```

I want to create two shared libraries that have their own "copy" of static library and its global state:

```<code>//lib B
#include "liba.h"

void printB(){
    printA();
}
</code>```

```<code>//lib C
#include "liba.h"

void printC(){
    printA();
}
</code>```

... and use them simultaneously:

```<code>#include "libb.h"
#include "libc.h"

int main(){
    printB();
    printB();
    printC();
    printC();
}
</code>```

I expect following output:

```<code>0
1
0
1
</code>```

.. but actually get:

```<code>0
1
2
3
</code>```

Seems like libB and libC share common counter variable. If had access to libA source code, I would rebuild it with -fvisibility=hidden. But unfortunately I have only binary.

Is there any way to achieve expected behavior without libA rebuilding?

答:
You can copy the static library and rename all symbols that use the global state.  Because the symbols are compiled with c++, you are out of luck, the symbols are mangled.

You can write a C interface for all the accesses and recompile the static library hiding it's symbols and then use some objcopy --prefix-symbols org++ -Wl,--wrap=printA to prefix/rename the C symbols.

Or you need to know beforehand the already mangled C++ names, and then call objcopy --redefine-sym _Z6printAv=_Z10printAcopyv etc. for each symbol the library exports.

Below is the test setup that calls the objcopy on the mangled names. I found out the symbol names by inspecting the object files, nm a.o and nm c.o. Here it is:

```<code>cat <<EOF >Makefile
all: liba.a b.o main.o  c.o
    # we have access only to liba.a only
    objcopy --redefine-sym _Z6printAv=_Z10printAcopyv liba.a libacopy.a
    g++ main.o b.o c.o liba.a libacopy.a -o a.out
    ./a.out

liba.a: a.o
    ar rcs liba.a a.o

clean:
    rm -fr *.o *.a *.out tmp

EOF

cat <<EOF >a.cpp
#include <iostream>

static int i = 0;

void printA(){
    std::cout << i++ << std::endl;
}
EOF

cat <<EOF >b.cpp
void printA();
void printB(){
    printA();
}
EOF

cat <<EOF >c.cpp
void printAcopy();
void printC(){
    printAcopy();
}
EOF

cat <<EOF >main.cpp
void printB();
void printC();
int main(){
    printB();
    printB();
    printC();
    printC();
}
EOF
</code>```

You can compile with make and run:

```<code>g++    -c -o a.o a.cpp
ar rcs liba.a a.o
g++    -c -o b.o b.cpp
g++    -c -o main.o main.cpp
g++    -c -o c.o c.cpp
# we have access only to liba.a only
objcopy --redefine-sym _Z6printAv=_Z10printAcopyv liba.a libacopy.a
g++ main.o b.o c.o liba.a libacopy.a -o a.out
./a.out
0
1
0
1
</code>```

Body:
I have some static library that I can't change or rebuild. The library uses global variables. Something like this:

//lib A
#include <iostream>

static int i = 0;

void printA(){
    std::cout << i++ << std::endl;
}

I want to create two shared libraries that have their own "copy" of static library and its global state:

//lib B
#include "liba.h"

void printB(){
    printA();
}

//lib C
#include "liba.h"

void printC(){
    printA();
}

... and use them simultaneously:

#include "libb.h"
#include "libc.h"

int main(){
    printB();
    printB();
    printC();
    printC();
}

I expect following output:

0
1
0
1

.. but actually get:

0
1
2
3

Seems like libB and libC share common counter variable. If had access to libA source code, I would rebuild it with -fvisibility=hidden. But unfortunately I have only binary.

Is there any way to achieve expected behavior without libA rebuilding?

Body:
You can copy the static library and rename all symbols that use the global state.  Because the symbols are compiled with c++, you are out of luck, the symbols are mangled.

You can write a C interface for all the accesses and recompile the static library hiding it's symbols and then use some objcopy --prefix-symbols org++ -Wl,--wrap=printA to prefix/rename the C symbols.

Or you need to know beforehand the already mangled C++ names, and then call objcopy --redefine-sym _Z6printAv=_Z10printAcopyv etc. for each symbol the library exports.

Below is the test setup that calls the objcopy on the mangled names. I found out the symbol names by inspecting the object files, nm a.o and nm c.o. Here it is:

cat <<EOF >Makefile
all: liba.a b.o main.o  c.o
    # we have access only to liba.a only
    objcopy --redefine-sym _Z6printAv=_Z10printAcopyv liba.a libacopy.a
    g++ main.o b.o c.o liba.a libacopy.a -o a.out
    ./a.out

liba.a: a.o
    ar rcs liba.a a.o

clean:
    rm -fr *.o *.a *.out tmp

EOF

cat <<EOF >a.cpp
#include <iostream>

static int i = 0;

void printA(){
    std::cout << i++ << std::endl;
}
EOF

cat <<EOF >b.cpp
void printA();
void printB(){
    printA();
}
EOF

cat <<EOF >c.cpp
void printAcopy();
void printC(){
    printAcopy();
}
EOF

cat <<EOF >main.cpp
void printB();
void printC();
int main(){
    printB();
    printB();
    printC();
    printC();
}
EOF

You can compile with make and run:

g++    -c -o a.o a.cpp
ar rcs liba.a a.o
g++    -c -o b.o b.cpp
g++    -c -o main.o main.cpp
g++    -c -o c.o c.cpp
# we have access only to liba.a only
objcopy --redefine-sym _Z6printAv=_Z10printAcopyv liba.a libacopy.a
g++ main.o b.o c.o liba.a libacopy.a -o a.out
./a.out
0
1
0
1


问:
How to listen for modifier keys pressed in a click event on a deck.gl layer?
I would like to listen for shift-clicks on icons in a deck.gl IconLayer. An icon can have a selected state and with shift-clicking I want to be able to select multiple icons. I am using deck.gl in combination with Google Maps.

The onClick event of the (Icon)Layer returns info and event, with event.srcEvent.wa containing the MouseEvent. This has the shiftKey property but is always false regardless of the shift key being pressed or not.

new IconLayer({
  onClick: (info, event) => {
    console.log(
      `Shift key was ${event.srcEvent.wa.shiftKey ? '' : 'not '}pressed`,
    );
  },
});
```

I expected the shiftKey property to reflect the state of the shift key being pressed or not. Although this wa property seems a bit weird and the whole event is actually not documented as far as I've seen.

答:
From Pessimistress on GitHub (https://github.com/uber/deck.gl/issues/3147):

event.srcEvent is the raw event generated by the Google Maps API (map.addListener('click', cb)). You may need to find out how Google Maps exposes the shift key state.

Google Maps doesn't seem to be very helpful in exposing modifier keys. I found this quirky solution https://stackoverflow.com/a/47574211/11561793

Body:
I would like to listen for shift-clicks on icons in a deck.gl IconLayer. An icon can have a selected state and with shift-clicking I want to be able to select multiple icons. I am using deck.gl in combination with Google Maps.

The onClick event of the (Icon)Layer returns info and event, with event.srcEvent.wa containing the MouseEvent. This has the shiftKey property but is always false regardless of the shift key being pressed or not.

new IconLayer({
  onClick: (info, event) => {
    console.log(
      `Shift key was ${event.srcEvent.wa.shiftKey ? '' : 'not '}pressed`,
    );
  },
});

I expected the shiftKey property to reflect the state of the shift key being pressed or not. Although this wa property seems a bit weird and the whole event is actually not documented as far as I've seen.


问:
React Native - Focus a TextInput (Inside custom Component) that is inside of a Flat List element
I'm a React Native beginner and I'm working with a Flat List and custom Rows. Inside of each custom row, I have elements like Text, TextInput, and Button. The problem is that I need to press one of these buttons that enables and triggers a focus to the TextInput.

I tried implementing that with refs but everything freezes so I don't know how to do that correctly.

My constructor

```<code>class EditProfileScreen extends React.Component {
  constructor(props) {
    super(props);
    this._rowRefs = {}
  }
</code>```

My FlatList and MyCustomRow

```<code>_renderItem = ({item, index}) => {
    return (
      <MyCustomRow
                       fieldname={item.fieldname}
                       value={item.value}
                       isEditable={item.isEditable}
                       editFieldHandler={ this.editFieldHandler }
                       allowsEdition={item.allowsEdition}
                       ref={ref => { this._rowRefs[index] = ref}}
                      />
    )
  }

  _keyExtractor = (item, index) => index.toString();

  render() {
    return (
      <View style={styles.mainContainer}>
        <FlatList
          ref={this.flatListRef}
          style={styles.flatList}
          data={this.state.fields}
          renderItem={this._renderItem}
          keyExtractor= {this._keyExtractor}
          extraData={this.state.refresh}
        />
      </View>
    );
  }
</code>```

Trying to print the refs:

```<code>enableField(name) {
    console.log('Printing refs...')
    console.log(this._rowRefs) // the Button pressed freezes here
  }
</code>```

I expect to see what's inside of _rowRefs, but instead of that, the button just gets frozen and I never see that result in the console

答:
Can you try the above code after removing </p>

```<code>console.log(this._rowRefs)
</code>```

Body:
I'm a React Native beginner and I'm working with a Flat List and custom Rows. Inside of each custom row, I have elements like Text, TextInput, and Button. The problem is that I need to press one of these buttons that enables and triggers a focus to the TextInput.

I tried implementing that with refs but everything freezes so I don't know how to do that correctly.

My constructor

class EditProfileScreen extends React.Component {
  constructor(props) {
    super(props);
    this._rowRefs = {}
  }

My FlatList and MyCustomRow

_renderItem = ({item, index}) => {
    return (
      <MyCustomRow
                       fieldname={item.fieldname}
                       value={item.value}
                       isEditable={item.isEditable}
                       editFieldHandler={ this.editFieldHandler }
                       allowsEdition={item.allowsEdition}
                       ref={ref => { this._rowRefs[index] = ref}}
                      />
    )
  }

  _keyExtractor = (item, index) => index.toString();

  render() {
    return (
      <View style={styles.mainContainer}>
        <FlatList
          ref={this.flatListRef}
          style={styles.flatList}
          data={this.state.fields}
          renderItem={this._renderItem}
          keyExtractor= {this._keyExtractor}
          extraData={this.state.refresh}
        />
      </View>
    );
  }

Trying to print the refs:

enableField(name) {
    console.log('Printing refs...')
    console.log(this._rowRefs) // the Button pressed freezes here
  }

I expect to see what's inside of _rowRefs, but instead of that, the button just gets frozen and I never see that result in the console

Body:
Can you try the above code after removing

console.log(this._rowRefs)


问:
How to create custom background for UITableView section?
I'm trying to create a custom background for my tableview section. The look I'm going for is this:

How do I customize the tableview section background/layer please, rather than just the individual cells?

Edit: Just to clarify - I'm talking about the white background under 'Latest Transactions'. So the top of the section is rounded (as is bottom) but all the rows are rectangular.

答:
Use UITableViewDelegate method

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        <#code#>
    }
</code>```

This will help you to set the view of each section header programatically.

Body:
Use UITableViewDelegate method

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        <#code#>
    }

This will help you to set the view of each section header programatically.


问:
Swift Codable decode changing JSON and ignoring some fields
I have some REST API, which returns JSON. This API is used by more than one service (mobile, web,...) and it returns JSON that has more fields inside than I need and some of those additional fields can be changed on weekly basis.
For example I have JSON like that:

{   "name": "Toyota Prius",   "horsepower": 134,   "mileage": 123241,
  "manufactured": 2017,   "location": "One city",   "origin": "Japan",

  "convert": true //more properties follows... }

In mobile app I would only need to decode fields: name, horsepower and manufactured date, the rest can be ignored. Also some fields like origin haven't existed before but was added few days ago.

Question is how to write bulletproof decoder that would not break if there are some changes in JSON that do not affect my model in app? Also I have no word in output JSON from server and I cannot affect it. I just get data and I have to work with what I get.

I have wrote some experimental code for playground (car isn't printed out):

import UIKit

struct Car: Codable
{
    let name: String
    let horsePower: Int
    let selected: Bool //this is used as additional property inside my app to mark selected cars
    let index: Int //this is used as additional property inside my app for some indexing purposes

    enum CodingKeys: String, CodingKey
    {
        case name
        case horsePower = "horsepower"
        case selected
        case index
    }

    init(from decoder: Decoder) throws
    {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        selected = false
        index = 0

        name = try values.decode(String.self, forKey: .name)
        horsePower = try values.decode(Int.self, forKey: .horsePower)
    }
}

let json = "{\"name\": \"Toyota Prius\",\"horsepower\": 134, \"convert\", true}"

let data = json.data(using: .utf8)

if let car = try? JSONDecoder().decode(Car.self, from: data!)
{
    //does not print... :(
    print(car)
}

```

I would like to get car printed in my example but mostly have a working proof code that will not break if JSON get changed.
Also is there a way to get an decoding error description somehow?
I know there are a lot of things in apple documentation, but mostly it is just too confusing to me and I couldn't find any useful examples for my problem.

答:
First of all never try? JSONDecoder... , catch always the error and print it. DecodingErrors are extremely descriptive. They tell you exactly what is wrong and even where.

In your example you will get

"The given data was not valid JSON. ... No value for key in object around character 52."

which is the wrong comma (instead of a colon) after convert\"

To decode only specific keys declare the CodingKeys accordingly and delete the init method. selected and index are most likely supposed to be mutable so declare them as variable with a default value.

If the backend changes the JSON structure you'll get an error. The decoding process will break anyway regardless of the parsing API.

```<code>struct Car: Codable
{
    let name: String
    let horsePower: Int
    let convert : Bool

    var selected = false
    var index = 0

    enum CodingKeys: String, CodingKey {
        case name, horsePower = "horsepower", convert
    }
}

let json = """
{"name":"Toyota Prius","horsepower":134,"convert":true}
"""

let data = Data(json.utf8)

do {
    let car = try JSONDecoder().decode(Car.self, from: data)
    print(car)
} catch { print(error) }
</code>```

Body:
I have some REST API, which returns JSON. This API is used by more than one service (mobile, web,...) and it returns JSON that has more fields inside than I need and some of those additional fields can be changed on weekly basis.
For example I have JSON like that:

{   "name": "Toyota Prius",   "horsepower": 134,   "mileage": 123241,
  "manufactured": 2017,   "location": "One city",   "origin": "Japan",

  "convert": true //more properties follows... }

In mobile app I would only need to decode fields: name, horsepower and manufactured date, the rest can be ignored. Also some fields like origin haven't existed before but was added few days ago.

Question is how to write bulletproof decoder that would not break if there are some changes in JSON that do not affect my model in app? Also I have no word in output JSON from server and I cannot affect it. I just get data and I have to work with what I get.

I have wrote some experimental code for playground (car isn't printed out):

import UIKit

struct Car: Codable
{
    let name: String
    let horsePower: Int
    let selected: Bool //this is used as additional property inside my app to mark selected cars
    let index: Int //this is used as additional property inside my app for some indexing purposes

    enum CodingKeys: String, CodingKey
    {
        case name
        case horsePower = "horsepower"
        case selected
        case index
    }

    init(from decoder: Decoder) throws
    {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        selected = false
        index = 0

        name = try values.decode(String.self, forKey: .name)
        horsePower = try values.decode(Int.self, forKey: .horsePower)
    }
}

let json = "{\"name\": \"Toyota Prius\",\"horsepower\": 134, \"convert\", true}"

let data = json.data(using: .utf8)

if let car = try? JSONDecoder().decode(Car.self, from: data!)
{
    //does not print... :(
    print(car)
}

I would like to get car printed in my example but mostly have a working proof code that will not break if JSON get changed.
Also is there a way to get an decoding error description somehow?
I know there are a lot of things in apple documentation, but mostly it is just too confusing to me and I couldn't find any useful examples for my problem.

Body:
First of all never try? JSONDecoder... , catch always the error and print it. DecodingErrors are extremely descriptive. They tell you exactly what is wrong and even where.

In your example you will get

"The given data was not valid JSON. ... No value for key in object around character 52."

which is the wrong comma (instead of a colon) after convert\"

To decode only specific keys declare the CodingKeys accordingly and delete the init method. selected and index are most likely supposed to be mutable so declare them as variable with a default value.

If the backend changes the JSON structure you'll get an error. The decoding process will break anyway regardless of the parsing API.

struct Car: Codable
{
    let name: String
    let horsePower: Int
    let convert : Bool

    var selected = false
    var index = 0

    enum CodingKeys: String, CodingKey {
        case name, horsePower = "horsepower", convert
    }
}

let json = """
{"name":"Toyota Prius","horsepower":134,"convert":true}
"""

let data = Data(json.utf8)

do {
    let car = try JSONDecoder().decode(Car.self, from: data)
    print(car)
} catch { print(error) }


问:
Why is a regex match with an empty right-hand side false in bash 3.2, and true in 4.2?
Given two strings :-

```<code>a="hello h"
b=""
</code>```

In bash version 4.2, their regex compare results in true

```<code>[[ "${a}" =~ "${b}" ]]
echo $?                           # 0
</code>```

In bash version 3.2, the regex compare results in false

```<code>[[ "${a}" =~ "${b}" ]]
echo $?                           # 2
</code>```

Edit : 1st result is run on linux os shipping with 4.2.46(2)-release bash, while 2nd result is run OS Mojave running 3.2.57(1)-release bash.

答:
bash regex match behaving differently across bash versions

Evidently they do.

In bash version 3.2, the regex compare results in false

That's not quite correct.  You indicate that the exit status is 2, which conveys that the pattern given is syntactically incorrect.  That's a failure result, yes, and the status will be treated as false in boolean context, but it does not convey that the string does not match the pattern.  Rather, it conveys that no regex match attempt was performed at all.

I'm not sure where to find a manual for Bash 3.2, which is pretty old, but it's not crazy that it rejects empty regexes.  You should be able to work around that issue by handling the empty-regex case specially:

```<code>[[ -z "${b}" ]] || [[ "${a}" =~ "${b}" ]]
echo $?
</code>```

Do note, however, that quoting the regex causes it to be treated as a plain string.  If you want to test whether the plain string stored in variable bappears as a substring of the one stored in a, then you could also do so via a case expression:

```<code>case $a in
  *${b}*) echo "it matches" ;;
  *)      echo "it doesn't match" ;;
esac
</code>```

Body:
Given two strings :-

a="hello h"
b=""

In bash version 4.2, their regex compare results in true

[[ "${a}" =~ "${b}" ]]
echo $?                           # 0

In bash version 3.2, the regex compare results in false

[[ "${a}" =~ "${b}" ]]
echo $?                           # 2

Edit : 1st result is run on linux os shipping with 4.2.46(2)-release bash, while 2nd result is run OS Mojave running 3.2.57(1)-release bash.

Body:
bash regex match behaving differently across bash versions

Evidently they do.

In bash version 3.2, the regex compare results in false

That's not quite correct.  You indicate that the exit status is 2, which conveys that the pattern given is syntactically incorrect.  That's a failure result, yes, and the status will be treated as false in boolean context, but it does not convey that the string does not match the pattern.  Rather, it conveys that no regex match attempt was performed at all.

I'm not sure where to find a manual for Bash 3.2, which is pretty old, but it's not crazy that it rejects empty regexes.  You should be able to work around that issue by handling the empty-regex case specially:

[[ -z "${b}" ]] || [[ "${a}" =~ "${b}" ]]
echo $?

Do note, however, that quoting the regex causes it to be treated as a plain string.  If you want to test whether the plain string stored in variable bappears as a substring of the one stored in a, then you could also do so via a case expression:

case $a in
  *${b}*) echo "it matches" ;;
  *)      echo "it doesn't match" ;;
esac


问:
How can i trigger a function in JS file from gmail addon button?
I have js library which has some inbuilt functionalities required for our application. Now i want to import my js library and its css files in Gmail addon. After that i want bind a function to that button id so that whenever the button is clicked function in my library executes.

How can i do that? Please see sample code

As per the sample code myLib.js has function myFunc() which takes component id and url to be opened. So i created button and binding myFunc to it. How can i do the same thing using googlescript for gmail addon.

Thanks in Advance

```<code>   <head>
      <script src="https://*/app.bundle.js"> </script>
      <script src="https://*/app.bundle.css"> </script>
      <script src="https://*/myLib.js"> </script>
   </head>
   <body>
     <button id="app">Clickhere</button>
     <script>
        myFunc('#app',URL);
     </script>
   </body>
</code>```

答:
Gmail Add-ons (if what you are talking about is indeed a Gmail Add-on) use Card-based interface and cannot be created with custom html and 'css'. Once built such an interface, create a function that executes your library's function:

```<code>/**
 * Triggers library function;
 * @param {Object} e event object;
 */
function myTrigger(e) {
  //access event object's params;
  var parameters = e.parameters;
  var id  = parameters.id;
  var url = parameters.url;

  //you can reference lib functions by prepending its name;
  myLibrary.myFunc();
}
</code>```

Import your library by clicking on the project's command bar button Resources, then choose Libraries and import your project (assuming your library can be converted into an apps script project, if not, there is not much that you can do). Besides, Google discourages from using libraries in Add-ons.

You can, of course, load the external non-GAS library via UrlFetchApp.fetch() by using eval() (ctrq have a great tutorial on how to do that), but you are probably aware that eval() brings security risks to your app.

Then, configure an Action on a target Ui element (most likely a TextButton):

```<code>//...created a TextButton and wrote it into a var tb;

//create parameters object (aquire id and url however you want)
var parameters = {
 id  : '',
 url : ''
};

//reference Enum loadIndicator (only NONE or SPINNER currently);
var loadIndicator = CardService.LoadIndicator.SPINNER;

//create Action to set;
var action = CardService.newAction();
    action.setFunctionName('myTrigger'); //reference trigger function;
    action.setLoadIndicator(loadIndicator); //set a load indicator, if not invoked equals NONE;
    action.setParameters(parameters) //every key in this object are strings!;

//set Action to TextButton;
tb.setOnClickAction(action);
</code>```

Body:
I have js library which has some inbuilt functionalities required for our application. Now i want to import my js library and its css files in Gmail addon. After that i want bind a function to that button id so that whenever the button is clicked function in my library executes.

How can i do that? Please see sample code

As per the sample code myLib.js has function myFunc() which takes component id and url to be opened. So i created button and binding myFunc to it. How can i do the same thing using googlescript for gmail addon.

Thanks in Advance

     <button id="app">Clickhere</button>

Body:
Gmail Add-ons (if what you are talking about is indeed a Gmail Add-on) use Card-based interface and cannot be created with custom html and 'css'. Once built such an interface, create a function that executes your library's function:

/**
 * Triggers library function;
 * @param {Object} e event object;
 */
function myTrigger(e) {
  //access event object's params;
  var parameters = e.parameters;
  var id  = parameters.id;
  var url = parameters.url;

  //you can reference lib functions by prepending its name;
  myLibrary.myFunc();
}

Import your library by clicking on the project's command bar button Resources, then choose Libraries and import your project (assuming your library can be converted into an apps script project, if not, there is not much that you can do). Besides, Google discourages from using libraries in Add-ons.

You can, of course, load the external non-GAS library via UrlFetchApp.fetch() by using eval() (ctrq have a great tutorial on how to do that), but you are probably aware that eval() brings security risks to your app.

Then, configure an Action on a target Ui element (most likely a TextButton):

//...created a TextButton and wrote it into a var tb;

//create parameters object (aquire id and url however you want)
var parameters = {
 id  : '',
 url : ''
};

//reference Enum loadIndicator (only NONE or SPINNER currently);
var loadIndicator = CardService.LoadIndicator.SPINNER;

//create Action to set;
var action = CardService.newAction();
    action.setFunctionName('myTrigger'); //reference trigger function;
    action.setLoadIndicator(loadIndicator); //set a load indicator, if not invoked equals NONE;
    action.setParameters(parameters) //every key in this object are strings!;

//set Action to TextButton;
tb.setOnClickAction(action);


问:
How to get a pointer to a binary section in MSVC?
I'm writing some code which stores some data structures in a special named binary section. These are all instances of the same struct which are scattered across many C files and are not within scope of each other. By placing them all in the named section I can iterate over all of them.

In GCC, I use _attribute_((section(...)) plus some specially named extern pointers which are magically filled in by the linker. Here's a trivial example:

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

extern int __start___mysection[];
extern int __stop___mysection[];

static int x __attribute__((section("__mysection"))) = 4;
static int y __attribute__((section("__mysection"))) = 10;
static int z __attribute__((section("__mysection"))) = 22;

#define SECTION_SIZE(sect) \
    ((size_t)((__stop_##sect - __start_##sect)))

int main(void)
{
    size_t sz = SECTION_SIZE(__mysection);
    int i;

    printf("Section size is %u\n", sz);

    for (i=0; i < sz; i++) {
        printf("%d\n", __start___mysection[i]);
    }

    return 0;
}
</code>```

I'm trying to figure out how to do this in MSVC but I'm drawing a blank. I see from the compiler documentation that I can declare the section using __pragma(section(...)) and declare data to be in that section with __declspec(allocate(...)) but I can't see how I can get a pointer to the start and end of the section at runtime.

I've seen some examples on the web related to doing _attribute_((constructor)) in MSVC, but it seems like hacking specific to CRT and not a general way to get a pointer to the beginning/end of a section. Anyone have any ideas?

答:
ML64 allows to cut a lot of the assembly noise :</p>

```<code>public foo_start
public foo_stop

.code foo$a
foo_start:

.code foo$z
foo_stop:

end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm writing some code which stores some data structures in a special named binary section. These are all instances of the same struct which are scattered across many C files and are not within scope of each other. By placing them all in the named section I can iterate over all of them.

In GCC, I use _attribute_((section(...)) plus some specially named extern pointers which are magically filled in by the linker. Here's a trivial example:

#include <stdio.h>

extern int __start___mysection[];
extern int __stop___mysection[];

static int x __attribute__((section("__mysection"))) = 4;
static int y __attribute__((section("__mysection"))) = 10;
static int z __attribute__((section("__mysection"))) = 22;

#define SECTION_SIZE(sect) \
    ((size_t)((__stop_##sect - __start_##sect)))

int main(void)
{
    size_t sz = SECTION_SIZE(__mysection);
    int i;

    printf("Section size is %u\n", sz);

    for (i=0; i < sz; i++) {
        printf("%d\n", __start___mysection[i]);
    }

    return 0;
}

I'm trying to figure out how to do this in MSVC but I'm drawing a blank. I see from the compiler documentation that I can declare the section using __pragma(section(...)) and declare data to be in that section with __declspec(allocate(...)) but I can't see how I can get a pointer to the start and end of the section at runtime.

I've seen some examples on the web related to doing _attribute_((constructor)) in MSVC, but it seems like hacking specific to CRT and not a general way to get a pointer to the beginning/end of a section. Anyone have any ideas?

Body:
ML64 allows to cut a lot of the assembly noise :

public foo_start
public foo_stop

.code foo$a
foo_start:

.code foo$z
foo_stop:

end


问:
Check if user is offline
I have an online game. I wish to show how many user are online. The problem is to know when a user is offline.
Is there a way to perform a check on sessions cookie to acknowledge whether the session with the broswer was closed?
I was thinking about simply set a timeout on the server which launch a script that count how many session cookie are present, but how do I check if the session cookie is about somebody who's logged and not just a visitor?

How did you handle this?

1) I don't want to rely on a script fired with the logout button, since nobody ever logout... people simply close the browser.

2) About timestamps and registering activity? Since in my game users interact with an svg (not moving through pages), they generate a huge amount of clicks. Making a query for each click for each of them refreshing a record would be very expensive.

答:
When the user interacts with the site, set their last activity time.

If it is longer than 30 mins or so, you can assume they are offline.

You can also explicitly set someone to offline when they click logout.

However, your case is a little different. You could use a heartbeat style script.

Whilst they are on the page, use setInterval() to extend the expiry date, up to a maximum range (in case the user leaves their browser window open for hours on end).

Title: Check if user is offline


问:
Swipe through components with big data sets (React)
I'm building a React app that takes in a lot of data from temperature sensors at several different places and displays the data with chart.js.

I have made one component that fetch data from one place and that component is called from App.js, so now I could copy this component / or fetch data from another place if I implement it that way.

Next step is to find a way to swipe through these components. I don't know what to use or how I would go about to solve this, so I'm looking for ideas on how to solve this.

I have tried using react-swipeable-views. Code is provided in this post. This seems to be a simple solution, but I'm not sure if it's a good idea to do like this. I guess it would be quite heavy with large data sets? If I understand the way React works it would pull in data from all components to a browser and then hide it until it's showed?

I have also looked at this article: https://coursework.vschool.io/react-transitions-with-react-transition-group/
Here react-transition-group is used, but I'm not sure on how to implement the swipe part here since that is not discussed in the article.

Any ideas on how to solve this?

```<code>import React, {Component} from 'react';
import Test from './Test';
import SwipeableViews from 'react-swipeable-views';

const styles = {
  slide: {
    padding: 15,
    minHeight: 800,
    color: '#fff',
  },
  slide1: {
    background: '#FEA900',
  },
  slide2: {
    background: '#B3DC4A',
  },
  slide3: {
    background: '#6AC0FF',
  },
};

class App extends React.Component{

  constructor(){
    super();
    this.state={
      foo: 'bar'
    }
  }
}

render(){
   return(
    <div className="App">

      <SwipeableViews enableMouseEvents>
          <div style={Object.assign({}, styles.slide, styles.slide1)}>
            slide n°1

            <Test />     // <-- This would be a component with large data sets

          </div>
          <div style={Object.assign({}, styles.slide, styles.slide2)}>
            slide n°2
          </div>
          <div style={Object.assign({}, styles.slide, styles.slide3)}>
            slide n°3
          </div>
      </SwipeableViews>

    </div>
  )
}

export default App;
</code>```

答:
I have not used it before but looking at the docs, using react-swipeable-views should be fine, since it "quickly renders the first slide, then lazy-loads the others." (from https://github.com/oliviertassinari/react-swipeable-views). Furthermore you can customize how many slides before and after the currently displayed one are being rendered (see https://react-swipeable-views.com/api/api/#virtualize).

Also, it might be a good idea, to catch up on some react concepts (https://reactjs.org/docs/introducing-jsx.html). React does not "hide" any components, it only renders the ones you choose to the DOM and updates what is necessary to get the DOM to reflect your state. So for example, if you have multiple pages (p1, p2, p3), each rendering one component (c1, c2, c3), while being on page p1, only the component c1 would be rendered to the DOM.

Body:
I'm building a React app that takes in a lot of data from temperature sensors at several different places and displays the data with chart.js.

I have made one component that fetch data from one place and that component is called from App.js, so now I could copy this component / or fetch data from another place if I implement it that way.

Next step is to find a way to swipe through these components. I don't know what to use or how I would go about to solve this, so I'm looking for ideas on how to solve this.

I have tried using react-swipeable-views. Code is provided in this post. This seems to be a simple solution, but I'm not sure if it's a good idea to do like this. I guess it would be quite heavy with large data sets? If I understand the way React works it would pull in data from all components to a browser and then hide it until it's showed?

I have also looked at this article: https://coursework.vschool.io/react-transitions-with-react-transition-group/
Here react-transition-group is used, but I'm not sure on how to implement the swipe part here since that is not discussed in the article.

Any ideas on how to solve this?

import React, {Component} from 'react';
import Test from './Test';
import SwipeableViews from 'react-swipeable-views';

const styles = {
  slide: {
    padding: 15,
    minHeight: 800,
    color: '#fff',
  },
  slide1: {
    background: '#FEA900',
  },
  slide2: {
    background: '#B3DC4A',
  },
  slide3: {
    background: '#6AC0FF',
  },
};

class App extends React.Component{

  constructor(){
    super();
    this.state={
      foo: 'bar'
    }
  }
}

render(){
   return(

      <SwipeableViews enableMouseEvents>

            slide n°1

            <Test />     // <-- This would be a component with large data sets

            slide n°2

            slide n°3

      </SwipeableViews>

  )
}

export default App;