问:
Explode multiple nested columns, perform agg and join all the tables
I was wondering if there is another option much more efficient to do this job, for example:

```<code>val df0 = df.select($"id", explode($"event.x0") as "n_0" ).groupBy("id").agg(sum("n_0") as "0")
val df1 = df.select($"id", explode($"event.x1") as "n_1").groupBy("id").agg(sum("n_1") as "1")
val df2 = df.select($"id", explode($"event.x2") as "n_2").groupBy("id").agg(sum("n_2") as "2")
val df3 = df.select($"id", explode($"event.x3") as "n_3").groupBy("id").agg(sum("n_3") as "3)

val final_df = df.join(df0, "id").join(df1, "id").join(df2, "id").join(df3, "id")
</code>```

I was trying something like this:

```<code>val df_x = df.select($"id", $"event", explode($"event.x0") as "0" )
            .select($"id", $"event", $"0", explode($"event.x1") as "1")
            .select($"id", $"event", $"0", $"1", explode($"event.x2") as "2")
            .groupBy("id")
            .agg(sum("0") as "0", sum("1") as "1", sum("2") as "2")

val final_df = df.join(df_x, "id")
</code>```

Despite it runs much more faster!!!! The aggregations values are wrong, so it does not work actually :( !

Any ideas to decrease the amount of joins ?

答:
Assuming each id doesn't have too many matching records, you can use the collect_list aggregation function to collect all matching arrays into an array-of-arrays, and then a User Defined Function to sum over these nested arrays:

```<code>val flattenAndSum = udf[Int, mutable.Seq[mutable.Seq[Int]]] { seqOfArrays => seqOfArrays.flatten.sum }

val sums = df.groupBy($"id").agg(
  collect_list($"event.x0") as "arr0",
  collect_list($"event.x1") as "arr1",
  collect_list($"event.x2") as "arr2",
  collect_list($"event.x3") as "arr3"
).select($"id",
  flattenAndSum($"arr0") as "0",
  flattenAndSum($"arr1") as "1",
  flattenAndSum($"arr2") as "2",
  flattenAndSum($"arr3") as "3"
)

df.join(sums, "id")
</code>```

Alternatively, if that assumption cannot be made, you can create a User Defined Aggregation Function to perform the flatten-and-sum on the fly. This is safer and potentially faster but requires a bit more work:

```<code>// implement a UDAF:
class FlattenAndSum extends UserDefinedAggregateFunction {
  override def inputSchema: StructType = new StructType().add("arr", ArrayType(IntegerType))
  override def bufferSchema: StructType = new StructType().add("sum", IntegerType)
  override def dataType: DataType = IntegerType
  override def deterministic: Boolean = true

  override def initialize(buffer: MutableAggregationBuffer): Unit = buffer.update(0, 0)

  override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {
    val current = buffer.getAs[Int](0)
    val toAdd = input.getAs[Seq[Int]](0).sum
    buffer.update(0, current + toAdd)
  }

  override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
    buffer1.update(0, buffer1.getAs[Int](0) + buffer2.getAs[Int](0))
  }

  override def evaluate(buffer: Row): Any = buffer.getAs[Int](0)
}

// use it in aggregation:
val flattenAndSum = new FlattenAndSum()

val sums = df.groupBy($"id").agg(
  flattenAndSum($"event.x0") as "0",
  flattenAndSum($"event.x1") as "1",
  flattenAndSum($"event.x2") as "2",
  flattenAndSum($"event.x3") as "3"
)

df.join(sums, "id")
</code>```

Body:
I was wondering if there is another option much more efficient to do this job, for example:

val df0 = df.select($"id", explode($"event.x0") as "n_0" ).groupBy("id").agg(sum("n_0") as "0")
val df1 = df.select($"id", explode($"event.x1") as "n_1").groupBy("id").agg(sum("n_1") as "1")
val df2 = df.select($"id", explode($"event.x2") as "n_2").groupBy("id").agg(sum("n_2") as "2")
val df3 = df.select($"id", explode($"event.x3") as "n_3").groupBy("id").agg(sum("n_3") as "3)

val final_df = df.join(df0, "id").join(df1, "id").join(df2, "id").join(df3, "id")

I was trying something like this:

val df_x = df.select($"id", $"event", explode($"event.x0") as "0" )
            .select($"id", $"event", $"0", explode($"event.x1") as "1")
            .select($"id", $"event", $"0", $"1", explode($"event.x2") as "2")
            .groupBy("id")
            .agg(sum("0") as "0", sum("1") as "1", sum("2") as "2")

val final_df = df.join(df_x, "id")

Despite it runs much more faster!!!! The aggregations values are wrong, so it does not work actually :( !

Any ideas to decrease the amount of joins ?

Body:
Assuming each id doesn't have too many matching records, you can use the collect_list aggregation function to collect all matching arrays into an array-of-arrays, and then a User Defined Function to sum over these nested arrays:

val flattenAndSum = udf[Int, mutable.Seq[mutable.Seq[Int]]] { seqOfArrays => seqOfArrays.flatten.sum }

val sums = df.groupBy($"id").agg(
  collect_list($"event.x0") as "arr0",
  collect_list($"event.x1") as "arr1",
  collect_list($"event.x2") as "arr2",
  collect_list($"event.x3") as "arr3"
).select($"id",
  flattenAndSum($"arr0") as "0",
  flattenAndSum($"arr1") as "1",
  flattenAndSum($"arr2") as "2",
  flattenAndSum($"arr3") as "3"
)

df.join(sums, "id")

Alternatively, if that assumption cannot be made, you can create a User Defined Aggregation Function to perform the flatten-and-sum on the fly. This is safer and potentially faster but requires a bit more work:

// implement a UDAF:
class FlattenAndSum extends UserDefinedAggregateFunction {
  override def inputSchema: StructType = new StructType().add("arr", ArrayType(IntegerType))
  override def bufferSchema: StructType = new StructType().add("sum", IntegerType)
  override def dataType: DataType = IntegerType
  override def deterministic: Boolean = true

  override def initialize(buffer: MutableAggregationBuffer): Unit = buffer.update(0, 0)

  override def update(buffer: MutableAggregationBuffer, input: Row): Unit = {
    val current = buffer.getAs[Int](0)
    val toAdd = input.getAs[Seq[Int]](0).sum
    buffer.update(0, current + toAdd)
  }

  override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {
    buffer1.update(0, buffer1.getAs[Int](0) + buffer2.getAs[Int](0))
  }

  override def evaluate(buffer: Row): Any = buffer.getAs[Int](0)
}

// use it in aggregation:
val flattenAndSum = new FlattenAndSum()

val sums = df.groupBy($"id").agg(
  flattenAndSum($"event.x0") as "0",
  flattenAndSum($"event.x1") as "1",
  flattenAndSum($"event.x2") as "2",
  flattenAndSum($"event.x3") as "3"
)

df.join(sums, "id")


来源: stackexchange

问:
Overriding keypress
I know this may be an easy answer to some of you but i dont know how to properly do this. Ive created a text editor, that also has a docking window that will display functions. I have it set up in the menu that F8 is the shortcut key for showing the function window. I would also like to catch the F8 keypress event to parse the current data for the functions in the program but I cant get this to happen.. </p>

答:
Capture your Text Editors KeyPressed Event and check the KeyEventArgs that are coming in, then mark the not handled as false which will cause the event to be passed up to the parent control:

Example

```<code>KeyPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F8) DoSomething();
    e.Handled = false;
}
</code>```

In response to the comment that you added to your question. You may need to set the controls KeyPreview to True. I think that KeyPreview may be available at only the form level, but I'm not sure.

ContentLicense: CC BY-SA 2.5

Title: Overriding keypress

Body:
Capture your Text Editors KeyPressed Event and check the KeyEventArgs that are coming in, then mark the not handled as false which will cause the event to be passed up to the parent control:

Example

KeyPressed(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F8) DoSomething();
    e.Handled = false;
}

In response to the comment that you added to your question. You may need to set the controls KeyPreview to True. I think that KeyPreview may be available at only the form level, but I'm not sure.


问:
Spring Cloud Stream Rabbit Delivery acknowledgment
How can one ensure in Spring Cloud Stream Rabbit guaranteed delivery. My code below : -

```<code>class Source {
    MessageChannel output;
    Repository repo;

    @Transactional
    void publisher(Command command){
      repo.save(command);
      output.send(MessageBuilder
                .withPayload(new Event()).build());
    }
}

class Sink {

  @StreamListener(Event.class)
  void eventListener(Event event){
     // method body
  }
}
</code>```

Any help is appreciated.

答: You can use the Rabbit consumer property spring.cloud.stream.rabbit.bindings.<channelName>.consumer.acknowledgeMode on how do you want to acknowledge. The acknowledgeMode comes from Spring AMQP and you can refer more documentation on this here

ContentLicense: CC BY-SA 3.0

Body:
How can one ensure in Spring Cloud Stream Rabbit guaranteed delivery. My code below : -

class Source {
    MessageChannel output;
    Repository repo;

    @Transactional
    void publisher(Command command){
      repo.save(command);
      output.send(MessageBuilder
                .withPayload(new Event()).build());
    }
}

class Sink {

  @StreamListener(Event.class)
  void eventListener(Event event){
     // method body
  }
}

Any help is appreciated.


问:
PHP code located on linux server needs to run windows .exe
The project I am apart of uses a Linux server to host our code. The API I was provided to use was only usable within C#, so currently I have a Windows executable that performs a small task. This executable is called to execute by a PHP file from a website.

Currently, I am attempting to run the file remotely from the Linux server by letting the Windows executable reside on a server running Windows and doing a remote execute call using http://php.net/manual/en/features.remote-files.php, but even if this works, it doesn't seem like a safe or correct way to do things.

A senior suggested I use an IIS server to call it securely, but I am not familiar with this. Before continuing, I thought it would be responsible to ask: is there is a way to have this PHP code residing on a Linux server to run a Windows executable without having to call a remote Windows server for it to run on.

答:
You could write a small web API to run on your Windows server, that after authenticating the request will allow you to execute certain commands locally. Your application running on the linux server could then send requests to this web API and either wait for the results to be returned in that request, or have the Windows server send the results back in an API request later.

The other option which is arguably simpler... just host the entirety of your application on the Windows server.


问:
dynamically add suggestion chips on Api.ai for Actions on google
I want to add suggestions for the user in my Google Assistant Bot. I am using API.ai for bot development and using fulfilment, I am communicating with my backend for data.

I am not able to send suggestions using suggestions chips to my bot.

 I have followed as answered here Webhook response with "suggestion chips"
as well as the document at https://developers.google.com/actions/assistant/responses#json.
But still, I only see simple text response at my bot on device as well as on simulator.

I also checked at https://discuss.api.ai/t/google-assistant-rich-message-responses/5134/19. But didn't find any way to switch to V1 or V2. The sample format also didn't work!

Here are my 2 JSONs:

at API.ai

```<code>"fulfillment": {
  "speech": "want to proceed further?",
  "messages": [
    {
      "type": 0,
      "speech": "want to proceed further?"
    }
  ],
  "data": {
    "google": {
      "conversationToken": "[\"AS-PER-JSON-FROM-SIMULATOR\"]",
      "expectedInputs": [
        {
          "inputPrompt": {
            "richInitialPrompt": {
              "items": [
                {
                  "simpleResponse": {
                    "textToSpeech": "want to proceed further?",
                    "displayText": "want to proceed further?"
                  }
                }
              ],
              "suggestions": [
                {
                  "title": "Yes"
                },
                {
                  "title": "No"
                }
              ]
            }
          }
        }
      ]
    }
  }
},
</code>```

at action on Google

```<code>"expectUserResponse": true,
    "expectedInputs": [
        {
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": [
                        {
                            "simpleResponse": {
                                "textToSpeech": "want to proceed?"
                            }
                        }
                    ]
                },
                "noMatchPrompts": [],
                "noInputPrompts": []
            },
            "possibleIntents": [
                {
                    "intent": "assistant.intent.action.TEXT"
                }
            ],
            "speechBiasingHints": [
                "$subject",
                "$answer"
            ]
        }
    ]
</code>```

python server

```<code>return = '{"speech":"want to proceed?", "data": {"google":{"expectedInputs":[{"inputPrompt":{"richInitialPrompt":{"items":[{"simpleResponse":{"textToSpeech":"want to proceed?","displayText":"want to proceed?"}}],"suggestions":[{"title":"Yes"},{"title":"No"}]}}}]}}}'
</code>```

答: Solved using format as explained here https://developers.google.com/actions/apiai/webhook</p>

Body:
I want to add suggestions for the user in my Google Assistant Bot. I am using API.ai for bot development and using fulfilment, I am communicating with my backend for data.

I am not able to send suggestions using suggestions chips to my bot.

 I have followed as answered here Webhook response with "suggestion chips"
as well as the document at https://developers.google.com/actions/assistant/responses#json.
But still, I only see simple text response at my bot on device as well as on simulator.

I also checked at https://discuss.api.ai/t/google-assistant-rich-message-responses/5134/19. But didn't find any way to switch to V1 or V2. The sample format also didn't work!

Here are my 2 JSONs:

at API.ai

"fulfillment": {
  "speech": "want to proceed further?",
  "messages": [
    {
      "type": 0,
      "speech": "want to proceed further?"
    }
  ],
  "data": {
    "google": {
      "conversationToken": "[\"AS-PER-JSON-FROM-SIMULATOR\"]",
      "expectedInputs": [
        {
          "inputPrompt": {
            "richInitialPrompt": {
              "items": [
                {
                  "simpleResponse": {
                    "textToSpeech": "want to proceed further?",
                    "displayText": "want to proceed further?"
                  }
                }
              ],
              "suggestions": [
                {
                  "title": "Yes"
                },
                {
                  "title": "No"
                }
              ]
            }
          }
        }
      ]
    }
  }
},

at action on Google

"expectUserResponse": true,
    "expectedInputs": [
        {
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": [
                        {
                            "simpleResponse": {
                                "textToSpeech": "want to proceed?"
                            }
                        }
                    ]
                },
                "noMatchPrompts": [],
                "noInputPrompts": []
            },
            "possibleIntents": [
                {
                    "intent": "assistant.intent.action.TEXT"
                }
            ],
            "speechBiasingHints": [
                "$subject",
                "$answer"
            ]
        }
    ]

