问:
How do I go back to the finished activity dynamically?
For example, user passed between activities A to B. Now finish A and pass B to C, then finish B. Then click to the back button and go B again. Because B is the activity that the user comes from to current(ActivityC) activity.If the user go to the C from A directly, then finish A. If press the back button, then goes to the A again. Because A is the activity that the user comes from to current(ActivityC) activity.
   I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

```<code>  ActivityA --> ActivityB --> ActivityC --> ActivityD
</code>```

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

```<code>ActivityF --> ActivityD
ActivityF finished
</code>```

Current activity:

```<code>ActivityD
</code>```

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

```<code>ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
ActivityA --> ActivityB --> ActivityC /// click back button
ActivityA --> ActivityB /// click back button
ActivityA
</code>```

or

```<code>ActivityA --> ActivityF --> ActivityD /// click back button
ActivityA --> ActivityF /// click back button
ActivityA
</code>```

But I want to generate this scenario:

```<code>ActivityA
--> ActivityB
--> ActivityC
--> ActivityD /// click back button
ActivityC <-- /// click back button
ActivityB <-- /// click back button
ActivityA
</code>```

or

```<code>ActivityA
--> ActivityF
--> ActivityD /// click back button
ActivityF <-- /// click back button
ActivityA <--
</code>```

答:
You will need to pass ActivityA (Parent Activity) name to ActivityB (Child Activity) to keep reference of parent activity and use it in onBackPressed method need for starting parent activity.

When starting activity:

```<code>private void startActivity(){
    Intent intent =new Intent(this, ActivityB.class);
    intent.putExtra("parentClassName",this.getClass().getName());
    startActivity(intent);
    finish();
}
</code>```

In child activity :

```<code>public class ActivityB extends AppCompatActivity {

    String parentClassName;

    //..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        parentClassName = getIntent().getExtras().get("parentClassName").toString();

        //..
    }

    @Override
    public void onBackPressed() {
        try {
            Intent intent = new Intent(this, Class.forName(parentClassName));
            startActivity(intent);
        } catch (ClassNotFoundException e) {

        }

        finish();
    }
}
</code>```

Body:
For example, user passed between activities A to B. Now finish A and pass B to C, then finish B. Then click to the back button and go B again. Because B is the activity that the user comes from to current(ActivityC) activity.If the user go to the C from A directly, then finish A. If press the back button, then goes to the A again. Because A is the activity that the user comes from to current(ActivityC) activity.
   I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

  ActivityA --> ActivityB --> ActivityC --> ActivityD

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

ActivityF --> ActivityD
ActivityF finished

Current activity:

ActivityD

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
ActivityA --> ActivityB --> ActivityC /// click back button
ActivityA --> ActivityB /// click back button
ActivityA

or

ActivityA --> ActivityF --> ActivityD /// click back button
ActivityA --> ActivityF /// click back button
ActivityA

But I want to generate this scenario:

ActivityA
--> ActivityB
--> ActivityC
--> ActivityD /// click back button
ActivityC <-- /// click back button
ActivityB <-- /// click back button
ActivityA

or

ActivityA
--> ActivityF
--> ActivityD /// click back button
ActivityF <-- /// click back button
ActivityA <--

Body:
You will need to pass ActivityA (Parent Activity) name to ActivityB (Child Activity) to keep reference of parent activity and use it in onBackPressed method need for starting parent activity.

When starting activity:

private void startActivity(){
    Intent intent =new Intent(this, ActivityB.class);
    intent.putExtra("parentClassName",this.getClass().getName());
    startActivity(intent);
    finish();
}

In child activity :

public class ActivityB extends AppCompatActivity {

    String parentClassName;

    //..

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        parentClassName = getIntent().getExtras().get("parentClassName").toString();

        //..
    }

    @Override
    public void onBackPressed() {
        try {
            Intent intent = new Intent(this, Class.forName(parentClassName));
            startActivity(intent);
        } catch (ClassNotFoundException e) {

        }

        finish();
    }
}


来源: stackexchange

问:
Convert multiple png to gif as an animation in R
I have a bunch of png files in a directory and I want to convert them into a gif (animated) file via R. Can you please advise how to do that? </p>

答:
A solution with the gifski package:

```<code>library(gifski)
png_files <- list.files("path/to/your/pngs/", pattern = ".*png$", full.names = TRUE)
gifski(png_files, gif_file = "animation.gif", width = 800, height = 600, delay = 1)
</code>```

The advantage of gifski is that the number of colors in the GIF is not limited to 256.

ContentLicense: CC BY-SA 4.0

Body:
A solution with the gifski package:

library(gifski)
png_files <- list.files("path/to/your/pngs/", pattern = ".*png$", full.names = TRUE)
gifski(png_files, gif_file = "animation.gif", width = 800, height = 600, delay = 1)

The advantage of gifski is that the number of colors in the GIF is not limited to 256.


问:
C# WebSockets Multicast notifications asynchronously
I have a Asp.NET core application. Startup.Configure() mainly contains this code

```<code>app.UseWebSockets();
app.Use(async (httpContext, next) =>
{
    // If the request is a WebServerRequest, handle it as such ...
    if (httpContext.WebSockets.IsWebSocketRequest)
    {
        ClientHandler h = new ClientHandler(httpContext);

        if (h.IsWebsockOpen)
        {
            await h.Handle();
        }
        else
        {
            httpContext.Response.StatusCode = 400;
        }
    }

    // ... otherwise just hand the request to the next element in chain
    else
    {
        await next();
    }
});
</code>```

Inside h.Handle() the client is supposed to register with a ClientManager which in turn multicasts that a new client has connected like this

```<code>public async Task Multicast<T>(List<ClientHandler> l, Msg<T> m)
{
    foreach (ClientHandler h in l)
    {
        if (h.IsWebsockOpen)
        {
            await h.webSocket.SendAsync(
                System.Text.Encoding.UTF8.GetBytes(m.ToString()),
                System.Net.WebSockets.WebSocketMessageType.Text,
                true,
                System.Threading.CancellationToken.None);
        }
    }
}
</code>```

I am now wondering if that is safe to do. I can imagine a scenario where two clients connect at the same time resulting in h.webSocket.SendAsync being called twice simultaneously, which is not allowed as said in

https://learn.microsoft.com/en-us/dotnet/api/system.net.websockets.websocket.sendasync?view=netframework-4.8

Remarks
  This operation will not block. The returned Task object will complete after the data has been sent on the WebSocket.

Exactly one send and one receive is supported on each WebSocket object in parallel.

Wraping the h.webSocket.SendAsync in a lock-statement seems to be impossible due to the await keyword.

How can I make my code safe? Related questions are either not using WebSockets or they use different frameworks for which mechanisms apply.

答:
You can make use of a semaphore here, specifically SemaphoreSlim.  I'd suggest making a SendAsync method on your ClientHandler class and piping all requests via that - ie call it from your Multicast method.

The content of your ClientHandler would then be something like:

```<code>class ClientHandler() {
    private readonly SemaphoreSlim _sendLock;
    public ClientHandler(HttpContext context) {
        _sendLock = new SemaphoreSlim(1, 1);
        //....
    }

    public async Task SendAsync(string msg) {
        await _sendLock.WaitAsync();
        try {
            await webSocket.SendAsync(
                System.Text.Encoding.UTF8.GetBytes(msg.ToString()),
                System.Net.WebSockets.WebSocketMessageType.Text,
                true,
                System.Threading.CancellationToken.None);
        } finally {
            _sendLock.Release();
        }
    }
}
</code>```

The SemaphoreSlim is IDisposable, so you'll need to take care of that, and its WaitAsync method has overloads for cancellation tokens and/or timeouts that might be appropriate for you to use.

Body:
I have a Asp.NET core application. Startup.Configure() mainly contains this code

app.UseWebSockets();
app.Use(async (httpContext, next) =>
{
    // If the request is a WebServerRequest, handle it as such ...
    if (httpContext.WebSockets.IsWebSocketRequest)
    {
        ClientHandler h = new ClientHandler(httpContext);

        if (h.IsWebsockOpen)
        {
            await h.Handle();
        }
        else
        {
            httpContext.Response.StatusCode = 400;
        }
    }

    // ... otherwise just hand the request to the next element in chain
    else
    {
        await next();
    }
});

Inside h.Handle() the client is supposed to register with a ClientManager which in turn multicasts that a new client has connected like this

public async Task Multicast<T>(List<ClientHandler> l, Msg<T> m)
{
    foreach (ClientHandler h in l)
    {
        if (h.IsWebsockOpen)
        {
            await h.webSocket.SendAsync(
                System.Text.Encoding.UTF8.GetBytes(m.ToString()),
                System.Net.WebSockets.WebSocketMessageType.Text,
                true,
                System.Threading.CancellationToken.None);
        }
    }
}

I am now wondering if that is safe to do. I can imagine a scenario where two clients connect at the same time resulting in h.webSocket.SendAsync being called twice simultaneously, which is not allowed as said in

https://learn.microsoft.com/en-us/dotnet/api/system.net.websockets.websocket.sendasync?view=netframework-4.8

Remarks
  This operation will not block. The returned Task object will complete after the data has been sent on the WebSocket.

Exactly one send and one receive is supported on each WebSocket object in parallel.

Wraping the h.webSocket.SendAsync in a lock-statement seems to be impossible due to the await keyword.

How can I make my code safe? Related questions are either not using WebSockets or they use different frameworks for which mechanisms apply.

Body:
You can make use of a semaphore here, specifically SemaphoreSlim.  I'd suggest making a SendAsync method on your ClientHandler class and piping all requests via that - ie call it from your Multicast method.

The content of your ClientHandler would then be something like:

class ClientHandler() {
    private readonly SemaphoreSlim _sendLock;
    public ClientHandler(HttpContext context) {
        _sendLock = new SemaphoreSlim(1, 1);
        //....
    }

