text:
Q: Button does not recharge component each time you press I have form with button in my main component, I have two components but the first is default data (in a range time, init, end are date and obra,st,folio,profesional are strings), when I press my button I call my component with these data, but when I press button again, my component is not calling again.
I add an image from my browser to explain my problem.
Browser console image
As you can see line [data-table, constructor] is calling for default (last day), in second case I change init and end, but I when try again not show my [data-table, constructor] with my data, because I did not call the component, any ideas why?
This is my dashboard.component.html, where I call component to render data.
<app-data-table *ngIf=!active [start]=defaultDateStart [end]=defaultDateEnd>
          Loading data-table...
        </app-data-table>
        <app-data-table
          *ngIf=active
          [start]=defaultDateStart
          [end]=defaultDateEnd
          [obra]=selectedObra
          [st]=selectedST
          [folio]=selectedFolio
          [profesional]=selectedProfesional>
          Loading data-table...
</app-data-table>

This is my onSubmit(f), this function is call when I press button in my form.
onSubmit(f: NgForm) {
    if (f.value["init"] == null || f.value["init"] == "") {
      alert("Ingrese la fecha de inicio.");
      return;
    }
    if (f.value["end"] == null || f.value["end"] == "") {
      alert("Ingrese la fecha final.");
      return;
    }
    if (f.value["init"] > f.value["end"]) {
      alert("Las fechas no tienen coherencia.")
      return;
    }
    if (f.value["obra"] == null) {
      console.log("Obra no seleccionada");
    }
    if (f.value["st"] == null) {
      console.log("ST no seleccionada");
    }
    if (f.value["folio"] == null) {
      console.log("Folio no seleccionado");
    }
    if (f.value["profesional"] == null) {
      console.log("Profesional no seleccionado");
    }
    this.defaultDateStart = this.localISOTime(f.value["init"]);
    this.defaultDateEnd = this.localISOTime(f.value["end"]);
    this.active = true;
    console.log("Form values -> ", f.value);
}

UPDATE
I add my dashboard.component.html

  <md-card flex="100" class="md-card-dashboard">
    <md-card-title>BUSCADOR DE IMÁGENES
    </md-card-title>
    <md-card-subtitle>FILTROS</md-card-subtitle >
    <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
      <md-card>

                <md-input-container>
                  <input
                    mdInput
                    [mdDatepicker]="pickerInit"
                    placeholder="Fecha inicial"
                    [min]="minDate"
                    [max]="maxDate"
                    [value]="10-2-2017"
                    name="init"
                    #init="ngModel"
                    ngModel
                    required>
                  <button mdSuffix [mdDatepickerToggle]="pickerInit"></button>
                </md-input-container>
                <md-datepicker #pickerInit></md-datepicker>

                <md-input-container>
                  <input
                    mdInput
                    [mdDatepicker]="pickerEnd"
                    placeholder="Fecha final"
                    [min]="minDate"
                    [max]="maxDate"
                    name="end"
                    ngModel
                    required>
                  <button mdSuffix [mdDatepickerToggle]="pickerEnd"></button>
                </md-input-container>
                <md-datepicker #pickerEnd></md-datepicker>

                    <md-select placeholder="Obra" [(ngModel)]="selectedObra" name="obra">
                      <md-option *ngFor="let obra of obras" [value]="obra.value">
                        {{obra.value}}
                      </md-option>
                    </md-select>

                      {{selectedObra}}

                    <md-select placeholder="ST" [(ngModel)]="selectedST" name="st">
                      <md-option *ngFor="let st of sts" [value]="st.value">
                        {{st.value}}
                      </md-option>
                    </md-select>

                      {{selectedST}}

                    <md-select placeholder="Folio" [(ngModel)]="selectedFolio" name="folio">
                      <md-option *ngFor="let folio of folios" [value]="folio.value">
                        {{folio.value}}
                      </md-option>
                    </md-select>

                      {{selectedFolio}}

                    <md-select
                      placeholder="Profesional"
                      [(ngModel)]="selectedProfesional"
                      name="profesional">
                      <md-option
                        *ngFor="let profesional of profesionales"
                        [value]="profesional.value">
                        {{profesional.value}}
                      </md-option>
                    </md-select>

                      {{selectedProfesional}}

            <button md-raised-button>Buscar</button>

      </md-card>
    </form>

    <md-card-content>
      <md-card style="background-color:rgba(176,224,230,0.2);">
        <md-card-title>RESULTADOS</md-card-title>
        <app-data-table *ngIf=!active [start]=defaultDateStart [end]=defaultDateEnd>
          Loading data-table...
        </app-data-table>
        <app-data-table
          *ngIf=active
          [start]=defaultDateStart
          [end]=defaultDateEnd
          [obra]=selectedObra
          [st]=selectedST
          [folio]=selectedFolio
          [profesional]=selectedProfesional>
          Loading data-table...
        </app-data-table>
      </md-card>
    </md-card-content>
    <md-card-footer style="text-align:center">© 2017</md-card-footer>
  </md-card>

And my dashboard.component.ts with new function (I am trying resolve this) reloadWithNewId()
import { Component, OnInit, Input } from '@angular/core';
import { NgForm, NgModel } from '@angular/forms';
import { DateAdapter } from '@angular/material';
import {MdSelectChange} from '@angular/material';
import {SelectionService} from '../shared/selection.service';
import {SelectionData} from '../shared/selection-data';
import {ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  active: boolean;
  start: string;
  end: string;
  defaultDateStart: Date;
  defaultDateEnd: Date;
  minDate = new Date(2000, 0, 1);
  maxDate = new Date(Date.now());
  selectionData: SelectionData;
  obras: string[];
  sts: string[];
  folios: string[];
  profesionales: string[];

  constructor(
    private dateAdapter: DateAdapter<Date>,
    private selectionService: SelectionService,
    private route: ActivatedRoute,
    private r: Router) {
    dateAdapter.setLocale('nl'); //DD-MM-YYYY
    this.active = false;
  }

  ngOnInit() {
    let date = new Date(Date.now());
    let date_end = date;
    this.defaultDateEnd = date_end;
    this.defaultDateStart = new Date(date);
    this.defaultDateStart.setDate(this.defaultDateStart.getDate() - 1);
    this.defaultDateStart = this.localISOTime(this.defaultDateStart);
    this.defaultDateEnd = this.localISOTime(this.defaultDateEnd);
    console.log("init ", this.defaultDateStart);
    console.log("end ", this.defaultDateEnd);
    this.getDataFilters();
  }

  localISOTime(d): any {
    if (!d)
      d = new Date()
    var tzoffset = d.getTimezoneOffset() * 60000; //offset in milliseconds
    return (new Date(d - tzoffset)).toISOString().slice(0, -1);
  }

  setData(array: string[]): any[] {
    let objetos = new Array<any>();
    for (var ix of array) {
      objetos.push({ value: ix });
    }
    return objetos;
  }
  getDataFilters(): void {
    this.selectionService.getData().then(data => {
      this.selectionData = data;
      this.obras = this.setData(this.selectionData[2]["obra"]);
      this.sts = this.setData(this.selectionData[0]["st"]);
      this.folios = this.setData(this.selectionData[1]["folio"]);
      this.profesionales = this.setData(this.selectionData[3]["profesional"]);
    });

  }
  selectedObra: string;
  selectedST: string;
  selectedFolio: string;
  selectedProfesional: string;

  reloadWithNewId() {
    console.log("reloadWithNewId");
    this.r.navigateByUrl('/home');
  }

  onSubmit(f: NgForm) {
    if (!f.value["init"]) {
      alert("Ingrese la fecha de inicio.");
      return;
    }
    if (!f.value["end"]) {
      alert("Ingrese la fecha final.");
      return;
    }
    if (f.value["init"] > f.value["end"]) {
      alert("Las fechas no tienen coherencia.")
      return;
    }
    if (f.value["obra"] == null) {
      console.log("Obra no seleccionada");
    }
    if (f.value["st"] == null) {
      console.log("ST no seleccionada");
    }
    if (f.value["folio"] == null) {
      console.log("Folio no seleccionado");
    }
    if (f.value["profesional"] == null) {
      console.log("Profesional no seleccionado");
    }
    this.defaultDateStart = this.localISOTime(f.value["init"]);
    this.defaultDateEnd = this.localISOTime(f.value["end"]);
    this.active = true;
    console.log("Form values -> ", f.value);
    this.reloadWithNewId();
  }
}

NEW UPDATE
I add my data-table.component.ts and my data-table.service.ts
import {Component, ElementRef, ViewChild, Input, OnInit} from '@angular/core';
import {DataSource} from '@angular/cdk/table';
import {MdPaginator, MdSort, SelectionModel} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/debounceTime';

import { DataTableService } from '../shared/data-table.service';
import { DataTable } from '../shared/data-table';
import { Router }   from '@angular/router';

/**
 * @title Feature-rich data table
 */
@Component({
  selector: 'app-data-table',
  styleUrls: ['data-table.component.css'],
  templateUrl: 'data-table.component.html',
})
export class DataTableComponent {
  displayedColumns = ['select', 'foto', 'obra', 'st', 'folio', 'profesional', 'date'];
  exampleDatabase: ExampleDatabase | null;
  selection = new SelectionModel<string>(true, []);
  dataSource: ExampleDataSource | null;
  photos: DataTable[];
  @Input() start: string;
  @Input() end: string;
  @Input() obra: string;
  @Input() st: string;
  @Input() folio: string;
  @Input() profesional: string;
  @ViewChild(MdPaginator) paginator: MdPaginator;
  @ViewChild(MdSort) sort: MdSort;
  @ViewChild('filter') filter: ElementRef;

  constructor(
    private router: Router,
    private datatableService: DataTableService) {
  }