python server

return = '{"speech":"want to proceed?", "data": {"google":{"expectedInputs":[{"inputPrompt":{"richInitialPrompt":{"items":[{"simpleResponse":{"textToSpeech":"want to proceed?","displayText":"want to proceed?"}}],"suggestions":[{"title":"Yes"},{"title":"No"}]}}}]}}}'


问:
Parsing ISO 8601 with NSDateFormatter
I've read through the various posts on SO about this, but have still not solved the problem.

Here's the string that I'm trying to parse into an NSDate object:

```<code>2012-04-08T12:00:00.00+02:00
</code>```

I understand that the problem is the time zone format. Here's the date format string that I'm trying:

```<code>yyyy-MM-dd'T'HH:mm:SSZZZZ
</code>```

Thanks for any help.

答: Now the dedicated NSISO8601DateFormatter is available.</p>

Title: Parsing ISO 8601 with NSDateFormatter

Body:
I've read through the various posts on SO about this, but have still not solved the problem.

Here's the string that I'm trying to parse into an NSDate object:

2012-04-08T12:00:00.00+02:00

I understand that the problem is the time zone format. Here's the date format string that I'm trying:

yyyy-MM-dd'T'HH:mm:SSZZZZ

Thanks for any help.


问:
Multiple hyperlinks on a image in pdf android
I created an app that generates business card with ( Phone, Email, Link )

Saves it in two formats   PDF (using LIB  itextpdf) and Image

I inserted the same Image inside PDF

Image looks like this

Now problem is

Number, email and website should be clickable

What I tried so far

I tried to hack this feature using Hyperlink Rectangle

But when I add Rectangle using the following code

```<code>PdfContentByte canvas = writer.getDirectContent();
                Rectangle rect = new Rectangle(36, 636, 559, 10);
                rect.setBorder(Rectangle.BOX);
                rect.setBorderWidth(2);
                canvas.rectangle(rect);
</code>```

But i am unable to place the rectangle in right place

X, Y, width AND height is ok but gave this output

PDF OUTPUT

My questions are

Is it possible to hack this feature?

How to make Clickable Rectangle that is positioned correctly?

Any other way you can suggest me?

答:
I solved my problem and answering my own question

Solved my Rectangle position with

```<code>Rectangle phone = new Rectangle(36, 640,540,676);
Rectangle email = new Rectangle(36,604,540, 640);
Rectangle website = new Rectangle(36,568,540, 604);
</code>```

Linked the Rectangle with following code

```<code>                PdfReader reader = new PdfReader(file.getAbsolutePath() + File.separator + "card1_" + name.getText().toString() + ".pdf");
                PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(file.getAbsolutePath() + File.separator + "card1_Clickable_" + name.getText().toString() + ".pdf"));
                Rectangle phone = new Rectangle(36, 640,540,676);
                Rectangle email = new Rectangle(36,604,540, 640);
                Rectangle website = new Rectangle(36,568,540, 604);
                phone.setBorder(0);
                email.setBorder(0);
                website.setBorder(0);

                PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
                        phone, PdfAnnotation.HIGHLIGHT_INVERT,new PdfAction("tel://"+phone_edit.getText().toString()));
                link.setBorder(new PdfBorderArray(0, 0, 0));

                PdfAnnotation link1 = PdfAnnotation.createLink(stamper.getWriter(),
                        email, PdfAnnotation.HIGHLIGHT_INVERT,new PdfAction("mailto:"+email_edit.getText().toString()));
                link1.setBorder(new PdfBorderArray(0, 0, 0));

                PdfAnnotation link2 = PdfAnnotation.createLink(stamper.getWriter(),
                        website, PdfAnnotation.HIGHLIGHT_INVERT,new PdfAction(website_edit.getText().toString()));
                link2.setBorder(new PdfBorderArray(0, 0, 0));

                stamper.addAnnotation(link,1);
                stamper.addAnnotation(link1,1);
                stamper.addAnnotation(link2,1);
                stamper.close();
</code>```

Now i am able to click every link on image

Body:
I created an app that generates business card with ( Phone, Email, Link )

Saves it in two formats   PDF (using LIB  itextpdf) and Image

I inserted the same Image inside PDF

Image looks like this

Now problem is

Number, email and website should be clickable

What I tried so far

I tried to hack this feature using Hyperlink Rectangle

But when I add Rectangle using the following code

PdfContentByte canvas = writer.getDirectContent();
                Rectangle rect = new Rectangle(36, 636, 559, 10);
                rect.setBorder(Rectangle.BOX);
                rect.setBorderWidth(2);
                canvas.rectangle(rect);

But i am unable to place the rectangle in right place

X, Y, width AND height is ok but gave this output

PDF OUTPUT

My questions are

Is it possible to hack this feature?

How to make Clickable Rectangle that is positioned correctly?

Any other way you can suggest me?

Body:
I solved my problem and answering my own question

Solved my Rectangle position with

Rectangle phone = new Rectangle(36, 640,540,676);
Rectangle email = new Rectangle(36,604,540, 640);
Rectangle website = new Rectangle(36,568,540, 604);

Linked the Rectangle with following code

                PdfReader reader = new PdfReader(file.getAbsolutePath() + File.separator + "card1_" + name.getText().toString() + ".pdf");
                PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(file.getAbsolutePath() + File.separator + "card1_Clickable_" + name.getText().toString() + ".pdf"));
                Rectangle phone = new Rectangle(36, 640,540,676);
                Rectangle email = new Rectangle(36,604,540, 640);
                Rectangle website = new Rectangle(36,568,540, 604);
                phone.setBorder(0);
                email.setBorder(0);
                website.setBorder(0);

                PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
                        phone, PdfAnnotation.HIGHLIGHT_INVERT,new PdfAction("tel://"+phone_edit.getText().toString()));
                link.setBorder(new PdfBorderArray(0, 0, 0));

                PdfAnnotation link1 = PdfAnnotation.createLink(stamper.getWriter(),
                        email, PdfAnnotation.HIGHLIGHT_INVERT,new PdfAction("mailto:"+email_edit.getText().toString()));
                link1.setBorder(new PdfBorderArray(0, 0, 0));

                PdfAnnotation link2 = PdfAnnotation.createLink(stamper.getWriter(),
                        website, PdfAnnotation.HIGHLIGHT_INVERT,new PdfAction(website_edit.getText().toString()));
                link2.setBorder(new PdfBorderArray(0, 0, 0));

                stamper.addAnnotation(link,1);
                stamper.addAnnotation(link1,1);
                stamper.addAnnotation(link2,1);
                stamper.close();

Now i am able to click every link on image


问:
JS if else statement and a reset
I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

```<code>   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>
</code>```

JS

```<code>function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}
</code>```

答: You can have a global flag (say isAttacked) which will store whether the attacked button is clicked. Then in the send function check for isAttacked variable and if it's true send the troops.

Title: JS if else statement and a reset

Body:
I want to prevent any actions if the button attack is not clicked. In this case i want to prevent If attack is clicked you can click on send troops, else alert('You need first to attack!'). Also when the time runs out, i want to the clock disappear if that is possible.

Clock

   <button class="attack" onclick="startTimer(60,document.querySelector('#time'))">ATTACK</button>
<button class="troops" onclick="send()">SEND TROOPS</button>

JS

function startTimer(duration, display) {
  var timer = duration,minutes, seconds;
  var timers = setInterval(runner, 1000);
  function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer <= 0) {
     clearInterval(timers)
     finish()
   }
 }

}


问:
Check if Seleniums chrome webbrowser is downloading
I've seen a few questions asking if it's possible to check if a specific download is completed, or if a specific download has been completed successfully. (to which the answer appears to be no.)

What I want to know: Is it possible to see if selenium is currently downloading any file? I.e. it doesn't matter if it's one file, or 20. Something like a small boolean check would be ideal.