    public async Task SendAsync(string msg) {
        await _sendLock.WaitAsync();
        try {
            await webSocket.SendAsync(
                System.Text.Encoding.UTF8.GetBytes(msg.ToString()),
                System.Net.WebSockets.WebSocketMessageType.Text,
                true,
                System.Threading.CancellationToken.None);
        } finally {
            _sendLock.Release();
        }
    }
}

The SemaphoreSlim is IDisposable, so you'll need to take care of that, and its WaitAsync method has overloads for cancellation tokens and/or timeouts that might be appropriate for you to use.


问:
jQuery mouseleave bugs with animated elements
I have bumped into a weird issue.

jQuery 1.4.1 mouseenter/mouseleave events fire up correctly if the mouse is being moved, not a big deal. However, it bugs in some browsers when the cursor itself remains static but the element is being moved away by animate().

So imagine the code like this:

```<code>jQuery('somelement').bind(
{
   mouseenter: function(e) {
     log.debug("enter");
     $(this).animate({left: 9999}, 2000);
   },
   mouseleave: function() {
     log.debug("leave");
   }
});
</code>```

if you rapidly move the mouse onto the element and then stop it, you'll get different results depending on the browser.

FF3.6, Safari 4, IE7: mouseleave fired as expected when cursor has left the animated element, even if the mouse itself stands still.

IE6, IE8, Opera 9/10, Safari 3, Chrome: mouseleave NOT fired even when the element is outside the window. It takes a slight mouse move to trigger correct mouseleave event.

Any ideas how to fix it?

答:
Unfortunately, it appears that the mouseover, mouseleave, mouseover, and mouseout functions are all bound to the mouse, not to the actual object.  This is just as true when using the inline alternative: onmouseout, etc.

As far as I know, there isn't really a great alternative for what you are trying to do.  If it's an absolutely necessary function, here's how I would go about it.

Create a mouseenter handler for your element.  When the mouse enters the element, bind both mouseout and mousemove.

When the mousemove event is called, use that event object to store the mouse's x and y positions in global variables.

Use a custom animation function that moves the element with a while loop.  Inside of that while loop, check to see if the element has moved out of the the x and y coordinates stored in step 2.

If that element has moved off those x and y coords, do whatever you need to do, and also unbind mousemove (otherwise it will eat up unnecessary resources).  This should also be the function that runs if the mouseout from step 1 is called.

Hope that makes sense.  If I find some more time today I'll build an example fiddle so you can see how it works.

ContentLicense: CC BY-SA 2.5

Body:
I have bumped into a weird issue.

jQuery 1.4.1 mouseenter/mouseleave events fire up correctly if the mouse is being moved, not a big deal. However, it bugs in some browsers when the cursor itself remains static but the element is being moved away by animate().

So imagine the code like this:

jQuery('somelement').bind(
{
   mouseenter: function(e) {
     log.debug("enter");
     $(this).animate({left: 9999}, 2000);
   },
   mouseleave: function() {
     log.debug("leave");
   }
});

if you rapidly move the mouse onto the element and then stop it, you'll get different results depending on the browser.

FF3.6, Safari 4, IE7: mouseleave fired as expected when cursor has left the animated element, even if the mouse itself stands still.

IE6, IE8, Opera 9/10, Safari 3, Chrome: mouseleave NOT fired even when the element is outside the window. It takes a slight mouse move to trigger correct mouseleave event.

Any ideas how to fix it?

ContentLicense: CC BY-SA 3.0


问:
Convert DD-MMM-YYYY HH:MM:SS.SSS to Progress DATETIME-TZ
Is there an easy way to convert a date time value in format DD-MMM-YYYY HH:MM:SS.SSS to Progress DATETIME-TZ. For example, I am trying to store "15-Sep-2017 20:51:14.566" date in to Progress ABL variable whose datatype is datetime-tz with format "99/99/9999 HH:MM:SS.SSS+HH:MM".

I can get this working by splitting date, month, year, hours, minutes etc to individual variables and combining them using functions like DATE, DATETIME. But, I believe that there should be some good way of doing this. Thanks for your help.

答:
I know this is an old thread, but for the benefit of others who may find this:  simple variable assignment will work.

```<code>DEFINE VARIABLE dt  AS DATETIME.
DEFINE VARIABLE dtz AS DATETIME-TZ /* FORMAT "..." */.

dt = NOW.
dtz = dt.
DISPLAY dt SKIP dtz.
</code>```

[Edit]
You can use the session variable SESSION:TIMEZONE to set the time zone used in this assignment.  But there have been issues with that in older versions of Progress, and you may need to use the startup parameter -useSessionTZ.  See the Progress KB article:  Inconsistency assigning datetime-tz to datetime

Body:
I know this is an old thread, but for the benefit of others who may find this:  simple variable assignment will work.

DEFINE VARIABLE dt  AS DATETIME.
DEFINE VARIABLE dtz AS DATETIME-TZ /* FORMAT "..." */.

dt = NOW.
dtz = dt.
DISPLAY dt SKIP dtz.

[Edit]
You can use the session variable SESSION:TIMEZONE to set the time zone used in this assignment.  But there have been issues with that in older versions of Progress, and you may need to use the startup parameter -useSessionTZ.  See the Progress KB article:  Inconsistency assigning datetime-tz to datetime


问:
sort Javascript array by two numeric fields
```<code>grouperArray.sort(function (a, b) {
    var aSize = a.gsize;
    var bSize = b.gsize;
    var aLow = a.glow;
    var bLow = b.glow;
    console.log(aLow + " | " + bLow);
    return (aSize < bSize) ? -1 : (aSize > bSize) ? 1 : 0;
});
</code>```

This code sorts the array by gsize, smallest to largest.

How would I change it to sort first by gsize and then by glow?

答:
Here is the solution for the case, when you have a priority sort key, which might not exist in some particular items, so you have to sort by fallback keys.

An input data example (id2 is priority sort key):

const arr = [
    {id: 1},
    {id: 2, id2: 3},
    {id: 4},
    {id: 3},
    {id: 10, id2: 2},
    {id: 7},
    {id: 6, id2: 1},
    {id: 5},
    {id: 9, id2: 2},
    {id: 8},
];
```

<p>And the output should be: </p>

```[ { id: 6, id2: 1 },
  { id: 9, id2: 2 },
  { id: 10, id2: 2 },
  { id: 2, id2: 3 },
  { id: 1 },
  { id: 3 },
  { id: 4 },
  { id: 5 },
  { id: 7 },
  { id: 8 } ]
```

<p>The comparator function will be like: </p>

<pre class="lang-js prettyprint-override"><code>arr.sort((a,b) => {
  if(a.id2 || b.id2) {
    if(a.id2 && b.id2) {
      if(a.id2 === b.id2) {
        return a.id - b.id;
      }
      return a.id2 - b.id2;
    }
    return a.id2 ? -1 : 1;
  }
  return a.id - b.id
});
</code>```

P.S. In case if .id of .id2 can be zeros, consider to use typeof.

Body:
grouperArray.sort(function (a, b) {
    var aSize = a.gsize;
    var bSize = b.gsize;
    var aLow = a.glow;
    var bLow = b.glow;
    console.log(aLow + " | " + bLow);
    return (aSize < bSize) ? -1 : (aSize > bSize) ? 1 : 0;
});

This code sorts the array by gsize, smallest to largest.

How would I change it to sort first by gsize and then by glow?

Body:
Here is the solution for the case, when you have a priority sort key, which might not exist in some particular items, so you have to sort by fallback keys.

An input data example (id2 is priority sort key):

const arr = [
    {id: 1},
    {id: 2, id2: 3},
    {id: 4},
    {id: 3},
    {id: 10, id2: 2},
    {id: 7},
    {id: 6, id2: 1},
    {id: 5},
    {id: 9, id2: 2},
    {id: 8},
];

And the output should be:

[ { id: 6, id2: 1 },
  { id: 9, id2: 2 },
  { id: 10, id2: 2 },
  { id: 2, id2: 3 },
  { id: 1 },
  { id: 3 },
  { id: 4 },
  { id: 5 },
  { id: 7 },
  { id: 8 } ]

The comparator function will be like:

arr.sort((a,b) => {
  if(a.id2 || b.id2) {
    if(a.id2 && b.id2) {
      if(a.id2 === b.id2) {
        return a.id - b.id;
      }
      return a.id2 - b.id2;
    }
    return a.id2 ? -1 : 1;
  }
  return a.id - b.id
});

P.S. In case if .id of .id2 can be zeros, consider to use typeof.


问:
How do I select Lat & Long coordinates back out of SQL Server Geography data type field
Considering the SQL Server 'geography' data type...

I can enter an array of latitude and longitude (btw is that the correct order to do so or should it be longitude latitude?) points into the field as follows:

```<code>INSERT INTO SpatialZonePolygons (Coordinates)
VALUES (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326));
GO
</code>```

This then appears as:

```<code>0xE6100000010405000000DD24068195D34740F4FDD478E9965EC0508D976E12D3474083C0CAA145965EC04E62105839D4474083C0CAA145965EC04E62105839D44740F4FDD478E9965EC0DD24068195D34740F4FDD478E9965EC001000000020000000001000000FFFFFFFF0000000003
</code>```

How do I select them back into their latitude and longitude formats?

答:
You may use something like this(SQL SERVER)

```<code>SELECT Coordinates.Lat 'Latitude', Coordinates.Long 'Longitude' FROM SpatialZonePolygons
</code>```

For more information - How To Get Lat-Long From Geography Data Type

Body:
Considering the SQL Server 'geography' data type...

I can enter an array of latitude and longitude (btw is that the correct order to do so or should it be longitude latitude?) points into the field as follows:

INSERT INTO SpatialZonePolygons (Coordinates)
VALUES (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326));
GO

This then appears as:

0xE6100000010405000000DD24068195D34740F4FDD478E9965EC0508D976E12D3474083C0CAA145965EC04E62105839D4474083C0CAA145965EC04E62105839D44740F4FDD478E9965EC0DD24068195D34740F4FDD478E9965EC001000000020000000001000000FFFFFFFF0000000003

How do I select them back into their latitude and longitude formats?

Body:
You may use something like this(SQL SERVER)

SELECT Coordinates.Lat 'Latitude', Coordinates.Long 'Longitude' FROM SpatialZonePolygons

For more information - How To Get Lat-Long From Geography Data Type


问:
group function is not allowed here (sql-oracle)
I want to update saboloo with the following table

```<code>update sagani
set saboloo=sum(sagani.qula + sagani.shualeduri + sagani.finaluri)
where sagnis_id='9';
</code>```

答:
SUM is not applicable here as your requirement is very straight forward. You can try this following script for your purpose-</p>

```<code>UPDATE sagani
SET saboloo=(sagani.qula + sagani.shualeduri + sagani.finaluri)
WHERE sagnis_id='9';
</code>```

Body:
I want to update saboloo with the following table

update sagani
set saboloo=sum(sagani.qula + sagani.shualeduri + sagani.finaluri)
where sagnis_id='9';

Body:
SUM is not applicable here as your requirement is very straight forward. You can try this following script for your purpose-

UPDATE sagani
SET saboloo=(sagani.qula + sagani.shualeduri + sagani.finaluri)
WHERE sagnis_id='9';


问:
"NZEC" Error in the "Life, the Universe and Everything" problem
This is the problem presented in the question by codechef
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at the input are integers of one or two digits.

Example
Input:
1
2
Output:
1
2

I tried approaching this problem by setting up a while loop which would accept all inputs, except 42 and return the same input back to the user. Upon encountering 42 I used the sys.exit() function to exit the program

```<code>import sys
number=int()
while number != 42:
    number = int(input('enter any number '))
    print(number)
    if number == 42:
        sys.exit("yup that's 42 ")
</code>```

Instead of getting a successful submission I'm getting an NZEC Error

答:
When you exit the script by giving a message, it is considered to be an error and returns exit code 1. I tested this by running the script and then executing echo $? to check the previous exit code.

You should print the message normally first, then sys.exit().

It's mentioned in the docs as well:

If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Body:
This is the problem presented in the question by codechef
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at the input are integers of one or two digits.

Example
Input:
1
2
Output:
1
2

I tried approaching this problem by setting up a while loop which would accept all inputs, except 42 and return the same input back to the user. Upon encountering 42 I used the sys.exit() function to exit the program

import sys
number=int()
while number != 42:
    number = int(input('enter any number '))
    print(number)
    if number == 42:
        sys.exit("yup that's 42 ")

Instead of getting a successful submission I'm getting an NZEC Error


问:
What could be happened if at a dismissModalViewController call doesn't follow up a dealloc call?
I have a strange problem.
I set up a simple system that present modally a view. When i call dismiss for this modal view, the view disappear correctly but neither dealloc or viewDidUnload calls are done.

Here the code to make the view appear:

```<code>-(IBAction) spendBtnTap{
    SpendVC *spendVC = [[SpendVC alloc] initSpendWithContext:self.context];
    spendVC.delegate = self;
    [self presentModalViewController:spendVC animated:YES];
    [spendVC release];
}
</code>```

And the code to make the view disappear (from SpendVC.m):

```<code>-(void) pressBackBtn{
    [self.delegate dismissModalViewControllerAnimated:YES];
}
</code>```

And for dealloc in SpendVC ... i just added this output (But nothing happen in my console log...):

```<code>- (void)dealloc {
    NSLog(@"spend dealloc");
}
</code>```

In my application i have other button set this way... and they work correctly ... what can i missed?

答:
I just added another test in disappear function (that is correctly called) to check retain count with :

```<code>NSLog(@"%d",[self retainCount]);
</code>```

It returns 2 ..

I found that in viewDidLoad of SpendVC if i remove this code the retain is correctly set to 1 and after dismiss dealloc is call correctly.

```<code>//Setup category list
self.cats = [[CatSelectVC alloc]initWithContext:self.context];
self.cats.delegate = self;
self.cats.view.center = CGPointMake(160, 160);
[self.view addSubview:self.cats.view];
</code>```

where is incremented the retain in this code ? self.cats.delegate = self ? in this case what i have to do to release all correctly ?

Body:
I have a strange problem.
I set up a simple system that present modally a view. When i call dismiss for this modal view, the view disappear correctly but neither dealloc or viewDidUnload calls are done.

Here the code to make the view appear:

-(IBAction) spendBtnTap{
    SpendVC *spendVC = [[SpendVC alloc] initSpendWithContext:self.context];
    spendVC.delegate = self;
    [self presentModalViewController:spendVC animated:YES];
    [spendVC release];
}

And the code to make the view disappear (from SpendVC.m):

-(void) pressBackBtn{
    [self.delegate dismissModalViewControllerAnimated:YES];
}

And for dealloc in SpendVC ... i just added this output (But nothing happen in my console log...):

- (void)dealloc {
    NSLog(@"spend dealloc");
}

In my application i have other button set this way... and they work correctly ... what can i missed?

Body:
I just added another test in disappear function (that is correctly called) to check retain count with :

NSLog(@"%d",[self retainCount]);

It returns 2 ..

I found that in viewDidLoad of SpendVC if i remove this code the retain is correctly set to 1 and after dismiss dealloc is call correctly.

//Setup category list
self.cats = [[CatSelectVC alloc]initWithContext:self.context];
self.cats.delegate = self;
self.cats.view.center = CGPointMake(160, 160);
[self.view addSubview:self.cats.view];

where is incremented the retain in this code ? self.cats.delegate = self ? in this case what i have to do to release all correctly ?


问:
SQL to find almost identical values
I am looking for a sql-query to identify product numbers in a table that is almost identical. The only difference between some of the product numbers is that "/" is replaced with "-", at the exact same position in product number.

Example 1:

```<code>Product number: ab345-2
Product number: ab345/2
</code>```

Example 2:

```<code>Product number: z0059966-98
Product number: z0059966/98
</code>```

Appreciate your help!

答:
You can use exists:

```<code>select t.*
from t
where exists (select 1
              from t t2
              where replace(replace(t2.product_number, '/', ''), '-') = replace(replace(t2.product_number, '/', ''), '-') and
                    t2.product_number <> t1.product_number
             );
</code>```

Note that this can find matches to number that are missing these characters, such as 'ab345-2' and 'ab3452'.  Also, it removes all the special characters, so they can be in any position.

Title: SQL to find almost identical values

Body:
I am looking for a sql-query to identify product numbers in a table that is almost identical. The only difference between some of the product numbers is that "/" is replaced with "-", at the exact same position in product number.

Example 1:

Product number: ab345-2
Product number: ab345/2

Example 2:

Product number: z0059966-98
Product number: z0059966/98

Appreciate your help!

Body:
You can use exists:

select t.*
from t
where exists (select 1
              from t t2
              where replace(replace(t2.product_number, '/', ''), '-') = replace(replace(t2.product_number, '/', ''), '-') and
                    t2.product_number <> t1.product_number
             );

Note that this can find matches to number that are missing these characters, such as 'ab345-2' and 'ab3452'.  Also, it removes all the special characters, so they can be in any position.


问:
Which iPhone does an iPad running an iPhone only app correspond to?
Every once in a while, my iPhone only app seems to crash for users running it on iPad.

Recently I found a crash report at globalinit pointing to the initialisation of this enum type which is used heavily for design and sizes.

```<code>static var iPhone = IPhone(height: UIScreen.main.bounds.height)!
</code>```

It seems the iPad device will not match any of these heights so that nil crashes the app (This being an iPad Air with iOS 11).
On the simulator, all iPad devices seem to correspond to an existing iPhone size when running an iPhone only app.

```<code>enum IPhone: String {
  case SE, normal, plus, X, XSMax

  init?(height: CGFloat) {
    switch height {
    case 568: self = .SE
    case 667: self = .normal
    case 736: self = .plus
    case 812: self = .X
    case 896: self = .XSMax
    default:
       return nil
    }
  }
}
</code>```

Of course, I'd never want to return nil and instead incorporate possible iPad screen sizes which begs the question: Which iPhone does an iPad "simulate" when running my app?
I've recently read that from iOS 12 on, iPads will display iPhone apps no longer in 3/4 format but in 16/9.
Which is the best way to handle this so that any iPad running this app will correspond to one of my existing designs?

答:
Below reference tells that after iOS 12 all the iPhone only applications will run on iPad with iPhone 6's resolution. Change your default to self = .normal and I think you will be good to go.

https://ioshacker.com/ipad/ios-12-improves-experience-of-using-iphone-apps-on-ipad

Body:
Every once in a while, my iPhone only app seems to crash for users running it on iPad.

Recently I found a crash report at globalinit pointing to the initialisation of this enum type which is used heavily for design and sizes.

static var iPhone = IPhone(height: UIScreen.main.bounds.height)!

It seems the iPad device will not match any of these heights so that nil crashes the app (This being an iPad Air with iOS 11).
On the simulator, all iPad devices seem to correspond to an existing iPhone size when running an iPhone only app.

enum IPhone: String {
  case SE, normal, plus, X, XSMax

  init?(height: CGFloat) {
    switch height {
    case 568: self = .SE
    case 667: self = .normal
    case 736: self = .plus
    case 812: self = .X
    case 896: self = .XSMax
    default:
       return nil
    }
  }
}