  ngOnInit() {
    this.exampleDatabase = new ExampleDatabase(this.datatableService, this.start, this.end, this.obra, this.st, this.folio, this.profesional);
    //this.getDataTable(this.start, this.end);
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.paginator, this.sort);
    console.log("[data-table, ngOnInit] ");

  }

  gotoDetail(foto: string): void {
    this.router.navigate(['/detail', foto]);
  }

  isAllSelected(): boolean {
    if (!this.dataSource) { return false; }
    if (this.selection.isEmpty()) { return false; }

    if (this.filter.nativeElement.value) {
      return this.selection.selected.length == this.dataSource.renderedData.length;
    } else {
      return this.selection.selected.length == this.exampleDatabase.data.length;
    }
  }

  masterToggle() {
    if (!this.dataSource) { return; }

    if (this.isAllSelected()) {
      this.selection.clear();
    } else if (this.filter.nativeElement.value) {
      this.dataSource.renderedData.forEach(data => this.selection.select(data.id));
    } else {
      this.exampleDatabase.data.forEach(data => this.selection.select(data.id));
    }
  }
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase implements OnInit {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<DataTable[]> = new BehaviorSubject<DataTable[]>([]);
  get data(): DataTable[] { return this.dataChange.value; }
  photos: DataTable[];
  s: string;
  e: string;
  o: string;
  st: string;
  f: string;
  p: string;
  ngOnInit() {
    console.log("ngOnInit ExampleDatabase");
    if (!this.o)
      this.o = "";
    if (!this.st)
      this.st = "";
    if (!this.f)
      this.f = "";
    if (!this.p)
      this.p = "";
    this.getDataTable(this.s, this.e, this.o, this.st, this.f, this.p);
  }
  constructor(private datatableService: DataTableService, start: string, end: string, obra: string, st: string, folio: string, profesional: string) {
    this.s = start;
    this.e = end;
    this.o = obra;
    this.st = st;
    this.f = folio;
    this.p = profesional;
    console.log("[data-table, constructor] ", this.s, this.e, this.o, this.st, this.f, this.p);
    this.ngOnInit();
  }

  //getDataTable call dataTableService with two dates
  getDataTable(start: string, end: string, obra: string, st: string, folio: string, profesional: string): void {
    this.datatableService.getData(start, end, obra, st, folio, profesional).then(photos => {
      //this.dataChange = photos;
      for (let i = 0; i < photos.length; i++) {
        const copiedData = this.data.slice();
        photos[i].id = (i + 1).toString();
        copiedData.push(photos[i]);
        this.dataChange.next(copiedData);
      }
    })

  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  _filterChange = new BehaviorSubject('');
  get filter(): string { return this._filterChange.value; }
  set filter(filter: string) { this._filterChange.next(filter); }

  filteredData: DataTable[] = [];
  renderedData: DataTable[] = [];

  constructor(private _exampleDatabase: ExampleDatabase,
    private _paginator: MdPaginator,
    private _sort: MdSort) {
    super();
    // Reset to the first page when the user changes the filter.
    this._filterChange.subscribe(() => this._paginator.pageIndex = 0);
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<DataTable[]> {
    // Listen for any changes in the base data, sorting, filtering, or pagination
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.mdSortChange,
      this._filterChange,
      this._paginator.page,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      // Filter data
      this.filteredData = this._exampleDatabase.data.slice().filter((item: DataTable) => {
        let searchStr = (item.obra).toLowerCase();
        return searchStr.indexOf(this.filter.toLowerCase()) != -1;
      });

      // Sort filtered data
      const sortedData = this.sortData(this.filteredData.slice());

      // Grab the page's slice of the filtered sorted data.
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      this.renderedData = sortedData.splice(startIndex, this._paginator.pageSize);
      return this.renderedData;
    });
  }

  disconnect() { }

  /** Returns a sorted copy of the database data. */
  sortData(data: DataTable[]): DataTable[] {
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number | string | Date = '';
      let propertyB: number | string | Date = '';

      switch (this._sort.active) {
        case 'id': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'foto': [propertyA, propertyB] = [a.foto, b.foto]; break;
        case 'obra': [propertyA, propertyB] = [a.obra, b.obra]; break;
        case 'st': [propertyA, propertyB] = [a.st, b.st]; break;
        case 'folio': [propertyA, propertyB] = [a.folio, b.folio]; break;
        case 'profesional': [propertyA, propertyB] = [a.profesional, b.profesional]; break;
        case 'date': [propertyA, propertyB] = [a.date, b.date]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}

This is my service
import { Injectable } from '@angular/core';
import { Headers, RequestOptions, RequestMethod, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import { DataTable } from './data-table';

@Injectable()
export class DataTableService {
  private Url = 'http://127.0.0.1:8000';  // URL to web api
  private headers = new Headers({ 'Content-Type': 'application/json' });
  constructor(private http: Http) { }

  printRequest(url, headers, options): void {
    console.log("[url request] ", url);
    console.log("[headers] ", this.headers);
    console.log("[options] ", options);
  }

  getPhoto(id: string): string {
    return id;
  }

  getData(start: string, end: string, obra: string, st: string, folio: string, profesional: string): Promise<DataTable[]> {
    const url = `${this.Url}/server/datatable/`;
    console.log("url -> ", url);
    const options = new RequestOptions({
      headers: this.headers,
    });

    const body = JSON.stringify({ start, end, obra, st, folio, profesional })
    return this.http
      .post(url, body, options)
      .toPromise()
      .then(response => response.json().data as DataTable[])
      .catch(this.handleError);
  }
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}


text:
Q: .Net core 2.2 to 3.x migration: Url.Action generate wrong URL with endpoint routing deactivated I'm working on migrating a webapp from .Net core 2.2 to 3.1. In it, We have extensive use of attribute routing and Url.Action in both controllers and views (we don't use any asp tag). Because we would need to change a lot to use endpoint routing, I deactivated it using EnableEndpointRouting = false.
Problem is: Url.Action is generating wrong urls that ends up in 404! It ignores completely the attribute routing when generating the url and I don't understand why.
If anyone could help me understand what I'm doing wrong and how to look properly at this thing, it would be much appreciated.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
    // First I tried this, using
    services.AddControllersWithViews(options => options.EnableEndpointRouting = false)
                .AddRazorRuntimeCompilation()
                .AddNewtonsoftJson(options =>
                {
                    // Use the default property (Pascal) casing
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                });
    services.AddRazorPages()
                .AddMvcOptions(options => options.EnableEndpointRouting = false)
                .AddRazorRuntimeCompilation();

    // Then I tried this
    services
                .AddMvc(options => options.EnableEndpointRouting = false)
                .AddRazorRuntimeCompilation()
                .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();
    app.UseAuthorization();

    // I remove all app.UseRouting and app.UseEndpoints to keep only mvc
    app.UseMvc(
                routes =>
                {
                    routes.MapRoute(name: "default", template: "controller=Home}/{action=Index}/{id?}");

                });
}

Then I have the following controller with attribute routing:
    [Authorize(AuthPermissions.HardLogin)]
    [Route("maker/cards")]
    public class CreditCardsController : Controller
    {

        [Route("")]
        [HttpGet]
        public async Task<IActionResult> IndexAsync()
        {//Do stuff}
    }

To  access this one, it needs to go through ~/maker/cards, easy.
And then in some cshtml page, Using the following to link to the previous action:
// Existing link

    Stored cards

// Tried this as well
Stored cards asp-action

Problem both generate the following url ~/creditcards/indexasync, which is not the one configure in the routing! In 2.2, the same Url.Action generates the expected url /maker/cards.
With EnableEndpointRouting = false, I would expect the UrlHelper to use the attribute routing to generate the link, but it doesn't. What am I missing here?
fun fact: if I use the Url.RouteUrl and add the route name to the controller, it generates it properly!

    Manage subscriptions (@(Model.User.SubscriptionsCount))

=> Generates '/maker/cards'

Edit: after more than a day spent on it and only after an hour after posting here, I found the problem. In 3.0, they introduced a new functionality that ignores Async in action name, which forces you to use the name without async when generating a link.
https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio#async-suffix-removal-from-controller-action-names
So there was 2 solutions:

*

*I could transform @Url.Action("IndexAsync", "CreditCards") to @Url.Action("Index", "CreditCards") and it works, but I have to update it everywhere in the app. (funny enough, with that format, visual studio does not recognises the endpoint and tags it as unknown)

*Or there is an option to deactivate this option app wise by adding the following options in the ConfigureService options.SuppressAsyncSuffixInActionNames = false;. Which is what I ended up doing.

Working solution is as follow now:
Startup.cs
ConfigureServices:
           services.AddControllersWithViews(options =>
                {
                    options.EnableEndpointRouting = false;
                    options.SuppressAsyncSuffixInActionNames = false;
                })
                .AddRazorRuntimeCompilation()
                .AddNewtonsoftJson(options =>
                {
                    // Use the default property (Pascal) casing
                    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                });

Configure:
        app.UseMvc(
                routes =>
                {
                    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
                });

(btw you can replace the above by app.UseMvcWithDefaultRoute(); now)

I now have the same behaviour as before bumping to 3.1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Context and meaning of " cloak myself in the mantle of Voltaire ..."? This is from an old story about a publisher backing off from publishing a book after having made an initial contract with the author, because of some of the latter's controversial views. Chris Hitchens debated this on Charlie Rose. Towards the end Hitchens makes this statement..
" I dont want to cloak myself in the mantle of Voltaire, but it seems to me a perfectly simple point that it is not .....  upon me to defend anything Irving says or hypothesizes in order for me to defend, not his right to say it so much as my right to read it....".
Could someone explain how Voltaire is related to this view??
Also what is such a use of language called, allegory?
https://www.youtube.com/watch?v=1dWxklSFPEA

A: The phrase you quote in your title is a metaphor meaning 'use Voltaire's words to articulate or defend my position' complete with an allusion, an explicit reference to Voltaire.
Later comes another allusion, much more indirect, to this quote from Voltaire: "I may not agree with what you have to say, but I will defend to the death your right to say it."
The initial metaphor, as is later revealed, is wrapped in a proslepsis, a form of paralipsis, "stating and drawing attention to something in the very act of pretending to pass it over".
Altogether, then, what you've cited in your question is an anamnesis, a referral to authority (usually by allusion). In this case, the authority referred to is Voltaire, and specifically the quote from Voltaire.
For definitions of all the terms I've italicized, see The Forest of Rhetoric. A search feature is available, central top. Many more rhetorical elements are exampled in the quote you've provided.
So, your final questions:

*

*The quote from Voltaire is related to the view expressed rather remotely, because what the view expressed by the quote becomes has only a remote connection with what Voltaire actually said.

*The language used, more properly the way the language is used, is highly figurative. I've mentioned some (only some) of the figures used in italics, above.


text:
Q: C++ pointer pointing to const object that was never made const I have a set of Students and an iterator which finds a specific student which I then need to change. The problem is, when I go to change the object the pointer points to, it says the object is const. I'm not sure why this is, as I do not think I ever explicitly make the objects constant. I am relatively new to C++, so I may be doing something to make the Student objects const accidentally.
Here is the main funcion
set<Student> students;
ifstream file(*somefilename*);
while (!file.is_open())
{
    cout << filename << endl;
    cout << "Could not open file. Enter new filename: ";
    cin >> filename;
    file.open(filename);
}

while (!file.eof()) {
    string temp = "";
    string name;
    int regNo;
    if (file.eof())break;
    for (int i = 0; i < 3; i++) {
        if (i == 0)
            file >> regNo;
        else {
            file >> temp;
            name += temp;
        }
    }
    cout << "For loop done" << endl;
    students.insert(Student(name, regNo));
}

file.close();

file.open("ex1/marks.txt");

while(!file.eof()){
    int regNo;
    string module;
    int mark;
    file >> regNo;
    Student tempStud("",regNo);
    file >> module;
    file >> mark;
    set<Student>::iterator it = students.find(tempStud);
    if (it != students.end()) {
        **it->addMark(module, mark);**//here's the problem code
    }
}

file.close();

for (set<Student>::iterator it = students.begin(); it != students.end(); it++)
    cout << *it << endl;

cin.get();}

And here is the header file for the Student class
    public:
       Student(const string &name, int regNo);

    int getRegNo() const;

    void addMark(string& module, float mark);

    float getMark(const string &module) const;

    float getMin() const;

    float getMax() const;

    float getAvg() const;

    bool operator <(const Student& s2) const;

    bool operator >(const Student& s2);

    bool operator ==(const Student& s2);

private:
    int regNo;
    map<string, float> marks;  // keys are modules, values are marks in range 0.0 to 100.0
friend ostream& operator<<(ostream &str, const Student &s);

A: You are not doing anything to make the Student objects const accidentally.

The Problem
Here is your problem: (C++ documentation)

All iterators in a set point to const elements.

In other words, a set will not allow you to modify elements through an iterator, even if the elements are not technically const otherwise.
So why is set defined that way? (source)

The elements of the set will be in sorted order. If you are allowed to
  modify an element, then this sorting order can not be maintained.
  Hence you can not modify the item.

The Solution
You have one of three options.
1) Don't use set
Unless there is a very good (and very specific) reason you need to use set, then don't.  Use map instead.  It won't have this same restriction.
2) Remove and Insert
Remove the old element and insert the "updated" version of that element.  This takes O(1) time.  (example)
3) Use mutable
If the data members that you want to modify are not involved in the natural ordering of the object type, then declare them to be mutable.  This is equivalent to saying that their value does not change the identity of a logically const instance of the class.  This will let you mutate those data members even in a const object or iterator  (example)


