I would like to split a string by a variable and a character but it doesn't use the variable

Question: I used re.split to be able to split it with more than 1 character and it works fine for the ", " but it doesn't seem to be detecting the variable.
import re

a1 = "my"
b2 = "Hello! 34 is my number, bye."
b2 = re.split("{a1}|, ", b2)
print(b2)

I tried changing it to different variable types but that's not it. I don't know if it's the "|" but I can't figure out why it's happening.
Answer: You have given a literal string {a1} to the regex, so it would split on the 4 chars bracket/'a'/'1'/bracket, you need a f-string to use the value of the variable
a1 = "my"
b2 = "Hello! 34 is my number, bye."

b2 = re.split(f"{a1}|, ", b2)
print(b2) # ['Hello! 34 is ', ' number', 'bye.']

print("{a1}|, ")  # {a1}|,
print(f"{a1}|, ") # my|,

Answer: If you want a string to use a value from a variable, one convenient way is to use an f string:
b2 = re.split(f"{a1}|, ", b2)

For regex, I also recommend using raw strings, it will save you many headaches with special characters.
b2 = re.split(rf"{a1}|, ", b2)


$\cot x - \tan x = 2\cot 2x$, but the period on the left is $\pi$, while on the right it's $\pi/2$. Shouldn't the periods match?

Question: It's not difficult to show $$\cot x - \tan x = 2\cot 2x$$ The period of LHS is $T_1 = \pi$ but the period of RHS is $T_2 = \pi /2$ . Why are $T_1$ and $T_2$ not equal? So we can't use that identity for solving problems?
Comment: @SHW As nice comments above have shown, what you can conclude is that $\pi$ is a period of LHS. It is not necessarily the fundamental period.
Comment: $\cot(x+\pi/2) - \tan(x + \pi/2) = -\tan x + \cot x = \cot x - \tan x$
Comment: Why do you think that the period of LHS is $\pi$?
Comment: @zhoraster Because the period of $\tan x$ and $\cot x$ is $\pi$ .
Comment: @samjoe Therefore what we can say about the period of addition or subtraction of two periodic functions ?
Answer: Say $f(x) = 2\cot (2x)$ and let $T_2$ be a period for $f$, then $$f(x+T_2)= f(x)\implies \cot (2x+2T_2)= \cot 2x$$
Mark $\alpha = 2x$ (so clearly $\alpha$  can be any angle) then we have $$\cot (\alpha +2T_2) = \cot (\alpha)$$
and thus $2T_2$ is a period for $\cot$ so $2T_2 = \pi$

But $\pi/2$ is also period for $g(x)=\cot x-\tan x$: $$ g(x+\pi/2) = \cot(x+\pi/2)-\tan (x+\pi/2)$$ $$ =\cot(x-\pi/2)-\tan (x-\pi/2)$$
$$ =-\cot(\pi/2-x)+\tan (\pi/2-x)$$
$$ =-\tan(x)+\cot (x)=g(x)$$


Where did the Sailsjs websockets documentation go?

Question: If I try to look up the docs in google, I get to see this: broken link. Has Sails stopped the websockets support and if not: where can I find something like a docs/tutorial?
Answer: http://sailsjs.org/#!/documentation/reference/websockets
Works pretty good for me. Just check out the link and go to documentation...
Comment: As you can see, they removed websockets from their documentation. sailsjs.org/#!documentation/sockets < this is the old link
Comment: http://sailsjs.org/#/documentation/reference/websockets - sorry I should have been more specific
Comment: Thanks! I think they moved it and Google hasn't re-indexed it than.
Answer: The Sails websocket framework is built on top of http://socket.io/. It provides a publish/subscribe protocol for your existing models.
So for example, to subscribe a client connected socket to all "create" and "destroy" events for a User model you would add the following to a controller.
<code>   User.find({}).exec(function(e,listOfUsers){
       User.subscribe(req.socket,listOfUsers,['create','destroy']);
   });
</code>
Then on the client side you simply include the sails.io script to allow the client to connect. If the above controller has a route applied to it such as /user/socket the client would simply do:
<code>   io.socket.get('/user/socket', function (data, jwres){
      // do something if any data is returned
   });
</code>
Then the client could "subscribe" to the event:
<code>   io.socket.on('user', function onServerSentEvent (msg) {
     // this event will fire any time the 'User.create' and 'User.destroy' event is called
   });
</code>
For those of you looking for this documentation that stumble across this thread and the above url isn't working, they moved it here (I think they added hash bang /#!/ to their site). The documentation does a better job of explaining it then I do.
http://sailsjs.org/#!/documentation/reference/websockets
Comment: Please quote here some parts of the solution and don't give only a link


Making Django & Vue.js work together with {% verbatim %}

Question: I'm trying to make django & Vue work together even though they share the same {{ X }} template syntax.
I know that from django 1.5 we can use the {% verbatim %} tag. So I thought I could use django templates as usual and in the section where I need VUE to take over I would just use the {% verbatim %} tag. However instead of loading my vue data django loads the {{ variable }}.
For example my django code looks something like this:
{% verbatim %}

{{message}}

{% endverbatim %}

And in my app.js file I have:
var sessions = new Vue({
  el: '#sessions',
  data: {
    message: 'Hello Vue!'
  }
})

But instead of rendering Hello Vue! it renders {{message}}
The console doesn't show any error and vue loads correctly otherwise.
How I can make the two work together? Ideally without the need to change the vue.js {{}} syntax.
Answer: You can change Vue's interpolation delimiters to whatever you want.
var sessions = new Vue({
  el: '#sessions',
  delimiters: ['${', '}'],
  data: {
    message: 'Hello Vue!'
  }
})

That way you can use whatever your framework needs.
Edit
It turned out in this case, @Costantin had more than one div#sessions on the page.
Comment: I tried but I can't seem to get it to work. With your settings I should be able to load the message with `${ message }` right?
Comment: @Costantin You should, yes. Are you getting a console error?
Comment: Because doing that I just get ` ${message}` rendered
Comment: @Costantin Is it possible the template is rendered after the script?
Comment: no console log error. But If I type `sessions.message` I get correctly
"Hello Vue!"
Comment: @Costantin what is the rendered html?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142369/discussion-between-costantin-and-bert-evans).


How to average columns over an ID?

Question: I have a large file of data with multiple ID's followed by several columns of observations. I need to average over one of the columns of ID's. I think this can be done using awk, but I'm not sure of how to set it up.
Data:
ID1 ID2 Observation
1 15_24 -0.00002649
2 15_24 0.00001584
3 15_24 -0.00003168
1 16_2 0.00002649
2 16_2 -0.00002014
3 16_2 -0.00003058
1 12_25 0.00009636
2 12_25 -0.00007514
3 12_25 0.00003021

Need the observations averaged over ID2 like this:
1 15_24 -0.00001411
2 16_2 -0.00000808
3 12_25 0.00001714

Thank you.
Answer: Maybe so:
awk 'BEGIN{ FS=" " } { cnt[$2] += $3; lincnt[$2] +=1;  } END{i=1; for (x in cnt){print i++, x, (cnt[x] /lincnt[x] )  } }' file

