text:
Q: Can Angular Routing be used if single page application is changed so that 2 routes can be both visible w splitted view? I have an example application created by VS2017 Angular template that is a single page app with 3 routes defined in app.module.ts
RouterModule.forRoot([
  { path: '', component: HomeComponent, pathMatch: 'full' },
  { path: 'counter', component: CounterComponent },
  { path: 'fetch-data', component: FetchDataComponent },
])

and in app.component.html

  <app-nav-menu></app-nav-menu>

    <router-outlet></router-outlet>

where navigation is defiend in nav-menu.component.html

      my_new_app
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-label="Toggle navigation"
        [attr.aria-expanded]="isExpanded" (click)="toggle()">

      </button>

            Home

            Counter

            Fetch data

The normal situation with Counter selected would look like this (if the navigation was on the side):
Home        | Counter |
Counter (x) |         |
Fetch       |         |

In some cases I would need to have 2 "main level" components visible so that instead of having area in router outlet for 1 compponent the area would be splitted in 2 and 2 routes would be active somehow.
Home        | Counter | Fetch |
Counter (x) |         |       |
Fetch   (x) |         |       |

Can or should this be done with angular routing?
The normal use would still be that only 1 route is active and the router-outlet area is not splitted.
This can be done e.g using ngIf and have (toggle)buttons instead of routerlinks. However I'm developing a very large application and I'm interested in using routes if possible.
The linked "duplicate" is about second router outlet and has nothing to do with this. Here what I'm trying to achieve is main router outlet having 2 routes active at same time and content is splitted. This is probably not possible, but that's the idea, not some sidebar secondary navigation.

A: One option I tried is to have 3 split-areas where 1 of them has a router-outlet. The other 2 have counter and fetch-data components as their content. When used as single page app only the 1st split area is visible.
app.component.html

  <app-nav-menu></app-nav-menu>

  <as-split direction="horizontal">
    <as-split-area>
      <router-outlet></router-outlet>
    </as-split-area>
    <as-split-area *ngIf="secondSplitAreaVisible">
      <app-counter-component></app-counter-component>
    </as-split-area>
    <as-split-area *ngIf="thirdSplitAreaVisible">
      <app-fetch-data></app-fetch-data>
    </as-split-area>
  </as-split>

The other 2 can be set visible with a checkbox in the navigation component that looks like below. Note that in my case it must be controlled that the component can be visible only once in GUI. This is done by using auth guards for routes and disabling the checkboxes mentioned above to prevent showing a aplit area for a component that is already visible in router-outlet.
nav-menu.component.html:

      my_new_app
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-label="Toggle navigation"
              [attr.aria-expanded]="isExpanded" (click)="toggle()">

      </button>

              <mat-checkbox [(ngModel)]="firstChecked" (change)="toggleTab('home')" [disabled]="firstDisabled"></mat-checkbox>Home

            <mat-checkbox [(ngModel)]="secondChecked" (change)="toggleTab('counter', secondChecked)" [disabled]="secondActive"></mat-checkbox>Counter

            <mat-checkbox [(ngModel)]="thirdChecked" (change)="toggleTab('fetch-data', thirdChecked)" [disabled]="thirdActive"></mat-checkbox>Fetch data

app.module.ts route definitions
RouterModule.forRoot([
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
  { path: 'counter', component: CounterComponent, canActivate: [AuthGuard] },
  { path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthGuard]},
  { path: '', redirectTo: '/home', pathMatch: 'full' }

and the auth guard:
@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  subscription;
  outletUrl: string;
  secondSplitAreaVisible: boolean = false;
  thirdSplitAreaVisible: boolean = false;

  constructor(
    private router: Router,
    private ngRedux: NgRedux<IAppState>,
    private actions: TabActions) {
      this.subscription = ngRedux.select<string>('outletUrl')
        .subscribe(newUrl => this.outletUrl = newUrl);    // <- New
        this.subscription = ngRedux.select<boolean>('secondOpen') // <- New
        .subscribe(newSecondVisible => this.secondSplitAreaVisible = newSecondVisible);    // <- New
        this.subscription = ngRedux.select<boolean>('thirdOpen') // <- New
        .subscribe(newThirdVisible => this.thirdSplitAreaVisible = newThirdVisible);    // <- New
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (state.url === '/counter' && this.secondSplitAreaVisible) {
      return false;
    }
    if (state.url === '/fetch-data' && this.thirdSplitAreaVisible) {
      return false;
    }
    return true;
  }
}

Above uses redux to manage state changes. That part is also below just in case someone is interested:
nav-menu.component.ts
@Component({
  selector: 'app-nav-menu',
  templateUrl: './nav-menu.component.html',
  styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent {
  firstChecked: boolean = false;
  secondChecked: boolean = false;
  thirdChecked: boolean = false;

  firstDisabled: boolean = true;
  secondActive: boolean = false;
  thirdActive: boolean = false;

  constructor(
    private ngRedux: NgRedux<IAppState>,
    private actions: TabActions,
    private router: Router) {
    router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.ngRedux.dispatch(this.actions.setOutletActiveRoute(event.url));
        if (event.url.includes('counter')) {
          this.secondActive = true;
          this.thirdActive = false;
          this.firstChecked = false;
        }
        else if (event.url.includes('fetch')) {
          this.thirdActive = true;
          this.secondActive = false;
          this.firstChecked = false;
        }
        else {
          // home
          this.secondActive = false;
          this.thirdActive = false;
          this.firstChecked = true;
        }
      }
    });
  }

  isExpanded = false;

  collapse() {
    this.isExpanded = false;
  }

  toggle() {
    this.isExpanded = !this.isExpanded;
  }

  toggleTab(name: string, isChecked : boolean) {
    this.ngRedux.dispatch(this.actions.toggleSplitArea({ splitArea : name, isVisible: isChecked}));
  }
}