text:
Q: Internet is not working on VM I have two NIC configured between two servers one to connect server with internet and other is for fast internal connectivity of the servers each server have three VM's each
i have configured both the NIC on all VM but IP is assign by DHCP on 172.26.43.1 VLAN which is connected to Internet but 10.10.10.1 is IP i am using for private network (only for internal connectivity between all the other VM)  with no DHCP so i am assigning static ip
when i assign static IP on VM from here
internet stops working on my VM
configuration on VM is
/etc/network/interfaces
auto eth1
iface eth1 inet static
address 10.10.10.17
netmask 255.255.255.0
gateway 10.10.10.11

10.10.10.11 is the ip of the server on which VM is running
ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:e8:2e:19
          inet addr:172.26.43.88  Bcast:172.26.43.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fee8:2e19/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:55831 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1945 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:9126338 (9.1 MB)  TX bytes:158629 (158.6 KB)

eth1      Link encap:Ethernet  HWaddr 08:00:27:68:bd:91
          inet addr:10.10.10.17  Bcast:10.10.10.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe68:bd91/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:468 (468.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:16 errors:0 dropped:0 overruns:0 frame:0
          TX packets:16 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1184 (1.1 KB)  TX bytes:1184 (1.1 KB)

route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.26.43.1     0.0.0.0         UG    100    0        0 eth0
10.10.10.0      10.10.10.11     255.255.255.0   U     0      0        0 eth1
172.26.43.0     *               255.255.255.0   U     0      0        0 eth0


text:
Q: ASP.NET MVC 2 Editor Templates The following link explains editor templates:  http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx
What I want to know is if I have a editor template for a drop down, how is the initial value set?
I have a drop down and I use the Html.EditorFor(c => c.Country, "CountryDropDown")
But it always defaults to the first selected item in the list... any ideas?

A: I would think, you need to create a viewdata, or create a viewmodel to include the select list passing to the dropdown list. For example, in your controller action, you should do sth like this:
    //get your item for editing here i.e named itemToEdit
    //get your country collection here

      ArrayList countryList=New ArrayList;
       foreach (Country c In YourCountryCollection)
{          countryList.Add(New With {.Item = c.CountryName, .value = c.CountryID})
}
    Viewdata("CountryList")=New SelectList(countryList, "Value", "Item", itemToEdit.countryID)}

Now in your view, instead of using html.editorfor, you should uuse the following:
 Html.Editor("CountryLis", "CountryDropDown")
This should set your dropdownlist with the selected value.
Hope this help.


text:
Q: How are text messages added to html messages I'm using cURL to send Mailgun messages. One of the cURL arguments is -F template='mytemplate' \, which uses a template set-up on Mailgun.  How do I add a text version of the message?

A: According to the MailGun API docs, you can request a text-only version by including the parameter -F t:text='yes' as part of your cURL request.
This will change the MIME Content-Type from text/html to multipart/alternative which most mail clients will render first as HTML, falling back to text if there's a problem. It's worth noting however, that this leaves the text interpretation up to MailGun meaning that you don't get any say in how the text is composed.
I've tested this a few times and ran into minimal issues, but if you want to ensure that your text comes through as intended, you're better off composing your own multipart/alternative MIME message and passing that to MailGun using the /messages.mime API endpoint.