答:
When chrome is downloading a file you can check your downloads folder for the temp file (*.crdownload) that Chrome uses. When the download finishes that file is "replaced" by the actual filename/type.

```<code>/// <summary>
/// Looks for a file with the given extension (Example: "*.crdownload") in the current user's "Download" folder.
/// </summary>
public static string LocateDownloadedFile(string fileExtension)
{
    // Get the default downloads folder for the current user
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
    DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
    FileInfo[] filesFound = di.GetFiles(fileExtension);
    if (filesFound.Length == 0)
    {
        // do stuff
    }
    else
    {
        // do other stuff
    }
}
</code>```

Body:
When chrome is downloading a file you can check your downloads folder for the temp file (*.crdownload) that Chrome uses. When the download finishes that file is "replaced" by the actual filename/type.

/// <summary>
/// Looks for a file with the given extension (Example: "*.crdownload") in the current user's "Download" folder.
/// </summary>
public static string LocateDownloadedFile(string fileExtension)
{
    // Get the default downloads folder for the current user
    string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
    DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
    FileInfo[] filesFound = di.GetFiles(fileExtension);
    if (filesFound.Length == 0)
    {
        // do stuff
    }
    else
    {
        // do other stuff
    }
}


问:
Schedule or trigger jobs in gitlab-ci
I want to run a heavy test only once per day in Gitlab-ci. Is it possible schedule a job? Or is it possible to set it to manual and trigger it using the API?</p>

答:
It's possible to schedule a pipeline since GitLab 9.1, see:
https://docs.gitlab.com/ce/user/project/pipelines/schedules.html

Currently (i.e. with version 9.2) it can be configured as follows:

Navigate to your project's Pipelines ➔ Schedules and click the New Schedule button.

Fill in the form

Hit Save pipeline schedule for the changes to take effect.

Title: Schedule or trigger jobs in gitlab-ci


问:
IQueryable convert int to string - sortOrder and Filtring
int' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains(IQueryable, string)' requires a receiver of type 'IQueryable

This is part of the code of the Controller:

```<code>        var projects = db.Projects.Include(p => p.Engineer).Include(p => p.SiteLocation);

        // var projects = from p in db.Projects
        //  select p;

        if (!String.IsNullOrEmpty(searchString))
        {
            projects = projects.Where(p => p.NumberMCP.Contains(searchString)
            || p.nameProject.Contains(searchString) ||
            p.Ptype.Contains(searchString) || p.EngineerID.Contains(searchString));
        }
</code>```

Projects Model

```<code>public partial class Project
{
    public int ProjectID { get; set; }
    [DisplayName("MCP")]
    [Required(ErrorMessage = "NumberMCP es requerido")]
    public string NumberMCP { get; set; }
    [DisplayName("Ingeniero")]
    [Required(ErrorMessage = "Tarjeta Ingeniero es requerido")]
    public int EngineerID { get; set; }
    [DisplayName("Localidad")]
    [Required(ErrorMessage = "ID Localidad  es requerido")]
    public int SiteLocationID { get; set; }
    [DisplayName("Descripción")]
    [Required(ErrorMessage = "Descripción es requerido")]
    public string nameProject { get; set; }
    [DisplayName("Tipo Proyecto")]
    [Required(ErrorMessage = "Tipo Proyecto es requerido")]
    public string Ptype { get; set; }
    [DisplayName("Año")]
    [Required(ErrorMessage = "Año es requerido")]
    public Nullable<int> Pyear { get; set; }
    [DisplayName("Link del Proyecto")]
    [Required(ErrorMessage = "Link del Proyecto")]
    public string Plink { get; set; }

    public virtual Engineer Engineer { get; set; }
    public virtual SiteLocation SiteLocation { get; set; }
}
</code>```

}

答:
Use int.TryParse and literally compare ints to ints:

```<code>if (!String.IsNullOrEmpty(searchString))
{
    int searchInt = 0;
    var isInt = int.TryParse(searchString, out searchInt);

    projects = projects.Where(p =>
           (isInt && p.NumberMCP == searchInt) ||
           (!isInt && p.nameProject.Contains(searchString)) ||
           (!isInt && p.Ptype.Contains(searchString)) ||
           (isInt && p.EngineerID == searchInt)
    );
}
</code>```

Body:
int' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains(IQueryable, string)' requires a receiver of type 'IQueryable

This is part of the code of the Controller:

        var projects = db.Projects.Include(p => p.Engineer).Include(p => p.SiteLocation);

        // var projects = from p in db.Projects
        //  select p;

        if (!String.IsNullOrEmpty(searchString))
        {
            projects = projects.Where(p => p.NumberMCP.Contains(searchString)
            || p.nameProject.Contains(searchString) ||
            p.Ptype.Contains(searchString) || p.EngineerID.Contains(searchString));
        }

Projects Model

public partial class Project
{
    public int ProjectID { get; set; }
    [DisplayName("MCP")]
    [Required(ErrorMessage = "NumberMCP es requerido")]
    public string NumberMCP { get; set; }
    [DisplayName("Ingeniero")]
    [Required(ErrorMessage = "Tarjeta Ingeniero es requerido")]
    public int EngineerID { get; set; }
    [DisplayName("Localidad")]
    [Required(ErrorMessage = "ID Localidad  es requerido")]
    public int SiteLocationID { get; set; }
    [DisplayName("Descripción")]
    [Required(ErrorMessage = "Descripción es requerido")]
    public string nameProject { get; set; }
    [DisplayName("Tipo Proyecto")]
    [Required(ErrorMessage = "Tipo Proyecto es requerido")]
    public string Ptype { get; set; }
    [DisplayName("Año")]
    [Required(ErrorMessage = "Año es requerido")]
    public Nullable<int> Pyear { get; set; }
    [DisplayName("Link del Proyecto")]
    [Required(ErrorMessage = "Link del Proyecto")]
    public string Plink { get; set; }

    public virtual Engineer Engineer { get; set; }
    public virtual SiteLocation SiteLocation { get; set; }
}

}

Body:
Use int.TryParse and literally compare ints to ints:

if (!String.IsNullOrEmpty(searchString))
{
    int searchInt = 0;
    var isInt = int.TryParse(searchString, out searchInt);

    projects = projects.Where(p =>
           (isInt && p.NumberMCP == searchInt) ||
           (!isInt && p.nameProject.Contains(searchString)) ||
           (!isInt && p.Ptype.Contains(searchString)) ||
           (isInt && p.EngineerID == searchInt)
    );
}


问:
Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive - Angular reactive forms
I have the following template. I'm trying to get to grips with reactive forms but am having a problem.

<form [formGroup]="guestForm" novalidate>

        <form>

                    First Name*
                    <input formControlName="firstname" type="text" class="form-control input-sm">

        </form>

</form>
```
<p>Then in my component I have:</p>
<pre class="lang-js prettyprint-override"><code>@Component({
    selector: 'guest-input',
    templateUrl: './guest-input.component.html',
})
export class GuestInputComponent implements OnInit {
    @Input()
    guest: Guest;

    guestForm: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.guestForm = this._fb.group({
            firstname: ['test', [Validators.required, Validators.minLength(3)]]
        });
    }
}
</code>```

This all looks fine to me but for some reason I am getting:

Error: Uncaught (in promise): Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).

I thought I had declared this in my <form>.

答:
In modelDrivenForms, [formGroup]="guestForm" should be in the parent element

```<code><div class="form-group col-md-3 col-sm-6" [formGroup]="guestForm">
  <label>First Name*  </label>
  <input formControlName="firstname" type="text" class="form-control input-sm">
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following template. I'm trying to get to grips with reactive forms but am having a problem.

<form [formGroup]="guestForm" novalidate>

        <form>

                    First Name*
                    <input formControlName="firstname" type="text" class="form-control input-sm">

        </form>

</form>

Then in my component I have:

@Component({
    selector: 'guest-input',
    templateUrl: './guest-input.component.html',
})
export class GuestInputComponent implements OnInit {
    @Input()
    guest: Guest;

    guestForm: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.guestForm = this._fb.group({
            firstname: ['test', [Validators.required, Validators.minLength(3)]]
        });
    }
}

This all looks fine to me but for some reason I am getting:

Error: Uncaught (in promise): Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).

I thought I had declared this in my <form>.

Body:
In modelDrivenForms, [formGroup]="guestForm" should be in the parent element

<div class="form-group col-md-3 col-sm-6" [formGroup]="guestForm">
  <label>First Name*  </label>
  <input formControlName="firstname" type="text" class="form-control input-sm">
</div>


问:
ActiveMQ Redelivery - send invalid message to the back of the Q
Upon Redelivery how can I send the message to the back of the Q?
Currently, it sends the message to the front of the Q, consequently the other messages are stuck

答:
In case of exhaustion of redelivery, don't put the message back to the original queue, instead make use of the DLQ (deadletter queue) mechanism.

Example broker config:

```<code><destinationPolicy>
  <policyMap>
    <policyEntries>
      <!-- Set the following policy on all queues using the '>' wildcard -->
      <policyEntry queue=">">
        <deadLetterStrategy>
            <!--
              Use the prefix 'DLQ.' for the destination name, and make
              the DLQ a queue rather than a topic
            -->
          <individualDeadLetterStrategy queuePrefix="DLQ." useQueueForQueueMessages="true"/>
        </deadLetterStrategy>
      </policyEntry>
    </policyEntries>
  </policyMap>
</destinationPolicy>
</code>```

For more details see the ActiveMQ documentation.

Body:
In case of exhaustion of redelivery, don't put the message back to the original queue, instead make use of the DLQ (deadletter queue) mechanism.

Example broker config:

<destinationPolicy>
  <policyMap>
    <policyEntries>
      <!-- Set the following policy on all queues using the '>' wildcard -->
      <policyEntry queue=">">
        <deadLetterStrategy>
            <!--
              Use the prefix 'DLQ.' for the destination name, and make
              the DLQ a queue rather than a topic
            -->
          <individualDeadLetterStrategy queuePrefix="DLQ." useQueueForQueueMessages="true"/>
        </deadLetterStrategy>
      </policyEntry>
    </policyEntries>
  </policyMap>
</destinationPolicy>

For more details see the ActiveMQ documentation.


问:
Find duplicate words in GNU make
I'm looking for a good way to find all words that occur more than once in a string. Some constraints apply:

Sub-quadratic speed is needed: There will be ~1000 words, and I can afford a few milliseconds.

Must be implemented in pure make:

I want to avoid $(shell), because it is expensive and it must work on Windows (on pure Linux, sort|uniq -u would have solved my problem nicely).

No Guile, because I cannot control the make version used and need compatibility with old make versions (3.81).

The implementation should be readable to an acceptable degree.

Furthermore, the number of duplicates will be small, and words will only contain nice characters, something like [-_+a-zA-Z0-9]+.

I tried two strategies:

(1) Force $(sort) to keep duplicates (add a unique suffix to each word, sort, and strip the suffix). Then find adjacent identical words in the sorted list:

```<code># given 0 1 0 1 0 1 0 1 ... , return 0 0 1 1 0 0 1 1 ...
double=$(wordlist 1,$(words $(1)),$(subst 0,0 0,$(subst 1,1 1,$(1))))
# Produce a list of N unique strings. $(1) contains N words, with a
# repetition cycle of length M, and $(2) contains N words, either 0 or
# 1, alternating between 0 and 1 every Mth word.
binseq=$(if $(findstring 1,$(2)),$(call binseq,$(join $(2),$(1)),$(call double,$(2))),$(1))
# return 0 1 0 1 ..., as many words as $(1)
alternating_bits=$(wordlist 1,$(words $(1)),$(patsubst %,0 1,$(1)))
# Produce as many unique words as there are words in $(1)
unique=$(call binseq,,$(call alternating_bits,$(1)))
# Sort $(1) without eliminating duplicates. $(1) may not contain /.
sorted_keep_dups=$(subst /,,$(dir $(sort $(join $(1:=/),$(call unique,$(1))))))

