问:
Find a subarray from a array that equals some value X
Background

You are given an array that includes positive and negative numbers.
You are to find a subarray within the array that equals some value X.
The input is the array and the X value.
The output is the starting and ending index of the subarray.

Example

```<code>Array = [2,6,0,9,7,3,1,4,1,10]
X = 15
Output = [1,3]
</code>```

Following is the Code I found on geeks4geeks

```<code>  public static void subArraySum(int[] arr, int n, int sum) {
        //cur_sum to keep track of cummulative sum till that point
        int cur_sum = 0;
        int start = 0;
        int end = -1;
        HashMap<Integer, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            cur_sum = cur_sum + arr[i];
            //check whether cur_sum - sum = 0, if 0 it means
            //the sub array is starting from index 0- so stop
            if (cur_sum - sum == 0) {
                start = 0;
                end = i;
                break;
            }
            //if hashMap already has the value, means we already
            // have subarray with the sum - so stop
            if (hashMap.containsKey(cur_sum - sum)) {
                start = hashMap.get(cur_sum - sum) + 1;
                end = i;
                break;
            }
            //if value is not present then add to hashmap
            hashMap.put(cur_sum, i);

        }
        // if end is -1 : means we have reached end without the sum
        if (end == -1) {
            System.out.println("No subarray with given sum exists");
        } else {
            System.out.println("Sum found between indexes "
                            + start + " to " + end);
</code>```

QUESTION
Overall I am able to understand why this solution works. The first block with the condition cur_sum - sum == 0 makes total sense to me.

However I am extremely confused about why the hashMap.containsKey(cur_sum - sum) check is working. I know that it works every time but I want to understand the mathematical significance behind it. I read in a interview blog that this uses the common diff technique but i am not sure how this applies to this.

I am not trying to memorize this solution as I prepare for interview but trying to build a solid understanding of why it is working.

I have spent hours coming up with examples and traced through them by hand and the solution works but I am not able to grasp why this technique works and i refuse to memorize it blindly.

For instance if we are talking about a array with positive numbers only then i know the "SLIDING WINDOW" technique can be used and that i am able to completely comprehend. As you expand the window the sum gets larger and as you close the window the sum gets smaller. This is not the case for the problem above and so would appreciate some help.

答:
sum - is the number we want to achieve

cur_sum - is the sum of all the elements in the array so far

say that cur_sum - sum = x

Each step we update cur_sum at the beginning and if the condition that confuses you evaluates to false we update the hashmap and continue.

So far so good.

Now, why are we looking to see if x is already in the hashmap?

The answer to that is that if there was a previous index i which all the elements till that index (inclusive) had the sum of x, this means that from index i+1 till the current index, we have a subarray which sums to: cur_sum - x

And since we already know that cur_sum - sum = x that means that the subarray that starts at i+1 and ends at the current index sums exactly to sum.

Let's take the example you posted:

```<code>Array = [2,6,0,9,7,3,1,4,1,10]
X = 15
Output = [1,3]
</code>```

Let's iterate the array:

index 0: sum 2 => updating the map with (0:2)

index 1: sum 2+6=8 => updating the map with (1:8)

index 2: sum 2+6+0=8 => updating the map with (2:8)

index 3: sum 2+6+0+9=17 =>

but now we can see that the map already contains 17-15=2 (0:2)
hence we know that the sum of the subarray that starts at index 1 (index 1 comes after zero from (0:2)) and ends at the current index: 3 - this subarray sums to 15.

Body:
Background

You are given an array that includes positive and negative numbers.
You are to find a subarray within the array that equals some value X.
The input is the array and the X value.
The output is the starting and ending index of the subarray.

Example

Array = [2,6,0,9,7,3,1,4,1,10]
X = 15
Output = [1,3]

Following is the Code I found on geeks4geeks

  public static void subArraySum(int[] arr, int n, int sum) {
        //cur_sum to keep track of cummulative sum till that point
        int cur_sum = 0;
        int start = 0;
        int end = -1;
        HashMap<Integer, Integer> hashMap = new HashMap<>();

        for (int i = 0; i < n; i++) {
            cur_sum = cur_sum + arr[i];
            //check whether cur_sum - sum = 0, if 0 it means
            //the sub array is starting from index 0- so stop
            if (cur_sum - sum == 0) {
                start = 0;
                end = i;
                break;
            }
            //if hashMap already has the value, means we already
            // have subarray with the sum - so stop
            if (hashMap.containsKey(cur_sum - sum)) {
                start = hashMap.get(cur_sum - sum) + 1;
                end = i;
                break;
            }
            //if value is not present then add to hashmap
            hashMap.put(cur_sum, i);

        }
        // if end is -1 : means we have reached end without the sum
        if (end == -1) {
            System.out.println("No subarray with given sum exists");
        } else {
            System.out.println("Sum found between indexes "
                            + start + " to " + end);

QUESTION
Overall I am able to understand why this solution works. The first block with the condition cur_sum - sum == 0 makes total sense to me.

However I am extremely confused about why the hashMap.containsKey(cur_sum - sum) check is working. I know that it works every time but I want to understand the mathematical significance behind it. I read in a interview blog that this uses the common diff technique but i am not sure how this applies to this.

I am not trying to memorize this solution as I prepare for interview but trying to build a solid understanding of why it is working.

I have spent hours coming up with examples and traced through them by hand and the solution works but I am not able to grasp why this technique works and i refuse to memorize it blindly.

For instance if we are talking about a array with positive numbers only then i know the "SLIDING WINDOW" technique can be used and that i am able to completely comprehend. As you expand the window the sum gets larger and as you close the window the sum gets smaller. This is not the case for the problem above and so would appreciate some help.

Body:
sum - is the number we want to achieve

cur_sum - is the sum of all the elements in the array so far

say that cur_sum - sum = x

Each step we update cur_sum at the beginning and if the condition that confuses you evaluates to false we update the hashmap and continue.

So far so good.

Now, why are we looking to see if x is already in the hashmap?

The answer to that is that if there was a previous index i which all the elements till that index (inclusive) had the sum of x, this means that from index i+1 till the current index, we have a subarray which sums to: cur_sum - x

And since we already know that cur_sum - sum = x that means that the subarray that starts at i+1 and ends at the current index sums exactly to sum.

Let's take the example you posted:

Array = [2,6,0,9,7,3,1,4,1,10]
X = 15
Output = [1,3]

Let's iterate the array:

index 0: sum 2 => updating the map with (0:2)

index 1: sum 2+6=8 => updating the map with (1:8)

index 2: sum 2+6+0=8 => updating the map with (2:8)

index 3: sum 2+6+0+9=17 =>

but now we can see that the map already contains 17-15=2 (0:2)
hence we know that the sum of the subarray that starts at index 1 (index 1 comes after zero from (0:2)) and ends at the current index: 3 - this subarray sums to 15.


来源: stackexchange

问:
Making my elements appear in vertically aligned rows
I am trying to replicate this website:
https://t.gyazo.com/teams/leovegas/dcfef17a5c89c99b7b59e88f997e7cfe.mp4

( might have to refresh the page to get GIF to work)

I have everything setup that I want using flexbox so that it sizes change when the browser window does, I just need to make these three sections appear in three vertical rows from left to right when the screen size is larger then 710px.

I have tried to use flex-direction: row; and flex-direction: column; but they don't seem to want to work! Even when I use justify content, or align items the three sections break off and arrange themselves in odd ways. I think its some code of mine that is messing with it but I cannot figure it out!

https://repl.it/@GunarsAuskaps/flexbox-mobile-first-starter-1

here is my code for anyone that wants to look it over.

I want the three columns to be arranged from left to right, in their own separate up-down columns, separated evenly, and shrink and grow with flex.

答:
I just reviewed the code structure. There's no code issue. You need to add the clear: both; class in main element. I have tried and it's working.

```<code>@media screen and (min-width: 710px) {
  main {
    display: flex;
    flex-direction: row;
    clear: both;
  }
}
</code>```

Here is the solution:

https://codepen.io/ydhiman20/pen/LomeKG

ContentLicense: CC BY-SA 4.0

Body:
I just reviewed the code structure. There's no code issue. You need to add the clear: both; class in main element. I have tried and it's working.

@media screen and (min-width: 710px) {
  main {
    display: flex;
    flex-direction: row;
    clear: both;
  }
}

Here is the solution:

https://codepen.io/ydhiman20/pen/LomeKG


问:
Scenario's for loseing messages with akka when all actors run in the same jvm
I once wrote a multiplayer game in java with the help of the akka framwork. With their 'at-least-once' delivery I always wondered in which cases a message can get lost if all the akka actors are running in the same local jvm.

The design of the game was like a giant state machine (as events needed to be processed in order), so most of the times only 1 message was on it's way between all the involved actors. (Running multiple session in parralel was possible)

I have read that the communication of actors, when running locally, is done in-memory. So not considering out of memory error's, are their other (preferably reroducable) scenario's where messages are actually lost?

Note:
Message box manipulation is also not what I am looking for. Just legit cases where something goes wrong and the message is really lost.

答:
I have read that the communication of actors, when running locally, is done in-memory. So not considering out of memory error's, are their other (preferably reroducable) scenario's where messages are actually lost?

So, normally in-memory delivery is true, but you also specified that you are talking about the "at-least-once delivery" feature. And the docs ( https://doc.akka.io/docs/akka/current/persistence.html#at-least-once-delivery ) specifically talk about how at-least-once changes a lot of the normal behavior. Specifically, at-least-once uses persistence to track what has been sent and what has been acknowledged.

So, when you are using at-least-once, there is a whole dance that has to happen when sending a message. First the message has to to be stored such that if the sending actor fails, that work can resume elsewhere. Second, the message has to be sent. Third, any response has to be correlated with the sent message and the receipt persisted so that if the actor fails after that point that the resuming actor knows that the message doesn't have to be retried.

Because of this, there should be no case where a message is lost. Even when a JVM is lost. (Even when all JVM's are lost.) That, after all is the point of "at-least-once", that the message is guaranteed to be delivered (and replied to). However, note that this does come with tradeoffs. (See the docs for the tradeoffs, although one obvious one is performance.)


问:
Core Data `deleteObject:` problem!
I have the following entities in core data as shown in the figure below.

The delete rule for all the relationship is cascade.

Questions:
When ever i delete the any one of the entity object at level 2 and do [context save:&error]; all other objects in Table Entity1 gets the data fault and the app crashes due to not able to read the Entity1 object any more, giving EXC_BAD_ACCESS error.

I am using this code

```<code>for(Entity1 *entity in listOfEntitys)
{
    if(entity.Relation1)
        [context deleteObject:entity.Relation1];

    if(entity.Relation2)
        [context deleteObject:entity.Relation2];

    if(entity.Relation3)
        [context deleteObject:entity.Relation3];
}
[context save:&error];
</code>```

Its not like I have never deleted any object from core data but this is the only place where problem is occurring. Can anyone Help.

Thanks.

PS. I have seen other questions on SO but none has the same kind of situation as i do.

Edit:

My problem is that when I try to delete any one object from level 2 then all the objects in the entity1 are getting data fault. some thing like this.

```<code>Printing description of listOfEntitys:
(
    "<Entity1: 0x4dc3d80> (entity: Entity1; id: 0x4dc2d60 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p5> ; data: <fault>)",
    "<Entity1: 0x5b06ea0> (entity: Entity1; id: 0x5b077d0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p6> ; data: <fault>)",
    "<Entity1: 0x4dc2cf0> (entity: Entity1; id: 0x4dc2df0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p7> ; data: <fault>)",
    "<Entity1: 0x4dc2b80> (entity: Entity1; id: 0x4dc3640 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p8> ; data: <fault>)"
)
</code>```

答:
From the Core Data Programming Guide

If a relationship delete rule is
  Cascade, then deleting one object may
  result in the deletion of others.

If you don't want related objects to be deleted when you delete a given object, then the deletion rule for those relationships should be something other than 'cascade'. You probably want 'nullify' instead.

ContentLicense: CC BY-SA 3.0

Title: Core Data `deleteObject:` problem!

Body:
I have the following entities in core data as shown in the figure below.

The delete rule for all the relationship is cascade.

Questions:
When ever i delete the any one of the entity object at level 2 and do [context save:&error]; all other objects in Table Entity1 gets the data fault and the app crashes due to not able to read the Entity1 object any more, giving EXC_BAD_ACCESS error.

I am using this code

for(Entity1 *entity in listOfEntitys)
{
    if(entity.Relation1)
        [context deleteObject:entity.Relation1];

    if(entity.Relation2)
        [context deleteObject:entity.Relation2];

    if(entity.Relation3)
        [context deleteObject:entity.Relation3];
}
[context save:&error];

Its not like I have never deleted any object from core data but this is the only place where problem is occurring. Can anyone Help.

Thanks.

PS. I have seen other questions on SO but none has the same kind of situation as i do.

Edit:

My problem is that when I try to delete any one object from level 2 then all the objects in the entity1 are getting data fault. some thing like this.

Printing description of listOfEntitys:
(
    "<Entity1: 0x4dc3d80> (entity: Entity1; id: 0x4dc2d60 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p5> ; data: <fault>)",
    "<Entity1: 0x5b06ea0> (entity: Entity1; id: 0x5b077d0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p6> ; data: <fault>)",
    "<Entity1: 0x4dc2cf0> (entity: Entity1; id: 0x4dc2df0 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p7> ; data: <fault>)",
    "<Entity1: 0x4dc2b80> (entity: Entity1; id: 0x4dc3640 <x-coredata://DF11191D-0BE9-4A63-955D-0A43153290A4/Entity1/p8> ; data: <fault>)"
)


问:
Why this while loop is not breaking?
I am writing a json parser. And while considering such json string "\"K\":12}]" for looping I am using a while loop with pointer. The code I am trying is this:

```<code>while ((*memptr != ',')||(*memptr != '}')||(*memptr != ']'))
            memptr++;
</code>```

When the memptr points to '1' of "12" it goes on increasing beyond ']'.
But if the memptr points to ',' or '}' or ']' this loop should break isn't it? but this loop never breaks! And the memptr goes on increasing.
what am I missing?

答:
When debugging logic, make yourself a truth table.

Let the first column be *memptr, the second be *memptr != ',', then for } and ], and finally the whole controlling expression (*memptr != ',')||(*memptr != '}')||(*memptr != ']')

```<code>1 | True  | True  | True  | True
, | False | True  | True  | True
} | True  | False | True  | True
] | True  | True  | False | True
</code>```

See the problem?  The controlling expression is always true, so the loop happily continues.

You may choose to instead use a Venn diagram.  Draw three disjoint circles, for ,, }, and ].  Now use three different hatching patterns to fill in "things that are not ,", "things that are not }', "things that are not ]".

