Query very slow despite having indices

Question: I am using the following query which is very slow despite having indices, can someone help?
table a has close to 50k entries and table b about 2 million
i tried creating index on batchid in table 2 but it didnt help
select distinct x, y
from t1 a,t2 b
where b.batch_id = a.batch_id and b.sm_id = a.smid and b.status = 'new' and target_userid = *some value*
limit 10

here is the explain output
+----+-------------+-------+------+-----------------------------------+---------------+---------+------------------------------+---------+------------------------------+
| id | select_type | table | type | possible_keys                     | key           | key_len | ref                          | rows    | Extra                        |
+----+-------------+-------+------+-----------------------------------+---------------+---------+------------------------------+---------+------------------------------+
|  1 | SIMPLE      | b     | ALL  | smreconhistory_sm_id_status_index | NULL          | NULL    | NULL                         | 2033644 | Using where; Using temporary |
|  1 | SIMPLE      | a     | ref  | smid_batch_id,idx_batch_id        | smid_batch_id | 16      | sync.b.sm_id,sync.b.batch_id |       1 | Using where; Distinct        |
+----+-------------+-------+------+-----------------------------------+---------------+---------+------------------------------+---------+--------------------

index for table 1
+-----------------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table           | Non_unique | Key_name                   | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-----------------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| SMReconJobEntry |          0 | PRIMARY                    |            1 | id          | A         |       49323 |     NULL | NULL   |      | BTREE      |         |               |
| SMReconJobEntry |          1 | smreconjobentry_ugid_index |            1 | ugid        | A         |       49323 |     NULL | NULL   |      | BTREE      |         |               |
| SMReconJobEntry |          1 | smid_batch_id              |            1 | smid        | A         |       49323 |     NULL | NULL   |      | BTREE      |         |               |
| SMReconJobEntry |          1 | smid_batch_id              |            2 | batch_id    | A         |       49323 |     NULL | NULL   |      | BTREE      |         |               |
| SMReconJobEntry |          1 | idx_batch_id               |            1 | batch_id    | A         |       49323 |     NULL | NULL   |      | BTREE      |         |               |
+-----------------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+--

for table 2
+----------------+------------+-----------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table          | Non_unique | Key_name                          | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------------+------------+-----------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| SMReconHistory |          0 | PRIMARY                           |            1 | id           | A         |     2033644 |     NULL | NULL   |      | BTREE      |         |               |
| SMReconHistory |          1 | smreconhistory_sm_id_status_index |            1 | sm_id        | A         |          18 |     NULL | NULL   | YES  | BTREE      |         |               |
| SMReconHistory |          1 | smreconhistory_sm_id_status_index |            2 | status       | A         |          18 |     NULL | NULL   |      | BTREE      |         |               |
| SMReconHistory |          1 | gmailunit_id_foreign              |            1 | gmailunit_id | A         |     2033644 |     NULL | NULL   | YES  | BTREE      |         |               |
+----------------+------------+-----------------------------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

Comment: You've omitted some crucial information, such as the table definitions.  Also, what are `*value*` and `target_userid`?  Also, I've not seen `*value*` without quotes as a valid string literal in mysql (though it's been awhile since I used mysql).
Comment: Please [edit] your post and show the ***actual*** sql statement that is causing the issue.
Comment: @JimGarrison edited, target_userid is another column and value is any value i meant
Comment: Your low-cardinality index `smreconhistory_sm_id_status_index` does not contribute anything, as shown by the fact that the optimizer chose a full table scan instead of an index,  as explained [here](https://www.ibm.com/developerworks/data/library/techarticle/dm-1309cardinal/index.html)
Comment: @JimGarrison yes, this i have seen, should i create an index on batch_id then?
Comment: We cannot tell you, only you know the data distribution.  EXPERIMENT!!  You can find the optimal solution a lot faster than we can guess.
Comment: @JimGarrison you dont understand, i did try, i created an index on batch_id and also tried the combination of smid,batchid,status even then nothing works. Thats why i am posting here
Comment: `b.batch_id = a.batch_id and b.sm_id = a.smid`  -- table `a` has an index on `batch_id, smid`.  Why does table `b` not have one also?
Comment: @JimGarrison i did add batch_id index to table b too, but even that didnt help. thats what i was trying to convey
Answer: Do not use find_in_set, replace function, it will calculate every time, I would suggest to  use IN  with static values.
x IN ('a', 'b', 'c')

Comment: that find_in_set has nothing to do with performance, because even this query is slow
select distinct x, y
from t1 a,t2 b
where b.batch_id = a.batch_id and b.sm_id = a.smid and b.status = 'new' and target_userid = ***
limit 10
Comment: ok, then I suspect that distinct may cause performance issue, please have a try by removing it to check the difference.
Comment: Tried that already, thats not the culprit
Comment: checked the explain output,  rows value of second row is 1, probably your index doesn't work, could you also create a multiple columns index for table2 just like table1?

Query very slow despite having indices


Issue with Core Data attribute returning 0

Question:
Possible Duplicate:
Core Data not saving NSString.

Hey all!
Currently experiencing a weird issue with Core Data in my latest application. Basically what I'm accomplishing is that of parsing JSON and adding each object into Core Data under the respective attribute. This works fine as far as I can see from the NSLogs I have set in place. However, when it comes to displaying one of the values in a UITableView, it always returns 0 for some unknown reason.
Here is the function that I am using to store the objects into the Core Data entity.
-(void)syncNotes {

UIApplication *app = [UIApplication alloc];
app.networkActivityIndicatorVisible = YES;

NSDictionary *params = [NSDictionary dictionaryWithObject:authToken forKey:@"api_key"];

[[LRResty client] get:@"http://notacio.us/api/note" parameters:params withBlock:^(LRRestyResponse *response){

    if(response.status == 200) {
        NSLog(@"Successful Connection \n%@", [response asString]);

        // Create SBJSON object to parse JSON
        SBJSON *parser = [[SBJSON alloc] init];

        // parse the JSON string into an object - assuming [response asString] is a NSString of JSON data
        NSDictionary *object = [parser objectWithString:[response asString] error:nil];

        NSFetchRequest *noteFetch;
        NSManagedObject *newNote;

        appDelegate =(NotaciousAppDelegate *) [[UIApplication sharedApplication] delegate];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:appDelegate.managedObjectContext];
        NSArray *fetchedNotes;

        NSArray *notes = [object valueForKey:@"result"];
        for (NSDictionary *singleNote in notes){

            noteFetch=[[NSFetchRequest alloc] init];
            [noteFetch setEntity:entity];
            NSPredicate *pred=[NSPredicate predicateWithFormat:@"ID==%@",[singleNote objectForKey:@"note id"]];
            [noteFetch setPredicate:pred];

            NSError *fetchError=nil;
            fetchedNotes=[appDelegate.managedObjectContext executeFetchRequest:noteFetch error:&fetchError];

            if (fetchError!=nil) {
                NSLog(@"syncNotes fetchError=%@,details=%@",fetchError,fetchError.userInfo);
            }
            if ([fetchedNotes count]==0) {

                NSString *notelocked = [singleNote objectForKey:@"note locked"];

                NSString *notecreated = [singleNote objectForKey:@"note created"];
                NSString *noteupdated = [singleNote objectForKey:@"note updated"];
                NSString *notetitle = [singleNote objectForKey:@"note title"];
                NSString *notesummary = [singleNote objectForKey:@"note summary"];
                NSString *noteid = [singleNote objectForKey:@"note id"];
                NSString *notecontent = [singleNote objectForKey:@"note content"];

                NSLog(@"Note Title: %@",notetitle);
                NSLog(@"Note Summary: %@",notesummary);
                NSLog(@"Note ID: %@",noteid);
                NSLog(@"Note Content: %@",notecontent);
                NSLog(@"Note Created: %@",notecreated);
                NSLog(@"Note Updated: %@",noteupdated);
                NSLog(@"Note Locked: %@",notelocked);

                newNote = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:appDelegate.managedObjectContext];
                [newNote setValue:notecontent forKey:@"content"];
                [newNote setValue:notesummary forKey:@"summary"];
                [newNote setValue:notetitle forKey:@"title"];
                [newNote setValue:noteid forKey:@"ID"];
                [newNote setValue:notecreated forKey:@"created"];
                [newNote setValue:noteupdated forKey:@"updated"];
                [newNote setValue:notelocked forKey:@"locked"];

                NSError *error = nil;
                if (![appDelegate.managedObjectContext save:&error]) {
                    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                    abort();
                }

            }

        }

        [noteFetch release];
        app.networkActivityIndicatorVisible = NO;

    }

    if (response.status == 404) {
        NSLog(@"FAIL\n%@", [response asString]);
        app.networkActivityIndicatorVisible = NO;
    }

}];

}

So the NSLog's from me outputting the strings that represent that of the objects parsed from the JSON and that are going to be stored are as follows.
2011-03-31 10:52:23.334 Notacious[755:707] Note Title: Business Draft
2011-03-31 10:52:23.335 Notacious[755:707] Note Summary: Make sure you get one to Pez by end of w
2011-03-31 10:52:23.336 Notacious[755:707] Note ID: 676
2011-03-31 10:52:23.336 Notacious[755:707] Note Content: Business Draft
Conclusion is about 150 words, the rest is for the body of the report.
2011-03-31 10:52:23.337 Notacious[755:707] Note Created: Thu Feb 24 17:02:13 -0800 2011
2011-03-31 10:52:23.339 Notacious[755:707] Note Updated: Thu Feb 24 17:10:43 -0800 2011
2011-03-31 10:52:23.339 Notacious[755:707] Note Locked: 0