text:
Q: Is it possible to have a type class for both constants and expressions in DSL? Suppose, I have a DSL with computations in LangL r a. I might want to have functions work both with constants (0 :: Int, "lala" :: String) and DSL expressions (LangL r a). So, I implement a type class. However, any way I try to implement it, I stumble into problems.
Here's a minimal example of a problem when using type families:
{-# LANGUAGE DeriveAnyClass        #-}
{-# LANGUAGE DeriveFunctor         #-}
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving    #-}
{-# LANGUAGE TypeFamilies          #-}

data LangL r a = LangL a
deriving instance Functor (LangL r)
deriving instance Applicative (LangL r)

class DSLEntity r a where
  type ValueOf a
  entityValue :: a -> LangL r (ValueOf a)

instance DSLEntity r (LangL r a) where
  type ValueOf (LangL r a) = a
  entityValue = id

instance DSLEntity r Int where
  type ValueOf Int = Int
  entityValue = pure

foo :: LangL r Int -> LangL r Int
foo m = entityValue (entityValue m)

GHC gives the following output:
    • Ambiguous type variable 'r0' arising from a use of 'entityValue'
      prevents the constraint '(DSLEntity
                                  r (LangL r0 Int))' from being solved.
      Relevant bindings include
        m :: LangL r Int (bound at temp.hs:25:5)
        foo :: LangL r Int -> LangL r Int
          (bound at temp.hs:25:1)
      Probable fix: use a type annotation to specify what 'r0' should be.
      These potential instance exist:
        instance DSLEntity r (LangL r a)
          -- Defined at temp.hs:16:10
    • In the expression: entityValue (entityValue m)
      In an equation for 'foo': foo m = entityValue (entityValue m)
   |
temp.hs:25:22-34: error: …
    • Ambiguous type variable 'r0' arising from a use of 'entityValue'
      prevents the constraint '(DSLEntity
                                  r0 (LangL r Int))' from being solved.
      Relevant bindings include
        m :: LangL r Int (bound at temp.hs:25:5)
        foo :: LangL r Int -> LangL r Int
          (bound at temp.hs:25:1)
      Probable fix: use a type annotation to specify what 'r0' should be.
      These potential instance exist:
        instance DSLEntity r (LangL r a)
          -- Defined at /temp.hs:16:10
    • In the first argument of 'entityValue', namely '(entityValue m)'
      In the expression: entityValue (entityValue m)
      In an equation for 'foo': foo m = entityValue (entityValue m)
   |

The problem is clear. There is no dependency between r parameter of LangL r a and r parameter of DSLEntity. However, we cannot add such a dependency because for Int instance it actually does not exist.
I'm rather confused and would like to know if it's possible to accomplish what I'm trying to do. If not, why?

A: You can use:
instance (r ~ r') => DSLEntity r' (LangL r a) where

instead of:
instance DSLEntity r (LangL r a) where

It's a little arcane what this actually does.
Your original instance declaration says that GHC can only use that instance when it can prove that the r in LangL r a is the same type in the argument and in the result of entityValue. But entityValue :: a -> LangL r (ValueOf a), so any type at all can be used as the input (and require GHC to go looking for a matching instance). In particular, any LangL r0 a can appear as the input, even for non-matching r. So in entityValue (entityValue m), the first one could be used at any r0, and the second will convert it back to the r used in the type of foo. Since GHC can't establish which r you're talking about in the middle, you get the problem that the ambiguous type variable prevents it from knowing which DSLEntity instance it should choose to resolve the constraint.
Whereas instance (r ~ r') => DSLEntity r' (LangL r a) says that this instance applies for any types r and r', but using it adds the constraint that r and r' are equal. This sounds the same as just writing instance DSLEntity r (LangL r a), but it actually isn't because of the rule that GHC doesn't consider constraints when choosing instances, only afterwards. Now GHC doesn't need to prove that r and r' are equal in order to choose this instance, it will choose the instance any time the second parameter of a DSLEntity constraint looks like LangL _ _, and then after that it will know that in order to typecheck the constraint r ~ r' must hold, so it will go ahead and assume that (if it's possible; otherwise you get a type error).
You can see the difference pretty clearly by looking at the type of entityValue . entityValue. With your original instance, you get:
λ :t entityValue . entityValue
entityValue . entityValue
  :: (DSLEntity r1 (LangL r2 (ValueOf a)), DSLEntity r2 a) =>
     a -> LangL r1 (ValueOf a)

And with the new instance you get this:
λ :t entityValue . entityValue
entityValue . entityValue
  :: DSLEntity r a => a -> LangL r (ValueOf a)

A: I think you just need to give GHC a little help with the intermediate type:
{-# LANGUAGE ScopedTypeVariables   #-}

foo :: forall r. LangL r Int -> LangL r Int
foo m = entityValue (entityValue m :: LangL r Int)


text:
Q: Removing license I'm nearing the end of my master's thesis, which was done in collaboration with a local company. I used their computers during the work, but they could not provide me with a Visual Studio licence, thus I used my own MSDN Academic Alliance licence. Now that I'm leaving the company, I need to remove the licence. Does a uninstallation completly remove the licence? Is there a way of just removing the licence without uninstallation?
It's Visual Studio 2010 Professional edition, installed on a Windows XP computer.

A: MSDNAA FAQ:

Q: Does the license (or "key") permanently unlock the software?
A: No - the key allows you to install the software once. If you need to re-install the software, you will need to contact the PA (Program Administrator) at your school. Your PA's contact email information can be found in the support page. To view this information, please click on the Support button above.


text:
Q: Alguien sabe como obtener el carácter del medio Alguien sabe como obtener el caracter del medio de una cadena por ejemplo de un nombre :JUANA
Y EL CARACTER DEL MEDIO SERIA LA :  A

A: Deberias intentar por tu cuenta antes de pedir la solucion y sino sale pones el código de lo que hayas intentado.
Cada cadena tienen una propiedad llamada Length, que es la longitud de una cadena.
Ejemplo :
J u a n a
0 1 2 3 4

Considerando la longitud de la cadena deberias hacer una division.
Con esto deberias solucionar tu problema.


text:
Q: enter line to an object Hello in R how could I write a function which takes as an input a number at which aline should be entered into an existing object
matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)

Each vector should now be entered into the matrix into the matrix at row 3 (so it should be the new co row 3 .  The other rows would just be a pushed so the old row 3 is row 4 then

A: Here's a function I wrote for that a while back.  I've been using it.
#Christopher Barry, 28/01/2015

insertRows <- function(DF, mtx, row){
  if(is.vector(mtx)){
    mtx <- matrix(mtx, 1, length(mtx), byrow=T)
  }
  nrow0 <- nrow(DF)
  nrows <- nrow(mtx)
  ncols <- ncol(DF) #should be same as for mtx
  if(is.matrix(DF)){DF <- rbind(DF, matrix(0, nrows, ncols))}
  if(nrow0 >= row){
    DF[seq(row+nrows,nrow0+nrows),] <- DF[seq(row,nrow0),]
    DF[row:(row+nrows-1),] <- mtx
  }else{
    DF[seq(nrow0+1,nrow0+nrows),] <- mtx
  }
  return (DF)
}

Edited to work for matrices and data frames.

A: One way of doing this can be :
aa<- matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)
rbind(aa[1:2,],x,aa[3:5,])

A similar solution ot this, actually:
R: Insert a vector as a row in data.frame


text:
Q: Given two numbers n1 and n2 as input, return an array containing all the primes between n1 and n2 (Note that both n1 and n2 can be included in the array if they are prime) Also, the primes in the array need to be in ascending order.
public int[] getPrimes(int start,int stop){

      int flag=0;
      int k=0;
      int arr[] =new int[stop-start];

      if(start==1){
      for(int i=start+1; i<=stop; i++){
      flag=0;
      for(int j=2; j<=i/2; j++)
      {
        if(i%j==0)
        {
          flag=1;
          break;
        }
      }
      if(flag==0){
      arr[k]=i;
      k++;
      }

      }
    }

      else{
      for(int i=start; i<=stop; i++){
      flag=0;
      for(int j=2; j<=i/2; j++)
      {
        if(i%j==0)
        {
          flag=1;
          break;
        }
      }
      if(flag==0){
      arr[k]=i;
      k++;
      if(k+1==0)
      break;
      }

      }
    }
    return arr;

   }

Testcase Parameters
'1' '20'

Testcase Expected Answer

{2,3,5,7,11,13,17,19}

My Answer

{2,3,5,7,11,13,17,19,0,0,0,0,0,0,0,0,0,0,0}

My Answer could not limit array,any suggestion please? also if can optimize my code without using any array function?

A: In this line: int arr[] =new int[stop-start]; you are giving the output array a size of 19 (in your example), but the problem is that you don't know how many primes there are between the 2 indexes.
The default value in an array of Int's is 0, so all of the unused index's in the array are assigned to this value.
My advise would be to instead use an ArrayList<Integer> instead of a standard array, because it's size expands as and when necessary.

A: try returning trimmed array:
return Arrays.copyOf(arr, k);

instead of
return arr;

A:
    int []arr = new int[num2-num1];//an array of relatively a larger size
            for(int i=num1;i<=num2;i++){
                for(int j=2;j<i;j++){
                     result = i%j;//this will calculate the modulus
                     if(result==0)//yes then the number is composite
                        break;
                }
               //this says that loop has executed i-1 times but factor not found
            if(result!=0){
                    arr[count] = i;
                    count++;
                }
            }

You should have added some comment for us to understand your code, nevertheless try this logic which will divide any number from 2 to (number-1) if it is prime then it must got to be divided
Now to solve your printing problem restrict your array from (0 to count) or till
the array has value and print the array.


text:
Q: Delete object using v3 ASK PHP SDK I'm having trouble logging in:
require 'aws-autoloader.php';

$client = new Aws\S3\S3Client([
    'version' => 'latest',
    'region'  => REGION,
    'endpoint'    => HOST,
        'credentials' => [
        'key'      => AWS_KEY,
        'secret'   => AWS_SECRET_KEY,
    ],
]);

$result = $client->deleteObject(array(
'Bucket' => $BucketName,
'Key'    => $FileKey,
));

The $client object is never created. If I run it without the credentials it creates the $client. The Amazon docs say this is how to hardcode credentials. The docs have varying examples from previous sdk's which is really confusing. What's the correct way for deleting an object from V3? I'm not using composer if that matters.
UPDATE
The code works but the endpoint value is causing issues. if I use http://bucket.s3.amazonaws.com/ as the host it tries to fetch http://bucket.bucket.s3.amazonaws.com/key and throws a 404 not found, if i change it to http://s3.amazonaws.com it doesn't work at all, if I remove the host it tries fetching http://s3.amazonaws.com/bucket/key which gives a 204 status message and the deletemarker is still false and the file isn't deleted. I dunno how to make deleteObject create the correct effectiveuri in the result. I dunno what the 204 status means.
SOLUTION
The code works fine without the endpoint field. I hadn't put DELETE as allowed in the S3 CORRS. It works now.
require 'aws-autoloader.php';

$client = new Aws\S3\S3Client([
    'version' => 'latest',
    'region'  => REGION,
        'credentials' => [
        'key'      => AWS_KEY,
        'secret'   => AWS_SECRET_KEY,
    ],
]);

$result = $client->deleteObject(array(
'Bucket' => $BucketName,
'Key'    => $FileKey,
));


text:
Q: Optimization Routine in Fortran 90 I am doing (trying to do) numerical optimization in Fortran 90, on a Windows 7 machine with the gfortran compiler. I have a function, pre-written by someone else, which returns the loglikelihood of a function, given a large set of parameters (about 60 parameters in total) passed in. I am trying to replicate someone's results, so I know the final parameter values, but I was to try and re-estimate them and, eventually, extend their model and use different data. I've been trying the uobyqa.f90 routine available here, which has not been particularly successful thus far.
My questions are: First, for an optimization problem with a large number of parameters (over 60), can anyone suggest the best freely available routine? Derivatives are not available, and would be costly to estimate numerically, hence trying the uobyqa routine first. Also, would implementing parallelization aid significantly in solving this problem? And, if so, could anyone suggest an optimization routine that already implements parallelization using openmp?
Thanks!

A: I don't have a good suggestion for a specific optimization strategy, but the NLopt package has a few derivative-free optimizers that can handle larger numbers of variables. Worth checking out. I've found the Fortran interface to be very easy to use.

A: Do a regular (published academic) literature search on this question first.
Maybe try including "LAPACK" with your other search terms (e.g. "optimization", "uobyqa", etc) to see relavant work by other parties.


text:
Q: Find $\int\arcsin(\sqrt{x})dx$
Find $\displaystyle\int\arcsin(\sqrt{x})dx$

My Attempt
Put $y=\sqrt{x}\implies dy=\frac{1}{2\sqrt{x}}dx\implies dx=2ydx$
$$
\int\arcsin(\sqrt{x})dx=2\int \arcsin(y)\,y\,dy=2\bigg[\frac{y^2}{2}\arcsin(y)-\int\frac{1}{\sqrt{1-y^2}}\frac{y^2}{2}dy\bigg]\\
=y^2\arcsin(y)-\int\frac{y^2}{\sqrt{1-y^2}}dy.
$$
How do I proceed further and find the solution or is there any easier way ?

A: Hint. Note that
$$-\int\frac{y^2}{\sqrt{1-y^2}}\,dy=\int\frac{1-y^2}{\sqrt{1-y^2}}\,dy-\int\frac{dy}{\sqrt{1-y^2}}=\int\sqrt{1-y^2}\,dy-\arcsin(y).$$

A: I would proceed as follows:\begin{align}\int\frac{y^2}{\sqrt{1-y^2}}\,\mathrm dy&=\int y\frac y{\sqrt{1-y^2}}\,\mathrm dy\\&=-y\sqrt{1-y^2}+\int\sqrt{1-y^2}\,\mathrm dy.\end{align}

A: $$\int\frac{-y^2}{\sqrt{1-y^2}}dy=\int\frac{1-y^2-1}{\sqrt{1-y^2}}dy
=\int\frac{1-y^2}{\sqrt{1-y^2}}dy-\int\frac{1}{\sqrt{1-y^2}}dy=$$ $$=
\int\sqrt{1-y^2}dy-\arcsin(y)=\left[y=\sin{t}, dy=\cos{t}\ dt\right]=\int\cos^2{t}dt-\arcsin(y)=$$ $$=\frac12\int(1+\cos{2t})dt-\arcsin(y)=\frac12\left[t+\frac12\sin{2t}\right]_{t=\arcsin{y}}-\arcsin(y)+C=$$ $$=\frac12\arcsin{y}+\frac14\sin{(2\arcsin{y})}-\arcsin(y)+C=$$ $$=-\frac12\arcsin{y}+\frac12\sin{(\arcsin{y})}\cos{(\arcsin{y})}+C=$$
$$=-\frac12\arcsin{y}+\frac12y\sqrt{1-y^2}+C$$

A: Hint. Notice that $\int\frac{1}{\sqrt{1-y^2}}\mathrm{d}y=\sin^{-1}(y)$, so you could try writing $y^2$ as $y^2-1+1$ and splitting into two integrals:
$$\int\frac{y^2}{\sqrt{1-y^2}}\mathrm{d}y=\int\left(\frac{y^2-1}{\sqrt{1-y^2}}+\frac{1}{\sqrt{1-y^2}}\right)\mathrm{d}y\\=\int\left (\frac{1}{\sqrt{1-y^2}}-\sqrt{1-y^2}\right )\mathrm{d}y=\int\frac{1}{\sqrt{1-y^2}} \mathrm{d}y-\int\sqrt{1-y^2} \mathrm{d}y$$
Solving $\int\sqrt{1-y^2} \mathrm{d}y$ can be made via trigonometric substitution, setting $y=\sin u$.

A: Note that
$$
d/dx((x - 1/2) \sin^{-1}(\sqrt x)) = \frac{x - 1/2}{2 \sqrt{x(1 - x)} } + \sin^{-1}(\sqrt x )
$$
So you can easily integrate
$$
\int\sin^{-1}\sqrt{x}dx \\
= (x - 1/2) \sin^{-1}(\sqrt x) - \int \frac{x - 1/2}{2 \sqrt{x(1 - x)} } dx \\
= (x - 1/2) \sin^{-1}(\sqrt x) + \frac{ \sqrt{x(1 - x)}}{2}
$$

A: By parts directly:
$$\begin{cases}u=\arcsin\sqrt x,&u'=\frac1{2\sqrt x\sqrt{1-x}}\\{}\\
v'=1,&v=x\end{cases}\;\;\implies \int\arcsin\sqrt x\,dx=x\arcsin\sqrt x-\frac12\int\sqrt\frac x{1-x}\,dx$$
and now substitute
$$\;u^2=\frac x{1-x}\implies x(-u^2-1)=-u^2\implies x=\frac{u^2}{u^2+1}=1-\frac1{1+u^2}\implies$$
$$ dx=\frac{2u}{(1+u^2)^2}\;$$
and from here your integrals equals
$$x\arcsin\sqrt x-\int\frac{u^2}{(1+u^2)^2}\,du=x\arcsin x-\frac12\left(\arctan u-\frac u{1+u^2}\right)$$
and now go back to $\;x\;$ and etc.


text:
Q: Calculate VWAP using JavaScript I have this Java code which I would like to rewrite to JavaScript:
package example;

import java.util.List;

public class Tain {

    public static void main(String[] args) {

    }

    private class PriceData {

        private double volume;
        private double price;

        public double getVolume() {
            return volume;
        }

        public void setVolume(double volume) {
            this.volume = volume;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }
    }

    private double calculateBaseValueVwap(List<PriceData> side, double positionStep) {
        double cumSum = 0d;
        double totalVolume = 0d;
        double amountLeft = positionStep;
        for(PriceData level : side) {
            if(totalVolume >= positionStep || amountLeft <= 0) {
                break;
            }
            double amountForPriceLevel = 0d;
            if(amountLeft > level.getVolume()) {
                amountForPriceLevel = level.getVolume();
                cumSum += level.getPrice() * level.getVolume();
                totalVolume += level.getVolume();
            }
            else {
                amountForPriceLevel = level.getVolume() - amountLeft;
                cumSum += level.getPrice() * amountForPriceLevel;
                totalVolume += amountForPriceLevel;
            }
            amountLeft -= amountForPriceLevel;
        }
        return cumSum / totalVolume;
    }

}

I tried this:
class Tain
{
    static
    main(args)
    {}
    class PriceData
    {
        #volume = 0.0;
        #price = 0.0;
        getVolume()
        {
            return this.#volume;
        }
        setVolume(volume)
        {
            this.volume = volume;
        }
        getPrice()
        {
            return this.#price;
        }
        setPrice(price)
        {
            this.price = price;
        }
    }
    calculateBaseValueVwap(side, positionStep)
    {
        var cumSum = 0.0;
        var totalVolume = 0.0;
        var amountLeft = positionStep;
        for (const level of side)
        {
            if (totalVolume >= positionStep || amountLeft <= 0)
            {
                break;
            }
            var amountForPriceLevel = 0.0;
            if (amountLeft > level.getVolume())
            {
                amountForPriceLevel = level.getVolume();
                cumSum += level.getPrice() * level.getVolume();
                totalVolume += level.getVolume();
            }
            else
            {
                amountForPriceLevel = level.getVolume() - amountLeft;
                cumSum += level.getPrice() * amountForPriceLevel;
                totalVolume += amountForPriceLevel;
            }
            amountLeft -= amountForPriceLevel;
        }
        return cumSum / totalVolume;
    }
}
Tain.main([]);

It's not clear to me how to rewrite the Java Object PriceData and send it as a list in JavaScript. Can you guide me what is the proper way to implement this in JavaScript?

A: Probably your problem has to do with the definition of PriceData as an inner class of Tain. AFAIK there is not a clear, if possible, way to define a nested class even in modern Javascript versions.
As pointed out as well in other answers for the same reason, you can create an independent PriceData class: honestly I think it will be the best option.
As an alternative, another approach you could try would be defining PriceData as static. Please, see the following code:
class Tain
{
    static main(args) {}

    static PriceData = class {
        #volume = 0.0;
        #price = 0.0;
        getVolume(){
            return this.#volume;
        }
        setVolume(volume){
            this.volume = volume;
        }
        getPrice(){
            return this.#price;
        }
        setPrice(price){
            this.price = price;
        }
    }

    //...
}

It will allow you to use PriceData like this:
const pa = new Tain.PriceData();
pa.setPrice(12.4);
pa.setVolume(200);
const pb = new Tain.PriceData();
pb.setPrice(20.4);
pb.setVolume(100);

In Javascript there is not an explicit concept for List like in Java, you need to create an array that will contain these objects to pass that information to the main method:
const prices = [pa, pb];

Then you can test your Tain main method with something like - I assume, as it is unclear in the question:
Tain.main(prices, 100);

Please, pay attention to the definition of static methods in Javascript, they are conceived to handle stuff that, although defined in a class, it is not directly related to instances of that class. I am saying this because, if, for instance, in your main method you are supposed to use calculateBaseValueVwap then a better approach will be to directly define calculateBaseValueVwap as static instead and use just that method. In Java you can define a static main method that will be used to run your application, in Javascript there is not such a need.
Although you can certainly use classes for this task, one simpler approach could be the use of functions.
Let's first define Tain:
Tain = function() {

    this.calculateBaseValueVwap = function(side, positionStep) {
        let cumSum = 0.0;
        let totalVolume = 0.0;
        let amountLeft = positionStep;
        for (let i = 0; i < side.length; i++) {
            level = side[i];
            if(totalVolume >= positionStep || amountLeft <= 0) {
                break;
            }
            let amountForPriceLevel = 0.0;
            if(amountLeft > level.volume) {
                amountForPriceLevel = level.volume;
                cumSum += level.price * level.volume;
                totalVolume += level.volume;
            }
            else {
                amountForPriceLevel = level.volume - amountLeft;
                cumSum += level.price * amountForPriceLevel;
                totalVolume += amountForPriceLevel;
            }
            amountLeft -= amountForPriceLevel;
        }
        return cumSum / totalVolume;
    }
}

In order to being able to access PriceData, you can create a kind of class level function to represent that concept, for instance:
Tain.PriceData = function(volume, price) {
    this.volume = volume;
    this.price = price;
}

You can define getters and setters for the volume and price properties if required.
Please, be aware that if you could define PriceData as an independent function as well; you could even do not use a function to represent that concept but simple Javascript objects:
{
  price: 12.4,
  volume: 200
}

As stated before, it is unclear in your Java code how the main method is implemented but, for testing purposes, let's assume something like this:
Tain.main = function(side, positionStep) {
    const tain = new Tain();
    const baseValueVwap = tain.calculateBaseValueVwap(side, positionStep);
    console.log(`Base value vwap: ${baseValueVwap}`);
    return baseValueVwap;
}

Then, test the code in a similar way as defined above:
const pa = new Tain.PriceData(12.4, 200);
const pb = new Tain.PriceData(20.4, 100);
// Or, using directly objects
// const pa = { price: 12.4,  volume: 200 };
// const pb = { price: 20.4,  volume: 100 };

const prices = [pa, pb];
Tain.main(prices, 100);

The code could be improved with ES6 syntax and for sure in many ways, but it should work correctly.
If you have the opportunity, my advice would be using Javascript object notation for representing the PriceData and a single, independent function, calculateBaseValueVwap, defined somewhere - your HTML pages, your Javascript module, etcetera - that will be invoked directly in your code.

A: There isn't actually that much wrong with your code. You're simply nesting a class inside a class, which ES6 does not permit, and you have an extra ending curly brace.

class Tain {
    static main(args) {}
}

class PriceData {
    #volume = 0.0;
    #price = 0.0;
    getVolume() {
        return this.#volume;
    }
    setVolume(volume) {
        this.volume = volume;
    }
    getPrice() {
        return this.#price;
    }
    setPrice(price) {
        this.price = price;
    }
    calculateBaseValueVwap(side, positionStep) {
        var cumSum = 0.0;
        var totalVolume = 0.0;
        var amountLeft = positionStep;
        for (const level of side) {
            if (totalVolume >= positionStep || amountLeft <= 0) {
                break;
            }
            var amountForPriceLevel = 0.0;
            if (amountLeft > level.getVolume()) {
                amountForPriceLevel = level.getVolume();
                cumSum += level.getPrice() * level.getVolume();
                totalVolume += level.getVolume();
            } else {
                amountForPriceLevel = level.getVolume() - amountLeft;
                cumSum += level.getPrice() * amountForPriceLevel;
                totalVolume += amountForPriceLevel;
            }
            amountLeft -= amountForPriceLevel;
        }
        return cumSum / totalVolume;
    }
}

Tain.main([]);


text:
Q: Is there a way to reduce the amount of lines in this code? I made a code to filter a list of names based on certain conditions.. and wanted to see if I can reduce this further and eliminate redundancy in code. Here is my code:
names1 = ["Jane", "Jake", "Bradley", "Bill", "Betty", "Kara", "Kris", "Jil"]
names2 = ["George", "Kate", "Karen", "Kurt", "Greg", "Gary"]
selection_criteria = ["full_list", "four_characters", "three_characters",  "start_with_k", "start_with_z"]

def sublist (name_list, condition):
    return_list = []
    if condition == "full_list":
        return name_list
    if condition == "four_characters":
        for name in name_list:
            if len(name) == 4:
                return_list.append(name)
    if condition == "three_characters":
        for name in name_list:
            if len(name) == 3:
                return_list.append(name)
    if condition == "start_with_k":
        for name in name_list:
            if name[0] == 'K':
                return_list.append(name)
    if condition == "start_with_z":
        for name in name_list:
            if name[0] == 'Z':
                return_list.append(name)
    return return_list

for criteria in selection_criteria:
    print(sublist(names1, criteria))

for criteria in selection_criteria:
    print(sublist(names2, criteria))

A: In Python, if you find yourself interpreting a string as the name of a function to perform, you'd probably be better off just passing the function itself.  Your sublist() function could be simply replaced by the built-in filter() function (or, on Python 3, perhaps list(filter(...)) to get a list instead of a generator as the result).  Your list of possible criteria would become:
selection_criteria = [
    lambda n: True,  # or simply None instead of a lambda
    lambda n: len(n) == 4,
    lambda n: len(n) == 3,
    lambda n: n.startswith("K"),
    lambda n: n.startswith("Z")
]


text:
Q: Are there any synchronization issue when it's used two counters and one clock, all of them working in a different Thread? i need two counters to work like a chess clock. When the first one starts the second stops. When the second starts the fisrt one stop.
In parallel with these two counters i need another clock which never stops.
I am trying to do it. I created two counters and it works fine but when i create a new thread(3 Threads in total), which will run the clock, it causes some problem(increment both counters at the same time).
Does these problem have something related with  synchronization problem? Why does it run correctedly for 2 Threads but not for three?
//////////////////////////////// HOW THE OBJECTS ARE CREATED /////////////////////////

private Relogio relogioBranco, relogioPreto;
private RelogioGeral relogioGeral;

relogioBranco = new Relogio(relogioBrancoLabel);
relogioPreto = new Relogio(relogioPretoLabel);
relogioGeral= new RelogioGeral(relogioPretoLabel,menu);
new Thread(relogioBranco).start();
new Thread(relogioPreto).start();
new Thread(relogioGeral).start();

relogioBranco.rodarRelogio(false);
relogioPreto.rodarRelogio(false);
relogioGeral.rodarRelogio(true);

////////////////////////////////////// COUNTERS //////////////////////////////
// The clock will be used to autosave my game every 1 minute

package Janela;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JLabel;

public class Relogio implements Runnable, Serializable {

    private volatile AtomicInteger segundo, minuto, hora;
    private JLabel relogioLabel;
    private boolean relogioRodando;

    public Relogio(JLabel relogio) {
        segundo = new AtomicInteger();
        minuto =  new AtomicInteger();
        hora =  new AtomicInteger();

        minuto.set(0);
        hora.set(0);
        segundo.set(0);
        minuto.set(0);
        this.relogioLabel = relogio;
    }

    public void rodarRelogio(boolean rodar) {
        relogioRodando = rodar;

    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1000);
                if (relogioRodando) {
                    segundo.incrementAndGet();
                    if (segundo.intValue() == 60) {
                        segundo.set(0);
                        minuto.incrementAndGet();
                        if (minuto.intValue() == 60) {
                            minuto.set(0);
                            hora.incrementAndGet();
                            if (hora.intValue() == 24) {
                                segundo.set(0);
                                minuto.set(0);
                                hora.set(0);
                            }
                        }
                    }
                    String tempo = String.format("%02d:%02d:%02d", hora.intValue(), minuto.intValue(), segundo.intValue());
                    relogioLabel.setText(tempo);
                }
            }
        } catch (InterruptedException ie) {
            System.out.println("EXCEÇÃO INTERRUPTED EXCEPTION");
        }
    }
}