What region does the union of these three areas cover?
What region does the intersection cover?

Title: Why this while loop is not breaking?

Body:
I am writing a json parser. And while considering such json string "\"K\":12}]" for looping I am using a while loop with pointer. The code I am trying is this:

while ((*memptr != ',')||(*memptr != '}')||(*memptr != ']'))
            memptr++;

When the memptr points to '1' of "12" it goes on increasing beyond ']'.
But if the memptr points to ',' or '}' or ']' this loop should break isn't it? but this loop never breaks! And the memptr goes on increasing.
what am I missing?

Body:
When debugging logic, make yourself a truth table.

Let the first column be *memptr, the second be *memptr != ',', then for } and ], and finally the whole controlling expression (*memptr != ',')||(*memptr != '}')||(*memptr != ']')

1 | True  | True  | True  | True
, | False | True  | True  | True
} | True  | False | True  | True
] | True  | True  | False | True

See the problem?  The controlling expression is always true, so the loop happily continues.

You may choose to instead use a Venn diagram.  Draw three disjoint circles, for ,, }, and ].  Now use three different hatching patterns to fill in "things that are not ,", "things that are not }', "things that are not ]".

What region does the union of these three areas cover?
What region does the intersection cover?


问:
Can't connect to arangodb using Java API
I have a problem when accessing arangodb using Java driver.
When i run my application, it runs but neither it shows any response and nor it throws any error. Then i think it must be something on my connection to the remote arangodb server, and i tried to connect using Python arangodb, and it's success to connect.

Anyone knows what's the problem with my arangodb Java application? Is there any difference between java connector and python to arango? I'm using java driver arango 5.0.1

Here's what I've tried:

Java Driver :

```<code>public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("deprecation")
        ArangoDB arangodb = new ArangoDB.Builder().timeout(100).host("10.22.21.70",8599).user("xxx").password("xxx").useProtocol(Protocol.VST).build();
        System.out.println("Test Start");
        ArangoDatabase db = arangodb.db("data");

        boolean tes = db.exists();

        System.out.println("success");
        arangodb.shutdown();
    }
</code>```

This program continues to run like this, without being terminated and throwing an error :
enter image description here

Using Python Arango :

```<code>import json
from arango import ArangoClient
from pyArango.connection import *

USER = 'xxx'
PASS = 'xxx'
HOST = '10.22.21.70'
DATABASE = 'data'
PORTT = 8599

client = ArangoClient(host=HOST,port=PORTT)
db = client.db(DATABASE,username=USER,password=PASS)

query = 'FOR s IN Email FILTER s.date>= "2018-11-07" LIMIT 0,2 RETURN s'
queryResult = db.aql.execute(query,batch_size=2,count=True)
res = queryResult.batch()

print(res)
</code>```

And also i've tried to use telnet to the remote server, and it shows blank screen, which means no problem with the connection between my local host with the remote host.

Thanks

答:
I'm using java driver arango 5.0.1

I had the same issue. Using v4.2.2 solved the problem. If someone could explain why drivers are not compatible, that would be great.

Body:
I have a problem when accessing arangodb using Java driver.
When i run my application, it runs but neither it shows any response and nor it throws any error. Then i think it must be something on my connection to the remote arangodb server, and i tried to connect using Python arangodb, and it's success to connect.

Anyone knows what's the problem with my arangodb Java application? Is there any difference between java connector and python to arango? I'm using java driver arango 5.0.1

Here's what I've tried:

Java Driver :

public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("deprecation")
        ArangoDB arangodb = new ArangoDB.Builder().timeout(100).host("10.22.21.70",8599).user("xxx").password("xxx").useProtocol(Protocol.VST).build();
        System.out.println("Test Start");
        ArangoDatabase db = arangodb.db("data");

        boolean tes = db.exists();

        System.out.println("success");
        arangodb.shutdown();
    }

This program continues to run like this, without being terminated and throwing an error :
enter image description here

Using Python Arango :

import json
from arango import ArangoClient
from pyArango.connection import *

USER = 'xxx'
PASS = 'xxx'
HOST = '10.22.21.70'
DATABASE = 'data'
PORTT = 8599

client = ArangoClient(host=HOST,port=PORTT)
db = client.db(DATABASE,username=USER,password=PASS)

query = 'FOR s IN Email FILTER s.date>= "2018-11-07" LIMIT 0,2 RETURN s'
queryResult = db.aql.execute(query,batch_size=2,count=True)
res = queryResult.batch()

print(res)

And also i've tried to use telnet to the remote server, and it shows blank screen, which means no problem with the connection between my local host with the remote host.

Thanks


答:
If you use OR condition, you have to be very careful on the exit criteria.
Say if your condition is pointer != A || pointer != B,
    When it encounters A, the first condition returns false, but second returns true.
    When it encounters B, the first condition returns true, so it doesn't evaluate second.

Try using AND.

Title: Why this while loop is not breaking?


问:
How to modify keras model to get output between 0 to 7 except for just 0 and 1?
I am pretty new to data science and neural network. I have a dataset of unicode sentences which havebeen labeled as 0 and 1 for 'spam' or 'not_spam'. the Model I used for data is the code below(excluding the data preprocessing):

```<code>from keras.models import Model
from keras.layers import LSTM, Activation, Dense, Dropout, Input, Embedding

def RNN():
    inputs = Input(name='inputs',shape=[max_len])

    layer = Embedding(max_words,50,input_length=max_len)(inputs)

    layer = LSTM(64)(layer)

    layer = Dense(256,name='FC1')(layer)

    layer = Activation('relu')(layer)

    layer = Dropout(0.5)(layer)

    layer = Dense(1,name='out_layer')(layer)

    layer = Activation('sigmoid')(layer)
    # sigmoid aka 0 to 1 output

    model = Model(inputs=inputs,outputs=layer)

    return model

model.compile(loss='binary_crossentropy',optimizer=RMSprop(),metrics=['accuracy'])
</code>```

The predictions are so far so good.