Of course, I'd never want to return nil and instead incorporate possible iPad screen sizes which begs the question: Which iPhone does an iPad "simulate" when running my app?
I've recently read that from iOS 12 on, iPads will display iPhone apps no longer in 3/4 format but in 16/9.
Which is the best way to handle this so that any iPad running this app will correspond to one of my existing designs?


问:
How to find if we have two or more equal minimum values in specific columns
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

```<code>head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")
</code>```

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

```<code>head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")
</code>```

Thank you in advance.

答:
If you have a large dataset, the following might be fast. It uses package matrixStats, function rowMins. See this answer.

```<code>icol <- grepl("^a", names(mydata))
min_row <- matrixStats::rowMins(as.matrix(mydata[icol]))

mydata$flag <- rowSums(mydata[icol] == min_row) > 1 & min_row < 200
</code>```

Body:
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")

Thank you in advance.

Body:
If you have a large dataset, the following might be fast. It uses package matrixStats, function rowMins. See this answer.

icol <- grepl("^a", names(mydata))
min_row <- matrixStats::rowMins(as.matrix(mydata[icol]))

mydata$flag <- rowSums(mydata[icol] == min_row) > 1 & min_row < 200


问:
Seam: Validation of s:fileUpload?
I've got a JSF page that allows users to upload images.  I'd like to perform some validation on the uploaded file to ensure it's the correct size, dimensions, content type, etc.  I've created a JSF Validator, and have tried specifying it both in the <s:fileUpload validator="XXX" /> attribute, as well as using the <f:validator /> tag.  However, no matter what I try my validator is never called.  Is there any way to validate a file upload in Seam?  Would using <rich:fileUpload /> allow me to do validation on the uploaded file?

答:
You can try with a listener like (not sure if event has a cancel method to call if your constraint fails, but you can check):

```<code>public void listener(UploadEvent event) throws IOException {
    UploadItem item = event.getUploadItem();

    String name = "unnamed_attachment";
    byte[] data = item.getData();

    if (item.isFile()) {
        name = FilenameUtils.getName(item.getFileName());
        data = FileUtils.readFileToByteArray( item.getFile() );
    }

    debug("file uploaded '#0' : '#1'", name, item.getFileName());
</code>```

And some constraints you can put in components.xml, like:

<web:multipart-filter create-temp-files="false"
                          max-request-size="5200000"
                          url-pattern="/*"/>

Title: Seam: Validation of s:fileUpload?

Body:
You can try with a listener like (not sure if event has a cancel method to call if your constraint fails, but you can check):

public void listener(UploadEvent event) throws IOException {
    UploadItem item = event.getUploadItem();

    String name = "unnamed_attachment";
    byte[] data = item.getData();

    if (item.isFile()) {
        name = FilenameUtils.getName(item.getFileName());
        data = FileUtils.readFileToByteArray( item.getFile() );
    }

    debug("file uploaded '#0' : '#1'", name, item.getFileName());

And some constraints you can put in components.xml, like:

<web:multipart-filter create-temp-files="false"
                          max-request-size="5200000"
                          url-pattern="/*"/>


问:
Should Internal error (500) be part of Swagger API documentation?
As far as I checked on many swagger files of Amazon/Google and more, That error code (or generally error codes of 5xx family) is not shown as a part of the swagger files. Is their  a reason for that?

I am asking because one of our microservices API returns 500 when it fails to communicate to other service (for instance) and we are wondering if that error code should be part of our swagger files.

答: I think API documentation should only contain expected errors such as 4xx ones. But 5xx are unexpected errors and should not be documented.</p>


问:
Laravel Passport TokenGuard::__construct() must implement interface
I'm creating a rest api with Laravel and Laravel Passport. I try to access a route protected with the default laravel api auth middleware:

```<code>Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::prefix('auth')->group(function () {
    Route::post('login', 'Auth\ApiAuthController@login');
});
</code>```

In the request header I pass Authorization: Bearer <my_secret_token> but I get this exception:

```<code>Argument 1 passed to Illuminate\Auth\TokenGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in /Users/markusheinemann/Projekte/Lycus/application/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 162
</code>```

Here my request header:

```<code>{
  content-type: "application/json",
  x-requested-with: "XMLHttpRequest",
  authorization: "********",
  user-agent: "PostmanRuntime/7.13.0",
  accept: "*/*",
  cache-control: "no-cache",
  postman-token: "ebfa3211-958d-4042-ab6a-a488847fc2f7",
  host: "localhost",
  accept-encoding: "gzip, deflate",
  connection: "keep-alive"
}
</code>```

Here my token creating process:

```<code>public function login(LoginRequest $request)
{
    $credentials = $request->only(['email', 'password']);

    if(!Auth::attempt($credentials)) {
        return response()->json(['message' => trans('auth.failed')], 401);
    }

    $token = $request->user()->createToken('Lycus Frontend Client');
    $token->token->save();

    return response()->json([
        'accessToken' => $token->accessToken,
        'expiresAt' => $token->token->expires_at,
    ]);
}
</code>```

Has anyone an idea why I get this error?

答:
Make sure your user model uses:

```<code>class User extends Authenticatable
{
    use HasApiTokens;
}
</code>```

---EDIT----

I have seen that login code in some guides on the internet, I personally think it is better to resend the request to the Passport API and let it login and create the tokens.

```<code>$request->validate([
    'email'    => 'required|string|email',
    'password' => 'required|string'
]);

$http = new Client();

try {
    $response = $http->post('/oauth/token', [
        'form_params' => [
            'grant_type'    => 'password',
            'client_id'     => 2,
            'client_secret' => 'secret_key_from_passport_client',
            'username'      => $request->email,
            'password'      => $request->password,
        ]
    ]);

    return $response->getBody();
} catch (BadResponseException $e) {
    return response()->json([], 422);
}
</code>```

---EDIT---
If you move User to other namespace don't forget to change in auth.php

```<code>'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Auth\User::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],
</code>```

Body:
I'm creating a rest api with Laravel and Laravel Passport. I try to access a route protected with the default laravel api auth middleware:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::prefix('auth')->group(function () {
    Route::post('login', 'Auth\ApiAuthController@login');
});

In the request header I pass Authorization: Bearer <my_secret_token> but I get this exception:

Argument 1 passed to Illuminate\Auth\TokenGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in /Users/markusheinemann/Projekte/Lycus/application/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 162

Here my request header:

{
  content-type: "application/json",
  x-requested-with: "XMLHttpRequest",
  authorization: "********",
  user-agent: "PostmanRuntime/7.13.0",
  accept: "*/*",
  cache-control: "no-cache",
  postman-token: "ebfa3211-958d-4042-ab6a-a488847fc2f7",
  host: "localhost",
  accept-encoding: "gzip, deflate",
  connection: "keep-alive"
}

Here my token creating process:

public function login(LoginRequest $request)
{
    $credentials = $request->only(['email', 'password']);

    if(!Auth::attempt($credentials)) {
        return response()->json(['message' => trans('auth.failed')], 401);
    }

    $token = $request->user()->createToken('Lycus Frontend Client');
    $token->token->save();

    return response()->json([
        'accessToken' => $token->accessToken,
        'expiresAt' => $token->token->expires_at,
    ]);
}

Has anyone an idea why I get this error?

Body:
Make sure your user model uses:

class User extends Authenticatable
{
    use HasApiTokens;
}

---EDIT----

I have seen that login code in some guides on the internet, I personally think it is better to resend the request to the Passport API and let it login and create the tokens.

$request->validate([
    'email'    => 'required|string|email',
    'password' => 'required|string'
]);

$http = new Client();

try {
    $response = $http->post('/oauth/token', [
        'form_params' => [
            'grant_type'    => 'password',
            'client_id'     => 2,
            'client_secret' => 'secret_key_from_passport_client',
            'username'      => $request->email,
            'password'      => $request->password,
        ]
    ]);

    return $response->getBody();
} catch (BadResponseException $e) {
    return response()->json([], 422);
}

---EDIT---
If you move User to other namespace don't forget to change in auth.php

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\Auth\User::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],


问:
hibernate + spring boot store date on UTC time zone troubles
I'm making some tests to define UTC as default time zone for my application. First of all I want my datetime values to be stored with the UTC one.

According to VLAD MIHALCEA (https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/) and https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/ I have set in my properties file:

```<code>spring.jpa.properties.hibernate.jdbc.time_zone= UTC
</code>```

For testing I'm using h2 database, I've created a sample entity with all java 8 dateTime Type.

In my liquibase config they are defined like this:

```<code><column name="instant" type="timestamp"/>
<column name="local_date" type="date"/>
<column name="local_time" type="time"/>
<column name="offset_time" type="time"/>
<column name="local_date_time" type="timestamp"/>
<column name="offset_date_time" type="timestamp"/>
<column name="zoned_date_time" type="timestamp"/>
</code>```

I think I'm using the good type for every fields. It's work for all fields except for "local_time" "offset_time" which are Time sql types not timestamp.

As you can see i added this row at 8:39am (Paris GMT+2) and timestamps have the good UTC value (6:38am).
BUT both "local_time" and "offset_time" have a strange value (7:39am).

I wonder why this behaviour, if some of you have an idea why my two time fields not store values correctly.

PS: version:

Hibernate: 5.2.17.Final

Spring boot: 2.0.4.RELEASE

My sample Entity use to insert data :

```<code>import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;

@Entity
@Table(name = "avdev_myData")
public class MyData implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "instant")
    private Instant instant;

    @Column(name = "local_date")
    private LocalDate localDate;

    @Column(name = "local_time")
    private LocalTime localTime;

    @Column(name = "offset_time")
    private OffsetTime offsetTime;

    @Column(name = "local_date_time")
    private LocalDateTime localDateTime;

    @Column(name = "offset_date_time")
    private OffsetDateTime offsetDateTime;

    @Column(name = "zoned_date_time")
    private ZonedDateTime zonedDateTime;
</code>```