///////////////////////////////////////////// CLOCK ///////////////////////////////////

package Janela;

import MesaTabuleiro.ArrayPecas;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class RelogioGeral implements Runnable, Serializable {

private volatile AtomicInteger segundo, minuto, hora;
private final JLabel relogioLabel;
private boolean relogioRodando;

public RelogioGeral(JLabel relogio, Menu menu) {
    segundo = new AtomicInteger();
    minuto = new AtomicInteger();
    hora = new AtomicInteger();

    segundo.set(0);
    minuto.set(0);
    hora.set(0);
    this.relogioLabel = relogio;
}

public void rodarRelogio(boolean rodar) {
    relogioRodando = rodar;
}

@Override
public void run() {
    try {
        while (true) {
            Thread.sleep(1000);
            if (relogioRodando) {
                segundo.incrementAndGet();
                if (segundo.intValue() == 60) {
                    segundo.set(0);
                    minuto.incrementAndGet();
                    if (minuto.intValue() == 60) {
                        minuto.set(0);
                        hora.incrementAndGet();
                        if (hora.intValue() == 24) {
                            segundo.set(0);
                            minuto.set(0);
                            hora.set(0);
                        }
                    }
                }
                String tempo = String.format("%02d:%02d:%02d", hora.intValue(), minuto.intValue(), segundo.intValue());
                relogioLabel.setText(tempo);
                if (minuto.intValue() %1 == 1) {
                    saveGame();
                }
            }
        }
    } catch (InterruptedException ie) {
        System.out.println("EXCEÇÃO INTERRUPTED EXCEPTION");
    }
}

public void saveGame() {
    JOptionPane.showMessageDialog(null, " 1 Minuto de Partida. Salvando Jogo.");
    FileOutputStream output;
    ObjectOutputStream oos = null;
    try {
        output = new FileOutputStream("jogo.ser");
        oos = new ObjectOutputStream(output);

        oos.writeObject(ArrayPecas.getInst().getPecasPretas());
        oos.writeObject(ArrayPecas.getInst().getPecasBrancas());
        oos.writeObject(ArrayPecas.getInst().getxPerdePr());
        oos.writeObject(ArrayPecas.getInst().getyPerdePr());
        oos.writeObject(ArrayPecas.getInst().getxPerdeBr());
        oos.writeObject(ArrayPecas.getInst().getyPerdeBr());

        oos.writeObject(TelaMenuJogo.getTela().getXequeVsbl());
        oos.writeObject(TelaMenuJogo.getTela().getXequeMateVsbl());
        oos.writeObject(TelaMenuJogo.getTela().getHistoricoTxt());
        oos.writeObject(TelaMenuJogo.getTela().getJaDesenhou());
        oos.writeObject(TelaMenuJogo.getTela().getLinha());
        oos.writeObject(TelaMenuJogo.getTela().getColuna());
        oos.writeObject(TelaMenuJogo.getTela().getLinPecaSel());
        oos.writeObject(TelaMenuJogo.getTela().getColPecaSel());
        oos.writeObject(TelaMenuJogo.getTela().getQtdJogadas());
        oos.writeObject(TelaMenuJogo.getTela().getJogador());

    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Arquivo nao encontrado");
    } catch (IOException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "Erro ao tentar gravar no arquivo de saida");
    } finally {
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo de saida");
            }
        }
    }
}

}