app.component.ts
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy {
  title = 'app';
  secondSplitAreaVisible: boolean = false;
  thirdSplitAreaVisible: boolean = false;

  subscription;

  constructor(
    private ngRedux: NgRedux<IAppState>,
    private actions: TabActions) {
      this.subscription = ngRedux.select<boolean>('secondOpen')
        .subscribe(newSecondVisible => {
          this.secondSplitAreaVisible = newSecondVisible;
        });
        this.subscription = ngRedux.select<boolean>('thirdOpen')
        .subscribe(newThirdVisible => {
          this.thirdSplitAreaVisible = newThirdVisible;
        });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

app.actions.ts
@Injectable()
export class TabActions {
  static TOGGLE_SPLIT_AREA = 'TOGGLE_SPLIT_AREA';
  static SET_OUTLET_ACTIVE_ROUTE = 'SET_OUTLET_ACTIVE_ROUTE';

  toggleSplitArea(splitAreaToggle: SplitAreaToggle): SplitAreaToggleAction {
    return {
        type: TabActions.TOGGLE_SPLIT_AREA,
        splitAreaToggle
    };
  }

  setOutletActiveRoute(url: string) : SetOutletActiveRouteAction {
    return {
        type: TabActions.SET_OUTLET_ACTIVE_ROUTE,
        url
    };
  }
}

store.ts
export interface IAppState {
    outletUrl : string;
    secondOpen : boolean;
    thirdOpen : boolean;
};

export const INITIAL_STATE: IAppState = {
    outletUrl: 'home',
    secondOpen : false,
    thirdOpen : false
};

export function rootReducer(lastState: IAppState, action: Action): IAppState {
    switch(action.type) {
        case TabActions.SET_OUTLET_ACTIVE_ROUTE: {
            const setRouteAction = action as SetOutletActiveRouteAction;
            const newState: IAppState = {
                ...lastState,
                outletUrl: setRouteAction.url
            }
            return newState;
        }
        case TabActions.TOGGLE_SPLIT_AREA: {
            const splitToggleAction = action as SplitAreaToggleAction;
            console.log('rootreducer splitareatoggle:' + splitToggleAction.splitAreaToggle.splitArea);
            if (splitToggleAction.splitAreaToggle.splitArea === 'counter') {
                const newState: IAppState = {
                    ...lastState,
                    secondOpen: splitToggleAction.splitAreaToggle.isVisible
                }
                return newState;
            }
            else {
                const newState: IAppState = {
                    ...lastState,
                    thirdOpen: splitToggleAction.splitAreaToggle.isVisible
                }
                return newState;
            }
        }
        default : {
            return lastState;
        }
    }
}


text:
Q: Is intuitionistic first-order logic with no function or relation symbols decidable? Classical first-order logic with no function or relation symbols is decidable.  If I'm not mistaken, this is essentially because any formula (with possible free variables) has truth value uniquely determined by the partition of its free variables into "equality classes" and by the "cardinality of the model" - and furthermore, for any given partition, the answer is stable for large enough cardinality starting at some finite cardinality.  So, you can write a decision procedure which recursively evaluates the set of partitions and cardinalities for which each subformula is true (which is finitely representable due to the stability condition).  Then, at the end, satisfiability or tautology should be easy to read off from the result.
I recently found myself wondering whether the same thing would be true for intuitionistic first-order logic with no function or relation symbols.  The above argument would certainly need some heavy-duty refinements if it were to work in this case, if it is salvageable at all.  For example, the "partitions" above would need to become much more complicated objects, since there is essentially no restriction on the equality relations between free variables other than that they need to form an equivalence relation.  (e.g. in a topos with subobject classifier $\Omega$, for any global section $p \in \Omega(1)$, we can form the quotient of $\{ 0, 1 \}$ by the equivalence relation $\{ (0, 0)_\top, (1, 1)_\top, (0, 1)_p, (1, 0)_p \}$ to get an object of the topos with two global sections $\bar 0$ and $\bar 1$ such that $\bar 0 = \bar 1$ is equivalent to $p$.)  Similarly, in a topos, the notion of "cardinality" of the space would have to be much more involved to be of much use in classification.
Nonetheless, given that intuitionistic propositional logic is decidable, it doesn't seem completely beyond hope that maybe some sort of quantifier elimination could hold and reduce each subformula to some combination of propositions in terms of $v_i = v_j$ and some "cardinality like" conditions.
Or possibly, some mild extension of propositional sequent calculus might be able to resolve questions in this language, and still satisfy the cut elimination theorem in such a way that an automated proof search procedure can be shown to terminate in all cases.  Along this line of thinking, the main addition to sequent calculus would probably be something like: given the problem $\Gamma, v_i = v_j \vdash \phi$, reduce the number of free variables by one and substitute $v_i$ in place of $v_j$ in both $\Gamma$ and $\phi$; if this $\Gamma[v_j := v_i] \vdash \phi[v_j := v_i]$ is provable, then $\Gamma, v_i = v_j \vdash \phi$ is provable.  And then of course, the introduction rule $v_i = v_i$; and similarly for the $\forall$ and $\exists$ intro/elimination rules, we require in the elimination rules that the proposition being eliminated is directly in the context.  This approach seems more promising, though I haven't thought too much about the details.
Just as very wild speculation for what a proof of the negative answer could potentially look like: for all I know, maybe given an instance of the group word problem, it might be possible to translate that into evaluation of tautology of some first-order sentence which is a tautology if and only if the topos of $G$-sets satisfies that sentence, if and only if that instance of the group word problem is true.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How are arrays stored in Virtual Memory? If you have an array
int arr[100];

How exactly is this stored in a modern machine, which obviously runs using virtual memory?
I understand we have to use paging with virtual memory and since an array is a contiguous block, if we have a 4kb page, this array arr will fit into 1 page.
But then is this page stored on DISK or RAM?

A: In summary, the data may be in various locations, where it is may change automatically (by actions of the operating system), and, when working within normal programs, you generally do not need to know about it.
First, the fact that you declare an array in source code does not necessarily mean the full array, or any array at all, is created in memory. A compiler may optimize the source code in ways that eliminate part or all of the array.
However, let us suppose the array is actual created. Virtual memory is created to present an illusion that a process has exclusive use of physical memory and/or that it has more memory than is actually available as physical memory. A purpose of this illusion is that processes should not have to be concerned about where their data actually is. And the vast majority of normal processes can neglect that.
Also, for the most part, compilers will pay little attention to where small objects are placed relative to page boundaries. It usually will make little difference whether an array of 100 int is placed so that it is entirely within one page or that it spans a page boundary.
When it is necessary to know or influence where the data actually is, a number of issues come into play.
There are ways to affect the location of data relative to page boundaries, either by using system or library calls for that purpose or by allocating excess memory and then putting the data at a chosen location within it.
If data is important and is preferred or required to remain in physical memory, there may be system calls (depending on the system, of course) to request that.
In the absence of such specific requests, where data is located depends on a number of factors. If you declare a static array of int and initialize it with compile-time data, the data may appear in a section of the executable file that is ultimately generated. In some systems, when an executable file is started, the system does not load the entire file into memory. It loads various portions of data from the executable file only when they are referenced. Thus, this data may initially reside on disk. After it is loaded into memory, if the system is burdened with other things that need memory, the system may discard this data from memory, so that it again exists only in the executable file on disk.
On the other hand, if the data is generated during program execution, it is of course in memory when the program generates it. Again, though, if the system is burdened with other demands, the system may remove the data from memory. In this case, since the data does not already exist on disk (as the data in the executable file did), the data is first written to a page or swap file on disk.
Generally, where the data is may change over time.

A:
I understand we have to use paging with virtual memory.

You don't have to using paging. You can turn paging off.

If we have a 4kb page, this array arr will fit into 1 page.

It may fit in a 4kb page, but it's very likely not going be aligned on (or near) a 4kb boundary, so in reality, it'll probably be stored across two pages.

Is this page stored on DISK or RAM?

Arrays are no different from other data structures. They are stored in memory (RAM), unless swapped out to DISK by the OS, if it is running low on memory.


text:
Q: python : open commad as administrator execute a command to stop a service I am trying to open a cmd prompt to "run as administrator", in order to stop a service using net stop.
however nothing seems to be working, i have tried the following,
import os
import subprocess

subprocess.Popen(['runas', '/user:Administrator', '', 'cmd.exe', 'net stop "Cisco AnyConnect Secure Mobility Agent"'])

please can someone help with this

A: I anticipate that runas is a command that is built into the console rather than its own executable and as such requires the shell=True parameter.
But I'm not in a situation to try this myself at the moment.
Keep in mind that this can be a security hazard with untrusted input. Use with caution. But hopefully you are already doing that when trying to run as admin :).


text:
Q: Use jQuery or Q.Js for promises I'm looking into BreezeJs and there samples are using Q.js for promises to handle asynchronous calls. John Papa is also using Q. JQuery has promises as well. What are the differences between the two?

A: Both are based on the Promises/A standard and implement a then method (though only current jQuery, they once had a incompatible pipe instead of then). However, there are a few differences:

*

*Q has exception handling. All thrown errors in the async then callbacks will be caught and reject the promise (and will only get re-thrown if you call .end()). Not sure whether I personally like that. It's the standardized way which jQuery does not follow, rejecting from then in jQuery deferreds is much more complicated.

*Q promises are resolved with a single value/reason (like you return/throw it from then), while jQuery allows multiple arguments in resolve/reject calls on its Deferreds.

*Q has lots of Proxy methods which will allow you to modifiy future values

*Q has .all and similiar, which are more complicated with jQuery ($.when.apply($, […])).

*Q does explicitly work with ticks in the event loop and guarantees asynchronity, while jQuery can be synchronous as well. This is now required by the Promises A/+ specification.

… which is basically Promises/B. As you can see, the Q API is more powerful, and (imho) better designed. Depending on what you want to do, Q could be the better choice, but maybe jQuery (especially if already included) is enough.

A: JQuery's promise implementation of the Promises/A spec has some real issues.  The following link describes them far better than I can: missing-the-point-of-promises

A: Bergi's answer covers things fairly well. I wanted to add, though, that we've created a guide for Q users coming from jQuery. To summarize the relevant sections:

*

*Q handles exceptions, allowing you to handle all errors through a uniform interface.

*Q focuses on chaining with all its methods, whereas jQuery only allows chaining from then/pipe.

*Q promises guarantee asynchronicity, thus avoiding the control flow hazards and race conditions that result from jQuery's sometimes-sync, sometimes-async behavior.

*Q promises are always fulfilled with a single value or rejected with a single reason, just like synchronous functions always either return a single value or throw a single exception.

*Q enforces a separation between the deferred and the promise, whereas jQuery merges them into one object with the option of separating them.

*Q does not track a context object along with the fulfillment or rejection, since this has no parallel for synchronous functions (i.e., you never return a value as well as a this in which the caller must run). So there is no resolveWith or rejectWith.

*Q uses Promises/A+ terminology; the main difference is that Q uses "fulfilled" where jQuery uses "resolved," and in Q "resolved" means something more subtle.

The guide also contains a table paralleling jQuery and Q promise APIs.


text:
Q: Shredding Nested JSON in snowflake We have scenario to Shred the below JSON (records & array) in a variant column to a relational views and we are able to achieve (shown below - 3 Views).
However if we want to stich/join all three records we don't have any keys to join, do we have any function/ways in snowflake to add keys  dynamically when we shred the view like fk/pk ids.

A: One of the ways to do this is, create a hash key from names and add it to the other tables. (Borrowed hash key concept from Data Vault)
Your views would look like
EMP_REC
EMP_KEY (Hash key of FName + LName using MD5 or similar)
FNAME
LNAME

ADDRESS
EMP_KEY
FLATE
ST

SEMESTER_MARKS
EMP_KEY
MATHS
SCIENCE


text:
Q: How to combine/merge observables into a single observable and associate result with the input? I have a saveForm() function which is expected to perform below operations in order:

*

*Take form data and add it to FireStore collection as a document.

*On success, loop through(attachmentsFormArray) all the files the user has selected and upload each file to FireStorage.

*When all files are uploaded completely, assign the documentUrl of each file to the corresponding file map on the FireStore document we saved in step #1. Then make api call to actually save the updated firestore document.

Below is my saveForm() function:
saveForm() {
    let fixedDepositEntity = this.getEntityFromForm();
    this.fixedDepositsFirestoreCollection.add(fixedDepositEntity).then(documentRef => {
        if (this.attachmentsFormArray.controls.length !== 0) {
            this.attachmentsFormArray.controls.forEach(group => {

                let fileRef = this.fireStorage.ref(this.fixedDepositsStorageFolderPath + group.get('fileName').value);
                let uploadTask = fileRef.put(group.get('file').value);

                // observe percentage changes
                uploadTask.percentageChanges().subscribe(percent => {
                    group.get('percentComplete').setValue(Math.round(percent));
                });
                // get notified when the download URL is available
                uploadTask.snapshotChanges().pipe(
                    finalize(() => {
                        fileRef.getDownloadURL().subscribe(url => {
                            group.get('downloadUrl').setValue(url);
                        });
                    }))
                    .subscribe();
            });
        }
    });
}

Currently, the above code simply loops through the attachmentsFormArray and once the file is uploaded, finally it assigns the downloadUrl to the attachmentsFormArray.
When the user selects the multiple file, I have the below handleFileInput() event handler:
handleFileInput(files: FileList) {
    if (!files || files.length === 0) {
        return;
    }
    Array.from(files).forEach(file => {
        this.attachmentsFormArray.push(this.formBuilder.group({
            fileName: [file.name],
            fileSize: [file.size],
            label: [''],
            file: [file],
            downloadUrl: [''],
            percentComplete: [''],
            uploadTaskState: ['']

        }));
    });

The AngularFire library provides a snapshotChanges() method which returns Observable<UploadTaskSnapshot>. I would want to combine/merge all these Observables (so that know once all files are completely uploaded) and then subscribe the resultant Observable. But I am not sure how to associate the individual observable result with corresponding file object that the user selected (as described in #3).
I know we can achieve this behavior with RxJs operators, but not sure which one to use in my scenario. Any help is appreciated in advance.

EDIT 1: Implemented as per "Mrk Sef's" answer. It works fine most of the times. However, once in a while the downloadUrl is not set. I'm unable to understand the reason for this intermittent issue.
saveForm() {
    try {
        this.fixedDepositsFormGroup.disable();
        let fixedDepositEntity = this.getEntityFromForm();
        this.fixedDepositsFirestoreCollection
            .add(fixedDepositEntity)
            .then(documentRef => {
                this.isBusy = true;
                // Changes will be mapped to an array of Observable, once this mapping
                // is complete, we can subscribe and wait for them to finish
                console.log('Voila! Form Submitted.');
                if (this.attachmentsFormArray.controls.length !== 0) {
                    const changes = this.attachmentsFormArray.controls.map(
                        group => {
                            const fileRef = this.fireStorage.ref(this.fixedDepositsStorageFolderPath + group.get('fileName').value);
                            const uploadTask = fileRef.put(group.get('file').value);

                            const percentageChanges$ = uploadTask.percentageChanges().pipe(
                                tap(percent => group.get('percentComplete').setValue(Math.round(percent)))
                            );
                            const snapshotChanges$ = uploadTask.snapshotChanges().pipe(
                                finalize(() => fileRef.getDownloadURL().subscribe(url => group.get('downloadUrl').setValue(url)))
                            );
                            return [percentageChanges$, snapshotChanges$];
                        }
                    ).reduce((acc, val) => acc.concat(val), []);; // Turn our array of tuples into an array

                    // forkJoin doesn't emit until all source Observables complete
                    forkJoin(changes).subscribe(_ => {
                        // By now all files have been uploaded to FireStorage
                        // Now we update the attachments property in our fixed-deposit document
                        const attachmentValues = (this.getControlValue('attachments') as any[])
                            .map(item => <Attachment>{
                                fileName: item.fileName,
                                fileSize: item.fileSize,
                                label: item.label,
                                downloadUrl: item.downloadUrl
                            });
                        documentRef.update({ attachments: attachmentValues });
                        console.log("Files Uploaded Successfully and Document Updated !");
                    });
                }
            })
            .finally(() => {
                this.fixedDepositsFormGroup.enable();
                this.isBusy = false;
            });
    } finally {

    }
}

A: A common design you see when observable are generated by a third party is to tag it with some custom information that you know at call-time but may not know when you're subscribed.
For example, get the third word of each document whose title starts with 'M':
const documents: Document[] = getDocumentsService();

wordStreams: Observable<[Document, HttpResponse]>[] = documents
  .filter(file => file.title.charAt(0) === 'M')
  .map(file => getThirdWordService(file.id).pipe(
    map(serviceResponse => ([file, serviceResponse]))
  );

merge(...wordStreams).subscribe(([file, serviceResponse]) => {
  console.log(`The third word of ${file.title} is ${serviceResponse.value}`)
});

The big takeaway is that by mapping a value into a tuple or an object (The same pattern works objects, maps, ect) you can carry that information forward through the operations in a stream.
The only problem is that if you're not careful, you may end up with a stream that isn't purely functional (can cause side effects to your program state).

I'm not really sure what your example is doing, but here's my best guess at what you want:
saveForm() {
  let fixedDepositEntity = this.getEntityFromForm();
  this.fixedDepositsFirestoreCollection
    .add(fixedDepositEntity)
    .then(documentRef => {
      // Changes will be mapped to an array of Observable, once this mapping
      // is complete, we can subscribe and wait for them to finish
      const changes = this.attachmentsFormArray.controls.map(
        group => {
          const fileRef = this.fireStorage.ref(this.fixedDepositsStorageFolderPath + group.get('fileName').value);
          const uploadTask = fileRef.put(group.get('file').value);

          const percentageChanges$ = uploadTask.percentageChanges().pipe(
              tap(percent => group.get('percentComplete').setValue(Math.round(percent)))
          );
          const snapshotChanges$ = uploadTask.snapshotChanges().pipe(
            mergeMap(_ => fileRef.getDownloadURL()),
            tap(url => group.get('downloadUrl').setValue(url))
          );
          return [percentageChanges$, snapshotChanges$];
        }
      ).flat(); // Turn our array of tuples into an array

      // forkJoin doesn't emit until all source Observables complete
      forkJoin(changes).subscribe(_ =>
        console.log("All changes are complete")
      );
    });
}

If instead, you want to delay writing values out until your subscribe, here's another option that more clearly tags the observable stream with some added data that gets used later:
saveForm() {
  let fixedDepositEntity = this.getEntityFromForm();
  this.fixedDepositsFirestoreCollection
    .add(fixedDepositEntity)
    .then(documentRef => {
      // Changes will be mapped to an array of Observable, once this mapping
      // is complete, we can subscribe and wait for them to finish
      const changes = this.attachmentsFormArray.controls.map(
        group => {
          const fileRef = this.fireStorage.ref(this.fixedDepositsStorageFolderPath + group.get('fileName').value);
          const uploadTask = fileRef.put(group.get('file').value);

          const percentageChanges$ = uploadTask.percentageChanges().pipe(
              map(percent => ([group, percent]))
          );
          const snapshotChanges$ = uploadTask.snapshotChanges().pipe(
            mergeMap(_ => fileRef.getDownloadURL()),
            map(url => ([group, url]))
          );
          return [percentageChanges$, snapshotChanges$];
        }
      );

      const percentageChanges$ = changes.map(([a, b]) => a);
      const snapshotChanges$ = changes.map(([a, b]) => b);

      merge(...percentageChanges$).subscribe({
        next: ([group, percent]) => group.get('percentComplete').setValue(Math.round(percent)),
        complete: _ => console.log("All percentageChanges complete")
      });

      merge(...snapshotChanges$).subscribe({
        next: ([group, url]) => group.get('downloadUrl').setValue(url),
        complete: _ => console.log("All snapshotChanges complete")
      });
    });
}

It goes without saying that none of this is tested. It's my hope you can use what's described here to retool your solution to include files or whatever other information you find pertinent.

update
My solution created a stream called
const snapshotChanges$ = uploadTask.snapshotChanges().pipe(
  mergeMap(_ => fileRef.getDownloadURL()),
  tap(url => group.get('downloadUrl').setValue(url))
);

Which wasn't really what you were after, you wanted a stream that only starts after uploadTask.snapshotChanges() completes. Finalize is strange in that it operates on failure as well as completion, I'm sure there's an operator that can be configured to do that, but I don't know how.
My solution creates a custom operator (waitForEnd) that emits a boolean value when the source completes or errors and ignores all other elements from the source stream
const waitForEnd = () =>
  waitOn$ => new Observable(obsv => {
    const final = (bool) => {
      obsv.next(bool);
      obsv.complete();
    }
    waitOn$.subscribe({
      next: _ => {/*do nothing*/},
      complete: () => final(true),
      error: _ => final(false)
    });
    return {unsubscribe: () => waitOn$.unsubscribe()}
  });

let snapshotChanges$ = uploadTask.snapshotChanges().pipe(
  waitForEnd(),
  mergeMap(_ => fileRef.getDownloadURL()),
  tap(url => group.get('downloadUrl').setValue(url))
);

snapshotChanges$ will wait for uploadTask.snapshotChanges() to have ended, only then will it get the download URL and set the value before it completes as well.


text:
Q: Quick format vs full format When formatting a drive as ntfs for a windows XP install, you have an option to choose between a "quick" format and complete format.
What is the difference between the two (aside from how long it takes to complete)?

A: Inasmuch as the term "format" has been badly misused in modern times, a "quick" format simply creates an empty directory structure which renders the disk "empty" for all intents and purposes.  Linux has the more appropriately named mkfs (make file system) command for the same purpose.
The "complete" format erases every sector on the disk and checks for bad blocks in the process.  Hence, the long run time.
Modern disks have firmware that checks for bad blocks and relocates them automatically.  This makes it unlikely that the old-style "scan for bad blocks" will ever turn up anything.

A: Basically, quick format doesn't do a scan of the disk to check for bad sectors.
Here's a MS article on the topic.


text:
Q: Issue with the rectangle position My concept is simple, I've got draw one square for each character I have in a textarea element. The enviroment to draw them is a 500x500 canvas. But the problem is: I'm not being able to jump to the next line when the squares hit the limit of 500px.
Each square is 10x10, therefore, just 50 squares can fit in a single row with 500px.
Here's my code:
<textarea id="text"></textarea>
<button id="convert">Draw Squares</button><br>

<canvas id="canvas" width="500" height="500" style="border:1px solid"></canvas>
<script>
    var canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        text = document.getElementById("text");

    var y = 0;

    document.getElementById("convert").addEventListener("click", function(){
        context.beginPath();

        for(var i = 0; i < text.value.length; i++){
            if(i > 0 && i % 50 == 0) y++; // Here I try to jump to the next line
            context.rect(i * 10, y * 10, 10, 10);
        }

        context.fillStyle = 'red';
        context.fill();
    });
</script>

The problem might be inside the loop, however, I have no idea what's the actual issue there.

A: Your y value is correct, but you need to reset x back to 0.  The % operator will work for this:
var canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    text = document.getElementById("text");

var y = 0;

document.getElementById("convert").addEventListener("click", function(){
    context.beginPath();

    for(var i = 0; i < text.value.length; i++){
        if(i > 0 && i % 50 == 0) y++; // Here I try to jump to the next line
        console.log(y)
        x = (i % 50) * 10
        context.rect(x, y * 10, 10, 10);
    }

    context.strokeStyle = 'red';
    context.stroke();
});

JS FIddle example:  https://jsfiddle.net/igor_9000/Lx0vq3st/
Hope that helps!


text:
Q: Yii2 Events: How to add multiple event handlers using behavior's events method? Here is my Behavior's class events() method. When I trigger an event second handler i.e. sendMailHanlder gets called and it ignores anotherOne. I believe, the second one overwrites first one. How do I solve this problem so that both event handlers get called?
    // UserBehavior.php
    public function events()
    {
        return [
            Users::EVENT_NEW_USER => [$this, 'anotherOne'],
            Users::EVENT_NEW_USER => [$this, 'sendMailHanlder'],
        ];
    }
    // here are two handlers
    public function sendMailHanlder($e)
    {
        echo ";
    }
    public function anotherOne($e)
    {
        echo 'another one';
    }

One thing to notice is that I'm attaching this behavior to my Users.php model. I tried adding both handlers using model's init() method. That way both handlers got called. Here is my init code.
public function init()
{
    $this->on(self::EVENT_NEW_USER, [$this, 'anotherOne']);
    $this->on(self::EVENT_NEW_USER, [$this, 'sendMailHanlder']);
}

A: You can override Behavior::attach() so you can have something like this in your UserBehavior and no need of your events()
    // UserBehavior.php
    public function attach($owner)
    {
        parent::attach($owner);
        $owner->on(self::EVENT_NEW_USER, [$this, 'anotherOne']);
        $owner->on(self::EVENT_NEW_USER, [$this, 'sendMailHanlder']);
    }

A: You can use anonymous function for attaching handler's in events method :
ActiveRecord::EVENT_AFTER_UPDATE => function ($event) {
    $this->deleteRemovalRequestFiles();
    $this->uploadFiles();
}

A: You should not use equal event names. Use this instead:
 public function events()
 {
     return [
         Users::EVENT_NEW_USER => [$this, 'sendMailHanlder'],
     ];
 }

 // Here are two handlers
 public function sendMailHanlder($e)
 {
     echo '';
     $this->anotherOne($e);
 }

 public function anotherOne($e)
 {
     echo 'another one';
 }


text:
Q: Directly copying values of evaluated Excel functions I know that I can copy a column containing evaluated formulas, paste it into an adjacent column, and specify to paste values (i.e., a text string), so that the value sticks and I can then select, copy, and edit the value text as I desire.  However, I would like a more direct way to produce an editable column of values.
In order of preference, I would be satisfied if I could either:
(1) simply copy the values directly from the formula-containing cells by specifying a copy mode/option instead of having to specify a paste mode/option (so that if I want to paste the values outside Excel, for example, I can do so directly) - I believe this is not possible but would like to know if I have overlooked something
(2) write the formulas in a way that "throws" the evaulated values to other cells, overwriting whatever is in those other cells as needed, but passing no trace of the formula itself to the other cells
(3) use a worksheet macro that runs in the background and automatically copies values from column A into column B whenever column A values are updated or
(4) perform some operation on the formula column that removes the formulas but leaves the (editable) values (with the obvious drawback that you can't reuse the formulas once they are gone).
Which of these are possible?

A: The following Event Macro:
Private Sub Worksheet_Calculate()
   Dim r As Range

   Application.EnableEvents = False
      For Each r In Columns(1).SpecialCells(xlFormulas).Cells
         r.Offset(0, 1).Value = r.Value
      Next r
   Application.EnableEvents = True
End Sub

will monitor calculations in column A.  Whenever a calculation is made, all the values of the formulas in column A will be copied to column B
Note:

*

*the data will not be copied

*macros must be enabled

*all the formula results will be copied, even un-changed results


text:
Q: jQuery form auto submission I am trying to write an autosubmit form (similar to google instant), and right now I am using this script to do so:
$(document).ready(function() {
    $('#string').change(function(){
        var url = $(this).val();
        $('#area').load('cgi/test.pl',{string:url});
    });
});

Now the problem with this is that after use finishes typing he will need to click outside the input field. I have tried using onkeyup etc. instead of change but firstly that will result in insane amount of requests, and secondly if you paste text in the field, it won't work. I have also tried to use javascript setTimeout with combination of the script, but couldn't really get it working.
Basically what I am after is autosubmission script that 'detects' when user is still typing (so some kind of delay for the submission) and also can detect when text has been pasted to the input field.
Cheers for any suggestions.

A: I would use the doTimeout plugin to implement "debouncing" (example: http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/).
This way, you can use keyup. To account for users pasting text, keep the change handler; just invoke the keyup handler when change fires.

A: Why didn't setTimeout work? Try doing something like this:
$(document).ready(function() {
    var currentTimeout = null;

    $('#string').keyup(handler);
    $('#string').change(handler);

    var handler = function() {
        if(currentTimeout != null) {
           clearTimeout(currentTimeout);
        }

        currentTimeout = setTimeout(function() {
           var url = $(this).val();
           $('#area').load('cgi/test.pl',{string:url});
        }, 750);
    };
});


text:
Q: SQLite Android Has Stopped im just learning android programming and try following example from some tutorial to make sqlite
databasehelper.java
package simpleform.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

private static final String DATABASE_NAME = "studentdb";
private static final int DATABASE_VERSION = 1;

public static final String TABEL_STUDENT = "student";

public static final String ID            = "id";
public static final String NAME          = "name";
public static final String ADDRESS= "address";
public static final String BIRTH = "birth";

public static final String CREATE_TABEL_STUDENT = "CREATE TABLE "
        + TABEL_STUDENT + "(" + ID + " INTEGER PRIMARY KEY, "
        + NAME+ " TEXT, " + ADDRESS+ " TEXT, "
        + BIRTH + " DATE" + ")";

private static DataBaseHelper instance;

public static synchronized DataBaseHelper getHelper(Context context) {
    if (instance == null)
        instance = new DataBaseHelper(context);
    return instance;
}

private DataBaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABEL_STUDENT);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

When I am trying to run it on Android virtual Device , It says unfortunately , sqLite has stopped

A: Have you tried?
  protected void setFragmentTitle(int resourseId) {
        setTitle(resourseId);
        getSupportActionBar().setTitle(resourseId);
    }

As pointed out by petey.


text:
Q: OpenCV: 3D Matrix on GPU I was wondering if it is possible to upload a 3-dimensional matrix to the gpu to work with it? I have a sequence of images all having the same resolution (around 100 frames); now I want to upload them to the gpu using OpenCV's .upload function and do a few computations on them.
The simple approach would be to just create a GPuMat for each frame and upload them sequentially but I was wondering if there is a more elegant way.

A: Depending upon how your algorithm works, you might be able to simply concatenate the images in one of the existing image dimensions instead of trying to create a "3D" image. For instance, if you had two frames of 640x480 images, make a single 640x960 image as your image to be sent to the GPU.


text:
Q: Handing the ID from the database to the URL - CodeIgniter I am starting my game with CodeIgniter and I have a problem - I would like to download the ID - of the product from the database so that it will be passed to the URL address:
Example address:
http://localhost/crm-SEO/api/admin/domains/{{ID in database}}/notes

When I have other methods like:
domains/GET/6
domains/update/6

Everything works fine for me, but I can not grasp it that I have domains/{{ID}}/
My code i models:
public function get( $id = false)
    {
        if ( $id == false ) {
            $q = $this->db->get('domains');
            $q = $q->result();
        }
        else{
            $this->db->where('id', $id);
            $q = $this->db->get('domains');
            $q = $q->row();
        }
        return $q;
    }

    public function update($domain)
    {
        $this->db->where('id', $domain['id'] );
        $this->db->update('domains', $domain);
    }

    public function create($domain)
    {
        $this->db->insert('domains', $domain);
    }

    public function delete($domain)
    {
        $this->db->where('id', $domain['id'] );
        $this->db->delete('domains');
    }

My code in controller:
public function __construct()
    {
        parent::__construct();

        $post = file_get_contents('php://input');
        $_POST = json_decode($post,true);
        $this->load->model('admin/domains_model');
    }

    public function get($id = false)
    {
        $result = $this->domains_model->get($id);
        echo '{"records":' . json_encode( $result ) . '}';
    }

    public function update()
    {
        $domain = $this->input->post('domain');
        $this->domains_model->update($domain);
    }

    public function create()
    {
        $domain = $this->input->post('domain');
        $this->domains_model->create($domain);
    }

    public function delete()
    {
        $domain = $this->input->post('domain');
        $this->domains_model->delete($domain);
    }


text:
Q: Changing destination of a printer in lp in linux When I type lpstat -p in bash I get:
    lp@linuxbox 'xerox printer in room 100' (dest lp@193.233.9.7)

How do I change dest to another IP?

A: Printers for plain vanilla lpd are configured in /etc/printcap - the printcap(5) man page has all the gory details on that.
Your distribution is probably using CUPS though (you mentioned lpadmin), so you need to make your changes through the CUPS tools.  You can remove and re-add the printer via lpadmin, or see if the CUPS web interface is enabled and will let you do what you want (it's typically http://localhost:631)

A: You don't. You add another printer at the address of interest.


text:
Q: Gulp error File not found with singular glob After changing gulp 3 to 4 I receive the error when I try to run gulp build:
Error: File not found with singular glob: /assets/css/argon.css (if this was purposeful, use `allowEmpty` option)

The code was working before with gulp 3 (as I was told) and I made a couple of changes to be able to work with gulp 4 as well. The error is received after all tasks has run correcltly.

File is located where it is looking for it:

And here is my gulpfile.js:
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var csscomb = require('gulp-csscomb');
var cleanCss = require('gulp-clean-css');
var cssnano = require('gulp-cssnano');
var composer = require('gulp-uglify/composer');
var concat = require('gulp-concat');
var del = require('del');
var imagemin = require('gulp-imagemin');
var htmlPrettify = require('gulp-html-prettify');
var gulp = require('gulp');
var gulpIf = require('gulp-if');
var gulpRun = require('gulp-run');
var gulpUtil = require('gulp-util');
var npmDist = require('gulp-npm-dist');
var postcss = require('gulp-postcss');
var runSequence = require('gulp4-run-sequence');
// var sass = require('gulp-sass');
var uglifyEs = require('uglify-es');
var uglify = composer(uglifyEs, console);
var rename = require('gulp-rename');
var useref = require('gulp-useref-plus');
var wait = require('gulp-wait');
var sass = require('gulp-sass')(require('sass'));

// Define paths

var paths = {
 dist: {
     base: 'dist',
     img:  'dist/assets/img',
     libs: 'dist/assets/vendor'
 },
 base: {
     base: './',
     node: 'node_modules'
 },
 src: {
     base: './',
     css:  'assets/css',
     html: '**/*.html',
     img:  'assets/img/**/*.+(png|jpg|gif|svg)',
     js:   'assets/js/**/*.js',
     scss: 'assets/scss/**/*.scss'
 }
}

// Compile SCSS

gulp.task('scss', async function() {
return gulp.src(paths.src.scss)
 .pipe(wait(500))
 .pipe(sass().on('error', sass.logError))
 .pipe(postcss([require('postcss-flexbugs-fixes')]))
 .pipe(autoprefixer({
     browsers: ['> 1%']
 }))
 .pipe(csscomb())
 .pipe(gulp.dest(paths.src.css))
 .pipe(browserSync.reload({
     stream: true
 }));
});

// Minify CSS

gulp.task('minify:css', async function() {
return gulp.src([
     paths.src.css + '/argon.css'
 ])
 .pipe(cleanCss())
 .pipe(rename({ suffix: '.min' }))
 .pipe(gulp.dest(paths.dist.base + '/css'))
});

// Concat JS files

gulp.task('concat:js', async function(done) {

 files = [
     paths.src.base + '/assets/js/components/license.js',
     paths.src.base + '/assets/js/components/layout.js',
     paths.src.base + '/assets/js/components/init/*js',
     paths.src.base + '/assets/js/components/custom/*js',
     paths.src.base + '/assets/js/components/maps/*js',
     paths.src.base + '/assets/js/components/charts/*js',
     paths.src.base + '/assets/js/components/vendor/*js'
 ];

 return gulp
     .src(files)
     .pipe(concat("argon.js"))
     .pipe(gulp.dest(paths.dist.base + '/js'));

 done();
});

// Minify JS

gulp.task('minify:js', async function(cb) {
 return gulp.src([
         paths.dist.base + '/js/argon.js'
     ])
     .pipe(uglify())
     .pipe(rename({ suffix: '.min' }))
     .pipe(gulp.dest(paths.dist.base + '/js'))
});

// Live reload

gulp.task('browserSync', async function() {
 browserSync.init({
     server: {
         baseDir: [paths.src.base, paths.base.base]
     },
 })
});

// Watch for changes

gulp.task('watch', gulp.series('browserSync', 'scss', async function() {
 gulp.watch(paths.src.scss, ['scss']);
 gulp.watch(paths.src.js, browserSync.reload);
 gulp.watch(paths.src.html, browserSync.reload);
}));

// Clean

gulp.task('clean:dist', async function() {
 return del.sync(paths.dist.base);
});

// Copy CSS

gulp.task('copy:css', async function() {
 return gulp.src([
     paths.src.base + '/assets/css/argon.css'
 ])
 .pipe(gulp.dest(paths.dist.base + '/css'))
});

// Copy JS

gulp.task('copy:js', async function() {
 return gulp.src([
     paths.src.base + '/assets/js/argon.js'
 ])
 .pipe(gulp.dest(paths.dist.base + '/js'))
});

// Build

gulp.task('build', async function(callback) {
 runSequence('clean:dist', 'scss', 'copy:css', 'copy:js', 'concat:js', 'minify:js', 'minify:css',
     callback);
});

// Default

gulp.task('default', async function(callback) {
 runSequence(['scss', 'browserSync', 'watch'],
     callback
 )
});

Any help would be appreciated :)

A: In copy:css you have this line:
paths.src.base + '/assets/css/argon.css'
where apparently your error is.  The problem is your paths.src.base is defined as
base: './'  to which you are adding /assets/css/argon.css so you end up with
.//assets/css/argon.css note the two leading backslashes.
Get rid of the leading backslash in the /assets/... and check the rest of your code for the same problem.

Also since you are using gulp4 get rid of runSequence - look at the documentation for gulp.series.


text:
Q: IF Statement being Ignored - SQL Server I have a 2008 R2 SQL Server that is used very sporadically so I've created a scheduled task that calls a very basic stored procedure to put the server to sleep if no one is logged in (by means of an IF() function)... this is the stored procedure;
/****** Object: StoredProcedure [dbo].[sp_GoToSleep] Script Date: 07/21/2013 13:53:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:   <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_GoToSleep]
AS
BEGIN

SET NOCOUNT ON;

IF NOT EXISTS
(
SELECT
a.loginame AS LoginName

FROM master.sys.sysprocesses AS a

WHERE
loginame NOT LIKE '%XXXX%'
AND hostname <> ''

GROUP BY
db_name(dbid)
, loginame
, hostname

UNION ALL

SELECT
a.LogonName AS LoginName

FROM XXXXDB.dbo.CurrentUser AS a)

BEGIN
EXEC xp_cmdshell "rundll32.exe powrprof.dll,SetSuspendState 0,1,0"
END

END

The problem I'm having is the EXEC statement getting called when users are logged in and data should exist. There is nothing else putting the PC to sleep (stays on when the script is disabled).
Everything is being run from the same local account that has sufficient permissions which I verified by logging in via RDP under that account and checking that I get expected results when a user is logged in (just me at the moment).
The task is set to run when the local account is logged off and that appears to be when the issue starts...
Is there something here I'm missing? The IF function HAS to be initiating the EXEC statement but I KNOW the there should be data that would otherwise stop it - unless SQL is somehow returning different results when the account is logged off?
Would love some suggestions on this because it's got me tearing my hair out :-)
UPDATE: If it makes any difference, the task scheduler is calling the sp via sqlcmd - I figure this side of things is working because there's no doubting the sp is being initiated.


text:
Q: How to prove that $x=0.1234567891011\dots $ is irrational? I'm in $9th$ class and I was wondering how to solve this problem. I only know how to prove that $0.1010010001\dots$ is irrattional.

A: The decimal representation of a rational ends by repeating the same digits periodically.
The number 0.1234567891011… includes arbitrarily large sequences of zeroes (it inculdes 10, 100, 1000, 10000, ...).  But it also includes arbitrarily large sequences of 1's  (it includes 1, 11, 111, 1111, ...).  This is contradictory with the fact that it ends with a finite period.

A: It has many proofs.
Okay I can give you one hint this is much interesting
any rational number can have only finite decimal representation or recurrence decimal representation.
For start just take $\frac pq$ where $gcd(p,q)=1$ then see after using division algorithm what are the remainders that will come.
Do it then you will get generalised statement.


text:
Q: sending polymer iron form data to firebase I want to send this form data to Firebase URL:
https://blazing-heat-759.firebaseio.com/senso/
<form is="iron-form" id="form" method="post" action="/">
<paper-input name="qty2" label="Quantity"></paper-input>
<paper-input name="cdate2" id="d2" type="date"></paper-input>
<button type="submit" class="submit">Submit</button>

is there a way to do it?

A: You need to push your data to a Firebase ref. Try to adapt from this example for a contact form.


text:
Q: Editing without using id hidden field in form? I am not sure if this is the cleanest way of writing an edit. But after hours of research this is the best I could come up with. However I don't like the fact that I have to store the id inside a hiddenfield just to retrieve it again as POST to actually update the model.
Is there a more efficient way of doing this?
def edit_contact_view(request):
    profile = request.user.get_profile()
    if 'id' in request.GET:
        try:
            id = request.GET['id']
            contacts = profile.company.contact_set.all()
            form = ContactsForm(profile.company, instance=contacts.get(id=id))
            form.data['id'] = id
            variables = RequestContext(request, {'form':form })
            return render_to_response("contact.html", variables)
        except Contact.DoesNotExist:
            raise Http404(_(u'Contact not found'))
    else:
        if request.method == 'POST':
            form = ContactsForm(profile.company, request.POST)
            if form.is_valid():
                contacts = profile.company.contact_set.all()
                contact = contacts.get(id=form.cleaned_data['id'])
                contact.last_name = form.cleaned_data['last_name']
                contact.save()
    return HttpResponseRedirect('/')

A: Yes, you are making this more complicated than it needs to be.
Firstly, in Django it's more usual to pass the id in the URL itself, rather than in a GET parameter - eg /contact/edit/3/ rather than /contact/edit?id=3. See for example this question to see how to configure URLs like that.
Secondly, whichever way you do it, there's no need to pass the id in a hidden variable since it's already available from the URL. You can always get the instance from there.
Thirdly, I presume that ContactForm is a ModelForm, but you're not using the save functionality, which simplifies things still further.
Putting it all together:
def edit_contact_view(request, id=None):
    profile = request.user.get_profile()
    if id is not None:
        contact = get_object_or_404(Contact, pk=id)
    else:
        contact = Contact(company=profile.company)
    if request.POST:
       form = ContactForm(request.POST, instance=contact)
       if form.is_valid():
           contact = form.save()
           return redirect(...)

    else:
        form = ContactForm(instance=contact)
    return render_to_response('contact.html', {'form': form})

A: I must be missing something here but why don't you encode the id in the url as is standard?
i.e. in urls.py:
url('^/contact/?P<contact_id>[0-9]+)/edit/$', edit_contact_view, name='edit_contact_view')

your view:
def edit_contact_view(request, contact_id):
    profile = request.user.get_profile()
    contact = get_object_or_404(Contact, id=contact_id)
    if contact not in profile.company.contact_set.all():
        return Http404

and in your template
<form method="POST">
   {{ form.as_p }}
   ...
</form>


text:
Q: T-SQL filtering by date in dd/mm/yyy format In T-SQL is there a way to filter by greater than a date given in dd/mm/yyyy format?
so for example:
SELECT BIRTHDAY FROM ATABLE WHERE BIRTHDAY > 12/12/1990

A: Since many date formats are dependent on language & regional settings, I recommend to always use the ISO-8601 format of YYYYMMDD - and of course, also put your date literal into single quotes:
SELECT Birthday
FROM dbo.ATable
WHERE Birtday > '19901212'

This works on all SQL Servers - regardless of what language, date and regional settings you have


text:
Q: Can any Gaussian integral with complex limits be written as a (complex) error function? Can the integral,
$$I = \int^{-x}_{-\infty} e^{-at^2}\ \mathrm dt,\ a \in \mathbb{C},\ Re(a) > 0,$$
be written as an error function?
I tried, by substitution,
$$\int^{-x}_{-\infty} e^{-at^2}\ \mathrm dt = \frac{1}{\sqrt{a}}\int^{-x\sqrt{a}}_{-\infty\sqrt{a}} e^{-u^2}\ \mathrm du.$$
Reducing this to a complementary error function, $erfc(z) = \frac{2}{\sqrt{\pi}} \int_{z}^{\infty}e^{-u^2}du$, seems to require that the lower bound of the integral obtained after the substitution, $-\sqrt{a}\cdot \infty$, is real.
Despite this, Mathematica computes the integral as defined above to,
$\int^{-x}_{-\infty} e^{-at^2}\ dt = \frac{\sqrt{\pi}}{2\sqrt{a}}erfc(\sqrt{a}x)$,
subject to the above constraints on the parameter $a$. The limit of the error function for $x \rightarrow \infty$ depends on the real and imaginary parts of $\sqrt{a}$. [see http://functions.wolfram.com/GammaBetaErf/Erfc/ for limiting values at infinity]. For the initial integral, $I(x \rightarrow \infty) \rightarrow 0$, independent of $a$. I would like to understand where this apparent discrepancy arises.
Any thoughts would be very helpful!


text:
Q: Is there distributed task queue in Python that enables me to kill hanging tasks that are not willing to cooperate Basically I have a lot of tasks (in batches of about 1000) and execution times of these tasks can vary widely (from less than second to 10 minutes). I know that if a task is executing more than a minute i can kill it. These tasks are steps in optimization of some data mining model (but are independent of each other) and are spending most of the time inside some C extension function so they would not cooperate if I tried to kill them gracefully.
Is there a distributed task queue that fits into that schema --- AFAIK: celery allows aborting tasks that are willing to cooperate. But I might be wrong.
I recently asked similar question about killing hanging functions in pure python Kill hanging function in Python in multithreaded enviorment.
I guess I could subclass celery task so it spawns a new process and then executes its payload aborting it's execution if it takes to long, but then I would be killed by overhead of initialization of new interpreter.

A: Celery supports time limiting. You can use time limits to kill long running tasks. Beside killing tasks you can use soft limits which enable to handle SoftTimeLimitExceeded exceptions in tasks and terminate tasks cleanly.
from celery.task import task
from celery.exceptions import SoftTimeLimitExceeded

@task
def mytask():
    try:
        do_work()
    except SoftTimeLimitExceeded:
        clean_up_in_a_hurry()

A: Pistil allows multiple process management, including killing uncooperative tasks.
But:

*

*it's beta software, even if it powers gunicorn which is reliable

*I don't know how it handle 1000 processes

*Communication between process is not included yet, so you'll have to setup your own using for example zeromq
Another possibility is to use the timer signal so it raises an exception in 36000 seconds. But signals are not trigered if somebody acquire the GIL, which you C program might do.

A: When you revoke a celery task, you can provide it with an optional terminate=True keyword.
task.revoke(terminate=True)

It doesn't exactly fit your requirements since it's not done by the process itself, but you should be able to either extend the task class to be able to commit suicide, or have a reccurring cleanup task or process killing off tasks that have not completed on time.


text:
Q: children().length is returning an unexpected value Everything can be found here: http://jsfiddle.net/dweiliu/NBFMq/3/
This is the relevant code in question:
$('article.weeklyStandings').each(function(){
   var numPlayers = $(this).children('table tr').length;
   $(this).children('h2').append(" - " + numPlayers + " Players");
});

I have potentially multiple tables of data with results as displayed in the jsfiddle. I want to point out the number of players who played on any given week by looking up the number of rows in the table.
Why is $(this).children('table tr').length; returning 0 on jsfiddle? Note that on my local machine, this same code is returning 3.

A: The problem you are having is:

*

*children() will only look at direct children. You'll want to use find() which will find all the table tr within each article.

*If you count all of the tr's you will have end up with an extra because your heading will also be counted as a player. For this reason you can subtract 1 from the length of tr's.

Solution
Here is an example implementing the above solutions: Demo
var numPlayers = $(this).find('table tr').length -1;

Alternative (the one I would use)
As you have a record class on your player tr's, you could use .record in your selector instead, this will provide better readability and flexibility if you wish to add other rows in the future that should not be counted as a player: Demo
var numPlayers = $(this).find('.record').length;

Another Alternative
You could also use context selectors like $('.record', this) instead of $(this).find('.record'), but in my opinion it's easier to read find() chaining. Also, as context selectors internally have to use find() anyway, using find() directly will perform slightly better: Performance test

A: Change
var numPlayers = $(this).children('table tr').length;

to
var numPlayers = $('.record', this).length;

DEMO

A: Change
var numPlayers = $(this).children('table tr').length;

to
var numPlayers = $(this).find('table tr').length-1;

jsFiddle example
.children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well

A: Change children() by find() in your numPlayer affectation :)

A: Try
$(document).ready(function(){
    $('tr.record').each(function(){
        var cells = $(this).children('td');
        var gamesWon = parseInt(cells[1].innerText);
        var gamesPlayed = parseInt(cells[2].innerText);
        var winningPercentage = (gamesWon / gamesPlayed * 100).toFixed(1) + "%";
        $(cells[3]).html(winningPercentage);
    });
    $('article.weeklyStandings').each(function(){
        var numPlayers = $(this).find('tr.record').length;
        $(this).children('h2').append(" - " + numPlayers + " Players");
    });
});

Demo: Fiddle

A: Ditto to other answers:
var numPlayers = $(this).children('table').find('tr').length;

A: The .children() function only looks at immediate descendants, so those that are one level down in the DOM. What you're saying is "look for a <tr> that's inside a <table> and is also the direct descendant of the <article class="weeklyStandings"> element"; that won't ever be the case because the <table> is between those two.
You should use .find() instead, as well as modify your selector so that it doesn't include your header row:
$(this).find('table tr.records').length;


text:
Q: Call PHP functions twice removed What I currently have are a few php files with different functions that need to be called at the start of every page.
Instead of calling each php file and the necessary functions, I'm thinking of creating a "startup.php" file which will have all the necessary include and call functions and simply call that one page, instead.
Would this work?
Every page, such as index.php, would call startup.php, which is, in turn, calling timeout.php, request_timeout(), session_start(), tracker.php, etc.

A: It is a good thinking/practice to group similar functions, or functions a with similar purposes... like sessions handling, plain functions, classes, queries, admin... in a separate files, but you can't call php functions from html file.
For example, this block of included files,  is at the top of my every page, inside share.php because, the functions are needed by all my pages.
<?php
require_once("inc/session.php");
require_once("inc/conn.php");
require_once("inc/functions.php");
require_once("inc/direct.php");


text:
Q: Why is this marked as a potential leak using ARC? I'm still a bit confused with ARC, bridging, and certain non-toll-free bridged CF objects. My current confusion is around CFSocket. I'm pretty sure I'm cleaning up correctly, but the analysis tool is telling me otherwise. Maybe my dissonance is keeping me from seeing the leak, or the tool is wrong. I'm not ready to blame the tool, so I'm looking for other eyes to point out the issue. For example, am I missing a form of __bridge to transfer ownership to me?
In my project, using ARC, I have a TCP-based server. Let's call this class "MyServer". In MyServer, I have an internal property, socket, defined as such:
@property (assign) CFSocketRef socket;

This property holds the socket reference while the server is running. Stopping the server will release the reference, as will deleting the server object. I am also trying to clean up any potential leaks that get created during the process of starting the server. It is in this area where I'm having an issue with the static analysis.
The server is started with this method:
- (BOOL)startServer
{
    BOOL started = NO;

    NSLog(@"[%@ %@] starting server on port %u", NSStringFromClass([self class]), NSStringFromSelector(_cmd),self.port);

    self.lastError = nil;

    if ([self createSocket]) {
        started = YES;
        _state = SERVER_STATE_STARTING;
    };

    return started;
}

The createSocket method creates a socket (duh), like so:
-(BOOL)createSocket
{
    BOOL result = YES;

    self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM,
                                 IPPROTO_TCP, 0, NULL, NULL);
    if (self.socket != NULL) {
        int reuse = true;
        int fileDescriptor = CFSocketGetNative(self.socket);
        if (setsockopt(fileDescriptor, SOL_SOCKET, SO_REUSEADDR,
                       (void *)&reuse, sizeof(int)) == 0) {

            struct sockaddr_in address;
            memset(&address, 0, sizeof(address));
            address.sin_len = sizeof(address);
            address.sin_family = AF_INET;
            address.sin_addr.s_addr = htonl(INADDR_ANY);
            address.sin_port = htons(self.port);

            CFDataRef addressData = CFDataCreate(NULL,
                                                 (const UInt8 *)&address,
                                                 sizeof(address));

            if (addressData && CFSocketSetAddress(self.socket, addressData) == kCFSocketSuccess) {
                self.listenHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileDescriptor
                                                                  closeOnDealloc:YES];

                [[NSNotificationCenter defaultCenter] addObserver:self
                                                         selector:@selector(receiveIncomingConnectionNotification:)
                                                             name:NSFileHandleConnectionAcceptedNotification
                                                           object:nil];
                [self.listenHandle acceptConnectionInBackgroundAndNotify];

                _state = SERVER_STATE_RUNNING;
            } else {
                result = NO;
                [self errorWithName:@"Unable to bind socket to address."];
            }
            CFRelease(addressData);
        } else {
            [self errorWithName:@"Unable to set socket options."];
            CFRelease(self.socket);
            CFSocketInvalidate(self.socket);
            CFRelease(self.socket);
            self.socket = nil;
            result = NO;
        }
    } else {
        [self errorWithName:@"Unable to create socket."];
        // CFRelease(self.socket); //NO - CFRelease(NULL) is a runtime error!
        result = NO;
    }

    return result;
}

When I run static analysis on this code, Xcode reports a bunch of potential leaks around self.socket. Here's one example, from the above createSocket method:

It is indeed true that I don't reference the object any more in this path. Perhaps there's some way to tell the system that I want to own the object and the reason it's complaining is that it can't tell that I do. Am I supposed to be using one of the __bridge casts to convey that information? I tried making the property retain or strong, but that doesn't build because it's not an object. Any other thoughts?

A: A couple of thoughts:

*

*The problem, as Jesse points out, is that you're using the accessor methods for socket and the analyzer is getting a little confused, thinking that the object passed to the setSocket method is leaking, not realizing that you're saving it in the instance variable. If you replace these occurrences of self.socket with _socket, your warnings related to self.socket go away.

*Your code generates a second warning about addressData relate to the fact that you have an execution path whereby addressData could be NULL, but you're still calling CFRelease. You should make the code explicitly check for not NULL before trying to CFRelease.

*You're releasing your socket twice, once before invalidating it, and again after. Clearly, you don't want to be releasing that twice. I'd also suggest setting the socket to NULL, not nil, not that it is that important.

*Partially because of my change related to point #2 (where I'd otherwise need to add another else clause if addressData was NULL), but also as a general shift in logic, since you have many execution paths associated with failure, but only have one associated with success, I'd suggest to defaulting result to NO and set it to YES in that single successful execution path. This makes sure that we invalidate and release the socket in all of the different paths where the creation succeeded, but the listening didn't succeed. I believe there were a few execution paths that were not being covered properly, previously.
Thus, I end up with this rendition of createSocket:
-(BOOL)createSocket
{
    BOOL result = NO;

    _socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM,
                                 IPPROTO_TCP, 0, NULL, NULL);

    if (_socket != NULL) {
        int reuse = true;
        int fileDescriptor = CFSocketGetNative(self.socket);
        if (setsockopt(fileDescriptor, SOL_SOCKET, SO_REUSEADDR,
                       (void *)&reuse, sizeof(int)) == 0) {

            struct sockaddr_in address;
            memset(&address, 0, sizeof(address));
            address.sin_len = sizeof(address);
            address.sin_family = AF_INET;
            address.sin_addr.s_addr = htonl(INADDR_ANY);
            address.sin_port = htons(self.port);

            CFDataRef addressData = CFDataCreate(NULL,
                                                 (const UInt8 *)&address,
                                                 sizeof(address));

            if (addressData) {
                if (CFSocketSetAddress(_socket, addressData) == kCFSocketSuccess) {
                    self.listenHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileDescriptor
                                                                      closeOnDealloc:YES];

                    [[NSNotificationCenter defaultCenter] addObserver:self
                                                             selector:@selector(receiveIncomingConnectionNotification:)
                                                                 name:NSFileHandleConnectionAcceptedNotification
                                                               object:nil];
                    [self.listenHandle acceptConnectionInBackgroundAndNotify];

                    result = YES;
                    _state = SERVER_STATE_RUNNING;
                } else {
                    [self errorWithName:@"Unable to bind socket to address."];
                }
                CFRelease(addressData);
            }
        }

        if (result != YES) {
            [self errorWithName:@"Unable to set socket options."];
            CFSocketInvalidate(_socket);
            CFRelease(_socket);
            _socket = NULL;
        }
    } else {
        [self errorWithName:@"Unable to create socket."];
    }

    return result;
}

My original answer was focusing on the basics of Core Foundation Memory Management, while important, are not immediately relevant to the issue at hand.
Original Answer:
Yes, if a Core Foundation function call has Create or Copy in the name, you own the object. As such, you must either:

*

*Release the object via CFRelease. See Core Foundation Memory Management Programming Guide.

*Transfer ownership to ARC via CFBridgingRelease or __bridge_transfer. See the Transitioning to ARC Release Notes.
Clearly, the former is applicable here, but in general either approach works.

A: It's being reported as a potential leak because it is a potential leak. If the createSocket method is called twice, you have a leak because you never release the socket.
Try adding:
CFRelease(self.socket);

just before the call to CFSocketCreate. And made sure you are calling CFRelease on the socket in the dealloc method.

A: The problem here is that you're using a property, which is confusing the compiler. (It can't figure out that the call self.socket = ..., which is actually [self setSocket:...] expects an already-retained item and stores it.
If you use an instance variable directly, it should quiet the warning, because it will understand that you're holding on to a reference to that CFSocketRef on your own. (In this case, since your property is private and assign, you might as well use an instance variable anyway.)
Also, you're using the socket after you call CFRelease later on (you're calling CFSocketInvalidate on it after CFRelease), which is a bad idea.


text:
Q: JQUERY - Change hidden input with multiple submit I Have a simple FORM with a Hidden Input only - and multiple submit buttons (1 to infinite)
When the user click on submit - the button change the hidden input value to submit the form.
<form action="" id="form">
    <input type="hidden" name="answer" id="answer">
    <input type="submit" value="A">
    <input type="submit" value="B">
    <input type="submit" value="C">
</form>

$("#form").on("submit", function (event) {
   event.preventDefault();
   var currentForm = $(this);
   $("#answer").val() = $("#submit").val();
});

how can I do this?
I'm trying Jquery, but - something is wrong. I know this is easy, but I'm not an expert
tks a lot!
Daniel

A: If I know what you mean...
For example, this is HTML of your form
<form action="" id="form_id_example">
    <input type="hidden" name="change_value" id="change_value">
    <input type="submit" name="">
</form>

The jQuery is something similar to that
$("#form_id_example").on("submit", function (event) {
   event.preventDefault();
   var currentForm = $(this);
   $("#change_value").val("new input value");
   $("#form_id_example").off("submit");
   currentForm.submit();
});


text:
Q: How to skip a step if a condition is met in a previous step - Stepper | Angular Material How do I skip a step using a true/false condition of a variable present in a few steps back?

A: I found the solution, that was after all so simple!
On the stepper's parent component html, I used a conditional ngIf that checks the value of a property saved on a form!

A: u can use conditional if. This is a possibility.


text:
Q: Apache Rewrite not working I have a very strange thing happening in my apache2 setup. I just want to redirect HTTP to HTTPS. I have tried all possible ways, like this:
RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

I put this in /etc/apache2/apache2.conf but it simply didn't work.
I then put the above in <VirtualHost *:80> and it works, but I instead get

This page isn't working
  kanzan.se redirected you too many times.

This is because I use port 80 behind a cache server (Varnish) and in front of that I use a <VirtualHost *:443>. Every works fine except for this.
I even had this problem before I put Varnish there, but then I could solve it by putting the rewriting in <VirtualHost *:80> since that worked.
Somehow Apache doesn't care about its main config file /etc/apache2/apache2.conf?

A:
I put this in /etc/apache2/apache2.conf but it simply didn't work.

If by that you mean you put the directives directly in the server, in a server context, then the directives won't do anything if you have mod_rewrite directives in the <VirtualHost> being accessed. You would need to enable mod_rewrite inheritance (but you may not want to do that).
If you are behind a proxy server that manages your SSL then your application server is always serving content over port 80, so the HTTPS server variable is never on - hence your redirect loop.
However, the proxy server should set the X-Forwarded-Proto request header, indicating (to your application server) which protocol is being used. eg. Either http or https. So, you could probably change your directive to read the following instead:
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$ [NC]
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

Then again, your config may be setting some other non-standard header (or environment variable) that you would need to use instead.


text:
Q: How to build and deploy dockerized PHP application in dockerized Jenkins I'm going to use Jenkins to build and deploy my PHP (Laravel) application. That's why I decided to use this http://jenkins-php.org/ decision to reach my purpose. But I'm a fun of Docker and it's a reason why I dared to create my own Docker images that implemented decision above. Here it is: https://github.com/AntonKozytskyi/jenkins-php.
For my Laravel App I have a decision that looks similar this https://github.com/LaraDock/laradock.
Totally I have both Jenkins and Laravel App working via Docker.
I would like to run Jenkins job that:

*

*gets Laravel App project from Bitbucket repo (this point have already
reached by using bitbucket plugin:
https://wiki.jenkins-ci.org/display/JENKINS/BitBucket+Plugin);

*runs docker-compose.xml to build and start containers;

*launch Ant tasks (composer install, various code checks, phpunit and so on);

*publish project to another server if checks above was passed.

What is the right way to build Laravel App working under Docker in Jenkins that is working under Docker as well?
Any help is appreciated.
Thanks in advance.


text:
Q: onClick - Call Function from Another File I have a functionality.js file which is linked to the front-end, within here I want to click on a div(item1wrapper) and call a function from my index.js file.
Within this functionality.js file I append the div:
  socket.on('response', function (data) {
        if (msg.includes('totalPrice')) {
        if (parsed.itemPrice.length === 1) {
            $('#messages').append($('
').append($(`

 Please click on the item you want to return

`
        )).append($('
')));
        $("#messages").animate({ scrollTop: $("#messages")[0].scrollHeight }, 1000);

        $('.customerName').text('Customer name: ' + customerName);
        $('.orderNum').text('Order number: ' + orderNum);

        $('.item1Title').text('Item: ' + item1Title);
        $('.item1Price').text('Price: ' + item1Price);

        }

Module exports isnt working because it's linked to the front-end?
Here is my function within my index.js file:
 function oneCall() {
            itemId = itemIdArray[0];
            // matching API get

            // getRefundCalc API post.
            console.log('ngrokurl' + ngrokUrl)
            console.log('domain' + domain)
            console.log('orderId' + orderId)
            console.log('itemId' + itemId)

            /*
            The Purchase date must be in the future
            */

            rp(optionsPOST1)
                .then(function (parsedBody) {
                    Match = parsedBody.Match;
                    if (Match) {
                        console.log('Match is true');

                        httpRequest.post(
                            `${ngrokUrl}/${domain}/${orderId}`,
                            {
                                json:
                                    {
                                        "line_items": [
                                            {
                                                "line_item_id": itemId, "quantity": 1
                                            }
                                        ]
                                    }
                            },
                            function (error, resp, body) {
                                if (!error && resp.statusCode == 200) {
                                    console.log(body)

                                    response = responseToFrontEnd
                                    data = [details.chatuser, response]
                                    io.of('/main').to(socket.id).emit('response', data);

                                }
                                else {
                                    console.log('error' + error)
                                }
                            }
                        )
                        // include getRefundCalc within here
                    } else {
                        console.log('Match is false');
                        response = `I'm sorry but your item fell out of the refund policy. Please check the purchase date of your item or if it falls under the minimum price.`
                    }
                });
            }

Currently the "onclick" is empty because it wasnt working, when I click on that div in this functionality.js file I want to call that function! and it has to be outside of the functionality file as it requires node modules and needs to be within the socket function!


text:
Q: Why does MySQL allow HAVING to use SELECT aliases? In SQL, as far as I know, the logical query processing order, which is the conceptual interpretation order, starts with FROM in the following way:

*

*FROM

*WHERE

*GROUP BY

*HAVING

*SELECT

*ORDER BY

Following this list it's easy to see why you can't have SELECT aliases in a WHERE clause, because the alias hasn't been created yet. T-SQL (SQL Server) follows this strictly and you can't use SELECT aliases until you've passed SELECT.
But in MySQL it's possible to use SELECT aliases in the HAVING clause even though it should (logically) be processed before the SELECT clause. How can this be possible?
To give an example:
SELECT YEAR(orderdate), COUNT(*) as Amount
FROM Sales.Orders
GROUP BY YEAR(orderdate)
HAVING Amount>1;

The statement is invalid in T-SQL (because HAVING is referring to the SELECT alias Amount)...
Msg 207, Level 16, State 1, Line 5
Invalid column name 'Amount'.

...but works just fine in MySQL.
Based upon this, I'm wondering:

*

*Is MySQL taking a shortcut in the SQL rules to help the user? Maybe using some kind of pre-analysis?

*Or is MySQL using a different conceptual interpretation order than the one I though all RDBMS were following?

A: Good question.
I think you should run these querys
EXPLAIN SELECT YEAR(orderdate), COUNT(*) as Amount
FROM Sales.Orders
GROUP BY YEAR(orderdate)
HAVING Amount>1;
SHOW WARNINGS;

and check how the query is rewritten.
iam pretty sure the query optimizer replace Amount with COUNT(*)
SELECT YEAR(orderdate), COUNT(*) as Amount
FROM Sales.Orders
GROUP BY YEAR(orderdate)
HAVING COUNT(*)>1;

Like it does with
select
 *
from
 test
where
 id = 5 - 3

after query optimizer its something like this.
select
 test.id as 'id'
from
 test
where
 test.id = 2

A: Well when you have a question of this sort the best source of information IMHO is MySQL documentation. Now to the point. This is the behavior of MySql extension to GROUP BY which is enabled by default.

MySQL Extensions to GROUP
  BY
  MySQL extends this behavior to permit the use of an alias in the
  HAVING clause for the aggregated column

If you want standard behavior you can disable this extension with sql_mode ONLY_FULL_GROUP_BY
SET [SESSION | GLOBAL] sql_mode = ONLY_FULL_GROUP_BY;

If you try to execute the above-mentioned query in ONLY_FULL_GROUP_BY sql_mode you'll get the following error message:

Non-grouping field 'Amount' is used in HAVING clause: SELECT
  YEAR(orderdate), COUNT(*) as Amount FROM Orders GROUP BY
  YEAR(orderdate) HAVING Amount > 1

Here is SQLFiddle demo
Therefore it's up to you how to configure and use your instance of MySQL.


text: Q: Lisp native functions source codes Is there a way to read the source code of native Lisp functions (e.g. 'merge') through Interactive Lisp Shell GNU CLisp (v 2.49) ? If there isn't what is the best (and fastest) way to get it ?


text:
Q: How to find the equation of a hyperbola knowing its asymptotes and one focus? Which is the equation for the hyperbola with one focus in $(2,-1)$ and its asymptotes are $x=0$ and $3x - 4y = 0$ ? I am not able to see how to find the answer.

A: A hyperbola is a set of points, such that for any point $P$ of the set, the absolute difference of the distances $|PF_{1}|,\ |PF_{2}|$ to two fixed points $F_{1},F_{2}$ (the foci), is constant. The two asymptotes intersect in $(0,0)$. Therefore the hyperbola is symmetric respect to this point i.e. for any point $(x,y)$ of the hyperbola the point $(-x,-y)$ is also a point of it. Alternatively this leads to if $(x_{f_1},y_{f_1})$ is a focus of it the other one is $$(x_{f_2},y_{f_2})=(-x_{f_1},-y_{f_1})$$
This enables us to write the equation of the hyperbola according to the definition as follows:
$$|\sqrt{(x-x_{f_1})^2+(y-y_{f_1})^2} -\sqrt{(x-x_{f_2})^2+(y-y_{f_2})^2}|=\lambda$$
where $\lambda$ is the same constant difference of distances. By substitution we obtain:
$$|\sqrt{(x-2)^2+(y+1)^2} -\sqrt{(x+2)^2+(y-1)^2}|=\lambda$$
squaring both sides gives us:
$$x^2+y^2+5-\sqrt{(x^2+y^2+5)-(4x-2y)^2}={\lambda^2\over 2}$$
or
$$x^2+y^2+5-{\lambda^2\over 2}=\sqrt{(x^2+y^2+5)^2-(4x-2y)^2}$$
squaring again
$$(x^2+y^2+5-{\lambda^2\over 2})^2=(x^2+y^2+5)^2-(4x-2y)^2$$
which gives us after simplification
$${\lambda^4\over 4}-5{\lambda^2}=({\lambda^2}-16)x^2+({\lambda^2}-4)y^2+16xy$$
dividing both sides by $y^2$ and letting $t={x\over y}$ we obtain:
$${{{\lambda^4\over 4}-5{\lambda^2}}\over{y^2}}=({\lambda^2}-16)t^2+{\lambda^2}-4+16t$$
since by definition of asymptote $y\to\infty$ results $t\to 0$ or $t\to{4\over 3}$ these two numbers should be roots of below equation:
$$({\lambda^2}-16)t^2+16t+{\lambda^2}-4=0$$
which gives us $\lambda=2$ and the final equation of the hyperbola is:
$$3x^2-4xy-4=0$$

A: The center of the hyperbola lies at the intersection of the asymptotes, that is $(0,0)$. If $F=(2,-1)$ is one focus, the other one is the symmetric with respect to the center, that is $G=(-2,1)$.
If you now take a point $P$ on the hyperbola with $x\to0$ and $y\to-\infty$, the difference $PG-PF$ tends to $y_{G}-y_F=2$, and this difference is the same for all points on the hyperbola on the same branch, while it is $-2$ on the other branch of the curve. The equation of the hyperbola is then:
$$
\sqrt{(x+2)^2+(y-1)^2}-\sqrt{(x-2)^2+(y+1)^2}=\pm 2,
$$
which after the usual manipulations becomes
$$
3x^2-4xy-4=0.
$$

A: The asymptotes of a hyperbola are themselves the degenerate member of a single-parameter family of hyperbolas with common asymptotes. If the equations of the asymptotes are $Ax+By+C=0$ and $Ex+Fy+G=0$, then the equations of these hyperbolas are $(Ax+By+C)(Ex+Fy+G)=k$, for various values of $k$. For this problem, this means that an equation of the desired hyperbola will have the form $x(3x-4y)=k$.
Now, the perpendicular distance of a hyperbola's focus to either of its asymptotes is equal to its semi-minor axis length $b$, which we can see at a glance is $2$ for this hyperbola. Using the fact that the two semiaxis lengths $a$ and $b$ and the distance $c$ from the center to the focus are a Pythagorean triple, and that the center of this hyperbola is the origin, we can find the semimajor axis length: $a^2 = c^2-b^2 = 2^2+(-1^2)-2^2=1$. This means that a vertex of this hyperbola is $\frac1{\sqrt5}(2,-1)$. Plugging this point into the equation of the hyperbola and solving for $k$, we get $k=4$ and so an equation of the hyperbola is $$3x^2-4xy-4=0.$$


text:
Q: How to use Java Comparator to sort an array of arrays? The problem is to sort an array of two element arrays based on the absolute difference of the elements of those inner arrays in descending order, so {{1, 3}, {4, 12}, {5, 8} would be sorted as {{4, 12}, {5, 8}, {1, 3}}
I have code like this:
import java.util.Arrays;
import java.util.Comparator;

public class Main {

    public static void main(String[] args) {
        Integer[][] arr = {{1, 3}, {3, 12}, {12, 16}};

        Arrays.sort(arr, Comparator.comparing(arr, (Integer[] a, Integer[] b) -> a[1] + b[1] - a[0] - b[0]);
    }
}

but I get this error. It says "cannot infer functional interface type".
Edit: upon changing the above to
import java.util.Arrays;
import java.util.Comparator;

public class Main {

    public static void main(String[] args) {
        Integer[][] arr = {{1, 3}, {3, 12}, {12, 16}};

        Arrays.sort(arr, Comparator.comparing(a -> a[0] - a[1]));

        for (int i = 0; i < arr.length; i++ ) {
            System.out.print("{" + arr[i][0] + ", " + arr[i][1] + "}, ");
        }
    }
}

I get the desired output, but I was unable to get the reversed() method to work like in this answer. I get this error where it says "Array type expected; found: 'java.lang.Object'"
I suppose my question is mostly answered but if someone could clarify the issue with reversed I'd appreciate it.
Edit: and sorry, I neglected to use Math.abs() as in the context of my problem I know the array is always increasing like {2,3}, {3,6}, {6,8}... etc

A: Descending:
Arrays.sort(arr, (o1, o2) -> Math.abs(o2[0] - o2[1]) - Math.abs(o1[0] - o1[1]));

Ascending:
Arrays.sort(arr, Comparator.comparingInt(o -> Math.abs(o[0] - o[1])));


text:
Q: Proper way of interpreting system load on a 4 core 8 thread processor As we all know, load of 1.00 on a single processor means that there is a load of 100%. Analogically a 4.00 load on a quad core would be 100%.
How should I interpret load on a 4 core 8 thread processor ? When do I reach CPU's maximum capacity ? At 4.00 or 8.00 ?

A: As hyperthreading is not actually a 2nd core it will never take a core to 200% but it will take it beyond 100% for certain workloads.
So your maximum load is somewhere unknown between approx 4 and 6
(of course this can go up higher when overloaded because it actually counts runnable processes, particularly when they are waiting for IO)

A: Load average doesn't mean what you think it means. It's not about instant CPU usage, but rather how many processes are waiting to run. Usually that's because of lots of things wanting CPU, but not always. A common culprit is a process waiting for IO - disk or network.
Try running ps -e v and looking for process state flags.
state    The state is given by a sequence of characters, for example, "RWNA". The      first character indicates the run state of the process:
D    Marks a process in disk (or other short term, uninterruptible) wait.
I    Marks a process that is idle (sleeping for longer than about 20 seconds).
L    Marks a process that is waiting to acquire a lock.
R    Marks a runnable process.
S    Marks a process that is sleeping for less than about 20 seconds.
T    Marks a stopped process.
W    Marks an idle interrupt thread.
Z    Marks a dead process (a "zombie").

This is from the ps manpage, so you an find more detail there - R and D processes are probably of particular interest.
You can end up with load average 'spikes' for all sorts of reasons, so they're not really a good measure of anything other than 'is this system busy-ish'. Getting bogged down in mapping load average to CPU cores isn't going to do you any good.

A: On a Linux system not just the processes in the runnable queue are counted up to calculate load but also those in uninterruptible sleep states , wikipedia, causing the load to spike when you have lots of processes waiting for disk.

A: I did some experiments on our 24-core Xeon system (2 socket x 12 cores).  The maximum load is 48.0 in this case due to the way Linux sets up hyperthreading.
However, you don't get the equivalent of 48 cores of throughput. What I have observed is that you get about 90% of the throughput in the first 24 logical processors, i.e. if the load runs to 24.0. Then you get an additional throughput of about 10% for the remaining 24 logical processors (load runs to 48.0). Another way of thinking about it is is that if you run 48 threads on the 24 cores, you will get a boost of about 10-20% if you enable hyperthreading versus not. It's not 100% boost like the marketing guys would imply.
For example, one way of testing this observation is have a process that runs 48 threads (say using TBB or handrolled threading model), then run
time numactl --physcpubind=0-23  ./myprocess

and then run
time numactl --physcpubind=0-47  ./myprocess

The latter should run in about 10-20% less time. If your process is highly I/O blocked, then the result might be different.
The former will disable hyperthreading by only allowing the threads to run on a single logical processor (of each core), while the latter will enable hyperthreading by allowing the threads to run on 2 logical processors (of each core).
The load in both cases should be reported as 48.0 ... which as you can see is very misleading.

A: Not surely, but mostly on 1.00*n_cpu.
The load means the following: if there are multiple processes on a single-cpu system, they are running seemingly parallel. But it is not true. What practically happens: the kernel gives 1/100th second to a process, and then breaks its running with an interrupt. And gives the next 1/100th second to another process.
Practically the question, "which process should get our next 1/100th seconds interval?", will be decided by a complex heuristics. It is named as task scheduling.
Of course, processes which are blocked, for example they are waiting their data what they are reading from the disk, are exempt from this task scheduling.
What load says: how many processes are currently waiting their next 1/100th second time frame. Of course, it is a mean value. This is because you can see multiple numbers in a cat /proc/loadavg.
The situation in a multi-cpu system is a little bit complexer. There are multiple cpus, whose time frames can be given to multiple processes. That makes the task scheduling a little bit - but not too much - complexer. But the situation is the same.
The kernel are intelligent, it tries to share the system resources for the optimal efficiency, and it is in the near of that (there are minor optimization things, for example it is better if a process will be runned the longest possible time on the same cpu because of caching considerations, but they doesn't matter there). This is because if we have load 8, that means: there are actually 8 processes waiting for their next time slice. If we have 8 cpus, we can give these time slices to the cpus one-to-one, and thus our system will optimally used.
If you see a top, you can see that the number of the actual running processes is surprisingly low: they are the processes marked by R there. Even on a not really hardcore system is it often below 5. This is partially because the processes waiting their data from the disks or from the network are also suspended (marked with S in top). The load shows only the cpu usage.
There are tools to measure the disk load as well, imho they should be at least important as the cpu usage monitoring, but somehow it isn't so well known here in our professional sysadmin world.

Windows tools are often dividing the load with the actual number of the cpus. This causes some professional windows system administrator to use the system load in this divided-by-cpu sense. They haven't right and will be probably happier after you explain this to them.

Multicore CPUs are practically multiple CPUs on the same silicon chip. There is no difference.
In case of hyperthreaded CPUs there is an interesting side effect: loading a cpu makes its hyperthreaded pairs slower. But this happens on a deeper layer what the normal task scheduling handles, although it can (and should) influence the process-moving decisions of the scheduler.
But from our current viewpoint - what determines the system load - it doesn't matter as well.