问:
How to check for nil on a Realm Results array value
I'm trying to figure out why I cannot check for nil on the following function call:

```<code>var allExercises : Results<Exercises>?
var exerciseIndex : Int = 0

        @objc func goToNextExercise(){

            if allExercises?[exerciseIndex] != nil {
                print("Does not equal nil")
                exerciseIndex += 1
            } else {
                print("Does equal nil")
            }

        }
</code>```

When allExercises?[exerciseIndex] does equal nil, the application crashes and I get an "indexPath out of Range" error:

```<code>*** Terminating app due to uncaught exception 'RLMException', reason: 'Index 3 is out of bounds (must be less than 3).'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000104a7127e __exceptionPreprocess + 350
    1   libobjc.A.dylib                     0x00000001048deb20 objc_exception_throw + 48
    2   SectionRowsTutorial                 0x00000001025d7aae _Z20RLMThrowResultsErrorP8NSString + 670
    3   SectionRowsTutorial                 0x00000001025d8cc6 _ZL25translateRLMResultsErrorsIZ28-[RLMResults objectAtIndex:]E3$_6EDaOT_P8NSString + 118
    4   SectionRowsTutorial                 0x00000001025d8bf4 -[RLMResults objectAtIndex:] + 100
    5   SectionRowsTutorial                 0x000000010278c9dc $s10RealmSwift7ResultsVyxSicig + 236
    6   SectionRowsTutorial                 0x00000001022dc576 $s19SectionRowsTutorial19ThirdViewControllerC16goToNextExerciseyyF + 246
    7   SectionRowsTutorial                 0x00000001022dc87b $s19SectionRowsTutorial19ThirdViewControllerC16goToNextExerciseyyFTo + 43
    8   UIKitCore                           0x0000000108571fff -[UIApplication sendAction:to:from:forEvent:] + 83
    9   UIKitCore                           0x0000000107f4a00e -[UIControl sendAction:to:forEvent:] + 223
    10  UIKitCore                           0x0000000107f4a358 -[UIControl _sendActionsForEvents:withEvent:] + 398
    11  UIKitCore                           0x0000000107f492b7 -[UIControl touchesEnded:withEvent:] + 481
    12  UIKitCore                           0x00000001085acbbf -[UIWindow _sendTouchesForEvent:] + 2604
    13  UIKitCore                           0x00000001085ae4c6 -[UIWindow sendEvent:] + 4596
    14  UIKitCore                           0x000000010858953b -[UIApplication sendEvent:] + 356
    15  UIKitCore                           0x000000010860a71a __dispatchPreprocessedEventFromEventQueue + 6847
    16  UIKitCore                           0x000000010860d1e0 __handleEventQueueInternal + 5980
    17  CoreFoundation                      0x00000001049d4471 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    18  CoreFoundation                      0x00000001049d439c __CFRunLoopDoSource0 + 76
    19  CoreFoundation                      0x00000001049d3b74 __CFRunLoopDoSources0 + 180
    20  CoreFoundation                      0x00000001049ce87f __CFRunLoopRun + 1263
    21  CoreFoundation                      0x00000001049ce066 CFRunLoopRunSpecific + 438
    22  GraphicsServices                    0x000000010e756bb0 GSEventRunModal + 65
    23  UIKitCore                           0x0000000108570d4d UIApplicationMain + 1621
    24  SectionRowsTutorial                 0x00000001022e759b main + 75
    25  libdyld.dylib                       0x0000000105ba4c25 start + 1
    26  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

答:
You are checking the value of allExercises, if you pass a greater index than the array size, it's crashing. for check, you should first check if exerciseIndex is less than allExercises count - 1 and then check data

if  exerciseIndex <= allExercises.count - 1

```

Body:
I'm trying to figure out why I cannot check for nil on the following function call:

var allExercises : Results<Exercises>?
var exerciseIndex : Int = 0

        @objc func goToNextExercise(){

            if allExercises?[exerciseIndex] != nil {
                print("Does not equal nil")
                exerciseIndex += 1
            } else {
                print("Does equal nil")
            }

        }

When allExercises?[exerciseIndex] does equal nil, the application crashes and I get an "indexPath out of Range" error:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Index 3 is out of bounds (must be less than 3).'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000104a7127e __exceptionPreprocess + 350
    1   libobjc.A.dylib                     0x00000001048deb20 objc_exception_throw + 48
    2   SectionRowsTutorial                 0x00000001025d7aae _Z20RLMThrowResultsErrorP8NSString + 670
    3   SectionRowsTutorial                 0x00000001025d8cc6 _ZL25translateRLMResultsErrorsIZ28-[RLMResults objectAtIndex:]E3$_6EDaOT_P8NSString + 118
    4   SectionRowsTutorial                 0x00000001025d8bf4 -[RLMResults objectAtIndex:] + 100
    5   SectionRowsTutorial                 0x000000010278c9dc $s10RealmSwift7ResultsVyxSicig + 236
    6   SectionRowsTutorial                 0x00000001022dc576 $s19SectionRowsTutorial19ThirdViewControllerC16goToNextExerciseyyF + 246
    7   SectionRowsTutorial                 0x00000001022dc87b $s19SectionRowsTutorial19ThirdViewControllerC16goToNextExerciseyyFTo + 43
    8   UIKitCore                           0x0000000108571fff -[UIApplication sendAction:to:from:forEvent:] + 83
    9   UIKitCore                           0x0000000107f4a00e -[UIControl sendAction:to:forEvent:] + 223
    10  UIKitCore                           0x0000000107f4a358 -[UIControl _sendActionsForEvents:withEvent:] + 398
    11  UIKitCore                           0x0000000107f492b7 -[UIControl touchesEnded:withEvent:] + 481
    12  UIKitCore                           0x00000001085acbbf -[UIWindow _sendTouchesForEvent:] + 2604
    13  UIKitCore                           0x00000001085ae4c6 -[UIWindow sendEvent:] + 4596
    14  UIKitCore                           0x000000010858953b -[UIApplication sendEvent:] + 356
    15  UIKitCore                           0x000000010860a71a __dispatchPreprocessedEventFromEventQueue + 6847
    16  UIKitCore                           0x000000010860d1e0 __handleEventQueueInternal + 5980
    17  CoreFoundation                      0x00000001049d4471 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    18  CoreFoundation                      0x00000001049d439c __CFRunLoopDoSource0 + 76
    19  CoreFoundation                      0x00000001049d3b74 __CFRunLoopDoSources0 + 180
    20  CoreFoundation                      0x00000001049ce87f __CFRunLoopRun + 1263
    21  CoreFoundation                      0x00000001049ce066 CFRunLoopRunSpecific + 438
    22  GraphicsServices                    0x000000010e756bb0 GSEventRunModal + 65
    23  UIKitCore                           0x0000000108570d4d UIApplicationMain + 1621
    24  SectionRowsTutorial                 0x00000001022e759b main + 75
    25  libdyld.dylib                       0x0000000105ba4c25 start + 1
    26  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException


来源: stackexchange

问:
SQL Server machine learning services r version 3.5
According to this link, SQL Server machine learning service's highest R version is 3.3. Does anyone know when one can upgrade to version 3.5 or later?

Or is my only option to switch to sql server 2019?

Thanks.

答:
Well cs0815, let's take a look.

According to your post, you tagged this with sql-server-2017, so I'll be basing this on that version.

After reading through your link and this one, I was thinking there might be two options:

Hack a new version of R into the R-Services module of SQL server.

Setup an R-Client with version 3.5

However, it looks like R-Client is for a different use case than you might need so we'll focus on an attempt to replace R in R-Services with a higher version directly.

After installing a new instance of 2017 with the following features:

R Services natively installs to:

```<code>"C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\R_SERVICES"
</code>```

Using WinDiff, I pulled the following comparisons vs CRAN R 3.5.3 and Microsoft Open R 3.5.3 and not surprisingly the Microsoft Open R is much closer.

Full diffs:
R_Services vs CRAN R
R_Services vs MS OPEN R

Personally, I'm not at the level to understand all the differences in R Core / runtime between R 3.3 (R_Services) and R 3.5.3 so of main interest to me is the library diff.

What exists in R_Services which does not in Open R is what I'm assuming to be the core of what makes R_Services work with SQL Server so that will be where we need to fill in those gaps with our "replacement" R_Services but with v3.5.3.

Libraries which are completely missing - not just added docs or some small difference:

compatibilityapi

dorsr

microsoftml

mrsdeploy

olapr

revopemar

revoscaler

revotreeview

sqlrutils

And that information leads to us to the Microsoft MLS Docs "R Packages" resource:

https://learn.microsoft.com/en-us/machine-learning-server/r-reference/introducing-r-server-r-package-reference

Which, no, it looks like those packages are not publicly available through MRAN, CRAN, or even directly via devtools from github.

Still, searching brought me onto this possibility:
https://learn.microsoft.com/en-us/sql/advanced-analytics/install/upgrade-r-and-python?view=sql-server-2017#offline-binding-no-internet-access