Comment: My comment was meant to help/clarify, too. No need to take it personal.
Comment: Using associative arrays does not preserve ordering (not sure if it's relevant).
Comment: Order is not important, as long as the ID's stay associated with the observations.
Comment: I have a follow-up question. What if I have 40 columns of observations instead of just one? Can I alter this to average over all columns that are not ID's?
Comment: No need to set FS as that's the default, and you could use `++` instead of `+=1`. You might want to consider `sum` instead of `cnt` as the name of that array just for clarity.
Comment: You do not need to set `i=1`, use instead `++i` This way increment `i` before use, instead of after use. You can also remove some `{}` and `;`. So summing up you can use it like this `awk '{sum[$2]+=$3;cnt[$2]++} END {for (x in sum) print ++i,x,sum[x]/cnt[x]}' file`
Answer: If ordering is relevant, this awk script could help:
#!/usr/bin/env awk

lastItem==$2{
    observation+=$3
    observationCounter+=1
    next
}
observationCounter>0{
    print ++i" "lastItem" - "observation/observationCounter
}
{
    lastItem=$2
    observation=$3
    observationCounter=1
}
END{
    print ++i" "lastItem" - "observation/observationCounter
}

How to average columns over an ID?


How to create button with dynamic links (that automatically updates with the last blog post link in a category) in Wordpress

Question: As title says I am trying to have a button on my home page that automatically updates the link with the link of the last blog post in a certain category
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: You need to code shortcode (in child theme functions.php for example or make a plugin), that will generate this button HTML output, fetch last post url and add it to button. Then you can use something like [last_post_button] anywhere where you need.


MySQL correlated subquery at FROM

Question: I'm working with the Sakila sample database, and trying to get the most viewed film per country. So far I've managed to get the most viewed film of a certain country given its id with the following query:
SELECT
    F.title, CO.country, count(F.film_id) as times
FROM
    customer C
INNER JOIN
    address A ON C.address_id = A.address_id
INNER JOIN
    city CI ON A.city_id = CI.city_id
INNER JOIN
    country CO ON CI.country_id = CO.country_id
INNER JOIN
    rental R ON C.customer_id = R.customer_id
INNER JOIN
    inventory I ON R.inventory_id = I.inventory_id
INNER JOIN
    film F ON I.film_id = F.film_id
WHERE
    CO.country_id = 1
GROUP BY
    F.film_id
ORDER BY
    times DESC
LIMIT 1;

I supose that I'll have to use this query or something similar in the FORM of another query, but I've tried it all I could think and am completely unable to figure out how to do so.
Thanks in advance!
Answer: I admit, this is a hell of a query. But well, as long as it works.
Explanation:

Subquery: almost the same as you already has. Without the WHERE and LIMIT. Resulting in a list of movie-count per country
Result of that, grouped per country
GROUP_CONCAT(title ORDER BY times DESC SEPARATOR '|||'), will give ALL titles in that 'row', with the most-viewed title first. The separator doesn't matter, as long as you are sure it will never occurs in a title.
SUBSTRING_INDEX('...', '|||', 1) results in the first part of the string until it finds |||, in this case the first (and thus most-viewed) title

Full query:
SELECT
    country_name,
    SUBSTRING_INDEX(
        GROUP_CONCAT(title ORDER BY times DESC SEPARATOR '|||'),
        '|||', 1
    ) as title,
    MAX(times)
FROM (
    SELECT
        F.title AS title,
        CO.country_id AS country_id,
        CO.country AS country_name,
        count(F.film_id) as times
    FROM customer C INNER JOIN address A ON C.address_id = A.address_id
    INNER JOIN city CI ON A.city_id = CI.city_id
    INNER JOIN country CO ON CI.country_id = CO.country_id
    INNER JOIN rental R ON C.customer_id = R.customer_id
    INNER JOIN inventory I ON R.inventory_id = I.inventory_id
    INNER JOIN film F ON I.film_id = F.film_id
    GROUP BY F.film_id, CO.country_id
) AS count_per_movie_per_country
GROUP BY country_id

Proof of concept (as long as the subquery is correct): SQLFiddle
Comment: You are correct. I missed a `GROUP BY` country. I've updated my answer, can you recheck?
Comment: This doesen't seem to be working correctly, wich probably is due to my subquerry not being correct
Comment: That's it! Thank you very much, it's working correctly

MySQL correlated subquery at FROM


Linked list not freed, missing memory leak

Question: I'm currently playing with linked lists, and I've put together the following code for testing purposes.
First I'd like to point out, I'm aware of my unusual list setup, it was just a test, to get a not upside down list. My actual "problem" now is, that I don't seem to have any memory leaks once the program terminates, although I'm not freeing the list. I'm using drmemory on Windows for analyzing, and it always worked nicely. If I put some other mallocs in this code, it notices the not freed memory. Why doesn't it notice the list?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// ----------------------

typedef struct Item
{
    char name[10];
    struct Item *next;
} Item;

Item *items = NULL;

Item *items_add(const char* name)
{
    Item *new = malloc( sizeof(Item) );
    strcpy(new->name, name);
    new->next = NULL;

    if(items == NULL)
    {
        items = new;
    }
    else
    {
        Item *iter = items;
        while(iter->next != NULL)
        {
            iter = iter->next;
        }

        iter->next = new;
    }

    return new;
}

void items_rem(const char* name)
{
    if(items == NULL)
        return;

    Item *iter = items, *prev;
    do
    {
        if(strcmp(iter->name, name) == 0)
        {
            prev->next = iter->next;
            free(iter);
            break;
        }

        prev = iter;
        iter = iter->next;
    }
    while(iter->next);
}

// ----------------------

int main(void)
{
    items_add("Item1");
    items_add("Item2");
    items_add("Item3");
    items_add("Item4");

    items_rem("Item3");

    for(Item *iter = items; iter != NULL; iter = iter->next)
    {
        printf("%s\n", iter->name);
    }

    /*
        Output:
            Item1
            Item2
            Item4
    */
}

Comment: +1 for Playing with linked list.
Comment: It seems `prev->next`  is used uninitialized during the removal of first element.
Comment: @EAGER_STUDENT: You're right, thanks. Didn't really think about the case of only one item being in the list, before posting this.
Answer: drmemory doesn't show reachable allocations by default, try running drmemory with the -show_reachable option set
Answer: The reason, I can think of is that Item *items = NULL 'items' is a global variable. So, as far as the memory leak checking tool is concerned, the memory is still accessible from the code, so it may be assuming that you still need that memory.
Atleast IBM Rational Purify works in this way. In IBM Rational Purify, you can select the option to show "Memory in use" and it will display this pointer and number of bytes held by it.
Please note that a memory is considered leaked only when there are no pointer variables containing that address and it has not been freed also.
For Ex:
int main()
{
  function();
}

int function()
{
   char *ptr = NULL;
   ptr = malloc(10);
   return 0;
}

Now, in the above example, once you return from function, there is no way for you to access variable ptr. So, the memory allocated for ptr is definitely lost
Comment: Ah~ of course! Shame on me for not thinking about that. Thank you.


cryptocompare module in Anaconda not installed to get real time cryptocurrencies price

Question: Ni Hao,
I am trying to read cryptocurrencies price in python. I tried to install cryptocompare module, but using the following codes in Anaconda prompt did not work:
<code> conda install cryptocompare

 conda install -c conda-forge cryptocompare
</code>
Also, I tried to install the downloaded file, but again did not work. Should I use another channel? If so, how can I add that channel. Also, if masters think better modules exist I appreciate to know that. Thanks
Comment: `didn't work` isn't an error message or problem description
Comment: Please [edit] to show the output of those commands and any other error messages.
Answer: Try with pip
<code>pip install cryptocompare
</code>


Increase isolated storage size on windows phone from a different application

Question: Is there a way of increasing the isolated storage size of a Windows Phone 8 application from another application or via settings on the phone?
Answer: This question begs another question of why exactly do you want to do it? Specifically what problem are you experiencing that makes you want to increase isolated storage?... Could your problem be solved by the answer provided in this SO post about how to stream directly to isolated storage?
Namely look at the use of the following function:
IncreaseIsolatedStorageSpace(e.Result.Length)

And take a look at this Windows 7 Phone solution
protected bool IncreaseIsolatedStorageSpace(long quotaSizeDemand)
{
    bool CanSizeIncrease = false;
    IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
    //Get the Available space
    long maxAvailableSpace = isolatedStorageFile.AvailableFreeSpace;

    if (quotaSizeDemand > maxAvailableSpace)
    {
        if (!isolatedStorageFile.IncreaseQuotaTo(isolatedStorageFile.Quota + quotaSizeDemand))
        {
            CanSizeIncrease = false;
            return CanSizeIncrease;
        }

        CanSizeIncrease = true;
        return CanSizeIncrease;
    }

    return CanSizeIncrease;
}

EDIT: Failing that, have a look into Windows Phone Power Tools, it's much better than the basic SDK
Answer: Applications are sandboxed on Windows Phone
There is no way to increase isolated storage size from a different application.


How to prepare chemically paint stripped wall before repainting?

Question: The attached picture below is my wall after I paint stripped it: I would apply the paint stripper on the surface, let it act for the required amount of time and then I would scrape - I've repeated this 3 times on the same wall to achieve the result as in the picture.

I have a few questions please :

Visually, is the wall clean enough now paint-wise for me to continue to the next step or do I need to reapply the stripper again and give it more scraping?

Before I repaint the wall, what are the advised steps I should do to prep the wall before I can paint on it? I assume I would need to do something to make sure the paint stripper chemicals are off the wall like sanding or cleaning with water or spirits?

Many thanks!
Comment: 1) It's your decision whether the base is clean enough or not. 2) After scraping, always clean the surface with warm water until all residuals are wiped clean. I would at least let it dry overnight to apply the primer and see whether it stays or not. A light sanding may help before paint.
Comment: Thanks. 1) Would a professional consider that clean/good enough?
Comment: Primer, with or without a skim coat for smoothness. Your call.
Comment: @JACK your comment is exactly the answer I was going to type up. Why not make an actual answer out of that.
Comment: Thank you so much, do I need to do anything to remove the paint stripper residues before applying the primer like some sanding or wiping?
Comment: We can't possibly know without knowing ***your reasons*** for paint stripping.  It's not something everybody just does all the time.  Have you removed all the layers of paint that were delaminating?  Have you removed the lead paint you were after?
Answer: Go over the paint stripper directions. They will tell you what's needed to remove any stripper residue. Then a good primer based on the type of paint you'll be using for the final coat. I have always used a pole sander and give the wall a quick sanding just to remove any rough edges left from scraping or taping. Once the primer dries, you'll get a good idea on how smooth the wall is and whether or not it's ready for your final coat.
Comment: Thanks Jack, sorry, what do you mean by going over the paint stripper directions?
Comment: @ld_pvl  Read the directions on the label of the paint stripper you used. They always include how to apply it, how to scrap it off and then how to clean, remove the residue.
Comment: Ah silly me! It says wipe surface using white spirit or methylated spirit. After that rub with sandpaper. Thanks!
Comment: @ld_pvl  You learn something new every day on this site...


Redmine and Related issues

Question: Is there a way to export tickets with the "related issues" status?
As far as I can see, I have no opportunity to export the information on related issues.
Thanks,
Mario
Answer: There is no way so far, unless you want to go the database directly. You can use the redmine-java-model on google code if you want to do that in java.

Redmine and Related issues


How do I send the a String to AppDelegate in Objective-C?

Question: I've create a class 'Datetool' inherit from NSObject to record the date when the application was launched. But I need to show the startTime string in the AppDelegate.
I tried to use the Block to send the string with a variable declared in 'AppDelegate.h', however, I couldn't get it in Datetool's method initialize.
Datetool.m
static NSString *startTime2;

+(void)initialize
{

   if (self == [DateTool self])
   {
       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
       [formatter setDateStyle:NSDateFormatterNoStyle];
       [formatter setTimeStyle:NSDateFormatterMediumStyle];
       startTime2 = [formatter stringFromDate:[NSDate date]];
    }
}

Comment: you can access to the appDelegate instance via [UIApplication sharedApplication].delegate
Comment: Why don't you just call a function in AppDelegate when the app starts and populate a local variable?
Comment: Yes, I did. Then I couldn't get the block in appdelegate via  [UIApplication sharedApplication].delegate.dateToolBlock .
Answer: Why not simply call a function in the AppDelegate when the app starts.(warning I have not tried compiling this).
- (NSString*)getStartDate {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterNoStyle];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    return [formatter stringFromDate:[NSDate date]];
}

Comment: thanks. The real demand is to get the date from the other class when it called the method `initialize`.
Comment: Then use a delegate protocol as suggested above.
Answer: You can get at your AppDelegate from anywhere by using the UIApplication's singleton method: [UIApplication sharedApplication].delegate
Just cast it as your custom class to access specific methods: (AppDelegate*)[UIApplication sharedApplication].delegate
That said, I don't think that's the right approach to take here. Your Datetool is a utility class and shouldn't be reliant on references to the AppDelegate, which makes for very tightly coupled code. Instead, Datetool should be able to be called from the AppDelegate and return the desired value. Since you're already using a class method, it doesn't seem like Datetool needs an instance at all. You can scrap storing the static value and just return what you need:
+ (NSString*)startTime
{
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   [formatter setDateStyle:NSDateFormatterNoStyle];
   [formatter setTimeStyle:NSDateFormatterMediumStyle];
   return [formatter stringFromDate:[NSDate date]];
}

Now you're pulling a value from the tool rather than trying to push it onto the AppDelegate, which makes it reusable for other purposes.
Answer: Would it be a bad idea to import the class definition to AppDelegate.h and instantiate the object within AppDelegate?
Comment: It's not clear from the question, but I think the OP is probably having compiler errors as it doesn't know what `dateToolBlock` is.  He needs to import `AppDelegate.h` and probably cast `[UIApplication sharedApplication].delegate` to `(AppDelegate *)`.
Answer: I suggest that you provide a delegate protocol in your DateTool which is implemented by your AppDelegate. For example (not tested):
DateTool.h:
/** The delegate protocol of DateTool. */

@protocol DateToolDelegate <NSObject>

/** The start date was set. */
- (void)startDateSet:(NSDate)startDate;