dups_from_sorted2=$(filter $(patsubst %0,%,$(filter %0,$(1))),$(patsubst %1,%,$(filter %1,%,$(1))))
# Given a sorted list, return all duplicates.
dups_from_sorted=$(sort $(call dups_from_sorted2,$(join $(1),$(call alternating_bits,$(1)))))

dups=$(call dups_from_sorted,$(call sorted_keep_dups,$(1)))
</code>```

(2) Use $(filter) repeatedly with different partitions of the word list, such that each pair of words occurs at least once in different args of $(filter):

```<code># given 0 1 0 1 0 1 0 1 ... , return 0 0 1 1 0 0 1 1 ...
double=$(wordlist 1,$(words $(1)),$(subst 0,0 0,$(subst 1,1 1,$(1))))
# given words with suffix 0 or 1, remove suffixes and return the words
# that occur both with 0 and 1 as suffix
filter_dups=$(filter $(patsubst %0,%,$(filter %0,$(1))),$(patsubst %1,%,$(filter %1,$(1))))
_dups=$(if $(findstring 1,$(2)),$(call filter_dups,$(join $(1),$(2)))
$(call _dups,$(1),$(call double,$(2))))
# return 0 1 0 1 ..., as many words as $(1)
alternating_bits=$(wordlist 1,$(words $(1)),$(patsubst %,0 1,$(1)))
# given a list of words, return the list of words that occur twice
dups=$(sort $(call _dups,$(1),$(call alternating_bits,$(1))))
</code>```

Both approaches work and are sufficiently fast, but they are rather hard to read and comprehend. Is there a simpler way with acceptable (sub-quadratic) speed?

答:
I don't know if this is really improving on clarity for a casual make-programmer, but here goes:

```<code>######################################################################
# Count a binary literal up by 1
# $1 = binary literal string
# Example: bincnt(010011) -> 010100
bincnt=$(if $1,$(if $(patsubst %1,,$1),$(patsubst %0,%1,$1),$(call bincnt,$(patsubst %1,%,$1))0),1)

######################################################################
# Add a ¤ (Character 164) and a unique binary number to all elements of a list
# $1 = list
# $2 = binary literal (needs 0 or any other as starting value)
cat-sufx = $(if $1,$(firstword $1)¤$2 $(call cat-sufx,$(wordlist 2,999999,$1),$(call bincnt,$2)))

######################################################################
# Sort a list without dropping duplicates (built-in $sort will drop them)
# $1 = list (elements must not contain ¤ (Character 164))
sort-all = $(foreach i,$(sort $(call cat-sufx,$1,0)),$(firstword $(subst ¤, ,$(i))))

all-duplicates = $(call _all-duplicates,$(call sort-all,$1))
_all-duplicates = $(if $1,$(if $(subst $2,,$(firstword $1)),,$2) $(call _all-duplicates,$(wordlist 2,999999,$1),$(firstword $1)))
</code>```

I also added the functions to the GNU make table toolkit.

PS: the 999999 is my way to signal "up to end of list" without counting it, which is rather wasteful.

Title: Find duplicate words in GNU make

Body:
I'm looking for a good way to find all words that occur more than once in a string. Some constraints apply:

Sub-quadratic speed is needed: There will be ~1000 words, and I can afford a few milliseconds.

Must be implemented in pure make:

I want to avoid $(shell), because it is expensive and it must work on Windows (on pure Linux, sort|uniq -u would have solved my problem nicely).

No Guile, because I cannot control the make version used and need compatibility with old make versions (3.81).

The implementation should be readable to an acceptable degree.

Furthermore, the number of duplicates will be small, and words will only contain nice characters, something like [-_+a-zA-Z0-9]+.

I tried two strategies:

(1) Force $(sort) to keep duplicates (add a unique suffix to each word, sort, and strip the suffix). Then find adjacent identical words in the sorted list:

# given 0 1 0 1 0 1 0 1 ... , return 0 0 1 1 0 0 1 1 ...
double=$(wordlist 1,$(words $(1)),$(subst 0,0 0,$(subst 1,1 1,$(1))))
# Produce a list of N unique strings. $(1) contains N words, with a
# repetition cycle of length M, and $(2) contains N words, either 0 or
# 1, alternating between 0 and 1 every Mth word.
binseq=$(if $(findstring 1,$(2)),$(call binseq,$(join $(2),$(1)),$(call double,$(2))),$(1))
# return 0 1 0 1 ..., as many words as $(1)
alternating_bits=$(wordlist 1,$(words $(1)),$(patsubst %,0 1,$(1)))
# Produce as many unique words as there are words in $(1)
unique=$(call binseq,,$(call alternating_bits,$(1)))
# Sort $(1) without eliminating duplicates. $(1) may not contain /.
sorted_keep_dups=$(subst /,,$(dir $(sort $(join $(1:=/),$(call unique,$(1))))))

dups_from_sorted2=$(filter $(patsubst %0,%,$(filter %0,$(1))),$(patsubst %1,%,$(filter %1,%,$(1))))
# Given a sorted list, return all duplicates.
dups_from_sorted=$(sort $(call dups_from_sorted2,$(join $(1),$(call alternating_bits,$(1)))))

dups=$(call dups_from_sorted,$(call sorted_keep_dups,$(1)))

(2) Use $(filter) repeatedly with different partitions of the word list, such that each pair of words occurs at least once in different args of $(filter):

# given 0 1 0 1 0 1 0 1 ... , return 0 0 1 1 0 0 1 1 ...
double=$(wordlist 1,$(words $(1)),$(subst 0,0 0,$(subst 1,1 1,$(1))))
# given words with suffix 0 or 1, remove suffixes and return the words
# that occur both with 0 and 1 as suffix
filter_dups=$(filter $(patsubst %0,%,$(filter %0,$(1))),$(patsubst %1,%,$(filter %1,$(1))))
_dups=$(if $(findstring 1,$(2)),$(call filter_dups,$(join $(1),$(2)))
$(call _dups,$(1),$(call double,$(2))))
# return 0 1 0 1 ..., as many words as $(1)
alternating_bits=$(wordlist 1,$(words $(1)),$(patsubst %,0 1,$(1)))
# given a list of words, return the list of words that occur twice
dups=$(sort $(call _dups,$(1),$(call alternating_bits,$(1))))

Both approaches work and are sufficiently fast, but they are rather hard to read and comprehend. Is there a simpler way with acceptable (sub-quadratic) speed?

Body:
I don't know if this is really improving on clarity for a casual make-programmer, but here goes:

######################################################################
# Count a binary literal up by 1
# $1 = binary literal string
# Example: bincnt(010011) -> 010100
bincnt=$(if $1,$(if $(patsubst %1,,$1),$(patsubst %0,%1,$1),$(call bincnt,$(patsubst %1,%,$1))0),1)

######################################################################
# Add a ¤ (Character 164) and a unique binary number to all elements of a list
# $1 = list
# $2 = binary literal (needs 0 or any other as starting value)
cat-sufx = $(if $1,$(firstword $1)¤$2 $(call cat-sufx,$(wordlist 2,999999,$1),$(call bincnt,$2)))

######################################################################
# Sort a list without dropping duplicates (built-in $sort will drop them)
# $1 = list (elements must not contain ¤ (Character 164))
sort-all = $(foreach i,$(sort $(call cat-sufx,$1,0)),$(firstword $(subst ¤, ,$(i))))

all-duplicates = $(call _all-duplicates,$(call sort-all,$1))
_all-duplicates = $(if $1,$(if $(subst $2,,$(firstword $1)),,$2) $(call _all-duplicates,$(wordlist 2,999999,$1),$(firstword $1)))

I also added the functions to the GNU make table toolkit.

PS: the 999999 is my way to signal "up to end of list" without counting it, which is rather wasteful.


问:
How to keep dynamically generated HTML upon validation failure
I have a page with various input field. Some additional fields can be added and they are generated with Javascript. The issue I am having is that upon validation failure the page is reloaded and the generated content input fields are lost. How would I go about it to preserve these input fields? Thanks</p>

答:
Can you use local storage or cookies to store what are the input fields which were added to the page? so that when the page is reloaded it can repopulate that information?

More about LocalStorage

More about cookies


问:
MS Access - setup combobox to allow input of data not in the tables
I need help with MS Access 2010.

One of the client's requirement is they need to be able to input new data and also be able to have a drop down list of the data existing in the table for selecting using a combobox. Im very new to MS Access, only managed to work around it using online tutorials. Im not too clued up with VBA coding. I have tried swicthng around the properties components, still not working.

please assist.
thanks

答:
That's what I have done. Wanted to allow free entry but still assist the user if value already exists.

One option is to use the data table as source for the combobox RowSource. Set the combobox LimitToList property to No. Then the combobox RowSource would be like:

SELECT DISTINCT fieldname FROM tablename WHERE NOT fieldname IS NULL ORDER BY fieldname;

However, if you want a new value to be available for next record for a continuous or datasheet form, the record must be committed to table and then requery the combobox. Record is committed when: 1. close table/query/form; or 2. move to another record; or 3. run code to save. So code in the form Current event like:
Me.comboboxname.Requery

Another option is to have lookup table for the combobox RowSource and set the comobobox LimitToList property to Yes. Then code in the combobox NotInList event to allow new value input by user to be saved to lookup table. Review: https://msdn.microsoft.com/en-us/library/office/ff845736.aspx


问:
Call a method without expecting a response
I'm trying to create a server-side application to listen for connections and call a method based on what the client says. However when I call the method upload i want to continue executing code under main.

Is there anyway i can achieve this, or am i taking the incorrect approach? Code below;

```<code>def main(ipAddr, tcpPort, bufferSize, s):
    try:
        s.bind((ipAddr, tcpPort))
        s.listen(4)
        conn, addr = s.accept()

    print("Connection attempt from: %s" % addr)
    messageRecv = ""
    while True:
        data = conn.recv(bufferSize)
        if not data: break
        messageRecv = data.decode('utf-8')
finally:
    conn.close()
    if messageRecv == "Ready": upload(addr)

main(ipAddr, tcpPort, bufferSize, s)

def upload(addr):
    pass