But now I had my data-set modified. I added 6 columns instead of 'spam' column so my data label become an integer between [1-7]. Data-set looks like this (case #1):

```<code>sentence | category
 sent 1  | 1
 sent 2  | 3
 sent 3  | 2
 sent 4  | 7
   .
   .
   .
</code>```

I know I can add dummy variables and modify it like this one(case#2):

```<code>sentence | category_1 | category_2 | category_3 |  ...  | category_7
 sent 1  |     1      |     0      |     0      |       |     0
 sent 2  |     0      |     0      |     1      |       |     0
 sent 3  |     0      |     1      |     0      |       |     0
 sent 4  |     0      |     0      |     0      |       |     1
   .
   .
   .
</code>```

So I'm familiar with feature engineering part for data-set. What actually I'm looking for is to modify the code to have output from model like 1,2,3,4,.. (which implies prediction for each category).

Does anybody know how can I modify the code (The keras model) with as little editing as possible?

Any other recommendation for enhancing accuracy (based on experiences in NLP and Neural Network fields) would be appreciated.

答:
Seems like you're getting one-hot encoded outputs, to decode it back to integer

```<code>decoded = np.argmax(encoded, axis=1)
</code>```

check the example here

Hope this helps.

Body:
I am pretty new to data science and neural network. I have a dataset of unicode sentences which havebeen labeled as 0 and 1 for 'spam' or 'not_spam'. the Model I used for data is the code below(excluding the data preprocessing):

from keras.models import Model
from keras.layers import LSTM, Activation, Dense, Dropout, Input, Embedding

def RNN():
    inputs = Input(name='inputs',shape=[max_len])

    layer = Embedding(max_words,50,input_length=max_len)(inputs)

    layer = LSTM(64)(layer)

    layer = Dense(256,name='FC1')(layer)

    layer = Activation('relu')(layer)

    layer = Dropout(0.5)(layer)

    layer = Dense(1,name='out_layer')(layer)

    layer = Activation('sigmoid')(layer)
    # sigmoid aka 0 to 1 output

    model = Model(inputs=inputs,outputs=layer)

    return model

model.compile(loss='binary_crossentropy',optimizer=RMSprop(),metrics=['accuracy'])

The predictions are so far so good.

But now I had my data-set modified. I added 6 columns instead of 'spam' column so my data label become an integer between [1-7]. Data-set looks like this (case #1):

sentence | category
 sent 1  | 1
 sent 2  | 3
 sent 3  | 2
 sent 4  | 7
   .
   .
   .

I know I can add dummy variables and modify it like this one(case#2):

sentence | category_1 | category_2 | category_3 |  ...  | category_7
 sent 1  |     1      |     0      |     0      |       |     0
 sent 2  |     0      |     0      |     1      |       |     0
 sent 3  |     0      |     1      |     0      |       |     0
 sent 4  |     0      |     0      |     0      |       |     1
   .
   .
   .

So I'm familiar with feature engineering part for data-set. What actually I'm looking for is to modify the code to have output from model like 1,2,3,4,.. (which implies prediction for each category).

Does anybody know how can I modify the code (The keras model) with as little editing as possible?

Any other recommendation for enhancing accuracy (based on experiences in NLP and Neural Network fields) would be appreciated.

Body:
Seems like you're getting one-hot encoded outputs, to decode it back to integer

decoded = np.argmax(encoded, axis=1)

check the example here

Hope this helps.


问:
Image compression java
I want to transfer Images via network socket(java.net).Where Can I find a sample Code for

compressing Buffered Images in java..Say for example If my Image file is around 200kb,I want

it to be converted to atleat 100kb..So that the transfer will be lil bit fast..

Thank you..

答: You could use ImageIO.write() to stream a BufferedImage in a supported image format that's compressed, e.g. jpg (lossy compression) or png (lossless compression).

Title: Image compression java


问:
Issue converting KeyPoints to and from JSON and then using FlannBasedMatcher
I'm saving my KeyPoints and Descriptors in a JSON file. Later when I retrieve them, I am trying to use them in a FlannBasedMatcher. However, I think something is going wrong in the conversion because I am getting the following error.

```<code>cv2.error: OpenCV(4.1.0) /io/opencv/modules/flann/src/miniflann.cpp:315: error: (-210:Unsupported format or combination of formats) in function 'buildIndex_'
> type=4
>
</code>```

Creating the keypoints and descriptors

```<code>brisk = cv2.BRISK_create()
kp1, des1 = brisk.detectAndCompute(img, None)
</code>```

Converting to JSON

```<code>temp = [{'point0':k.pt[0],'point1':k.pt[1],'size':k.size,'angle': k.angle, 'response': k.response, "octave":k.octave,
        "id":k.class_id} for k in kp1]
json.dumps(temp) #JSON KeyPoints
json.dumps(des1.tolist()) #JSON Descriptors
</code>```

Converting back

```<code>rawKeys = json.loads(result[key]["KEYPOINTS"])
rawDes = json.loads(result[key]["DESCRIPTORS"])

kp2 = []

for kp in rawKeys:
    p = cv2.KeyPoint(x=kp["point0"],y=kp["point0"],_size=kp["size"], _angle=kp["angle"], _response=kp["response"], _octave=kp["octave"], _class_id=kp["id"])
    kp2.append(p)
des2 = np.array(rawDes)
</code>```

Matcher

```<code>FLANN_INDEX_LSH = 6

index_params= dict(algorithm = FLANN_INDEX_LSH,
                   table_number = 6, # 12
                   key_size = 12,     # 20
                   multi_probe_level = 1) #2

search_params = dict(checks = 50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1,des2,k=2) # ERROR HERE
</code>```

答:
Solution was deceptively simple.</p>

```<code>des2 = np.array(rawDes,dtype=np.uint8)
</code>```

Body:
I'm saving my KeyPoints and Descriptors in a JSON file. Later when I retrieve them, I am trying to use them in a FlannBasedMatcher. However, I think something is going wrong in the conversion because I am getting the following error.

cv2.error: OpenCV(4.1.0) /io/opencv/modules/flann/src/miniflann.cpp:315: error: (-210:Unsupported format or combination of formats) in function 'buildIndex_'
> type=4
>

Creating the keypoints and descriptors

brisk = cv2.BRISK_create()
kp1, des1 = brisk.detectAndCompute(img, None)

Converting to JSON

temp = [{'point0':k.pt[0],'point1':k.pt[1],'size':k.size,'angle': k.angle, 'response': k.response, "octave":k.octave,
        "id":k.class_id} for k in kp1]
json.dumps(temp) #JSON KeyPoints
json.dumps(des1.tolist()) #JSON Descriptors

Converting back

rawKeys = json.loads(result[key]["KEYPOINTS"])
rawDes = json.loads(result[key]["DESCRIPTORS"])

kp2 = []

for kp in rawKeys:
    p = cv2.KeyPoint(x=kp["point0"],y=kp["point0"],_size=kp["size"], _angle=kp["angle"], _response=kp["response"], _octave=kp["octave"], _class_id=kp["id"])
    kp2.append(p)
des2 = np.array(rawDes)

Matcher

FLANN_INDEX_LSH = 6

index_params= dict(algorithm = FLANN_INDEX_LSH,
                   table_number = 6, # 12
                   key_size = 12,     # 20
                   multi_probe_level = 1) #2

search_params = dict(checks = 50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1,des2,k=2) # ERROR HERE

Body:
Solution was deceptively simple.

des2 = np.array(rawDes,dtype=np.uint8)


问:
Compass watch and .sass-cache
(I added the line wp-content/themes/klasik-child/mysass/.sass-cache in the file .gitignore from) when I execute "Compass watch" I have this error:

```<code>Errno::ENOENT on line ["247"] of C: No such file or directory'
 -C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\github2015\myproject\wp-content\themes\klasik-child\mysass\.sass-cache\75fcaf1b4852ceb732871195e41567cc2a7d8997
C%058C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\github2015
run with --trace to see the full backtrace
</code>```

Yet 75fcaf1b4852ceb732871195e41567cc2a7d8997 and github2015 folder exists.

I reset my .gitingnore file and I tried to delete the folder ".sass-cache"
but I still have the same problem.

I tried adding sass_options = {:cache_location => "path\to\tmp\sass-cache"} in config.rb but it gives errors "mkdir" invalid argument - path

thank !

++ Other info :

1- Command is run here : C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\github2015\myproject\wp-content\themes\klasik-child\mysass
from windows command

2- directory structure

```<code>mysass
|---css
     |----principal.css
|---images
|---sass
     |----partials
           |-----_accueil.scss
     |----pricipal.scss
config.rb
</code>```

3- config.rb

```<code>require 'compass/import-once/activate'

http_path = "/"
css_dir = "css"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"
# sass_options = {:cache_location => "path\to\tmp\sass-cache"}
relative_assets = true
line_comments = false
</code>```

答:
I had the same issue it turns out my .sass-cache path was too long, and the file was silently failing and not being outputted to that directory. It never mentioned anywhere that my path was too long, I was trying a suggestion found here:

https://github.com/Compass/compass/issues/1791

To fix it,
Add this line to to your config.rb

```<code>cache_path = 'C:\temp\sass'
</code>```

Title: Compass watch and .sass-cache

Body:
(I added the line wp-content/themes/klasik-child/mysass/.sass-cache in the file .gitignore from) when I execute "Compass watch" I have this error:

Errno::ENOENT on line ["247"] of C: No such file or directory'
 -C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\github2015\myproject\wp-content\themes\klasik-child\mysass\.sass-cache\75fcaf1b4852ceb732871195e41567cc2a7d8997
C%058C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\github2015
run with --trace to see the full backtrace

Yet 75fcaf1b4852ceb732871195e41567cc2a7d8997 and github2015 folder exists.

I reset my .gitingnore file and I tried to delete the folder ".sass-cache"
but I still have the same problem.

I tried adding sass_options = {:cache_location => "path\to\tmp\sass-cache"} in config.rb but it gives errors "mkdir" invalid argument - path

thank !

++ Other info :

1- Command is run here : C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\github2015\myproject\wp-content\themes\klasik-child\mysass
from windows command

2- directory structure

mysass
|---css
     |----principal.css
|---images
|---sass
     |----partials
           |-----_accueil.scss
     |----pricipal.scss
config.rb

3- config.rb

require 'compass/import-once/activate'

http_path = "/"
css_dir = "css"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"
# sass_options = {:cache_location => "path\to\tmp\sass-cache"}
relative_assets = true
line_comments = false

Body:
I had the same issue it turns out my .sass-cache path was too long, and the file was silently failing and not being outputted to that directory. It never mentioned anywhere that my path was too long, I was trying a suggestion found here:

https://github.com/Compass/compass/issues/1791

To fix it,
Add this line to to your config.rb

cache_path = 'C:\temp\sass'


问:
How can I solve the "unable to locate adb problem" other than checking sdk path and uninstalling avast
I am trying to run my android project and there a "unable to locate adb" problem, anyone have any idea please?

My android sdk location is correct and I also uninstalled my avast antivirus application in case they are the reasons

答:
1- on your android studio go to Tools > android > SDK Manager.

2- view android SDK location (this will show you your sdk path)

3- navigate to file explorer on your system, and locate the file path, this should be found something like c://Users/xxxx/AppData/local/android (you can now see the sdk.)

4- check the platform tools folder and see if you would see anything like adb.exe (it should be missing probably because it was corrupted and your antivirus or windows defender has quarantined it)

5- delete the platform tools folder

6- go back to android studio and from where you left off navigate to sdk tools (this should be right under android sdk location)

7- uncheck android sdk platform-tools and select ok. (this will uninstall the platform tools from your ide) wait till it is done and then your gradle will sync.

8- after sync is complete, go back and check the box of android sdk platform-tools (this will install a fresh one with new adb.exe) wait till it is done and sync project and then you are good to go.

I hope this saves someone some hours of pain.


问:
Pandas - replace all NaN values in DataFrame with empty python dict objects
I have a pandas DataFrame where each cell contains a python dict.

```<code>>>> data = {'Q':{'X':{2:2010}, 'Y':{2:2011, 3:2009}},'R':{'X':{1:2013}}}
>>> frame = DataFrame(data)
>>> frame
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        NaN
</code>```

I'd like to replace the NaN with an empty dict, to get this result:

```<code>                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        {}
</code>```

However, because the fillna function interprets empty dict not as a scalar value but as a mapping of column --> value, it does NOTHING if I simply do this  (i.e. it doesn't work):

```<code>>>> frame.fillna(inplace=True, value={})
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        NaN
</code>```

Is there any way to use fillna to accomplish what I want?
Do I have to iterate through the entire DataFrame or construct a silly dict with all my columns mapped to empty dict?

答:
DataFrame.where is a way of achieving this quite directly:

```<code>>>> data = {'Q': {'X': {2: 2010}, 'Y': {2: 2011, 3: 2009}}, 'R': {'X': {1: 2013}}}
>>> frame = DataFrame(data)
>>> frame
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        NaN

>>> frame.where(frame.notna(), lambda x: [{}])
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}         {}
</code>```

Also, it appears to be a bit faster:

```<code>>>> %timeit frame.where(frame.notna(), lambda x: [{}])
791 µs ± 16.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit frame.applymap(lambda x: {} if isnull(x) else x)
1.07 ms ± 7.15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

(on larger datasets I've observed speedups of ~10x)

Body:
I have a pandas DataFrame where each cell contains a python dict.

>>> data = {'Q':{'X':{2:2010}, 'Y':{2:2011, 3:2009}},'R':{'X':{1:2013}}}
>>> frame = DataFrame(data)
>>> frame
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        NaN

I'd like to replace the NaN with an empty dict, to get this result:

                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        {}

However, because the fillna function interprets empty dict not as a scalar value but as a mapping of column --> value, it does NOTHING if I simply do this  (i.e. it doesn't work):

>>> frame.fillna(inplace=True, value={})
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        NaN

Is there any way to use fillna to accomplish what I want?
Do I have to iterate through the entire DataFrame or construct a silly dict with all my columns mapped to empty dict?

Body:
DataFrame.where is a way of achieving this quite directly:

>>> data = {'Q': {'X': {2: 2010}, 'Y': {2: 2011, 3: 2009}}, 'R': {'X': {1: 2013}}}
>>> frame = DataFrame(data)
>>> frame
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}        NaN

>>> frame.where(frame.notna(), lambda x: [{}])
                    Q          R
X           {2: 2010}  {1: 2013}
Y  {2: 2011, 3: 2009}         {}

Also, it appears to be a bit faster:

>>> %timeit frame.where(frame.notna(), lambda x: [{}])
791 µs ± 16.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
>>> %timeit frame.applymap(lambda x: {} if isnull(x) else x)
1.07 ms ± 7.15 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

(on larger datasets I've observed speedups of ~10x)


问:
What's an Elmer Cipher
What's an Elmer Cipher? Where can I find a reference on this cipher algorithm?</p>

答:
Maybe it's a misheard LM Hash?

Or maybe this is what you're after ;)

Title: What's an Elmer Cipher


问:
While loop that ends with a semiconlon
I have the code;

```<code>    while(nread = read(fd,&c,1)==0);
</code>```

Why is this while loop ending with a semicolon? Isn't this line going to to go through the whole fd without doing anything?

答:
An empty statement does nothing, so

```<code>while(nread = read(fd,&c,1)==0);
</code>```

is equivalent to

```<code>while(nread = read(fd,&c,1)==0) { }
</code>```

This is what the statement does:

If read returns 1 (because it read one character), the loop will end immediately (after setting nread to 0).

If read returns 0 (because it reached EOF), it will try to read again (which may or may not return returns 0 again).

If read returns -1 (because an error occurred), it will try to read again (which may or may not return -1 again).

Since this can easily degenerate into an infinite loop, this code is surely broken.

Title: While loop that ends with a semiconlon

Body:
I have the code;

    while(nread = read(fd,&c,1)==0);

Why is this while loop ending with a semicolon? Isn't this line going to to go through the whole fd without doing anything?

Body:
An empty statement does nothing, so

while(nread = read(fd,&c,1)==0);

is equivalent to

while(nread = read(fd,&c,1)==0) { }

This is what the statement does:

If read returns 1 (because it read one character), the loop will end immediately (after setting nread to 0).

If read returns 0 (because it reached EOF), it will try to read again (which may or may not return returns 0 again).

If read returns -1 (because an error occurred), it will try to read again (which may or may not return -1 again).

Since this can easily degenerate into an infinite loop, this code is surely broken.


问:
softmax and sigmoid function for the output layer
In the deep learning implementations related to object detection and semantic segmentation, I have seen the output layers using either sigmoid or softmax. I am not very clear when to use which? It seems to me both of them can support these tasks. Are there any guidelines for this choice?</p>

答:
The sigmoid and the softmax function have different purposes. For a detailed explanation of when to use sigmoid vs. softmax in neural network design, you can look at this article: "Classification: Sigmoid vs. Softmax."

Short summary:

If you have a multi-label classification problem where there is more than one "right answer" (the outputs are NOT mutually exclusive) then you can use a sigmoid function on each raw output independently. The sigmoid will allow you to have high probability for all of your classes, some of them, or none of them.

If you instead have a multi-class classification problem where there is only one "right answer" (the outputs are mutually exclusive), then use a softmax function. The softmax will enforce that the sum of the probabilities of your output classes are equal to one, so in order to increase the probability of a particular class, your model must correspondingly decrease the probability of at least one of the other classes.


问:
MongoParseError: Invalid connection string
I am trying to connect MongoDB database with this code but when running it I get the error (see the error below after the code). The initial error was in the line where it was resolved by adding useNewUrlParser: true but even after this I still get more errors. I am using MongoDB version 4.0.1. Does anybody know how to resolve this error?

```<code>mongoose.connect('User://localhost:27017/User',{ useNewUrlParser: true })
</code>```

Error while running this code:

(node:11068) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): MongoParseError: Invalid connection string
      (node:11068) [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.

答: I had this same issue.  In my case, the issue was caused by my password.  Apparently, if there are special characters in the password, you need to use the HEX value.  </p>

Body:
I am trying to connect MongoDB database with this code but when running it I get the error (see the error below after the code). The initial error was in the line where it was resolved by adding useNewUrlParser: true but even after this I still get more errors. I am using MongoDB version 4.0.1. Does anybody know how to resolve this error?

mongoose.connect('User://localhost:27017/User',{ useNewUrlParser: true })

Error while running this code:

(node:11068) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): MongoParseError: Invalid connection string
      (node:11068) [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.


问:
How to extract dotted text from image?
I'm working on my bachelor's degree final project and I want to create an OCR for bottle inspection with python. I need some help with text recognition from the image. Do I need to apply the cv2 operations in a better way, train tesseract or should I try another method?

I tried image processing operations on the image and I used pytesseract to recognize the characters.

Using the code bellow I got from this photo:

to this one:

and then to this one:

Sharpen function:

```<code>def sharpen(img):
  sharpen = iaa.Sharpen(alpha=1.0, lightness = 1.0)
  sharpen_img = sharpen.augment_image(img)
  return sharpen_img
</code>```

Image processing code:

```<code>textZone = cv2.pyrUp(sharpen(originalImage[y:y + h - 1, x:x + w - 1])) #text zone cropped from the original image

sharp = cv2.cvtColor(textZone, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(sharp, 127, 255, cv2.THRESH_BINARY)

#the functions such as opening are inverted (I don't know why) that's why I did opening with MORPH_CLOSE parameter, dilatation with erode and so on

kernel_open = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
open = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel_open)

kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,7))
dilate = cv2.erode(open,kernel_dilate)

kernel_close = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 5))
close = cv2.morphologyEx(dilate, cv2.MORPH_OPEN, kernel_close)

print(pytesseract.image_to_string(close))
</code>```

This is the result of pytesseract.image_to_string:

```<code>22203;?!)