@end

@interface DateTool : NSObject

/** The delegate of DateTool. */
@property (weak) id<DateToolDelegate> delegate;

@end

DateTool.m:
+(void)initialize
{

   if (self == [DateTool self])
   {
       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
       [formatter setDateStyle:NSDateFormatterNoStyle];
       [formatter setTimeStyle:NSDateFormatterMediumStyle];
       startTime2 = [formatter stringFromDate:[NSDate date]];
       if ([_delegate conformsToProtocol:@protocol(DateToolDelegate)]) {
           [_delegate startDateSet:startTime2];
       }
    }
}

In AppDelegate.h you need to add the protocol:
#import "DateTool.h"
@interface AppDelegate : UIResponder <DateToolDelegate>

In your AppDelegate.m you need to register itself as delegate:
...
dateTool.delegate = self;
...

and implement the protocol:
- (void)startDateSet:(NSDate)startDate
{
// Do something with startDate
}

Hope that helps.
PS: Why is initialize a class method? I'd suggest to instantiate an object.


Form UX needs to be improved

Question: I have an Assessment Form (located here) which has got 70+ questions and seventeen steps to complete it which is a tedious job and respondent can easlity lose the patience.
All the question has only one Answer (Radio button only). Being that said, I want to modify the Form UX and planning to Group similar questions and use checkmarks so as to reduce the number of questions.

I am also thinking about having steps available on Left hand side so that it shows related Form with scroll may be. Here's a wireframe to make my thoughts more clear.