</code>```

答:
Consider using the multiprocessing module, which is essentially Python's "multithreading" package. The API is very similar to the threading module's, but threading may be prohibitive due to the GIL.

In your case, you may have something like this:

```<code>p = Process(target=upload, args=(addr,))
p.start()
# some other code
p.join()
</code>```

Body:
I'm trying to create a server-side application to listen for connections and call a method based on what the client says. However when I call the method upload i want to continue executing code under main.

Is there anyway i can achieve this, or am i taking the incorrect approach? Code below;

def main(ipAddr, tcpPort, bufferSize, s):
    try:
        s.bind((ipAddr, tcpPort))
        s.listen(4)
        conn, addr = s.accept()

    print("Connection attempt from: %s" % addr)
    messageRecv = ""
    while True:
        data = conn.recv(bufferSize)
        if not data: break
        messageRecv = data.decode('utf-8')
finally:
    conn.close()
    if messageRecv == "Ready": upload(addr)

main(ipAddr, tcpPort, bufferSize, s)

def upload(addr):
    pass

Body:
Consider using the multiprocessing module, which is essentially Python's "multithreading" package. The API is very similar to the threading module's, but threading may be prohibitive due to the GIL.

In your case, you may have something like this:

p = Process(target=upload, args=(addr,))
p.start()
# some other code
p.join()


问:
Wait for codebuild and get build result using aws cli or boto3
I want to wait for a codebuild build and get the result of the build using the aws cli or boto3. There does not seem to be any command for this. All I can do is list builds, but only the build-ids. There is not information about the build (if it is still running and what the build result is).</p>

答:
Pass the build ID to batch-get-builds:
http://docs.aws.amazon.com/cli/latest/reference/codebuild/batch-get-builds.html</p>


问:
printing on screen and a text file
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

```
1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >
```

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

```<code>printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
</code>```

Is there an easiest way to implement this to cut down the number of lines of code?

答:
Edit: the C++ tag seems misleading, can someone remove it please? thanks :)

I use variadic macros to customize printf and friends.

I would write something like this:

```<code>#define     tee(fp,fmt, ...)                             \
        {                                                \
                printf (fmt, __VA_ARGS__);               \
                fprintf (fp, fmt, __VA_ARGS__);          \
        }
</code>```

(the name comes from the tee(1) utility)

OwnerDisplayName: Thi

Title: printing on screen and a text file

Body:
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);

Is there an easiest way to implement this to cut down the number of lines of code?

LastEditorDisplayName: Jonathan Leffler

Body:
Edit: the C++ tag seems misleading, can someone remove it please? thanks :)

I use variadic macros to customize printf and friends.

I would write something like this:

#define     tee(fp,fmt, ...)                             \
        {                                                \
                printf (fmt, __VA_ARGS__);               \
                fprintf (fp, fmt, __VA_ARGS__);          \
        }

(the name comes from the tee(1) utility)

OwnerDisplayName: rjack

LastEditorDisplayName: rjack


问:
Scala Free Monads with Coproduct and monad transformer
I'm trying to start using free monads in my project and I'm struggling to make it elegant.

Let's say I have two contexts (in reality I have more) - Receipt and User - both have operations on a database and I would like to keep their interpreters separate and compose them at the last moment.

For this I need to define different operations for each and combine them into one type using Coproduct.

This is what I have after days of googling and reading:

```<code>  // Receipts
sealed trait ReceiptOp[A]
case class GetReceipt(id: String) extends ReceiptOp[Either[Error, ReceiptEntity]]

class ReceiptOps[F[_]](implicit I: Inject[ReceiptOp, F]) {
  def getReceipt(id: String): Free[F, Either[Error, ReceiptEntity]] = Free.inject[ReceiptOp, F](GetReceipt(id))
}

object ReceiptOps {
  implicit def receiptOps[F[_]](implicit I: Inject[ReceiptOp, F]): ReceiptOps[F] = new ReceiptOps[F]
}

// Users
sealed trait UserOp[A]
case class GetUser(id: String) extends UserOp[Either[Error, User]]

class UserOps[F[_]](implicit I: Inject[UserOp, F]) {
  def getUser(id: String): Free[F, Either[Error, User]] = Free.inject[UserOp, F](GetUser(id))
}

object UserOps {
  implicit def userOps[F[_]](implicit I: Inject[UserOp, F]): UserOps[F] = new UserOps[F]
}
</code>```

When I want to write a program I can do this:

```<code>type ReceiptsApp[A] = Coproduct[ReceiptOp, UserOp, A]
type Program[A] = Free[ReceiptsApp, A]

def program(implicit RO: ReceiptOps[ReceiptsApp], UO: UserOps[ReceiptsApp]): Program[String] = {

  import RO._, UO._

  for {
    // would like to have 'User' type here
    user <- getUser("user_id")
    receipt <- getReceipt("test " + user.isLeft) // user type is `Either[Error, User]`
  } yield "some result"
}
</code>```

The problem here is that for example user in for comprehension is of type Either[Error, User] which is understandable looking at the getUser signature.

What I would like to have is User type or stopped computation.

I know I need to somehow use an EitherT monad transformer or FreeT, but after hours of trying I don't know how to combine the types to make it work.

Can someone help?
Please let me know if more details are needed.

I've also created a minimal sbt project here, so anyone willing to help could run it: https://github.com/Leonti/free-monad-experiment/blob/master/src/main/scala/example/FreeMonads.scala

Cheers,
Leonti

答:
After long battle with Cats:

```<code>  // Receipts
sealed trait ReceiptOp[A]
case class GetReceipt(id: String) extends ReceiptOp[Either[Error, ReceiptEntity]]

class ReceiptOps[F[_]](implicit I: Inject[ReceiptOp, F]) {
  private[this] def liftFE[A, B](f: ReceiptOp[Either[A, B]]) = EitherT[Free[F, ?], A, B](Free.liftF(I.inj(f)))

  def getReceipt(id: String): EitherT[Free[F, ?], Error, ReceiptEntity] = liftFE(GetReceipt(id))
}

object ReceiptOps {
  implicit def receiptOps[F[_]](implicit I: Inject[ReceiptOp, F]): ReceiptOps[F] = new ReceiptOps[F]
}

// Users
sealed trait UserOp[A]
case class GetUser(id: String) extends UserOp[Either[Error, User]]

class UserOps[F[_]](implicit I: Inject[UserOp, F]) {
  private[this] def liftFE[A, B](f: UserOp[Either[A, B]]) = EitherT[Free[F, ?], A, B](Free.liftF(I.inj(f)))

  def getUser(id: String): EitherT[Free[F, ?], Error, User] = Free.inject[UserOp, F](GetUser(id))
}

object UserOps {
  implicit def userOps[F[_]](implicit I: Inject[UserOp, F]): UserOps[F] = new UserOps[F]
}
</code>```

Then you write program as you want:

```<code>type ReceiptsApp[A] = Coproduct[ReceiptOp, UserOp, A]
type Program[A] = Free[ReceiptsApp, A]