92:53 a
</code>```

The expected result is :

```<code>22/03/20

02:53 A
</code>```

答:
One potential thing you could do to improve recognition on the characters is to dilate the characters so pytesseract gives a better result. Dilating the characters will connect the individual blobs together and can fix the / or the A characters. So starting with your latest binary image:

Original

Dilate with a 3x3 kernel with iterations=1 (left) or iterations=2 (right). You can experiment with other values but don't do it too much or the characters will all connect. Maybe this will provide a better result with you OCR.

```<code>import cv2

image = cv2.imread("1.PNG")
thresh = cv2.threshold(image, 115, 255, cv2.THRESH_BINARY_INV)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
dilate = cv2.dilate(thresh, kernel, iterations=1)
final = cv2.threshold(dilate, 115, 255, cv2.THRESH_BINARY_INV)[1]

cv2.imshow('image', image)
cv2.imshow('dilate', dilate)
cv2.imshow('final', final)
cv2.waitKey(0)
</code>```

Title: How to extract dotted text from image?

Body:
I'm working on my bachelor's degree final project and I want to create an OCR for bottle inspection with python. I need some help with text recognition from the image. Do I need to apply the cv2 operations in a better way, train tesseract or should I try another method?

I tried image processing operations on the image and I used pytesseract to recognize the characters.

Using the code bellow I got from this photo:

to this one:

and then to this one:

Sharpen function:

def sharpen(img):
  sharpen = iaa.Sharpen(alpha=1.0, lightness = 1.0)
  sharpen_img = sharpen.augment_image(img)
  return sharpen_img

Image processing code:

textZone = cv2.pyrUp(sharpen(originalImage[y:y + h - 1, x:x + w - 1])) #text zone cropped from the original image

sharp = cv2.cvtColor(textZone, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(sharp, 127, 255, cv2.THRESH_BINARY)

#the functions such as opening are inverted (I don't know why) that's why I did opening with MORPH_CLOSE parameter, dilatation with erode and so on

kernel_open = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
open = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel_open)

kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,7))
dilate = cv2.erode(open,kernel_dilate)

kernel_close = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 5))
close = cv2.morphologyEx(dilate, cv2.MORPH_OPEN, kernel_close)

print(pytesseract.image_to_string(close))

This is the result of pytesseract.image_to_string:

22203;?!)

92:53 a

The expected result is :

22/03/20

02:53 A

Body:
One potential thing you could do to improve recognition on the characters is to dilate the characters so pytesseract gives a better result. Dilating the characters will connect the individual blobs together and can fix the / or the A characters. So starting with your latest binary image:

Original

Dilate with a 3x3 kernel with iterations=1 (left) or iterations=2 (right). You can experiment with other values but don't do it too much or the characters will all connect. Maybe this will provide a better result with you OCR.

import cv2

image = cv2.imread("1.PNG")
thresh = cv2.threshold(image, 115, 255, cv2.THRESH_BINARY_INV)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
dilate = cv2.dilate(thresh, kernel, iterations=1)
final = cv2.threshold(dilate, 115, 255, cv2.THRESH_BINARY_INV)[1]

cv2.imshow('image', image)
cv2.imshow('dilate', dilate)
cv2.imshow('final', final)
cv2.waitKey(0)


问:
malloc - runtime memory pointer type allocation
I don't know how to use malloc correctly when I need my code to determine it's type at runtime. How do I declare one buffer in my header that can use either one of two different structs using malloc during runtime?

```<code>struct rgb_16 {
    unsigned short r;
    unsigned short g;
    unsigned short b;
};