Do you think this will improve the usability of the survey and contribute to a higher completion rate?
Comment: A few questions for you: (1) What do the icons in the navigation represent? Right now, they don't really make much sense to me. (2) Are the section titles going to remain as "Stage 1, 2, etc..." or will they be more like category labels which group related questions? (3) What do the downward-pointing triangles before each of your questions represent? If there's no functionality behind it, I would lose them for the sake of removing clutter from a task that will already risk overwhelming the user (filling out 70+ questions).
Comment: The screenshot that I have shared (http://prnt.sc/c3jnuk) is just a dummy to make my thoughs more clear. Please have a look on the form  http://www.ngo-academy.org/online-ngo-assessment-tool/ to get better idea of current functionality Thanjs!
Comment: too complex. a survey should be short and simple. the number of items are outrageous. other than completion rate, you would also face challenge of veracity. would simply start revisiting those questions by reducing the numbers  - ranking them by priority and by impact.
Comment: Great suggestion @jonT
Answer: The form may be complex, but some tasks are indeed complex too. What isn't clear is whether the current complexity of the form is well suited to the problem or need. The trick is to get the right level of complexity for the task at hand. Applying for a mortgage is a lot more complex than signing up for a facebook account, and therefore requires a more complex form.
You mention that respondents can easily lose patience with the form. Can I ask if this has been determined through usability studies? If not, performing a usability study is one of the best ways of finding out what issues exist when it comes to forms.
One possible enhancement is to phrase the questions differently. For instance, many of the responses seem to follow a scale. One way of phrasing these types of questions is by using a Likert scale, which starts off with a statement, then asking the user to choose a response ranging from 'strongly disagree' to 'strongly agree'.
https://en.wikipedia.org/wiki/Likert_scale
For instance, question 3 on step 2 could be changed from:
'How well is the NGO performing technically in comparison with other NGOs?'
to:
'The NGO is performing well technically against other NGOs'
then using a Likert scale as the response mechanism.
Of course, I would strongly encourage you to find representative users of the form and recruit them for a usability study. Nothing beats user feedback as a way of testing and validating design decisions.
Comment: Thanks for the insights! I haven't got Usability Studies done for the Form, I  will consider this. Using Likert Scale for questions is also a good idea!
Answer: You might explore some of the writings of Caroline Jarrett (https://twitter.com/cjforms), something of The Queen of Forms:
http://www.formsthatwork.com
Comment: Great resources!
Answer: I think your problem is bigger than groupings and checkmarks.
Step one would be to give the form a hard edit. Shorten it as much as possible. Look closely at each question and evaluate whether its answer provides you any benefit. Will a change in responses to this question result in a change in your organization? Also look at whether the questions are vague or open to interpretation. (I saw some that are.) Those are the ones where the answers don't accurately reflect the users' true thoughts.
The longer a form is, the more likely the user will get interrupted midway through. So it's very important that you save the user's answers on each page and allow them to complete the form later. This will require some technical mumbo-jumbo or a registration. It will also require that you remind users of the form's unfinished state and provide some sort of enticement for them to come back and finish.
Answer: What problems are you trying to solve here? This should be the first thought when designing a form like this. Are the 70 questions necessary? If they are I'd recommend providing a timeframe for the user. So they know how much time the questionnaire will take to compete. If my employer asked me to complete a 70 question survey I might ignore it.

Form UX needs to be improved


get google maps link using gwt maps api

Question: How do you get the link to google maps image so i can attached to a email and send.  Using the google web toolkit api.
Answer: You can use Google Static Maps API to build a URL to get the image you need.
Google Static Maps
http://code.google.com/apis/maps/documentation/staticmaps/
Comment: @Eric, your edit could have been a stand-alone answer on its own, it adds _significantly_ to @Perishable's answer..

get google maps link using gwt maps api


rpmUtils.miscutils in python3.6

Question: I am refactoring code from python2(RHEL 7.6) to python3(RHEL 8.2) and I have problem with missing library in python3.6.
Problem:
<code>from rpmUtils.miscutils import splitFilename ModuleNotFoundError: No module named 'rpmUtils' </code>
I've tried to install python3-dnf and python3-rpm packages to RHEL8, but still not working. Is there any solution how to use this library in python3.6 and RHEL8 or should I write some custom function by myself?
Thank you for your answer.
Answer: This library was indeed removed, but you have several other options you can use.
Please note that these other functions expect to receive a string in the NEVRA (name, epoch, version, release, architecture) format as an input, not a filename. Thus you must remove the '.rpm' extension of the filename, in order to get a NVRA string (epoch normally is not included in the filename of the RPM package).
So basically you have 2 options:

to use dnf as suggested in i.e. https://bugzilla.redhat.com/show_bug.cgi?id=1364504

to use hawkey i.e. :
<code>  import hawkey

  rpm_base_filename = os.path.basename(rpm_file)
  nevra = hawkey.split_nevra(rpm_base_filename[:-len(".rpm")])
  name = nevra.name
  version = nevra.version
  release = str(nevra.release)
  epoch = str(nevra.epoch)
  arch = nevra.arch
</code>

For example here is a patch for such modification that I made for one of the tools we use as part of the oVirt release process:
https://github.com/oVirt/releng-tools/commit/823405e6b261f7ff27ddbba0e8fa2b86dd2a8698

rpmUtils.miscutils in python3.6


How to restore the down arrow icon on the Downloads folder in the home directory?

Question: I removed the original Downloads folder in the home directory and created a new one with the same name, but the down arrow icon on the new Download folder now disappeared. Could someone please tell me how to restore that icon?

In addition, from the image above we see "Downloads" disappears also in "Places" category in the left panel. I think it should be there originally. If after restoring the down arrow icon, the "Downloads" is still not in "Places" category, I would also like to ask you to help me put "Downloads" back to "Places". Thank you.
PS: I am not using any theme.
Comment: This might be the straightforward answer you've been looking for: https://unix.stackexchange.com/a/606950/19643
Answer: To change the icon, right click on the Downloads folder and select the Properties option. Now click on the folder icon in the properties window. It will give you an option to select a custom icon.

Navigate to /usr/share/icons/Humanity/places and select the appropriate icon.
To add an entry in the places menu, you have to edit the ~/.config/user-dirs.dirs file.
nano ~/.config/user-dirs.dirs

Add the following entry and press ctrl+X to save -
XDG_DOWNLOAD_DIR="$HOME/Downloads"
Comment: Thank you so much. PS: I chose the 48 size and it fits well.


Solving a differential equations but an error appears saying "'Add' object is not callable". I am using Jupyter Notebook

Question: To make it clearer I want to plot the solutions of the 2nd order differential equation of the damping oscillation for a pendulum. Link to wiki about the equations used : https://en.wikipedia.org/wiki/Harmonic_oscillator
from sympy.interactive import printing
printing.init_printing(use_latex=True)
import numpy as np
import scipy as sp
from sympy import*
mport sympy as syp
`from scipy.integrate import odeint
import matplotlib.pyplot as plt

t=syp.Symbol('t')
x=syp.Function('x')(t)
m=2.0
k=5.0
a=0.5
z=a/(2.0*np.sqrt(m*k))
w=np.sqrt(k/m)
eq=x.diff(t,t)+2.0*z*w*x.diff(t)+w**2.0*x
dsolve(eq,t,0,ics={eq(1.0):0,eq(2.0):5})

Answer: You're not constructing the ics argument as intended:
In [6]: dsolve(eq, ics={x.subs(t, 1.0): 0, x.subs(t, 2.0): 5})
Out[6]:
                                                                                -0.125⋅t
x(t) = (-0.0346285740992263⋅sin(1.57619002661481⋅t) - 6.42012708343871⋅cos(1.57619002661481⋅t))⋅ℯ

The answer comes out nicer (subjectively) if you don't use floats. Also I find it more natural to keep the variable x as the function x rather than the applied function x(t) e.g.:
In [15]: x = Function('x')

In [16]: x
Out[16]: x

In [17]: x(t)
Out[17]: x(t)

In [18]: eq = x(t).diff(t, 2) + x(t).diff(t)/4 + 5*x(t)/2

In [19]: eq
Out[19]:
         d
         ──(x(t))     2
5⋅x(t)   dt          d
────── + ──────── + ───(x(t))
  2         4         2
                    dt

In [20]: dsolve(eq, x(t), ics={x(1): 0, x(2): 5})
Out[20]:
       ⎛   1/4    ⎛√159⋅t⎞                     ⎞  -t
       ⎜5⋅ℯ   ⋅sin⎜──────⎟                     ⎟  ───
       ⎜          ⎝  8   ⎠      1/4    ⎛√159⋅t⎞⎟   8
x(t) = ⎜────────────────── - 5⋅ℯ   ⋅cos⎜──────⎟⎟⋅ℯ
       ⎜       ⎛√159⎞                  ⎝  8   ⎠⎟
       ⎜    tan⎜────⎟                          ⎟
       ⎝       ⎝ 8  ⎠                          ⎠

Comment: Thank you for your suggestion and for your time. Although i tried your solution however this error poped out "Python int too large to convert to C ssize_t" and i don't know how to overcome this also.
Comment: That error does not come from the code that I showed. I expect that you are mixing up numpy and sympy somewhere.


Adding a delay to droppable event

Question: I have a droppable element with a dropover event handler. Dragging an element over the droppable expands a node. However, I want to add a delay so the node does not expand immediately, i.e. you have to hold the draggable over the droppable for a second before it expands.
droppable.over = function(event, ui) {
    // expand node if dragover lasts 1000 milliseconds
    node.expand();
};

My first thought was to simply use setTimeout on node.expand(), but this doesn't do what I want, it simply delays the node expanding. It doesn't look like there's any configuration I can set to achieve this, so I'm wondering how I can do it.
Comment: You might consider having a global variable that you set = to the timeout and have another function for when the mouse goes out to cancel the setTimeout job.
Comment: No sure if you might be able to adapt the following so it detects if user is hovering while dragging an element. http://cherne.net/brian/resources/jquery.hoverIntent.html
Answer: Something like this maybe?
var globalTimer;

//..
droppable.over = function(event, ui)
{
    globalTimer = setTimeout(function(){node.expand()}, 1000);
},
droppable.out = function(event, ui)
{
    clearTimeout(globalTimer);
};

Comment: Thanks, this seems like the best option.
Answer: try adding this setTimeout(function () { node.expand() }, 1000);
but I might misunderstood you, do you want the node to appear later or appear only if it stays in the droppable for 1000 ms?
Comment: I tried this already as I described in my question, but this isn't the behavior I'm looking for. I only want the node to to expand if it's in the droppable for 1000 milliseconds.

Adding a delay to droppable event


bash protect HD from excessive use

Question: How do I avoid breaking the HD? I have a bash script running on an ubuntu machine, with this meta code:
bash1.sh
while(true)
 run bash2.sh
 sleep 60 seconds
done

bash2.sh:
if(directory is empty): exit
process file
delete file

The directory is network shared, and the computer is not doing anything else. Once per day a new file arrives and is processed. (I do know that bash1.sh can be replaced by watch). My concern is that bash1.sh is reading bash2.sh everytime - that can presumably be avoided by only having one script!? and bash2.sh is reading the same directory everytime. Is the directory really read from the HD, or is ubuntu somehow caching the dir in ram? -so it is only read when something changes? is it a problem that it is the same place on the HD that is read every time, or does it not matter because the HD is already spinning? If the HD never sleeps, does it matter if I set the loop time down to only one second?
Maybe the directory could be a pure ram dir - how do I do that? -or is there some simple way to check if something has arrived over the network without reading the directory?
Answer: Reading a file or directory once every sixty seconds is not excessive use.
Seriously, don't worry about it.

If it's really worrying you, you can rethink your strategy for detecting the file.
For example, do you really need to know, within sixty seconds, that the file has arrived? Can it arrive any time during the day? Can some parts of the day be considered unlikely?
Using information like that, you can adjust the timing of checks to suit. If the file is supposed to be delivered after 4pm, don't check for it at all before then.
Check for it every sixty seconds between 4pm and 5pm, then every ten minutes after that.
These are all business-related decisions that can be made but I would still suggest that it's unnecessary. Provided you regularly back up your disks (and have standby hardware if you need to be back up in a hurry), you shouldn't lose anything.
In fact, if you were really paranoid, you could dedicate an entire machine for this, whose sole purpose is to receive the file via FTP and, when it arrives, send it across to your real processing box.
Put nothing else on that machine and have a warm standby (exactly same software, IP address and so on but powered down) so that, if it fails, the standby can be activated in minutes.
The real processing machine is then only written to once a day - that's unlikely to affect the disk lifetime.
That's probably too paranoid for my liking but it shows that there are ways to mitigate almost any problem.
Comment: OK - then how about every second for several years? I know that it is not a lot of data, but the HD will never have a chance to spin down!?
Comment: @Hans, modern drive with their SMART tech will run for years quite happily, even under load - we tend to replace ours on three-year cycles, including loaded-up servers (these ones are backed up more frequently however, just in case) and have only rarely suffered genuine loss in that cycle time. What you have is _not_ load.
Comment: If it's really worrying you, you can rethink your strategy for detecting the file. I'll update the answer.

bash protect HD from excessive use


Vector Fields on $\mathbf R^2$

Question: Let $X : \mathbf R^2 \to \mathbf R^2$ be a no-zero smooth vector field. I want to show (without background about vector bundles or manifolds, just if possible differentiable calculus in $\mathbf R^n$) that there is a smooth function $\psi : \mathbf R^2 \to \mathbf R^2$ such that $ d_p\psi(X_p)$ is constant $\forall\ p \in \mathbf R^2$.
Thanks in advance!
Comment: Did you try using the Mobius band?
Answer: Interesting question.
If such a function $\psi$ exists then $\psi$ takes the integral curves of $X$ to a family of parallel lines in $\mathbb{R}^2$. This puts strong restrictions on the family of integral curves. For instance, the orbit space of $X$ - meaning the quotient space obtained by collapsing each integral curve to a point - must be homeomorphic to $\mathbb{R}$.
However, there are counterexamples where the orbit space of $X$ is not homeomorphic to $\mathbb{R}$. For example, you can put the universal cover of this foliation in each horizontal strip $\mathbb{R} \times [n-1,n]$. The resulting orbit space is not even Hausdorff, let alone homeomorphic to $\mathbb{R}$.

Vector Fields on $\mathbf R^2$


In Postgresql, how to un-invert the timezone offsets with "At Time Zone"

Question: I'm trying to wrap my head around Postgresql timezones, and I can't seem to figure this out. EST is "Eastern Standard Time" in America, and is typically UTC-5.
Example 1: Base Test
select '08/31/2011 12:00 pm EST'::timestamptz  at time zone 'EST';
      timezone
---------------------
 2011-08-31 12:00:00

Example 2: Offset is +5
select '08/31/2011 12:00 pm EST' at time zone '+5';
      timezone
---------------------
 2011-08-31 12:00:00

Example 3: Offset is -5
 select '08/31/2011 12:00 pm EST' at time zone '-5';
      timezone
---------------------
 2011-08-31 22:00:00

Clearly, everything is backwards. EST is again... supposed to be UTC-5. Now, I did search through documentation, and it does explain that things are "POSIX", which is backwards. (Positive offset is west of GMT, while negative offsets are east of GMT).
However, how do I get around this? At the application layer, I can always invert the + sign to a - sign, but that seems a bit messy to me IMO. Thus, my ultimate question.
At the database layer (Postgres), is there a way to use the "At Time Zone" syntax so that GMT-5 corresponds to EST? Or do I just have to invert everything at the application layer?
Answer: Use interval datatype as written in documentation to get proper behaviour:

In these expressions, the desired time zone zone can be specified
  either as a text string (e.g., 'PST') or as an interval (e.g.,
  INTERVAL '-08:00').

Base test:
SELECT '08/31/2011 12:00 pm EST'::timestamptz AT TIME ZONE 'EST';
      timezone
---------------------
 2011-08-31 12:00:00
(1 row)

Timezone info:
SELECT * FROM pg_timezone_abbrevs WHERE abbrev LIKE 'EST';
 abbrev | utc_offset | is_dst
--------+------------+--------
 EST    | -05:00:00  | f
(1 row)

Proper offset -5:
SELECT '08/31/2011 12:00 pm EST'::timestamptz AT TIME ZONE '-05:00'::interval;
      timezone
---------------------
 2011-08-31 12:00:00
(1 row)

Proper offset +5:
SELECT '08/31/2011 12:00 pm EST'::timestamptz AT TIME ZONE '+05:00'::interval;
      timezone
---------------------
 2011-08-31 22:00:00
(1 row)

Comment: Lol. That link you have has a link to the Postgresql Documentation. Oh well, I guess I just didn't read all of the manual. Thanks for the link, I guess I'll just read more carefully next time.
Comment: Thanks. I couldn't find this feature documented anywhere. Do you know where you learned about this?
Comment: @Dragontamer5788: Sure, I found this on http://postgresql.1045698.n5.nabble.com/Behavior-of-quot-at-time-zone-quot-td1928049.html


What is the most expensive item obtained from the Mixer in Wonderful 101?

Question: There is one item which costs 30 of each ingredient. All other items are health recovery items (the left panel) or attack all items I think (right panel, except the lowest). But the lowest item is nothing of the above. What is it? Below is a self-made picture of the mixer.
Answer: That item in the bottom-right is a Wonderful Card, and is indeed by far the most useful item you can mix - it acts as a freebie for any one thing from the store. Something you want costs far more money than you have? Throw a Wonderful Card at it, and it's free. Mix as many as you can and use them on whatever the best or most expensinve thing available is; you get enough recovery items through the levels that you shouldn't really need to mix them yourself.


How can I get the RGB value of a given cell in a xlsx file using python?

Question: Given a row and a column (plus sheet name) I need a way to extract the rgb value for a cell, as reported within excel, from a python script.
I've been using openpyxl. The following do not work consistently:
cell.fill.fgColor.rgb
cell.fill.bgColor.rgb

The following give the wrong value:
openpyxl.styles.colors.COLOR_INDEX[cell.fill.fgColor.index]
openpyxl.styles.colors.COLOR_INDEX[cell.fill.fgColor.index]

So I'm looking for another way to do it. Possible solutions need not be limited to the openpyxl library, as I'm willing to use another one.
Comment: What do you mean by "do not work consistently", what are you getting? If you have a new xlsx file, what are the cell colours?
Comment: Sometimes it will have a valid and correct rgb value when dealing with, say, a blue cell, but other times it will not.
Comment: In a new xlsx file, colored cells have rgb 'None', attempting to access the rgb returns the string 'Values must be of type '.
Comment: Do you use Python/Excel for Windows?
Comment: Yes. (character limit)
Comment: Because the python implementation might not be doing the "right thing." I would back up to excel and look at this question http://stackoverflow.com/questions/24382561/excel-formula-to-get-cell-color and also this http://dmcritchie.mvps.org/excel/colors.htm and from there compare what you are getting from openpyxl and from within excel.
Answer: Consider win32com library if using Python for Windows as it can access the Excel Object Library and use any of its methods and properties such as Workbooks.Open, Interior.Color, Workbook.Close.
Using this interesting link for RGB value extraction, you can translate VBA to Python. Specifically, VBA's integer division operator, the backslash, \, translates to Python's double forward slash, // and the modulo operator in VBA mod becomes Python's %
Below outputs the RGB of a yellow-colored cell. Both cell reference types are included. Entire routine is wrapped in a try/except/finally to close background processes and release resources with or without a runtime error.
import win32com.client as win32

def getRGB(xlCell):
    C = xlCell.Interior.Color

    R = C % 256
    G = C // 256 % 256
    B = C // 65536 % 256

    return "R={}, G={}, B={}".format(R, G, B)

try:
    xlApp = win32.gencache.EnsureDispatch('Excel.Application')
    wb = xlApp.Workbooks.Open('C:\\Path\\To\\Workbook.xlsx')
    ws = wb.Worksheets('RESULTS')

    print(getRGB(ws.Range("A2")))      # A1 Style Reference
    # R=255, G=255, B=0  (yellow-colored cell)

    print(getRGB(ws.Cells(2,1)))       # R1C1 Style Reference
    # R=255, G=255, B=0  (yellow-colored cell)

    wb.Close(False)
    xlApp.Visible = False

except Exception as e:
    print(e)

finally:
    xlApp.Quit
    ws = None
    wb = None
    xlApp = None

Aside, do note VBA is NOT part of MS Excel but an external component (by default connected to the software). It is just another language to connect to Excel's object library as any programming language demonstrated here with Python can make a COM interface to this library.
Answer: So this isn't an answer but it will be useful to folks who want a quick fix.
Using Microsoft Excel 2007 (but I believe most versions), if you go to Format Cells, choose Fill tab, and then select a color for Background color, the ten basic colors at the bottom always work for me.
However I've had only intermittent success with the gradient colors above those.
I mention this is a quick fix because if for your program, you want a simple way to bookmark cells for some function rather than the cell contents, you can still do this if you stick with the ten basic colors.
I found it easier doing that, rather than importing another library just to handle the extra colors I don't need anyway.
Answer: The solution by @Parfait is excellent. But I improved getRGB(), I think shifting will be better than redundant N divisions:
def getRGB(xlCell):
    C = int(xlCell.Interior.Color)

    R = C & 255
    G = C >> 8 & 255
    B = C >> 16 & 255

    return "R={}, G={}, B={}".format(R, G, B)


How to create array of objects with unique key/values pairs from another array of objects?

Question: I'm trying to achieve from this array of objects one smaller array of objects with unique key/value pairs.
This is the array from which I want to get a group and its value.
This is the main array of objects:
let samples = {
    {
       id: 2,
       group: 'picturesWithDescription',
       elements: [
            {
                id: 1
            },
            {
                id: 2
            }
           ]
        },
        {
            id: 3,
            group: 'footers',
            elements: [
            {
                id: 1
            },
            {
                id: 2
            }
           ]
        },
        {
            id: 4,
            group: 'movies',
            elements: [
            {
                id: 1
            },
            {
                id: 2
            }
           ]
        },
        {
            id: 4,
            group: 'movies',
            elements: [
            {
                id: 1
            },
            {
                id: 2
            }
           ]
        }
    }

And this is something I would like to achieve:
let result = [
{group: 'picturesWithDescription'},
{group: 'footers'},
{group: 'movies'}
]

Answer: Assuming that samples is an array as said in question.
Try following

let samples = [{id:2,group:'picturesWithDescription',elements:[{id:1},{id:2}]},{id:3,group:'footers',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]}];

/* 1. Create an array with only group names
** 2. Convert it into Set to remove duplicates.
** 3. Convert back to array.
** 4. Create an array with object with group property. */
let result = [...new Set(samples.map(({group}) => group))].map((group) => {return {group}});

console.log(result);

OR

let samples = [{id:2,group:'picturesWithDescription',elements:[{id:1},{id:2}]},{id:3,group:'footers',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]},{id:4,group:'movies',elements:[{id:1},{id:2}]}];

/* 1. Reduce the array into an object with group names as key (removes duplicate)
** 2. Iterate over the keys (group names) and create an object with group property*/
let result = Object.keys(samples.reduce((a,{group}) => {a[group] = group; return a}, {})).map((group) => {return {group}});

console.log(result);
Comment: Good to hear this :)


Woocommerce - Variation Swatches for WooCommerce Plugin - REST API for the attribute terms custom field?

Question: I've been using this plugin for a little bit and it's perfect for what i need. The unfortunate thing is however that i'm looking to build the attribute colours programatically. Because of that i'm having issues assigning the colour hex code for the swatches.
The only way i've been able to successfully do this is by doing the following:

Use Rest API to create the attribute colour if it doesn't exist
Use Rest API to retrieve the attribute and it's fields after being created
CURL using the information retrieved in order to adjust the attribute term in the table

While this works per se it's not exactly an elegant solution. I could also use mysql as well to do the same, however i don't like the idea of having a remote database connection for this to work.
Does anyone have any ideas?
Answer: Rather than go ahead with the curl idea, i decided to be incredibly secure about my mysql connection.
For anyone who's curious, the table you need to edit is wp_termmeta
<code>insert into wp_termmeta (term_id, meta_key, meta_value)
VALUES ("<your_created_attributes_id>", "<colour_taxonomy_name>", "<hex_value_for_colour>");
</code>


Physically realistic received irradiance values given some BRDF?

Question: I am trying to simulate the actual response of a camera given some object that is reflecting light.  I've written a ray tracer, and have a BRDF that I need to use, and I have a camera sensitivity in terms of signal/Watts.  But I am confused by one (rather important) detail:
Each ray coming out of the camera has some solid angle associated with it (this part I've already figured out).  So each ray should then have a "Radiance" value associated with it (as radiance has units of W/(sr*m^2)).  That way each ray would just multiply its solid angle by its radiance value, and you'd get an "Irradiance" value of W/m^2.  However, I am unsure how to actually calculate this initial radiance value for each ray.  The reason I am confused is because this seems to be backwards from what the BRDF is giving me.
A BRDF gives me the radiance leaving the surface in the direction of the camera, meaning the vertex of the solid angle is at the point of intersection.  The solid angle for the ray however is defined flipped, with the vertex of the solid angle at the camera itself.
How do I bridge this gap?  My idea is that is that if I can actually calculate the radiance for each ray, then I can simply multiple the radiance of each ray by its corresponding solid angle to get an irradiance value, then apply the inverse square law, and finally add up the irradiance for each ray per pixel and divide by the area of the pixel to get the wattage it receives.
But I am very lost as to how to calculate the radiance for each ray given that the only calculations I'm familiar with (the BRDF) returns a radiance value for a solid angle in the "wrong direction".
Am I misunderstanding what is going on?  Am I approaching this incorrectly?  Any help would be really appreciated!
Answer: I didn't get this part:

That way each ray would just multiply its solid angle by its radiance
  value, and you'd get an "Irradiance" value of W/m^2.

I'll try to explain how the whole thing works though. You have a light source, it emits light rays. Those light rays bounce around the scene and eventually end up at your camera film. So at the end of the day you have multiple rays hitting the film surface and the radiance of those gets multiplied with the sensitivity function. For efficiency reasons you usually start backwards - from the camera. But if you work with symmetric BRDFs this should not matter. So what arrives at your film is radiance, you multiply that radiance with the sensitivity function and integrate within a "film pixel" to get the result in terms of your screen pixel.
Edit: To clarify what I meant by integrated out:
If you have radiance which is a measure of W/(sr * m^2), you can integrate out sr or m^2 like so:
$$E(x) = \int_{\Omega}{L(x,\omega)\cos\theta\,d\omega}$$
From where you get irradiance at a point $x$, which gives you the energy arriving from all directions at point $x$ (W/m^2). Now you can go further and find out the energy that arrives at some surface with area A, by integrating over all points on the surface:
$$\Phi = \int_{A}{E(x)\,d\mu(x)} = \int_{A}\int_{\Omega}{L(x,\omega)\cos\theta\,d\omega\,d\mu(x)}$$
Comment: What I meant by the comment you copied is that the sensitivity function I have to work with is a function of Watts.   Radiance has units of W*m^-2*sr^-1.  So if I multiply the radiance value by the solid angle represented by the ray, then I would get an irradiance value, with units W*m^2.  I then multiply that by the surface area of the pixel that the ray originated from the get the Watts received, which I can then use in the sensitivity calculation.
Comment: But the part that is confusing me is that the solid angles of the BRDF and of the ray appear (at least to me) to be opposite one another.  The BRDF deals with solid angles whose vertex is at the point of intersection on the surface.  The rays on the other hand have a solid angle with its vertex at the camera (more specifically, somewhere on the pixel that it was sent from.  If no super sampling is done, then it originates just from the pixel center).  So at the intersection point, the ray forms a cone in one direction, while the BRDF forms a cone in the exact opposite direction
Comment: You're not multiplying radiance by a solid angle, to get a different measure you're integrating out the steridian part. Granted you're integrating over the solid angle, but multiply the radiance with the solid angle doesn't make much sense. The BRDF is not something related to the camera, its simply a function that describes the scattering properties of a surface at some point. It just tells you how ray coming from direction A scatters (and vice-versa).
Comment: With graphics:  [Here is a simple diagram of a ray] (https://upload.wikimedia.org/wikipedia/commons/b/b2/RaysViewportSchema.png).  It is diverging away from the camera, so the solid angle of incoming light to the sensor represented by the ray has its vertex at the camera origin.  [This diagram of a BRDF](https://www.researchgate.net/profile/David_Delafosse/publication/256444960/figure/fig1/AS:297976355409923@1448054507535/Geometry-for-the-definition-of-the-BRDF_W640.jpg) shows that the solid angle diverging off the surface.  Which is opposite how the ray looks at that point
Comment: I understand it has nothing to do with the camera, but the rays reflected off the object are diverging away from the point they reflected off of.  The camera rays however, are diverging from the camera, not the point they intersect.
Comment: It doesn't matter, BRDFs are usually symmetric (at least if they are to be physically based). Also a common convention is to have both directions point out in the BRDF: https://en.wikipedia.org/wiki/Bidirectional_reflectance_distribution_function
I still don't get what your question is really. Can you try and formalize this.
Comment: Also, I'm not entirely sure what you mean that the steradian is being integrated out.  Each ray has some associated solid angle with it which if not accounted for, would mean that adding more and more rays per pixel would increase the brightness per pixel.  Giving each ray an appropriately scaled solid angle allows you to ensure adding more rays doesn't increase the actual signal, rather just increases sub pixel resolution.  At least, that is how it was explained to me.
Comment: [Here is a drawing of what I mean](https://i.imgur.com/OEUrblI.png).  Tracing the light forward makes perfect sense.  It is reflected in some manner, and is now diverging away from the reflection point (indicated by the green arrows).  The red line is the traced intersection point of the ray, which also makes sense.  However, it is my understanding that the rays are diverging from the camera, and so I represented them with the blue arrows.  This means that they are diverging in opposite directions which leaves me confused as to how the reflection value can be transfered to the ray.
Comment: @ChrisGnam See the edit. A possibly easier to understand analogy is through acceleration, speed, and distance. If you have the acceleration function for an object over time, you can find its speed at each point in time by integrating the acceleration (which integrates out 1/s, so from m/s^2 you get m/s). You can also integrate speed over time to get distance traveled (that gets rid of the other 1/s and you get from m/s to m).
Comment: @ChrisGnam The Bi-directional part in BRDF stands for the fact that it is symmetric. It shouldn't matter in which direction the radiance travels, since both are equivalent under the assumptions made.
Comment: Thank you that does help somewhat.  Do you have any recommendation on textbooks or papers or anything that covers the math used here in rigorous, yet understandable terms?
Comment: @ChrisGnam I recommend Advanced Global Illumination. But depending on your background, you may not find it rigorous enough, in which case you can refer to Eric Veach's thesis, Mathias Lang's thesis, or Christian Lessig's thesis (this one is the most abstract that I know of and the hardest). Refer to the acknowledgements section here for more resources: https://vchizhov.github.io/resources/ray%20tracing/ray%20tracing%20tutorial%20series%20vchizhov/index.html
Comment: thank you for the help.  I've ordered the textbook and I'm looking forward to reading it!  I hate to ask one more question, but I must know.  Having calculated the reflected light off of the object, do I apply the inverse square law to that irradiance to obtain the irradiance received by the camera?  Or is that accounted for by the fact that the object is so far away that it takes up a small pixel area?
Comment: @ChrisGnam Depends on whether you use the area or the solid angle formulation of the rendering equation. See my answer here: https://computergraphics.stackexchange.com/questions/9015/rendering-equation-in-terms-of-paths-rather-than-directions


Get gridview column values using jQuery

Question: Please excuse formatting on this but we can not connect to and post to any public sites so this is posted from my phone.
We have an ASP.Net gridview with checkboxes. We have logic that will look for what values are checked or not. The only issue we have is that we have one case that opens another window with a new page based on those check boxes. The user might have checked more check boxes since the last post back so we are going through the gridview to check that page of data and get checked values.
I can get the checked boxes with no problems. The problem is I am not sure how to find the value from another column.
I can not post much code, but I did get permission to post this much.
function myfunctionname (gridviewid){
    var myvalue = "";
    $('#' + gridviewid + ' input[type=checkbox]:checked').each(function (index){
        myvalue = myvalue + $(this).IDontKnowWhatINeedHere
    });
}

I have tried .find(), .parente(), .name() and many other things. Basically I always have undefined, a jQuery function, or an error no matter what I have tried.
What I am trying get for is, since I have the correct checkbox, I want to get the parent row and get the value from a label generated as a span in another column.
Anyone have any ideas where to go from here to get to my next step?
Thanks
Comment: Assuming that checkbox is inside of table cell - `.parent()` should give your the TD and then just traverse siblings, e.g. `.parent().next()` - should give you the next cell
Comment: Thanks for the help everyone .closest was exactly what I needed. I knew it had to be simple, but just could not find exactly what I wanted no matter how much I searched.
Answer: The first problem is to find the parent row.
$(this).closest('tr');

will get you to the parent row of the checkbox.  You can get the list of columns in the row like this:
var tds = $(this).closest('tr').find('td');

Then once you have that you can just use the .eq function and the index of the column you are looking for like this
var col = tds.eq(index);

Then you should be able to get the value from inside the span like this:
var spanValue = col.find('span').text();

Re: .eq() and .closest()
Answer: You can get the text from a  on another column by getting the parent
, after that, you can find the correct column by index or, more recommended, find by ID or class attribute:
...

    <input type="checkbox">
    ...
    Here
    ...

...

Notice that I used closest(). This method searches up the DOM for the first parent that it founds with the specifiled selector. In this case, it will traverse the DOM up until the parent
 of the checkbox. From there you can search down for any children.
Answer: Without seeing the code I could guess at a possible solution. The jquery function "closest".
http://api.jquery.com/closest/
this is probably a bad example but it shows how it could work or maybe help.

label<input type="text" name="randomName" id="randomName"/>

label<input type="text" name="randomName1" id="randomName1"/>

Get gridview column values using jQuery


bash: syntax error near unexpected token `do'

Question: Tried searching around and couldn't find a direct answer to my problem, as all other codes out there appear to be doing what I'm doing. I'm working on a shell scripting exercise to calculate averages for a class, and I've made it to this point using our reference scripts, however I'm getting errors about the syntax (error at bottom of code)
#!/bin/bash

avg=0
temp_total=0
number_of_args=$#

# First see the sufficient cmd args
if [ $# -lt 2 ] ; then
        echo -e "Oops! I need at least 2 command line args to calculate an average\n"
        echo -e "Syntax: $0: number1 number2 ... numberN\n"
        echo -e "Example:$0 5 4\n\t$0 56 66 34"
        exit 1
fi

# now calculate the average of the numbers given on command line as cmd args for i in $*
do
     # addition of all the numbers on cmd args
        temp_total='expr $temp_total + $i '
done

avg='expr $temp_total / $number_of_args '
echo "The average of all the numbers is $avg"

So, the error I'm getting is
./avg.sh: line 16: syntax error near unexpected token `do'
./avg.sh: line 16: `do'

I can't find anything particularly wrong around that area, so I was hoping someone could help me out! Thanks!
edit: In particular, I've tried removing the comments on the off chance that they were causing issues, to no avail. I re-typed the section as well. I also tried finding different ways to handle that portion, but most averaging scripts seem to handle it in a very similar fashion, so I'm at a loss!
Answer: The error message complains about an unexpected do because you used it wrong: do is a reserved word used in for, case, while and until loops. As the preceding comment ends with for i in $* I assume you just forgot to add a line break there:
# now calculate the average of the numbers given on command line as cmd args
for i in $*
do
  # addition of all the numbers on cmd args
  temp_total='expr $temp_total + $1 '
done

man bash/SHELL GRAMMAR/Compound Commands explains how to build for and other loops. If you simply want to loop over every argument bash also supports a short form, I'll combine it with bash Arithmetic Expansion here:
# now calculate the average of the numbers given on command line as cmd args
for i
do
  # addition of all the numbers on cmd args
  temp_total=$((temp_total+i))
done

Answer: You can also get this error from non-breaking spaces at the start of each line (happened to me when I copied code out of a Word document that used tabs and pasted it into Mac Notes to edit).


Passing integer variables into SQL statement from another form

Question: I'm working with a school project where we are supposed to build a simple booking system that utilizes SQL database. Used language is C# and environment Visual Studio Community 2017. I'm trying to build a function where user selects a row from dataGridView1 and clicks 'Add new invoice button'. The booking_id is extracted from dataGridView1 and passed to Form2 where booking-related data is searched with booking_id. This data is then presented in dataGridView2 which lists all services included in the one user-specified booking.
Database contains three relevant tables; Booking, Service and BoughServices.

Booking contains column booking_id (INT)
Services contains columns service_id (INT), name (VARCHAR) and price (INT)
BoughtServices, contains columns Booking.booking_id (INT),
Service.service_id (INT) and amount (INT)

Code on Form1:
// Establish a class for data.
public static class DataToForm2
{
    public static int booking_id;
}

// User clicks button 'Add new invoice'.
private void button_CreateInvoice_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2();

    //Note: CurrentRow.Cells[0] contains booking_id.
    DataToForm2.booking_id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
    f2.Show();
}

Code on Form2:
private void Form2_Load(object sender, EventArgs e)
{
    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        // Set SQL query string.
        string query = "SELECT Service.name, Services.price, BoughtServices.amount " +
            "FROM Service " +
                "INNER JOIN Service.service_id ON BoughtServices.service_id " +
                "INNER JOIN Bookings ON Bookings.booking_id = BoughtServices.booking_id " +
            "WHERE " +
                "Booking.booking_id = @booking_id";

        SqlCommand command = new SqlCommand(query, connection);

        // Set query parameters.
        command.Parameters.Add("@booking_id", SqlDbType.Int).Value = Form1.DataToForm2.booking_id;

        // Run SQL query
        var dataAdapter = new SqlDataAdapter(query, connection);
        DataSet ds = new DataSet();
        dataAdapter.Fill(ds);
        dataGridView1.ReadOnly = true;
        dataGridView2.DataSource = ds.Tables[0];
    }
}

However, this approach is non-functional and crashes with an error System.Data.SqlClient.SqlException: Must declare the scalar variable "@booking_id. I have spent an increasing number of hours to figure this out and find solution from tutorials but so far they all have failed. Interestigly, everything is working just fine when I add booking_id directly to SQL statement. In otherwords, WHERE Booking.booking_id = 2 works like a charm.
Could someone help me and propose how I should format my code so that I am able to perform desired actions? Thank you in advance!
Comment: You need to add Parameters and fill in the values you said you were going to
Answer: Almost right. The only problem is the SqlDataAdapter that receives the sql string and not the command where you have defined the parameter. Just change
// Run SQL query
var dataAdapter = new SqlDataAdapter(command);

As you can see there is a SqlDataAdapter's constructor that receives a SqlCommand where you could define parameters and set the connection.
Comment: Works like a charm! Thank you so much for your help Steve!
Answer: You're using the parameterized SQL query incorrectly. It functions more like string.Replace than an assignment. Try
command.Parameters.Add("@booking_id",
Form1.DataToForm2.booking_id);

Comment: The syntax used is perfectly valid.


Visual Studio launch error: Retrieving the COM class factory for component with CLSID failed with Access is denied error

Question: I have recently installed visual studio 2022 on my machine. I am getting this error on startup: Retrieving the COM class factory for component with CLSID {177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D} failed due to the following error: 80070005 Access is denied.
I tried installing 2019 and got the same error. Attaching the below screenshot:

The activity log is showing me the same thing in detail
<entry>
<record>153</record>
<time>2021/12/25 16:16:04.905</time>
<type>Error</type>
<source>VisualStudio</source>
<description>SetSite failed for package [Visual Studio Common IDE Package]Source: 'mscorlib' Description: Retrieving the COM class factory for component with CLSID {177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.VisualStudio.CommonIDE.PreviewFeatures.UsePreviewSdk.IsPreviewChannel()
   at Microsoft.VisualStudio.CommonIDE.PreviewFeatures.UsePreviewSdk.Initialize()
   at Microsoft.VisualStudio.CommonIDE.BasePackage.<InitializeAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.CommonIDE.CommonIDEPackage.<InitializeAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Shell.AsyncPackage.<>c__DisplayClass20_0.<<Microsoft-VisualStudio-Shell-Interop-IAsyncLoadablePackageInitialize-Initialize>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Threading.JoinableTask.<JoinAsync>d__76.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.VisualStudio.Services.VsTask.RethrowException(AggregateException e)
   at Microsoft.VisualStudio.Services.VsTask.InternalGetResult(Boolean ignoreUIThreadCheck)</description>
<guid>{6E87CFAD-6C05-4ADF-9CD7-3B7943875B7C}</guid>

80070005 - E_ACCESSDENIED

<errorinfo></errorinfo>

I tried setting up the permission level of my current local user in my windows 10 OS to full control. But it is not working.
I even followed this link to troubleshoot. Followed the solution there but still no luck.
I know it is not directly related to the visual studio but something is wrong with the permission level set for my machine's local user, the setting of which I haven't changed but still I am not able to find any solution for this.
Comment: https://developercommunity.visualstudio.com/t/access-denied-for-visual-studio-common-ide-package/962361
Comment: @HansPassant, I did follow the same steps as mentioned in the link, i.e.  reset the permissions for that folder to its defaults, but still getting the same error
Answer: Finally found a solution to my issue after so much hustle. From the start, it was evident that there was some issue with the permissions given to the user installing the visual studio installer. Although my user was an admin user. Basically, I followed the below steps to get it resolved:

Run the installer as an administrator(Right-click --> Run as administrator)
Before this navigate to Program Files --> Microsoft Visual Studio
Right-click --> properties --> security(make sure administrators have full control)
Secondly Right-click --> properties --> security --> advanced --> change the owner of the setting to administrator
Also make sure that replace all child objects checkbox are checked
Now run the installer as admin.
This solved the issue for me. Hope this helps others too, facing similar issues.


Do I have to replace this entire valve or can it be fixed?

Question: My bathtub/shower faucet has been constantly dripping and I took it apart to try and get it repaired.
Here is what is on the inside:

I would rather, for obvious reasons, avoid having to take the valve out, but I am not sure how to proceed at this point.
1. is there a  way to repair this valve in place?
2. If not how do I go about getting this thing out?
A "good enough" fix to keep it from dripping temporarily would be fine, I plan to remodel this bathroom completely in the near-ish future.
Answer: This is definitely a Moen shower valve, with a common Moen cartridge. There is no "seat" per se. You can perform a simple replacement of the cartridge and it should solve your problem. First you need to shut off the hot and cold water supply.
If you look closely, there is a horseshoe shaped retaining clip with a small hole at the top of the inverted "U", this holds the cartridge in. Once the clip is removed, there are various ways (all involve pulling) to remove the old cartridge, my favorite being using a stiff steel bar with a hole in it, screwing it to the protruding stem, and using the handle/knob screw to fasten the bar to the stem as a "pull handle". Then I twist and pull to remove the cartridge. There are brass (old) and plastic (new) cartridges, they are interchangeable.
There are various other ways to assist in cartridge removal, including a special puller tool manufactured for that purpose. You may be able to borrow or rent the puller from a good plumbing or hardware shop. There are circumstances where the puller tool is pretty much the only tool that will work.
Replacement is simple, insert the new cartridge and install the retainer clip... done! Moen guarantees them for life too, so if you send them back the old one they will send you a new one free, for next time.

Check out this video
Comment: Not that you can do anything about it short of complete demolition, but you should be made aware that tile adhered directly to unprotected plywood, like in the picture, is a recipe for water damage and complete failure of the tub/shower surround.
Comment: Thanks for the input.  And I agree, like I said I plan to do a replacement of the bathroom in the future...just haven't gotten around to it yet :)


Are there any .NET content management systems that focus on usability and leave out the bloat?

Question: I work in a shop that is mostly .NET based, and we're trying to pick out a content management system to use. This means we mostly likely won't be able to use any of the common open source CMS projects (Plone, phpNuke, anthing not based on .NET, etc.).
Since I'm a huge usability nerd (just finished reading The Design of Everyday Things by Norman), I've been looking at them from that point of view. Frankly, I haven't been too impressed. This quote sums it up:

Most open source content management software is useless. The only thing worse is every commercial CMS I've used. - Jeffrey Veen

Here's a short list of our requirements:

Has to be .NET based
Prefer open source or on the inexpensive side
Limited feature set (we don't need too many features and they make things harder to use)
Does need Active Directory integration and robust permissions
Should be focused on web standards and usability

I know it's probably an impossible feature list, but are there any content management systems that kinda sorta look like they might not suck more than a Dyson?
Edit:
Here's the current situation:

I'm going to push for N2. I've got Active Directory integration working well (I even wrote a custom role provider). The only thing missing is workflow functionality. Hopefully I can get something going with that since it's the last sticking point. The N2Contrib project might provide a starting point if I can figure it out.
I would still love to check out Stencil CMS if/when it gets off the ground.
One of my co-workers was trying to get Umbraco going but wasn't having much luck.

Thanks for the help!
Answer: Self-plug is lame, but what you're describing is pretty much exactly what I am getting ready to release for $79 a pop. If you're still looking in a few weeks, take a peek. If you'd like, shoot me an email (firstname.lastname@example.com).
I've heard both positive and negative feedback about Umbraco. A lot of people like Graffiti, but it's more blog-oriented than a full-blown CMS.
Comment: We've been looking for a couple months now, I'm sure a few weeks won't make a difference. You've got me interested so far.
Answer: Check out N2 (http://n2cms.com/).  I think that it covers most, if not all, of your requirements (I don't think it has Active Directory capability at this time).  We are using N2 and I have really enjoyed how flexible it has been.
Comment: Yeah, the 2005 thing is annoying.  We're running Visual Studio 2005 as well.  If you go in and edit the project file in Notepad and change the  tag from 9 to 8, you can open the solution in Visual Studio 2005.
Comment: I would love to check out N2, but unfortunately we haven't upgraded to Visual Studio 2008 yet. Even though the sample code projects say they should work with 2005, they really don't. I might end up having to download the demo of 2008.

Thanks for the suggestion.
Answer: My company just completed a review of several commercial .NET-based CMS/portal platforms and, while I can't reveal who was in them (thanks, NDAs!), I can tell you that IMO they all sucked very, very badly.
Good luck on your search. I'll keep an eye on this thread in the hopes that there's something we missed.
Answer: We had a similar set of requirements and chose Telerik Sitefinity. It's got it's faults but overall I've been happy with it so far.
Comment: In my experience, if Sitefinity is anything, it's not simple or lean.
Comment: Could you tell me a little bit more about your experience with Sitefinity?

We did look at that initially, but it seems like their purchasing options only allow you to use one domain per license, which might be a problem for us.
Answer: Unfortunately Jeffery speaks the truth. Which is probably why I build a new custom cms from the ground up every few years. Basically, the motivation for "boxed" CMS packages is to have every feature on earth and be everything to everyone and therefore do nothing particularly well for anyone. With the feature bloat comes the usability nightmares. Unless you start customizing and then you usually end up forking the project and losing the advantage of community updates.
Comment: Indeed. We need CM software that does very little but does it very well. It needs to save you time and effort on the common things and get out of your way for everything else. Most dictate the way a web app/site should work, and trying to break out of that model costs so much its a wash with developing one from scratch.
Answer: Kentico CMS according your list:

Has to be .NET based

It's .net based, .NET Framework 2.0 or later

Prefer open source or on the inexpensive side

Free edition which can be used for commercial purposes is available, paid license starts at $750, source code is an option

Limited feature set (we don't need too many features and they make things harder to use)

Many built-in modules/features, anyway they can be easily disabled to keep the UI simple to use

Does need Active Directory integration and robust permissions

AD, Forms and Live Id! Integration

Should be focused on web standards and usability

UTF-8 Support including RTL languages, WAI Compliant, XHTML Compliant, XML, XHTML, HTML, XSLT, CSS.
Instant on-line demo or download available at:
http://www.kentico.com/Download.aspx
Comment: We spent a bit of time evaluating Kentico. We ended up not being able to get it easily set up for development in our environment, which pretty much killed it right there.


Default F key keyboard shortcuts gone

Question: I have the dell xps laptop with ubuntu.
The f keys on the keyboard have specific shortcuts relating to the picture on the keys - to vary brightness of turn on the illumination under the keys.
I'm not sure how but these default f key shortcuts seem to have been replaced with other ones - only the f key ones, the rest of the shortcuts are unchanged. For instance F11 which used to reduce screen brightness now makes a web page full screen.
I know it is possible to define keyboard shortcuts in system settings but many of them are not there and I don't want to have to create custom commands.
It seems like I might have accidentally pressed another keyboard shortcut which toggled the shortcuts only for the f keys.
How can I reset the f key shortcuts to what they were before?
Thanks!
Answer: Aha!
So I found if you hold the "Fn" you toggle the function of the F shortcut keys. So somehow I have managed to switch around the two sets of shortcuts such that I can only now use the default ones (which refer hardware shortcuts specific to the PC) if I hold "Fn".
to actually fix the problem and swap around the active F key shortcuts do Fn + Esc

Default F key keyboard shortcuts gone


Are these equivalent answers?

Question: The question:
$$\int{(7x-2)(3x+2)^{1/2}dx}$$
is done by some complicated methods in my Textbook and the answer they got is:
$$\frac{14}{45}(3x+2)^{5/2}-\frac{40}{27}(3x+2)^{3/2}+c$$
But I managed to do it using integration by parts and I got the answer as:
$$x(7x-2)(3x+2)^{1/2}-\frac79(3x+2)^{3/2}+\frac{14}3(3x+2)^{1/2}+c$$
Are both the answers equivalent?.If I'm wrong,feel free to correct me.
If they're not equivalent,does that mean that it can't be done by parts?
Comment: Compute the derivatives of both expressions.
Comment: @YvesDaoust yes, those weren't there when I made the comment. One can calculate each of these expressions at another point and subtract the two results and this will show disagreement anyway.
Comment: They aren't equivalent - for one, they disagree at $x=0$.
Comment: You can test for equivalence yourself. Here's a general method. Just use bounds (to simulate a definite integral calculation). Since this is a rational function, you can choose an upper bound to be transcendental (like $\pi$) and a convenient lower bound like $0$. That way if the two come out to be equal (within the limit of accuracy) on your calculator you know it's not an algebraic coincidence.
Comment: @JohnDoe: this is not conclusive, there are unknown integration constants.
Comment: Their graphs arent shaped the same, so im guessing no
Comment: @JohnDoe: yes, you need two points (provided you don't cross a singularity).
Answer: factorizing your first term(solution) we get
$${\frac {2\, \left( 3\,x+2 \right) ^{3/2} \left( 63\,x-58 \right) }{135
}}
+C$$ this is the right solution
your second one is (simplified)
$$1/9\,\sqrt {3\,x+2} \left( 63\,{x}^{2}-39\,x+28 \right) $$ and this is wrong

Are these equivalent answers?


incorrect run php by button click

Question: I have php function which update all records in data table and need it run by click button in html.
My php function look like this:
<?php
try {
  $sql = 'SELECT id_data, date_record, value1, value2, value3 FROM data ';
  $s = $pdo->prepare($sql);
  $s->execute();
} catch (PDOException $e) {
  $error = 'Error with select data' . $e->getMessage();
  include 'error.html.php';
  exit();
}

while ($row = $s->fetch()) {
  $dane[] = array(
    'id_data' => $row['id_data'],
    'date_record' => $row['date_record'],
    'value1' => $row['value1'],
    'value2' => $row['value2'],
    'value3' => $row['value3']
  );
}

if (isset($_GET['edytion'])) {
  foreach ($data as $data2) {
    try {
      $sql = 'UPDATE data SET date_record = :date_record, value1 = :value1, value2 = :value2, value3 = :value3 WHERE id_data= :id_data';
      $s = $pdo->prepare($sql);
      $s->bindValue(':date_record', $_POST['date_record']);
      $s->bindValue(':value1', $_POST['value1']);
      $s->bindValue(':value2', $_POST['value2']);
      $s->bindValue(':value3', $_POST['value3']);
      $s->bindValue(':id_data', $_POST['id_data']);
      $s->execute();
    } catch (PDOException $e) {
      $error = 'Edit data error  ' . $e->getMessage();
      include 'error.html.php';
      exit();
    }
  }

  Header("Location: theme3.php");
}
?>

And my form in html where i try run this look:

        Date
        Value 1
        Value 2
        Value 3

    <?php if (isset($data)): ?>
      <?php foreach ($data as $data1): $a = 0 ?>
        <form action="?edytion" method="post" id='ed'>

            <input type="hidden"  name="id_data" id="id_data" value="<?php echo $data1['id_data']; ?>">
            <input type="date"  name="date_record" id="date_record" value="<?php echo $data1['date_record']; ?>">
            <input type="text"  name="value1" id="value1" value="<?php echo $data1['value1']; ?>">
            <input type="text" name="value2" id="value2" value="<?php echo $data1['value2']; ?>">
            <input type="text" name="value3" id="value3" value="<?php echo $data1['value3']; ?>">

        </form>
        <?php $a++;
      endforeach; ?>
    <?php endif; ?>

  <input type="submit" id="id_buttona" onclick="document.getElementById('ed').submit();" value="Edit"/>

Ultimately when i try update data it update only first record in table, rest of them is invariable.
Anybody know what is wrong and have idea how correct it? I will be grateful for help!
Comment: show your js code also
Comment: show your php, html view, and js code properly, it looks incomplete
Comment: Where is your submit function which you used in `onclick="document.getElementById('ed').submit();"`?
Comment: Chris i check this result and it write all id_data correctly
Comment: Nana I dont have submit function, i was thinking it was buitd in  specification.
Answer: You create too many forms with the same id. Surround the table with the <form> and do foreach on
 only.
Something like this

 <form action="?edytion" method="post" id='ed'>

        Date
        Value 1
        Value 2
        Value 3

    <?php if (isset($data)): ?>
      <?php $a = 0; foreach ($data as $data1): ?>

            <input type="hidden"  name="id_data<?php echo $a; ?>" id="id_data" value="<?php echo $data1['id_data']; ?>" />
            <input type="date" name="date_record<?php echo $a; ?>" value="<?php echo $data1['date_record']; ?>">
            <input type="text" name="value1<?php echo $a; ?>" value="<?php echo $data1['value1']; ?>">
            <input type="text" name="value2<?php echo $a; ?>" value="<?php echo $data1['value2']; ?>">
            <input type="text" name="value3<?php echo $a; ?>" value="<?php echo $data1['value3']; ?>">

        <?php $a++;
      endforeach; ?>
    <?php endif; ?>

  <input name="row_count" value="<?php echo isset($a) ? $a : 0; ?>" type="hidden"/>
  </form>
  <input type="submit" id="id_buttona" onclick="document.getElementById('ed').submit();" value="Edit"/>

The way you created each form for each row will not work well because: (1) all your forms have the same javascript id, when you do getElementById only the first form is affected, (2) when you submit that one form the page reloads and all the changes to other rows are lost.
One solution is to make only 1 form and have different name to all fields. Forms fields are sent by name and value so you need different names for all fields and you don't really need ids.
You can add row count somewhere in the form and then change php to something like this:
$row_count = $_POST['row_count'];
for($i = 0; i < $row_count; i++) {
try {
            $sql = 'UPDATE data SET
                            date_record = :date_record,
                            value1 = :value1,
                            value2 = :value2,
                            value3 = :value3
                         WHERE id_data= :id_data';

            $s = $pdo->prepare($sql);
            $s->bindValue(':date_record', $_POST['date_record' . $i]);
            $s->bindValue(':value1', $_POST['value1' . $i]);
            $s->bindValue(':value2', $_POST['value2' . $i]);
            $s->bindValue(':value3', $_POST['value3' . $i]);
            $s->bindValue(':id_data', $_POST['id_data' . $i]);
            $s->execute();
        }
        catch (PDOException $e) {
            $error = 'Edit data error  ' . $e->getMessage();
            include 'error.html.php';
            exit();
        }
  }

Comment: It will not work because in loop a send every change in forms depending on id_data. When i do one form button dont update.
Comment: You'll need to change the names of input fields in each iteration. You can concatenate the `$a` variable to the input name. You don't use that variable right now. You'll need to change the php on the server side accordingly.
Comment: I remove $a and incrementation
Comment: But i noticed when i dependence form id  from $data1['id_data'] like this:

 '>

And in input submit induce:

Then it will hange last index. But how induce all id_data array?
Comment: You can make few forms with different `id`s but you'll need a submit button for each form. Also this does not solve the problem number (2) in my answer; you'll lose changes to other forms when you submit one form. And you can only submit one form at a time.
Comment: So how is the best way to solve this? I suspect i should change php implementation, but how when i want change all records in table?
Comment: But it still don't working and don't update table, first -  it don't increase
`$a` variable.
Comment: Yeah. I forgot to move `$a=0;` outside of `foreach` loop.
Comment: Now it change only last record in table. But when i ''  it shows me 0 all the time
Comment: Now it work!! Thank you very very very much!! :) :) :) :)
Comment: @Monika you are welcome. Accept and upvote the answer, please.
Answer: It is all html file
<!DOCTYPE HTML PUBLIC>

    <title>Tematyka2</title>

    <link rel="stylesheet" href="style.css" type="text/css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>

Example title
	 Logout

Your Page

Main menu

                        :: Main page

	</tr

Them

                            :: Them 1

                            :: Them 2

                            :: Them 3

	</tr

Charts

                            :: Chart1

                            :: Chart2

                                    EDYTION

                                        Date
                                        Value 1
                                        Value 2
                                        Value 3

                                    <?php if(isset($data)): ?>
                                        <?php foreach($data as $data1): $a=0?>
                                            <form action="?edytion" method="post" id='ed'>

                                                    <input type="hidden"  name="id_data" id="id_data" value="<?php echo $data1['id_data']; ?>">
                                                    <input type="date"  name="date_record" id="date_record" value="<?php echo $data1['date_record']; ?>">
                                                    <input type="text"  name="value1" id="value1" value="<?php echo $data1['value1']; ?>">
                                                    <input type="text" name="value2" id="value2" value="<?php echo $data1['value2']; ?>">
                                                    <input type="text" name="value3" id="value3" value="<?php echo $data1['value3']; ?>">

                                            </form>
                                        <?php $a++; endforeach; ?>

                                    <?php endif; ?>

                                <input type="submit" id="id_buttona" onclick="document.getElementById('ed').submit();" value="Edit"/>

         My page

And Php part:
<?php

header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

include $_SERVER['DOCUMENT_ROOT'] . '/connection_to_database.php';

include $_SERVER['DOCUMENT_ROOT']. '/check_login.php';      try {
        $sql = 'SELECT id_data, date_record, value1, value2, value3 FROM data ';

        $s = $pdo->prepare($sql);
        $s->execute();
    } catch (PDOException $e) {
        $error = 'Error with select data' . $e->getMessage();
        include 'error.html.php';
        exit();
    }

    while ($row = $s->fetch()) {
        $dane[] = array(
            'id_data' => $row['id_data'],
            'date_record' => $row['date_record'],
            'value1' => $row['value1'],
            'value2' => $row['value2'],
            'value3' => $row['value3']
        );
    }

    if (isset($_GET['edytion'])) {

        foreach ($data as $data2) {

            try {
                $sql = 'UPDATE data SET
                                date_record = :date_record,
                                value1 = :value1,
                                value2 = :value2,
                                value3 = :value3
                             WHERE id_data= :id_data';

                $s = $pdo->prepare($sql);
                $s->bindValue(':date_record', $_POST['date_record']);
                $s->bindValue(':value1', $_POST['value1']);
                $s->bindValue(':value2', $_POST['value2']);
                $s->bindValue(':value3', $_POST['value3']);
                $s->bindValue(':id_data', $_POST['id_data']);
                $s->execute();
            }
            catch (PDOException $e) {
                $error = 'Edit data error  ' . $e->getMessage();
                include 'error.html.php';
                exit();
            }

        }

        Header("Location: theme3.php");

    }

?>

And that's all about update data. Php and html are in one file, I know it's look unprofessionally and i shoudln't do it in this way.
Comment: Just an aside note, you shouldn't post additional code in an answer, just edit the initial question instead

incorrect run php by button click


Multiple notifications via notify-osd or alternatives

Question: I am searching for a way to display multiple notifications at once. The default app for Ubuntu seems to be notify-osd.
Can this be configured to display multiple notifications?
PNotify is a very cool project bringing this feature in HTML world. But is there any way to do something like this, natively?
Answer: Ubuntu 14.04 LTS: notify-send
$ urg=(low normal critical) ; for v in 0 1 2  ;do notify-send --expire-time=100 -u ${urg[$v]} "Mama says" "Mama had a little lamb - $v - ${urg[$v]}" ;done

... seems to bring up them one at a time, with order slightly re-arranged by -u ${urg[$v]}

Note:
https://askubuntu.com/a/51440/289138
Comment: Doesn't show me any notifications...
Comment: Posting edited.
Comment: Actually `notify-send` doesn't do anything on my machine (no error, just nothing).
Comment: That is strange, do you actually have `notify-osd` installed? `dpkg --list | grep notify` should show it. For me it also shows others: gir1.2-notify-0.7
libnotify-bin
libnotify4:amd64
notify-osd
notify-osd-icons
python-notify
python-pyinotify
Comment: I know it should work. I have `notify-osd` installed and the other notifications (from Rhythmbox for example) work.
Comment: `notify-osd` works again. The notifications are swill shown one by one... Aren't there other alternatives for notify osd that will show multiple notifications *same time*?