Download after signing up with Visual Studio Dev Services:
https://learn.microsoft.com/en-us/machine-learning-server/install/machine-learning-server-windows-install#download-machine-learning-server-installer

So - binding this version of MLS to our existing instance:

After that installation is fully complete, let's check and see what's available on our server!

So first things first, this being a new instance of SQL Server - Set to enable external scripts:

```<code>sp_configure 'external scripts enabled', 1;
RECONFIGURE WITH OVERRIDE;
</code>```

And then to bring this soup to nuts:

```<code>EXECUTE sp_execute_external_script @language = N'R'
    , @script = N'
print(R.Version())
';
</code>```

output below:

```<code>$language
[1] "R"

$version.string
[1] "R version 3.5.2 (2018-12-20)"

$nickname
[1] "Eggshell Igloo"
</code>```

TLDR: Yes - download the MLS 9.4.7 packages from Visual Studio Dev Services and install on server host.

ContentLicense: CC BY-SA 4.0

Body:
Well cs0815, let's take a look.

According to your post, you tagged this with sql-server-2017, so I'll be basing this on that version.

After reading through your link and this one, I was thinking there might be two options:

Hack a new version of R into the R-Services module of SQL server.

Setup an R-Client with version 3.5

However, it looks like R-Client is for a different use case than you might need so we'll focus on an attempt to replace R in R-Services with a higher version directly.

After installing a new instance of 2017 with the following features:

R Services natively installs to:

"C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\R_SERVICES"

Using WinDiff, I pulled the following comparisons vs CRAN R 3.5.3 and Microsoft Open R 3.5.3 and not surprisingly the Microsoft Open R is much closer.

Full diffs:
R_Services vs CRAN R
R_Services vs MS OPEN R

Personally, I'm not at the level to understand all the differences in R Core / runtime between R 3.3 (R_Services) and R 3.5.3 so of main interest to me is the library diff.

What exists in R_Services which does not in Open R is what I'm assuming to be the core of what makes R_Services work with SQL Server so that will be where we need to fill in those gaps with our "replacement" R_Services but with v3.5.3.

Libraries which are completely missing - not just added docs or some small difference:

compatibilityapi

dorsr

microsoftml

mrsdeploy

olapr

revopemar

revoscaler

revotreeview

sqlrutils

And that information leads to us to the Microsoft MLS Docs "R Packages" resource:

https://learn.microsoft.com/en-us/machine-learning-server/r-reference/introducing-r-server-r-package-reference

Which, no, it looks like those packages are not publicly available through MRAN, CRAN, or even directly via devtools from github.

Still, searching brought me onto this possibility:
https://learn.microsoft.com/en-us/sql/advanced-analytics/install/upgrade-r-and-python?view=sql-server-2017#offline-binding-no-internet-access

Download after signing up with Visual Studio Dev Services:
https://learn.microsoft.com/en-us/machine-learning-server/install/machine-learning-server-windows-install#download-machine-learning-server-installer

So - binding this version of MLS to our existing instance:

After that installation is fully complete, let's check and see what's available on our server!

So first things first, this being a new instance of SQL Server - Set to enable external scripts:

sp_configure 'external scripts enabled', 1;
RECONFIGURE WITH OVERRIDE;

And then to bring this soup to nuts:

EXECUTE sp_execute_external_script @language = N'R'
    , @script = N'
print(R.Version())
';

output below:

$language
[1] "R"

$version.string
[1] "R version 3.5.2 (2018-12-20)"

$nickname
[1] "Eggshell Igloo"

TLDR: Yes - download the MLS 9.4.7 packages from Visual Studio Dev Services and install on server host.


问:
Google Sheets Regexreplace - remove numbers, double quotes, "X" and "x" from strings
I have a listing of products that include sizes, in a variety of formats.
I need to separate them into 2 columns, 1 with the sizes, the other with the names.
So, for example, "12"x10" Large Widget" becomes [12" x 10"] [Large Widget].

I'm trying to use REGEXREPLACE to remove the numbers, but can't seem to find a combined syntax that will handle "any number, double quotes, the letter X lowercase and capital" in a single expression.

And then I'd need to do the reverse, in other words, extract JUST the numbers and double quotes and X/x, for the other column.

Can't just use SPLIT or RIGHT/LEFT, because the position of the intended split will differ from line to line. Can't "Split Text To Columns", because there are occasional double quotes in the item names too.

So I'm thinking, Step 1: filter out just the numbers and double quotes, Step 2: filter out just the names.

In other words:

```<code>Input: [14" x 17" Large Widget]
Output (2 columns): [14" x 17"] [Large Widget]

Input: [7"x2" Small Gadget]
Output (2 columns): [7"x2"] [Small Gadget]
</code>```

I understand how REGEXREPLACE works, just need help with the syntax.

Thanks in advance!

答:
try:

```<code>=ARRAYFORMULA(IFNA(REGEXEXTRACT(A1:A, "(.+"") (.+)")))
</code>```

Body:
I have a listing of products that include sizes, in a variety of formats.
I need to separate them into 2 columns, 1 with the sizes, the other with the names.
So, for example, "12"x10" Large Widget" becomes [12" x 10"] [Large Widget].

I'm trying to use REGEXREPLACE to remove the numbers, but can't seem to find a combined syntax that will handle "any number, double quotes, the letter X lowercase and capital" in a single expression.

And then I'd need to do the reverse, in other words, extract JUST the numbers and double quotes and X/x, for the other column.

Can't just use SPLIT or RIGHT/LEFT, because the position of the intended split will differ from line to line. Can't "Split Text To Columns", because there are occasional double quotes in the item names too.

So I'm thinking, Step 1: filter out just the numbers and double quotes, Step 2: filter out just the names.

In other words:

Input: [14" x 17" Large Widget]
Output (2 columns): [14" x 17"] [Large Widget]

Input: [7"x2" Small Gadget]
Output (2 columns): [7"x2"] [Small Gadget]

I understand how REGEXREPLACE works, just need help with the syntax.

Thanks in advance!

Body:
try:

=ARRAYFORMULA(IFNA(REGEXEXTRACT(A1:A, "(.+"") (.+)")))


问:
How do I detect an aborted connection in Django?
I have a Django view that does some pretty heavy processing and takes around 20-30 seconds to return a result.

Sometimes the user will end up closing the browser window (terminating the connection) before the request completes -- in that case, I'd like to be able to detect this and stop working.  The work I do is read-only on the database so there isn't any issue with transactions.

In PHP the connection_aborted function does exactly this.  Is this functionality available in Django?

Here's example code I'd like to write:

```<code>def myview(request):
    while not connection_aborted():
        # do another bit of work...
        if work_complete:
            return HttpResponse('results go here')
</code>```

Thanks.

答:
So you have an AJAX view that runs a query that takes 20-30 seconds to process requested in the background of a rendered page and you're concerned about wasted resources for when someone cancels the page load.

I see that you've got options in three broad categories:

Live with it. Improve the situation by caching the results in case the user comes back.

Make it faster. Throw more space at a time/space trade-off. Maintain intermediate tables. Precalculate the entire thing, etc.

Do something clever with the browser fast-polling a "is it ready yet?" query and the server cancelling the query if it doesn't receive a nag within interval * 2 or similar. If you're really clever, you could return progress / ETA to the nags. However, this might not have particularly useful behaviour when the system is under load or your site is being accessed over limited bandwidth.

I don't think you should go for option 3 because it's increasing complexity and resource usage for not much gain.

ContentLicense: CC BY-SA 3.0

Body:
I have a Django view that does some pretty heavy processing and takes around 20-30 seconds to return a result.

Sometimes the user will end up closing the browser window (terminating the connection) before the request completes -- in that case, I'd like to be able to detect this and stop working.  The work I do is read-only on the database so there isn't any issue with transactions.

In PHP the connection_aborted function does exactly this.  Is this functionality available in Django?

Here's example code I'd like to write:

def myview(request):
    while not connection_aborted():
        # do another bit of work...
        if work_complete:
            return HttpResponse('results go here')

Thanks.


问:
What are the static ip addresses for SendGrid Incoming Parse WebHook servers?
I have a webserver endpoint for SendGrid Incoming Parse Webhook callback and would like to lock it down to the SendGrid server IP's.

What are the static ip addresses for SendGrid Incoming Parse WebHook servers?

答: I'm not aware of any lookup for those IPs. Additionally Sendgrid could change them at any time which would break your setup. If you are trying to prevent random people and/or bots from messing with your endpoint(s) check out this solution: SendGrid event notification authentication</p>


问:
Using Durable Functions, how to return multiple values from an Activity Functions
I’m a big Domain Driven Design fan and developer, and am always attempting to map technology/architecture into the world of DDD. Mapping microservices to bounded contexts provides for a natural marriage. At the end of the day, I just want to focus on my business logic and host that in the right environment. Durable Functions looked promising to me, in needing to solve the distributed transaction problem across microservices, Sagas or Process Manager if you will. I have been using NServicebus for years, and love their Saga technology, but would like to leverage Durable Function orchestrations for handling saga logic.