答:
```<code>spring.datasource.url=jdbc:mysql://...?serverTimezone=Asia/Shanghai
</code>```

works for me.

Hibernate SHOULD reflect mysql timezone.

mysql jdbc should reflect mysql timezone.

Body:
I'm making some tests to define UTC as default time zone for my application. First of all I want my datetime values to be stored with the UTC one.

According to VLAD MIHALCEA (https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/) and https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/ I have set in my properties file:

spring.jpa.properties.hibernate.jdbc.time_zone= UTC

For testing I'm using h2 database, I've created a sample entity with all java 8 dateTime Type.

In my liquibase config they are defined like this:

<column name="instant" type="timestamp"/>
<column name="local_date" type="date"/>
<column name="local_time" type="time"/>
<column name="offset_time" type="time"/>
<column name="local_date_time" type="timestamp"/>
<column name="offset_date_time" type="timestamp"/>
<column name="zoned_date_time" type="timestamp"/>

I think I'm using the good type for every fields. It's work for all fields except for "local_time" "offset_time" which are Time sql types not timestamp.

As you can see i added this row at 8:39am (Paris GMT+2) and timestamps have the good UTC value (6:38am).
BUT both "local_time" and "offset_time" have a strange value (7:39am).

I wonder why this behaviour, if some of you have an idea why my two time fields not store values correctly.

PS: version:

Hibernate: 5.2.17.Final

Spring boot: 2.0.4.RELEASE

My sample Entity use to insert data :

import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;

@Entity
@Table(name = "avdev_myData")
public class MyData implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "instant")
    private Instant instant;

    @Column(name = "local_date")
    private LocalDate localDate;

    @Column(name = "local_time")
    private LocalTime localTime;

    @Column(name = "offset_time")
    private OffsetTime offsetTime;

    @Column(name = "local_date_time")
    private LocalDateTime localDateTime;

    @Column(name = "offset_date_time")
    private OffsetDateTime offsetDateTime;

    @Column(name = "zoned_date_time")
    private ZonedDateTime zonedDateTime;

Body:
spring.datasource.url=jdbc:mysql://...?serverTimezone=Asia/Shanghai

works for me.

Hibernate SHOULD reflect mysql timezone.

mysql jdbc should reflect mysql timezone.


问:
Univocity - Parse single row into multiple beans
Is it possible to parse a single line into multiple beans based on index ranges

Example:

Line: "field1", "field2", "field3", ...., "field9"

```<code>class ColumnsOneAndTwo {
   protected String field1;
   protected String field2;
}

class ColumnThreeAndNine {
   protected String field3;
   protected String field9;
}

class Row {

  @Parsed(indexes = 0, 1)
  protected ColumnOneAndTwo fields;

  @Parsed(indexes = 2, 8)
  protected ColumnThreeAndNine moreFields;

}

BeanListProcessor<Row> rowProcessor = new BeanListProcessor<Row>(Row.class);

CsvRoutines routines = new CsvRoutines(parserSettings);

for (Row data : routines.iterate(Row.class, <file>, "UTF-8")) {

}
</code>```

答:
You are looking for the @Nested annotation. Just use:

```<code>class ColumnsOneAndTwo {
    @Parsed(index=1)
    protected String field1;

    @Parsed(index=2)
    protected String field2;
}

class ColumnThreeAndNine {
    @Parsed(index=3)
    protected String field3;

    @Parsed(index=9)
    protected String field9;
}

class Row {

   @Nested
   protected ColumnOneAndTwo fields;

   @Nested
   protected ColumnThreeAndNine moreFields;

}
</code>```

Hope it helps.

Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0 license)

Body:
Is it possible to parse a single line into multiple beans based on index ranges

Example:

Line: "field1", "field2", "field3", ...., "field9"

class ColumnsOneAndTwo {
   protected String field1;
   protected String field2;
}

class ColumnThreeAndNine {
   protected String field3;
   protected String field9;
}

class Row {

  @Parsed(indexes = 0, 1)
  protected ColumnOneAndTwo fields;

  @Parsed(indexes = 2, 8)
  protected ColumnThreeAndNine moreFields;

}

BeanListProcessor<Row> rowProcessor = new BeanListProcessor<Row>(Row.class);

CsvRoutines routines = new CsvRoutines(parserSettings);

for (Row data : routines.iterate(Row.class, <file>, "UTF-8")) {

}

Body:
You are looking for the @Nested annotation. Just use:

class ColumnsOneAndTwo {
    @Parsed(index=1)
    protected String field1;

    @Parsed(index=2)
    protected String field2;
}

class ColumnThreeAndNine {
    @Parsed(index=3)
    protected String field3;

    @Parsed(index=9)
    protected String field9;
}

class Row {

   @Nested
   protected ColumnOneAndTwo fields;

   @Nested
   protected ColumnThreeAndNine moreFields;

}

Hope it helps.

Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0 license)


问:
Why two lines in git source tree cross each other?
Why do these lines cross each other. They could have run parallel. What is the significance of crossing lines?

答:
This has no particular meaning in Git. This is merely how the GUI chose to visualize it.

You can see if Git does the same with git log --graph --oneline. My guess is that it won't show this crossing in that particular case, but hard to say without seeing the full screenshot.


问:
Error in .External2(C_dataviewer, x, title) : unable to start data viewer
In R I get the following errors any time I hit View() or data.frame and I do not understand why. It happened suddenly.

```<code>> View(Fhat_all)
Error in .External2(C_dataviewer, x, title) : unable to start data viewer
In addition: Warning message:
In View(Fhat_all) : unable to open display

> da <- data.frame(comb[true_comb_RMSE[1],1], comb[true_comb_RMSE[1],2],
comb[true_comb_KS[1],1],comb[true_comb_KS[1],2])
Error in (function (env, objName)  :
could not find function "object.size"
</code>```

I checked this other page in Stackoverflow Can't use either View() or edit() functions, getting "Error in .External2(C_dataviewer, x, title) : invalid device" error message but I didn't understand how to fix it. So I hit locale on terminal and got this result:

```<code>Last login: Mon Mar 21 16:47:07 on ttys000
MacBook-Pro:~ "username"$ locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=
MacBook-Pro:~ "username"$ LC_CTYPE = C R
-bash: LC_CTYPE: command not found
</code>```

so I hit LC_CTYPE=C R on the the terminal as by suggestion and tried to view a vector in R, but I got the same error message:

```<code>> View(w)
Error in .External2(C_dataviewer, x, title) : unable to start data viewer
In addition: Warning message:
In View(w) : unable to open display
</code>```

Can you please help me? Thank you.

答:
I had the same error when using the jagsUI package, which masks the View function. Perhaps you have conflicts between packages?

Check potential conflicts between functions by calling conflicts(detail=TRUE) (Taken from this answer for finding which functions are masked in R).

Easiest workaround in my case was calling detach("package:jagsUI", unload = TRUE) once I finished using JAGS.

Body:
In R I get the following errors any time I hit View() or data.frame and I do not understand why. It happened suddenly.

> View(Fhat_all)
Error in .External2(C_dataviewer, x, title) : unable to start data viewer
In addition: Warning message:
In View(Fhat_all) : unable to open display