As you can see, there are values set for everything. However, my issue gets a little weird here. When setting up the UITableViewCell and I try to grab the value for updated, it returns 0. I am calling the value like this:
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

NSLog(@"%@",[[managedObject valueForKey:@"title"] description]);
NSLog(@"%@",[[managedObject valueForKey:@"updated"] description]);

NSString *updated = [[managedObject valueForKey:@"updated"] description];
NSString *parsedDate = [NSDate getNoteTime:updated];

NSLog(@"Before Format: %@",updated);
NSLog(@"After Format: %@",parsedDate);

Which in turn logs the following:
2011-03-31 10:56:22.544 Notacious[755:707] Business Draft
2011-03-31 10:56:22.545 Notacious[755:707] 0
2011-03-31 10:56:22.548 Notacious[755:707] time0
2011-03-31 10:56:22.549 Notacious[755:707] note:0, current:1301531182
2011-03-31 10:56:22.550 Notacious[755:707] Before Format: 0
2011-03-31 10:56:22.550 Notacious[755:707] After Format: ********

As you can see, the updated string returns 0. Can anyone shed any light as to why this would be happening?
EDIT
I tried to do it with the created valueForKey instead, and you'll never guess what happened. It worked perfectly fine. So the only thing I can think of is if when we're saving the value to the Core Data attribute, it isn't saving properly. Which is weird, because both the created and updated attributes are NSStrings. Actually, everything in the Core Data entity are NSStrings.
Comment: Well, I'm not the best with CoreData but it seems to me your pulling the data twice. It looks like your trying to pull the updated string twice. I doubt that is the error but it doesn't look like you dot nned that. Also, you can shorten this 'UIApplication *app = [UIApplication alloc];
app.networkActivityIndicatorVisible = YES;' up to this '[[UIApplication shared application] setNetworkActivityIndicatorVisible:YES]; I think thats how it is or its [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Answer: The most likely explanation is that you have a mismatch between the object classes returned by the dictionary and the objects expected by the entity. E.g. noteUpdated is supposed to be a date but there is nothing in the code that enforces that. If you try to set a date using a string value it cannot parse, the date may report a value of zero. You should check the classes returned by the dictionaries to see if they are appropriate for the attributes they are assigned to.
Also, this use of description is unnecessary:
NSLog(@"%@",[[managedObject valueForKey:@"title"] description]);

... because NSLog sends the description message anyway. What you have here is the description of a string returned by description. That may or may not accurately reflect the value of the object. Just use:
NSLog(@"%@",[managedObject valueForKey:@"title"]);

When troubleshooting, I would recommend printing the managed objects directly like so:
NSLog(@"%@",manageObject);

... which will let you see everything in it's more raw state.
Comment: The issue is however, diminished if I use the "created" valueForKey. Which is set exactly the same way in the pulling of the notes. It is odd and makes no sense that one doesn't work, yet the other works perfectly.
Comment: Eliminate possible logging errors first and foremost. Just logging the object itself directly will show you all the attribute/property values as the object holds them. If they show correctly there, then its just a logging error. If not, then the problem is where you set the attribute/property values.
Comment: When I do NSLog(@"%@",managedObject); it likes to spit out the following error. terminate called after throwing an instance of 'NSException'
Program received signal:  "SIGABRT". So I can't actually see what is happening...
Comment: If you have a managedObject you should be able to log it directly. If your getting an error still then you've got something else entirely going on.
Comment: Hmph, very weird thing going on.


(Nested) cross-validation for model selection and optimization?

Question: I try to solve a binary classification problem.
I have a set of features to build a model. The simplest model just pics a single feature $f$ and optimizes a cutoff $c_f$ to separate the two classes.
Question 1:
Can I think of the feature to select and its corresponding cutoff as of 2 parameters to be optimized and run the whole process in a standard k-fold cross-validation loop?
I.e. I do an exhaustive search of all possible feature/cutoff combinations on the training folds, select the one combination with best performance and evaluate it on the test fold. By averaging over all test folds, I get the estimate for the expected performance on unseen data for a model trained the same way on the whole data set.
Or would I rather need to split feature selection and cutoff optimization already in a nested cross-validation?

Now I want to extend the model to two features $f_1, f_2$ that will be logically combined to define the classification model. So I will fit two cutoffs $c_{f_1}, c_{f_2}$ and predict the class of a case $x$ as $\text{class}(x) = f_1(x) \geq c_{f_1} \land f_2(x) \geq c_{f_2}$.
Again, I would take all possible combinations of two features and their cutoffs, identify the one combination performing best on the training folds, and apply it to the test fold.
Question 2:
Can I think of the number of features $n$ to include (1 or 2) as of a hyperparameter of my model?
For model selection, i.e. optimization of $n$, I would then run a nested cross-validation. The inner CV uses the above described process to identify the best univariate ($n=1$) model on the inner training folds and evaluate its performance on the inner test fold. The same for the bivariate models ($n=2$). Then I would rank them (the top-candidate from $n=1$ and the top-candidate from $n=2$) according to their performance estimate from the inner CV, and select the best one to apply it to the outer test fold.
Then I would finally run the inner CV on the whole data set to get the final model. The average performance on the outer test folds would then serve as a unbiased estimated of the expected performance of this final model on unseen data.
Is this a valid setup?
Answer: Your validation strategies are valid.
Essentially cross validation does not estimate the error of models, but the method to build them. So if you encompass all steps in each fold, your estimation is unbiased.
In your case, it shows that you want to perform feature selection in the 1st question, and feature selection as well as model selection in the 2nd question. Because you independently perform these tasks in each fold, your estimation will be unbiased.


How to create a taxonomy terms "skills" with level "low", "medium", "high"

Question: I'm trying to create a field that allows you to add your skill from a select list, and the level of your skill.
i.e.
skill football, level medium.
I may create the taxonomy in this way
Football
-Low
-Medium
-High
and the use hierarchical taxonomy but it means that I need to add the level per each term.
Is there a way to attach a vocabulary to another vocabulary? in this way I may create a vocabulary skills with all the skills and one vocabulary level with 3 terms.
Is there a module or a better technique?
Thanks in advance
Comment: you can use 2 separate vocabularies for this as well.
Comment: I second @AyeshK that would be the way to go.
Answer: Without knowing how you're planning to use this in a larger context, here's what I would do:

Create a vocabulary (or possibly just a plain text field with a select list) for "skill"
Create a second field with a dropdown list for skill level (I probably wouldn't use a taxonomy for this).
Make the second field dependent on the first, per this Stackoverflow question about fieldsets and conditions
Answer: Yes, that type of field configuration is possible with
http://drupal.org/project/conditional_fields

version is -dev for D7 but works well.


Will leaving the G string off an acoustic guitar for a few days hurt the guitar?

Question: I was playing my acoustic guitar when the string popped right off - it was time for a string changing anyways.
However, I won't be able to get strings for another two days. Will this hurt the guitar (warping the neck, etc.)? If so, would it be possible to tune the other strings up to compensate for the lost tension, to minimize damage?
Answer: It is unlikely to make a bit of difference. Note there some, notably Keith Richards, who consistently play with one string removed. (OK so it's not the same string.) Don't worry.
The biggest worry would be if you have a movable bridge, with greatly reduced tension on most of the strings, the bridge of such a guitar could move. Secondly if you try to twist the neck by detuning three strings on one side, you probably can... after a long time period.
Commonly damage to guitars comes from dehydration, this too will often take time to accomplish.
Comment: @Cbagdon You are welcome, and welcome to the site. Accepting the answer is another way to say that.
Comment: Worries of this sort may come from string instrument considerations (violas and violins (for example) have sound posts inside the body of the instrument that can come loose when the tension on the instrument is loosened, and they do have a movable bridge as well.).
Answer: The short answer--leave it alone, restring it when you can, and if you happen to notice any issues then give the guitar a day or two before making adjustments so that the replaced string can reverse the effect.
The reason that it's not a problem is that the tension which was held by the broken string has been transferred to the remaining strings.  The overall tension on the neck is more or less unchanged and the distribution of tension is changed very little as well.
Comment: ...and if by chance any further work is needed then it would most likely just be a truss rod adjustment, which is normal upkeep (mine get adjusted a couple times a year to compensate for the seasons)
Comment: Where in the world do you live for that to be needed? What a pain in the neck...
Comment: @STW You may be able to mitigate the need for constant adjustments by humidifying the guitar. If you are in a climate where it has a cold winter then the time to humidify is basically when ever the heat in your home is on. If you are in a desert then you are stuck with humidifying on a constant basis. AC can remove humidity from the air, but it is not as bad as heat. I find some of my guitars are thirstier than others (type of wood, type of finish perhaps)
Comment: I live pretty far north and I'm cheap with my heating bill--so even if the relative humidity is kept constant the actual moisture in the guitar rises and falls.  The truss rod doesn't have to be adjusted, but it makes a small yet noticeable improvement.  For high end instruments, especially acoustics, doing a setup at least once a year is good practice.
Comment: @STW It is also true that in cold conditions the air holds less moisture (constant relative humidity numbers can actually mean different amounts of moisture content depending on temperature) and in a consistently cold environment guitars can become dryer then what is desirable. Adjustments many times a year seems excessive to me, especially if we are talking truss rod adjustments each time. Also the type of heat can be a factor. Radiators are nicer than central air, and you never need to humidify if you have steam heat (not many do any more).
Comment: It sounds nice to say that we need to do a set-up once a year, but I think there is allot of mitigation to that. I know when my guitar is out, and when it needs help. Once a year is excessive for most of my instruments. It is more or less true when you talk about different types of guitars, and different types of set-ups. For example, I could see setting up a Floyd Rose system or even an electric guitar quite often. Classical guitars are quite stable and rarely need professional help (there is not much to do but re-dress the frets, even if things go south).
Comment: BTW, despite my ramblings, I do judge your answer to be sound.
Answer: When a string breaks, the change in tension will not damage the guitar, but it will cause all the other strings to go slightly out of tune, so if you continue playing you may want to check the tuning. The more flexible the instrument is, and the thicker the strings, the more it will be detuned by the loss of a string. For example, an electric guitar with thin neck and heavy strings (more flexible and under more tension) will change much more than a classical guitar with nylon strings (more rigid and under less tension).
For the same reason, if you tune the strings from top to bottom, if there were some big changes after you finish you may need to go again from top to bottom once or twice again, because changing the tension of the last strings you tune will affect the tuning of the strings you tuned before.


How are Just-Tuned scales beyond those of 12-notes constructed?

Question: I was experimenting with what ratios come up when one continues on the Pythagorean cycling of fifths, and came up with the following chart:

Those ratios beyond the 12-note Pythagorean scale are shown in red. Now, two things come to mind here. I was trying to construct a proper 19-EDO scale. Now, what I noticed is that in the 12-EDO Justly-tuned scaled, there are of course 13 actual ratios, since due to the fundamental theorem of arithmetic, the cycling of fifths can never converge together, thus creating the infamous wolf interval. However, it seems that such a wolf-interval can't really occur in the same way at the ends of the 19-EDO scale. The reason being that 19 is an odd number. With 12-EDO, we get 13 different ratios, 6 in both "directions" plus 1:1, unison. With 19-EDO can't do cycle through an equal number of times in both directions and end up with 20 (i.e. 19+1) different ratios.
I guess my main question is that, is this indeed how the 19-EDO Pythagorean scale should be constructed? Furthermore, what becomes of the wolf-interval caused by the non-equivalence of 588.27¢ and 611.73¢ ? It's not like taking the process further causes these ratios to somehow disappear. Is there a wolf-interval peculiar to 19-EDO? Or is there something special about 12-EDO in that respect?
Comment: One thing you can do is to take the 19-tone scale and select the 12 closest notes to just tuning. Or use a 31 or 53 tone scale.
Comment: (a) I think that there are some typeoes in your question, e.g. I don't understand what "bother directions" are. Even so, I don't really understand what you specific answerable question is.
Comment: @Dave meant to say "in both directions", just a typo, fixed
Answer: Your diagram indeed shows a 19-pitch Pythagorean scale.
19 just perfect fifths exceed 11 octaves by an interval of frequency ratio 319:230. This interval is about 137.145 cents. If you want to divide the octave into 19 and have a closed circle of 19 fifths, then your 19 fifths, however you temper them, will add up to exactly 11 octaves. So the question is how to share that 137.145 cents among the 19 fifths. The tuning system you give in your diagram has 18 just fifths, which implies that the other fifth (between the pitches you label "9" and "-9" is narrowed by the full 137.145 cents. This makes it 564.81 cents -- much narrower even than a tritone! There's your wolf.
19-EDO of course shares out the 137.145 cents equally among the 19 fifths, narrowing each one by 7.218 cents.
One thing you might consider is to pick a number of divisions where the amount to temper is less. For example 53 (as suggested by ttw in a comment). 53 just perfect fifths exceed 31 octaves by an interval of frequency ratio 353:284. This interval is about 3.615 cents -- a much smaller wolf. 53-EDO shares that equally among the 53 fifths, narrowing each one by 0.068 of a cent.


File field fails to upload any files

Question: I've been having an issue with a file field that is not accepting any file uploads -- it ends up returning a 500 ISE on the specific field call (see image of the returned upload error). 1
The actual field itself is left over from a Database import of the site on an Acquia Cloud install. I know that it may be possible to re-create the field, but we stand the risk of losing existing records. Server configuration wise, it looks like the file directory is writable by httpd, so I don't see any issues there.
It doesn't help that the Acquia logs don't give anything useful. Any ideas?
Answer: Check the size of the files, maybe they are to big. Check the max. file sizes on your server and in Drupal!.
PHP configuration check:
check the following parameters:
post_max_size
upload_max_filesize
If these values are to small, you have to change them on your server in your PHP configuration (for example php.ini)
Comment: I don't think it's going to be size or permissions related, those issues usually return a friendly drupal error message rather than resulting in a 500 error.
Comment: He has a point. We have pretty high settings for those already on Acquia Cloud. I'm wondering if they know something I don't. The files are typically under 2MB with a max size of at least 256 MB. Size isn't the issue.

File field fails to upload any files


How to add rows with 0 counts to summarised output

Question: I have added sample data below, I have used dplyr to count on Rco and month:
structure(list(Rco = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 4L, 4L, 4L), .Label = c("A220", "B334", "C123", "D445"
), class = "factor"), month = structure(c(3L, 2L, 4L, 1L, 3L,
2L, 4L, 1L, 3L, 4L, 2L, 4L, 3L), .Label = c("Apr", "Feb", "Jan",
"Mar"), class = "factor"), count = c(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13)), .Names = c("Rco", "month", "count"), row.names = c(NA,
-13L), class = "data.frame")

Is there a way to transform this data to:
structure(list(Rco = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("A220", "B334",
"C123", "D445"), class = "factor"), month = structure(c(3L, 2L,
4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 2L, 4L, 1L), .Label = c("Apr",
"Feb", "Jan", "Mar"), class = "factor"), count = c(1, 2, 3, 4,
5, 6, 7, 8, 9, 0, 10, 0, 13, 11, 12, 0)), .Names = c("Rco", "month",
"count"), row.names = c(NA, -16L), class = "data.frame")

So basically I need to add extra rows for all months that have missing count, because dplyr::count does not give 0 counts if a month - Rco combination does not exist.
The number of months is variable in my data ( I have shown Jan Feb Mar Apr but it could be for all 12 months as well) , so please if someone can provide me a dynamic solution, I would be grateful.
Comment: related Q&A: https://stackoverflow.com/questions/23451372/add-rows-to-grouped-data-with-dplyr
Answer: You can use tidyr::complete and specify the fill to be 0 (instead of the default NA):
library(tidyr)
complete(df, Rco, month, fill = list(count = 0))

Comment: Thanks a lot docendo.
Answer: We can use expand.grid on the unique values of the first two columns, and merge with the initial dataset.  This will fill NA for combinations that are not present in the expand.grid.
res <- merge(expand.grid(lapply(df1[1:2], unique)), df1, all.x=TRUE)

But, it is easy to change the NA to 0
res[is.na(res)] <- 0


como colocar o retorno de um json em um lugar especifico de uma tabela?

Question: Tenho uma tabela fixa com horarios das 08:00am até as 19:00pm cada tem sua linha com sua descrição(que seria o tipo de consulta)
recebo um json na minha pagina ao selecionar uma data no meu jQuery datepicker que vem com as informações do banco de dados.
neste banco o que nos importa é o horario da consulta e o tipo dela..
O que preciso fazer é checar neste retorno os horarios e colocar a descrição dele no seu devido lugar da tabela. por exemplo: tenho 2 consultas, uma as 08:00am e outra às 17:00pm (lembrando que cada uma tem sua descrição). Preciso colocar essas descrições na tabela que já esta criada nos horarios 08:00 e 17:00.. quanto aos outros horarios deixar vazios
Segue meu código:

html

<!doctype html>

        <meta charset="UTF-8">
        <title>Agenda</title>

        <link type="text/css" rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css" media="screen">

        08:00

        8:30

        9:00

        9:30

        10:00

        10:30

        11:00

        11:30

        12:00

        12:30

        13:00

        13:30

        14:00

        14:30

        15:00

        15:30

        16:00

        16:30

        17:00

        17:30

        18:00

        18:30

        19:00

javascript

retornar_data.php

<?php

     $date = $_POST['date'];

    $conecta = mysqli_connect("localhost","root","","odonto");

    $selecao = "SELECT * from agenda WHERE dataAgenda = '{$date}' ";
    $categorias = mysqli_query($conecta,$selecao);

    $retorno = array();
    while($linha = mysqli_fetch_object($categorias)) {
        $retorno[] = $linha;
    }

    echo json_encode($retorno);

    // fechar conecta
    mysqli_close($conecta);
?>

exemplo do meu json retorno

[{"agendaId":"2","dentistaId":"1","dataAgenda":"2015-12-02","horaAgenda":"08:30","descricaoAgenda":"Restauracao"},{"agendaId":"3","dentistaId":"2","dataAgenda":"2015-12-02","horaAgenda":"09:00","descricaoAgenda":"Protese"}]

Answer:

    Agenda

        08:00

        8:30

        9:00

        9:30

        10:00

        10:30

        11:00

        11:30

        12:00

        12:30

        13:00

        13:30

        14:00

        14:30

        15:00

        15:30

        16:00

        16:30

        17:00

        17:30

        18:00

        18:30

        19:00

Comment: Pode nos expplicar melhor como isso poderia responder a pergunta?
Comment: @Danilo Primeiro eu percorri o json de retorno, depois para cada registro do Json, eu percorri a tabela comparando os horários do registro com cada linha da tabela
Comment: @Danilo esse trecho do código que executa todo o processo $.each(data, function(i, item) {

                    $('#tableSchedule tr').each(function (x, el) {

                        var tr = $(el).find('td');

                        var hora = $(tr[0]).text();
                        var descricao = $(tr[1]).text();

                        if (hora.length == 4) hora = '0' + hora;

                        if (hora == item.horaAgenda)
                            $(tr[1]).html(item.descricaoAgenda);

                    })
                })
Comment: podes colocar isso na sua resposta para que os usuários vejam melhor a sua solução?


Python EasyGUI fileopenbox() filter more items

Question: I want to set EasyGUI fileopenbox() to filter more filetypes and not just one.
Here below is a code I tried but instead of custom files selection i get more selections.
file=easygui.fileopenbox(title='Select image', filetypes=('*.png', '*.jpg'))

How to fix this?
Answer: From docs

About the "filetypes" argument
If specified, it should contain a list of items, where each item is
either:

a string containing a filemask # e.g. "*.txt"

a list of strings, where
all of the strings except the last one are filemasks (each beginning
with ".", such as ".txt" for text files, "*.py" for Python files,
etc.). and the last string contains a filetype description

EXAMPLE:
filetypes = ["*.css", ["*.htm", "*.html", "HTML files"]  ]

So corresponding to your usecase, you can write:
file=easygui.fileopenbox(title='Select image', filetypes=[["*.png", "*.jpg", "Image files"]])


How to restore mongo db data from old files?

Question: my server crashed... I don't have a recent backup but I do have access of the files. I'm wondering If I can restore data from the old mongodb folder? any suggestions?
Comment: just copying the old files from /var/lib/mongodb worked but I had to fix the permissions
Answer: You can get query logs mongodb.log file if your profiling level set  for logging any queries. If not, you can't restore.


Fatal error when adding row-actions (Wordpress)

Question: I am creating a table by extending the class WP_List_Table. But when i want to add the actions "edit" and "delete" into my rows i do get an error:

Fatal error: Cannot use object of type stdClass as array in
  C:\xampp\htdocs\norskeanalyser\wp-content\plugins\aksjeanalyser\aksjeanalyser.php
  on line 228

And this is how my function looks:
function column_col_name($item){
         $actions = array(
        'edit' => sprintf('Edit',$_REQUEST['page'],'edit',$item['id']),
        'delete' => sprintf('Delete',$_REQUEST['page'],'delete',$item['id']),
    );
    return sprintf('%1$s %2$s', $item['name'], $this->row_actions($actions) );
}

Line 228 is this one: 'edit' => sprintf('Edit',$_REQUEST['page'],'edit',$item['id']),
Maybe it has something to do with $_REQUEST['page']?
Thanks for your help!
Answer: Can you var_dump($item)?
I believe your $item is not an array.
Try using $item->name, $item->ID instead of $item['name'], $item['id']
If you want to get some property from the object, you need to use the
$object->property

syntax, not $object['property']
Answer: You need to use some thing like this
'edit'    => sprintf('Edit', $_REQUEST['page'], 'edit',$item->id)
Comment: but when i now click on "Delete", i come to a page which says i haven't capability to access this page. Why this?
Comment: You are logged in from admin account or user account?
Comment: Did you also change
`'delete' => sprintf('Delete',$_REQUEST['page'],'delete',$item->id)`
Comment: Did you add delete
function `function process_bulk_action() {
global $wpdb;
if( 'delete'===$this->current_action() ) {
$id = $_REQUEST['id'];
$ids = '';
if(is_array($id)) {
foreach($id as $k=>$v) {
$ids .= $v . ",";
}
$ids = substr($ids, 0, -1);
} else {
$ids = $id;
}
if($ids != '') {
                $wpdb->query( "DELETE FROM `".$wpdb->prefix."users` WHERE ID IN ($ids)" );
   }

  }

 }
`
Comment: this function needs to call like `$this->process_bulk_action();` in query function where you set query for fetching records
Comment: I am logged in as admin user and i did also the changes you have mentioned above  but it doesnt help. Im still getting the same error.
Comment: Can you send me file or paste here full code of  file so i can take a look


Chamar classe construtor

Question: Na verdade, dessa forma, está muito errado? Não estou entendendo muito a tipagem:
class FinanceiroController extends Controller
{

    /**
     * @var ChamadosFinanceirosRepository
     */
    private $chamadosFinanceirosRepository;
    /**
     * @var FinanceiroService
     */
    private $financeiroService;
    /**
     * @var ChamadosFinanceirosService
     */
    private $chamadosFinanceirosService;
    /**
     * @var ChamadosParcelasPagasService
     */
    private $chamadosParcelasPagasService;

    public function __construct(ChamadosFinanceirosRepository $chamadosFinanceirosRepository, FinanceiroService $financeiroService,
                                ChamadosFinanceirosService $chamadosFinanceirosService, ChamadosParcelasPagasService $chamadosParcelasPagasService)
    {
        $this->chamadosFinanceirosRepository = $chamadosFinanceirosRepository;
        $this->financeiroService = $financeiroService;
        $this->chamadosFinanceirosService = $chamadosFinanceirosService;
        $this->chamadosParcelasPagasService = $chamadosParcelasPagasService;
    }
    public function getProvisionamentoPrestador()
    {
        return view('financeiro.provisionamentoPrestador');
    }
    /**
     * @return mixed
     * Busca os chamados financeiros com status_provisionamento_sac finalizado
     */
    public function getBuscaPrestadoresFinanceirosSac()
    {
        return $this->chamadosFinanceirosService->buscaProvisionamentosSac(['status_provisionamento_sac','finalizado']);
    }
    /**
     * @return mixed
     * Busca os chamados financeiros pelo id financeiro
     */
    public function getBuscaPrestadoresFinanceirosSacId()
    {
        //return $this->chamadosFinanceirosService->buscaProvisionamentosSac(['id',\Request::input('id')]);
        return $this->financeiroService->buscaProvisionamentosSac(['id',\Request::input('id')]);
    }

    public function postGravaPagamentoPrestadorChamado()
    {
        return $this->chamadosParcelasPagasService->pagamentoPrestadorChamado(\Request::all());
    }

}

Comment: Não, forçar a tipagem ou não, não vai instanciar o objeto. somente com o new mesmo.
Comment: Você não está chamando a classe no construtor. Você está induzindo o tipo que será aceito por parâmetro
Comment: Mais posso trabalhar dessa forma ao invés de instanciar ?
Comment: Mais eu consigo acessar os métodos dessa classe !
Comment: Estamos falando da classe que é dona do construtor ou da classe do parâmetro? Pois ao forçar a tipagem faz sua IDE começar enxergar o que tem naquela variável pois ele tem certeza qual vai ser a classe dela, dai ele disponibiliza pra ti os métodos.
Comment: Se você estiver falando do $this->classe, você tem que instanciar o objeto antes de passar por parâmetro.
Comment: Se eu fuzer assim funciona $this->classe->método()
Answer: Nesse caso você está forçando a tipagem do parametro para uma classe do tipo "Classe".
A vantagem é que você garante o tipo de dados e pode trabalhar melhor com o polimorfismo e garantir a integridade do sistema.
A desvantagem é que se você por algum motivo quiser passar outro tipo de dado vai precisar re-escrever o método.
Mas essa desvantagem na verdade é uma má estruturação do código pois essa é a melhor maneira de trabalhar e escrever um código limpo e claro.
Answer: Você não está chamando a classe no construtor. Você está induzindo o tipo que será aceito por parâmetro.
Veja para que serve a sua declaração:
class X {

   private $classe;

    public  function __construct(Classe $classe)
    {
           $this->classe = $classe;
    }
}

Nesse caso, você está dizendo que somente a instância de Classe será aceita por parâmetro no construtor.
Veja:
 new X(new Classe);

Se você tentar passar um outro valor qualquer, isso gerará um erro:
new X(1);

Saída:

X::__construct() must be an instance of Classe, integer given.
Answer: Para que a classe FinanceiroController seja instanciada, ela precisa receber 4 parâmetros em seu construtor, o tipo que é induzido é o nome das classes que você precisa utilizar, sendo uma delas é do tipo repositório e as outras três do tipo de serviços. Geralmente essas classes são ramificadas dentro do seu projeto /entity/entities/ e /service/services/.
Para entender melhor o conceito, sugiro que você procure estudar Design Patterns e Strategy Patterns.
Se já está acostumado com inglês, aqui tem um site muito bom:
https://sourcemaking.com/design_patterns/strategy
Se prefere algo em português, tem esse site também que é excelente:
http://br.phptherightway.com/pages/Design-Patterns.html
Para entender esse tipo de indução, na documentação do PHP tem mais informações:
http://php.net/manual/pt_BR/language.oop5.typehinting.php
Comment: Isso eu entendo, o que não entendo é que se eu consigo acessar os métodos da classe tipando ela dessa forma pra que instanciar ?

Chamar classe construtor


Webform as homepage

Question: Im using the webform module to create some reports.
I have only 2 pages available to users : submit a report and view existing reports.
Is there any way of making the "submit a report" page the default homepage ? ( right now it's a navigation item and i have the "add new content" link in the homepage)
I use a custom content-type for the form. Not sure if this is relevant or not.
Answer: Of course you can - just enter the path alias in admin/config/system/site-information or enter node/[your webform node ID] instead.
Comment: Thank you! ( waiting on the timer to allow me to mark this as the correct answer )
Comment: You're welcome - sometimes simple things aren't intuitive at first glance.

Webform as homepage


How does retired hurt and absent hurt affect career average?

Question:
If a batsman has retired hurt while batting, will this inning be added as an inning in his statistics (Does it affect his career batting average)?
What about the innings count in the case of absent hurt?
Answer: Law 2 in the ICC Law Book states that,

Batsman retiring
A batsman may retire at any time during his innings when the ball is dead. The umpires, before allowing play to proceed shall be informed of the reason for a batsman retiring.
(a)    If a batsman retires because of illness, injury or any other unavoidable cause, he is entitled to resume his innings subject to (c) below. If for any reason he does not do so, his innings is to be recorded as 'Retired - not out'.
(b)    If a batsman retires for any reason other than as in (a) above, he may resume his innings only with the consent of the opposing captain. If for any reason he does not resume his innings it is to be recorded as 'Retired - out'.
(c)    If after retiring a batsman resumes his innings, it shall be only at the fall of a wicket or the retirement of another batsman.

Retired Hurt:
If a batsman falls ill or gets injured while batting, he may retire with the umpires permission. At the end of the teams innings, if this batsman does not return to bat, he is considered 'Retired Hurt' and is considered not-out. Statistics-wise, the runs scored by him will be added to his career total as well as the innings. However, as average is calculated by "Runs scored / ( Innings - Not outs )", the denominator would not be affected by this game, as he is still not out. As long as he has scored a run or more before retiring hurt, it effectively means his career average will be better at the end of the game than it did at the start of it.
Absent-Hurt:
This is a scenario where a batsman is not able to come to the pitch to bat even without facing a ball, due to prior illness or injury. In this case, no runs will be added to his career stats and therefore, will not affect this average as neither will the (Innings - not outs) change. So, his batting average prior to the game is the same as that at the end of it.
Retired out:
If a batsman retired without the umpire's consent and if he does not have permission from the opposing captain, then he is considered 'Retired-out'. This is considered as a dismissal. Only two batsmen have retired out in an international cricket Test match. Both instances occurred in the same match, with the Sri Lankan batsmen Marvan Atapattu and Mahela Jayawardene retiring out.
Answer: Retired hurt will count in the innings as notout and Absence hurt will count as match played but not as an innings.


How to extract individual tensors from a batch of tensors?

Question: I am trying to upsample a bilateral grid using a guidance map (following this research paper).
I have created a Keras layer which takes 3 inputs and will provide the upsampled image:

BilateralGrids of shape (None, 16, 16, 96)
GuidanceMaps of shape (None, 256, 256)
InputImages of shape (None, 256, 256, 3)

Here, 'None' is the batch size which will be decided at runtime.
My motive is to perform pixel-wise computations as follows:
def slicing(BilateralGrids, GuidanceMaps, InputImages):
  output_images = []
  for i in range(batchSize):
    grid = BilateralGrids[i]
    guide = GuidanceMaps[i]
    input_img = InputImages[i]

    output = performPixelwiseComputation(grid, guide, input_img)
    #output.shape => (256, 256, 3)
    output_images.append(output)

  return output_images #output_images.shape => (BatchSize, 256, 256, 3)

The problem is we cannot run a loop over batch size since it is unknown.
I tried following things but nothing solved the problem:

Initially I thought lambda layer will provide inputs one by one, but it provides the complete batch.
Then I tried zip() in python, but it cannot work on tensors. [I need exactly something like zip()]
I tried tf.stack(), but it needs all the shapes and ranks of the tensors to be exactly same (which is not possible in my case)

PS: This is my first StackOverflow question. I apologize if it is not asked in an ideal way.
Comment: Is there no way that `performPixelwiseComputation` can be used on the whole batch at once using tensorflow ops? Otherwise, this seems to me like a good opportunity to write your own kernel and design whatever operation you need on the whole batch.
Comment: @Sunreef No, tensorflow default ops do not work for me. The pielwiseComputation need to access each pixel from each of the inputs, and since they are of different dimensions I need to write my own computation.

I do not have any idea or experience about writing our own kernel. I have seen some code in C++ which created their kernel, but other than tracking the flow of code I was not able to understand the working. Can you please forward me to some links where I can find more information about that. Also, can we write our kernel in Keras or tensorflow, or we must work in C++ for that?
Comment: Do you require that the batch size to be unknown to the function? Can you use a fixed batch size like 32 or so?
Comment: I would prefer it to be unknown and decided at runtime, but for testing purpose, I can try with a fixed batch size.

Can you tell how to fix a batch size, as I thought it was internally taken care by keras, and we do not have a control on that.
Comment: @AparSinghal  To create your own operation in C++, I found [Tensorflow tutorial](https://www.tensorflow.org/extend/adding_an_op) to be informative enough.
Comment: Okay, I will go through it and update if it solved my problem.
Answer: What you need is tf.py_func, link
Basically, you need to write a custom function to cover your need. However, tensorflow is a symbolic framework. That prevents you to declare custom operations as you write normal python. You can access, modify and do whichever operation that you want to do through py_func 'hack'. However, you also may need to define back-propagation layer and calculations if you have any decision algorithms in ff network. Also, it is quite tricky and hard to debug this approach.
Alternatively, try a define-by-run framework like Chainer. So that, you can run your network as you type.


Why add "keep state" to pf firewall rules

Question: If pf is a stateful firewall and keeps state by default, why do so many rulesets explicitly mention keep state?
Answer: Without examples or asking the people who create the configurations, at least two reasons might be copying known working configurations without understanding the configurations or a partial configuration from a tutorial example where keep state is required while other configurations are unknown, such as set state-defaults.
Answer: To complement Paul's answer - I looked this up from the OpenBSD pf documentation:

The keep state option is the implicit default for all filter rules. Despite this, when specifying stateful options, one of the state keywords must still be used in front of the options.


How to upgrade ubuntu 14.04 to openssl version 1.0.1s or 1.0.2g , which will be released on 1 March 2016

Question: I have some prod servers which are running with openssl version as 1.0.1f-1ubuntu2.16 . Since on 1 March 2016 a new ssl version will be released which will cover a majority of HIGH severity bugs, How do i upgrade my prod servers to this latest openssl release ?
Comment: How do you normally update your systems ?
Comment: apt-get update / upgrade . I was thinking of downloading the source when it's available, i want to be sure it won't break anything
Answer: You don't.
Most reputable distributions take security fixes and retrospectively apply them to the current version of (in this case) openSSL that they distribute.
This allows them to keep up-to-date with security patches while lessening the risk of new bugs appearing from the use of relatively untested software.
You'll notice that openSSL will update quite often. If you install apt-listchanges it will show you the changelog during these updates so that you can confirm that the HIGH severity bugs have been patched.
But if you're insisting on the latest version, then you'll probably have to compile it yourself.
Comment: you mean download from the source and do a `make` ?
Comment: Yes.  But if you install into the default locations and overwrite your existing openSSL, then expect your system to break.  If you (sensibly) install into a different directory (such as `/usr/local`) then you'll have to ensure that applications find it - they'll use the distro provided version by default.
Comment: @mikato this is exactly my question as well. Now that we have passed EOL the version is still not upgradable. I am asking myself if Ubuntu will update to 1.0.2 or not. If not I must consider compiling like garethTheRed mentioned.
Comment: Ubuntu 14.04 LTS end of life is April 2019. Latest version of OpenSSL supported for it is 1.0.1f. OpenSSL will cease support for 1.0.1 versions on 2016-12-31. Is there a problem here? Or is that normal? No ALPM (and HTTP2) for Ubuntu 14.04 it seems.
https://launchpad.net/ubuntu/+source/openssl ,
https://www.openssl.org/policies/releasestrat.html


Ordenando cartas em Python

Question: Tenho uma lista com as cartas e o naipe de um baralho que preciso ordenar. Considerando a ordem correta:
A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K
E os naipes: P(paus). O(ouro), E(espada), C(copas)
Após a leitura do arquivo com todos as cartas de todos os naipes, preciso ordenar cada naipe.
Por exemplo: a leitura do arquivo retorna (vou considerar apenas um naipe):
K P
A P
3 P
9 P
10 P
J P
4 P
2 P
6 P
8 P
7 P
Q P
5 P

Preciso ordenar pelo valor das cartas. Pensei em jogar em um dicionário onde as chaves são as cartas e o valor é o naipe, e depois ordenar pela chave, mas não consigo sair disso.
Alguém pode me ajudar?
Meu código até agora:
arquivo = open('nome_arquivo.txt', 'r')
dados = arquivo.readlines()
dic = {}
for linha in dados:
    linha = linha.split()
    dic[linha[0]] = linha[1]
print(dic)

Comment: Relacionada: [Estrutura de dados que represente um baralho de cartas](https://pt.stackoverflow.com/q/261210/5878)
Comment: Se você jogar as cartas como chaves e os valores sendo os naipes, você vai ter (se estiver trabalhando com todas as cartas), quatro casos para cada chave.
Acredito que isso traria um problema para o resto do código.

No entanto, você poderia usar [listas aninhadas](https://www.devmedia.com.br/como-trabalhar-com-listas-em-python/37460) sendo a primeira posição o valor da carta e o segundo valor o naipe.
Answer: O método "sorted" retorna a lista baralho ordenada de forma ascendente.
O método "enumerate" retorna o índice e os elementos da lista baralho.
As variáveis "k" e "v" recebem o índice e o elemento da lista baralho.
O método "strip" remove da "string" as quebras de linha, espaços em branco, etc.
O método "dic.update" atualiza o dicionário, a chave será a variável "k" e "v" o valor.
O método "dic.get" retorna o valor de uma chave especificada ou vazio se a chave não existir.
arquivo = open('cartas.txt', 'r')
baralho = arquivo.readlines()

dic = {}

for k, v in enumerate(sorted(baralho)):
    v = v.strip().strip('\n').strip('P')
    dic.update({k:v})

if dic.get(0) != 'A':
    dic.update({0:'A'})

if dic.get(9) != '10':
    dic.update({9:'10'})

if dic.get(11) != 'Q':
    dic.update({11:'Q'})

if dic.get(12) != 'K':
    dic.update({12:'K'})

print(dic)

Comment: Saudações Éder. Considere também, junto com o código, adicionar uma explicação em texto do que implementou, como funciona e porque isso resolve o problema em questão. Vi que suas últimas respostas são basicamente código e isso dificilmente colaborá de alguma forma para a comunidade (e está sujeito a receber votos negativos). Lembre-se que um código pode ser trivial para você, mas para outros usuários não.

Ordenando cartas em Python


Achieving left hand finger independance

Question: I've played guitar on and off for years and I am picking it up again, both electric and classical, hopefully in a consistent manner now.
I am back at working on both my diatonic and chromatic scales and my middle finger on my left hand is causing me quite a lot of trouble:
- When doing the chromatic scale  using the sequence 4-1-2-3 or 4-1-3-2 each time I lift my pinky the middle finger is lifting itself too far from the strings, sometimes to the point of almost "flipping someone off".
- When doing diatonic scales, particularly major scales on the electric, when I use fingers 1-2-4, as soon as I lift the index finger to go to the next lower string the middle finger since "it wants" to lift itself it kind of slide upwards and sometimes it even hits the upper string with the nail.
If I do the exercises slow, and I do mean painfully slow, this behaviour is very mild, sometimes even it is not present, but as soon as I try to do them a little faster it comes again and it gets worse as I increase the speed.
Since my understanding is that chromatic scales exercises are precisely the ones that achieve finger independence, should I just be patient, keep doing them slowly and hope that one day the fingers behave or should I try something else?
It has been close to two months since I started practising again and I have been doing it for one hour every single day, seven days a week.
Thank you.
Comment: I have found that to be an age thing. When I, once again, picked up the guitar about four years ago, I had the same thing. For a long time, there was an exercise I found by googling. The exercise does not involve a guitar, but routinely doing finger bends with your index and ring finger, then the middle finger and pinky. Then doing single finger combinations. That helped a bit.
Answer: Scott Tennant of the LA Guitar Quartet has an instructional book called Pumping Nylon. The book has a number of exercises that promote independence.
Also 30-Day Guitar Workout by Jody Fisher is a good resource.

Achieving left hand finger independance


Django forms - How to change form data with HTML DOM?

Question: I am trying to change a Django form's data by using:
document.getElementById("id_role").innerHTML = "developer"

The CustomUser model has a "role" field that is referenced in the function.  By testing the output (with the displayField() function, it appears that document.getElementById("id_role").innerHTML actually references all of the available fields ("choices" given in the models.py).
The goal is for the second function, changeField(), to change the selected data on the form (my goal isn't to change the database's stored data at this point, just the selected form's input).
My question:  How do I use document.getElementById().innerHTML to access the specific value that is shown in the form, instead of all of the options for the field?
models.py
TECH_OPTIONS = ( ('developer','DEVELOPER'), ('manager','MANAGER'), ('testing','TESTING'), )

class CustomUser(AbstractUser):
  career = models.CharField(max_length=30)
  role = models.CharField(choices=TECH_OPTIONS,blank = True, max_length=30)

    def __str__(self):
        return self.username

html page
{% extends "base.html" %}
{% load bootstrap3 %}

{% block content %}

{{user.username}}'s Info

<input onclick="displayField(); changeField();" type="submit" name="" value="TESTING">

  <form method="post">

      {% csrf_token %}
      {% bootstrap_form form %}
      <input type="submit" value="Save" />

  </form>

{% endblock %}

Answer: You need to use value rather than innerHTML to change/read the value of a field:
document.getElementById("id_role").value = "developer"

Comment: Thank you, that was the fix!


What's returned from @ViewBuilder if the conditional isn't met?

Question: I've been using @ViewBuilder like so:
@ViewBuilder
var warning: some View {
    if someWarningIsShown {
        Text("WARNING")
    }
}

This works fine, but I'm trying to figure out how @ViewBuilder works when the conditional isn't met. Since the type isn't optional I assume that something other than nil is returned. EmptyView()? AnyView(EmptyView())? What also strikes me is that there's no return keyword by the Text(). How's that even possible? I'm guessing @ViewBuilder is operating in an unconventional way. Can anyone explain?
Comment: you should make a `View` instead because `body` is already `@ViewBuilder` and more.
Answer: This will simply just return an EmptyView. This is essentially the same as writing:
@ViewBuilder func warning() -> some View {
    if someWarningIsShown {
        Text("WARNING")
    } else {
        EmptyView()
    }
}

If you want to write a function that allows you to return, you can simply omit the @ViewBuilder and return within your code as follows (note that all paths through the function must return a value, and all paths must return the same type of view):
func warning() -> some View {
    if someWarningIsShown {
        return Text("WARNING")
    } else {
        return Text("SUCCESS")
    }
}

You CAN NOT write a non @ViewBuilder annotated function, that returns different types. For example, the following will return an error telling you that the function declares an opaque return type, but does not return values with the same underlying types. This is only possible with functions annotated with @ViewBuilder:
func warning() -> some View {
    if someWarningIsShown {
        return Text("WARNING")
    } else {
        return EmptyView()
    }
}

Given the above info, we can ascertain that the @ViewBuilder attribute is doing some work under the hood that will return an EmptyView() when a block contains no statements that it can process. Digging deeper into the underlying code and the documentation we can see this to be true:
static func buildBlock() -> EmptyView
// Builds an empty view from a block containing no statements.

Comment: @JoakimSjöstedt no probs mate :)


How do I add multiple custom CSS classes to Views rows?

Question: This is a kind of follow up to this question:
I have a view where I added taxonomy tags as custom CSS class for rows of a unformatted list:

I did that using Replacement Pattern [tags] as row class.
The problem is that I need to filter by tags and so every taxonomy tag should be added as a separate class. I would need spaces instead of - so the output would be something like that:

Is this possible with Views GUI or do I have to use Views preprocess function?
Answer: if you're using multivalue class token, this bug report may be of interest for you. There's also a patch as a workaround available.

Currently if a views field token contains multiple space-separated class names, these classes will be combined into one class when the string is run through drupal_html_class(). Attached is a patch to split token classes before they are sanitized for HTML.
Comment: Updating to the newest Views module fixed the issue as the mentioned bug is committed since Views 7.x-3.16. Thanks! Now I need to fix the same bug for a References View: https://drupal.stackexchange.com/questions/245716/how-do-i-add-multiple-custom-css-classes-to-views-references-field
Answer: Under "Format" in the left column of the view, you click on "Settings" near the format you choosed, for example "Unformatted list".
In the popup you can edit the row classes.


Pegar os últimos IDS

Question: Quero pegar os últimos ID's deste site
Não quero pegar os IDS com número mais altos e sim os últimos da ordem:
Exemplo:
<effect id="195" lib="CrossTrainer" type="fx" revision="62175"/>
<effect id="500" lib="BigSpn" type="fx" revision="90000"/>
<effect id="501" lib="SmallS" type="fx" revision="90000"/>
<effect id="502" lib="BigJmp" type="fx" revision="90000"/>
<effect id="503" lib="SmallJ" type="fx" revision="90000"/>
<effect id="504" lib="Hoverplan1" type="fx" revision="90000"/>
<effect id="505" lib="Hoverplan2" type="fx" revision="90000"/>
<effect id="506" lib="Hoverplan3" type="fx" revision="90000"/>
<effect id="507" lib="TrampolineTest" type="fx" revision="90000"/>

Pegar somente os 3 últimos IDs... "505,506,507"
Comment: Poderia usar o `str_split()` para cortar a string em `id="` dai apos cortar você em um `foreach` pega apenas as três primeiras letras de cada item.
Comment: Como ficaria o código inteiro?
Comment: Esse codigo dai é realmente uma string? Vou postar a resposta.
Comment: não entendi sua pergunta, este código que mostrei é apenas um exemplo dos IDS que é para pegar do link: http://hebbohotel.com.br/swf/gordon/RELEASE-HEBBO/effectmap.xml
Answer: Sendo um XML pode usar o DOMDocument
$url = 'http://hebbohotel.com.br/swf/gordon/RELEASE-HEBBO/effectmap.xml';

$xml = file_get_contents($url);

$dom = new DOMDocument;
$dom->loadXML($xml);
$effects = $dom->getElementsByTagName('effect');

foreach ($effects as $effect) {
    echo $effect->getAttribute('id'), PHP_EOL;
}

O exemplo anterior servia somente para entender, para obter os 3 últimos ids use array (converta com iterator_to_array) e use a função array_slice assim:
$url = 'http://hebbohotel.com.br/swf/gordon/RELEASE-HEBBO/effectmap.xml';

$xml = file_get_contents($url);

$dom = new DOMDocument;
$dom->loadXML($xml);
$effects = iterator_to_array($dom->getElementsByTagName('effect'));//Passa para array

//-3 no segundo parametro pega os 3 ultimos itens
$effects = array_slice($effects, -3);

foreach ($effects as $effect) {
    echo $effect->getAttribute('id'), PHP_EOL;
}

Note que file_get_contents falhar você pode ser devido a não habilitado o acesso a urls externas, você pode habilitar isso no php.ini (como expliquei nesta resposta https://pt.stackoverflow.com/a/72746/3635):
allow_url_fopen=1

Ou pode trocar file_get_contents por curl, assim:
<?php
$url = 'http://hebbohotel.com.br/swf/gordon/RELEASE-HEBBO/effectmap.xml';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //Transferência binaria
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Força retornar transferência na variável

$xml = curl_exec($ch);

curl_close($ch);

$dom = new DOMDocument;
$dom->loadXML($xml);
$effects = iterator_to_array($dom->getElementsByTagName('effect'));//Passa para array

Respostas compactadas GZ
As vezes pode ocorrer de mesmo você não solicitando o header Accept-Encoding o servidor ainda enviar, isso é um problema talvez de má configuração, no caso o link que deseja acessar esta com este problema, tentei enviar os headers, mas aparentemente não funciona, então uma solução é usar o gzdecode do php, assim:

file_get_contents
$url = 'http://hebbohotel.com.br/swf/gordon/RELEASE-HEBBO/effectmap.xml';

$xml = gzdecode(file_get_contents($url));

$dom = new DOMDocument;
$dom->loadXML($xml);
$effects = iterator_to_array($dom->getElementsByTagName('effect'));//Passa para array

curl
$url = 'http://hebbohotel.com.br/swf/gordon/RELEASE-HEBBO/effectmap.xml';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //Transferência binaria
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Força retornar transferência na variável

$xml = gzdecode(curl_exec($ch));

curl_close($ch);

$dom = new DOMDocument;
$dom->loadXML($xml);
$effects = iterator_to_array($dom->getElementsByTagName('effect'));//Passa para array

Comment: Deu certo obrigado mano! <3
Comment: @Rafa editei a resposta, leia o final que adicione e tente, se houver qualquer problema adicione no começo `<?php error_reporting(E_ALL); ini_set('display_errors', 1);` apenas pra depurar, depois que estiver funcionando pode remover o `error_reporting` e o `ini_set`, leia mais sobre isto em http://pt.stackoverflow.com/q/106562/3635
Comment: @Rafa voce não pode esperar m codigo pronto aqui no site pois não sabemos o que você quer fazer, o restante do seu código, o site não é pra pegar codigo pronto e sim tratar duvidas específicas, como a sua que já foi tratada nas duas resposta, agora se sua aplicação do codigo no seu contexto está sendo errada aí ja fica difícil ajudar.
Comment: @GuilhermeNascimento olhe oque deu http://rafagarcia.eu5.org/efeito.php
Comment: Você acha que em javascript não seria melhor?
Comment: @Rafa Eram pequenos problemas no código, provavelmente você usou o curl, eu corrigi troquei `array_values` por `iterator_to_array` e no curl eu adicione o `CURLOPT_RETURNTRANSFER` que estava faltando. Teste agora os exemplos.
Comment: Continua com errinhos! e está tudo com letras como se fosse criptografado http://rafagarcia.eu5.org/efeito.php se puder contatar pelo skype ia me ajudar mais! skype: rafa.garcia.gamer
Comment: Usei o da última edição da postagem
Comment: o curl, porque o file_get_contents fica tudo branco a página!
Comment: @Rafa faz o seguinte, cria um novo arquivo php chamado teste.php e depois cola esse conteudo nele e salva: http://pastebin.com/raw/q5kMkxRv então acesse ele
Comment: @Rafa recomendo que estude as funções e estude php, entenda como um comentário pra você se tornar melhor, muitos dos erros foram por você desconhecer as funções que tentou usar e não entender as explicações que passei, foi apenas no copy+paste e por isso falhou, é só uma critica construtiva :)
Answer: Não sei se vai ajudar pois vocês está trabalhando com XML, logo, não postou se está trabalhando com ele como string ou transformando-o em array.
Na realidade não usei o str_slipt, fiz de outra forma.
Fiz uma classe para dar conta do recado, GetIds.php:
<?php
class GetIds
{
    /*
    *   Atributos
    */
    private $string = null;
    private $limit = null;
    private $split = null;

    /*
    *   Construtor com insercao de um atributo
    */
    public function __construct($string = null)
    {
        $this->string = $string;
    }

    /*
    *   Varre atributo string até que o caracter lido não seja string, apos iss une os numeros formando o id
    *   @return result - array com os ids
    */
    public function getIds()
    {
        $this->appLimit();

        $result = array();
        foreach($this->split as $value)
        {
            $isNumber = 0;
            for($letter = 0; $letter < strlen($value); $letter ++)
            {

                if(filter_var($value[$letter], FILTER_VALIDATE_INT) or $value[$letter] === '0')
                    $isNumber ++;
                else
                    break;

            }
            for($letter = 0; $letter < count($value); $letter ++)
            {
                array_push($result, mb_substr($value, 0, $isNumber));
            }
        }

        return $result;
    }

    /*
    *   Muda o valor do atributo limit
    */
    public function setLimit($newLimit)
    {
        $this->limit = $newLimit;
    }

    /*
    *   Separa o atributo string em determinado separador passado por parametro
    */
    public function setSplit($separator)
    {
        if(!is_null($this->string))
            $this->split = explode('id="', $this->string);
        unset($this->split[0]);
    }

    /*
    *   Apaga elementos do array deixando os x ultimos
    */
    private function appLimit()
    {
        if(!is_null($this->string) and !is_null($this->limit))
        {
            $crop = count($this->split) - $this->limit;
            for($item = 0; $item < $crop; $item ++)
            {
                unset($this->split[$item]);
            }
        }

    }
}

Arquivo teste.php:
<?php
require_once 'GetIds.php';
$myResult =
'<effect id="195" lib="CrossTrainer" type="fx" revision="62175"/>
<effect id="500" lib="BigSpn" type="fx" revision="90000"/>
<effect id="501" lib="SmallS" type="fx" revision="90000"/>
<effect id="502" lib="BigJmp" type="fx" revision="90000"/>
<effect id="503" lib="SmallJ" type="fx" revision="90000"/>
<effect id="5" lib="Hoverplan1" type="fx" revision="90000"/>
<effect id="122150" lib="Hoverplan2" type="fx" revision="90000"/>
<effect id="50654" lib="Hoverplan3" type="fx" revision="90000"/>
<effect id="502170" lib="TrampolineTest" type="fx" revision="90000"/>';

// cria uma classe com a string de resultado
$ids = new GetIds($myResult);

// define o limite para 3
$ids->setLimit(3);

// define onde devo cortar o resultado
$ids->setSplit('id="');

// pega os ids encontrados
$result = $ids->getIds();

var_dump($result);

Saída:
array (size=3)
  0 => string '122150' (length=6)
  1 => string '50654' (length=5)
  2 => string '502170' (length=6)

Obs: Alterei os ids apenas para mostrar que funciona com id de comprimentos diferentes.
Comment: O `var_dump` exibe o array de uma forma mais elegante, os ids estão armazenado no aray, se nao entendeu isso sugiro que estude array e mais sobre linguagem de programação

Pegar os últimos IDS


Adaboost Sklearn Feature Importance NaN

Question: I am building an Ada boost model with Sklearn. Last year I made the same model with the same data, and I was able to access the feature importances. This year when I build the model with the same data the feature importance attribute contains NaNs.I have read some other stuff where people have has the same problem and its where there is NaN's in their data, however mine does not.
I am at loss of what is different, but I have isolated the Base_estimator DecisionTree max_depth to be the problem. The higher the max_depth, the greater number of NaNs. However I have identified that max_depth=10 is best for my work. This is my code
Can anyone point out where I am going wrong? Or explain what is happening or another way to get the feature_importance?
I have recreated the same error with a sklearn dataset below.
I have a old version of sklearn with python 2.7 and with the same data this error doesn't occur.
Thank you
Data that I am working with is available here: https://github.com/scikit-learn/scikit-learn/discussions/20315
import pandas
import xarray
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier

train_data=pandas.read_csv('data_train.csv')
model_variables=['RH','t2m','tp_r5','swvl1','SM_r20','tp','cvh','vdi','SM_r10','SM_IDW']

X = train_data[model_variables] # Features
y = train_data.ignition_no

np.count_nonzero(np.isnan(y))
0
#no missing target variables

tree = DecisionTreeClassifier(max_depth=10, random_state=12)
ada_model= AdaBoostClassifier(base_estimator = tree, random_state=12)
model= ada_model.fit(X,y)
model.feature_importances_
/home/mo/morc/.virtualenvs/newroo/lib/python3.6/site-packages/sklearn/tree/_classes.py:605: RuntimeWarning: invalid value encountered in true_divide
  return self.tree_.compute_feature_importances()
array([       nan,        nan,        nan,        nan,        nan,
              nan,        nan, 0.02568412,        nan,        nan])
>>>

#Here is the same error recreated with the load_digits dataset from sklearn

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier

from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import train_test_split
from sklearn.model_selection import learning_curve

from sklearn.datasets import load_digits
>>> dataset = load_digits()
>>> X = dataset['data']
>>> y = dataset['target']
>>>
>>> score = []
>>> for depth in [1,2,10] :
...     reg_ada = AdaBoostClassifier(DecisionTreeClassifier(max_depth=depth))
...     scores_ada = cross_val_score(reg_ada, X, y, cv=6)
...     score.append(scores_ada.mean())
...
score
>>>[0.2615310293571163, 0.6466908212560386, 0.9621609067261242]
#best depth is 10, so making ada_boost classifier with base_estimator of max_depth=10
reg_ada = AdaBoostClassifier(DecisionTreeClassifier(max_depth=10))
model=reg_ada.fit(X,y)
model.feature_importances_
/home/mo/morc/.virtualenvs/fox/lib/python3.6/site-packages/sklearn/tree/_classes.py:605: RuntimeWarning: invalid value encountered in true_divide
  return self.tree_.compute_feature_importances()
array([0.00000000e+00, 3.97071545e-03,            nan, 1.04739889e-02,
       1.71911851e-02, 1.13877668e-02, 5.53334918e-03, 3.48635371e-03,
       3.81562332e-16, 2.97882448e-04, 5.21107270e-03, 1.90482369e-03,
       9.54317398e-03,            nan, 4.04579846e-03, 2.85770367e-03,
       2.41466161e-03, 2.22172771e-04,            nan,            nan,
       2.64452796e-02, 2.35455672e-02, 5.91982800e-03, 9.63862404e-15,
       2.51667106e-05, 8.22347398e-03, 3.53522516e-02, 3.49199633e-02,
                  nan,            nan, 7.85924750e-03, 0.00000000e+00,
       0.00000000e+00, 2.43861329e-02,            nan, 4.52136284e-03,
       2.84309340e-02, 8.70846798e-03,            nan, 0.00000000e+00,
       0.00000000e+00, 8.51258472e-03,            nan, 4.08880381e-02,
       6.47568594e-03, 1.75046890e-02, 1.37183583e-02, 3.95955193e-32,
       0.00000000e+00, 6.36631892e-05, 2.06906508e-02,            nan,
                  nan,            nan, 9.47079562e-03, 3.71242630e-03,
       0.00000000e+00, 7.14153611e-06,            nan, 5.14482654e-03,
       2.23621689e-02, 1.79753787e-02, 3.05869803e-03, 4.80512718e-03])

Comment: A reproducible example would be great: a subset of your data, or recreate the issue with one of sklearn's builtin datasets.  Also try escalating the warning to an error so we can get the full error traceback.
Comment: However, the warning suggests an issue [here](https://github.com/scikit-learn/scikit-learn/blob/15a949460dbf19e5e196b8ef48f9712b72a3b3c3/sklearn/tree/_tree.pyx#L1047); the only place I see a unguarded division is [here](https://github.com/scikit-learn/scikit-learn/blob/15a949460dbf19e5e196b8ef48f9712b72a3b3c3/sklearn/tree/_tree.pyx#L1074), but can the weighted sample size be zero at the root?...maybe the last estimators are broken somehow, by fully learning the training data?  Try printing/plotting the last fitted tree?
Comment: Thanks for your reply @BenReiniger I have added the recreated error with a sklearn dataset.
Comment: I can't recreate this in sklearn version 0.22.2.post1; what version are you running?
Comment: I am using version 0.24.2 Do you think its some kind of bug?
Comment: @BenReiniger I installed version 0.22.2 and I don't have the problem anymore. Thanks so much for your help, it was very frustrating!
Answer: I've narrowed it down in your digits example.  At the tree 20, feature 38 is used for five splits, and in the last of those (node 353), the impurity of the right child is -np.inf (!?).  So the raw (un-normalized) importance at that split is +inf, so the total raw importance of the feature for this tree is +inf, and so when normalizing the importances for this tree, every other feature gets something / inf = 0, while this feature gets inf / inf = nan.  Then aggregating that across trees, this feature (and others, because of presumably similar issues in other trees) has importance nan (and the other features' importances are skewed for not getting real contributions from this tree).
I cannot see what changed between 0.22 and 0.23 that causes this issue, nor do I really understand how the calculation comes up with -inf for the gini coefficient; perhaps some overflow issue?
Comment: Wow! you really managed to get to the heart of the problem and it makes total sense.I have logged it on Github as a possible bug.Thank you so much for looking at it and solving it (why the impurity ends up being -np-inf is another story!)
Comment: Here's a link to that issue:  https://github.com/scikit-learn/scikit-learn/issues/20320, thanks!
Answer: About the nans that appear: I find they only appear using the SAMME.R algorithm and really make a mess of things. I am almost certain that SAMME.R is used by default. The nans do not appear using SAMME. I compute feature importances with SAMME then fit the most important features with SAMME.R
Two steps:

calculate feature importances with SAMME:

#import numpy as np

def sci_sort(self,X_train, y_train,depth,tris):
algo = 'SAMME'
    regr = AdaBoostClassifier(DecisionTreeClassifier(max_depth=depth),algorithm=algo,n_estimators=tris)
    regr.n_estimators =X_train.shape[1]+tris
    regr.n_jobs=-1
    regr.compute_importances = True
    regr.fit(X_train, y_train)
    fout = open('hugrunES_buy.txt','w')
    fout.write (str(list(np.argsort(regr.feature_importances_)))+'\n')
    fout.close()
    return np.argsort(regr.feature_importances_)

Do the actual fitting with SAMME.R:

def sci(self,X_train, y_train,X_test,y_test,nam,depth,trees,learning_ratee,tak):
    algo ='SAMME.R'
    regr = AdaBoostClassifier(DecisionTreeClassifier(max_depth=depth),algorithm=algo,n_estimators=trees,learning_rate=learning_ratee)
    regr.n_jobs=-1
    regr.fit(X_train, y_train)

Adaboost Sklearn Feature Importance NaN


Inserting in a Partially Ordered Tree

Question: I'm trying to insert an element in a Partially Ordered Tree but when I tried to display the tree which is implemented as an array, it won't show the elements.
Here's the heap structure. I just made it simple for now.
typedef struct{
    int Elem[SIZE];
    int last;
}Heap;

Here's what I did for my insert.
void insertHeap(Heap *HH, int given)
{
    int parent, child, temp;

    if(HH->last < SIZE){
        HH->Elem[HH->last] = given;
        parent = (HH->last - 1) / 2;
        for(child = HH->last ; child >= 0 && HH->Elem[child] <= HH->Elem[parent] ;  child = parent, parent = parent - 1 / 2 ){
            temp = HH->Elem[parent];
            HH->Elem[parent] = HH->Elem[child];
            HH->Elem[child] = temp;
        }
        HH->last++;
    }
}

Comment: `parent - 1 / 2` should be `(parent - 1) / 2`.And you will need a better condition to stop your loop, probably `child > 0`, because item 0 has no parent.
Comment: Care to upload your `Heap` struct definition?
Comment: I don't know what other problems you have, but integer division in C doesn't work like you think it does. `1/2` in integer arithmetic is zero.
Comment: @Michał Szydłowski  Just uploaded the structure.
Comment: @M Oehm Thanks, but I don't get your first sentence. I don't have that statement.
Comment: It's in the update clause of the `for` loop. (The loop might be easier to read as a while `loop` with the two update statements pulled into the loop.)
Comment: @M Oehm If you don't mind, wouldn't that make my code longer? I'm actually concern about efficiency and readability.
Comment: The `while` and `for` loops will have the same statements, only arranged in a different way. I doubt that the compiled code for the two variants should be drastically different. And I don't find the long `for` control particularly readable, but that's just personal preference, of course.
Answer: Your code goes into an infinite loop. You should fix two things:

There should be parentheses around (parent - 1) when you calculate the new parent in the update section of the for loop control;
Your condition parent >= 0 will always be true, because even for parent == 0, (parent - 1) / 2 will yield 0, because -1 / 2 is zero according to C's integer division rules.

So:
void insertHeap(Heap *HH, int given)
{
    int parent, child, temp;

    if(HH->last < SIZE){
        HH->Elem[HH->last] = given;
        parent = (HH->last - 1) / 2;
        for (child = HH->last;
             child > 0 && HH->Elem[child] <= HH->Elem[parent];
             child = parent, parent = (parent - 1) / 2)
        {
            temp = HH->Elem[parent];
            HH->Elem[parent] = HH->Elem[child];
            HH->Elem[child] = temp;
        }
        HH->last++;
    }
}

The for loop with three long sections looks a bit clumsy. You can also move the variable declarations closer to where the variables are needed and initialise them immediately. The code below does the same, but is more readable, in my opinion, but it's a matter of personal style, of course.
void insertHeap(Heap *HH, int given)
{
    if(HH->last < SIZE){
        int parent = (HH->last - 1) / 2;
        int child = HH->last;

        HH->Elem[HH->last] = given;

        while (child > 0 && HH->Elem[child] <= HH->Elem[parent]) {
            int temp = HH->Elem[parent];

            HH->Elem[parent] = HH->Elem[child];
            HH->Elem[child] = temp;

            child = parent;
            parent = (parent - 1) / 2;
        }

        HH->last++;
    }
}

Answer: I just changed the first conditional statement of my for loop child > 0

Inserting in a Partially Ordered Tree