The architecture problem that I am currently having is the following. I have mapped the DDD Application Service to an Activity Function. A Saga would therefore be created simply with an Orchestrator tapping the right set of Activity Functions to run their transactions. Building out a rollback is pretty straightforward as well conceptually, but I am having an implementation problem. As an aside, each Activity Function will delegate to a library that handles all the business logic details, and will then take the list of events returned by the business logic and return that back to the Orchestrator. As far as I have researched, there is no way to return a polymorphic return value from an Activity Function. So if my business logic generates either a UpdateSucceeded or a UpdateFailed event, how would I simply return that from my Activity Function back to the Orchestrator so that the Orchestrator can take corrective action by calling distinct rollback Activity Functions?</p>

答: While you may not be able to return a polymorphic result from an Activity, have you considered returning a serialized value that can be deserialized by the Orchestrator and handled accordingly. It's not ideal, but would give you the ability to accomplish the same task. </p>


问:
Find count of each consecutive characters
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

```<code>str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)
</code>```

答:
Here is a LINQ solution:

```<code>var input = "aaaabbccaa";
var result = string.IsNullOrEmpty(input) ? "" : string.Join("",input.Skip(1)
        .Aggregate((t:input[0].ToString(),o:Enumerable.Empty<string>()),
           (a,c)=>a.t[0]==c ? (a.t+c,a.o) : (c.ToString(),a.o.Append(a.t)),
           a=>a.o.Append(a.t).Select(p => $"{p.Length}{p[0]}")));
</code>```

Here is the iterator solution:

```<code>var result = RleString("aaaabbccaa");

private static IEnumerable<(char chr, int count)> Rle(string s)
{
    if (string.IsNullOrEmpty(s)) yield break;

    var lastchar = s.First(); // or s[0]
    var count = 1;
    foreach (char letter in s.Skip(1))
    {
        if (letter != lastchar)
        {
            yield return (lastchar, count);
            lastchar = letter;
            count = 0;
        }
        count++;
    }
    if (count > 0)
        yield return (lastchar, count);
}
private static string RleString(string s)
{
    return String.Join("",Rle(s).Select(z=>$"{z.count}{z.chr}"));
}
</code>```

Body:
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)

Body:
Here is a LINQ solution:

var input = "aaaabbccaa";
var result = string.IsNullOrEmpty(input) ? "" : string.Join("",input.Skip(1)
        .Aggregate((t:input[0].ToString(),o:Enumerable.Empty<string>()),
           (a,c)=>a.t[0]==c ? (a.t+c,a.o) : (c.ToString(),a.o.Append(a.t)),
           a=>a.o.Append(a.t).Select(p => $"{p.Length}{p[0]}")));

Here is the iterator solution:

var result = RleString("aaaabbccaa");

private static IEnumerable<(char chr, int count)> Rle(string s)
{
    if (string.IsNullOrEmpty(s)) yield break;

    var lastchar = s.First(); // or s[0]
    var count = 1;
    foreach (char letter in s.Skip(1))
    {
        if (letter != lastchar)
        {
            yield return (lastchar, count);
            lastchar = letter;
            count = 0;
        }
        count++;
    }
    if (count > 0)
        yield return (lastchar, count);
}
private static string RleString(string s)
{
    return String.Join("",Rle(s).Select(z=>$"{z.count}{z.chr}"));
}


问:
How to get a float value with a string as input parameter in Python?
I wrote the following:

```<code>def payment(order):

B = 2.00
W = 2.50
S = 1.50

order = ["B", "W", "S"]

return(order)

payment('BBSWS')
</code>```

I need to get 9.5 as output, however, my output is ('B', 'W', 'S').

What do I need to change in my code to get the right answer 9.5?

Thank you.

答:
This is a simple task with reduce and a mapping:</p>

```<code>mapping = {'B': 2.00, 'W': 2.50, 'S': 1.50}
payment = lambda order: sum(map(mapping.get, order))

payment('BBSWS')
>>> 9.5
</code>```

Body:
I wrote the following:

def payment(order):

B = 2.00
W = 2.50
S = 1.50

order = ["B", "W", "S"]

return(order)

payment('BBSWS')

I need to get 9.5 as output, however, my output is ('B', 'W', 'S').

What do I need to change in my code to get the right answer 9.5?

Thank you.

Body:
This is a simple task with reduce and a mapping:

mapping = {'B': 2.00, 'W': 2.50, 'S': 1.50}
payment = lambda order: sum(map(mapping.get, order))

payment('BBSWS')
>>> 9.5


问:
how to make animation inactive for some time period in jQuery
here the jsfiddle link to my problem http://jsfiddle.net/XnnvD/35/ (not quite working)

I'll try explaining what the problem is, I have 3 sets of animation in jQuery

1- Image bounces and fades away after  some TimePeriod as below:

```<code>$('#homePageImage').animate(
                    { top: '50px' },
                    { queue: false, duration: 1000, easing: 'easeOutBounce' });
$('#homePageImage').delay(3000).effect('drop', { direction: "right" });
</code>```

2- Set of images .fadeIn() randomly as below:

```<code>randNumArray = shuffle(randNumArray);
for (var i = 0; i < 9; i++)
{ $('#fs' + randNumArray[i]).delay(j += 200).fadeIn(j); }
</code>```

3- Hovering over these images, will enlarge them as below:

```<code>$(function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        });
</code>```

The Problem:
If the user hovers before the 1st set of animation is complete, the images don't .fadeIn() completely, and hence are partially/not visible

What I want:
I want the 3rd set (hovering to enlarge) to remain inactive till my 1st and 2nd set of animations are complete, how can I do this?

Thanks

答:
Could you try calling the hover function as a callback function on the back of the second animation. In basic terms:</p>

```<code>$("#homePageImage").fadeIn("slow", function() {

// enable hover function

});
</code>```

Body:
here the jsfiddle link to my problem http://jsfiddle.net/XnnvD/35/ (not quite working)

I'll try explaining what the problem is, I have 3 sets of animation in jQuery

1- Image bounces and fades away after  some TimePeriod as below:

$('#homePageImage').animate(
                    { top: '50px' },
                    { queue: false, duration: 1000, easing: 'easeOutBounce' });
$('#homePageImage').delay(3000).effect('drop', { direction: "right" });

2- Set of images .fadeIn() randomly as below:

randNumArray = shuffle(randNumArray);
for (var i = 0; i < 9; i++)
{ $('#fs' + randNumArray[i]).delay(j += 200).fadeIn(j); }

3- Hovering over these images, will enlarge them as below:

$(function () {
            $("ul.thumb li").hover(function () {
                $(this).css({ 'z-index': '10' });
                $(this).find('img').addClass("hover").stop().animate({
                    marginTop: '-110px',
                    marginLeft: '-110px',
                    top: '50%',
                    left: '50%',
                    width: '174px',
                    height: '174px',
                    padding: '20px'
                }, 500);

            }, function () {
                $(this).css({ 'z-index': '0' });
                $(this).find('img').removeClass("hover").stop().animate({
                    marginTop: '0',
                    marginLeft: '0',
                    top: '0',
                    left: '0',
                    width: '100px',
                    height: '100px',
                    padding: '5px'
                }, 500);
            });
        });

The Problem:
If the user hovers before the 1st set of animation is complete, the images don't .fadeIn() completely, and hence are partially/not visible

What I want:
I want the 3rd set (hovering to enlarge) to remain inactive till my 1st and 2nd set of animations are complete, how can I do this?

Thanks

Body:
Could you try calling the hover function as a callback function on the back of the second animation. In basic terms:

$("#homePageImage").fadeIn("slow", function() {

// enable hover function

});


问:
Decompressed error: Error Domain=NSOSStatusErrorDomain Code=-12909
I am using H264 algorithm below is the link which I am referring to decompress video using VideoToolbox framework

https://stackoverflow.com/a/29525001/1679255

Not all a few videos are stuck in a specific position.

Below is the error logs which i am recieving during the decompressing the frame.

```<code>NALU Raw: 00, 00, 00, 01, 41, 9a, 00, 18
~~~~~~~ Received NALU Type "1: Coded slice of a non-IDR picture (VCL)" ~~~~~~~~
Decompressed error: Error Domain=NSOSStatusErrorDomain Code=-12909 "(null)"
</code>```

Xocde version is 11.2.1

Development Target is 10.0

If you need more info feel free to ask me.

My VideoDecoder Class Code is below :