> da <- data.frame(comb[true_comb_RMSE[1],1], comb[true_comb_RMSE[1],2],
comb[true_comb_KS[1],1],comb[true_comb_KS[1],2])
Error in (function (env, objName)  :
could not find function "object.size"

I checked this other page in Stackoverflow Can't use either View() or edit() functions, getting "Error in .External2(C_dataviewer, x, title) : invalid device" error message but I didn't understand how to fix it. So I hit locale on terminal and got this result:

Last login: Mon Mar 21 16:47:07 on ttys000
MacBook-Pro:~ "username"$ locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=
MacBook-Pro:~ "username"$ LC_CTYPE = C R
-bash: LC_CTYPE: command not found

so I hit LC_CTYPE=C R on the the terminal as by suggestion and tried to view a vector in R, but I got the same error message:

> View(w)
Error in .External2(C_dataviewer, x, title) : unable to start data viewer
In addition: Warning message:
In View(w) : unable to open display

Can you please help me? Thank you.


问:
How to fix the bot from asking for id in DM , discord bot in JavaScript
Am coding a discord bot, the bot works fine if run inside the server but I want to add some commands that will also work inside DM, I have some code that set prefix for every server and when I run the bot and try commands in DM it produce error because it looking for guild id which DM doesn't have, how can I go around this.

```<code>//the code from line index.js:63:30 in the error message

if(message.author.bot) return;

let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]){
  prefixes[message.guild.id] = {
    prefixes: botconfig.prefix
  };
}
</code>```

I have tried using if statement but when I run command in DM the command still doesn't work but it doesn't produce any error.

```<code>bot.on("message", async message => {
  if (message.channel.type === "dm") {
      let prefix = "!";
} else (message.guild) {
      let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
  if(!prefixes[message.guild.id]){
    prefixes[message.guild.id] = {
      prefixes: botconfig.prefix
    };
  let prefix = prefixes[message.guild.id].prefixes;
  if(!message.content.startsWith(prefix)) return;

    let messageArray = message.content.split(" ");
  let cmd = messageArray[0];
  let args = messageArray.slice(1);

  let commandfile = bot.commands.get(cmd.slice(prefix.length));
  if(commandfile) commandfile.run(bot,message,args);
  }
}
}
</code>```

Below is the error am getting which is pointing me to line 63 in my code which is the code I posted above

```<code>    at Client.bot.on (C:\Users\Milan\Desktop\episode-18-code\index.js:63:30)
    at Client.emit (events.js:198:13)
    at MessageCreateHandler.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
    at WebSocketConnection.onPacket (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:198:13)
    at Receiver.receiverOnMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\websocket.js:789:20)
    at Receiver.emit (events.js:198:13)
(node:2912) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2912) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```
```

答:
You can use </p>

```<code>if(message.channel.type === 'dm') {
    let prefix = 'bot main prefix'
}
else if(message.channel.type === 'guild') {
      let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
}
</code>```

Body:
Am coding a discord bot, the bot works fine if run inside the server but I want to add some commands that will also work inside DM, I have some code that set prefix for every server and when I run the bot and try commands in DM it produce error because it looking for guild id which DM doesn't have, how can I go around this.

//the code from line index.js:63:30 in the error message

if(message.author.bot) return;

let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
if(!prefixes[message.guild.id]){
  prefixes[message.guild.id] = {
    prefixes: botconfig.prefix
  };
}

I have tried using if statement but when I run command in DM the command still doesn't work but it doesn't produce any error.

bot.on("message", async message => {
  if (message.channel.type === "dm") {
      let prefix = "!";
} else (message.guild) {
      let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
  if(!prefixes[message.guild.id]){
    prefixes[message.guild.id] = {
      prefixes: botconfig.prefix
    };
  let prefix = prefixes[message.guild.id].prefixes;
  if(!message.content.startsWith(prefix)) return;

    let messageArray = message.content.split(" ");
  let cmd = messageArray[0];
  let args = messageArray.slice(1);

  let commandfile = bot.commands.get(cmd.slice(prefix.length));
  if(commandfile) commandfile.run(bot,message,args);
  }
}
}

Below is the error am getting which is pointing me to line 63 in my code which is the code I posted above

    at Client.bot.on (C:\Users\Milan\Desktop\episode-18-code\index.js:63:30)
    at Client.emit (events.js:198:13)
    at MessageCreateHandler.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
    at WebSocketConnection.onPacket (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\event-target.js:120:16)
    at WebSocket.emit (events.js:198:13)
    at Receiver.receiverOnMessage (C:\Users\Milan\Desktop\episode-18-code\node_modules\ws\lib\websocket.js:789:20)
    at Receiver.emit (events.js:198:13)
(node:2912) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2912) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

Body:
You can use

if(message.channel.type === 'dm') {
    let prefix = 'bot main prefix'
}
else if(message.channel.type === 'guild') {
      let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8"));
}


问:
How to use LIKE operator on a query of sequelize?
```<code>sequelize.query('(..) WHERE LOWER(u.NOMBRE) LIKE "LOWER(:find)%" AND u.ACTIVO = 1 ', {replacements: {find: req.params.usuario, id: req.session.passport.user}, type: sequelize.QueryTypes.SELECT})
</code>```

答:
An example of how to use $like based on your question:</p>

```<code>const Sequelize = require('sequelize');
const Op = Sequelize.Op;

const user = User.findAll({ // or User.findOne
    where: {
        activo: 1, // your search condition
        [Op.like]: [
            { nombre: req.params.nombre } // your $like params
        ],
    }
    attributes: ['id', 'nombre'] // results you want returned
})
</code>```

Body:
An example of how to use $like based on your question:

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

const user = User.findAll({ // or User.findOne
    where: {
        activo: 1, // your search condition
        [Op.like]: [
            { nombre: req.params.nombre } // your $like params
        ],
    }
    attributes: ['id', 'nombre'] // results you want returned
})


问:
'PublishAsync' missing in RabbitMq package
I have the following code:

```<code>public async Task<IActionResult> Post([FromBody]CreateActivity command)
        {
            command.Id = Guid.NewGuid();
            command.CreatedAt = DateTime.UtcNow;

            await _busClient.PublishAsync(command);

            return Accepted($"activities/{command.Id}");

        }
</code>```

It seems like 'PublishAsync' method is missing in RabbitMq. This is my .csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
    <PackageReference Include="RawRabbit" Version="2.0.0-beta8" />
    <PackageReference Include="RawRabbit.DependencyInjection.ServiceCollection" Version="2.0.0-beta8" />
    <PackageReference Include="RawRabbit.Operations.Subscribe" Version="2.0.0-beta8" />
  </ItemGroup>

</Project>
</code>```

It is the same with all other stable versions.

答:
Looking at the source code it seems that the PublishAsync method is defined as an extension method in the RawRabbit.Operations.Publish NuGet pacakge:

Enrich the BusClient with PublishAsync, used to perform a BasicPublish

Body:
I have the following code:

public async Task<IActionResult> Post([FromBody]CreateActivity command)
        {
            command.Id = Guid.NewGuid();
            command.CreatedAt = DateTime.UtcNow;

            await _busClient.PublishAsync(command);

            return Accepted($"activities/{command.Id}");

        }

It seems like 'PublishAsync' method is missing in RabbitMq. This is my .csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
    <PackageReference Include="RawRabbit" Version="2.0.0-beta8" />
    <PackageReference Include="RawRabbit.DependencyInjection.ServiceCollection" Version="2.0.0-beta8" />
    <PackageReference Include="RawRabbit.Operations.Subscribe" Version="2.0.0-beta8" />
  </ItemGroup>

</Project>

It is the same with all other stable versions.


问:
Getting Token and User Info iOS Swift
I am working on web view login form and I have requested the URL in web view and on success login I got an authorization code. Now to get token I am trying to use the code but seems like its status code 400.

How can I get the access token? Hopefully, the method should be right; I don't know where it's going wrong.

```<code>super.viewDidLoad()
        let url = URL(string: "https://***/oauth2/authorize?scope=openid&response_type=code&redirect_uri=\(REDIRECT_URI)&client_id=\(CLIENT_ID)")
        let request = URLRequest(url: url!)
        webView.load(request)
        self.webView.navigationDelegate = self

    }
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        if let url = webView.url?.absoluteString{
            print("url = \(url)")

            let queryItems = URLComponents(string: url)?.queryItems
            authCode = queryItems?.filter({$0.name == "code"}).first
            sessionState = queryItems?.filter({$0.name == "session_state"}).first

            print("CODE VALUE IS",authCode?.value as Any)
            print("SESSION STATE VALUE IS",sessionState?.value as Any)

           let headers = ["content-type": "application/x-www-form-urlencoded"]
            let postData = NSMutableData(data: "grant_type=\(GRANT_TYPE)".data(using: String.Encoding.utf8)!)
            postData.append("&client_id=\(CLIENT_ID)".data(using: String.Encoding.utf8)!)
            postData.append("&client_secret=\(CLIENT_SECRET)".data(using: String.Encoding.utf8)!)
            postData.append("&code=\(String(describing: authCode?.value))".data(using: String.Encoding.utf8)!)
            postData.append("&redirect_ui=\(REDIRECT_URI)".data(using: String.Encoding.utf8)!)

            let request = NSMutableURLRequest(url: NSURL(string: TOKEN_URL)! as URL,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            print("POSTDATA",postData.debugDescription)

           request.httpMethod = "POST"
           request.allHTTPHeaderFields = headers
            request.httpBody = postData as Data

            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if (error != nil) {
                    print(error as Any)
                } else {
                    let httpResponse = response as? HTTPURLResponse

                    print("Response is",httpResponse as Any)
                }
            })

            dataTask.resume()
        }

}
}
</code>```

RESPONSE:

```<code>Response is Optional(<NSHTTPURLResponse: 0x600000230a60> { URL: https://account.eziemall.com/oauth2/token } { Status Code: 400, Headers {
        "Content-Length" =     (
            82
        );
        "Content-Type" =     (
            "application/json"
        );
        Date =     (
            "Fri, 31 May 2019 11:03:42 GMT"
        );
        Server =     (
            "nginx/1.13.5"
        );
        "Set-Cookie" =     (
            "AWSALB=1Kah/jnLt4LFWcdh26U0DF9Jmf3IjVmSpKleCr9tNyq28wjoRANlQ6DSWcYGtMnWRJfBCQ0N7cMOpganMOaYVNzmoqp7vDyONPA1nwnYVdD9vJctwDAt7MB96xlf; Expires=Fri, 07 Jun 2019 11:03:42 GMT; Path=/"
        );
        "x-content-type-options" =     (
            nosniff
        );
        "x-xss-protection" =     (
            "1; mode=block"
        );
    } })
</code>```

答:
Most likely the reason of the error is the optional authCode?.value which adds a literal "Optional( in String Interpolation.

Unwrap the optional in the first if let line.

This is an improved version getting rid of the ugly objective-c-ish NSMutable... classes

```<code>func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    if let url = webView.url?.absoluteString, let authCodeValue = authCode?.value {
        let headers = ["content-type": "application/x-www-form-urlencoded"]
        var postString = "grant_type=\(GRANT_TYPE)"
        postString += "&client_id=\(CLIENT_ID)"
        postString += "&client_secret=\(CLIENT_SECRET)"
        postString += "&code=\(authCodeValue)"
        postString += "&redirect_uri=\(REDIRECT_URI)"

        var request = URLRequest(url: URL(string: TOKEN_URL)!)
        request.cachePolicy = .useProtocolCachePolicy
        request.timeoutInterval = 10.0
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = Data(postString.utf8)

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                print(error)
            } else {
                if let httpResponse = response as? HTTPURLResponse {
                    print("Response is", httpResponse)
                }
            }
        })
    }
}
</code>```

Title: Getting Token and User Info iOS Swift

Body:
I am working on web view login form and I have requested the URL in web view and on success login I got an authorization code. Now to get token I am trying to use the code but seems like its status code 400.

How can I get the access token? Hopefully, the method should be right; I don't know where it's going wrong.

super.viewDidLoad()
        let url = URL(string: "https://***/oauth2/authorize?scope=openid&response_type=code&redirect_uri=\(REDIRECT_URI)&client_id=\(CLIENT_ID)")
        let request = URLRequest(url: url!)
        webView.load(request)
        self.webView.navigationDelegate = self

    }
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        if let url = webView.url?.absoluteString{
            print("url = \(url)")

            let queryItems = URLComponents(string: url)?.queryItems
            authCode = queryItems?.filter({$0.name == "code"}).first
            sessionState = queryItems?.filter({$0.name == "session_state"}).first

            print("CODE VALUE IS",authCode?.value as Any)
            print("SESSION STATE VALUE IS",sessionState?.value as Any)

           let headers = ["content-type": "application/x-www-form-urlencoded"]
            let postData = NSMutableData(data: "grant_type=\(GRANT_TYPE)".data(using: String.Encoding.utf8)!)
            postData.append("&client_id=\(CLIENT_ID)".data(using: String.Encoding.utf8)!)
            postData.append("&client_secret=\(CLIENT_SECRET)".data(using: String.Encoding.utf8)!)
            postData.append("&code=\(String(describing: authCode?.value))".data(using: String.Encoding.utf8)!)
            postData.append("&redirect_ui=\(REDIRECT_URI)".data(using: String.Encoding.utf8)!)

            let request = NSMutableURLRequest(url: NSURL(string: TOKEN_URL)! as URL,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            print("POSTDATA",postData.debugDescription)

           request.httpMethod = "POST"
           request.allHTTPHeaderFields = headers
            request.httpBody = postData as Data

            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if (error != nil) {
                    print(error as Any)
                } else {
                    let httpResponse = response as? HTTPURLResponse

                    print("Response is",httpResponse as Any)
                }
            })

            dataTask.resume()
        }

}
}

