Difference between CFRunloopRun() and a simple infinite loop?

Question: I schedule a HIDManager on the current runloop, which is the runloop for the main function.
When I add the following line
CFRunLoopRun();
All HID events will be captured and the output will be shown on the screen, which is compatible with the Runloop Model

But if I add a
for(;;);
at the end of the main loop, from my understanding, I can also keep this runloop exist and the thread will never die. Why I cannot receive any HID events and nothing got printed on the screen right now?
Answer: CFRunLoopRun() works different from a simple infinite loop, as it pauses the execution of the program and waits for new events to arrive, which could either be timers firing, HID events, etc. When you call CFRunLoopRun(), you will notice that the CPU usage of your program drops to zero as long as no new events arrive.
By running an infinite loop inside the thread that your run loop is on, your program is busy running that infinite loop and it has no time to process new events.
Comment: So will having a queue to receive tasks and a semaphore to "wait" unless there is something in the task have more or less the same effect?
Comment: I suppose that would be similar effect. As CoreFoundation is open source, you can see the implementation [here](https://github.com/opensource-apple/CF/blob/master/CFRunLoop.c#L2676)


how to access webform submission data from a custom content type

Question: I 'd be grateful if someone could help with this..
I have a webform, let's call it input form, which, when submitted, triggers an external application to run on my server.  That application uses some of the submission data (reading from webform_submission_data table) and after some time produces an output in the form of XML.
Now, through the use of feeds module, I read that XML data and produce a node, of a certain content type, let's call it results CT ..
I have a twig template for the results content type, and output is nicely presented to the user.
So far, so good.
Now my problem is this.  I need to show both input and output in the same results page.
I tried to use Webform Content Creator module and indeed I have nodes with submission data - let's call this input data CT.
However, at the time of input form submission, I don't have the results yet.  And I want to link the two together, obviously upon the creation of the results node.
I tried to reference each content type, using Corresponding Entity References so that when a results node is created (automatically through feeds) it would link to the corresponding input data CT.  I thought that if I can achieve that connection, then I would be able to access the 'input' data through the results page template.
However, I can't make this connection to work - the 'entity reference' field that I use on the results CT, wants an 'entity ID' - and I can't find that.  Remember that nodes are created automatically, I don't have a user creating nodes via a select form or autocomplete text field.
I am trying to figure out how to do this through the sid (submission id) which seems to be a unique key for every submission, and I have this on both my content types .. So ideally I would like to use the sid that I have on my results template, and use that to get the submission data I need.
(obviously) I am not very familiar with the drupal API - I am however comfortable with twig .. I don't know if (and how) I could pass that information through a pre-process function to be available in the results template..  Is there a simpler way to do it?
Could I link two content types based on a custom field (say a unique number, like sid ??).
Ideally, in a few words, what I want is this:
I have a CT (results) with various fields, one of which is sid.  That sid corresponds to a (unique) submission id.  How can I access data relevant to that submission id from within the results twig template?  So I can then present both input (submission data) and output (results) in the same page.
PS - Perhaps one solution would be to refactor the whole logic, and use one CT for both input/output.  Insert some data upon form submission, and then, when results are ready, edit (i.e. fill-in) the rest of the 'output' fields via feeds.  Then all data are in one CT.  However I would rather avoid this as it's quite a big change ..  Shamefully enough, I might just re-enter input data through the XML again - it wouldn't be a problem - but it's a really crap solution  ..
I 'd be really grateful if someone could help .. I hope I explained the whole situation adequately enough ..
Answer: One way to accomplish that would be to use the https://www.drupal.org/project/webform_entity_handler module. It is not very widely used module yet but I've used it, it was simple to use and worked well. What that module does it allows you to create arbitrary entity from a webform submission (like the results node). So you could store the input, submission id and whatever else you need to this entity at this time.
Then feeds can update this same entity with the results if you know unique identifier like the submission id.


CSS - Adding padding to one td changes padding on all the other rows

Question: This is my HTML:

            name
 first comment

            name
 second comment

            name
 third comment

and this is my CSS:
.htmlCommentTable td {
    border-collapse: seperate;
    vertical-align: top;
    padding: 10px;
    border: 1px solid black;
    margin: 0;
}

.thirdtd {
    width: 90px;
}

.secondtd {
    width: 100%;
    position: relative;
}

As you can see, all I did was add a left padding to a single td (the first td in the second row) but for some reason when I do this, it gives a left padding to the second td's of the first and third row as well. How come? I want it so that only the first td in the second row gets the left padding and the rest of the table remains the same.
Note: I tested this fir Chrome and IE 8 - IE 10.
Comment: The columns of a table are supposed to act like that. If you expand or shrink a cell in one row, the other row's corresponding cell will also change. It's to keep them in line with each other.
Answer: The code from your question, to play with: http://jsfiddle.net/We5QF/
If you want the width of the first and third rows (in column 1) to be different than the second row, you'll have to do something tricky as suggested here: html table cell width for different rows
You may want to try using divs instead of a table if you're going after different widths in the same column. Something like this: http://jsfiddle.net/4ZB85/2/
HTML

            name
 first comment

            name
 second comment

            name
 third comment

CSS
div.htmlCommentTable {
    width: 100%;
}

div.row {
    width: 100%;
    margin-bottom: 20px;
    border: 1px solid #000;
    clear: both;
}

div.col1 {
   margin: 0;
   padding: 10px;
   display: inline-block;
   vertical-align: top;
   background-color: #efefef;
}

div.col2 {
   display: inline-block;
   vertical-align: top;
   padding: 10px;
   background-color: #dedede;
   border-left: 1px solid blue;
}

div.extraspace {
    padding-left: 90px;
}


Weird behavior of BehaviorSubject, async pipe, and *ngIf combination: ngOnChanges receives the change that theoretically cannot be possible

Question: I have two components - Parent component which fetches the data from the server, and child component which is displaying fetched entries as a list - but only if the list is not null or empty.
My problem is (short): Even if there is *ngIf checking that the list has some values, emission is done and in child component I get first emission with null items: ![First emission] (https://i.stack.imgur.com/OHRB5.png).
Second emission is though okay... ![Secod emission] (https://i.stack.imgur.com/vK8Op.png).
Does somebody have an idea?

The parent component also contains search field where you can search entries. Here is the code:
<lookup-area [debounceTime]="100"
             (searchValue)="searchChanged($event)"></lookup-area>

<app-virtual-list *ngIf="(channels$ | async)?.length > 0"
                  [items]="channels$ | async"
                  [itemHeightPx]="32"
                  [maxContainerHeightPx]="190 - ((channels$ | async)?.length ? 29 : 0)"
                  [trackByFn]="trackByFn">
    <ng-template let-item>Some template</ng-template>
</app-virtual-list>

@Component({
             selector: 'app-filter',
             templateUrl: './filter.component.html',
             changeDetection: ChangeDetectionStrategy.OnPush,
             encapsulation: ViewEncapsulation.None
           })
export class FilterComponent implements OnInit, OnDestroy {

    public search$ = new BehaviorSubject('');

    constructor(private service: YoutubeSearchService) {
    }

    public ngOnInit(): void {
        this.channels$ = combineLatest([this.service.getYoutubeChannels(), this.search$]).pipe(
            map(([channels, search]) => search ? channels.filter(channel => (channel.name || channel.id).startsWith(search)) : channels),
            map(channels => channels?.sort((a, b) => (a.name || a.id).localeCompare((b.name || b.id), undefined, { sensitivity: 'base' })))
        );
    }

    public ngOnDestroy(): void {
        this.search$.complete();
    }

    public searchChanged(search: string): void {
        this.search$.next(search);
    }

    public trackByFn(index: number, item: YoutubeChannel): any {
        return item.id;
    }

}

And the child component contains the logic for displaying. Here is the code:
@Component({
             selector: 'app-virtual-list',
             templateUrl: './virtual-list.html',
             styleUrls: ['./virtual-list.less'],
             changeDetection: ChangeDetectionStrategy.OnPush,
             encapsulation: ViewEncapsulation.None
           })
export class VirtualList<T> implements OnChanges {

  // Mandatory
  @Input() public items: T[];
  @Input() public itemHeightPx: number;

  // Optional
  @Input() public maxContainerHeightPx: number | undefined; // If undefined, scroll container's height is 100%

  public ngOnChanges(changes: SimpleChanges): void {
      const { items, itemHeightPx, maxContainerHeightPx } = changes;

      if (this.maxContainerHeightPx && (items || itemHeightPx || maxContainerHeightPx)) {
         this.setContainerScrollHeight();
      }
  }

}

I tried:

wrapping everything in <ng-container *ngIf="(channels$ | async)?.length > 0">, but no success
wrapping in another div, still did not work

I have no clue what else to try because it seems that *ngIf does not work which is really weird.
I would expect that the first change comes with the items inside since that is what *ngIf is telling.
Answer: Not sure I understand your issue, but I already see a bad thing in your code, so try to resolve it and see if the issue persists.
You don't need to create 3 subscriptions, a single one is enough.
<ng-container *ngIf="channels$ | async as channels">
  <app-virtual-list
    *ngIf="channels?.length"
    [items]="channels"
    [itemHeightPx]="32"
    [maxContainerHeightPx]="190 - (channels?.length ? 29 : 0)"
    [trackByFn]="trackByFn"
  >
    <ng-template let-item>Some template</ng-template>
  </app-virtual-list>
</ng-container>

Comment: Thanks for the hint. My problem is that even if there is *ngIf=(channels$ | async)?.length > 0 and the channels list is empty, I am getting emission in app-virtual-list...
Comment: Well your ngOnChanges function triggers not only for items, but for all inputs, you are aware of that right ?
Comment: Sure, but it should not even be rendered if there are no channels, and therefore not triggered
Comment: And just FYI, it will not create 3 subscriptions, but only 1. But I agree that it looks better as you did it.
Comment: It's triggered if the inputs change. You don't provide enough code for us to know if that's the case, so I wanted to make sure you knew that. And no, 3 `async` means 3 subscriptions, look at the source code of the pipe if you don't believe me


Landypy not understanding how to connect

Question: I am trying to query AD using this project,
https://landpyactivedirectory.codeplex.com/documentation
<code>using Landpy.ActiveDirectory.Core;
using Landpy.ActiveDirectory.Entity.Object;

namespace TestConsoleApp
{
    public class aLandypyTest
    {
        protected IADOperator ADOperator { get; set; }

        public void CallAD1000Times()
        {
            for (int i = 0; i < 1; i++)
            {
                using (var userObject = UserObject.FindOneByCN(this.ADOperator, 'pangxiaoliang'))
                {
                     // do something.
                }
</code>
But I am getting this error,

Error 2   The best overloaded method match for
  'Landpy.ActiveDirectory.Entity.Object.UserObject.FindOneByCN(Landpy.ActiveDirectory.Core.IADOperator,
  string)' has some invalid
  arguments D:\BackUp\TestConsoleApp\TestConsoleApp\TestConsoleApp\aLandypyTest.cs  20  41  TestConsoleApp
Answer: Change 'pangxiaoliang' to "pangxiaoliang". Typo. The compiler wants a string for second parameter, but if You wrap it with ' it's not a string. You have to wrap it in ".


Conditions for denseness in holomorphic functions

Question: Question:
Given a compact subset $K \subset \mathbb{C}$, and (non-polynomial) functions $h_i:K\rightarrow \mathbb{C}$, with $h_i\in \mathcal{A}(K)$ (that is each $h_i$ is holomorphic on the interior of $K$), are there any known sufficient criteria for $\{h_i\}$ to be dense in $\mathcal{A}(K)$?

Related:

A more general version of this question was asked on MathOverflow 7 years ago, but with inconclusive answer.

Nachbin's theorem says that an involutive subalgebra which separates points and tangent vectors is dense in the space of smooth functions. But the $h_i$ being holomorphic precludes them from forming an involutive subalgebra.

Mergelyan's theorem provides a result for the denseness of polynomials in $\mathcal{A}(K)$ so long as $\mathbb{C}\backslash K$ is connected. But I would not like to assume the $h_i$ to be polynomials.

Various Stone-Weierstrass theorems are concerned with continuity instead of holomorphicity and also require involutive sub-algebras.

Thanks for any help!
Edit: Corrected a misformulation of Nachbin's formulation: I originally said it guarantees denseness in continuous functions as opposed to smooth functions.
Answer: This is a long comment that is definitely not an answer but indicates a direction to look into if of course of interest.
First note that this is a very vague question and unless more details about why is of interest, it's going to be hard to answer - probably looking at research around Mergelyan's theorem gives stuff that may be of interest for general $K$
On the other hand, universality properties in the critical strip of (analytic continuations of) Dirichlet series based on Dirichlet characters and their derivatives say, give infinitely many such classes of dense analytic functions on disks as essentially any nontrivial linear combination (for same character modulus so the Davenport Heilbronn function for example) or derivative of such (eg $\zeta'(s)$) has dense vertical translates in some specific critical strip disc and of course this can be moved to any disc in the plane, so one gets such a class for each function as above.
A good article for this direction is Bagchi A joint universality theorem for Dirichlet L-functions
Comment: any finite sum as above is a subclass of exponential "Ritt" polynomials (those have general frequencies $b_k$) so looking at that topic, there may be results along those lines; would try a search on approximation properties of exponential polynomials to start with
Comment: Thanks very much for these pointers! I agree the question is vague. More specifically, I was hoping to show that countable sums of exponentials i.e. $f(z) = \sum_k a_k e^{b_kz} + c_k$  with  $a_k,b_k,c_k\in\mathbb{Z}$, lead to $\{f(z)\}$ being dense in $\mathcal{A}(K)$ where $K$ is a simply connected subset of $\mathbb{C}$.


Stacked Lines in Pandas

Question: I want to draw stacked lines in pandas Dataframe.
So, currently I draw one line:
df.plot.line(x='xvals',y='yvals')

in which xvals column contains x values, and yvals contains y values.
How can I add another line in the same graph?
Answer: Keep the returned Axes object and pass to ax argument:
ax = df.plot.line(x='xvals',y='yvals')
df.plot.line(x='xvals2',y='yvals2', ax=ax)

Stacked Lines in Pandas


For $x\neq 1$ find $x$ such that ...

Question: For $x\neq 1$, find $X$ such that:
$$x+1\mid 2$$
$$x+2\mid 3$$
$$x+3\mid 4$$
$$x+4\mid 5$$
Can someone help me with this ?
Comment: @HagenvonEitzen Thank you! the divisors of $X-1$ are $3,4,5$ so $X=60*k+1$
Comment: Can you conclude something about some divisors of $X-1$?
Comment: $X=-179$ is one solution.
Comment: What about $X = 1 + 120k$ for $k=1,2,3...$?
Answer: Given that
$$x+1\mid 2$$
$$x+2\mid 3$$
$$x+3\mid 4$$
$$x+4\mid 5$$
We rewrite it in modular form.
$$x+1\equiv 0 (\mod 2)$$
$$x+2\equiv 0 (\mod 3)$$
$$x+3\equiv 0 (\mod 4)$$
$$x+4\equiv 0 (\mod 5)$$
Subtracting so only $x$ is on the left, you get, by rules of modular arithmetic,
$$x\equiv 1 (\mod 2)$$
$$x\equiv 1 (\mod 3)$$
$$x\equiv 1 (\mod 4)$$
$$x\equiv 1 (\mod 5)$$
Therefore, $x-1$ is divisible by $2, 3, 4, 5$. The least common multiple of $2, 3, 4, 5$ is $60$, and so one solution is $x-1=60$, and so $x=61$ is a solution.
A more general solution is all numbers one more than a multiple of 60, usually written as $x=60k+1$ for $k\in \mathbb {Z} $ (But $k \neq 0$ because $x \neq 1$).

For $x\neq 1$ find $x$ such that ...


How to make images look good on both nexus and nexus 10?

Question: I'm trying to make my app workable and visually better across all different screen sizes, but I have run into some issues. I have a simple image layout :
The images are sized 200 x 200 for small and 400 x 400 for the large. In the drawable folders I have made some smaller ones for smaller screens 100x100 , 200x200 and then 50x50 , 100x100. However looking at the list of devices in eclipse, the galaxy nexus 10 and the galaxy nexus both take their images from the xdpi folder. If I make the images work for the nexus its makes the nexus 10 really small and if I make them for the nexus 10 it messes up the layout for other devices.  Why doesn't the nexus 10 just use the xxhdpi folder ?
How can I get around this issue ? I want to avoid separate layouts if possible as I've not attempted that yet as i'm still new to android programming.
How can solve this issue ?
Go easy on me as im still quite new. Thanks
edit
Listed as galaxy nexus in eclipse (720 x 1280)
and Nexus 10 (2560 x 1600)
as you can see major difference in sizes but use the same xdpi folder
Comment: Im trying to make it work on all devices really. But the ones I have issues with are the 4.7inch galaxy nexus and the nexus 10 as they use the same xdpi folder. If I make the images nice and big for the nexus 10 it also messes up my Samsung s3.
Comment: which two devices are you trying to make this work on?
Comment: I would create two folders, one for 720x1280 and one for 2560x1600
Answer: If you take a look at the android documentation.
It suggests that you create different layouts to support the different sizes.
If this become to much work you can restrict which sizes you support in the manifest.
So as i said in the comment above, I would create two folders, one for 720x1280 and one for 2560x1600.
I would then add a layout to each of the ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high) if you want to try and support as many as possible.
Sorry I don't know any shortcuts. If i find anything else I'll add to this answer.
Comment: Funnily enough I was currently reading that link for more information when you posted it. Thanks.
Comment: Haha, yeah its a shame there isn't an easier way to make one screen to fit all...
Answer: You can declare drawables for different screen widths
drawable-sw720dp/
Comment: Got it looking ok using this drawable folder however its still a little confusing to me as it didn't accept the larger images I designed for the bigger screen however the normal size images that were tiny before in the xdpi folder now look ok when stored in the folder above!?
Comment: @Xeo yes this is also in the android documentation for supporting multiple screens. For you want to do its diffidently worth a read.


Navigate in multiple sheet in VBA depending on cell value

Question: I am a fairly new VBA user and have doing few codes learning as I go and reading forums.
Now I want to code something and I couldn't find a way to do it/a hint in the forums so I am coming to ask for your kind help.
I have a lot of spreadsheet with names as title, representing expenses of those people. My goal is to create a file in which I regroup the spreadsheets, then would like to extract the expense references in the "Home" spreadsheet. The relevant expanses will be marked "Y" in the same row.
In the "Home" spreadsheet I have names of people on the first page e.g. "Paul", "Marie","Pierre" etc.... in the same column.
I would like to create a code that could look at the names in the spreadsheet "Home" and copy data from the "Named" Spreadsheet back to the "Home" one.
Format would be the same for the "Named spreadsheet" so I am always looking at the same column.
I have tried the following so far
Sub Expenses()

    Set wk=ThisWorkbok.sheets("Home")

    Dim Name as String
    Dim Expense as Integer
    line_newexpense = 9
    rowline = 10
    start_l =34

    Do While Name <> "#"
        Line = wk.Cells(start_l,3)
        Name = ThisWorkbook.Sheets("Home").Cells(line_newexpense,39).Value
        Expense = ThisWorkbook.Sheets(Name).Cells(rowline,3).Value

        For j=50 to 8
            If ThisWorkbook.Sheets(Name).Cells(25,j).Value="Y" Then
                Line = ThisWorkbook.Sheets(Name).Cells(3,j).Value
            End If
            rowline = rowline+1
        Next j

        line_newexpense = line_newexpense + 1
    Loop

The problem is when I try to run it I encounter an "Error 9 Subscript out of range", so not sure how I could counter the problem,
Many thanks in advance for your hints!
Kind Regards,
Comment: Hi Carolina, welcome to Stack Overflow. I have edited your question to make your code more readable.  Well indented code generally attracts better quality answers. Good luck!
Comment: Hey Carolina, when you `Set wk=ThisWorkbok.sheets("Home")` workbook is misspelled, which means that you cannot access `Line = wk.Cells(start_l,3)` as wk is not set. Then when you try to iterate j from 50 to 8, you need to specify that j will be j - 1 like this : `For j=50 to 8 step-1`, but with this j will go backward and rowline will go forward.
Comment: please add screenshots of "Home" and "Name" sheets
Comment: @user3598756 Never ask for screenshost, unless it is an UI question. See [here](http://meta.stackoverflow.com/questions/316945/is-please-post-a-picture-a-non-constructive-comment).
Comment: Carolina: then post files! @vacip: anyhow I was not asking for code in screenshot!
Comment: Thanks @Miguel_Ryu for spotting the tipo, but unfortunately still doesn't work for me, they have located the mistake on the "Expense" line... Apparently VBA doesn't like me using ThisWorkbook.Sheets(Name)...
Happy to post some screenshots (not sure I can the post the files) if you want to better understand the structure!
Answer: You do not need VBA for this. You can use INDIRECT function to achieve what you want.
For example
=INDIRECT(B1&"!$A$1")

Where B1 has the name of the worksheet, Say "Paul" and A1 is the cell which has the data that you need.

You can also factor the Y part in your above formula using IF function.
Comment: Thanks for the comments and the help!
Have tried to implement the changes but would like the extract on my front page to be one line after the other, I am not sure that indirect represents the best option for that. I wanted to use VBA as it allows for flexibility and formatting, but if indirect gets me there happy to learn the trick (e.g.: having three line of expenses but I want the #1 and #3 to appear on the "Home" Sheet one below the other, how can I do that? Thanks!


The connection to adb is down, and a severe error has occured. - Ubuntu 12.04

Question: I am using Eclipse ADT and it was working fine for me for last 1 year, but suddenly I faced this issue, may I know How can I resolve this ?
The connection to adb is down, and a severe error has occured.
[2015-12-12 09:57:13 - MyPlace] You must restart adb and Eclipse.
[2015-12-12 09:57:13 - MyPlace] Please ensure that adb is correctly located at '/home/system/adt-bundle-linux-x86-20140702/sdk/platform-tools/adb' and can be executed.

Comment: Make sure adb exist at that path. Also Eclipse isn't supported anymore. Start using Android Studio.
Answer: Try below steps....

Close the Eclipse if running
Navigate terminal to Android SDK platform-tools directory
Type adb kill-server (Eclipse should be closed before issuing these commands)
Then type adb start-server
No error message is thrown while starting ADB server, then adb is started successfully.

Now you can start Eclipse again.
Otherwise you can stop adb service from System Monitor, and restart eclispe.
For more details, click here...
Comment: can you brief this: Go to the Android SDK platform-tools directory in Command Prompt, like : Steps (I am using Ubuntu)
Comment: Oops sorry!
You can navigate terminal to android SDK directory.
Tell me where you keep your android sdk directory, I will write the command


How do people deduce symphonies from the sheet music?

Question: Now being an aspiring musician, I've heard of people who can deduce entire orchestral scores and seemingly hear symphonies on the spot — like they can hear them while they are reading it.
But what does it actually mean to be able to look at symphonies or other orchestral works like this?
Yeah, people say that when they read orchestral scores they can hear what it sounds like, and you think that you have to have a talent especially to sight read it.
But if I just familiarize with the music just by casually listening to it, then maybe I can go back and read, and then I can understand and hear some of the sounds playing back.
For example, if I listen to a Mozart sonata and I play the sheet music, then I can literally imagine the sound while sight reading it.
I guess there is a very good thing about being able to read orchestral scores that will help anyone improve their musicianship, and I'm wondering if I should do so.
Comment: I'm going to have to trot out my story [again] of the friend at the rehearsal for the first ever performance of a large choral piece… by a bad choir. He was given the score to follow along, which he did for about 5 minutes, after which he said to me, "I can either listen to them or read the score. I can't do both at once" & left the building so he could better 'hear' the music. Some people can just 'hear' it on first look.
Answer: What does it mean to hear symphonies or other orchestral works at sight?
It does mean that people can look at a score and imagine what it will sound like. As with any other musical ability, there are levels, and some develop it to a higher level of ability/skill than others.
How is it done?
It's no different than any other sight-reading; there's just more to look at. In general, one reads from the bottom of the score to the top, but there's also a process of scanning up, down, and across the page.
It is a very useful exercise to listen to music while following along in the score, whether a single instrument or a full symphony.
I'm wondering if I should learn to read orchestral scores.
"Should" only applies if the goal is to work as an accompanist, rehearsal pianist, or conductor, where score reading is a necessity. Otherwise, it's an interesting skill to develop, and can be occasionally useful*, but is far from necessary.

*For example, as a trumpet player, it's nice sometimes to be able to play from the orchestral score so that I can see what others in the ensemble are playing.
Comment: In addition to being able to read the whole orchestral score (no small feat), one must also be familiar with all the instruments of the orchestra and what they sound like.  Unlike choirs and pianos, orchestras are heterogeneous, which means much of 'what a symphony sounds like' is timbral, ie in the orchestration.
Comment: There's also the awkward part about needing the ability to sight-read the parts of transposing instruments correctly at concert pitch, including rarer instruments like A Trumpet and anomalous instruments that may not change key signature accordingly like French horn. (This also applies to concert band - baritone sax has a weird-looking cheat for fast transposition but requires transposing by a wicked large interval.)


React hook, wired issue when use useState, while if use setState work perfectly, how to solve it

Question: dear community, I am facing a wired issue, and I don't know how to summary my situation in the question title, so I wonder if the question title is accurate enough.
I was trying to convert a class component to a hook component.
The class version code like this
async componentDidMount() {
        const { dispatch, itemId } = this.props;
        try {
            if (itemId) {
                await dispatch({
                    type: 'assignment/fetchSubmissionsByAssignment', //here to fetch submissions in props
                    payload: {
                        id: itemId
                    }
                });
            }
            const { submissions } = this.props;
            this.setState({
                studentSubmissions: submissions,
            });
        } catch (error) {
            throw error.message;
        }
    }

render() {
        const { studentSubmissions } = this.state;
        return (

        )
    }

export default SubmissionsDetail;

and in hook, it look like this
    const [studentSubmissions, setStudentSubmissions] = useState([]);

    useEffect(() => {
        async function fetchSubmissions() {
            const { dispatch, itemId } = props;
            try {
                if (itemId) {
                    await dispatch({
                        type: 'assignment/fetchSubmissionsByAssignment',
                        payload: {
                            id: itemId
                        }
                    });
                }
                const { submissions } = props;
                setStudentSubmissions(submissions)
            } catch (error) {
                throw error.message;
            }
        };
        fetchSubmissions()
    }, []);

return (

        )

export default SubmissionsDetail;

I omitted some code for better reading, like connect to redux store or others.
and the component is import in the parent file like this
import SubmissionsDetail from './SubmissionsDetail'

{assignmentIds.map((itemId) => {
    <SubmissionsDetail itemId={itemId}/>
})}

it work perfect in class component, the expected result should return tables like this

However, when I change to use hook, the result return like this

or sometimes all data in tables become submissions3
I try to console.log(submissions) inside the try{...} block, when in class, the result is
which is correct, there have two assignments, the one have 4 submissions, another one have zero submission.
But the output in hook is different, the result is like this

either both have 4 submissions, either both have zero. That means one obj affect all other obj.
It seems like if useState change, it would influence other objs, that make me really confused. I think in the map method, each item is independent, right? If so, and how to explain why it work perfectly in class setState, but failed in hook useState?
I hope my question is clear enough, If you know how to describe my question in short, plz let me know, I would update the title, to help locate experts to answer.
Please don't hesitate to share your opinions, I really appreciate and need your help, many thanks!
Comment: @MichaelHoobler Hi, I just add it in the description, could you please take a look?
Comment: Can you console.log `submissions` inside the `try{...}` block, and tell us if it's different inside the class vs functional compoenent?
Answer: There is no reason to use a local component state in either the class or the function component versions.  All that the local state is doing is copying the value of this.props.submissions which came from Redux.  There's a whole section in the React docs about why copying props to state is bad.  To summarize, it's bad because you get stale, outdated values.
Ironically, those stale values were allowing it to "work" before by covering up problems in your reducer.  Your reducer is resetting the value of state.submissions every time you change the itemId, but your components are holding on to an old value (which I suspect is actually the value for the previous component? componentDidMount will not reflect a change in props).
You want your components to select a current value from Redux based on their itemId, so your reducer needs to store the submissions for every itemId separately.  @Michael Hoobler's answer is correct in how to do this.
There's no problem if you want to keep using redux-saga and keep using connect but I wanted to give you a complete code so I am doing it my way which is with redux-toolkit, thunks, and react-redux hooks.  The component code becomes very simple.
Component:
import React, { useEffect } from "react";
import { fetchSubmissionsByAssignment } from "../store/slice";
import { useSelector, useDispatch } from "../store";

const SubmissionsDetail = ({ itemId }) => {
  const dispatch = useDispatch();
  const submissions = useSelector(
    (state) => state.assignment.submissionsByItem[itemId]
  );

  useEffect(() => {
    dispatch(fetchSubmissionsByAssignment(itemId));
  }, [dispatch, itemId]);

  return submissions === undefined ? (

Loading

  ) : (

Assignment {itemId}

Submissions {submissions.length}

  );
};

export default SubmissionsDetail;

Actions / Reducer:
import { createAsyncThunk, createReducer } from "@reduxjs/toolkit";

export const fetchSubmissionsByAssignment = createAsyncThunk(
  "assignment/fetchSubmissionsByAssignment",
  async (id) => {
    const response = await getSubmissionsByAssignment(id);
    // can you handle this in getSubmissionsByAssignment instead?
    if (response.status !== 200) {
      throw new Error("invalid response");
    }
    return {
      itemId: id,
      submissions: response.data.collections
    };
  }
);

const initialState = {
  submissionsByItem: {}
};

export default createReducer(initialState, (builder) =>
  builder.addCase(fetchSubmissionsByAssignment.fulfilled, (state, action) => {
    const { itemId, submissions } = action.payload;
    state.submissionsByItem[itemId] = submissions;
  })
  // could also respond to pending and rejected actions
);

Comment: I hate why I can only accept one answer, I really benefit a lot from your answer, let me deepen my understanding of local component state in both class and functional component, the framework I use currently doesn't use thunk, but I can totally understand the elegant code you write. Thanks a lot!
Answer: Edit: You are probably going to want to rework the way you store the submission inside of the redux store if you really want to use the Hook Component. It seems like right now, submissions is just an array that gets overwritten whenever a new API call is made, and for some reason, the Class Component doesn't update (and it's suppose to update).
Sorry it's hard to make suggestions, your setup looks very different than the Redux environments I used. But here's how I would store the submissions:
// no submissions loaded
submissions: {}

// loading new submission into a state
state: {
  ...state,
  sessions: {
    ...state.session,
    [itemId]: data
  }
}

// Setting the state inside the component
setStudentSubmissions(props.submissions[itemId])

And I think you will want to change
yield put({
  type: 'getSubmissions',
  payload: response.data.collections
});

to something like
yield put({
  type: 'getSubmissions',
  payload: {
    data: response.data.collections,
    itemId: id
});

If you want to try a "hack" you can maybe get a useMemo to avoid updating? But again, you're doing something React is not suppose to do and this might not work:
// remove the useEffect and useState, and import useMemo
const studentSubmissions = useMemo(async () => {
  try {
    if (itemId) {
      await dispatch({
        type: "assignment/fetchSubmissionsByAssignment", //here to fetch submissions in props
        payload: {
          id: itemId,
        },
      });
      return this.props.submissions;
    }
    return this.props.submissions;
  } catch (error) {
    throw error.message;
  }
}, []);

return (

)

export default SubmissionsDetail;

Comment: Yes, it change at all, I just add it in the description, in class, it return different result base on different itemId, but in hook, it return the same result
Comment: `useMemo` doesn't work, but your suggestions about how to store submissions are really useful! Just to mention, it doesn't need to setting the state inside the component `setStudentSubmissions(props.submissions[itemId])` I try it, but eventually the result still get fail, same issue, but I change to pass props value directly like`` it work perfectly! I guess the reason why setState not work is already well explained by @Linda Paiste answer. Again, thanks for your patient, your effect, your professionalism, many thanks for sharing your experience!
Comment: @RH-st Is `submissions` coming from Redux? Can you show me how `submissions` is getting it's values?
Comment: Yes, it come from Redux, in the model, it fetch data like this `*fetchSubmissionsByAssignment({ payload }, { call, put }) {
   const { id } = payload;
   const response = yield call(getSubmissionsByAssignment, id);
   if (response.status === 200) {
    yield put({
     type: 'getSubmissions',
     payload: response.data.collections
    });
   }
  }`
and then `reducers: {
  getSubmissions(state, { payload }) {
   return {
    ...state,
    submissions: payload
   };
  }`
Answer: if you have an object as state, and want to merge a key to the previous state - do it like this
const [myState, setMyState] = useState({key1: 'a', key2: 'b'});

setMyState(prev => {...prev, key2: 'c'});

the setter of the state hook accepts a callback that must return new state, and this callback recieves the previous state as a parameter.
Comment: Actually I want the current state won't affect previous state, it seems in class, I don't need to worry about it, but in hook, if current state change, it will affect previous render
Answer: Since you did not include large part of the codes, and I assume everything works in class component (including your actions and reducers). I'm just making a guess that it may be due to the omission of key.
{assignmentIds.map((itemId) => {
    <SubmissionsDetail itemId={itemId} key={itemId} />
})}

OR it can be due to the other parts of our codes which were omitted.


Will this while loop end when the if statement inside is met

Question: I have this block of function that searches through my email column for matches. After a match has been found, will this While loop continue to search for other matches or will it end if the if statement inside it is met?
function find_similar_email ($email) {
    global $con;
    // select db
    mysql_select_db('practice', $con);

    // select a column to search from
    $emailList = mysql_query("SELECT email FROM users", $con);

    // search for similar matches
    while ($emailListResult = mysql_fetch_array($emailList)) {
        if ($email == $emailListResult['email']) {
            return TRUE;
        }
    }
}

Comment: Yep. I'd recommend running `return false` afterwards. Also, `mysqli_`, and DI, (pass `$con` to `find_similar_email`).
Answer: If the if conditon is met, the return statement will be exectued. This leaves the function, and effectively ends the while loop.
Comment: Thank you, now I know return ends it.
Answer: In your example, return will exit the function, effectively terminating the loop.
However, you should use a WHERE clause to do your selection rather than selecting everything and searching the result. Since you're only looking to see if the email address is in the table you could do this:
function find_similar_email ($email) {
  global $con;
  // select db
  mysql_select_db('practice', $con);

  // select all rows with matching email address
  $emailList = mysql_query("SELECT email FROM users where `email`='$email'", $con) or die(mysql_error($con);

  return(mysql_num_rows($emailList) !== 0);  // return true if we found it, false if we didn't
}

Answer: "return" exits the function. so yes, no more rows will be read...


AWS ECS containers - ELB health checks close the container

Question: I'm trying to create multiple WordPress instances on ECS containers.
I have a task definition where i set up 2 containers for WordPress
- 1 WordPress container with host port 0 (per AWS documentation)
- 1 MySQL container
Network is bridge
I create a service with an Application Load Balancer and "Health check grace period" of 200 sec. Via AWS interface i add the WordPress container in load balancer and set port 80 as Production listener port.  See screenshot http://prntscr.com/p7s30z
After i create the service, the task start running and the containers are working for a short period. I can access the WordPress install on a ip:port url(for ex: http://126.96.36.199:32768/ ), and i can even do the setup and publish a post. However in 2-3 minutes the containers get stopped and in task page i see
Stopped reason: Task failed ELB health checks in (target-group arn:aws:elasticloadbalancing:us-east-1:548086034478:targetgroup/cretutarget/e3a5f331c35eece1)

I use a security group that is very permissive and the Wordpress containers is accessible in the first moments.
For that target group the health checks looks like this : http://prntscr.com/p7s8u5
Any idea why the ELB health checks fails ?
Answer: Where are the php/html files stored for this wordpress database? I would check to make sure that the ALB Security Group has access to where the files are located or the security group your ECS instances are at. Also, make sure you use the root path '/' for the health check.
Comment: Also, if you used AWS ECS, it should have setup the correct ports for you with the ALB and ECS instance
Comment: This is my wp container definition http://prntscr.com/p7wn3q , so files are stored inside container. root path is '/' . security group is the same and is a very permisive one. Also the wp container is fully functional for 1-2 min until the health check runs.Thanks
Comment: Can you do a curl of the local host of the physical ECS instance and inside the container ?  Also, the files are stored in the container ? Do you mean the DB container or mounted EFS ?
Answer: Most likely the health check URL is getting a redirect to the WordPress setup page or login page. By default a Target Group health check expect a status code of 200 to be returned, not a 301 redirect. You can test this by watching your browser's network tab as you try to go to the / path on your WordPress site, and see what status code it returns. If that status code isn't 200 then you'll need to add the other status code (301 or whatever it is returning) in your target group's health check settings at least temporarily until you get the site configured and returning 200 on the / path.


Server performance abysmal, should mysql have many instances running?

Question: Mysql appears to be sucking a good chunk of memory up. Should mysql be running so many instances?
I've considered upgrading the server's memory (because it's maxed) but I'm concerned there is a problem with mysql because to me the memory usage seems high.
How can I determine if those instances of mysql should be running and do  need that much memory?
Let me know if I can provide further details, not sure how to troubleshoot.
Comment: Your MySQL is using about 211MiB out of 2GiB. There is nothing wrong with that.
Comment: So the total of all the mysql instances is 211MiB? Where the heck is all the server memory going to then...
Comment: Is this an OpenVZ container? That is probably your problem.
Comment: @payling Systems that aren't under memory pressure don't try to make free memory. It serves no purpose. (It's not like using less now lets you use more later. You can't save up memory for later.) Unless you have evidence a system is under memory pressure, there's absolutely no reason to care how much memory is being used.
Comment: Michael, it is OpenVZ. I guess that explains when I do a free -m there is no swap space setup.
Comment: David, my understanding of htop is green bars indicate used memory pages, blue is buffered, and yellow is cache. My memory bar is all green, I'm assuming that means all memory is actively used... Does that not mean my system is under pressure?
Answer: phpmyadmin processlist will show you what the connection are doing. If they are mostly sleeping you need to look at your application code to work out how to close the connection earlier. If they are mostly running queries, you need to look at your slow query log and start tuning queries. If there are a lot of blocked connection then you probably need to switch your storage engine.
But reducing the number of mysql connection might have no impact on overall performance. Analysing that, never mind fixing the problem goes way beyond the scope of a question here. You might start by reading some good books on web performance (1, 2, 3)


Derivatives in Recurrent Neural Networks

Question: I am studying the book of Goodfellow et al. on deep learning, and I am stuck at equation (10.19).
Said equation gives the gradient of the Loss with respect to the hidden layer.  Now, if the Loss gives a vector, and since the hidden layer weights is a vector too, this would result in a Jacobian matrix.  However, with the definition given, the result is a vector with the same dimensions as the hidden layer.
What am I missing?
Answer: Look up page 199 section 6.5.2 of the book.
This is a straight application of the chain rule of calculus.
V is the Jacobian Matrix in this case (eq 10.19) because o(t) = V*h(t) + c the partial derivatives are just the coefficients of the matrix (transposed).
There are no assumptions on h and o being same sized vector.
h depend on how many recurrent cells you have in your layer and o depends on how many cells you have in the output layer.


List comprehension of namedtuples results in empty list

Question: I've stumbled upon a problem I just can't seem to find an answer for. I am reading the contents of a csv file using csv.DictReader and constructing a list of namedtuples from that information. However, upon running it, the end result is an empty list.
from collections import namedtuple
import csv

nt = namedtuple('suminfo', 'a, b, c')
checklist = ['check1', 'check2', 'check3']

with open('test.csv', 'r') as csv_file:
     csv_rows = csv.DictReader(csv_file, delimiter='\t')
     tups = [nt(row['first'], row['second'], row['third'])
            for row in csv_rows if row['first'] in checklist]

I have also tried a typical normal loop of the rows followed by list appending of a namedtuple, and this seems to work just fine.
Why is the listcomprehension not behaving as expected? Thank you for your time.
Answer: The list comprehension is working for me. I used this test data (test.csv):
first   second  third
check1  1   1
check2  2   2
check3  3   3
check4  4   4

The values are separated by tabs. When I run your code,
nt = namedtuple('suminfo', 'a, b, c')
checklist = ['check1', 'check2', 'check3']

with open('test.csv', 'r') as csv_file:
    csv_rows = csv.DictReader(csv_file, delimiter='\t')
    tups = [nt(row['first'], row['second'], row['third'])
            for row in csv_rows if row['first'] in checklist]
    print(tups)

I get the following result:
>>> [suminfo(a='check1', b='1', c='1'), suminfo(a='check2', b='2', c='2'), suminfo(a='check3', b='3', c='3')]

Comment: 10 bucks says the OP's file is not tab delimited.
Comment: Thanks for taking your time to verify that it works!
Comment: @JaredSmith Sorry to dissapoint but the error seems to have been somewhere else. I just copied my own code and ran in stand-alone and it did what I was expected. Seems to be a silly spelling mistake somewhere.


Expected value notation

Question: I come across the notions $\mathrm{E}[wage]$ and $\mathrm{E}[wage_i]$. I would like to clarify if they have different meanings.

Take the first expression. $\mathrm{E}[wage]$ could represent the average of all elements in $wage$ in the population. Here, it is my guess that $wage$ is the vector of all theoretical $N$ observations. Otherwise I do not know what the first expression is trying to say.
We consider $y_i$ as a random variable. It has a distribution. The mean of this distribution is $\mathrm{E}[wage_i]$. Hence, $\mathrm{E}[wage_i]$ means that we take the average of all theoretical observations $wage_i$ can take.

Could I then conclude that $\mathrm{E}[wage]$ and $\mathrm{E}[wage_i]$ refer to the same thing?
Comment: First may mean vector of mean values, for example, in multidimensional distribution
Answer: Very often it is assumed that the stochastic variables under consideration are identically distributed. So $wage_i$ follows a distribution $F_i(.)$ but since this $F_i(.)= F(.)$ for all $i$ the expectation for $wage_1$ and $wage_2$ will be the same and so for all $i\not = j$. This very often leads to the adoption of the notation where the index is simply left out.
Note though that in some contexts authors choose to leave out index simply because it is too cumbersome to write. This is clearly the case in a setting of wage regressions where
$$\mathbb E[wage_i \lvert \mathbf x_i ] = \mathbf x_i^\top \boldsymbol \beta$$
is very often simply written as
$$\mathbb E[wage \lvert \mathbf x ] = \mathbf x^\top \boldsymbol \beta$$
without this implying that wages are identically distributed. So here it is simply short hand notation for the perhaps more precise notation that includes the index.
Comment: Thanks. So whenever I do not see the $i$ subscript, I should check that somewhere the i.i.d. assumption is made. I very much dislike shorthand notation. Mathematics is a language. If you swallow words when speaking it, why the audience is supposed to understand what you are talking about?
Comment: is it true that I could well use the notation E[x_i] instead of E[X] in the "Finite case" example made here: en.wikipedia.org/wiki/Expected_value? So would be perfectly acceptable if E[X] has been denoted as E[x_i]?

Expected value notation


"Rubato sufficiently repeated turns into a feature of the rhythm." Please critique

Question: I was thinking about the very idea of rubato the other day and was wondering if repeated rubato truly defeats its purpose.

Rubato sufficiently repeated turns into a feature of the rhythm.

I don't have any rigorous musical training, just some self-education in theory, so I was hoping I could get an informed critique of the validity, veracity or even the limitations of such a statement.
Thank you.
Comment: The first definition to come up for 'rhythm' in google is "a strong, regular repeated pattern of movement or sound" - which doesn't seem like a a bad definition. By that logic, *anything* repeated would become a feature of the overall rhythm of the piece. I'm wondering why you doubt the validity of the statement, if you do?
Answer: Seems a reasonable comment. One modification is decoration.  Modify EVERY time and it becomes 'baked in'.
I don't think there's any deep musical insight required here.  It's just a description in plain English.
Answer: A rhythm, by definition, is a pattern. If that pattern includes regular rubato, then that becomes part of that pattern.
So yes, it turns into a feature of that rhythm. Could depend, of course, on how regularly it features.


Enforce rule on Sticky to the top of lists

Question: I have x amount of nodes of content type "job", all of which are presented on page using two views, one that sits at the top "job-highlighted" and one that sits at the bottom "rest-of-jobs".
One job is selected to be displayed in the top view. It is selected using the "Sticky at top of lists" option in the back end.
The rest are displayed in the "rest-of-jobs" view.
The problem is that the user can set a number of jobs to have the sticky at the top of lists selected.
My question is, is there a way to enforce the content type job to have only one node with the sticky at the top of lists functionality. Can I implement a procedure that updates these or is there a module that already introduces this functionality?
Can anyone offer a solution. Thanks in advance.
Comment: In the context of [this question](http://meta.drupal.stackexchange.com/q/3619/39516) (on meta.drupal.SE), I wonder why you used the 8-tag in this question. Would you mind (briefly) explaining so please?
Answer: Do you have a node for the overview page? If so:
Instead of using the sticky to top button add a relationship field to the job overview node and set that to allow 1 value, and show the selected job in the highlight field.
Answer: Allow only 1 value in your view "job-highlighted". That should do it for you.
Comment: Hi @Umed, please refrain from posting one-sentence answers. If possibly, provide step-by-step instructions on how to do configure this and maybe add a screenshot of the resulting configuration screen. Thanks!


Checking to see if cell values are integers, if not then adding message

Question: I have a column (col G) where I want to verify the values are numeric. If they are not numeric I want to paste an error message in col A. I don't get any errors when running my code, but it seems to print the error message even though there is a number in the cell.

Dim cell As Range
Dim lastRow As Long
lastRow = Range("G" & Rows.Count).End(xlUp).row

For Each cell In Range("G2:" & "G" & lastRow)
If IsNumeric(Range("G2:" & "G" & lastRow)) = True Then cell.Offset(0, -6).Value = cell.Offset(0, -6).Value & ", G is not a number"
Next
End Sub

Answer: Looping through cells with condition could be done like this:
Sub TestMe()

    Dim cell As Range
    Dim lastRow As Long
    lastRow = Worksheets(1).Range("G" & Rows.Count).End(xlUp).Row

    For Each cell In Worksheets(1).Range("G2:" & "G" & lastRow)
        If IsError(cell) Then
            cell.Offset(0, -6).Value = cell.Address & " is error!"
        ElseIf Not IsNumeric(cell.Value) Then
            cell.Offset(0, -6).Value = cell.Value & " is not a number"
        End If
    Next

End Sub

It is a good practice to refer to the parent worksheet as in Worksheets(1).Range....
Comment: @Vityata, excellent answer. However, would you want to add a check for cell value in error. Something like this before the test `IsNumeric`: `If VarType(cell.Value) = vbError Then
        cell.offset(0, -6).Value = "Cell is in error"
    Else`
Comment: @Guest - thanks :) I have added the `IsError()` part.


Integrate $\int_{-\infty}^{-1}e^{tx}\frac{3}{2}x^{-4}\,dx + \int_1^{\infty}e^{tx}\frac 3 2 x^{-4}\,dx$

Question: I want to evaluate the integral
$$\int_{-\infty}^{-1}e^{tx}\frac{3}{2}x^{-4}\,dx + \int_1^{\infty}e^{tx}\frac 3 2 x^{-4}\,dx.$$
I know this is the exponential integral but I am wondering if it's possible to write this particular case in terms of elementary functions.
The taylor expansion for $e^{tx}$ is $e^{tx} = 1 + tx + \frac{t^2x^2}{2!} + \ldots = \sum_{k=0}^{\infty}\frac{(tx)^k}{k!}$, so going down that path I got this far:
\begin{align*}
    \int_{-\infty}^{-1}e^{tx}\frac{3}{2}x^{-4}\,dx + \int_1^{\infty}e^{tx}\frac 3 2 x^{-4}\,dx &= \frac{3}{2}\int_{-\infty}^{-1}\sum_{k=0}^{\infty}\frac{(tx)^k}{k!}x^{-4}\,dx + \frac{3}{2}\int_1^{\infty}\sum_{k=0}^{\infty}\frac{(tx)^k}{k!} x^{-4}\,dx \\
    &= \frac{3}{2}\int_{-\infty}^{-1}\sum_{k=0}^{\infty}\left(\frac{1}{x^4} + \frac{t}{x^3} + \frac{t^2}{2!x^2} + \ldots \right)\,dx \\ &+ \frac{3}{2}\int_1^{\infty}\sum_{k=0}^{\infty}\left(\frac{1}{x^4} + \frac{t}{x^3} + \frac{t^2}{2!x^2} + \ldots \right)\,dx \\
    &= \frac{3}{2}\left[\frac{-1}{3x^3} + \frac{t}{2x^2} - \frac{t^2}{2!x} + \ldots \right]_{-\infty}^{-1} + \frac{3}{2}\left[\frac{-1}{3x^3} + \frac{t}{2x^2} - \frac{t^2}{2!x} + \ldots \right]_{1}^{\infty} \\
    &=
\end{align*}
But am now struggling to evaluate the antiderivative at the limits. Is there a better way to do this?
Comment: Are you sure this integral converges? I can see that the second integrand diverges as $x\rightarrow\infty$ for any $t>0$ and first integrand diverges as $x\rightarrow-\infty$ for $t<0$.
Answer: Okay, I'm just going to assume that you meant
$$I(t)=\int_1^\infty e^{-tx}x^{-4}dx$$
for $t>0$ because otherwise the integral diverges. As far as I'm concerned, there are no elementary function that describes your integral because it involves error function (that is the antiderivative of Gaussian function) but it can be written as an antiderivative of elementary function.
Observe that
$$I'(t)=\int_{1}^\infty -e^{-tx}x^{-3}dx$$
and on the other hand, integrating by parts,
$$I(t)=\bigg[-\frac{1}{3}e^{-tx}x^{-3}\bigg]_1^\infty-\int_1^\infty\frac{t}{3}e^{-tx}x^{-3}dx=\frac{e^{-t}}{3}+\frac{tI'(t)}{3}.$$
You can then solve for $I(t)$ using method of integrating factor. Here's some reference https://mathworld.wolfram.com/IntegratingFactor.html in case you're not familiar with integrating factor.


Lie algebra (invariant)-action on bilinear form

Question: Let $(\pi, V)$ be a rational representation of $G$ a Lie algebra, and let $B$ be a bilinear form defined on $V$.
Then there is an action of $G$ on $B$ given by $$ g \cdot B(u,v) = B(g^{-1}u, g^{-1}v).$$
We can choose to write $B(u,v) = v^t \Gamma u$, so that succinctly $ g \cdot \Gamma = g^{-1} \Gamma g^{-1}$.
I want to show that the action of $X \in \mathfrak{g}$ on $B$ is given by $$ X \cdot B(u,v) = - B(d\pi(X)u,v) - B(u, d\pi(X)v).$$
This form looks related to the fact that the differential should be a derivation, but I am having trouble making this clear (this might be related to my other question here).
Otherwise, as in another of my questions, I am familiar with the definition of the differential via both the exponential map and vector fields, however I am unsure how to apply it here to obtain the desired action on the bilinear form.
Furthermore, is it true that if $B$ is $G$-invariant then it is also $\mathfrak{g}$-invariant? And/or if this is true/not true, is it clear from the solution to my first question?
Comment: Is this related to https://math.stackexchange.com/questions/674867/invariant-bilinear-forms-on-lie-algebras ?
Answer: To be clear, the action of $G$ is on the vector space of all bilinear forms
$$ \operatorname{Bil}(V) = \{B \colon V \times V \to \mathbb{C} \mid B \text{ bilinear}\}.$$
For a hand-wavy derivation of the action of $\mathfrak{g}$, suppose that $G$ is embedded inside $\operatorname{GL}_n$, so that we can consider a small perturbation $\pi(I + tX)$ for some $X \in \operatorname{Mat}_n$: by the definition of the differential we should have
$$ \pi(I + tX)(v) = v + t d \pi_I(X)(v) + O(t^2),$$
the term with the $t$ in front gives us the action of $X \in \mathfrak{g}$ on $V$, namely $X \cdot v = d \pi_I(X) v$.
Now let $\rho(g)(B)(u, v) = B(\pi(g^{-1})u, \pi(g^{-1})v)$, so considering a perturbation again we get
$$\begin{aligned} (\rho(I + tX)B)(u, v)
&= B(\pi(I + tX){^-1} u, \pi(I + tX)^{-1} v) \\
&= B(\pi(I - tX + O(t^2))u, \pi(I - tX + O(t^2))v) \\
&= B(u - t d\pi_I Xu + O(t^2), v - t d\pi_I Xv + O(t^2)) \\
&= B(u, v) - t B(d\pi_I X u, v) - t B(u, d \pi_I X v) + O(t^2).\end{aligned}$$
Here we have approximated $(I + tX)^{-1} = I - tX + t^2 X^2 - t^3 X^3 + \cdots$ by $I - tX + O(t^2)$, and the last inequality uses the bilinearity of $B$. So we find that the action of $X \in \mathfrak{g}$ is $$(X \cdot B)(u, v) = - B(d\pi_I(X) u, v) - B(u, d \pi_I(X), v).$$
Any "real" proof of this result is essentially upgrading this simplified result to be more rigorous (in fact for affine algebraic groups, this is basically the real proof, once one knows how to interpret $t^2 = 0$ appropriately). But if you are working over differentiable manifolds you can make this rigorous using your definition of the differential.
Another way to see this is to first understand how the Lie algebra acts on the dual $V^*$, and on tensor products; then one uses the canonical isomorphism $V^* \otimes V^* \to \operatorname{Bil}(V)$ taking $\varphi \otimes \psi$ to the bilinear form $(u, v) \mapsto \varphi(u) \psi(v)$. Of course then we have that
$$ X \cdot (\varphi \otimes \psi) = -d\pi_I(X)^t \varphi \otimes \psi - \varphi \otimes d\pi_I(X)^t \psi,$$
which is the same bilinear form.
Comment: @mizh: For a linear map $A: V \to V$, I am using $A^t$ to mean the _canonical_ transpose map, which is defined on the dual $A^t: V^* \to V^*$. For a functional $\varphi$, the action of $A^t$ is to precompose with $A$: we have $A^t \varphi := \varphi \circ A$, which is sometimes written as $(A^t \varphi)(v) = \varphi(Av)$.
Comment: As for the other questions, for a map $\pi: X \to Y$ of manifolds, the differential $d \pi: TX \to TY$ is a map of tangent bundles. We can fix a point $x \in X$ and look at the differential _just at that point_: $d \pi_x: T_x X \to T_{\pi(x)} Y$, which is a linear map. This is what I mean by the notation $d \pi_I$: it is the derivative of $\pi$ at the identity element of $G$. If you think of examples that come up in multivariable calculus, $d\pi$ is like a Jacobian matrix full of functions, and $d \pi_x$ is the Jacobian evaluated at a point: a matrix full of numbers.
Comment: And lastly, if $\pi: V \to W$ is a smooth (but possibly nonlinear) map between two vector spaces, the differential $d \pi_v: V \to W$ is a _linear_ map satisfying the condition that $\pi(v + tu) = \pi(v) + t d \pi_v(u) + O(t^2)$, in other words $\pi$ can be approximated near $v$ by $\pi(v + \epsilon) \approx \pi(v) + d\pi_v(\epsilon)$ for small vectors $\epsilon$. This definition of the derivative is probably incorrect for very technical reasons, but it's basically good enough for trying to figure out how things should work. For the "correct" definition see a multivariable calculus textbook :P
Comment: The second way to see the statement is actually what my textbook was doing, this makes a lot of sense now! I have some questions though.

1) Why do you replace $\pi$ with $\pi_I$?
Comment: 2) The expression $-d\pi_I(X)^t \varphi \otimes \psi - \varphi \otimes d\pi_I(X)^t \psi$ does not seem to be an element of $V^* \otimes V^*$, unless by convention we first act on $v \in V$ by $-d\pi(X)^t$ and then apply the functionals $\varphi$ and $\psi$. Is there a reason for this?
Comment: 3) In the first part, 'definition of the differential...' shouldn't we be differentiating with respect to $t$ on both sides at $t=0$?


Remover botão do form e remover o codigo

Question: Boa tarde pessoal, como posso limpar o codigo na situação onde, coloquei os botões conforme um determinado uso, depois resolvemos tirar os botões mas os codigos estão lá, ( os eventos click )
Como posso remover o botão e remover os eventos e referencias sem detonar o programa ?
Comment: Não é só apagar o código do evento?
Comment: Não tem porquê dar errado, é só remover o controle e depois o código.
Comment: Fiz uma vez e me dei mal, não quero arriscar novamente
Comment: Até então funcionou sem problemas
Comment: Isso é `Forms` ou `Web`? Procure os eventos no código pelo nome (*Button1_Click* por exemplo), porque os eventos podem ser registrados em outro local e dar erro se você remover só o método em si
Comment: Num `WindowsForm`, os eventos são registrados no arquivo `.Designer.cs`, se for um `WebForms` antigo, no método `InitializeComponent`, e assim por diante, então não adianta só remover do código, tem que limpar nesses locais também
Comment: @RicardoPontual é WindowsForm
Comment: Então procure os eventos no arquivo com o mesmo nome do form com `.Designer.cs`, senão vai dar erro se você remover só do arquivo `.cs`
Answer: Provavelmente o erro deve esse após a exclusão:

Isso acontece que ao click 2 vezes no controle para criar um evento ele vincula o evento no Form1.Designer.cs, dai se vc simplesmente apagar o evento no código ele gere esse erro.
Soluções:
1º Removendo a partir dos eventos disponíveis listados na aba Ferramentas.

2ºRemovendo direto em Form1.Design.cs

Espero ter ajudado!!!
Comment: Eu removi o botão e o evento tambem, está funcionando aqui tranquilo
Comment: blz!!!! Se ajudou, click na setinha sinalizando que a resposta foi útil.


ASP MVC 5 - Erro em Upload de Imagem "The input is not a valid Base-64 string"

Question: Estou tentando resolver esse erro de todas as maneiras que encontrei sugeridas em fóruns, mas todas as soluções que tentei nenhuma resolveu o meu problema. Sempre que efetuo um submit a minha View apresenta este erro e não chega nem receber nada no meu método de controlador com HttpPost.
Controller
    [HttpPost]
    public ActionResult Alterar(Produto produto, HttpPostedFileBase imagem = null)
    {
        if (ModelState.IsValid)
        {
            _repositorio = new ProdutosRepositorio();
            _repositorio.Salvar(produto);

            return RedirectToAction("Index");
        }

        return View(produto);
    }

Model Class
[Table("Produto")]
public class Produto
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Display(Name = "ID")]
    public int ProdutoId { get; set; }

    [Required(ErrorMessage = "Campo nome obrigatório")]
    [Column(TypeName = "varchar")]
    [StringLength(60, MinimumLength = 4, ErrorMessage = "Tamanho máximo permitido {1} e mínimo {0}.")]
    [Display(Name = "Nome")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "Campo primeiro nome obrigatório")]
    [Column(TypeName = "varchar")]
    [StringLength(60, MinimumLength = 4, ErrorMessage = "Tamanho máximo permitido {1} e mínimo {0}.")]
    [DataType(DataType.MultilineText)]
    [Display(Name = "Descrição")]
    public string Descricao { get; set; }

    [Required(ErrorMessage = "Campo preço obrigatório")]
    [Range(0.01, double.MaxValue, ErrorMessage = "Valor inválido")]
    [Display(Name = "Preço")]
    public decimal Preco { get; set; }

    [Display(Name = "Imagem")]
    public byte[] Imagem { get; set; }

    [MaxLength(50)]
    [Column(TypeName = "varchar")]
    public string ImagemMimeType { get; set; }

    [Required(ErrorMessage = "Campo categoria obrigatório")]
    [Column(TypeName = "varchar")]
    [StringLength(40, MinimumLength = 4, ErrorMessage = "Tamanho máximo permitido {1} e mínimo {0}.")]
    [Display(Name = "Categoria")]
    public string Categoria { get; set; }
}

View
    @using (Html.BeginForm("Alterar", "Produto", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

            @Html.HiddenFor(model => model.ProdutoId)

                @Html.LabelFor(model => model.Nome)
                @Html.TextBoxFor(model => model.Nome, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Descricao)
                @Html.TextAreaFor(model => model.Descricao, new { @class = "form-control", rows = 5 })
                @Html.ValidationMessageFor(model => model.Descricao, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Preco)
                @Html.EditorFor(model => model.Preco, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Preco, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Categoria)
                @Html.EditorFor(model => model.Categoria, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Categoria, "", new { @class = "text-danger" })

                    Imagem

                        Selecione a imagem...
                        <input type="file" name="imagem" size="40" style="position:absolute;z-index:2;top:0;left:0;filter:alpha(opacity=0);opacity:0;background-color:transparent;color:transparent;" />

                <input type="submit" value="Salvar" class="btn btn-primary" />
                @Html.ActionLink("Cancelar", "Index", null, new { @class = "btn btn-default" })

    }

Script

        $("input[name='imagem']").change(function () {
            var file = $(this).val().replace("C:\\fakepath\\", "");;

            $('#upload-file-info').html(file);
        });
Comment: Tente mudar o mudar o name do input para "Imagemproduto" e receba assim na controller
Comment: Como vc está adicionando a imagem?
Comment: Janderson, eu ainda nem comecei o código de inserção da imagem por causa desse erro. Eu estava fazendo o teste ainda de como ela estava chegando nos parâmetros do método de controlador Alterar e antes mesmo de chegar ao método já está apresentando este erro.
Comment: Janderson, funcionou. Obrigada!
Comment: Vou colocar como resposta ok..
Answer: Tente mudar o mudar o name do input de imagem para "imagemproduto" e receba assim na controller.
Acho que o que acontece é que deve estar conflitando com propriedade:
public byte[] Imagem { get; set; }"

com o name do input:
<input type="file" name="imagem" size="40" style="position:absolute;z-index:2;top:0;left:0;filter:alpha(opacity=0);opacity:0;background-color:transparent;color:transparent;" />

ASP MVC 5 - Erro em Upload de Imagem “The input is not a valid Base-64 string”


Como modificar um item em um ponto especifico da página? (HTML, CSS)

Question: Olá, na minha pagina possui um menu fixo composto por texto, preciso que quando ele chegue a certo ponto da pagina ele mude da cor branca para preta mas não tenho ideia de como posso fazer isso.
Comment: Como definir qual é o "certo ponto"?
Comment: mas quem era branco e deverá ser preto?  Como criar um exemplo Mínimo, Completo e Verificável https://pt.stackoverflow.com/help/mcve
Comment: Postar código como imagem -
 https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5485#5485
Comment: o que seria "certo ponto"? para mudar o estilo de um elemento em JS, usa `elemento.style = "estilo";` é isso?
Answer: Será que precisa ser somente com CSS mesmo?
Se puder ser com JavaScript pode usar o scroll touchmove do jQuery.
Segue um exemplo:

$(window).on("scroll touchmove", function() {
  if ($(document).scrollTop() >= $("#mudar").position().top) {
    $('body').css('background-color', 'orange');
  } else {
    $('body').css('background-color', 'white');
  }
});
div{
  height: 300px;
  padding: 10px;
}

Não muda.

Não muda.

Não muda.

Mudar quando chegar aqui.

Não muda.

Não muda.

Não muda.

Não muda.

Não muda.

Não muda.

A vantagem dessa função scroll touchmove é que você não precisa
  definir o tamanho da rolagem que vai ser feita para mudar a
  propriedade do elemento, porque o tamanho da rolagem pode mudar dependendo do
  dispositivo que está acessando o site. Então o scroll touchmove só
  muda a propriedade quando o topo do navegador chega no elemento
  escolhido que no caso do meu código foi a
 com o id="mudar".

Aprendi com o cara que respondeu essa pergunta minha: Mudar aparência ao passar pela section
Answer: Você pode utilizar tanto jQuery como Javascript.
JavaScript
window.addEventListener('scroll', myFunction);

function myFunction() {
  // Seleciona o elemento alvo
  var element = document.querySelector(".element");
  if (window.pageYOffset > 100) {
    // Ao descer 100px, realiza as modificações desejadas
    element.classList.add('scrolled');
  } else {
    // Ao retornar ao topo da página, desfaz as modificações
    element.classList.remove('scrolled');
  }
}

jQuery
$(window).scroll(function(e){
  if ($(this).scrollTop() > 100) {
    // Ao descer 100px, realiza as modificações desejadas
    $('.element').addClass('scrolled');
  } else {
    // Ao retornar ao topo da página, desfaz as modificações
    $('.element').removeClass('scrolled');
    }
});

Exemplos

JavaScript
jQuery


Erro na hora de efetuar a soma dentro do foreach

Question: Eu tenho esse método CadastroDespesas, só que ele está efetuando a soma errado no foreach que percorre a minha lista.
Eu não sei o que é, se alguém puder me ajudar...
A totdesp é uma variável global declarada na minha classe).
class Ex4
{
    List<String> descricaodespesas = new List<string>();
    List<float> valordespesas = new List<float>();
    List<String> descricaoreceitas = new List<string>();
    List<float> valorreceitas = new List<float>();
    float totdesp, totreceit;
    float mediareceit, mediadesp;

    public void CadastroDespesas()
    {
        string descricao;
        float valor,somadesp = 0;
        Console.Write("Informe o valor: ");
        valor = Convert.ToSingle(Console.ReadLine());
        valordespesas.Add(valor);
        Console.WriteLine("Informe uma descrição:");
        descricao = (Console.ReadLine());
        descricaodespesas.Add(descricao);
        foreach (float som in valordespesas)
        {
            somadesp += valor;
        }
        totdesp = somadesp;
    }
}

Comment: Veja: [Como e por que aceitar uma resposta?](https://pt.meta.stackoverflow.com/a/1079/3117)
Comment: Leia isto: https://pt.stackoverflow.com/q/219211/101
Answer: O erro é que você está percorrendo corretamente o valordespesas mas sempre soma o mesmo valor; você precisa adicionar som, não valor:
foreach (float som in valordespesas)
{
    somadesp += som;
}

Comment: Vlw Amigo, resolveu o problema aqui. :)
Comment: @GuilhermeSchubertMedeiros, se a resposta tá correta, marca como aceita ;)
Answer: Outra opção é nem usar o foreach() e sim o metodo Sum()
totdesp = valordespesas.Sum();


Absolute position in a single dimension

Question: Is there a way to absolute position a view using position() in a single axis?
For example, I want to absolute position an element's x position but leave the y position as default.
Answer: Yes. Use <code>.padding(.leading, 100)</code>. This will make the view have a 100 point gap on the left, but keep the Y position default.

Absolute position in a single dimension


Listening to outgoing sms not working android

Question: I am trying to listen to outgoing sms messages. I was following the accepted answer here but it is not working. I'm not sure where I am going wrong. I am no familiar at all with Content Observers so forgive my ignorance.
I wanted to create it in a service so it would be running all the time. here is my code in that service:
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class SmsOutgoingObserver extends Service {
    public SmsOutgoingObserver() {
    }
    /* this method handles a single incoming request */
    @Override
    public int onStartCommand(Intent intent, int flags, int id) {

        Log.d("OUTGOING", "RUNNING SERVICE");

        return START_STICKY; // stay running
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null; // disable binding
    }

    public class SmsObserver extends ContentObserver {

        public SmsObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);

            Uri uriSMSURI = Uri.parse("content://sms/out");
            Cursor cr = SmsOutgoingObserver.this.getContentResolver().query(uriSMSURI, null, null, null, null);

            cr.moveToNext();
            String address = cur.getString(cr.getColumnIndex("body"));

            Log.d("OUTGOING", address);

            cr.close();

            //Database.messageReceived(SmsOutgoingObserver.this, address);
        }
    }
}

What am I doing wrong?
Answer: In addition to the silly mistake on my part that @CommonsWare pointed out, me missing
@Override
public void onCreate() {
    super.onCreate();

    ContentResolver contentResolver = this.getContentResolver();
    contentResolver.registerContentObserver(Uri.parse("content://sms/out"),true, new SmsObserver(new Handler()));
}

the other issue was actually in these two lines
contentResolver.registerContentObserver(Uri.parse("content://sms/out"),true, new SmsObserver(new Handler()));

and
Uri uriSMSURI = Uri.parse("content://sms/out");

where I changed the content://sms/out to content://sms and then proceeded to check for the type to make sure the change I was getting was actually an outgoing message. I also had to make sure to check for multiple calls like so:
if (cr.getInt(cr.getColumnIndex("type")) == 2) {
    if(id != cr.getInt(cr.getColumnIndex(cr.getColumnName(0)))) {
        id = cr.getInt(cr.getColumnIndex(cr.getColumnName(0)));

        String address = cr.getString(cr.getColumnIndex("address"));
        Database.messageSent(SmsOutgoingObserver.this, address);
            Log.d("OUTGOING", address);
        } else {
            Log.d("OUTGOING", "MESSAGE ALREADY LOGGED");
        }
     };
}

and simply defined private int id = 0; as a global variable
Answer: Your SmsOutgoingObserver does nothing other than log a message to LogCat. If you want to use SmsObserver, you need to add some code, such as call registerContentObserver(). This is shown in the accepted answer on the question that you linked to.
Comment: I had it in there before I must have erased it accidentally and not realized it I will give it a shot
Comment: @SantiGallego: Having that code in `onCreate()` should work. Note that SMSes do not have to be written to that `ContentProvider`, and that many users may be very irritated with you for trying to have a service run continuously. Google has also hinted that this sort of service may be eliminated in the future. On Android 7.0+, you can use `JobScheduler` to monitor a `ContentProvider` without having to have a service run continuously -- see [this sample app](https://github.com/commonsguy/cw-omnibus/tree/master/JobScheduler) that monitors `ContactsContract`.


how to replace a string with another string only on the last word of each line

Question: I want to replace the 'UN' in the last word of each line with 'LK'.
Input file :
Y'UN 310R 07MAR DAUNEN UN2
Y'UN 720R 07MAR DENSUN HK2
Y'UN 721R 14MAR UNDDEN HK2
Y'UN1692R 14MAR DEUNAY UN2

Output needed :
Y'UN 310R 07MAR DAUNEN LK2
Y'UN 720R 07MAR DENSUN HK2
Y'UN 721R 14MAR UNDDEN HK2
Y'UN1692R 14MAR DEUNAY LK2

Comment: Are those blank lines present in your input, or were you just trying to separate each line of your data? Have you tried anything? This is very simple stuff.
Comment: Will the last UN always have number(s) too?
Comment: There is no empty lines between the data. Yes the UN always have a number with it
Answer: With awk:
awk '{sub(/UN/, "LK", $NF)}1' File

In the last field in each line ($NF), replace pattern UN (/UN/) with string LK ("LK"). Print the unaffected lines as well (1).
Output:
Y'UN 310R 07MAR DAUNEN LK2

Y'UN 720R 07MAR DENSUN HK2

Y'UN 721R 14MAR UNDDEN HK2

Y'UN1692R 14MAR DEUNAY LK2

Comment: Your choice of syntax means that the output of sub is being interpreted as a string then concatenated with a string `"1"`, so it does what you want but in quite a weird way. I'd recommend `awk '{ sub(/UN/, "LK", $NF) }1'` or even just write the `print` statement explicitly.
Comment: @TomFenech is 100% correct. We actually had a discussion about this on comp.lang.awk about 15 years ago and all agreed that the syntax shown here should never be used even though it's slightly briefer than doing it the clearer way with the action (`sub()`) in an action block and condition (`1`) in the condition section.
Comment: Oops...thanks guys for pointing that out... actually this was not what i actually wanted and missed the brackets because of the correct output..
Answer: The key here is using the 'end of line' anchor - $
sed -e 's/UN\([A-Z0-9]*\)$/LK\1/'

Comment: @DheebanChakkaravarthy it is replaced with matched content from the first pair of `()`, basic regular expression stuff


Receiving and Processing a multi dimensional array

Question: I have asked this question twice, with no satisfactory answer, that is, the problem I faced two questions ago still remains and none the wiser as how I am going to proceed with this.
This time I will provide all the code and what I receive, plus where the problem is occurring, I know what the issue is but since I'm relatively new to using AJAX it has me puzzled.
I have a form, which when you click the second to last field, duplicates itself, with the help of another user all the id's get changed to be unique.
<form role="form" class="batchinvoice form-horizontal" id="batchinvoice">

                                    <select class="form-control" name="sl_propid" >
                                        <?php foreach($property as $row) :?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo $row[ 'property_name'] . " " . $row[ 'property_address1']; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>

                                    <input type="text" name="sl_date" placeholder="Date" class="sl_date form-control" id="datepicker">

                                    <input type="text" name="sl_ref" placeholder="Invoice Reference" class="form-control" id="sl_ref">

                                    <select class="form-control" name="sl_nom_id" id="sl_nom_id">
                                        <?php foreach($subitem_nominals as $row) :?>
                                        <option value="<?php echo $row['subnom_id']; ?>">
                                            <?php echo $row[ 'nom_subitem_name']; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>

                                    <input type="text" name="sl_desc" id="sl_desc" placeholder="Invoice Description" class="form-control">

                                    <input type="text" name="sl_vat" placeholder="VAT Amount" class="vat form-control" id="vat">

                                    <input type="text" name="sl_net" placeholder="Net" class="form-control" id="sl_net">

                        </form>

The JS for the form clone

This is the particular controller function in CodeIgniter, Note I have tried multiple things.
function addInvoiceToLedger(){
    // $this->load->model('SalesLedgerModel');
    // $propid = $this->input->post('propid');
    // print_r($this->input->post());
    // $date = $this->input->post('date');
    // $ref = $this->input->post('ref');
    // $nomid = $this->input->post('id');
    // $desc = $this->input->post('desc');
    // $vat = $this->input->post('vat');
    // $net = $this->input->post('net');

    $res = $this->input->post(NULL, TRUE);

    //problem is probably here, it's

    //for($x = 0; $x < count($res); $x++){

    foreach($res as $row){

    $this->SalesLedgerModel->addInvoiceToLedger($row.propid, $row.date, $row.ref, $row.nomid, $row.desc, $row.vat, $row.net);

    }
    //}

    //redirect('home/financial_input/');
}

the Model Function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){

    $data = array('sl_prop_id' => $propid, 'sl_date' => $date,
        'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);

    $this->db->insert_batch('salesledger', $data);
}

Which all have the relevant field data for each form inside them.
My question is how do I receive and handle the array? Every loop I've tried doesn't work, I've tried getting variables singularly(as you can see above commented out) but that doesn't make sense (or work) because in the $.ajax data it is set to res, but $this->input->post('res') doesn't return anything nor does $this->input->post(NULL, TRUE)
Majorly stuck, I feel this should be a simple thing, but I clearly don't understand it.
Edit, still same problem can't find an answer anywhere D:, tried many things.
Still the same problem "res" is sent as post, but I can't retrieve it in the controller with $this->input->post()...anyone?
Answer: I only wanted to submit a comment but apparently I need 50 rep for that so I'll take my chances with an answer.
In your $.ajax block what if you change the data section to this:
$.ajax({
    type: 'POST',
    url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
    data: { res : res },
    sucess: function (e) {
        alert(e);
    },
    error: function (e) {
        alert(e.toString());
    }
});

Comment: That's what it should be but, it isn't let me check if that's the issue, if that fixes it, I'll first thank you then go punch myself haha.
Comment: It's still returning invalid argument in the foreachloop, aka res isn't set to anything.


Population equation in ODE and PDE looks and solutions

Question: In one of the Differential equation book says the following:
The  ODE population equation is $dp/dt = p$....(1)
and the general solution of the above cited equations is: $p(t) = ce^t$. ...(2)
Solving of (1) is nothing but integration. But, after integrating the (1), I dint get (2). How (2) is solution of (1). I am wrong or text book wrong?
Also, the PDE of population equation look like $u_t$= $u$ ....(3), where $u$ is in $x$ and $t$. Now as per the same text book, the general solution of (3) is $u_(x,t)$ $= F(x) e^t$. ...(4).
In (4), where we got F(x) and prove it (4) is solution of (3) as well as (2) is solution of (1).
Regards.
Comment: What?  Just take the derivative and you see 2 has to be true.  Do the same thing for 3,4.
Answer: You can do a little deduction to get (2) from (1).
\begin{equation}
\begin{array}{l}
\frac{dp}{dt}=p\\
\frac{dp}{p}=dt\\
\mbox{By integrating for each sides:}\\
\int\frac{dp}{p}=\int dt\\
\ln p=t+C\quad \mbox{where $C$ is a constant to be determined}\\
p=e^Ce^t\\
p=C_0e^t\quad\mbox{where $C_0=e^C$ is also a constant}
\end{array}
\end{equation}
You can get (4) from (3) by the same method but you should view $x$ as a constant when you do the analysis (say, integral) in $t$.
For the sake of simplicity, I use a alternative method, say integral factor, to solve (3). Note the integral factor of (3) is $e^{-t}$. By multiplying the factor on each sides of (3), we have
\begin{equation}
\frac{\partial u}{\partial t}e^{-t}-u e^{-t}=0\\
\frac{\partial}{\partial t}(e^{-t}u)=0\\
\end{equation}
Integrate each side of above equation in $t$, and note u is function of both $x$ and $t$, we have:
\begin{equation}
\int \frac{\partial}{\partial t}(e^{-t}u) dt=\int 0 dt\\
e^{-t}u=F(x)\quad\mbox{(*)}\\
u=F(x)e^t
\end{equation}
where $F(x)$ is a function to be determined. I should point out that $F(x)$ appear in (*) because $u$ is a function of both $x$ and $t$. So when we integrate the both side of equation in $t$, there must have a function of $x$ instead of a constant. (In the case of ODE, such as the previous example, there is a constant $C$ after indefinite integral.) In other word, if we compute derivative of (*) on each sides in $t$, we can get the original equation. That is,
\begin{equation}
\frac{\partial}{\partial t} e^{-t} u=\frac{\partial}{\partial t} F(x)\\
\frac{\partial u}{\partial t}e^{-t}-u e^{-t}=0\\
\frac{\partial u}{\partial t}=u\\
\end{equation}
The derivative of $F(x)$ in $t$ is zero because it is a function of $x$ and independent of $t$.
Comment: ! I dint get (4) from (3) as this is not like ODE. Can you do this. Please
Comment: @how we will get F(x) in solution. Please show me, getting (4) from (3).
Comment: I am so sorry that I have just received your comments. I have rewrite my answer for your new question.
Comment: Lion! you are really lion in Mathematics. I am so thankful to your wonderful explanation. There is no words to describe your help. Many many thanks. I have some small doubt, how to get or obtain Integral factors? is there any common formula to find integral factor of any function?
Comment: Indeed, there are a lot of formulas to find integral factor. And it is depend on construction of equation. But I do not remember them exactly. You can find them in references about ODE. BTW, although there are many formulas to find them, I usually compute them by intuition, say to add or time some items and then use formula such as multiplication derivative etc.. It is more convenient than using formulas in most time.
Comment: ! well, in your solution, please find derivative of (*) and show me the original equation. Please see the (*) in your solution please.
Comment: I have add it in my answer.
Comment: ! thank you and bye bye