struct half_16 {
    half r;
    half g;
    half b;
};

(void*)buffer;

if(sample_format == 1) {
    buffer = (rgb_16*)malloc(width * height * sizeof(rgb_16));
}

if(sample_format == 3) {
    buffer = (half_16*)malloc(width * height * sizeof(half_16));
}

if(tiff.sample_format == 3) {
    // data is float. do not normalize
    for(int x = 0; x < rgba.size(); x++) {
        rgba[x].r = (half)tiff.buffer[x]
                        .r; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].g = (half)tiff.buffer[x]
                        .g; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].b = (half)tiff.buffer[x]
                        .b; // error: Subscript of pointer to incomplete type 'void'

        rgba[x].a = 1.0;
    }
}
</code>```

I am getting an error that reads:

//error: Subscript of pointer to incomplete type 'void'

I was hoping that by using a void pointer it wouldn't care what type I end up using with malloc for my buffer.

Is there a way to let buffer be filled with either rgb_16 or half_16 at runtime?

First time posting here so please let me know if I should be formatting my post in a different way. Thank you.

答: Right after if( tiff.sample_format == 3) {, you need something like half_16* h = (half_16*) buffer. The compiler has no way to know what type buffer is, and so has no idea how far to go to get to the x'th entry. But with h[x], it does since h is of type half_16*.

Body:
I don't know how to use malloc correctly when I need my code to determine it's type at runtime. How do I declare one buffer in my header that can use either one of two different structs using malloc during runtime?

struct rgb_16 {
    unsigned short r;
    unsigned short g;
    unsigned short b;
};

struct half_16 {
    half r;
    half g;
    half b;
};

(void*)buffer;

if(sample_format == 1) {
    buffer = (rgb_16*)malloc(width * height * sizeof(rgb_16));
}

if(sample_format == 3) {
    buffer = (half_16*)malloc(width * height * sizeof(half_16));
}

if(tiff.sample_format == 3) {
    // data is float. do not normalize
    for(int x = 0; x < rgba.size(); x++) {
        rgba[x].r = (half)tiff.buffer[x]
                        .r; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].g = (half)tiff.buffer[x]
                        .g; // error: Subscript of pointer to incomplete type 'void'
        rgba[x].b = (half)tiff.buffer[x]
                        .b; // error: Subscript of pointer to incomplete type 'void'

        rgba[x].a = 1.0;
    }
}

I am getting an error that reads:

//error: Subscript of pointer to incomplete type 'void'

I was hoping that by using a void pointer it wouldn't care what type I end up using with malloc for my buffer.

Is there a way to let buffer be filled with either rgb_16 or half_16 at runtime?

First time posting here so please let me know if I should be formatting my post in a different way. Thank you.


问:
Why race condition happens in loop?
I have a code to simulate serial vs parallel computing.  However, it seems has a race condition.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void *foo(void *para) {
    printf("This is Thread %d running...\n", *(size_t *)para);
    fflush(stdout);
    sleep(2);
}

int main(void)
{
    /* loop version
    for (size_t i = 0; i < 4; i++) {
        foo((void *)&i);
    }
    */

    pthread_t pool[4];
    for (size_t i = 0; i < 4; i++) {
        pthread_create(&pool[i], NULL, foo, (void *)&i);
    }

    for (size_t i = 0; i < 4; i++) {
        pthread_join(pool[i], NULL);
    }

    return 0;
}
```

<p>Output:</p>

```[william@Notebook Downloads]$ time ./a.out
This is Thread 1 running...
This is Thread 2 running...
This is Thread 4 running...
This is Thread 3 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s

[william@Notebook Downloads]$ time ./a.out
This is Thread 3 running...
This is Thread 3 running...
This is Thread 2 running...
This is Thread 4 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s
```

Most of examples when race condition happens is whenn you have multiple threads try to write a shared value.  However, there is no write operation in this code at all.  So, why this happens?  Is it because for loop is not excuted in serial order?

答:
I didn't event read your question.  I just looked at your code and observed observed a huge problem that is likely the root cause of whatever you are asking about.  Look at the following loop code:

```<code>pthread_t pool[4];
for (size_t i = 1; i <= 4; i++) {
    pthread_create(&pool[i], NULL, foo, (void *)&i);
}
</code>```

You have an "array" of size 4, but you are iterating over indices [1..4].  C and C++ arrays start at index 0 and end at (len-1).  In other words, you should be iterating over indices [0..3].  Inserting anything into pool[4] is going create undefined behavior.

Instead of this line:

```<code>for (size_t i = 1; i <= 4; i++) {
</code>```

You want this:

```<code>for (size_t i = 0; i < 4; i++) {
</code>```

Apply the same fix to the second loop performing the pthread_join statements.

Also passing &i as the thread parameter is causing additional undefined behavior.  Your threads are accessing the address of a variable that is constantly changing by the main thread and then going out of scope.

Title: Why race condition happens in loop?

Body:
I have a code to simulate serial vs parallel computing.  However, it seems has a race condition.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void *foo(void *para) {
    printf("This is Thread %d running...\n", *(size_t *)para);
    fflush(stdout);
    sleep(2);
}

int main(void)
{
    /* loop version
    for (size_t i = 0; i < 4; i++) {
        foo((void *)&i);
    }
    */

    pthread_t pool[4];
    for (size_t i = 0; i < 4; i++) {
        pthread_create(&pool[i], NULL, foo, (void *)&i);
    }

    for (size_t i = 0; i < 4; i++) {
        pthread_join(pool[i], NULL);
    }

    return 0;
}

Output:

[william@Notebook Downloads]$ time ./a.out
This is Thread 1 running...
This is Thread 2 running...
This is Thread 4 running...
This is Thread 3 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s

[william@Notebook Downloads]$ time ./a.out
This is Thread 3 running...
This is Thread 3 running...
This is Thread 2 running...
This is Thread 4 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s

Most of examples when race condition happens is whenn you have multiple threads try to write a shared value.  However, there is no write operation in this code at all.  So, why this happens?  Is it because for loop is not excuted in serial order?

Body:
I didn't event read your question.  I just looked at your code and observed observed a huge problem that is likely the root cause of whatever you are asking about.  Look at the following loop code:

pthread_t pool[4];
for (size_t i = 1; i <= 4; i++) {
    pthread_create(&pool[i], NULL, foo, (void *)&i);
}

You have an "array" of size 4, but you are iterating over indices [1..4].  C and C++ arrays start at index 0 and end at (len-1).  In other words, you should be iterating over indices [0..3].  Inserting anything into pool[4] is going create undefined behavior.

Instead of this line:

for (size_t i = 1; i <= 4; i++) {

You want this:

for (size_t i = 0; i < 4; i++) {

Apply the same fix to the second loop performing the pthread_join statements.

Also passing &i as the thread parameter is causing additional undefined behavior.  Your threads are accessing the address of a variable that is constantly changing by the main thread and then going out of scope.


问:
how to properly do a countDown from the minutes of a Song?

I want to know how to properly get the total minutes and seconds of a song. And once I get the total minutes and seconds I want it to start to countdown the time.Just show up 2 decimal places for seconds and two places for minutes.

I want to know how to count up the song from the beginning
and also  would like to show 2 decimal places for seconds and 2 places for minutes

Thanks in advance

```<code>@objc func timerUpdate() {

    if (player != nil && player!.currentTime > 0.0) {
        increaseTime ()
        DecreaseTime()
        progressBar.setProgress(Float(player!.currentTime / player!.duration), animated:  false)

    }
    else {
        timer.invalidate()

    }
}
var totalOfTime :Double?
var minutes : Double?
var seconds : Double?
func changeSecondToMinutes() {
    minutes = player!.duration / 60.0

   seconds = minutes! / 60
   seconds! *= 100
    var rightOfSecods = Int(round(seconds!))
    seconds = Double(rightOfSecods) * 00.01
    print(seconds!)

}
var time  = 0
var minut = 0
func increaseTime () {

    startTime.text =  "\(Double(minut))   "
    print(minut)
    print(time)

}
var secondos = 0.0
func DecreaseTime() {
    seconds! -= 0.010

    print(seconds!)
    print(minutes!)
    if Double(round(10000*seconds!)/10000) == 0.00 {

        seconds! += 0.60
        minutes! -= 1
    }
    time += 1
    print(secondos)
    if time == 61 {
       minut += 1
       time = 0

    }

}
func PlayerFunction() {
 changeSecondToMinutes()

            Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)
 }
</code>```

答:
I'm using this singleton class in my project

```<code>class MediaPlayerManager: NSObject {

static let shared = MediaPlayerManager()

private var _player = AVPlayer()
private var _timer = Timer()
private var _songURL = ""
private var _isPaused = false
private var _isPlaying = false
private var _isStopped = false
private var _isRepeatEnabled = false
private var _isShuffleEnabled = false
private var _songProgressed : Float = 0.0
private var _observer: Any!
private var _rate: Float = 1.0

var songURL : String {
    set { _songURL = newValue }
    get { return _songURL }
}

var isPaused : Bool {
    set { _isPaused = newValue }
    get { return _isPaused }
}

var isPlaying : Bool {
    set { _isPlaying = newValue }
    get { return _isPlaying }
}

var isRepeatEnabled : Bool {
    set { _isRepeatEnabled = newValue }
    get { return _isRepeatEnabled }
}

var isShuffleEnabled : Bool {
    set { _isShuffleEnabled = newValue }
    get { return _isShuffleEnabled }
}

var songProgressed : Float {
    set { _songProgressed = newValue }
    get { return _songProgressed }
}

var rate : Float {
    set {
        _rate = newValue
        _player.rate = _rate
    }
    get { return _rate }
}

override init() {
    super.init()
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
        print("Playback OK")
        try AVAudioSession.sharedInstance().setActive(true)
        print("Session is Active")
    } catch {
        print(error)
    }
    _player = AVPlayer.init()
}

func playSong() {
    if isPaused {
        _player.play()
        isPlaying = true
        isPaused = false
        return
    }
    isPlaying = true
    isPaused = false
    let url = URL(string: self.songURL)
    let item = AVPlayerItem(url: url!)
    _player = AVPlayer(playerItem: item)
    _player.play()
    isPlaying = true
    isPaused = false
    addObserver()
}

func playSong(urlString: String) {

    let url = URL(string: urlString)
    songURL = urlString
    if isPaused {
        _player.play()
        isPlaying = true
        isPaused = false
        return
    }
    isPlaying = true
    isPaused = false
    let item = AVPlayerItem(url: url!)
    _player = AVPlayer(playerItem: item)
    _player.play()
    addObserver()
}

func addObserver() {
    _player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
    _player.currentItem!.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil)
    _player.currentItem!.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
    _player.currentItem!.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: nil)

    let interval = CMTime(value: 1, timescale: 2)
    _observer = _player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { (progressTime) in
        self.scheduleTimer()
        let seconds = CMTimeGetSeconds(progressTime)
        let secondsString = String(format: "%02d", Int(seconds.truncatingRemainder(dividingBy: 60.0)))
        let minutesString = String(format: "%02d", Int(seconds / 60))

        print( "\(minutesString):\(secondsString)" )
        self.songProgressed = Float( seconds )

    })
}

func pauseSong() {
    if isPlaying {
        isPlaying = false
        isPaused = true
        _player.pause()
    }
}

func stopSong() {
    isPlaying = false
    isPaused = false
    invalidateTimer()
    if let observer = _observer {
        _player.removeTimeObserver(observer)
        _observer = nil
    }
    _player = AVPlayer.init()
}

func reset() {
    songURL = ""
    stopSong()
}

func seekTo(Time time: Double) {
    let seconds : Int64 = Int64(time)
    let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1)

    _player.seek(to: targetTime)
}

func getRemainingTime() -> Double {
    let duration = _player.currentItem!.duration.seconds //total time
    let currentTime = _player.currentTime().seconds //playing time

    let remainingTime = duration - currentTime
    return (remainingTime.isNaN || remainingTime.isInfinite) ? 0 : remainingTime
}

func getSongDuration() -> Double {
    return (_player.currentItem!.duration.seconds.isNaN || _player.currentItem!.duration.seconds.isInfinite) ? 0 : _player.currentItem!.duration.seconds
}

func getSongProgress() -> Double {
    return (Double(self.songProgressed).isNaN || Double(self.songProgressed).isInfinite) ? 0 : Double(self.songProgressed)
}

private func scheduleTimer() {
    if (!_timer.isValid) {
        _timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

    }
}

private func invalidateTimer() {
    _timer.invalidate()
}

@objc func updateTimer() {
    NotificationCenter.default.post(name: .didReceiveRemainingTime, object: nil, userInfo: [Notification.Name.didReceiveRemainingTime: getRemainingTime()])
    NotificationCenter.default.post(name: .didReceiveElapsedTime, object: nil, userInfo: [Notification.Name.didReceiveElapsedTime: getSongProgress()])
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    switch keyPath {
    case "rate":
        if let rate = change?[NSKeyValueChangeKey.newKey] as? Float {
            if rate == 0.0 {
                print("playback stopped")
                isPlaying = false
                isPaused = true
                invalidateTimer()
            }
            if rate == 1.0 {
                print("normal playback")
            }
            if rate == -1.0 {
                print("reverse playback")
            }
        }
    case "playbackBufferEmpty":
        // Show loader
        print("buffer empty")
    case "playbackLikelyToKeepUp":
        // Hide loader
        print("buffer")
    case "playbackBufferFull":
        // Hide loader
        print("buffer full")
    case .none:
        break
    case .some(_):
        break
    }
}

}
</code>```

Here is how you can use this class and get the remaining time

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    addMediaPlayerObservers()
}

func addMediaPlayerObservers(){
    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveRemainingTime), name: NSNotification.Name.didReceiveRemainingTime, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveElapsedTime), name: NSNotification.Name.didReceiveElapsedTime, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(didSongFinished(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}

func playSong() {
    MediaPlayerManager.shared.playSong(urlString: "song url here")
}

@objc func didReceiveRemainingTime(_ notification: NSNotification) {
    if let remainingTime = notification.userInfo?[NSNotification.Name.didReceiveRemainingTime] as? Double {
//            print("Remaining time from observer: \(remainingTime)")

        self.hmsFrom(seconds: (Int)(remainingTime)) { (hours, minutes, seconds) in
            print("hours: \(hours)")
            print("minutes: \(minutes)")
            print("seconds: \(seconds)")
        }
    }
}
@objc func didReceiveElapsedTime(_ notification: NSNotification) {
    if let elapsedTime = notification.userInfo?[NSNotification.Name.didReceiveElapsedTime] as? Double {
 //            print("Elapsed time from observer: \(elapsedTime)")

        self.hmsFrom(seconds: (Int)(elapsedTime)) { (hours, minutes, seconds) in
            print("hours: \(hours)")
            print("minutes: \(minutes)")
            print("seconds: \(seconds)")
        }
    }
}
@objc func didSongFinished(_ notification: NSNotification) {
    print("Finished")
    MediaPlayerManager.shared.stopSong()
}
</code>```

This function actually convert total seconds into hours, minutes and seconds respectively

```<code>func hmsFrom(seconds: Int, completion: @escaping (_ hours: Int, _ minutes: Int, _ seconds: Int)->()) {
    completion(seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
</code>```

Here is the Notification extension

```<code>extension Notification.Name {
    static let didReceiveRemainingTime = Notification.Name("didReceiveRemainingTime")
    static let didReceiveElapsedTime = Notification.Name("didReceiveElapsedTime")
}
</code>```

Hope you get the desired result.

Body:
I want to know how to properly get the total minutes and seconds of a song. And once I get the total minutes and seconds I want it to start to countdown the time.Just show up 2 decimal places for seconds and two places for minutes.

I want to know how to count up the song from the beginning
and also  would like to show 2 decimal places for seconds and 2 places for minutes

Thanks in advance

@objc func timerUpdate() {

    if (player != nil && player!.currentTime > 0.0) {
        increaseTime ()
        DecreaseTime()
        progressBar.setProgress(Float(player!.currentTime / player!.duration), animated:  false)

    }
    else {
        timer.invalidate()

    }
}
var totalOfTime :Double?
var minutes : Double?
var seconds : Double?
func changeSecondToMinutes() {
    minutes = player!.duration / 60.0

   seconds = minutes! / 60
   seconds! *= 100
    var rightOfSecods = Int(round(seconds!))
    seconds = Double(rightOfSecods) * 00.01
    print(seconds!)

}
var time  = 0
var minut = 0
func increaseTime () {

    startTime.text =  "\(Double(minut))   "
    print(minut)
    print(time)

}
var secondos = 0.0
func DecreaseTime() {
    seconds! -= 0.010

    print(seconds!)
    print(minutes!)
    if Double(round(10000*seconds!)/10000) == 0.00 {

        seconds! += 0.60
        minutes! -= 1
    }
    time += 1
    print(secondos)
    if time == 61 {
       minut += 1
       time = 0

    }

}
func PlayerFunction() {
 changeSecondToMinutes()

            Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)
 }

Body:
I'm using this singleton class in my project

class MediaPlayerManager: NSObject {

static let shared = MediaPlayerManager()

private var _player = AVPlayer()
private var _timer = Timer()
private var _songURL = ""
private var _isPaused = false
private var _isPlaying = false
private var _isStopped = false
private var _isRepeatEnabled = false
private var _isShuffleEnabled = false
private var _songProgressed : Float = 0.0
private var _observer: Any!
private var _rate: Float = 1.0

var songURL : String {
    set { _songURL = newValue }
    get { return _songURL }
}

var isPaused : Bool {
    set { _isPaused = newValue }
    get { return _isPaused }
}

var isPlaying : Bool {
    set { _isPlaying = newValue }
    get { return _isPlaying }
}

var isRepeatEnabled : Bool {
    set { _isRepeatEnabled = newValue }
    get { return _isRepeatEnabled }
}

var isShuffleEnabled : Bool {
    set { _isShuffleEnabled = newValue }
    get { return _isShuffleEnabled }
}

var songProgressed : Float {
    set { _songProgressed = newValue }
    get { return _songProgressed }
}

var rate : Float {
    set {
        _rate = newValue
        _player.rate = _rate
    }
    get { return _rate }
}

override init() {
    super.init()
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
        print("Playback OK")
        try AVAudioSession.sharedInstance().setActive(true)
        print("Session is Active")
    } catch {
        print(error)
    }
    _player = AVPlayer.init()
}

func playSong() {
    if isPaused {
        _player.play()
        isPlaying = true
        isPaused = false
        return
    }
    isPlaying = true
    isPaused = false
    let url = URL(string: self.songURL)
    let item = AVPlayerItem(url: url!)
    _player = AVPlayer(playerItem: item)
    _player.play()
    isPlaying = true
    isPaused = false
    addObserver()
}

func playSong(urlString: String) {

    let url = URL(string: urlString)
    songURL = urlString
    if isPaused {
        _player.play()
        isPlaying = true
        isPaused = false
        return
    }
    isPlaying = true
    isPaused = false
    let item = AVPlayerItem(url: url!)
    _player = AVPlayer(playerItem: item)
    _player.play()
    addObserver()
}

func addObserver() {
    _player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
    _player.currentItem!.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil)
    _player.currentItem!.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
    _player.currentItem!.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: nil)

    let interval = CMTime(value: 1, timescale: 2)
    _observer = _player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { (progressTime) in
        self.scheduleTimer()
        let seconds = CMTimeGetSeconds(progressTime)
        let secondsString = String(format: "%02d", Int(seconds.truncatingRemainder(dividingBy: 60.0)))
        let minutesString = String(format: "%02d", Int(seconds / 60))

        print( "\(minutesString):\(secondsString)" )
        self.songProgressed = Float( seconds )

    })
}

func pauseSong() {
    if isPlaying {
        isPlaying = false
        isPaused = true
        _player.pause()
    }
}

func stopSong() {
    isPlaying = false
    isPaused = false
    invalidateTimer()
    if let observer = _observer {
        _player.removeTimeObserver(observer)
        _observer = nil
    }
    _player = AVPlayer.init()
}

func reset() {
    songURL = ""
    stopSong()
}

func seekTo(Time time: Double) {
    let seconds : Int64 = Int64(time)
    let targetTime: CMTime = CMTimeMake(value: seconds, timescale: 1)

    _player.seek(to: targetTime)
}

func getRemainingTime() -> Double {
    let duration = _player.currentItem!.duration.seconds //total time
    let currentTime = _player.currentTime().seconds //playing time

    let remainingTime = duration - currentTime
    return (remainingTime.isNaN || remainingTime.isInfinite) ? 0 : remainingTime
}

func getSongDuration() -> Double {
    return (_player.currentItem!.duration.seconds.isNaN || _player.currentItem!.duration.seconds.isInfinite) ? 0 : _player.currentItem!.duration.seconds
}

func getSongProgress() -> Double {
    return (Double(self.songProgressed).isNaN || Double(self.songProgressed).isInfinite) ? 0 : Double(self.songProgressed)
}

private func scheduleTimer() {
    if (!_timer.isValid) {
        _timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)

    }
}

private func invalidateTimer() {
    _timer.invalidate()
}

@objc func updateTimer() {
    NotificationCenter.default.post(name: .didReceiveRemainingTime, object: nil, userInfo: [Notification.Name.didReceiveRemainingTime: getRemainingTime()])
    NotificationCenter.default.post(name: .didReceiveElapsedTime, object: nil, userInfo: [Notification.Name.didReceiveElapsedTime: getSongProgress()])
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    switch keyPath {
    case "rate":
        if let rate = change?[NSKeyValueChangeKey.newKey] as? Float {
            if rate == 0.0 {
                print("playback stopped")
                isPlaying = false
                isPaused = true
                invalidateTimer()
            }
            if rate == 1.0 {
                print("normal playback")
            }
            if rate == -1.0 {
                print("reverse playback")
            }
        }
    case "playbackBufferEmpty":
        // Show loader
        print("buffer empty")
    case "playbackLikelyToKeepUp":
        // Hide loader
        print("buffer")
    case "playbackBufferFull":
        // Hide loader
        print("buffer full")
    case .none:
        break
    case .some(_):
        break
    }
}

}

Here is how you can use this class and get the remaining time

override func viewDidLoad() {
    super.viewDidLoad()
    addMediaPlayerObservers()
}

func addMediaPlayerObservers(){
    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveRemainingTime), name: NSNotification.Name.didReceiveRemainingTime, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(didReceiveElapsedTime), name: NSNotification.Name.didReceiveElapsedTime, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(didSongFinished(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}

func playSong() {
    MediaPlayerManager.shared.playSong(urlString: "song url here")
}

@objc func didReceiveRemainingTime(_ notification: NSNotification) {
    if let remainingTime = notification.userInfo?[NSNotification.Name.didReceiveRemainingTime] as? Double {
//            print("Remaining time from observer: \(remainingTime)")

        self.hmsFrom(seconds: (Int)(remainingTime)) { (hours, minutes, seconds) in
            print("hours: \(hours)")
            print("minutes: \(minutes)")
            print("seconds: \(seconds)")
        }
    }
}
@objc func didReceiveElapsedTime(_ notification: NSNotification) {
    if let elapsedTime = notification.userInfo?[NSNotification.Name.didReceiveElapsedTime] as? Double {
 //            print("Elapsed time from observer: \(elapsedTime)")

        self.hmsFrom(seconds: (Int)(elapsedTime)) { (hours, minutes, seconds) in
            print("hours: \(hours)")
            print("minutes: \(minutes)")
            print("seconds: \(seconds)")
        }
    }
}
@objc func didSongFinished(_ notification: NSNotification) {
    print("Finished")
    MediaPlayerManager.shared.stopSong()
}

This function actually convert total seconds into hours, minutes and seconds respectively

func hmsFrom(seconds: Int, completion: @escaping (_ hours: Int, _ minutes: Int, _ seconds: Int)->()) {
    completion(seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

Here is the Notification extension

extension Notification.Name {
    static let didReceiveRemainingTime = Notification.Name("didReceiveRemainingTime")
    static let didReceiveElapsedTime = Notification.Name("didReceiveElapsedTime")
}

Hope you get the desired result.


问:
link element onload
Is there anyway to listen to the onload event for a <link> element?

F.ex:

```<code>var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'styles.css';

link.onload = link.onreadystatechange = function(e) {
    console.log(e);
};
</code>```

This works for

答:
This is a cross-browser solution

```<code>// Your css loader
var d = document,
    css = d.head.appendChild(d.createElement('link'))

css.rel = 'stylesheet';
css.type = 'text/css';
css.href = "https://unpkg.com/tachyons@4.10.0/css/tachyons.css"

// Add this
if (typeof s.onload != 'undefined') s.onload = myFun;
} else {
    var img = d.createElement("img");
    img.onerror = function() {
      myFun();
      d.body.removeChild(img);
    }
    d.body.appendChild(img);
    img.src = src;
}

function myFun() {
    /* ..... PUT YOUR CODE HERE ..... */
}
</code>```

The answer is based on this link that say:

What happens behind the scenes is that the browser tries to load the
  CSS in the img element and, because a stylesheet is not a type of
  image, the img element throws the onerror event and executes our
  function. Thankfully, browsers load the entire CSS file before
  determining its not an image and firing the onerror event.

In modern browsers you can do css.onload and add that code as a fallback to cover old browsers back to 2011 when only Opera and Internet Explorer supported the onload event and onreadystatechange respectively.

Note: I have answered here too and it is my duplicate and deserves to be punished for my honesteness :P

ContentLicense: CC BY-SA 2.5

Title: link element onload

Body:
Is there anyway to listen to the onload event for a <link> element?

F.ex:

var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'styles.css';

link.onload = link.onreadystatechange = function(e) {
    console.log(e);
};

This works for

Body:
This is a cross-browser solution

// Your css loader
var d = document,
    css = d.head.appendChild(d.createElement('link'))

css.rel = 'stylesheet';
css.type = 'text/css';
css.href = "https://unpkg.com/tachyons@4.10.0/css/tachyons.css"

// Add this
if (typeof s.onload != 'undefined') s.onload = myFun;
} else {
    var img = d.createElement("img");
    img.onerror = function() {
      myFun();
      d.body.removeChild(img);
    }
    d.body.appendChild(img);
    img.src = src;
}

function myFun() {
    /* ..... PUT YOUR CODE HERE ..... */
}

The answer is based on this link that say:

What happens behind the scenes is that the browser tries to load the
  CSS in the img element and, because a stylesheet is not a type of
  image, the img element throws the onerror event and executes our
  function. Thankfully, browsers load the entire CSS file before
  determining its not an image and firing the onerror event.

In modern browsers you can do css.onload and add that code as a fallback to cover old browsers back to 2011 when only Opera and Internet Explorer supported the onload event and onreadystatechange respectively.

Note: I have answered here too and it is my duplicate and deserves to be punished for my honesteness :P


问:
Trying to read a table on Trigger during update, giving mutation error
Before updating a table I have to insert in another table, but to accomplish that I need information from the table (and other tables) which I'm updating, trying to read my updating table in the trigger is giving an error

ERROR at line 1:
  ORA-04091: table BASEDATOS2.SOL_SOLICITUD_PREMIOS is mutating, trigger/function
  may not see it
  ORA-06512: at "BASEDATOS2.INS_AFTER_UPD_PRICES", line 10
  ORA-04088: error during execution of trigger 'BASEDATOS2.INS_AFTER_UPD_PRICES'

Here´s my trigger

```<code>    CREATE OR REPLACE TRIGGER INS_AFTER_UPD_PRICES BEFORE UPDATE OF CONCEDIDO ON SOL_SOLICITUD_PREMIOS
FOR EACH ROW WHEN (new.CONCEDIDO = 'S')
DECLARE
    DESDE DATE;
    HASTA DATE;
    MONTO NUMBER;
    MAX_ID NUMBER;
    v_mov_premio NUMBER;
    CUENTA NUMBER;
BEGIN
    SELECT MAX(ID_MOVIMIENTO)+1 INTO MAX_ID FROM AHO_MOVIMIENTOS_CUENTA;
    SELECT SSP.FECHA_DESDE,SSP.FECHA_HASTA,SE.MONTO_COBERTURA INTO DESDE,HASTA,MONTO
    FROM SOL_SOLICITUD_PREMIOS SSP JOIN SOL_EVENTOS SE
    ON SE.COD_EVENTO = SSP.COD_EVENTO
    WHERE SE.COD_EVENTO=:OLD.COD_EVENTO
    AND SSP.ID=:OLD.ID;

    select id_tipo into v_mov_premio
            from aho_tipo_movimiento
            where UPPER(nombre_tipo) like '%PAGO DE PREMIO/SUBSIDIO%';

    SELECT AM.ID_CUENTA INTO CUENTA
    FROM AHO_MOVIMIENTOS_CUENTA AM
    JOIN AHO_TIPO_MOVIMIENTO ATM ON ATM.ID_TIPO=AM.ID_TIPO
    WHERE ATM.ID_TIPO='A' AND ROWNUM=1;

    INSERT INTO AHO_MOVIMIENTOS_CUENTA
    VALUES(MAX_ID, SYSDATE, MONTO*(HASTA-DESDE),v_mov_premio,CUENTA );
END;
</code>```

Anyone knows how can I make it work?

答:
The problem here is that your trigger is defined on SOL_SOLICITUD_PREMIOS, and in the body of the trigger you're SELECTing data from SOL_SOLICITUD_PREMIOS. In ROW triggers you're not allowed to read, insert, update, or delete other rows in the table which the trigger is defined on because it could cause a trigger loop, where the database gets stuck evaluating recursive invocations of the same trigger. However, in this case reading data from SOL_SOLICITUD_PREMIOS is not needed because you already have the data you need available to you in the :OLD pseudo-row. If I'm reading things correctly you can rewrite your trigger as follows and it should do what you're looking for:

```<code>CREATE OR REPLACE TRIGGER INS_AFTER_UPD_PRICES
  BEFORE UPDATE OF CONCEDIDO ON SOL_SOLICITUD_PREMIOS
  FOR EACH ROW
  WHEN (new.CONCEDIDO = 'S')
DECLARE
    MONTO         NUMBER;
    MAX_ID        NUMBER;
    v_mov_premio  NUMBER;
    CUENTA        NUMBER;
BEGIN
    SELECT MAX(ID_MOVIMIENTO)+1 INTO MAX_ID FROM AHO_MOVIMIENTOS_CUENTA;

    SELECT SE.MONTO_COBERTURA
      INTO MONTO
      FROM SOL_EVENTOS SE
      WHERE SE.COD_EVENTO = :OLD.COD_EVENTO;

    select id_tipo
      into v_mov_premio
      from aho_tipo_movimiento
      where UPPER(nombre_tipo) like '%PAGO DE PREMIO/SUBSIDIO%';

    SELECT AM.ID_CUENTA
      INTO CUENTA
      FROM AHO_MOVIMIENTOS_CUENTA AM
      JOIN AHO_TIPO_MOVIMIENTO ATM
        ON ATM.ID_TIPO = AM.ID_TIPO
      WHERE ATM.ID_TIPO = 'A' AND
            ROWNUM = 1;

    INSERT INTO AHO_MOVIMIENTOS_CUENTA
    VALUES(MAX_ID,
           SYSDATE,
           MONTO * (:OLD.FECHA_HASTA - :OLD.FECHA_DESDE),
           v_mov_premio,
           CUENTA );
END INS_AFTER_UPD_PRICES;
</code>```

Best of luck.

Body:
Before updating a table I have to insert in another table, but to accomplish that I need information from the table (and other tables) which I'm updating, trying to read my updating table in the trigger is giving an error

ERROR at line 1:
  ORA-04091: table BASEDATOS2.SOL_SOLICITUD_PREMIOS is mutating, trigger/function
  may not see it
  ORA-06512: at "BASEDATOS2.INS_AFTER_UPD_PRICES", line 10
  ORA-04088: error during execution of trigger 'BASEDATOS2.INS_AFTER_UPD_PRICES'

Here´s my trigger

    CREATE OR REPLACE TRIGGER INS_AFTER_UPD_PRICES BEFORE UPDATE OF CONCEDIDO ON SOL_SOLICITUD_PREMIOS
FOR EACH ROW WHEN (new.CONCEDIDO = 'S')
DECLARE
    DESDE DATE;
    HASTA DATE;
    MONTO NUMBER;
    MAX_ID NUMBER;
    v_mov_premio NUMBER;
    CUENTA NUMBER;
BEGIN
    SELECT MAX(ID_MOVIMIENTO)+1 INTO MAX_ID FROM AHO_MOVIMIENTOS_CUENTA;
    SELECT SSP.FECHA_DESDE,SSP.FECHA_HASTA,SE.MONTO_COBERTURA INTO DESDE,HASTA,MONTO
    FROM SOL_SOLICITUD_PREMIOS SSP JOIN SOL_EVENTOS SE
    ON SE.COD_EVENTO = SSP.COD_EVENTO
    WHERE SE.COD_EVENTO=:OLD.COD_EVENTO
    AND SSP.ID=:OLD.ID;

    select id_tipo into v_mov_premio
            from aho_tipo_movimiento
            where UPPER(nombre_tipo) like '%PAGO DE PREMIO/SUBSIDIO%';

    SELECT AM.ID_CUENTA INTO CUENTA
    FROM AHO_MOVIMIENTOS_CUENTA AM
    JOIN AHO_TIPO_MOVIMIENTO ATM ON ATM.ID_TIPO=AM.ID_TIPO
    WHERE ATM.ID_TIPO='A' AND ROWNUM=1;

    INSERT INTO AHO_MOVIMIENTOS_CUENTA
    VALUES(MAX_ID, SYSDATE, MONTO*(HASTA-DESDE),v_mov_premio,CUENTA );
END;

Anyone knows how can I make it work?

Body:
The problem here is that your trigger is defined on SOL_SOLICITUD_PREMIOS, and in the body of the trigger you're SELECTing data from SOL_SOLICITUD_PREMIOS. In ROW triggers you're not allowed to read, insert, update, or delete other rows in the table which the trigger is defined on because it could cause a trigger loop, where the database gets stuck evaluating recursive invocations of the same trigger. However, in this case reading data from SOL_SOLICITUD_PREMIOS is not needed because you already have the data you need available to you in the :OLD pseudo-row. If I'm reading things correctly you can rewrite your trigger as follows and it should do what you're looking for:

CREATE OR REPLACE TRIGGER INS_AFTER_UPD_PRICES
  BEFORE UPDATE OF CONCEDIDO ON SOL_SOLICITUD_PREMIOS
  FOR EACH ROW
  WHEN (new.CONCEDIDO = 'S')
DECLARE
    MONTO         NUMBER;
    MAX_ID        NUMBER;
    v_mov_premio  NUMBER;
    CUENTA        NUMBER;
BEGIN
    SELECT MAX(ID_MOVIMIENTO)+1 INTO MAX_ID FROM AHO_MOVIMIENTOS_CUENTA;

    SELECT SE.MONTO_COBERTURA
      INTO MONTO
      FROM SOL_EVENTOS SE
      WHERE SE.COD_EVENTO = :OLD.COD_EVENTO;

    select id_tipo
      into v_mov_premio
      from aho_tipo_movimiento
      where UPPER(nombre_tipo) like '%PAGO DE PREMIO/SUBSIDIO%';

    SELECT AM.ID_CUENTA
      INTO CUENTA
      FROM AHO_MOVIMIENTOS_CUENTA AM
      JOIN AHO_TIPO_MOVIMIENTO ATM
        ON ATM.ID_TIPO = AM.ID_TIPO
      WHERE ATM.ID_TIPO = 'A' AND
            ROWNUM = 1;

    INSERT INTO AHO_MOVIMIENTOS_CUENTA
    VALUES(MAX_ID,
           SYSDATE,
           MONTO * (:OLD.FECHA_HASTA - :OLD.FECHA_DESDE),
           v_mov_premio,
           CUENTA );
END INS_AFTER_UPD_PRICES;

Best of luck.


问:
How can I create Collapsible Column header in Data Table?
I have this Below Code. What I want is I want to make HR Information column and contact column to be collapsible by adding + and - symbol next to them name. How can I do it?</p>

```<code><link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"
   rel="stylesheet">
<link href="https://cdn.datatables.net/fixedcolumns/3.2.6/css/fixedColumns.dataTables.min.css"
   rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/fixedcolumns/3.2.6/js/dataTables.fixedColumns.min.js"></script>
<table id="example" class="stripe row-border order-column table table-condensed table-striped table-bordered" style="width:100%"  >
   <thead>
      <tr>
         <th rowspan="2">Name</th>
         <th colspan="2" class="header-1"  name="speed">HR Information <img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" /></th>
         <th colspan="4">Contact</th>
      </tr>
      <tr class="this_h">
         <th id="hrcolumn" class="x"  name="speed">Position</th>
         <th>Salary</th>
         <th>Office</th>
         <th>Extn.</th>
         <th>E-mail</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>Tiger Nixon</td>
         <td>System Architect</td>
         <td>$320,800</td>
         <td>Edinburgh</td>
         <td>5421</td>
         <td>t.nixon@datatables.net</td>
      </tr>
      <tr>
         <td>Garrett Winters</td>
         <td>Accountant</td>
         <td>$170,750</td>
         <td>Tokyo</td>
         <td>8422</td>
         <td>g.winters@datatables.net</td>
      </tr>
      <tr>
         <td>Ashton Cox</td>
         <td>Junior Technical Author</td>
         <td>$86,000</td>
         <td>San Francisco</td>
         <td>1562</td>
         <td>a.cox@datatables.net</td>
      </tr>
   </tbody>
</table>
$(document).ready(function() {
    var table = $('#example').DataTable({
        scrollY: "300px",
        scrollX: true,
        scrollCollapse: true,
        paging: false,
        fixedColumns: true
    });
});
th, td {
    white - space: nowrap;
    padding - left: 40 px!important;
    padding - right: 40 px!important;
}
div.dataTables_wrapper {
    width: 800 px;
    margin: 0 auto;
}
</code>```

答:
I don't think putting the icon next to the column name is the best idea, as when you hide the columns, the icon itself would be hidden.

Instead of this I have added two checkboxes above the table that will be of better use.

```<code><p>Toggle HR Info <input id="hrCheck" type="checkbox" /></p>
<p>Toggle Contact Info <input id="contactCheck" type="checkbox" /></p>
</code>```

I had to fix the colspan for the Contact column as it needed to be 3 instead of 4.

Here is a working jsbin: https://jsbin.com/kaloxokadu/edit?html,js,output

Body:
I have this Below Code. What I want is I want to make HR Information column and contact column to be collapsible by adding + and - symbol next to them name. How can I do it?

<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"
   rel="stylesheet">
<link href="https://cdn.datatables.net/fixedcolumns/3.2.6/css/fixedColumns.dataTables.min.css"
   rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

         Name
         HR Information
         Contact

         Position
         Salary
         Office
         Extn.
         E-mail

         Tiger Nixon
         System Architect
         $320,800
         Edinburgh
         5421
         t.nixon@datatables.net

         Garrett Winters
         Accountant
         $170,750
         Tokyo
         8422
         g.winters@datatables.net

         Ashton Cox
         Junior Technical Author
         $86,000
         San Francisco
         1562
         a.cox@datatables.net

$(document).ready(function() {
    var table = $('#example').DataTable({
        scrollY: "300px",
        scrollX: true,
        scrollCollapse: true,
        paging: false,
        fixedColumns: true
    });
});
th, td {
    white - space: nowrap;
    padding - left: 40 px!important;
    padding - right: 40 px!important;
}
div.dataTables_wrapper {
    width: 800 px;
    margin: 0 auto;
}

Body:
I don't think putting the icon next to the column name is the best idea, as when you hide the columns, the icon itself would be hidden.

Instead of this I have added two checkboxes above the table that will be of better use.

<p>Toggle HR Info <input id="hrCheck" type="checkbox" /></p>
<p>Toggle Contact Info <input id="contactCheck" type="checkbox" /></p>

I had to fix the colspan for the Contact column as it needed to be 3 instead of 4.

Here is a working jsbin: https://jsbin.com/kaloxokadu/edit?html,js,output


问:
What is an Object in Python?
I am surprised that my question was not asked (worded like the above) before. I am hoping that someone could break down this basic term "object" in the context of a OOP language like Python. Explained in a way in which a beginner like myself would be able to grasp.

When I typed my question on Google, the first post that appears is found here.

This is the definition:
An object is created using the constructor of the class. This object will then be called the instance of the class.

Wikipedia defines it like this:
An object is an instance of a Class. Objects are an abstraction. They hold both data, and ways to manipulate the data. The data is usually not visible outside the object.

I am hoping someone could help to break down this vital concept for me, or kindly point me to more resources. Thanks!

答:
Everything is an object

An object is a fundamental building block of an object-oriented language. Integers, strings, floating point numbers, even arrays and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string "hello, world" is an object, a list is an object that can hold other objects, and so on. You've been using objects all along and may not even realize it.

Objects have types

Every object has a type, and that type defines what you can do with the object. For example, the int type defines what happens when you add something to an int, what happens when you try to convert it to a string, and so on.

Conceptually, if not literally, another word for type is class. When you define a class, you are in essence defining your own type. Just like 12 is an instance of an integer, and "hello world" is an instance of a string, you can create your own custom type and then create instances of that type. Each instance is an object.

Classes are just custom types

Most programs that go beyond just printing a string on the display need to manage something more than just numbers and strings. For example, you might be writing a program that manipulates pictures, like photoshop. Or, perhaps you're creating a competitor to iTunes and need to manipulate songs and collections of songs. Or maybe you are writing a program to manage recipes.

A single picture, a single song, or a single recipe are each an object of a particular type. The only difference is, instead of your object being a type provided by the language (eg: integers, strings, etc), it is something you define yourself.

Title: What is an Object in Python?