```@interface VideoDecoder () {
    AVSampleBufferDisplayLayer *mVideoLayer;
    long videoTimestamp;
}
@property (nonatomic, assign) CMVideoFormatDescriptionRef formatDesc;
@property (nonatomic, assign) VTDecompressionSessionRef decompressionSession;
@property (nonatomic, assign) int spsSize;
@property (nonatomic, assign) int ppsSize;
@property (nonatomic, retain) NSMutableData* streamVideoData;
@end

@implementation VideoDecoder

NSString * const naluTypesStrings[] = {
    @"0: Unspecified (non-VCL)",
    @"1: Coded slice of a non-IDR picture (VCL)", // P frame
    @"2: Coded slice data partition A (VCL)",
    @"3: Coded slice data partition B (VCL)",
    @"4: Coded slice data partition C (VCL)",
    @"5: Coded slice of an IDR picture (VCL)", // I frame
    @"6: Supplemental enhancement information (SEI) (non-VCL)",
    @"7: Sequence parameter set (non-VCL)", // SPS parameter
    @"8: Picture parameter set (non-VCL)", // PPS parameter
    @"9: Access unit delimiter (non-VCL)",
    @"10: End of sequence (non-VCL)",
    @"11: End of stream (non-VCL)",
    @"12: Filler data (non-VCL)",
    @"13: Sequence parameter set extension (non-VCL)",
    @"14: Prefix NAL unit (non-VCL)",
    @"15: Subset sequence parameter set (non-VCL)",
    @"16: Reserved (non-VCL)",
    @"17: Reserved (non-VCL)",
    @"18: Reserved (non-VCL)",
    @"19: Coded slice of an auxiliary coded picture without partitioning (non-VCL)",
    @"20: Coded slice extension (non-VCL)",
    @"21: Coded slice extension for depth view components (non-VCL)",
    @"22: Reserved (non-VCL)",
    @"23: Reserved (non-VCL)",
    @"24: STAP-A Single-time aggregation packet (non-VCL)",
    @"25: STAP-B Single-time aggregation packet (non-VCL)",
    @"26: MTAP16 Multi-time aggregation packet (non-VCL)",
    @"27: MTAP24 Multi-time aggregation packet (non-VCL)",
    @"28: FU-A Fragmentation unit (non-VCL)",
    @"29: FU-B Fragmentation unit (non-VCL)",
    @"30: Unspecified (non-VCL)",
    @"31: Unspecified (non-VCL)",
};

- (instancetype)init {
    self = [super init];
    if (self) {
//        _videoLayer = [[AVSampleBufferDisplayLayer alloc] init];
////        _videoLayer.frame = self.view.frame;
////        _videoLayer.bounds = self.view.bounds;
//        _videoLayer.frame = CGRectMake(0, 0, 1280, 720);
//        _videoLayer.bounds = CGRectMake(0, 0, 1280, 720);
//        _videoLayer.videoGravity = AVLayerVideoGravityResizeAspect;
//
//        // set Timebase, you may need this if you need to display frames at specific times
//        // I didn't need it so I haven't verified that the timebase is working
//        CMTimebaseRef controlTimebase;
//        CMTimebaseCreateWithMasterClock(CFAllocatorGetDefault(), CMClockGetHostTimeClock(), &controlTimebase);
//
//        //videoLayer.controlTimebase = controlTimebase;
//        CMTimebaseSetTime(_videoLayer.controlTimebase, kCMTimeZero);
//        CMTimebaseSetRate(_videoLayer.controlTimebase, 1.0);

        self.streamVideoData = nil;
        self.startDumpData = NO;
        videoTimestamp = 0;
    }
    return self;
}

- (void)initDebugStreamingVideo
{
    self.streamVideoData = [[NSMutableData alloc] init];
}

- (void)releaseVideoDecorder
{
    if (_decompressionSession != NULL)
    {
        VTDecompressionSessionInvalidate(_decompressionSession);
        _decompressionSession = NULL;
    }

    videoTimestamp = 0;
}

- (long)getVideoTimeStamp
{
    return videoTimestamp;
}

- (void)setVideoTimestamp:(long)timestamp
{
    videoTimestamp = timestamp;

#ifdef DEBUG
    NSLog(@"(sync)video: %2.1f", (float)videoTimestamp/1000000.);
#endif
}

- (NSString*)getLiveStreamingMP4Path
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *rootOfCachepath = [paths objectAtIndex:0];
    NSString* nalFilePath = [self getUniqueFilePath:rootOfCachepath FileNamePrefix:@"liveRecord" FileNameSubfix:@"MP4"];

    return nalFilePath;
}

- (NSString*)closeAndSaveDebugStreamingVideo
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *rootOfCachepath = [paths objectAtIndex:0];
    NSString* nalFilePath = [self getUniqueFilePath:rootOfCachepath FileNamePrefix:@"liveRecord" FileNameSubfix:@"264"];

    if (self.streamVideoData.length > 0)
        [self.streamVideoData writeToFile:nalFilePath atomically:YES];

    self.streamVideoData = [[NSMutableData alloc] init];

    return nalFilePath;
}

- (NSString*)getUniqueFilePath:(NSString*)parentFolder FileNamePrefix:(NSString*)fileName FileNameSubfix:(NSString*)subFix
{
    NSString* fullFilePath = nil;
    NSString* memoFileName = @"";

    NSDate *currentDate = [NSDate date];
    NSDateFormatter *currentDateFormat = [[NSDateFormatter alloc] init];
    [currentDateFormat setDateFormat:@"yyyyMMddHHmmss"];
    NSString *currentDateString = [currentDateFormat stringFromDate:currentDate];

    memoFileName = [NSString stringWithFormat:@"%@_%@.%@", fileName, currentDateString, subFix];

    fullFilePath = [parentFolder stringByAppendingPathComponent:memoFileName];

    return fullFilePath;
}

//- (void)setVideoLayer:(AVSampleBufferDisplayLayer *)layer {
//    mVideoLayer = layer;
//    CMTimebaseRef controlTimebase;
//    CMTimebaseCreateWithMasterClock(CFAllocatorGetDefault(), CMClockGetHostTimeClock(), &controlTimebase);
//
//    mVideoLayer.controlTimebase = controlTimebase;
//    CMTimebaseSetTime(mVideoLayer.controlTimebase, kCMTimeZero);
//    CMTimebaseSetRate(mVideoLayer.controlTimebase, 1.0);
//}

- (BOOL)checkIfThisIsIDRFrame:(uint8_t *)frame withSize:(uint32_t)frameSize {

    BOOL isIDRFrame = NO;
    int startCodeIndex = 0;

    int pi = 0;
    if (frame[pi] == 0x00 && frame[pi+1] == 0x00 && frame[pi+2] == 0x00 && frame[pi+3] == 0x01 && frame[pi+4] == 0x09 && frame[pi+5] == 0x50)
        startCodeIndex = 6;

//    NSLog(@"NALU Raw: %02X, %02x, %02x, %02x, %02X, %02x, %02x, %02x", frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7]);
    int nalu_type = (frame[startCodeIndex + 4] & 0x1F);
//    NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

    // if we havent already set up our format description with our SPS PPS parameters, we
    // can't process any frames except type 7 that has our parameters
    if (nalu_type != 7 && _formatDesc == NULL) {
        NSLog(@"Video error: Frame is not an I Frame and format description is null");
        return isIDRFrame;
    }

    // NALU type 7 is the SPS parameter NALU
    if (nalu_type == 7) {
        isIDRFrame = YES;
    }

    return isIDRFrame;
}

- (void)receivedRawVideoFrame:(uint8_t *)frame withSize:(uint32_t)frameSize {
    OSStatus status = 0;

    uint8_t *data = NULL;
    uint8_t *pps = NULL;
    uint8_t *sps = NULL;

#if defined(DEBUG) || defined(_RECORD_USE_LIVE_PACKAGE)
    if (self.startDumpData && self.streamVideoData && frameSize <= 512*1024)
        [self.streamVideoData appendBytes:(const void*)frame length:frameSize];
    //if (self.streamVideoData && frameSize <= 512*1024)
    //    [self.streamVideoData appendBytes:(const void*)frame length:frameSize];
#endif

    // I know how my H.264 data source's NALUs looks like so I know start code index is always 0.
    // if you don't know where it starts, you can use a for loop similar to how I find the 2nd and 3rd start codes
    int startCodeIndex = 0;
    int secondStartCodeIndex = 0;
    int thirdStartCodeIndex = 0;

//#ifdef DEBUG
    int pi = 0;
    if (frame[pi] == 0x00 && frame[pi+1] == 0x00 && frame[pi+2] == 0x00 && frame[pi+3] == 0x01 && frame[pi+4] == 0x09 && frame[pi+5] == 0x50)
        startCodeIndex = 6;
//#endif

    long blockLength = 0;
    BOOL withSPSPPS = NO;

    CMSampleBufferRef sampleBuffer = NULL;
    CMBlockBufferRef blockBuffer = NULL;

    NSLog(@"NALU Raw: %02X, %02x, %02x, %02x, %02X, %02x, %02x, %02x", frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7]);
    int nalu_type = (frame[startCodeIndex + 4] & 0x1F);
    NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

    // if we havent already set up our format description with our SPS PPS parameters, we
    // can't process any frames except type 7 that has our parameters
    if (nalu_type != 7 && _formatDesc == NULL) {
        NSLog(@"Video error: Frame is not an I Frame and format description is null");
        return;
    }

    // NALU type 7 is the SPS parameter NALU
    if (nalu_type == 7) {
        // find where the second PPS start code begins, (the 0x00 00 00 01 code)
        // from which we also get the length of the first SPS code
        for (int i = startCodeIndex + 4; i < startCodeIndex + 40; i++) {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x00 && frame[i+3] == 0x01) {
                secondStartCodeIndex = i;
                //_spsSize = secondStartCodeIndex;   // includes the header in the size
//#ifdef DEBUG
                _spsSize = secondStartCodeIndex - startCodeIndex;   // includes the header in the size
//#endif

                break;
            }
        }

        // find what the second NALU type is
        nalu_type = (frame[secondStartCodeIndex + 4] & 0x1F);
//        NSLog(@"~~~n7~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);
    }

    // type 8 is the PPS parameter NALU
    if(nalu_type == 8) {

        // find where the NALU after this one starts so we know how long the PPS parameter is
//#ifdef DEBUG
        for (int i = _spsSize + 4 + startCodeIndex; i < _spsSize + 30; i++) {
//#endif
        //for (int i = _spsSize + 4; i < _spsSize + 30; i++) {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x00 && frame[i+3] == 0x01) {
                thirdStartCodeIndex = i;
                //_ppsSize = thirdStartCodeIndex - _spsSize;
//#ifdef DEBUG
                _ppsSize = thirdStartCodeIndex - _spsSize - startCodeIndex;
//#endif
                break;
            }
        }

        // allocate enough data to fit the SPS and PPS parameters into our data objects.
        // VTD doesn't want you to include the start code header (4 bytes long) so we add the - 4 here
        sps = malloc(_spsSize - 4);
        pps = malloc(_ppsSize - 4);

        // copy in the actual sps and pps values, again ignoring the 4 byte header
//#ifdef DEBUG
        memcpy (sps, &frame[4+startCodeIndex], _spsSize-4);
        memcpy (pps, &frame[_spsSize+4+startCodeIndex], _ppsSize-4);
        NSLog(@"SPS Raw: %02X, %02x, %02x, %02x, %02X, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x", sps[0],sps[1],sps[2],sps[3],sps[4],sps[5],sps[6],sps[7],sps[8],sps[9],sps[10],sps[11],sps[12],sps[13],sps[14],sps[15]);
        NSLog(@"PPS Raw: %02X, %02x, %02x, %02x", pps[0],pps[1],pps[2],pps[3]);
//#endif
//        memcpy (sps, &frame[4], _spsSize-4);
//        memcpy (pps, &frame[_spsSize+4], _ppsSize-4);

        // now we set our H264 parameters
        uint8_t*  parameterSetPointers[2] = {sps, pps};
        size_t parameterSetSizes[2] = {_spsSize-4, _ppsSize-4};

        status = CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault, 2,
                                                                     (const uint8_t *const*)parameterSetPointers,
                                                                     parameterSetSizes, 4,
                                                                     &_formatDesc);

//        NSLog(@"\t\t Creation of CMVideoFormatDescription: %@", (status == noErr) ? @"successful!" : @"failed...");
        if(status != noErr)
            NSLog(@"\t\t Format Description ERROR type: %d", (int)status);

        // See if decomp session can convert from previous format description
        // to the new one, if not we need to remake the decomp session.
        // This snippet was not necessary for my applications but it could be for yours
        /*BOOL needNewDecompSession = (VTDecompressionSessionCanAcceptFormatDescription(_decompressionSession, _formatDesc) == NO);
         if(needNewDecompSession)
         {
         [self createDecompSession];
         }*/

        // now lets handle the IDR frame that (should) come after the parameter sets
        // I say "should" because that's how I expect my H264 stream to work, YMMV
        nalu_type = (frame[thirdStartCodeIndex + 4] & 0x1F);
//        NSLog(@"~~~n8~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

        withSPSPPS = YES;
    }

    // create our VTDecompressionSession.  This isnt neccessary if you choose to use AVSampleBufferDisplayLayer
    //
    if (videoTimestamp == 0 && _decompressionSession != NULL)
    {
        if (_decompressionSession != NULL)
        {
            VTDecompressionSessionInvalidate(_decompressionSession);
            _decompressionSession = NULL;
        }
    }
    if ((status == noErr) && (_decompressionSession == NULL)) {
        [self createDecompSession];
    }

    // type 5 is an IDR frame NALU.  The SPS and PPS NALUs should always be followed by an IDR (or IFrame) NALU, as far as I know
    if(nalu_type == 5) {
        // find the offset, or where the SPS and PPS NALUs end and the IDR frame NALU begins
//#ifdef DEBUG
        int offset = _spsSize + _ppsSize + startCodeIndex;
        NSLog(@"Start IDR at %d", offset);
//#endif
//        int offset = _spsSize + _ppsSize;
        blockLength = frameSize - offset;
        //        NSLog(@"Block Length : %ld", blockLength);
        data = malloc(blockLength);
        data = memcpy(data, &frame[offset], blockLength);

        // replace the start code header on this NALU with its size.
        // AVCC format requires that you do this.
        // htonl converts the unsigned int from host to network byte order
        uint32_t dataLength32 = htonl (blockLength - 4);
        memcpy (data, &dataLength32, sizeof (uint32_t));

        // create a block buffer from the IDR NALU
        status = CMBlockBufferCreateWithMemoryBlock(NULL, data,  // memoryBlock to hold buffered data
                                                    blockLength,  // block length of the mem block in bytes.
                                                    kCFAllocatorNull, NULL,
                                                    0, // offsetToData
                                                    blockLength,   // dataLength of relevant bytes, starting at offsetToData
                                                    0, &blockBuffer);

//        NSLog(@"\t\t BlockBufferCreation: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");
    }

    // NALU type 1 is non-IDR (or PFrame) picture
    if (nalu_type == 1) {
        // non-IDR frames do not have an offset due to SPS and PSS, so the approach
        // is similar to the IDR frames just without the offset
//#ifdef DEBUG
        if (withSPSPPS)
        {
            blockLength = frameSize-(_spsSize + _ppsSize + startCodeIndex);
            data = malloc(blockLength);
            data = memcpy(data, &frame[0+startCodeIndex+ _spsSize + _ppsSize], blockLength);
        }
        else
        {
            blockLength = frameSize-startCodeIndex;
            data = malloc(blockLength);
            data = memcpy(data, &frame[0+startCodeIndex], blockLength);

        }
//#endif
//        blockLength = frameSize;
//        data = malloc(blockLength);
//        data = memcpy(data, &frame[0], blockLength);

        // again, replace the start header with the size of the NALU
        uint32_t dataLength32 = htonl (blockLength - 4);
        memcpy (data, &dataLength32, sizeof (uint32_t));

        status = CMBlockBufferCreateWithMemoryBlock(NULL, data,  // memoryBlock to hold data. If NULL, block will be alloc when needed
                                                    blockLength,  // overall length of the mem block in bytes
                                                    kCFAllocatorNull, NULL,
                                                    0,     // offsetToData
                                                    blockLength,  // dataLength of relevant data bytes, starting at offsetToData
                                                    0, &blockBuffer);

//        NSLog(@"\t\t BlockBufferCreation: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");
    }

    // now create our sample buffer from the block buffer,
    if(status == noErr) {
        // here I'm not bothering with any timing specifics since in my case we displayed all frames immediately
        const size_t sampleSize = blockLength;

        status = CMSampleBufferCreate(kCFAllocatorDefault,
                                      blockBuffer, true, NULL, NULL,
                                      _formatDesc, 1, 0, NULL, 1,
                                      &sampleSize, &sampleBuffer);

//        NSLog(@"\t\t SampleBufferCreate: \t %@", (status == noErr) ? @"successful!" : @"failed...");
    }

    if(status == noErr) {
        // set some values of the sample buffer's attachments
        CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
        CFMutableDictionaryRef dict = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
        CFDictionarySetValue(dict, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);

        // either send the samplebuffer to a VTDecompressionSession or to an AVSampleBufferDisplayLayer
        [self render:sampleBuffer];
    }

    // free memory to avoid a memory leak, do the same for sps, pps and blockbuffer
    if (NULL != data) {
        free (data);
        data = NULL;
    }
    return;
}

- (void) createDecompSession {
    // make sure to destroy the old VTD session
    _decompressionSession = NULL;
    VTDecompressionOutputCallbackRecord callBackRecord;
    callBackRecord.decompressionOutputCallback = decompressionSessionDecodeFrameCallback;

    // this is necessary if you need to make calls to Objective C "self" from within in the callback method.
    callBackRecord.decompressionOutputRefCon = (__bridge void *)self;

    // you can set some desired attributes for the destination pixel buffer.  I didn't use this but you may
    // if you need to set some attributes, be sure to uncomment the dictionary in VTDecompressionSessionCreate
    /*NSDictionary *destinationImageBufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
     [NSNumber numberWithBool:YES],
     (id)kCVPixelBufferOpenGLESCompatibilityKey,
     nil];*/

    OSStatus status =  VTDecompressionSessionCreate(NULL, _formatDesc, NULL,
                                                    NULL, // (__bridge CFDictionaryRef)(destinationImageBufferAttributes)
                                                    &callBackRecord, &_decompressionSession);
    NSLog(@"Video Decompression Session Create: \t %@", (status == noErr) ? @"successful!" : @"failed...");
    if(status != noErr)
        NSLog(@"\t\t VTD ERROR type: %d", (int)status);
}

void decompressionSessionDecodeFrameCallback(void *decompressionOutputRefCon,
                                             void *sourceFrameRefCon,
                                             OSStatus status,
                                             VTDecodeInfoFlags infoFlags,
                                             CVImageBufferRef imageBuffer,
                                             CMTime presentationTimeStamp,
                                             CMTime presentationDuration) {
    if (status != noErr) {
        NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
        NSLog(@"Decompressed error: %@", error);
    }
    else {
        //NSLog(@"Decompressed sucessfully: pts: %f", CMTimeGetSeconds(presentationTimeStamp));

//        NSLog(@"Decompressed sucessfully");
        CIImage *ciImage = [CIImage imageWithCVPixelBuffer:imageBuffer];
        CIContext *temporaryContext = [CIContext contextWithOptions:nil];
        CGImageRef videoImage = [temporaryContext
                                 createCGImage:ciImage
                                 fromRect:CGRectMake(0, 0,
                                                     CVPixelBufferGetWidth(imageBuffer),
                                                     CVPixelBufferGetHeight(imageBuffer))];

        UIImage *image = [[UIImage alloc] initWithCGImage:videoImage];
        CGImageRelease(videoImage);

        VideoDecoder *decoder = (__bridge VideoDecoder *)decompressionOutputRefCon;
        [decoder.delegate videoDecoderImage:image];
//        [decoder renderImage:image];

    }
}

- (void)renderImage:(UIImage *)img {
    dispatch_async(dispatch_get_main_queue(), ^{
//        [self->mVideoImageView setImage:img];
        [self->_delegate videoDecoderImage:img];
    });
}

- (void)render:(CMSampleBufferRef)sampleBuffer {

     VTDecodeFrameFlags flags = kVTDecodeFrame_EnableAsynchronousDecompression;
     VTDecodeInfoFlags flagOut;
     NSDate* currentTime = [NSDate date];
     OSStatus status = VTDecompressionSessionDecodeFrame(_decompressionSession, sampleBuffer, flags,
     (void*)CFBridgingRetain(currentTime), &flagOut);

    if (noErr != status)
        NSLog(@"video decode error: %d", status);

     CFRelease(sampleBuffer);

    // if you're using AVSampleBufferDisplayLayer, you only need to use this line of code
//    if (mVideoLayer) {
//        [mVideoLayer enqueueSampleBuffer:sampleBuffer];
//    }
}

@end
```