A: I think you pass the same label to the main clock as to one of the others:
relogioBranco = new Relogio(relogioBrancoLabel);
relogioPreto = new Relogio(relogioPretoLabel);
relogioGeral= new RelogioGeral(relogioPretoLabel,menu);

Shouldn't it have its own label?
I think this problem has nothing to do with concurrency. You will only get concurrency problems if two threads are working one resource (e.g. thread a and thread b are both reading the same field). This is not the case here. Every thread works on his own variables/objects.


text:
Q: encode and decode - Hebrew string look like gibberish - Python 3 from Teradata I connected to my Teradata DB and extract simple query result to a dataframe.
The dataframe (df_clients) has 1 column (FirstName) and 1 row with Hebrew string ('שלום לך')
as I print the dataframe I get gibberish instead of Hebrew language:
ùìåí ìê
I find a solution to encode and decode string:
strr = "ùìåí ìê"

print( strr) #not good

print( strr.encode('cp1252').decode('cp1255',errors='replace')) #good

it worked.. but when I tried the same solution with Pandas Dataframe it doesn't work (no error, but don't work):
df_clients.FirstName.apply(lambda x : x.encode('cp1252').decode('cp1255',errors='replace') )

A: The equivalent of your string encoding in Pandas is .str.<de|encode>. I have generated example of the same number as demo:
import pandas as pd

dataf = pd.DataFrame({
    'name':["ùìåí ìê", "ùìåí ìê"]
})

dataf["name"].str.encode('cp1252').str.decode('cp1255',errors='replace')

# result
# 0    שלום לך
# 1    שלום לך

Update

[assign and] a solution that can handle all rows[|columns].

import pandas as pd

dataf = pd.DataFrame({
    'first_name':["ùìåí ìê", "ùìåí ìê"], 'last_name': ["ùìåí ìê", "ùìåí ìê"]
})

# all columns [assuming all are text]

dataf = dataf.transform(lambda x: x.str.encode('cp1252', ,errors='replace').str.decode('cp1255', errors='replace'))

# or selecting subset of columns

dataf[["first_name","last_name"]] = dataf[["first_name","last_name"]].transform(lambda x: x.str.encode('cp1252', errors='replace' ).str.decode('cp1255',errors='replace'))

dataf

#    first_name last_name
# 0 שלום לך שלום לך
# 1 שלום לך שלום לך

If there are errors, try set errors='ignore' and see what worked and which characters are still gibberish.