RESPONSE:

Response is Optional(<NSHTTPURLResponse: 0x600000230a60> { URL: https://account.eziemall.com/oauth2/token } { Status Code: 400, Headers {
        "Content-Length" =     (
            82
        );
        "Content-Type" =     (
            "application/json"
        );
        Date =     (
            "Fri, 31 May 2019 11:03:42 GMT"
        );
        Server =     (
            "nginx/1.13.5"
        );
        "Set-Cookie" =     (
            "AWSALB=1Kah/jnLt4LFWcdh26U0DF9Jmf3IjVmSpKleCr9tNyq28wjoRANlQ6DSWcYGtMnWRJfBCQ0N7cMOpganMOaYVNzmoqp7vDyONPA1nwnYVdD9vJctwDAt7MB96xlf; Expires=Fri, 07 Jun 2019 11:03:42 GMT; Path=/"
        );
        "x-content-type-options" =     (
            nosniff
        );
        "x-xss-protection" =     (
            "1; mode=block"
        );
    } })

Body:
Most likely the reason of the error is the optional authCode?.value which adds a literal "Optional( in String Interpolation.

Unwrap the optional in the first if let line.

This is an improved version getting rid of the ugly objective-c-ish NSMutable... classes

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    if let url = webView.url?.absoluteString, let authCodeValue = authCode?.value {
        let headers = ["content-type": "application/x-www-form-urlencoded"]
        var postString = "grant_type=\(GRANT_TYPE)"
        postString += "&client_id=\(CLIENT_ID)"
        postString += "&client_secret=\(CLIENT_SECRET)"
        postString += "&code=\(authCodeValue)"
        postString += "&redirect_uri=\(REDIRECT_URI)"

        var request = URLRequest(url: URL(string: TOKEN_URL)!)
        request.cachePolicy = .useProtocolCachePolicy
        request.timeoutInterval = 10.0
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = Data(postString.utf8)

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                print(error)
            } else {
                if let httpResponse = response as? HTTPURLResponse {
                    print("Response is", httpResponse)
                }
            }
        })
    }
}


问:
Regex validation pattern only allows one character
I'm trying to make functions for validating usernames, emails, and passwords and my regex isn't working. My regex for usernames is ^[a-zA-Z0-9 _-]$ and when I put anything through that should work it always returns false.

As I understand it, the ^ and $ at the beginning and the end means that it makes sure the entire string matches this regular expression, the a-z and A-Z allows all letters, 0-9 allows all numbers, and the last three characters (the space, underscore, and dash) allow the respective characters.

Why is my regular expression not evaluating properly?

答:
You need a quantifier, + or *. As it was written that only allows 1 of the characters in the character class.

Your a-zA-Z0-9_ also can be replaced with \w. Try:

```<code>^[\w -]+$
</code>```

+ requires 1 or more matches. * requires 0 or more matches so if an empty string is valid use *.

Additionally you could use \h in place of the space character if tabs are allowed. That is the metacharacter for a horizontal space. I find it easier to read than the literal space.

Per comment, Update:

Since it looks like you want the string to be between a certain number of characters we can get more specific with the regex. A range can be created with {x,y} which will replace the quantifier.

```<code>^[\w -]{3,30}$
</code>```

Additionally in PHP you must provide delimiters at the start and end of the regex.

```<code>preg_match("/^[\w -]{3,30}$/", $username);
</code>```

Additionally, you should enable error reporting so you get these useful errors in the future. See https://stackoverflow.com/a/21429652/3783243

Body:
You need a quantifier, + or *. As it was written that only allows 1 of the characters in the character class.

Your a-zA-Z0-9_ also can be replaced with \w. Try:

^[\w -]+$

+ requires 1 or more matches. * requires 0 or more matches so if an empty string is valid use *.

Additionally you could use \h in place of the space character if tabs are allowed. That is the metacharacter for a horizontal space. I find it easier to read than the literal space.

Per comment, Update:

Since it looks like you want the string to be between a certain number of characters we can get more specific with the regex. A range can be created with {x,y} which will replace the quantifier.

^[\w -]{3,30}$

Additionally in PHP you must provide delimiters at the start and end of the regex.

preg_match("/^[\w -]{3,30}$/", $username);

Additionally, you should enable error reporting so you get these useful errors in the future. See https://stackoverflow.com/a/21429652/3783243


问:
A declarative workflow does not start automatically after you install Windows SharePoint Services 3.0 Service Pack 1
That's the title of kb947284 actually. Recently I was involved in a Sharepoint project. I run into this problem where my workflow does not start automatically. If I run the workflow manually, it's just fine. I found kb947284. Apparently the cause of this problem is the installation of WSS 3 SP1. I did what it said in the Resolution section but it didn't work.

The Resolution said to set the application pool account to use a different user account. What kind of different does it mean? What kind of user account will work? I changed the user account but both old and new account is in the same group of administrator for the server where SP is installed.

Oh! I also found a copy of kb947284 and one comments stated there is already a hotfix (kb956057). I've read the issues that are fixed but could not find anywhere about this workflow problem.

Could anyone please tell me how it's supposed to be done? Thanks in advance.

答:
From the KB:

This behavior occurs because a security fix in Windows SharePoint Services 3.0 SP1 prevents declarative workflows from starting automatically under the system account. After you install Windows SharePoint Services 3.0 SP1, declarative workflows do not start automatically if the following conditions are true:

The Windows SharePoint Services Web
application runs under a user's
domain account.

The user logs in by using this
domain account.

The site displays the user name as
System Account. Back to the top

My Questions are:
Have you installed WSS SP1?

Are the 3 conditions stated above met?

If so, the application pool identity should be changed to one that isn't used by a person logging into SharePoint.

OwnerDisplayName: ira

OwnerDisplayName: Jason


问:
Multipart Post request in Apache Httpclient 4.5.6 not working
I am trying to upload a file to the server. The request is working fine while using Postman tool.

In Postman I have :

```<code>POST :https://transport-stg.transperfect.com/api/files/upload?filename=test.png&targetFolderId=2ff5ea6a-8187-4622-ab58-c7511c445ae7
</code>```

In Header I have :

```<code>Content-Type = multipart/form-data
Authorixation = Bearer access_code
</code>```

In Body I have:

```<code>  file = test.txt (this is file to be uploaded,able to select file location in Postman)
</code>```

This Above is working as expected in postman tool.

Now I wrote a below code in Java using HttpClient 4.5.6 as

```<code>try {
 CloseableHttpClient httpClient = HttpClients.createDefault();
File file = new File("C:\\Users\\lKadariya\\Desktop\\test.txt");
  String authorizationValue = "Bearer "+accessToken;
HttpEntity data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addBinaryBody("srcUploader",file,ContentType.DEFAULT_BINARY,file.getName())
        .build();
  HttpUriRequest request = RequestBuilder.post("https://transport-stg.transperfect.com/api/files/upload")
          .addHeader("Content-Type","multipart/form-data")
          .addHeader("Authorization",authorizationValue)
          .addHeader("Accept","application/json")
          .addParameter("filename","test.txt")
          .addParameter("targetFolderId","2ff5ea6a-8187-4622-ab58-c7511c445ae7")
          .setEntity(data)
          .build();
   ResponseHandler<String> responseHandler = response -> {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
      HttpEntity entity = response.getEntity();
      return entity != null ? EntityUtils.toString(entity) : null;
    } else {
      throw new ClientProtocolException("Unexpected response status: " + status);
    }
  };
  String responseBody = httpClient.execute(request, responseHandler);
</code>```

And i am not able to upload the file.
ERROr: Unable to upload file from server.
the postman is giving the expected respone.

What could go wrong with this above Httpclient code?

The OKhttp library is also working fine as

```<code>OkHttpClient client = new OkHttpClient();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
//            .addPart(
//                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
//                    RequestBody.create(null, "test"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"test\""),
                    RequestBody.create(MEDIA_TYPE_TXT, new File("test.txt")))
//            .addFormDataPart("file","file.txt",
//                    RequestBody.create(MediaType.parse("application/octet-stream"),new File("test.txt"))
//                    )
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Bearer " + accessToken)
            .url("https://transport-stg.transperfect.com/api/files/upload?filename=basic.txt&targetFolderId=2ff5ea6a-8187-4622-ab58-c7511c445ae7")
            .post(requestBody)
            .header("Content-Type","multipart/form-data")
            .build();
try {
  Response response = client.newCall(request).execute();
</code>```