Thanks in advance

答:
In the cases where you are receiving 12909 error, please make sure that you are successfully able to create CMBlockBufferCreateWithMemoryBlock using sps & pps values.

In some NALUs (containing IDR Frame), you will not get SPS + PPS + IDR sequence, rather you might receive SPS + PPS + SEI + IDR sequence.

Hence if you are following the reference link that you mentioned above, it might not work in case of SPS+PPS+SEI+IDR NALU. Hence due to unsuccessful/no creation of CMBlockBufferCreateWithMemoryBlock, the later non-IDR frame may be failing to be decompressed.

In case of SEI, as it is non-VCL, simply iterate over it to find the next start code, you don't necessarily need to do anything with SEI other than that for successful decompression.

Body:
I am using H264 algorithm below is the link which I am referring to decompress video using VideoToolbox framework

https://stackoverflow.com/a/29525001/1679255

Not all a few videos are stuck in a specific position.

Below is the error logs which i am recieving during the decompressing the frame.

NALU Raw: 00, 00, 00, 01, 41, 9a, 00, 18
~~~~~~~ Received NALU Type "1: Coded slice of a non-IDR picture (VCL)" ~~~~~~~~
Decompressed error: Error Domain=NSOSStatusErrorDomain Code=-12909 "(null)"

Xocde version is 11.2.1