def program(implicit RO: ReceiptOps[ReceiptsApp], UO: UserOps[ReceiptsApp]): Program[Either[Error, String]] = {

  import RO._, UO._

  (for {
    // would like to have 'User' type here
    user <- getUser("user_id")
    receipt <- getReceipt("test " + user.isLeft) // user type is `User` now
  } yield "some result").value // you have to get Free value from EitherT, or change return signature of program
}
</code>```

A little explanation. Without Coproduct transformer, functions would return:

```<code>Free[F, A]
</code>```

Once we add Coproduct of operations into picture, return type becomes:

```<code>Free[F[_], A]
</code>```

, which works fine until we try to transform it to EitherT. If there would not be Coproduct, EitherT would look like:

```<code>EitherT[F, ERROR, A]
</code>```

Where F, is Free[F, A]. But if F is Coproduct and Injection is used, intuition leads to:

```<code>EitherT[F[_], ERROR, A]
</code>```

Which is wrong obviously, here we have to extract type of Coproduct. Which would lead us with kind-projector plugin to:

```<code>EitherT[Free[F, ?], ERROR, A]
</code>```

Or with lambda expression:

```<code>EitherT[({type L[a] = Free[F, a]})#L, ERROR, A]
</code>```

Now it is correct type to which we can lift with:

```<code>EitherT[Free[F, ?], A, B](Free.liftF(I.inj(f)))
</code>```

If needed, we can simplify return type to:

```<code>type ResultEitherT[F[_], A] = EitherT[Free[F, ?], Error, A]
</code>```

And use it in functions like:

```<code>def getReceipt(id: String): ResultEitherT[F[_], ReceiptEntity] = liftFE(GetReceipt(id))
</code>```

Body:
I'm trying to start using free monads in my project and I'm struggling to make it elegant.

Let's say I have two contexts (in reality I have more) - Receipt and User - both have operations on a database and I would like to keep their interpreters separate and compose them at the last moment.

For this I need to define different operations for each and combine them into one type using Coproduct.

This is what I have after days of googling and reading:

  // Receipts
sealed trait ReceiptOp[A]
case class GetReceipt(id: String) extends ReceiptOp[Either[Error, ReceiptEntity]]

class ReceiptOps[F[_]](implicit I: Inject[ReceiptOp, F]) {
  def getReceipt(id: String): Free[F, Either[Error, ReceiptEntity]] = Free.inject[ReceiptOp, F](GetReceipt(id))
}

object ReceiptOps {
  implicit def receiptOps[F[_]](implicit I: Inject[ReceiptOp, F]): ReceiptOps[F] = new ReceiptOps[F]
}

// Users
sealed trait UserOp[A]
case class GetUser(id: String) extends UserOp[Either[Error, User]]

class UserOps[F[_]](implicit I: Inject[UserOp, F]) {
  def getUser(id: String): Free[F, Either[Error, User]] = Free.inject[UserOp, F](GetUser(id))
}

object UserOps {
  implicit def userOps[F[_]](implicit I: Inject[UserOp, F]): UserOps[F] = new UserOps[F]
}

When I want to write a program I can do this:

type ReceiptsApp[A] = Coproduct[ReceiptOp, UserOp, A]
type Program[A] = Free[ReceiptsApp, A]

def program(implicit RO: ReceiptOps[ReceiptsApp], UO: UserOps[ReceiptsApp]): Program[String] = {

  import RO._, UO._

  for {
    // would like to have 'User' type here
    user <- getUser("user_id")
    receipt <- getReceipt("test " + user.isLeft) // user type is `Either[Error, User]`
  } yield "some result"
}

The problem here is that for example user in for comprehension is of type Either[Error, User] which is understandable looking at the getUser signature.

What I would like to have is User type or stopped computation.

I know I need to somehow use an EitherT monad transformer or FreeT, but after hours of trying I don't know how to combine the types to make it work.

Can someone help?
Please let me know if more details are needed.

I've also created a minimal sbt project here, so anyone willing to help could run it: https://github.com/Leonti/free-monad-experiment/blob/master/src/main/scala/example/FreeMonads.scala

Cheers,
Leonti

Body:
After long battle with Cats:

  // Receipts
sealed trait ReceiptOp[A]
case class GetReceipt(id: String) extends ReceiptOp[Either[Error, ReceiptEntity]]

class ReceiptOps[F[_]](implicit I: Inject[ReceiptOp, F]) {
  private[this] def liftFE[A, B](f: ReceiptOp[Either[A, B]]) = EitherT[Free[F, ?], A, B](Free.liftF(I.inj(f)))

  def getReceipt(id: String): EitherT[Free[F, ?], Error, ReceiptEntity] = liftFE(GetReceipt(id))
}

object ReceiptOps {
  implicit def receiptOps[F[_]](implicit I: Inject[ReceiptOp, F]): ReceiptOps[F] = new ReceiptOps[F]
}

// Users
sealed trait UserOp[A]
case class GetUser(id: String) extends UserOp[Either[Error, User]]

class UserOps[F[_]](implicit I: Inject[UserOp, F]) {
  private[this] def liftFE[A, B](f: UserOp[Either[A, B]]) = EitherT[Free[F, ?], A, B](Free.liftF(I.inj(f)))

  def getUser(id: String): EitherT[Free[F, ?], Error, User] = Free.inject[UserOp, F](GetUser(id))
}

object UserOps {
  implicit def userOps[F[_]](implicit I: Inject[UserOp, F]): UserOps[F] = new UserOps[F]
}

Then you write program as you want:

type ReceiptsApp[A] = Coproduct[ReceiptOp, UserOp, A]
type Program[A] = Free[ReceiptsApp, A]

def program(implicit RO: ReceiptOps[ReceiptsApp], UO: UserOps[ReceiptsApp]): Program[Either[Error, String]] = {

  import RO._, UO._

  (for {
    // would like to have 'User' type here
    user <- getUser("user_id")
    receipt <- getReceipt("test " + user.isLeft) // user type is `User` now
  } yield "some result").value // you have to get Free value from EitherT, or change return signature of program
}

A little explanation. Without Coproduct transformer, functions would return:

Free[F, A]

Once we add Coproduct of operations into picture, return type becomes:

Free[F[_], A]

, which works fine until we try to transform it to EitherT. If there would not be Coproduct, EitherT would look like:

EitherT[F, ERROR, A]

Where F, is Free[F, A]. But if F is Coproduct and Injection is used, intuition leads to:

EitherT[F[_], ERROR, A]

Which is wrong obviously, here we have to extract type of Coproduct. Which would lead us with kind-projector plugin to:

EitherT[Free[F, ?], ERROR, A]

Or with lambda expression:

EitherT[({type L[a] = Free[F, a]})#L, ERROR, A]

Now it is correct type to which we can lift with:

EitherT[Free[F, ?], A, B](Free.liftF(I.inj(f)))

If needed, we can simplify return type to:

type ResultEitherT[F[_], A] = EitherT[Free[F, ?], Error, A]

And use it in functions like:

def getReceipt(id: String): ResultEitherT[F[_], ReceiptEntity] = liftFE(GetReceipt(id))


问:
Authorise Pinterest App
I have added a collaborator for my Pinterest app, however, when accessing the colaberators account and clicking on the application there is no 'authorise' button or anything similar. The "You still need at least 1 collaborator to authorize your app before you can submit" warning still shows on the collaberators account.
Ant help would be appreciated, thanks!</p>

答:
for those who have this problem, note that you have to test your application before you could autorize or send to revision,

You need 3 Pinterest account, or 2 friends

register one as developer and another as tester

then, with the secret key and the app id, put it on your client application

after that, test the login,

finnaly go back to your pinterest app and the button for "send to revision" you wiil find it enabled,

Title: Authorise Pinterest App


问:
Amazon MWS implementation in android studio
I am developing an application which uses MWS (Amazon market web services). What I have done import java libraries given by Amazon Configuration application with respect seller or Merchant credential. But when I run application the following error occur at run time. I put my best to get rid off but never find any helpful answer.

AndroidRuntime:

FATAL EXCEPTION: main Process: com.example.aun.sample java.lang.NoSuchMethodError: No direct method (Ljava/lang/String;ILorg/apache/http/conn/scheme/SchemeSocketFactory;)V in class Lorg/apache/http/conn/scheme/Scheme; or its super classes (declaration of 'org.apache.http.conn.scheme.Scheme' appears in /system/framework/ext.jar) org.apache.http.impl.conn.SchemeRegistryFactory.createDefault(SchemeRegistryFactory.java:47) org.apache.http.impl.conn.PoolingClientConnectionManager.(PoolingClientConnectionManager.java:93) com.example.aun.sample.MwsConnection1.getConnectionManager(MwsConnection1.java:260) com.example.aun.sample.MwsConnection1.freeze(MwsConnection1.java:227) com.example.aun.sample.MwsConnection1.newCall(MwsConnection1.java com.example.aun.sample.MwsConnection1.call(MwsConnection1.java:398) com.example.aun.sample.MarketplaceWebServiceProductsClient1.getServiceStatus(MarketplaceWebServiceProductsClient1.java:168) com.example.aun.sample.GetServiceStatus.invokeGetServiceStatus(GetServiceStatus.java:22) com.example.aun.sample.MainActivity.onCreate(MainActivity.java:44) android.app.Activity.performCreate(Activity.java:6092) android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112) android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468) android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2595) android.app.ActivityThread.access$800(ActivityThread.java:178) android.app.ActivityThread$H.handleMessage(ActivityThread.java:14 android.os.Handler.dispatchMessage(Handler.java:111) android.os.Looper.loop(Looper.java:194) android.app.ActivityThread.main(ActivityThread.java:5631) java.lang.reflect.Method.invoke(Native Method) java.lang.reflect.Method.invoke(Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteIni) com.android.internal.os.ZygoteInit.main(ZygoteInit)

答:
Your log is missing the name of the missing method. I'm guessing it is "init", but anyways, it seems your build process is broken.

See this almost identical error: NoSuchMethodError: org.apache.http.conn.scheme.Scheme.<init>(Ljava/lang/String;ILorg/apache/http/conn/scheme/SchemeSocketFactory;)V


问:
How to use if-else logic in Java 8 stream forEach with another list
I have a situation when the list will be returned

```<code>List<String> list2 = list
.stream()
.map(str -> someCondition(str) ? doSomething(str) : doSomethingElse(str))
.collect(Collectors.toList());
</code>```

doSomething(str) - This action returns List<String>

doSomethingElse(str) -This action returns only String

Can I collect them(List<String> and String) as a common List using .collect? If you have other opinions please let me know. Thanks

答:
Just as if you were writing a method, you need your statement to return a consistent type. At the moment:

```<code> str -> someCondition(str) ? doSomething(str) : doSomethingElse(str)
</code>```

... returns either List<String> or String, so the nearest common superclass is Object. You probably don't want this. I would make it always return List<String>:

```<code>Function<String,String> myFunc = str -> someCondition(str)
     ? doSomething(str)
     : Collections.singletonList(doSomethingElse(str));
</code>```

(I've stored your function in a variable so we don't have to use it inline in later examples. You can still inline it if you prefer.)

Now how you use it depends on what you want to end up with. If you want a List<List<String>>:

```<code>List<List<String>> list2 = list
    .stream()
    .map(myFunc)
    .collect(Collectors.toList());
</code>```

But since you appear to want a List<String>:

```<code>List<String> list2 = list
    .stream()
    .flatMap(myFunc.andThen(List.stream))
    .collect(Collectors.toList());
</code>```

... or if you prefer ...

```<code>List<String> list2 = list
    .stream()
    .map(myFunc)
    .flatMap(List::stream)
    .collect(Collectors.toList());
</code>```

Body:
I have a situation when the list will be returned

List<String> list2 = list
.stream()
.map(str -> someCondition(str) ? doSomething(str) : doSomethingElse(str))
.collect(Collectors.toList());

doSomething(str) - This action returns List<String>

doSomethingElse(str) -This action returns only String

Can I collect them(List<String> and String) as a common List using .collect? If you have other opinions please let me know. Thanks

Body:
Just as if you were writing a method, you need your statement to return a consistent type. At the moment:

 str -> someCondition(str) ? doSomething(str) : doSomethingElse(str)

... returns either List<String> or String, so the nearest common superclass is Object. You probably don't want this. I would make it always return List<String>:

Function<String,String> myFunc = str -> someCondition(str)
     ? doSomething(str)
     : Collections.singletonList(doSomethingElse(str));

(I've stored your function in a variable so we don't have to use it inline in later examples. You can still inline it if you prefer.)

Now how you use it depends on what you want to end up with. If you want a List<List<String>>:

List<List<String>> list2 = list
    .stream()
    .map(myFunc)
    .collect(Collectors.toList());

But since you appear to want a List<String>:

List<String> list2 = list
    .stream()
    .flatMap(myFunc.andThen(List.stream))
    .collect(Collectors.toList());

... or if you prefer ...

List<String> list2 = list
    .stream()
    .map(myFunc)
    .flatMap(List::stream)
    .collect(Collectors.toList());


问:
How to extract text before special character from string in Excel?
I have below text on column A1:

100-This_Is_My-Test_200

Looking to get output as below in column B1:

100-This_Is_My-Test

so basically it needs to remove text starting from last _ (underscore)

I tried below:

```<code>=TRIM(RIGHT(SUBSTITUTE(A1,"_",REPT(" ",LEN(A1))),LEN(A1)))
</code>```

Output: 200

```<code>=TRIM(LEFT(SUBSTITUTE(A1,"_",REPT(" ",LEN(A1))),LEN(A1)))
</code>```

Output: 100-This

Body:
I have below text on column A1:

100-This_Is_My-Test_200

Looking to get output as below in column B1:

100-This_Is_My-Test

so basically it needs to remove text starting from last _ (underscore)

I tried below:

=TRIM(RIGHT(SUBSTITUTE(A1,"_",REPT(" ",LEN(A1))),LEN(A1)))

Output: 200

=TRIM(LEFT(SUBSTITUTE(A1,"_",REPT(" ",LEN(A1))),LEN(A1)))

Output: 100-This

Body: =LEFT(A1,FIND("}}}",SUBSTITUTE(A1,"_","}}}",LEN(A1)-LEN(SUBSTITUTE(A1,"_",""))))-1)


问:
Const correctness for data handled by not const classes
I want to use class-oriented design to efficiently and cleanly handle data on an embedded platform. I should not create new objects on the stack (or at least be very economic) so I intend to pass my data as reference to helper classes and manipulate it within there (also to achieve proper encapsulation).

The following code is a very stripped down example of the problem I'm facing.

```<code>#include "Vector.h"

void DoSomething(float* a1, const float* a2)
{
  // some code

  Vector v1(a1[0], a1[1], a1[2]);
  Vector v2(a2[0], a2[1], a2[2]);
  v1.MakeEqual(v2);

  // more code
}

int main()
{
  float x1[3] = { 0, 0, 0 };
  float x2[3] = { 1, 1, 1 };
  DoSomething(x1, x2);
  return 0;
}
</code>```

The Vector-Class is defined in the header file:

```<code>#pragma once
class Vector
{
public:
  Vector(float& _x, float& _y, float& _z) :x(_x), y(_y), z(_z)
  {}

  Vector(const float& _x, const float& _y, const float& _z)
      :x(const_cast<float&>(_x)), y(const_cast<float&>(_y)), z(const_cast<float&>(_z)) //works, but looks not good
  {}

  ~Vector(){};

  void MakeEqual(const Vector& other)
  {
    x = other.x;
    y = other.y;
    z = other.z;
  }

private:
  float& x;
  float& y;
  float& z;
};
</code>```

My data is defined somewhere extern (main-function) and then passed as pointers to a function DoSomething. Inside this function vector objects are wrapped around the data to help doing some vector-typical stuff (rotating, cross-products, etc...). Now I want to be const-correct and pass the data which is not intended to be changed as const but when the vector v2 is created I have the compiler complaining that he cannot convert argument 1 from 'const float' to 'float &'. I understand what he wants to say, but how can I solve this? The vector method only makes sense when I am using it on vectors but the constructor of the vector v2 does not know that I'm actually not manipulating the data of v2.

One way to solve this is shown in the code with a const_cast in a second constructor, but I have the feeling that this is not good style, since I'm casting away my legitimate const data. Another way would be to define a second class ConstVector but this seem weird as well.

I have to mention that due to compiler restrictions I am bound to the C++03 standard so unfortunately I cannot use too modern language features. Also stl-containers are (probably) not available since I cannot control how, when and where memory is allocated.

答:
You have:

```<code>Vector(float& _x, float& _y, float& _z) :x(_x), y(_y), z(_z)
</code>```

That does not work well. For example, you can't use:

```<code>Vector v1(0, 0, 0);
</code>```

Also, you are not able to use

```<code>Vector v1(a1[0], a1[1], a1[2]);
</code>```

since a1[0] evaluates to a const float&, not a float&.

That's poorly designed interface. Change the arguments to simple values:

```<code>Vector(float _x, float _y, float _z) :x(_x), y(_y), z(_z)
</code>```

Body:
I want to use class-oriented design to efficiently and cleanly handle data on an embedded platform. I should not create new objects on the stack (or at least be very economic) so I intend to pass my data as reference to helper classes and manipulate it within there (also to achieve proper encapsulation).

The following code is a very stripped down example of the problem I'm facing.

#include "Vector.h"

void DoSomething(float* a1, const float* a2)
{
  // some code

  Vector v1(a1[0], a1[1], a1[2]);
  Vector v2(a2[0], a2[1], a2[2]);
  v1.MakeEqual(v2);

  // more code
}

int main()
{
  float x1[3] = { 0, 0, 0 };
  float x2[3] = { 1, 1, 1 };
  DoSomething(x1, x2);
  return 0;
}

The Vector-Class is defined in the header file:

#pragma once
class Vector
{
public:
  Vector(float& _x, float& _y, float& _z) :x(_x), y(_y), z(_z)
  {}

  Vector(const float& _x, const float& _y, const float& _z)
      :x(const_cast<float&>(_x)), y(const_cast<float&>(_y)), z(const_cast<float&>(_z)) //works, but looks not good
  {}

  ~Vector(){};

  void MakeEqual(const Vector& other)
  {
    x = other.x;
    y = other.y;
    z = other.z;
  }

private:
  float& x;
  float& y;
  float& z;
};

My data is defined somewhere extern (main-function) and then passed as pointers to a function DoSomething. Inside this function vector objects are wrapped around the data to help doing some vector-typical stuff (rotating, cross-products, etc...). Now I want to be const-correct and pass the data which is not intended to be changed as const but when the vector v2 is created I have the compiler complaining that he cannot convert argument 1 from 'const float' to 'float &'. I understand what he wants to say, but how can I solve this? The vector method only makes sense when I am using it on vectors but the constructor of the vector v2 does not know that I'm actually not manipulating the data of v2.

One way to solve this is shown in the code with a const_cast in a second constructor, but I have the feeling that this is not good style, since I'm casting away my legitimate const data. Another way would be to define a second class ConstVector but this seem weird as well.

I have to mention that due to compiler restrictions I am bound to the C++03 standard so unfortunately I cannot use too modern language features. Also stl-containers are (probably) not available since I cannot control how, when and where memory is allocated.

Body:
You have:

Vector(float& _x, float& _y, float& _z) :x(_x), y(_y), z(_z)

That does not work well. For example, you can't use:

Vector v1(0, 0, 0);

Also, you are not able to use

Vector v1(a1[0], a1[1], a1[2]);

since a1[0] evaluates to a const float&, not a float&.

That's poorly designed interface. Change the arguments to simple values:

Vector(float _x, float _y, float _z) :x(_x), y(_y), z(_z)


问:
String delimiter is affecting some instances of its individual characters
So basically, I'm trying to print out a human readable list of file and directory sizes (without the current directory listed) with the following code

```<code>du -arh | sort -nr | tail -n +2 | awk -F"./" '{print $1 $2 $3}' | head -n $NUM
</code>```

The NUM variable is just an argument given for the amount of items listed.

The output of the above without the awk delimiter command is

4.0K  ./url-list

  4.0K  ./testurl.sh

  4.0K  ./diskhogger.sh

  4.0K  ./backup/url-list

  4.0K  ./backup.sh

However, adding the awk command outputs

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backuurl-list

  4.0K    backup.sh

A similar output occurs whenever there is a notable subdirectory.

./Library/Cache - LibrarCache, etc.

To be clear, I am attempting to cut out the "./" at the beginning of the file name without affecting the other forward slashes. My preferred output would be:

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backup/url-list

  4.0K    backup.sh

where the "backup/url-list" isn't affected.

Is the '.' in my delimiter a special character I don't know about? If not, what exactly is going on here?

I'm new to shell so any info on this would be great.

Thanks!

Edited for clarity.

答:
-F"./" - is treated as "any character followed by forward slash".
It's taken as regex pattern where . means "any character" in terms of regex expressions.
To use "dot followed by slash" ./ as a delimiter use one of the following approaches:

. within character class

```<code>awk -F"[.]/" '{print $1,$2,$3}'
</code>```

. escaped

```<code>awk -F'\\./' '{print $1,$2,$3}'
</code>```

Body:
So basically, I'm trying to print out a human readable list of file and directory sizes (without the current directory listed) with the following code

du -arh | sort -nr | tail -n +2 | awk -F"./" '{print $1 $2 $3}' | head -n $NUM

The NUM variable is just an argument given for the amount of items listed.

The output of the above without the awk delimiter command is

4.0K  ./url-list

  4.0K  ./testurl.sh

  4.0K  ./diskhogger.sh

  4.0K  ./backup/url-list

  4.0K  ./backup.sh

However, adding the awk command outputs

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backuurl-list

  4.0K    backup.sh

A similar output occurs whenever there is a notable subdirectory.

./Library/Cache - LibrarCache, etc.

To be clear, I am attempting to cut out the "./" at the beginning of the file name without affecting the other forward slashes. My preferred output would be:

4.0K  url-list

  4.0K    testurl.sh

  4.0K    diskhogger.sh

  4.0K    backup/url-list

  4.0K    backup.sh

where the "backup/url-list" isn't affected.

Is the '.' in my delimiter a special character I don't know about? If not, what exactly is going on here?

I'm new to shell so any info on this would be great.

Thanks!

Edited for clarity.

Body:
-F"./" - is treated as "any character followed by forward slash".
It's taken as regex pattern where . means "any character" in terms of regex expressions.
To use "dot followed by slash" ./ as a delimiter use one of the following approaches:

. within character class

awk -F"[.]/" '{print $1,$2,$3}'

. escaped

awk -F'\\./' '{print $1,$2,$3}'


问:
Combination and Multiplying Rows of array in matlab
I have a matrix (89x42) of 0's and 1's that I'd like to multiply combinations of rows together.

For example, for matrix

```<code>input = [1 0 1
         0 0 0
         1 1 0];
</code>```

and with 2 combinations, I want an output of

```<code>output = [0 0 0; % (row1*row2)
          1 0 0; % (row1*row3)
          0 0 0] % (row2*row3)
</code>```

Which rows to multiply is dictated by "n Choose 2" (nCk), or all possible combinations of the rows n taken k at a time. In this case k=2.

Currently I am using a loop and it works fine for the 89C2 combinations of rows, but when I run it with 89C3 it takes far too long too run.

What would be the most efficient way to do this program so I can do more than 2 combinations?

答:
You can do it using nchoosek and element-wise multiplication.

```<code>inp = [1 0 1; 0 0 0; 1 1 0];          %Input matrix
C = nchoosek(1:size(inp,1),2);        %Number of rows taken 2 at a time
out = inp(C(:,1),:) .* inp(C(:,2),:); %Multiplying those rows to get the desired output
</code>```

Body:
I have a matrix (89x42) of 0's and 1's that I'd like to multiply combinations of rows together.

For example, for matrix

input = [1 0 1
         0 0 0
         1 1 0];

and with 2 combinations, I want an output of

output = [0 0 0; % (row1*row2)
          1 0 0; % (row1*row3)
          0 0 0] % (row2*row3)

Which rows to multiply is dictated by "n Choose 2" (nCk), or all possible combinations of the rows n taken k at a time. In this case k=2.

Currently I am using a loop and it works fine for the 89C2 combinations of rows, but when I run it with 89C3 it takes far too long too run.

What would be the most efficient way to do this program so I can do more than 2 combinations?

Body:
You can do it using nchoosek and element-wise multiplication.

inp = [1 0 1; 0 0 0; 1 1 0];          %Input matrix
C = nchoosek(1:size(inp,1),2);        %Number of rows taken 2 at a time
out = inp(C(:,1),:) .* inp(C(:,2),:); %Multiplying those rows to get the desired output


问:
How can i pass parameters to the constructors through the Service Container?
I have a class that is responseible for calling a 3rd party payment solution.

As a part of this, there are various merchant id/shared secret parameters.
Theses will depend on who's logged into the application.

The class I'm working with takes this info in the constructor when the class is built. Is there a way to pass this in the service provider, perhaps like this:

```<code> $this->app->bind( 'App\BokaKanot\Interfaces\BillingInterface',function ($merchantId)
 {
    return new KlarnaBilling($merchantId);
 } );
</code>```

If so, is it still possible to do this through a constructor or do I need to manaully use App:make. If I do have to use App::make, how can I not hide this inside my calling class?

Or should I refactor the class I'm using to not need this in the constructor, and perhaps have an init method?

答:
On laravel 5.4 (https://github.com/laravel/framework/pull/18271), you need to use the method makeWith of the IoC container.

```<code>App::makeWith( 'App\MyNameSpace\MyClass',  [ $id ]  );
</code>```

if you still use 5.3 or below, the above answers will work

Body:
I have a class that is responseible for calling a 3rd party payment solution.

As a part of this, there are various merchant id/shared secret parameters.
Theses will depend on who's logged into the application.

The class I'm working with takes this info in the constructor when the class is built. Is there a way to pass this in the service provider, perhaps like this:

 $this->app->bind( 'App\BokaKanot\Interfaces\BillingInterface',function ($merchantId)
 {
    return new KlarnaBilling($merchantId);
 } );

If so, is it still possible to do this through a constructor or do I need to manaully use App:make. If I do have to use App::make, how can I not hide this inside my calling class?

Or should I refactor the class I'm using to not need this in the constructor, and perhaps have an init method?

Body:
On laravel 5.4 (https://github.com/laravel/framework/pull/18271), you need to use the method makeWith of the IoC container.

App::makeWith( 'App\MyNameSpace\MyClass',  [ $id ]  );

if you still use 5.3 or below, the above answers will work


问:
Mule Anypoint Studio slow to run a simple project
What I can do to Anypoint Studio run projects faster? When I run a simple project I need to wait almost 20 seconds. My computer is a new macbook pro touch i7. When I run in a VM with Windows 10 the execution is very fast. It no make sense to me I tried many things like clear cache, increase the memory to Anypoint but nothing solved my problem.</p>

答: I discovered that my Anypoint works slow (wait some seconds to run a project) when my computer is not connected in any network, when I connect my MAC in some network the Anypoint works fine. Don't make sense to me...</p>


问:
Set docker-compose environment variable to properly start Jenkins with custom java System.Property
I have Jenkins docker image and I want to relax Jenkins Content Security Policy from docker environment.

I can do that from Jenkins script console:

```<code>System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'self'; style-src 'self' 'unsafe-inline';")
System.getProperty("hudson.model.DirectoryBrowserSupport.CSP")
</code>```

But not from docker-compose environment. Then docker container is restarting on run.

Docker service is run by 'jenkins.sh' script:

```<code>cat /usr/local/bin/jenkins.sh

#! /bin/bash -e

: "${JENKINS_HOME:="/var/jenkins_home"}"
touch "${COPY_REFERENCE_FILE_LOG}" || { echo "Can not write to ${COPY_REFERENCE_FILE_LOG}. Wrong volume permissions?"; exit 1; }
echo "--- Copying files at $(date)" >> "$COPY_REFERENCE_FILE_LOG"
find /usr/share/jenkins/ref/ -type f -exec bash -c '. /usr/local/bin/jenkins-support; for arg; do copy_reference_file "$arg"; done' _ {} +

# if `docker run` first argument start with `--` the user is passing jenkins launcher arguments
if [[ $# -lt 1 ]] || [[ "$1" == "--"* ]]; then

  # read JAVA_OPTS and JENKINS_OPTS into arrays to avoid need for eval (and associated vulnerabilities)
  java_opts_array=()
  while IFS= read -r -d '' item; do
    java_opts_array+=( "$item" )
  done < <([[ $JAVA_OPTS ]] && xargs printf '%s\0' <<<"$JAVA_OPTS")

  jenkins_opts_array=( )
  while IFS= read -r -d '' item; do
    jenkins_opts_array+=( "$item" )
  done < <([[ $JENKINS_OPTS ]] && xargs printf '%s\0' <<<"$JENKINS_OPTS")

  exec java "${java_opts_array[@]}" -jar /usr/share/jenkins/jenkins.war "${jenkins_opts_array[@]}" "$@"
fi

# As argument is not jenkins, assume user want to run his own process, for example a `bash` shell to explore this image
exec "$@"
</code>```

My jenkins Dockerfile environment:

```<code>ENV JAVA_OPTS="-Xmx2048m"
ENV JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war"
</code>```

My docker-compose.yml:

```<code>version: '2'
services:
  jenkins:
    build: jenkins
    image: my-jenkins
    container_name: my-jenkins
    environment:
    - JAVA_OPTS="-Xmx2048m"
#    - JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war"
#    - JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war -Dhudson.model.DirectoryBrowserSupport.CSP=\"default-src 'self'; style-src 'self' 'unsafe-inline';\""
#    - JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war -Dhudson.model.DirectoryBrowserSupport.CSP=default-src 'self'; style-src 'self' 'unsafe-inline';"
    ports:
    - "49001:8080"
    - "50000:50000"
    volumes:
    - data-jenkins-home:/var/jenkins_home
    restart: always

volumes:
  data-jenkins-home:
</code>```

Jenkins container is broken (it is restarting in about a second or two) if any of the upper rows are uncommented. Run throws:

```<code>Mar 02, 2017 11:32:25 AM Main deleteWinstoneTempContents
WARNING: Failed to delete the temporary Winstone file /tmp/winstone/jenkins.war
</code>```

I see that the 'jenkins.sh' is recreating JENKINS_OPTS array. Is it possible to set env variable JENKINS_OPTS to run the service properly using taht script?

答:
You can set JENKINS_OPTS in the docker run command which creates container.
e.g. this docker run command shows how JAVA_OPTS and JENKINS_OPTS can be set.
Also it shows how jenkins GUI port can be mapped (from 8080 in container to 9090 to outside world here). Also it shows how jenkins home dir can be customized (docker volume mount).</p>

```<code>JENKINS_PORT=9090
JENKINS_SLAVE_PORT=50000
JENKINS_DIR=jenkins
IMAGE=whatever

docker run -it \
-d \
--name jenkins42 \
--restart always \
-p $OMN_HOST_IP:$JENKINS_PORT:8080 \
-p $OMN_HOST_IP:$JENKINS_SLAVE_PORT:50000 \
--env JAVA_OPTS="-Dhudson.Main.development=true \
    -Dhudson.footerURL=http://customurl.com \
    -Xms800M -Xmx800M -Xmn400M \
    " \
-v $JENKINS_DIR:/var/jenkins_home \
$VARGS \
$IMAGE
</code>```

Body:
I have Jenkins docker image and I want to relax Jenkins Content Security Policy from docker environment.

I can do that from Jenkins script console:

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "default-src 'self'; style-src 'self' 'unsafe-inline';")
System.getProperty("hudson.model.DirectoryBrowserSupport.CSP")

But not from docker-compose environment. Then docker container is restarting on run.

Docker service is run by 'jenkins.sh' script:

cat /usr/local/bin/jenkins.sh

#! /bin/bash -e

: "${JENKINS_HOME:="/var/jenkins_home"}"
touch "${COPY_REFERENCE_FILE_LOG}" || { echo "Can not write to ${COPY_REFERENCE_FILE_LOG}. Wrong volume permissions?"; exit 1; }
echo "--- Copying files at $(date)" >> "$COPY_REFERENCE_FILE_LOG"
find /usr/share/jenkins/ref/ -type f -exec bash -c '. /usr/local/bin/jenkins-support; for arg; do copy_reference_file "$arg"; done' _ {} +

# if `docker run` first argument start with `--` the user is passing jenkins launcher arguments
if [[ $# -lt 1 ]] || [[ "$1" == "--"* ]]; then

  # read JAVA_OPTS and JENKINS_OPTS into arrays to avoid need for eval (and associated vulnerabilities)
  java_opts_array=()
  while IFS= read -r -d '' item; do
    java_opts_array+=( "$item" )
  done < <([[ $JAVA_OPTS ]] && xargs printf '%s\0' <<<"$JAVA_OPTS")

  jenkins_opts_array=( )
  while IFS= read -r -d '' item; do
    jenkins_opts_array+=( "$item" )
  done < <([[ $JENKINS_OPTS ]] && xargs printf '%s\0' <<<"$JENKINS_OPTS")

  exec java "${java_opts_array[@]}" -jar /usr/share/jenkins/jenkins.war "${jenkins_opts_array[@]}" "$@"
fi

# As argument is not jenkins, assume user want to run his own process, for example a `bash` shell to explore this image
exec "$@"

My jenkins Dockerfile environment:

ENV JAVA_OPTS="-Xmx2048m"
ENV JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war"

My docker-compose.yml:

version: '2'
services:
  jenkins:
    build: jenkins
    image: my-jenkins
    container_name: my-jenkins
    environment:
    - JAVA_OPTS="-Xmx2048m"
#    - JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war"
#    - JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war -Dhudson.model.DirectoryBrowserSupport.CSP=\"default-src 'self'; style-src 'self' 'unsafe-inline';\""
#    - JENKINS_OPTS="--logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war -Dhudson.model.DirectoryBrowserSupport.CSP=default-src 'self'; style-src 'self' 'unsafe-inline';"
    ports:
    - "49001:8080"
    - "50000:50000"
    volumes:
    - data-jenkins-home:/var/jenkins_home
    restart: always

volumes:
  data-jenkins-home:

Jenkins container is broken (it is restarting in about a second or two) if any of the upper rows are uncommented. Run throws:

Mar 02, 2017 11:32:25 AM Main deleteWinstoneTempContents
WARNING: Failed to delete the temporary Winstone file /tmp/winstone/jenkins.war

I see that the 'jenkins.sh' is recreating JENKINS_OPTS array. Is it possible to set env variable JENKINS_OPTS to run the service properly using taht script?

Body:
You can set JENKINS_OPTS in the docker run command which creates container.
e.g. this docker run command shows how JAVA_OPTS and JENKINS_OPTS can be set.
Also it shows how jenkins GUI port can be mapped (from 8080 in container to 9090 to outside world here). Also it shows how jenkins home dir can be customized (docker volume mount).

JENKINS_PORT=9090
JENKINS_SLAVE_PORT=50000
JENKINS_DIR=jenkins
IMAGE=whatever

docker run -it \
-d \
--name jenkins42 \
--restart always \
-p $OMN_HOST_IP:$JENKINS_PORT:8080 \
-p $OMN_HOST_IP:$JENKINS_SLAVE_PORT:50000 \
--env JAVA_OPTS="-Dhudson.Main.development=true \
    -Dhudson.footerURL=http://customurl.com \
    -Xms800M -Xmx800M -Xmn400M \
    " \
-v $JENKINS_DIR:/var/jenkins_home \
$VARGS \
$IMAGE


问:
OOP + WorkFlow4
Got a simple "Newbie" kind of a question.

I would like to "share" an InArgument between 2 Workflows. Let's consider for a moment the following classic OOP scenario, you got 2 classes with the same property, a reasonable OOP approach would be to create a base class and implement this property once.

When you create a new WorkFlow project, you got a xaml file and your cs is auto-generated. I would like to be able to inherited from an activity that will specify that InArgument and make the WorkFlow show it's property in it's Argument designer. With this approach I should be able to define an InArgument once in an activity and enforce derived WF to have this argument.

Does it make sense?

Consider that this suppose to be part of a framework, I would like my framework user to do the minimum and I still wish him to be able to use a deisgner (using only CodeActivities is unreasonable).

How can I accomplish it?

Ariel

答:
FYI,
A Reply from WP4 Forum in MSDN:

WF4 workflow is not a OOP language,
  and I don't think that it is a good
  idea to inherit a existed workflow. As
  a an alternative solution. you can
  create a composte activity as a
  workflow template. then users can
  create their own workflow by using
  your workflow template.

http://social.msdn.microsoft.com/Forums/en-US/wfprerelease/thread/08b8e00d-8363-4858-8377-83373213edae#fb352215-da10-4c77-8782-d047519f0e08

Title: OOP + WorkFlow4