text:
Q: Programatically open a excel document using javascript office api How to programatically open a document using javascript office api ?
Is there a way to insert a document using javascript office api Or to get access to the document xml ? Something like this
Excel.run(function (ctx) {
    var application = ctx.workbook.application;
    application.load('newXmlWorkbook', worbookInXmlFormat);
    return ctx.sync().then(function() {
        console.log(application.calculationMode);
    });
}).catch(function(error) {
        console.log("Error: " + error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
});

A: In Word an add-in can insert an entire document with the Document.insertFileFromBase64() method.
In Excel this API isn't available. As an alternative, you can enable a download of the file instead of a replacement: for example, you can add an HTML link to the file and let the user download it or you can trigger the download yourself in JavaScript.
-Michael (PM for Office add-ins)


text:
Q: How to generate the content of an href link by the return value of a javascript function? I have a javascript function:
function foo() { return "/a/b/SomeApi"; }

then I have a href link in my web page. I want this link to point to the value returned by my javascript function, so that when the user clicks the link, it's as if the user had clicked a link with url /a/b/SomeApi.
I tried following:
Click

But the result of this is the browser would open a new window showing the literal value /a/b/SomeApi instead of sending a request to the server.
Any suggestions? Thanks.

A: Instead of returning the string, set the location of the current page with it, like this...
function foo() { document.location.href = "/a/b/SomeApi"; }

As pointed out by @haim770 - these are not the droids you are looking for.
If you want to specifically set the href attribute, you must do it from outside of the link.  Firstly you should give your link an id attribute, such as this...
Click

This piece of code should then be placed either after the element in the page, or as part of a "document loaded" piece of code.
document.getElementById("myAnchor").href = "/a/b/SomeApi";

If you were using jQuery (which is not in your list of tags) you could do something like this...
$(function(){
  $("#myAnchor").attr("href", "/a/b/SomeApi")
});

A: I don't think HREF was ever meant to be dynamic; for that, just use the onclick property, such as :
Click


text:
Q: How do I initialise a folder over ssh in git? I want to push my local repository onto my web server which does not have git using ssh. Is this possible, or do you need a git repository such as github to do this?
I tried:
git init --bare ssh://user@host.com/public_html/test

Error message:
fatal: cannot mkdir ssh://user......../test/: Invalid argument

This error came before I even had to enter my password. The folder already exists.
But it didn't work. I can't find any information in the git book.

A: You need to have git on the server, once you have it installed, you'll access to the server and run (on the server):
git init --bare ~/repository.git

Then in your local git repository, you'll add a remote
git remote add origin user@host.com:~/repository.git

If you not have a local git repository created, you only need to clone it and you can start to use and make push / pulls to origin
git clone user@host.com:~/repository.git

And push the master branch (or what you want) to it:
git push origin master

I hope this help you.


text:
Q: Spring AOP The matching wildcard is strict, but no declaration can be found for element 'aop:config' Line 13 in XML document from class path resource [ApplicationContextAOP.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'aop:config'.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="audience" class="com.idol.Audience" />

<aop:config>
<aop:aspect ref="audience">

    <!-- Before performance -->

    <aop:before pointcut="execution(*com.idol.performers.Performer.perform(..))"
    method="takeSeats"/>

    <aop:before pointcut="execution(*com.idol.performers.Performer.perform(..))"
    method="turnOffCellPhones" />

    <!-- After performance -->

    <aop:after-returning pointcut="execution(*com.idol.performers.Performer.perform(..))"
    method="applaud" />

    <!-- After bad performance(exception thrown) -->

    <aop:after-throwing pointcut="execution(*com.idol.performers.Performer.perform(..))"
    method="demandRefund" />

</aop:aspect>
</aop:config>
<bean id="poeticDuke" class="com.idol.performers.PoeticJuggler">
<constructor-arg value = "15" />
<constructor-arg ref = "sonnet29" />
</bean>

</beans>

I've seen similar error and I am pretty sure my classpath has org.springframework.aop-3.1.0.M2.jar
Could you tell me please what am I missing?

A:
Adding one more possibility to the earlier provided answers :

Wrong version of schemaLocation:
http://www.springframework.org/schema/aop/
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

Correct Version:
http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

REASON: The extra "/" after "schema/aop"

A: You need to add to your schemaLocation:
xsi:schemaLocation="
...
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
...
"

A: We received the similar error message for the element tx:advice and got it resolved by replacing the org.springframework.*-3.0.0.M3.jars with org.springframework.*-3.1.2.RELEASE.jars where * represents the jar modules. Hence, try getting a stable release to fix the similar issues.

A: It happened to me with the following schema definition file. The cause was the extra > after spring-aop-3.0.xsd. Solved after removing it.

<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd>
                            http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd">

<!--    reference to tht jdbc name space and schema definition file-->

    <!--    to enable AspectJ support-->
    <aop:aspectj-autoproxy/>

 </beans>


text:
Q: Show All and Hide list items in Angular i have a list of items that i got from API, i want to make list that have show all and hiden sources
this is what i want

.html code

Sources (channel)

{{ source.sourceName }}<ion-checkbox class="checkbox" ></ion-checkbox>

 3">

Hide sources

Show all sources

and this is my .ts code
   @IonicPage()
@Component({
  selector: 'page-my-opportunities-filter',
  templateUrl: 'my-opportunities-filter.html',
})

export class MyOpportunitiesFilterPage {
  public results = [];
  sourcesList =[];
  private is_shown: boolean = true;
  private N: number;

  constructor(public navCtrl: NavController,
    private viewCtrl: ViewController,
    public navParams: NavParams,
    public globalService: GlobalServiceProvider,
    public dataService: DataServiceProvider,
    ) {
  }

  public swap():void {
if (this.is_shown) {
  if (this.N > 3) {
    //show hide sources that will only show 3 list item
  } else {
    //show all data
  }
} else {
  //show all data
}
this.is_shown = !this.is_shown;}

  private ionViewWillLoad(): void {
  }

  private cancel(): void {
    this.viewCtrl.dismiss(null);
  }

  private show(): void {
    this.viewCtrl.dismiss(this.metaData);
  }

  private ionViewDidLoad(): void {
    this.globalService.showLoader();
    this.getAllSources();

    this.globalService.dismissLoader();
  }

  getAllSources(){
    this.dataService.getSources('mytokenAPI')
    .subscribe((results) =>  {
      this.sourcesList = results;
      console.log('JSON Response = ', JSON.stringify(results));
    })
  }

}
i am so confused how to make it works, in this code i just give the logic,
it run well when i just show all the item value, but i want to make there is show all and hiden list,i still confused how to make it in angular, iam new in angular, maybe u can help me how to fix my problem, it means alot

A: create a getter function
get getSourcesList(){
 return this.is_shown? this.sourcesList ? this.sourcesList.slice(0,3)
}

and iterate over that getter function

    {{ source.sourceName }}<ion-checkbox class="checkbox" ></ion-checkbox>

A: You can do something of this sort. Use of array features on the HTML will reduce the code in the component.ts fie.

Sources (channel)

      <ng-container *ngIf="sourceList && (sourceList.length < 4)">

          {{ source.sourceName }}
          <ion-checkbox class="checkbox" ></ion-checkbox>

       </ng-container>

      <ng-container *ngIf="sourceList && (sourceList.length > 3) && is_shown">

            {{ is_shown ? 'Hide ' : 'Show all ' }} sources

          {{ source.sourceName }}
          <ion-checkbox class="checkbox" ></ion-checkbox>

       </ng-container>


text:
Q: rails 3 - how to assign the value to nested attribute using callbacks I have three models, Document, Section and Paragraph.
class Document < ActiveRecord::Base
  attr_accessible :status

  has_many :sections
  accepts_nested_attributes_for :sections, :allow_destroy => :true

  private

  def assign_order_status
    section_statuses = sections.map(&:status)
    self.status =
    if section_statuses.all? {|value| value == "completed" }
      "completed"
    elsif section_statuses.all? {|value| value == "new" }
      "new"
    else
      "inprocess"
    end
  end
end

class Section < ActiveRecord::Base
  attr_accessible :document_id, :status

  belongs_to :document
  has_many :paragraphs, :dependent => :destroy

  accepts_nested_attributes_for :paragraphs, :allow_destroy => :true

  private
  def assign_order_status
    paragraph_values = paragraphs.map(&:text)
    self.status =
    if paragraph_values.all? {|value| !value.nil? }
      "completed"
    elsif paragraph_values.any? {|value| !value.nil? }
      "inprocess"
    else
      "new"
    end
  end
end

class Paragraph < ActiveRecord::Base
  attr_accessible :section_id, :text
  belongs_to :section
end

I want to update status of Document and Section models.
For example, 'status' column in sections table is depending on 'text' column in paragraphs table.
simillarly, 'status' column in documents table is depending on 'status' column in sections table.
Briefly, for sections,

*

*If all the 'text' in paragraphs table is nil then the 'status' of corresponding section have to change as "new".

*If any one 'text' column in paragraphs table is having value then the 'status' of section have to change as "inprocess".

*Otherwise status is "completed".

for document,

*

*If all the 'status' in section table is "new" then the 'status' of corressponding document have to change as "new".

*If any one 'status' is "inprocess" then 'status' of document have to change as "inprocess".

*Otherwise is "completed".

Problem:
I am confusing which callbacks is suitable for assign_order_status method.
Because 'status' of Document is depending on Section's status and Section's status is depending on value of Paragraph.
But Rails validation and callbacks are running from parent to child. In my case, calculation of 'status' value is based from child to parent.
How to update status value for both document and section before starting validation ?
Please anyone help me to solve this.


text:
Q: Ruby - cant load gems with "required", cant run rails I seem to have correct include path, but a lot of gems can't be loaded
via "required". What could be the problem?

test.rb
#!/usr/bin/ruby -w
require "cgi" # can load this
require "actionpack" # can not load this

/var/www/ruby/test.rb
/var/www/ruby/test.rb:3:in `require': no such file to load --
/var/lib/gems/1.9.2/gems/passenger-3.0.11/test/stub/vendor_rails/minimal/actionpack
(LoadError)
        from /var/www/ruby/test.rb:3:in `<main>'

rails server
/root/src/config/boot.rb:6:in `require': no such file to load --
bundler/setup (LoadError)
        from /root/src/config/boot.rb:6:in `<top (required)>'
        from script/rails:5:in `require'
        from script/rails:5:in `<main>'

gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 1.3.7
  - RUBY VERSION: 1.9.2 (2010-07-02 patchlevel -1) [i486-linux]
  - INSTALLATION DIRECTORY: /var/lib/gems/1.9.2/gems/
  - RUBY EXECUTABLE: /usr/bin/ruby1.9.2
  - EXECUTABLE DIRECTORY: /var/lib/gems/1.9.2/gems/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /var/lib/gems/1.9.2/gems/
     - /root/.gem/ruby/1.9.2
     - /var/lib/gems/1.9.2
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/

ls -l /var/lib/gems/1.9.2/gems/
total 296
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 abstract-1.0.0
drwxr-xr-x  3 root root 4096 2011-05-10 12:05 actionmailer-3.0.6
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 actionmailer-3.2.2
drwxr-xr-x  3 root root 4096 2012-03-21 18:59 actionpack-3.2.2
drwxr-xr-x  3 root root 4096 2011-05-10 12:05 activemodel-3.0.6
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 activemodel-3.2.2
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 activerecord-3.0.6
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 activerecord-3.2.2
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 activeresource-3.0.6
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 activeresource-3.2.2
drwxr-xr-x  3 root root 4096 2011-05-10 12:05 activesupport-3.0.6
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 activesupport-3.2.2
drwxr-xr-x  4 root root 4096 2012-03-14 15:21 akami-1.0.0
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 arel-2.0.9
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 arel-3.0.2
drwxr-xr-x  6 root root 4096 2011-05-10 12:05 builder-2.1.2
drwxr-xr-x  5 root root 4096 2012-03-15 17:50 builder-3.0.0
drwxr-xr-x  2 root root 4096 2012-03-21 18:17 bundle-0.0.1
drwxr-xr-x  6 root root 4096 2012-03-21 18:39 bundler-1.1.2
drwxr-xr-x  4 root root 4096 2012-03-15 17:56 daemon_controller-1.0.0
drwxr-xr-x  5 root root 4096 2011-05-10 12:05 diff-lcs-1.1.2
drwxr-xr-x 10 root root 4096 2011-05-10 12:05 erubis-2.6.6
drwxr-xr-x 10 root root 4096 2012-03-15 17:50 erubis-2.7.0
drwxr-xr-x  5 root root 4096 2011-05-10 12:05 factory_girl-1.3.3
drwxr-xr-x  5 root root 4096 2012-03-15 17:56 fastthread-1.0.7
drwxr-xr-x  4 root root 4096 2012-03-14 15:21 gyoku-0.4.4
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 hike-1.2.1
drwxr-xr-x  4 root root 4096 2012-03-14 15:21 httpi-0.9.6
drwxr-xr-x  5 root root 4096 2011-05-10 12:05 i18n-0.5.0
drwxr-xr-x  5 root root 4096 2012-03-15 17:50 i18n-0.6.0
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 journey-1.0.3
drwxr-xr-x 10 root root 4096 2012-03-15 17:50 json-1.6.5
drwxr-xr-x  3 root root 4096 2012-03-14 15:35 libv8-3.3.10.4-x86-linux
drwxr-xr-x  3 root root 4096 2011-05-10 12:05 mail-2.2.19
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 mail-2.4.4
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 mime-types-1.16
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 multi_json-1.1.0
drwxr-xr-x  7 root root 4096 2012-03-15 21:37 mysql-2.8.1
drwxr-xr-x  7 root root 4096 2011-05-10 12:05 nokogiri-1.4.4
drwxr-xr-x  5 root root 4096 2012-03-14 15:21 nori-1.1.0
drwxr-xr-x 14 root root 4096 2012-03-21 18:33 passenger-3.0.11
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 polyglot-0.3.1
drwxr-xr-x  7 root root 4096 2011-05-08 23:16 rack-1.2.2
drwxr-xr-x  7 root root 4096 2012-03-16 20:59 rack-1.4.1
drwxr-xr-x  6 root root 4096 2012-03-15 17:50 rack-cache-1.2
drwxr-xr-x  3 root root 4096 2011-05-10 12:05 rack-mount-0.6.14
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 rack-ssl-1.3.2
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 rack-test-0.5.7
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 rack-test-0.6.1
drwxr-xr-x  6 root root 4096 2012-03-15 21:37 radius-0.7.3
drwxr-xr-x  3 root root 4096 2011-05-10 12:05 rails-3.0.6
drwxr-xr-x  2 root root 4096 2012-03-15 17:50 rails-3.2.2
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 railties-3.0.6
drwxr-xr-x  5 root root 4096 2012-03-15 17:50 railties-3.2.2
drwxr-xr-x  6 root root 4096 2011-05-10 12:05 rake-0.8.7
drwxr-xr-x  5 root root 4096 2012-03-15 17:50 rdoc-3.12
drwxr-xr-x  8 root root 4096 2011-05-10 12:05 RedCloth-4.2.5
drwxr-xr-x  3 root root 4096 2011-05-10 12:06 rspec-2.5.0
drwxr-xr-x  7 root root 4096 2011-05-10 12:05 rspec-core-2.5.2
drwxr-xr-x  5 root root 4096 2011-05-10 12:05 rspec-expectations-2.5.0
drwxr-xr-x  6 root root 4096 2011-05-10 12:05 rspec-mocks-2.5.0
drwxr-xr-x  6 root root 4096 2011-05-10 12:06 rspec-rails-2.5.0
drwxr-xr-x  4 root root 4096 2012-03-21 18:32 rvm-1.9.2
drwxr-xr-x  4 root root 4096 2012-03-14 15:37 savon-0.9.9
drwxr-xr-x  3 root root 4096 2012-03-15 17:50 sprockets-2.1.2
drwxr-xr-x  7 root root 4096 2011-05-10 12:06 sqlite3-ruby-1.2.5
drwxr-xr-x  8 root root 4096 2012-03-14 15:35 therubyracer-0.9.10
drwxr-xr-x  5 root root 4096 2011-05-10 12:05 thor-0.14.6
drwxr-xr-x  5 root root 4096 2012-03-15 17:50 tilt-1.3.3
drwxr-xr-x  7 root root 4096 2011-05-10 12:05 treetop-1.4.9
drwxr-xr-x  4 root root 4096 2011-05-10 12:05 tzinfo-0.3.27
drwxr-xr-x  4 root root 4096 2012-03-15 17:50 tzinfo-0.3.32
drwxr-xr-x  4 root root 4096 2012-03-14 15:21 wasabi-2.1.0
drwxr-xr-x  5 root root 4096 2012-03-16 19:11 webrick-1.3.1

I re-installed ruby in a new path ( so the paths are different from my earlier posts). But still has the same issue.
# ruby -v
ruby 1.9.3p125 (2012-02-16 revision 34643) [i686-linux]
# gem -v
/usr/local/rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/yaml.rb:56:in `<top
(required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your
ruby.
1.8.19

# gem env
/usr/local/rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/yaml.rb:56:in `<top
(required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your
ruby.
RubyGems Environment:
  - RUBYGEMS VERSION: 1.8.19
  - RUBY VERSION: 1.9.3 (2012-02-16 patchlevel 125) [i686-linux]
  - INSTALLATION DIRECTORY: /usr/local/rvm/gems/ruby-1.9.3-p125
  - RUBY EXECUTABLE: /usr/local/rvm/rubies/ruby-1.9.3-p125/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/rvm/gems/ruby-1.9.3-p125/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /usr/local/rvm/gems/ruby-1.9.3-p125
     - /usr/local/rvm/gems/ruby-1.9.3-p125@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/

# gem list -d actionpack
/usr/local/rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/yaml.rb:56:in `<top
(required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your
ruby.

*** LOCAL GEMS ***

actionpack (3.2.2)
    Author: David Heinemeier Hansson
    Homepage: http://www.rubyonrails.org
    Installed at: /usr/local/rvm/gems/ruby-1.9.3-p125

    Web-flow and rendering framework putting the VC in MVC (part of
    Rails).

TEST.RB -
#!/usr/local/rvm/rubies/ruby-1.9.3-p125/bin/ruby -w
###!/usr/bin/ruby -w # copy of above binary
require 'rubygems'
require 'cgi'
require 'actionpack'

# /var/www/ruby/test.rb
/usr/local/rvm/rubies/ruby-1.9.3-p125/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- actionpack (LoadError)
        from
/usr/local/rvm/rubies/ruby-1.9.3-p125/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
        from /var/www/ruby/test.rb:8:in `<main>'

I tried adding require "rubygems". that didn't work either. Still getting the same error.
Hi Bhushan nad Tass.Yes I am using rvm. I tried bundler install. # bundler install bundler: command not found

A: This should work:
#!/usr/bin/ruby -w
require "rubygems"
require "cgi" # can load this
require "actionpack" # can not load this

CGI is a standard library, not a gem, that's why you can load it. In order to load gems, firstly require "rubygems"
UPDATE
Also, try to require "action_pack" instead of "actionpack". This has changed since Rails 3 for other active* Rails gems as well. They're still called the same, activesupport for example, but gotta be required with underline in the middle: active_support.
As someone else mentioned here, try also to update gem program, your version is very old: gem update --system


text:
Q: Commutative diagrams for groups You can present a group in a Cayley-like manner, replacing colors by explicit assignment of nodes to edges: while in a Cayley graph $x \circ y = z$ is presented like this:

you can also present it like this:

Now the group axioms can be stated like this:

*

*For each $x, y$ there is a unique $z$ with $x \circ y = z$, or: such that the following diagram holds ("commutes"):

*

*There is an $e$ such that for all $x$ it holds that $x\circ e = e \circ x = x$, or: such that the following two diagrams commute:

and for each $x$  there is a $x^{-1}$ such that $x \circ x^{-1} = x^{-1} \circ x = e$, or: such that the following diagram commutes:

*

*For each $x, y, z$ it holds that $x \circ (y \circ z) = (x \circ y) \circ z$, or: such that the following diagram commutes:

The last diagram is somewhat ugly, even when drawn in this most balanced way (I didn't find a more appealing and symmetric one).
But an astonishing symmetry arises, when we consider Abelian groups. Commutativity is expressed by the diagram:

and associativity becomes:

In the presence of commutativity, associativity seems to be related to commutativity (some sort of "second level commutativity").

Can any use be made of this kind of diagrams, or is it
  just vain baublery?

A: These pictures are a way of writing a group as an algebra over an operad.  The little square is the 2-ary operation, and the arrows are an indicator that makes the inputs distinguishable.
John Baez has written about operads using pictures similar to yours.  See for example TWF week 191.
The relation between associativity and commutativity is similar to a fact seen in some books on vertex algebras, where one starts with an axiom like $x(yz) = y(xz)$ and after some power series manipulations deduces $x(yz) = (xy)z$.


text:
Q: Stratified KFold on sparse(csr) feature matrix I have a large sparse matrix (95000, 12000) containing the features of my model. I want to do a stratified K fold cross validation using Sklearn.cross_validation module in python. However, I haven't found a way of indexing a sparse matrix in python.
Is there anyway I can perform StratifiedKFold on my sparse feature matrix?

A: try this:
# First make sure sparse matrix is to_csr
X_sparse = x.tocsr()
y= output
X_train = {}
Y_train = {}

skf = StratifiedKFold(5, shuffle=True, random_state=12345)
i=0
for train_index, test_index in skf.split(X,y):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train[i], X_test[i] = X[train_index], X[test_index]
    y_train[i], y_test[i] = y[train_index], y[test_index]
    i +=1


text:
Q: projecting onto Cartographic coordinates using Gauss Conformal Mercator in python The shapefiles and boundaries I work with are on WGS 84 referenced to SA:
GEOGCS["WGS 84", DATUM["World Geodetic System 1984", SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich", 0.0, AUTHORITY["EPSG","8901"]], UNIT["degree", 0.017453292519943295], AXIS["Geodetic longitude", EAST], AXIS["Geodetic latitude", NORTH], AUTHORITY["EPSG","4326"]]
I need to project them onto a plane to make area calculations and intersect shapes. I'm stuck with a few questions:

*

*local official projection is defined by Gauss Conformal Mercator. How do I project files with this map definition in Python?
here are a number of definitions: http://spatialreference.org/ref/epsg/2047/, as well as http://epsg.io/?q=south%20africa.

Which package/wrapper/function do I choose to do the heavy-lifiting?
I read that planar projection in SA are done in a variety of ways- Which of the Lo/Wg do I choose for the projection to cover the entire span of the country?

*The mapping needs to maintain the areas. Does tha GCM do that?

*Is Gauss-Krüger the same as Gauss Conformal?

A: Depending on the context, the Gauss-Krüger and Gauss Conformal are the same or very similar projections (see Gauss–Krüger coordinate system on wiki.
Relevant to your question, there are two important mutually exclusive classes of projections, each having distinctive geometric qualities:

*

*Conformal (or orthomorphic) projections preserve angular relationships between great circles.

*Equal area (or equivalent) projections preserve areal relationships.

Conformal projections definitely do not maintain correct areal scales.
Perhaps for South Africa, choose an Albers Equal Area Conic projection (see, generally wiki/Albers_projection, and specifically, albers-equal-area-conic-south-africa on spatialreference.org
If you do still wish to use the (conformal) Transverse Mercator (EPSG projection 2047) -- or whichever projection you decide you need -- using Python, perhaps you should ask that separately.


text:
Q: MPEG2 Presentation Time Stamps (PTS) calculation I have an MPEG2 TS file and now I am interested in extracting PTS information from each picture frame. I know that PTS is described in 33 bits including 3 marker bits. But I don't know how this bitfield can be converted to more understandable form (seconds, milliseconds). Can anybody help me please

A: 24hours/day * 60min/hr * 60secs/min *90k/sec (clock) = 7962624000, which needs 33 bits to be represented; You can extract your time from the clock using this info;

A: The MPEG2 transport stream clocks (PCR, PTS, DTS) all have units of 1/90000 second.  The PTS and DTS have three marker bits which you need to skip over.  The pattern is always (from most to least significant bit) 3 bits, marker, 15 bits, marker, 15 bits, marker.  The markers must be equal to 1.  In C, removing the markers would work like this:
uint64_t v; // this is a 64bit integer, lowest 36 bits contain a timestamp with markers
uint64_t pts = 0;
pts |= (v >> 3) & (0x0007 << 30); // top 3 bits, shifted left by 3, other bits zeroed out
pts |= (v >> 2) & (0x7fff << 15); // middle 15 bits
pts |= (v >> 1) & (0x7fff <<  0); // bottom 15 bits
// pts now has correct timestamp without markers in lowest 33 bits

They also have an extension field of 9bits, forming a 42bit integer in which the extension is the least significant bits.  The units for the base+extension are 1/27000000 second.  Many implementations leave the extension as all zeros.


text:
Q: How to convert list returned in django context to javascript or vuejs list? So I have a simple list being returned in the django context
rlinks: ['test1', 'test2'', 'test3']

var v_root = new Vue({
    delimiters: [ '[[', ']]' ],
    el: '#vue-main',
    data: {
        job_execs: [],
        rlinks: '{{ rlinks }}',

When I do console.log from vuejs on this I see:
['test1', 'test2']

How do I convert the above into a javascript list?  If at all possible - I would prefer the solution be on the javascript end and not the django end.

A: Assuming it's an array of strings, you could just use <textarea>s:

const arr = ["'test1'", "'test2'"];
const res = arr.map(e => {
  let inp = document.createElement("textarea");
  inp.innerHTML = e;
  return inp.value;
});
console.log(res);