Development Target is 10.0

If you need more info feel free to ask me.

My VideoDecoder Class Code is below :

@interface VideoDecoder () {
    AVSampleBufferDisplayLayer *mVideoLayer;
    long videoTimestamp;
}
@property (nonatomic, assign) CMVideoFormatDescriptionRef formatDesc;
@property (nonatomic, assign) VTDecompressionSessionRef decompressionSession;
@property (nonatomic, assign) int spsSize;
@property (nonatomic, assign) int ppsSize;
@property (nonatomic, retain) NSMutableData* streamVideoData;
@end

@implementation VideoDecoder

NSString * const naluTypesStrings[] = {
    @"0: Unspecified (non-VCL)",
    @"1: Coded slice of a non-IDR picture (VCL)", // P frame
    @"2: Coded slice data partition A (VCL)",
    @"3: Coded slice data partition B (VCL)",
    @"4: Coded slice data partition C (VCL)",
    @"5: Coded slice of an IDR picture (VCL)", // I frame
    @"6: Supplemental enhancement information (SEI) (non-VCL)",
    @"7: Sequence parameter set (non-VCL)", // SPS parameter
    @"8: Picture parameter set (non-VCL)", // PPS parameter
    @"9: Access unit delimiter (non-VCL)",
    @"10: End of sequence (non-VCL)",
    @"11: End of stream (non-VCL)",
    @"12: Filler data (non-VCL)",
    @"13: Sequence parameter set extension (non-VCL)",
    @"14: Prefix NAL unit (non-VCL)",
    @"15: Subset sequence parameter set (non-VCL)",
    @"16: Reserved (non-VCL)",
    @"17: Reserved (non-VCL)",
    @"18: Reserved (non-VCL)",
    @"19: Coded slice of an auxiliary coded picture without partitioning (non-VCL)",
    @"20: Coded slice extension (non-VCL)",
    @"21: Coded slice extension for depth view components (non-VCL)",
    @"22: Reserved (non-VCL)",
    @"23: Reserved (non-VCL)",
    @"24: STAP-A Single-time aggregation packet (non-VCL)",
    @"25: STAP-B Single-time aggregation packet (non-VCL)",
    @"26: MTAP16 Multi-time aggregation packet (non-VCL)",
    @"27: MTAP24 Multi-time aggregation packet (non-VCL)",
    @"28: FU-A Fragmentation unit (non-VCL)",
    @"29: FU-B Fragmentation unit (non-VCL)",
    @"30: Unspecified (non-VCL)",
    @"31: Unspecified (non-VCL)",
};

- (instancetype)init {
    self = [super init];
    if (self) {
//        _videoLayer = [[AVSampleBufferDisplayLayer alloc] init];
////        _videoLayer.frame = self.view.frame;
////        _videoLayer.bounds = self.view.bounds;
//        _videoLayer.frame = CGRectMake(0, 0, 1280, 720);
//        _videoLayer.bounds = CGRectMake(0, 0, 1280, 720);
//        _videoLayer.videoGravity = AVLayerVideoGravityResizeAspect;
//
//        // set Timebase, you may need this if you need to display frames at specific times
//        // I didn't need it so I haven't verified that the timebase is working
//        CMTimebaseRef controlTimebase;
//        CMTimebaseCreateWithMasterClock(CFAllocatorGetDefault(), CMClockGetHostTimeClock(), &controlTimebase);
//
//        //videoLayer.controlTimebase = controlTimebase;
//        CMTimebaseSetTime(_videoLayer.controlTimebase, kCMTimeZero);
//        CMTimebaseSetRate(_videoLayer.controlTimebase, 1.0);

        self.streamVideoData = nil;
        self.startDumpData = NO;
        videoTimestamp = 0;
    }
    return self;
}

- (void)initDebugStreamingVideo
{
    self.streamVideoData = [[NSMutableData alloc] init];
}

- (void)releaseVideoDecorder
{
    if (_decompressionSession != NULL)
    {
        VTDecompressionSessionInvalidate(_decompressionSession);
        _decompressionSession = NULL;
    }

    videoTimestamp = 0;
}

- (long)getVideoTimeStamp
{
    return videoTimestamp;
}

- (void)setVideoTimestamp:(long)timestamp
{
    videoTimestamp = timestamp;

#ifdef DEBUG
    NSLog(@"(sync)video: %2.1f", (float)videoTimestamp/1000000.);
#endif
}

- (NSString*)getLiveStreamingMP4Path
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *rootOfCachepath = [paths objectAtIndex:0];
    NSString* nalFilePath = [self getUniqueFilePath:rootOfCachepath FileNamePrefix:@"liveRecord" FileNameSubfix:@"MP4"];

    return nalFilePath;
}

- (NSString*)closeAndSaveDebugStreamingVideo
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *rootOfCachepath = [paths objectAtIndex:0];
    NSString* nalFilePath = [self getUniqueFilePath:rootOfCachepath FileNamePrefix:@"liveRecord" FileNameSubfix:@"264"];

    if (self.streamVideoData.length > 0)
        [self.streamVideoData writeToFile:nalFilePath atomically:YES];

    self.streamVideoData = [[NSMutableData alloc] init];

    return nalFilePath;
}