What could go wrong in the HttpClient code?

答:
```<code>HttpUriRequest request = RequestBuilder.post("https://transport-stg.transperfect.com/api/files/upload")
      .addHeader("Content-Type","multipart/form-data")
</code>```

The Content-Type value in your code is invalid as it does not include the boundary parameter.

You should not meddle with Content-Type header at the request level and let HttpClient generate it automatically based on properties of the enclosed request entity.

Body:
I am trying to upload a file to the server. The request is working fine while using Postman tool.

In Postman I have :

POST :https://transport-stg.transperfect.com/api/files/upload?filename=test.png&targetFolderId=2ff5ea6a-8187-4622-ab58-c7511c445ae7

In Header I have :

Content-Type = multipart/form-data
Authorixation = Bearer access_code

In Body I have:

  file = test.txt (this is file to be uploaded,able to select file location in Postman)

This Above is working as expected in postman tool.

Now I wrote a below code in Java using HttpClient 4.5.6 as

try {
 CloseableHttpClient httpClient = HttpClients.createDefault();
File file = new File("C:\\Users\\lKadariya\\Desktop\\test.txt");
  String authorizationValue = "Bearer "+accessToken;
HttpEntity data = MultipartEntityBuilder.create()
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .addBinaryBody("srcUploader",file,ContentType.DEFAULT_BINARY,file.getName())
        .build();
  HttpUriRequest request = RequestBuilder.post("https://transport-stg.transperfect.com/api/files/upload")
          .addHeader("Content-Type","multipart/form-data")
          .addHeader("Authorization",authorizationValue)
          .addHeader("Accept","application/json")
          .addParameter("filename","test.txt")
          .addParameter("targetFolderId","2ff5ea6a-8187-4622-ab58-c7511c445ae7")
          .setEntity(data)
          .build();
   ResponseHandler<String> responseHandler = response -> {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
      HttpEntity entity = response.getEntity();
      return entity != null ? EntityUtils.toString(entity) : null;
    } else {
      throw new ClientProtocolException("Unexpected response status: " + status);
    }
  };
  String responseBody = httpClient.execute(request, responseHandler);

And i am not able to upload the file.
ERROr: Unable to upload file from server.
the postman is giving the expected respone.

What could go wrong with this above Httpclient code?

The OKhttp library is also working fine as

OkHttpClient client = new OkHttpClient();
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
//            .addPart(
//                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
//                    RequestBody.create(null, "test"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"test\""),
                    RequestBody.create(MEDIA_TYPE_TXT, new File("test.txt")))
//            .addFormDataPart("file","file.txt",
//                    RequestBody.create(MediaType.parse("application/octet-stream"),new File("test.txt"))
//                    )
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Bearer " + accessToken)
            .url("https://transport-stg.transperfect.com/api/files/upload?filename=basic.txt&targetFolderId=2ff5ea6a-8187-4622-ab58-c7511c445ae7")
            .post(requestBody)
            .header("Content-Type","multipart/form-data")
            .build();
try {
  Response response = client.newCall(request).execute();

What could go wrong in the HttpClient code?

Body:
HttpUriRequest request = RequestBuilder.post("https://transport-stg.transperfect.com/api/files/upload")
      .addHeader("Content-Type","multipart/form-data")

The Content-Type value in your code is invalid as it does not include the boundary parameter.

You should not meddle with Content-Type header at the request level and let HttpClient generate it automatically based on properties of the enclosed request entity.


问:
Can't use either View() or edit() functions, getting "Error in .External2(C_dataviewer, x, title) : invalid device" error message
I'm running R through the Terminal in a Mac OSX Snow Leopard system.

I get this error message when trying to use View():

Error in .External2(C_dataviewer, x, title) : invalid device In
  addition: Warning messages: 1: In View(a) :   locale not supported by
  Xlib: some X ops will operate in C locale 2: In View(a) : X cannot set
  locale modifiers 3: In View(a) :   unable to create fontset
  --fixed-medium-r----120------

And this error message when trying to use edit():

Error in .External2(C_dataentry, datalist, modes) : invalid device In
  addition: Warning messages: 1: In edit.data.frame(a) :   locale not
  supported by Xlib: some X ops will operate in C locale 2: In
  edit.data.frame(a) : X cannot set locale modifiers 3: In
  edit.data.frame(a) :   unable to create fontset
  --fixed-medium-r----120------

I can't find information about this particular problem. What can I do to fix this?

sessionInfo() returns:

```<code>R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] C/UTF-8/C/C/C/C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base
</code>```

答:
I had the same error in RStudio. I'm not certain if this would be the same for using R via the Terminal, but for RStudio users who get this message using the jagsUI package masks the View function which triggers this warning. See this question

Easiest workaround seems to be to call detach("package:jagsUI", unload = TRUE) once you have finished using JAGS.

Check potential conflicts between functions by calling conflicts(detail=TRUE) (Taken from this answer for finding which functions are masked in R).

Body:
I'm running R through the Terminal in a Mac OSX Snow Leopard system.

I get this error message when trying to use View():

Error in .External2(C_dataviewer, x, title) : invalid device In
  addition: Warning messages: 1: In View(a) :   locale not supported by
  Xlib: some X ops will operate in C locale 2: In View(a) : X cannot set
  locale modifiers 3: In View(a) :   unable to create fontset
  --fixed-medium-r----120------

And this error message when trying to use edit():

Error in .External2(C_dataentry, datalist, modes) : invalid device In
  addition: Warning messages: 1: In edit.data.frame(a) :   locale not
  supported by Xlib: some X ops will operate in C locale 2: In
  edit.data.frame(a) : X cannot set locale modifiers 3: In
  edit.data.frame(a) :   unable to create fontset
  --fixed-medium-r----120------

I can't find information about this particular problem. What can I do to fix this?

sessionInfo() returns:

R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] C/UTF-8/C/C/C/C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base


问:
How to loop through a list where data points are dependent on each other?
I have a list, a = [5, 4, 9, 3, 6, 6, 8, 2], and I essentially want to sum the first three numbers, and that sum will be the first value in the new list. The next value in the new list will be the sum of 4, 9, and 3...etc. etc. How to loop this in Python?</p>

答:
list slicing is a good method.

all you need to do is travese from start index to end index-2 , ( can make sum of last 3 element and when you reach second last or last ement you wont be able to take 3 elemnts)

here you can take 3 elemnts and using list slicing, slice list from the
current index to next 3 index ie a[i:i+3]  where [i,i+3) is range. then on that new list performing sum operation and appending the reuslt to final list.

```<code>a = [5, 4, 9, 3, 6, 6, 8, 2]
res=[]
for i in range(len(a)-2):
    res.append(sum(a[i:i+3]))

print(res)
</code>```

output

```<code>[18, 16, 18, 15, 20, 16]
</code>```

Body:
list slicing is a good method.

all you need to do is travese from start index to end index-2 , ( can make sum of last 3 element and when you reach second last or last ement you wont be able to take 3 elemnts)

here you can take 3 elemnts and using list slicing, slice list from the
current index to next 3 index ie a[i:i+3]  where [i,i+3) is range. then on that new list performing sum operation and appending the reuslt to final list.

a = [5, 4, 9, 3, 6, 6, 8, 2]
res=[]
for i in range(len(a)-2):
    res.append(sum(a[i:i+3]))

print(res)

output

[18, 16, 18, 15, 20, 16]


问:
How to use array filter criteria agaist object in lodash?
How to filter object ageist another object in lodash? but the criteria object is array..

```<code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);
</code>```

The results should be xyz and abc:

```<code>results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]
</code>```

Is it something I can do using filter method?

答:
Well, you can use custom filter method with lodash. Try below:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

let filtered = _.filter(items, (item)=>{
    return form.type.indexOf(item.type) >= 0 && form.name == item.name
});

console.log(filtered);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

Body:
How to filter object ageist another object in lodash? but the criteria object is array..

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);

The results should be xyz and abc:

results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]

Is it something I can do using filter method?

Body:
Well, you can use custom filter method with lodash. Try below:

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

let filtered = _.filter(items, (item)=>{
    return form.type.indexOf(item.type) >= 0 && form.name == item.name
});

console.log(filtered);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


问:
Insert value referencing another field
After creating a table like this:

```<code>CREATE TABLE T1 (
    C1 INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) PRIMARY KEY,
    C2 INTEGER);
</code>```

I would like to insert in C2 the same value of C1:

```<code>INSERT INTO T1(C1, C2) VALUES (DEFAULT, C1)
</code>```

I could only do something that resembles this by introducing a sequence, is there a more straightforward way?

答:
If the C2 value is not going to be changed, you can declare it as a GENERATED column.

```<code>CREATE TABLE T1 (
C1 INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) PRIMARY KEY,
C2 INTEGER GENERATED ALWAYS AS (C1));
</code>```

Inserts are done with DEFAULT values.

```<code>INSERT INTO T1 VALUES DEFAULT, DEFAULT
</code>```

Title: Insert value referencing another field

Body:
After creating a table like this:

CREATE TABLE T1 (
    C1 INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) PRIMARY KEY,
    C2 INTEGER);

I would like to insert in C2 the same value of C1:

INSERT INTO T1(C1, C2) VALUES (DEFAULT, C1)

I could only do something that resembles this by introducing a sequence, is there a more straightforward way?

Body:
If the C2 value is not going to be changed, you can declare it as a GENERATED column.

CREATE TABLE T1 (
C1 INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) PRIMARY KEY,
C2 INTEGER GENERATED ALWAYS AS (C1));

Inserts are done with DEFAULT values.

INSERT INTO T1 VALUES DEFAULT, DEFAULT