- (NSString*)getUniqueFilePath:(NSString*)parentFolder FileNamePrefix:(NSString*)fileName FileNameSubfix:(NSString*)subFix
{
    NSString* fullFilePath = nil;
    NSString* memoFileName = @"";

    NSDate *currentDate = [NSDate date];
    NSDateFormatter *currentDateFormat = [[NSDateFormatter alloc] init];
    [currentDateFormat setDateFormat:@"yyyyMMddHHmmss"];
    NSString *currentDateString = [currentDateFormat stringFromDate:currentDate];

    memoFileName = [NSString stringWithFormat:@"%@_%@.%@", fileName, currentDateString, subFix];

    fullFilePath = [parentFolder stringByAppendingPathComponent:memoFileName];

    return fullFilePath;
}

//- (void)setVideoLayer:(AVSampleBufferDisplayLayer *)layer {
//    mVideoLayer = layer;
//    CMTimebaseRef controlTimebase;
//    CMTimebaseCreateWithMasterClock(CFAllocatorGetDefault(), CMClockGetHostTimeClock(), &controlTimebase);
//
//    mVideoLayer.controlTimebase = controlTimebase;
//    CMTimebaseSetTime(mVideoLayer.controlTimebase, kCMTimeZero);
//    CMTimebaseSetRate(mVideoLayer.controlTimebase, 1.0);
//}

- (BOOL)checkIfThisIsIDRFrame:(uint8_t *)frame withSize:(uint32_t)frameSize {

    BOOL isIDRFrame = NO;
    int startCodeIndex = 0;

    int pi = 0;
    if (frame[pi] == 0x00 && frame[pi+1] == 0x00 && frame[pi+2] == 0x00 && frame[pi+3] == 0x01 && frame[pi+4] == 0x09 && frame[pi+5] == 0x50)
        startCodeIndex = 6;

//    NSLog(@"NALU Raw: %02X, %02x, %02x, %02x, %02X, %02x, %02x, %02x", frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7]);
    int nalu_type = (frame[startCodeIndex + 4] & 0x1F);
//    NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

    // if we havent already set up our format description with our SPS PPS parameters, we
    // can't process any frames except type 7 that has our parameters
    if (nalu_type != 7 && _formatDesc == NULL) {
        NSLog(@"Video error: Frame is not an I Frame and format description is null");
        return isIDRFrame;
    }

    // NALU type 7 is the SPS parameter NALU
    if (nalu_type == 7) {
        isIDRFrame = YES;
    }

    return isIDRFrame;
}

- (void)receivedRawVideoFrame:(uint8_t *)frame withSize:(uint32_t)frameSize {
    OSStatus status = 0;

    uint8_t *data = NULL;
    uint8_t *pps = NULL;
    uint8_t *sps = NULL;

#if defined(DEBUG) || defined(_RECORD_USE_LIVE_PACKAGE)
    if (self.startDumpData && self.streamVideoData && frameSize <= 512*1024)
        [self.streamVideoData appendBytes:(const void*)frame length:frameSize];
    //if (self.streamVideoData && frameSize <= 512*1024)
    //    [self.streamVideoData appendBytes:(const void*)frame length:frameSize];
#endif

    // I know how my H.264 data source's NALUs looks like so I know start code index is always 0.
    // if you don't know where it starts, you can use a for loop similar to how I find the 2nd and 3rd start codes
    int startCodeIndex = 0;
    int secondStartCodeIndex = 0;
    int thirdStartCodeIndex = 0;

//#ifdef DEBUG
    int pi = 0;
    if (frame[pi] == 0x00 && frame[pi+1] == 0x00 && frame[pi+2] == 0x00 && frame[pi+3] == 0x01 && frame[pi+4] == 0x09 && frame[pi+5] == 0x50)
        startCodeIndex = 6;
//#endif

    long blockLength = 0;
    BOOL withSPSPPS = NO;

    CMSampleBufferRef sampleBuffer = NULL;
    CMBlockBufferRef blockBuffer = NULL;

    NSLog(@"NALU Raw: %02X, %02x, %02x, %02x, %02X, %02x, %02x, %02x", frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7]);
    int nalu_type = (frame[startCodeIndex + 4] & 0x1F);
    NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

    // if we havent already set up our format description with our SPS PPS parameters, we
    // can't process any frames except type 7 that has our parameters
    if (nalu_type != 7 && _formatDesc == NULL) {
        NSLog(@"Video error: Frame is not an I Frame and format description is null");
        return;
    }

    // NALU type 7 is the SPS parameter NALU
    if (nalu_type == 7) {
        // find where the second PPS start code begins, (the 0x00 00 00 01 code)
        // from which we also get the length of the first SPS code
        for (int i = startCodeIndex + 4; i < startCodeIndex + 40; i++) {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x00 && frame[i+3] == 0x01) {
                secondStartCodeIndex = i;
                //_spsSize = secondStartCodeIndex;   // includes the header in the size
//#ifdef DEBUG
                _spsSize = secondStartCodeIndex - startCodeIndex;   // includes the header in the size
//#endif

                break;
            }
        }

        // find what the second NALU type is
        nalu_type = (frame[secondStartCodeIndex + 4] & 0x1F);
//        NSLog(@"~~~n7~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);
    }

    // type 8 is the PPS parameter NALU
    if(nalu_type == 8) {

        // find where the NALU after this one starts so we know how long the PPS parameter is
//#ifdef DEBUG
        for (int i = _spsSize + 4 + startCodeIndex; i < _spsSize + 30; i++) {
//#endif
        //for (int i = _spsSize + 4; i < _spsSize + 30; i++) {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x00 && frame[i+3] == 0x01) {
                thirdStartCodeIndex = i;
                //_ppsSize = thirdStartCodeIndex - _spsSize;
//#ifdef DEBUG
                _ppsSize = thirdStartCodeIndex - _spsSize - startCodeIndex;
//#endif
                break;
            }
        }

        // allocate enough data to fit the SPS and PPS parameters into our data objects.
        // VTD doesn't want you to include the start code header (4 bytes long) so we add the - 4 here
        sps = malloc(_spsSize - 4);
        pps = malloc(_ppsSize - 4);

        // copy in the actual sps and pps values, again ignoring the 4 byte header
//#ifdef DEBUG
        memcpy (sps, &frame[4+startCodeIndex], _spsSize-4);
        memcpy (pps, &frame[_spsSize+4+startCodeIndex], _ppsSize-4);
        NSLog(@"SPS Raw: %02X, %02x, %02x, %02x, %02X, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x", sps[0],sps[1],sps[2],sps[3],sps[4],sps[5],sps[6],sps[7],sps[8],sps[9],sps[10],sps[11],sps[12],sps[13],sps[14],sps[15]);
        NSLog(@"PPS Raw: %02X, %02x, %02x, %02x", pps[0],pps[1],pps[2],pps[3]);
//#endif
//        memcpy (sps, &frame[4], _spsSize-4);
//        memcpy (pps, &frame[_spsSize+4], _ppsSize-4);

        // now we set our H264 parameters
        uint8_t*  parameterSetPointers[2] = {sps, pps};
        size_t parameterSetSizes[2] = {_spsSize-4, _ppsSize-4};

        status = CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault, 2,
                                                                     (const uint8_t *const*)parameterSetPointers,
                                                                     parameterSetSizes, 4,
                                                                     &_formatDesc);

//        NSLog(@"\t\t Creation of CMVideoFormatDescription: %@", (status == noErr) ? @"successful!" : @"failed...");
        if(status != noErr)
            NSLog(@"\t\t Format Description ERROR type: %d", (int)status);

        // See if decomp session can convert from previous format description
        // to the new one, if not we need to remake the decomp session.
        // This snippet was not necessary for my applications but it could be for yours
        /*BOOL needNewDecompSession = (VTDecompressionSessionCanAcceptFormatDescription(_decompressionSession, _formatDesc) == NO);
         if(needNewDecompSession)
         {
         [self createDecompSession];
         }*/

        // now lets handle the IDR frame that (should) come after the parameter sets
        // I say "should" because that's how I expect my H264 stream to work, YMMV
        nalu_type = (frame[thirdStartCodeIndex + 4] & 0x1F);
//        NSLog(@"~~~n8~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

        withSPSPPS = YES;
    }

    // create our VTDecompressionSession.  This isnt neccessary if you choose to use AVSampleBufferDisplayLayer
    //
    if (videoTimestamp == 0 && _decompressionSession != NULL)
    {
        if (_decompressionSession != NULL)
        {
            VTDecompressionSessionInvalidate(_decompressionSession);
            _decompressionSession = NULL;
        }
    }
    if ((status == noErr) && (_decompressionSession == NULL)) {
        [self createDecompSession];
    }

    // type 5 is an IDR frame NALU.  The SPS and PPS NALUs should always be followed by an IDR (or IFrame) NALU, as far as I know
    if(nalu_type == 5) {
        // find the offset, or where the SPS and PPS NALUs end and the IDR frame NALU begins
//#ifdef DEBUG
        int offset = _spsSize + _ppsSize + startCodeIndex;
        NSLog(@"Start IDR at %d", offset);
//#endif
//        int offset = _spsSize + _ppsSize;
        blockLength = frameSize - offset;
        //        NSLog(@"Block Length : %ld", blockLength);
        data = malloc(blockLength);
        data = memcpy(data, &frame[offset], blockLength);

        // replace the start code header on this NALU with its size.
        // AVCC format requires that you do this.
        // htonl converts the unsigned int from host to network byte order
        uint32_t dataLength32 = htonl (blockLength - 4);
        memcpy (data, &dataLength32, sizeof (uint32_t));

        // create a block buffer from the IDR NALU
        status = CMBlockBufferCreateWithMemoryBlock(NULL, data,  // memoryBlock to hold buffered data
                                                    blockLength,  // block length of the mem block in bytes.
                                                    kCFAllocatorNull, NULL,
                                                    0, // offsetToData
                                                    blockLength,   // dataLength of relevant bytes, starting at offsetToData
                                                    0, &blockBuffer);

//        NSLog(@"\t\t BlockBufferCreation: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");
    }

    // NALU type 1 is non-IDR (or PFrame) picture
    if (nalu_type == 1) {
        // non-IDR frames do not have an offset due to SPS and PSS, so the approach
        // is similar to the IDR frames just without the offset
//#ifdef DEBUG
        if (withSPSPPS)
        {
            blockLength = frameSize-(_spsSize + _ppsSize + startCodeIndex);
            data = malloc(blockLength);
            data = memcpy(data, &frame[0+startCodeIndex+ _spsSize + _ppsSize], blockLength);
        }
        else
        {
            blockLength = frameSize-startCodeIndex;
            data = malloc(blockLength);
            data = memcpy(data, &frame[0+startCodeIndex], blockLength);

        }
//#endif
//        blockLength = frameSize;
//        data = malloc(blockLength);
//        data = memcpy(data, &frame[0], blockLength);

        // again, replace the start header with the size of the NALU
        uint32_t dataLength32 = htonl (blockLength - 4);
        memcpy (data, &dataLength32, sizeof (uint32_t));

        status = CMBlockBufferCreateWithMemoryBlock(NULL, data,  // memoryBlock to hold data. If NULL, block will be alloc when needed
                                                    blockLength,  // overall length of the mem block in bytes
                                                    kCFAllocatorNull, NULL,
                                                    0,     // offsetToData
                                                    blockLength,  // dataLength of relevant data bytes, starting at offsetToData
                                                    0, &blockBuffer);

//        NSLog(@"\t\t BlockBufferCreation: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");
    }

    // now create our sample buffer from the block buffer,
    if(status == noErr) {
        // here I'm not bothering with any timing specifics since in my case we displayed all frames immediately
        const size_t sampleSize = blockLength;

        status = CMSampleBufferCreate(kCFAllocatorDefault,
                                      blockBuffer, true, NULL, NULL,
                                      _formatDesc, 1, 0, NULL, 1,
                                      &sampleSize, &sampleBuffer);

//        NSLog(@"\t\t SampleBufferCreate: \t %@", (status == noErr) ? @"successful!" : @"failed...");
    }

    if(status == noErr) {
        // set some values of the sample buffer's attachments
        CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
        CFMutableDictionaryRef dict = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
        CFDictionarySetValue(dict, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);

        // either send the samplebuffer to a VTDecompressionSession or to an AVSampleBufferDisplayLayer
        [self render:sampleBuffer];
    }

    // free memory to avoid a memory leak, do the same for sps, pps and blockbuffer
    if (NULL != data) {
        free (data);
        data = NULL;
    }
    return;
}

- (void) createDecompSession {
    // make sure to destroy the old VTD session
    _decompressionSession = NULL;
    VTDecompressionOutputCallbackRecord callBackRecord;
    callBackRecord.decompressionOutputCallback = decompressionSessionDecodeFrameCallback;

    // this is necessary if you need to make calls to Objective C "self" from within in the callback method.
    callBackRecord.decompressionOutputRefCon = (__bridge void *)self;

    // you can set some desired attributes for the destination pixel buffer.  I didn't use this but you may
    // if you need to set some attributes, be sure to uncomment the dictionary in VTDecompressionSessionCreate
    /*NSDictionary *destinationImageBufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
     [NSNumber numberWithBool:YES],
     (id)kCVPixelBufferOpenGLESCompatibilityKey,
     nil];*/

    OSStatus status =  VTDecompressionSessionCreate(NULL, _formatDesc, NULL,
                                                    NULL, // (__bridge CFDictionaryRef)(destinationImageBufferAttributes)
                                                    &callBackRecord, &_decompressionSession);
    NSLog(@"Video Decompression Session Create: \t %@", (status == noErr) ? @"successful!" : @"failed...");
    if(status != noErr)
        NSLog(@"\t\t VTD ERROR type: %d", (int)status);
}

void decompressionSessionDecodeFrameCallback(void *decompressionOutputRefCon,
                                             void *sourceFrameRefCon,
                                             OSStatus status,
                                             VTDecodeInfoFlags infoFlags,
                                             CVImageBufferRef imageBuffer,
                                             CMTime presentationTimeStamp,
                                             CMTime presentationDuration) {
    if (status != noErr) {
        NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
        NSLog(@"Decompressed error: %@", error);
    }
    else {
        //NSLog(@"Decompressed sucessfully: pts: %f", CMTimeGetSeconds(presentationTimeStamp));

//        NSLog(@"Decompressed sucessfully");
        CIImage *ciImage = [CIImage imageWithCVPixelBuffer:imageBuffer];
        CIContext *temporaryContext = [CIContext contextWithOptions:nil];
        CGImageRef videoImage = [temporaryContext
                                 createCGImage:ciImage
                                 fromRect:CGRectMake(0, 0,
                                                     CVPixelBufferGetWidth(imageBuffer),
                                                     CVPixelBufferGetHeight(imageBuffer))];

        UIImage *image = [[UIImage alloc] initWithCGImage:videoImage];
        CGImageRelease(videoImage);

        VideoDecoder *decoder = (__bridge VideoDecoder *)decompressionOutputRefCon;
        [decoder.delegate videoDecoderImage:image];
//        [decoder renderImage:image];

    }
}

- (void)renderImage:(UIImage *)img {
    dispatch_async(dispatch_get_main_queue(), ^{
//        [self->mVideoImageView setImage:img];
        [self->_delegate videoDecoderImage:img];
    });
}

- (void)render:(CMSampleBufferRef)sampleBuffer {

     VTDecodeFrameFlags flags = kVTDecodeFrame_EnableAsynchronousDecompression;
     VTDecodeInfoFlags flagOut;
     NSDate* currentTime = [NSDate date];
     OSStatus status = VTDecompressionSessionDecodeFrame(_decompressionSession, sampleBuffer, flags,
     (void*)CFBridgingRetain(currentTime), &flagOut);

    if (noErr != status)
        NSLog(@"video decode error: %d", status);

     CFRelease(sampleBuffer);

    // if you're using AVSampleBufferDisplayLayer, you only need to use this line of code
//    if (mVideoLayer) {
//        [mVideoLayer enqueueSampleBuffer:sampleBuffer];
//    }
}

@end

Thanks in advance


问:
Is there a fast and non-fancy C# code/algorithm to compress a string of comma separated digits close to maximum info density?
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

```<code>select SumKeys(id), name from SomeTable where name='multiple rows named this'
</code>```

and I get something like:

```<code>SumKeys         name
--------        ---------
1,4,495         multiple rows named this
</code>```

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?

答:
Not sure how "fancy" you'd consider it, but zip/gzip compression is highly effective for any text (sometimes to the tune of 90% reduction or better).  Since you're already working with C# and CLR integration, it hopefully wouldn't be too hard to setup/deploy.  I haven't tinkered with any C# libraries for compression yet, but it's easy to find them.  For example: http://sharpdevelop.net/OpenSource/SharpZipLib/ or http://dotnetzip.codeplex.com/ or even http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx

Or an easier option might be to switch your field to text or varchar/nvarchar(max), if that's feasible.

Body:
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

select SumKeys(id), name from SomeTable where name='multiple rows named this'

and I get something like:

SumKeys         name
--------        ---------
1,4,495         multiple rows named this

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?


问:
Transaction declined: invalid payment method [OR-CCSEH-05]
I'm trying to get the GCP Free Tier but when it reaches step 2 and I input my card details I get this error.

Transaction declined: invalid payment method. Learn more [OR-CCSEH-05]

Please help

答:
Indian debit or credit card not accepted

If you're trying to make payments for your Google service using an Indian debit or credit card and your card is being rejected, here's what you can do.

Try another credit card (not a debit card)

Due to issues with the 3D Secure verification service, we can't accept Indian debit cards for automatic payments at this time. We also can't accept certain Indian credit cards. If your card is being rejected, try another credit card.

Indian debit or credit card not accepted