text:
Q: Someone remotely encrypted my original source I was having a remote session with someone 2 days back for a web application demonstration, and suddenly, I don't know what he did, but my screen froze for 10 minutes and then when it got back to work, all my main original source files were encrypted.
I don't have any back up and it took so much to code all that files but now all my work has gone to waste. When I opened those files, it says "Encrypted by PHPMasterCrypt and when I visited that website, it says its one-way encryption and cannot be reverted back.
<?$__C44s='This program is encrypted by PHP MasterCrypt - phpMC v2.6.0. This encryption system has been developed by Subhash Bose. Visit http://programming.subhashbose.com/phpmc for using phpMC';$__v=1879;if(!function_exists('c___65gf')){function c___65gf($__44re,$__4bd7,$__hdh7){return substr($__44re.$__44re,$__4bd7%strlen($__44re),$__hdh7);}}$m__hes7j='[encoded data, 20904 characters]';$s___g6='__';$__v++;$m__c7df2=create_function(base64_decode('JG5fX2hmNzQsJGxfMzQzag=='),base64_decode('cmV0dXJuIGNyZWF0ZV9mdW5jdGlvbigkbl9faGY3NCwkbF8zNDNqKTs='));$m__065a3=$m__c7df2(base64_decode('JGhfXzY0M2g='),base64_decode('cmV0dXJuIGJhc2U2NF9kZWNvZGUoc3RycmV2KCRoX182NDNoKSk7'));$__C44s=base64_encode($__C44s);$m__a3e35=${'m'.$s___g6.substr(md5(c___65gf($__C44s,$__v,23)),8,5)}($m__065a3('=kjMmJ2XfRGJ'),$m__065a3('=sTKpkjMmJ2XfRGJoYXZyJHdzhSZ0FGbm5Wa6dGIuJXd0Vmc'));eval(strrev(${'m'.$s___g6.substr(md5(c___65gf($__C44s,($__v*3)*$__v,23)),8,5)}(${'m'.$s___g6.substr(md5(c___65gf($__C44s,$__v*$__v,23)),8,5)}(str_replace(md5($__C44s.'MC'),'',$m__hes7j)))));?>

A: I believe I have retrieved your code through sheer stubbornness.
<?php
require('mysql_func.php');
//ONLINE [REDACTED]
 define('GAPS_SERVER', 'localhost');                // eg, localhost
 define('GAPS_SERVER_USERNAME', 'root');
 define('GAPS_SERVER_PASSWORD', '[REDACTED]');
 define('GAPS_DATABASE', 'edaddy_irinfotech');

define('SITE_URL','http://localhost/edaddy');
define('SITE_ADMIN_URL','http://localhost/edaddy');
define('SITE_NAME','E-Daddy');
define('SITE_PAGE_REGISTRECTED','<div style="text-align:center;color:#FF0000" class="alert"><strong style="color:#FF0000">You do not have access to this page.</strong></div>');
//****** Table's Name of database ***********///
$SQLDB = array(
    'CRM_MENU'                         => 'crm_menu',
    'CRM_USERS'                        => 'crm_users',
    'CRM_MODULE'                       => 'crm_module',
    'CRM_CUSTOMER'                     => 'crm_customer',
    'CRM_DETAILS'                      => 'crm_detail',
    'CRM_CASE'                         => 'crm_case',
    'CRM_SUBCRIPTION_TYPE'             => 'crm_subcription_type',
    'CRM_OPERATING_SYSTEM'             => 'crm_operating_system',
    'CRM_SYSTEM_CONFIG'                => 'crm_system_config',
    'CRM_RAM'                          => 'crm_ram',
    'CRM_HDD'                          => 'crm_hdd',
    'CRM_VERIFICATION_QUESTION'        => 'crm_verification_question',
    'CRM_REGISTERED_COMPUTER'          => 'crm_registered_computers',
    'CRM_CURRENCY'                     => 'crm_currency',
    'CRM_COUNTRIES'                    => 'crm_countries',
    'CRM_ZONES'                        => 'crm_zones',
    'CRM_CASE_STATUS'                  => 'crm_case_status',
    'CRM_TEAM_MASTER'                  => 'crm_team_master',
    'CRM_COMPONENTS'                   => 'crm_components',
    'CRM_CUSTOMER_CASE_TEMP'           => 'crm_customer_case_temp',
    'CRM_CUSTOMER_CASE'                => 'crm_customer_case',
    'CRM_TIMEZONE'                     => 'crm_timezone',
    'CRM_CUSTOMER_NOTES'               => 'crm_customer_notes',
    'CRM_CASE_EDITED_DATE'             => 'crm_case_edited_date',
    'CRM_BREAK_MASTER'                 => 'crm_break_master',
    'CRM_USER_TIME_SLOT'               => 'crm_user_time_slot',
    'CRM_SETTINGS'                     => 'crm_settings',
    'CRM_CALL_TYPE'                    => 'crm_call_type',
    'CRM_CALL_MASTER'                  => 'crm_call_master',
    'CRM_CUSTOMER_CALLING_DATE'        => 'crm_customer_calling_date',
    'CRM_CUSTOMER_REACTION'            => 'crm_customer_reaction',
    'CRM_USER_RIGHT_MASTER'            => 'crm_user_right_master',
    'CRM_USER_RIGHT_CUSTOMER'          => 'crm_user_right_customer',
    'CRM_INTERNAL_EMAIL'               => 'crm_internal_email',
    'CRM_INTERNAL_EMAIL_USERS'         => 'crm_internal_email_users',
    'CRM_NOTICE_BOARD'                 => 'crm_notice_board',
    'CRM_NOTICE_BOARD_USER'            => 'crm_notice_board_user',
    'CRM_INTERNAL_EMAIL_REPLY'         => 'crm_internal_email_reply',
    'CRM_REFUND_REQUEST'               => 'crm_refund_request',
    'CRM_CALL_DISPOSITION'             => 'crm_call_disposition',
    'CRM_KNOWLEDGE_MANAGEMENT'         => 'crm_knowledge_management',
    'CRM_RESOURCE_MANAGEMENT'          => 'crm_resource_management',
    'CRM_NEWSLETTER_SEND'              => 'crm_newsletter_send',
    'CRM_USER_EMPLOYMENT'              => 'crm_user_employment',
    'CRM_USER_ATTENDANCE'              => 'crm_user_attendance',
    'CRM_CAMPAIGN'                     => 'crm_campaign',
    'CRM_CAMPAIGN_EXPECTED_RESPONSE'   => 'crm_campaign_expected_response',
    'CRM_CAMPAIGN_STATUS'              => 'crm_campaign_status',
    'CRM_CAMPAIGN_TYPE'                => 'crm_campaign_type',
    'CRM_LEAD'                         => 'crm_lead',
    'CRM_LEAD_INDUSTRY'                => 'crm_lead_industry',
    'CRM_LEAD_RATING'                  => 'crm_lead_rating',
    'CRM_LEAD_SOURCE'                  => 'crm_lead_source',
    'CRM_LEAD_STATUS'                  => 'crm_lead_status',
    'CRM_QA_MASTER'                    => 'crm_qa_master',
    'CRM_QA_MASTER_TYPE'               => 'crm_qa_master_type',
    'CRM_QA_MASTER_USERS'              => 'crm_qa_master_users',
    'CRM_CASE_FEEDBACK'                => 'crm_case_feedback',
    'CRM_INTERNET_OPTION'              => 'crm_internet_option',

    'CRM_QUALITY_REMARK'               => 'crm_quality_remark',
    'CRM_CHARGE_BACK'                  => 'crm_charge_back',
    'CRM_AVG_KEY'                      => 'crm_avg_key',
    'CRM_CLEAROMIZE'                   => 'crm_clearomize_key',
    'CRM_ANTISPYWARE'                  => 'crm_antispyware',
    'CRM_ANTIHIJACKING'                => 'crm_antihijacking',
    'CRM_BACKUP_TOOL'                  => 'crm_backup_tool',
    'CRM_OPEN_CASE'                    => 'crm_open_case',
    'CRM_CALL_SCHEDULE'                => 'crm_call_schedule',
    'CRM_REQUEST_CHARGEBACK_REFUND'    => 'crm_request_chargeback_refund',
    'CRM_USER_PENDING_ATTANDENCE'      => 'crm_user_pending_attandence',
    'CRM_ATTENDANCE_MASTER'            => 'crm_attendance_master',
    'CRM_UNRELATED_CALLS'              => 'crm_unrelated_calls',

);

 define('ERROR_MESSAGE','<div id="login_error"> %s</div>');
 define('SUBMIT_MESSAGE','<div class="message_div"> %s</div>');
 define('RECORD_DELETE','<div id="login_error"><strong>DELETE</strong>: %s</div>');
 define('RECORD_UPDATE','<div class="message_div"><strong>UPDATE</strong>: %s</div>');
 define('RECORD_INSERT','<div class="message_div"><strong>INSERT</strong>: %s</div>');
 define('RECORD_STATUS_CHANGE','<div class="message_div"><strong>STATUS</strong>: %s</div>');

$gaps_obj_1 = new gaps_sql();
$gaps_obj_1->gaps_connect();

$gaps_obj_2 = new gaps_sql();
$gaps_obj_2->gaps_connect();

$gaps_obj_3 = new gaps_sql();
$gaps_obj_3->gaps_connect();
error_reporting(0);

The process can be applied to any other files you have, but considering the time and effort involved I wouldn't be able to do it for free =/
On further review, I have succeeded in automating the process. I have created a tool that reverses this supposedly irreversible process.
You can find the tool here: http://thedarkworld.net/phpmc260.php The server has since been taken down, but I've re-created it in a JSFiddle.

A:
and suddenly, I don't know what he did, but my screen froze for 10 minutes

Blind bet is that your app allows file uploads and this feature is very much broken in your code as you allow uploaded files to be reached directly if one knows the right url. I suggest to inspect upload folder however the uploaded PHP script that did the mess could self-remove too.

it says its one-way encryption and cannot be reverted back.

There's no one way encryption as it would be no point of such.

I don't have any back up and it took so much to code

"so much to code" and no backup, no VCS. Well...


text:
Q: ¿Cómo calcular días laborales entre dos fechas en dataframe python? Buen día, necesito calcular del número de días transcurridos entre dos fechas, y que el resultado sea solo en días hábiles y/o laborales (Sin Sábados ni Domingos), actualmente tengo lo siguiente:
#DIFERENCIA DE FECHAS 'Fecha1' - 'Fecha2'
df['DIAS_TRANSCURRIDOS'] = (df.Fecha1 - df.Fecha2) / pd.Timedelta('1 day')
df.head()

Gracias.

A: La forma más sencilla si estás usando pandas y numpy es usar: numpy.busday_count(). Por ejemplo:
import pandas as pd
import numpy as np
import datetime
from datetime import date

# Generamos un ejeplo de datos
date1 = pd.Series(pd.date_range('2019-1-1 12:00:00', periods=7, freq='M'))
date2 = pd.Series(pd.date_range('2019-6-18 21:45:00', periods=7, freq='W'))
df = pd.DataFrame(dict(Start_date = date1, End_date = date2))

# Calculamos diferencias de días hábiles
df['diff_days'] = df.apply(lambda row : np.busday_count(row['Start_date'].date(),row['End_date'].date()),axis=1)

print(df)

           Start_date            End_date  diff_days
0 2019-01-31 12:00:00 2019-06-23 21:45:00        102
1 2019-02-28 12:00:00 2019-06-30 21:45:00         87
2 2019-03-31 12:00:00 2019-07-07 21:45:00         70
3 2019-04-30 12:00:00 2019-07-14 21:45:00         54
4 2019-05-31 12:00:00 2019-07-21 21:45:00         36
5 2019-06-30 12:00:00 2019-07-28 21:45:00         20
6 2019-07-31 12:00:00 2019-08-04 21:45:00          3

Eventualmente, está función, te permitiría definir el parámetro holidays para especificar días adicionales no laborables (por ej. feriados)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do the $\Gamma$ matrices behave like vectors and tensors in the spinor representation of SO groups? One of the things that confuse me most when I study group theory and quantum field theory is that  I constantly run into the situations where $\psi C \Gamma_M\chi$ are treated like vectors, $\psi C\Gamma_M\Gamma_N \Gamma_N \chi$ are treated like tensors, where $\psi$ and $\chi$ are spinors in the SO group's spinor representation.
But I never have been formally introduced that tensors and vectors in this way. I currently feels that maybe many traditional vectors (like what we learned since high school) can be represented in this way by the contraction with $\gamma$ matrices?
So back to the topic, what does it mean when some author says that "they are like vectors and tensors"?  Would these objects completely satisfy the definition of tensors? How do we manipulate the transformations of them; would they transform like tensors?

P.S.: I'm a physics student, so I would really appreciate it if your answer not heavily relies on math terms.  Thank you in advance.


text:
Q: Chipscope ILA unable to capture signals correctly ALL the ILA modules that I am having now do not work .
I mean they failed to even capture the user-assigned 'clk' and 'resetn' signals. Why ?
Note: the PCB schematics could be found here

A: Problem resolved by increasing the value of "Position" field to something larger, say 300


text:
Q: How to update radio button in view from viewmodel? Say I have a few radio buttons grouped together in my view.xaml:
<RadioButton GroupName="Group" Content="Item1" Command="{Binding ChangeRadioSelectionCommand}" CommandParameter="Item1" />
<RadioButton GroupName="Group" Content="Item2" Command="{Binding ChangeRadioSelectionCommand}" CommandParameter="Item2" />
<RadioButton GroupName="Group" Content="Item3" Command="{Binding ChangeRadioSelectionCommand}" CommandParameter="Item3" />

Then in my viewmodel.cs I have something like:
public class ViewModel : BindableBase
{
  private string radioSelection = "Item1";
  public string RadioSelection
  {
    get { return this.radioSelection; }
    set { SetProperty(ref this.radioSelection, value); }
  }

  public ViewModel()
  {
    this.ChangeRadioSelectionCommand = new DelegateCommand<string>(this.OnChangeRadioSelection, this.CanChangeRadioSelection);
  }

  public ICommand ChangeRadioSelectionCommand { get; private set; }
  private void OnChangeRadioSelection(string radioSelection)
  {
    RadioSelection = radioSelection;
  }
  private bool CanChangeRadioSelection(string radioSelection) { return true; }
}

This works fine for getting values from the view into the viewmodel, but how would I go from the viewmodel to the view if something changes in the viewmodel. For simplicity, let's say I add a button to the xaml:
<Button Command="{Binding ResetRadioSelectionCommand}" />

All it would do is reset the radio selection to the first item and so the viewmodel.cs would look something like:
public class ViewModel : BindableBase
{
  private string radioSelection = "Item1";
  public string RadioSelection
  {
    get { return this.radioSelection; }
    set { SetProperty(ref this.radioSelection, value); }
  }

  public ViewModel()
  {
    this.ChangeRadioSelectionCommand = new DelegateCommand<string>(this.OnChangeRadioSelection, this.CanChangeRadioSelection);
    this.ResetRadioSelectionCommand = new DelegateCommand(this.OnResetRadioSelection, this.CanResetRadioSelection);
  }

  public ICommand ChangeRadioSelectionCommand { get; private set; }
  private void OnChangeRadioSelection(string radioSelection)
  {
    RadioSelection = radioSelection;
  }
  private bool CanChangeRadioSelection(string radioSelection) { return true; }

  public ICommand ResetRadioSelectionCommand { get; private set; }
  private void OnResetRadioSelection()
  {
    RadioSelection = "Item1";
  }
  private bool CanResetRadioSelection() { return true; }
}

This would change radioSelection, but it won't reflect in the gui. Is there a way to do this? Or perhaps just a better way to deal with radio buttons in general?

A: It is completely the wrong way. Your ViewModel should contain a sensible property with sensible name. For example, CurrentMode.
FIRST SOLUTION
ViewModel
public enum DisplayMode { Vertical, Horizontal, Diagonal }

private DisplayMode currentMode;
public DisplayMode CurrentMode
{
    get { return currentMode; }
    set { SetProperty(ref currentMode, value); }
}

And now you can bind this property to RadioButton.IsChecked via IValueConverter:
<RadioButton GroupName="Group" Content="Vertical" IsChecked="{Binding CurrentMode, Converter={StaticResource enumToBoolConverter}, ConverterParameter=Vertical}" />
<RadioButton GroupName="Group" Content="Horizontal" IsChecked="{Binding CurrentMode, Converter={StaticResource enumToBoolConverter}, ConverterParameter=Horizontal}" />
<RadioButton GroupName="Group" Content="Diagonal" IsChecked="{Binding CurrentMode, Converter={StaticResource enumToBoolConverter}, ConverterParameter=Diagonal}" />

Converter is generic for all enums. You need to add it to your project and declare in resource-block of your view.
public class EnumBooleanConverter : IValueConverter
{
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string parameterString = parameter as string;
        if (parameterString == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(value.GetType(), value) == false)
            return DependencyProperty.UnsetValue;

        object parameterValue = Enum.Parse(value.GetType(), parameterString);

        return parameterValue.Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string parameterString = parameter as string;
        if (parameterString == null)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(targetType, parameterString);
    }
    #endregion
}

It's one of many solutions. You may not want to us enum for your property because the subject area is not mapped to enumeration of parameters. Then you can bind to text value:
SECOND SOLUTION
ViewModel
private string currentMode;
public string CurrentMode
{
    get { return currentMode; }
    set { SetProperty(ref currentMode, value); }
}

View
<RadioButton Name="RadioButton1"
                     GroupName="Group"
                     Content="Vertical"
                     IsChecked="{Binding Path=CurrentMode, Converter={StaticResource boolToStringValueConverter}, ConverterParameter=Vertical}" />
        <RadioButton Name="RadioButton2"
                     GroupName="Group"
                     Content="Horizontal"
                     IsChecked="{Binding Path=CurrentMode, Converter={StaticResource boolToStringValueConverter}, ConverterParameter=Horizontal}" />
        <RadioButton Name="RadioButton3"
                     GroupName="Group"
                     Content="Diagonal"
                     IsChecked="{Binding Path=CurrentMode, Converter={StaticResource boolToStringValueConverter}, ConverterParameter=Diagonal}" />

Converter
public class BooleanToStringValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (System.Convert.ToString(value).Equals(System.Convert.ToString(parameter)))
        {
            return true;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (System.Convert.ToBoolean(value))
        {
            return parameter;
        }
        return null;
    }
}

The general principle is to store meaningful projection of the subject area in ViewModels. There is no many sense if you'll keep store copy of view properties in your ViewModel. RadioSelection is a senseless name and it can't be correlated to model without additional commentaries.


text:
Q: How can i add colors to each selected date in js-calender-year using Angular. The color should be persistent after page refresh I am using js-year-calendar plugin to display all the months in a year at once. However, i can select just one day at a time and then store the date in the database. Please, is there a way to select multiple days e.g. 2020/08/04 - 2020-08-12 and then store this range in the database at once. Meanwhile, i have gone through the documentation but its was not clear to me. Please i need assistance to get a clear picture on how to go about this. Thanks
This is my view. I am sorry for the long code, i really assistance

HTML

{{'ALL_COMPANIES_HOLIDAY_CALENDER' | translate}}

                  <select class="form-control " [(ngModel)]="holidays.company_id" id="company" name="company"  (change)="getSelectedCompany(holidays.company_id)" required>
                    <option value="" disabled selected hidden>{{'SELECT_COMPANY' | translate}}</option>
                    <option *ngFor="let data of companyList; let i = index" [value]="data.id" >{{data.company_name}}</option>
                  </select>

          <ngx-datatable  #table class='bootstrap' [columnMode]="'force'" [headerHeight]="50" [footerHeight]="50"
              [rowHeight]="'auto'" [limit]="50" [rows]='holidaysDataRows'>
              <ngx-datatable-column name="{{'COMPANY_NAME' | translate}}" prop="company_name"></ngx-datatable-column>
            <ngx-datatable-column name="{{'YEAR' | translate}}" prop="year"></ngx-datatable-column>
            <ngx-datatable-column name="{{'HOLIDAY' | translate}}" prop="holidays_date">
            </ngx-datatable-column>
            <ngx-datatable-column name="{{'DESCRIPTION' | translate}}" prop="description" > </ngx-datatable-column>
            <ngx-datatable-column name="{{'ACTIONS' | translate}}" prop="status">
              <ng-template ngx-datatable-cell-template let-rowIndex="rowIndex" let-value="value" let-row="row"
              let-group="group" let-rowHeight="rowHeight">

                <button (click)="editHoliday(editModal,row)"  class="btn btn-raised mr-1 shadow-z-2 btn-info btn-sm ">{{'EDIT' | translate}}</button>
                <button  (click)="deleteModal(deleteholiday, row.holiday_id)" class="btn btn-raised mr-1 shadow-z-2 btn-danger btn-sm ">{{'DELETE' | translate}}</button>

              </ng-template>
            </ngx-datatable-column>
          </ngx-datatable>

TS CODE
import { Component, OnInit, ViewChild } from '@angular/core';
import { SnotifyService } from 'ng-snotify';
import { Router, ActivatedRoute } from "@angular/router";
import { NgbModal, ModalDismissReasons, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { HumanResourceService } from 'app/services/human-resource/human-resource.service';
  import { TranslateService } from '@ngx-translate/core';
  import { AuthenticationService } from 'app/services/authentication/authentication.service';
 import { HumanResourceMasterService } from '../../../services/human-resource-master/human-resource-master.service';
  import Calendar from 'js-year-calendar';
  import * as moment from 'moment';
  import { GlobalConstants } from 'app/shared/constants/global-constants';

@Component({
  selector: 'app-all-company-holiday-calender',
  templateUrl: './all-company-holiday-calender.component.html',
  styleUrls: ['./all-company-holiday-calender.component.scss']
})
export class AllCompanyHolidayCalenderComponent implements OnInit {
@ViewChild('openModal') OpenModalotdeletepos;
  companyList: any = [];
    company_id: any = '';
  datas: any;
 dateFromModal : any;
 closeResult: any;
 currentHolidays: any = [];
 holidaysDataRows: [];
 HolidayDeleteData: any;
 showLoader: boolean;
 deleterowid: any;
 holidaysData : any = [];
 holidays: any = {
   description: '',
   date: '',
   company_id:'',
   hr_id: '',
   hols_id: '',
 }
 selectedDate:any;
 hrID: any;
 eventDate: Date;
  eventText: string;
  myEvents: any[] = [];
  constructor(private snotifyService: SnotifyService,private spinner:
      FullLayoutComponent, private
     route: ActivatedRoute, private modalService: NgbModal, private
  loginService: LoginService,private  hrMasterService:
  HumanResourceMasterService, private hrService:
   HumanResourceService, public authService: AuthenticationService,public
translate: TranslateService) {

 ngOnInit() {
  this.getDate();
 }
 getDate(){
   var modalService = this.modalService;
   var snotifyService = this.snotifyService;
   var openModal = this.OpenModalotdeletepos;
   var getDismiss = this.getDismissReason;
   new Calendar('#calendar');
   var holiday = this.holidays;
   var translate = this.translate;
   document.querySelector('#calendar').addEventListener('clickDay',
   function(data) {
   var hols = moment(data['date']).format(GlobalConstants.DATE_FORMAT);;
    holiday.date = hols;
     if(!holiday.company_id){

 snotifyService.error(translate.instant('MESSAGE_PLEASE_SELECT_COMPANY'));
      }
     else{
     modalService.open(openModal).result.then((result) => {
      this.closeResult = GlobalConstants.CLOSE + `${result}`;
     }, (reason) => {
      this.closeResult =  GlobalConstants.DISMISSED +
  `${getDismiss(reason)}`;
    });
  }
})

 }

  getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
            return GlobalConstants.PRESS_ESC;
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
            return GlobalConstants.BACKDROP_CLICK;
    } else {
            return GlobalConstants.WITH + ` ${reason}`;
    }
}

 getHolidayData(){
   this.showLoader = true;
   this.hrMasterService.getHolidayData({}).subscribe(data => {
        if(data.status_code = 200){
            this.showLoader = false;
            this.holidaysData = data.data;
    this.holidaysDataRows = this.holidaysData;
        }
        else {
            this.showLoader = false;
            this.snotifyService.error(data.message);
        }
    })
 }
  saveHolidays(){
     this.holidays.hr_id = this.hrID.id;
     this.hrMasterService.createHolidays(this.holidays).subscribe(data =>{
     if(data.status_code = 200){
     this.snotifyService.success(this.translate.instant('MESSAGE_HOLIDAY_CREATED'));
     this.modalService.dismissAll();
     setTimeout(() => {
       window.location.reload();
     }, 1000);
   } else {
     this.snotifyService.error(data.message);
   }
  },error=>{

    });
 }

    onChangeDate(holiday){
    }
    getSelectedCompany(company_id: any){
      }
 }

A: Replace new Calendar('#calendar') with  new Calendar('#calendar',{enableRangeSelection: true});
then you can get it here:
document.querySelector('#calendar').addEventListener('selectRange', function(e) {
  console.log("Select the range: " + e.startDate + " - " + e.endDate);
})

Year Calendar Documentaion
Here is a Stackblitz


text:
Q: Error with FirebaseUI RecyclerView I am getting this error while running an app.I have posted my code below.
09-23 15:40:02.995 23658-23677/com.cleanpune.android.cleanpuneproject E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.internal.zzro.zzg
09-23 15:40:05.985 23658-23694/com.cleanpune.android.cleanpuneproject E/NativeCrypto: ssl=0x5d26e508 cert_verify_callback x509_store_ctx=0x5e497a40 arg=0x0
09-23 15:40:05.986 23658-23696/com.cleanpune.android.cleanpuneproject E/NativeCrypto: ssl=0x5d26e328 cert_verify_callback x509_store_ctx=0x5e597a40 arg=0x0
09-23 15:40:05.987 23658-23694/com.cleanpune.android.cleanpuneproject E/NativeCrypto: ssl=0x5d26e508 cert_verify_callback calling verifyCertificateChain authMethod=DHE_RSA
09-23 15:40:05.988 23658-23696/com.cleanpune.android.cleanpuneproject E/NativeCrypto: ssl=0x5d26e328 cert_verify_callback calling verifyCertificateChain authMethod=DHE_RSA
09-23 15:40:08.181 23658-23742/com.cleanpune.android.cleanpuneproject E/NativeCrypto: ssl=0x5ec91e38 cert_verify_callback x509_store_ctx=0x5e497ab0 arg=0x0
09-23 15:40:08.184 23658-23742/com.cleanpune.android.cleanpuneproject E/NativeCrypto: ssl=0x5ec91e38 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
09-23 15:40:12.161 23658-23658/com.cleanpune.android.cleanpuneproject E/test: Exception
09-23 15:40:12.170 23658-23658/com.cleanpune.android.cleanpuneproject E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                com.google.firebase.database.DatabaseException: Found two getters or fields with conflicting case sensitivity for property: details
                                                                                at com.google.android.gms.internal.zzaln$zza.zzst(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaln$zza.<init>(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaln.zzj(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaln.zzd(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaln.zzb(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaln.zza(Unknown Source)
                                                                                at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                                                at com.firebase.ui.database.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:154)
                                                                                at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:143)
                                                                                at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:183)
                                                                                at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471)
                                                                                at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504)
                                                                                at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741)
                                                                                at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
                                                                                at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
                                                                                at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
                                                                                at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
                                                                                at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
                                                                                at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
                                                                                at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2906)
                                                                                at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1482)
                                                                                at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:147)
                                                                                at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:294)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:579)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:547)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
                                                                                at android.os.Handler.handleCallback(Handler.java:725)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:153)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5299)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                                at dalvik.system.NativeStart.main(Native Method)

I dont know where am I going wrong.Kindly Help please!
I am included all the libraries and am usinhg picasao for retrieving images.
Here is the TestActivity.java
public class TestActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private DatabaseReference databaseReference;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");

    recyclerView = (RecyclerView) findViewById(R.id.posts_list);
    recyclerView.setHasFixedSize(true);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));

}
@Override
public void onStart() {
    super.onStart();
    mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
            Post.class,
            R.layout.posts_row,
            PostViewHolder.class,
            databaseReference

    )
    {
        @Override
        protected void populateViewHolder(PostViewHolder viewHolder, Post model, int position) {
            viewHolder.setDetails(model.getDetails());
            viewHolder.setLocation(model.getLocation());
            viewHolder.setImages(getApplicationContext(),model.getImages());

        }
    };

    recyclerView.setAdapter(mAdapter);

}
public static class PostViewHolder extends RecyclerView.ViewHolder {

    View view;

    public PostViewHolder(View itemView) {
        super(itemView);
        view = itemView;

    }

    public void setLocation(String location) {
        TextView textView = (TextView) view.findViewById(R.id.post_location);
        textView.setText(location);
    }

    public void setDetails(String details) {
        TextView textView = (TextView) view.findViewById(R.id.post_location);
        textView.setText(details);
    }

    public void setImages(Context context, String images) {
        ImageView image = (ImageView) view.findViewById(R.id.post_image);
        Picasso.with(context).load(images).into(image);

    }
 }

}

Here is the Model Post class
public class Post {
public String Details, Location, Images;

public Post(String details, String location) {
    Details = details;
    Location = location;
}

public String getDetails() {
    return Details;
}

public String getLocation() {
    return Location;
}
public Post(){

}

public String getImages() {
    return Images;
}

}

A: There are a few mistakes in your code that confuse the Firebase client:

*

*your fields are public, but you also have getters/setters

*your fields names start with a uppercase letter

If you change your class to be more idiomatic, it looks like
public class Post {
    private String details, location, images;

    public Post(){ }
    public Post(String details, String location) {
        this.details = details;
        this.location = location;
    }

    public String getDetails() {
        return details;
    }

    public String getLocation() {
        return location;
    }

    public String getImages() {
        return images;
    }
}

Alternatively, you can have a class with only public fields (and no getters/setters):
public class Post {
    public String Details, Location, Images;

    public Post(){ }
    public Post(String details, String location) {
        Details = details;
        Location = location;
    }
}

A: Kindly try using this model class
@IgnoreExtraProperties
public class Post {
    public String Details, Location, Images;

    public Post(){

    }

    public Post(String details, String location, String images) {
        Details = details;
        Location = location;
        Images = images;
    }

    @Exclude
    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();
        result.put("Details", Details);
        result.put("Location", Location);
        result.put("Images", Images);
        return result;
    }
}


text:
Q: HttpClient to send JSON String Windows Form app I'm writing a DLL but testing with a windows app and I have objects that I convert to JSON via
 Private Function SeraializeStoreInfo(objt As JSON_postStoreInfo) As String
     'This takes in an object of the JSON_postStoreInfo class
     'and converts it to JSON to send
     Dim JsonString As String
     JsonString = JsonConvert.SerializeObject(objt)
     Return JsonString
 End Function

I then want to send this JSON string to a webservice to process. I just want to send the JSON string I've just serialized. When I pass the JasonString in as Content to this function as a string, I get an error saying that

HttpStringContent is not defined. and that Content must be of the type HttpContent.

How can a get around this?
Private Async Function SendStoreInfo(Content As String) As Task(Of String)
     Dim stringContent As New HttpStringContent(Content, UnicodeEncoding.Utf8, "application/json")
     Dim aClient As New HttpClient()
     'Dim theContent As New StringContent(SR.ReadToEnd(), System.Text.Encoding.UTF8, "application/json")
     ' Dim theContent As New StringContent(Content, System.Text.Encoding.UTF8, "application/json")
     'Post the data
     Dim aResponse As HttpResponseMessage = Await aClient.PostAsync(theUrl, Content)
     If (aResponse.IsSuccessStatusCode) Then
         'this gets the response
         StoreResponse = aResponse.ToString
     Else
         'show the response status code
         Dim failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " – Reason: " + aResponse.ReasonPhrase
     End If
 End Function


text:
Q: Show that the derivative of any solution of equation $ y'' + py'+qy=0$ is also a solution. Solving $ y'' + py'+qy=0$ (where $p$ and $q$ are constants) :
Since $e^{mx}$ has the property that its derivatives are all constant multiples of the function itself, We consider $y=e^{mx}$ and substitute in the equation $ y'' + py'+qy=0$. This gives us $ ( m^2+pm+q)e^{mx}=0 $ and we solve for the roots of equation $m^2+pm+q=0$. After finding the nature of roots there can be three type of solutions possible and their formulas are derived. But the question states:

Without using the formulas obtained in this section (the solutions obtained after solving roots and substituting them), show that the
  derivative of any solution of equation $ y'' + py'+qy=0$ is also a
  solution.

Approach : Let the solution by $y$, if $y'$ is also a solution then it must satisfy $ y''' + py''+qy'=0$. Now if I solve this then it will be the same case as above but will have  $ m( m^2+pm+q)e^{mx}=0 $ instead. Where do I go from here?

A: The ODE is autonomous and homogeneous. Thus if $y(x)$ is a solution, so also are the shifted functions $y(x+a)$ and the linear combinations $\frac{y(x+a)-y(x)}a$ for $a>0$ including the limit for $a\to0$ which is $y'(x)$.

A: This is trivial. But you have to get things straight. If $y$ is a solution to the DE you need to show that $y'$ is a solution - a proof of this that starts out saying "if $y'$ is a solution..." is no good at all, since it assumes what you're trying to prove.
Suppose $y$ is a solution to the DE. Just to give it a name, say $z=y'$. Now you can simply calculate $$z''+pz'+qz=\dots;$$hence $z''+pz'+qz=0$, qed.


text:
Q: What's the deal with terminal colors? There are 256 terminal color escapes available:

*

*8 "system" colors (0 - 7)

*8 "bright" system colors (8 - 15)

*216, or 6*6*6 "RGB" colors (16 - 231)

*24 "grayscale" colors (232 - 255)

The "RGB" colors are what I'm wondering about.
The first six colors, from 16 to 21, map to the following hex RGB values:

*

*16: 000000

*17: 000054

*18: 000087

*19: 0000af

*20: 0000d7

*21: 0000ff

Now the blue values only, in decimal:

*

*16: 0

*17: 84

*18: 135

*19: 175

*20: 215

*21: 255

In other words, the RGB value goes up by 84, then 51 (84 + 51 = 135), then 40 the rest of the way.
This cycle of 6 values from 0 to 255 is repeated 36 times, first with blue, then green, then red, eventually forming our "cube" of 216 terminal colors:

My question is: Why?
Does anyone know if there is a historical/technical reason for this, or was it just an arbitrary decision made by whoever had to decide what the color codes meant? Did this mapping come to exist before RGB was such a universal convention? Why not go up by 42, 42, 42, 43, 43, 43?

A: In the sense suggested, it was "arbitrary": a developer chose to split up the set of 256 colors by reserving the first 16 colors to match existing usage, and then noticed that he could get a cube after discounting a conveniently-sized grayscale ramp.  Neither of the developers (256 or 88) referred to human-factors publications.  They simply chose the steps of color for convenience in computation and what "looked nice".
The technical details as such are in the xterm FAQ Can I set a color by its number?

A: In a course that I took in college, it was said to me that the human eye can detect about 256 shades of any one color [or so close that a byte can effectively match that], so 256 of each of the three primary colors allows for all of the colors that the human eye can see. The rest I am unsure of.

A: egmont's comment gives a hint:

I'm really not sure though that that'd look evenly distributed to the human eye.

Below is a comparison of the web-safe color palette to the terminal color.

Try to trace the color from bottom left (absolute green) to top right (absolute blue). If you find that the terminal palette blends the color more naturally, you might be right. In case you find it difficult to see how the color changes due to the surrounding colors, I've prepared two rows of black-blue gradient on the bottom left, and green-blue gradient on the bottom right. The top row corresponds to linear RGB value, while the bottom row is what the terminal palette uses (Note: I'm using the palette specified in the question).
The choice of the values in the terminal palette is actually grounded on gamma correction. You may want to check out Minute Physics' video on this topic. Basically, we are able to better perceive increase in brightness in the dark regions compared to the bright regions. Therefore, instead of assigning brightness values linearly to actual light intensity, a mapping is done so that dark colors cover a larger range of values when saving the color as data.
Looking at the black-blue gradient in the image, we see that the top row is biased towards dark shades of blue, while the bottom row is more evenly spread. Meanwhile, the top row in the green-blue gradient seems to be darker in the middle compared to the edges, while in the bottom row the transition seems more smooth.


text:
Q: Using gradient vector to find curve on plane I have this problem:
The temperature $T$ in a square region of the $(x,y)$ plane is given by the formula:
$$T(,)=^3−+11$$ for $$,∈(−2,2).$$
An ant inside the square region is initially at the point $(1,\frac{1}{3})$.
What is the equation of the curve the ant should move along in order to ensure that the temperature it experiences decreases as rapidly as possible?
So far I have gotten the partial differentials:
$$ f_x=-1, f_y=3y^2$$
So the gradient vector at any point $(x,y)$ has the vector equation $(-1 , 3y^2)$. But then to follow the steepest descent we should go away from the gradient vector in the opposite vector so $(1,-3y^2)$.
But then I am not sure where to go next to find the equation of the curve?
Is it a function with $f(1)=\frac{1}{3}$ and $f'(x)=-3y^2$
I am quite confused, wondering if anyone could shed any light on this? Thank you!

A: Hint:
So at the beginning the ant will move a $d {\bf s} = -\nabla T({\bf s}_0)v dt$

A: The easiest way is to solve the problem parametricaly. Write the trajectory of the ant as
$$
\gamma(t)=(x(t),y(t))
$$
Then to have the stepest descent in temperature we must have
$$
\gamma'(t)=-\nabla T(\gamma(t))
$$
In coordinates this reads
$$
x'(t)=1/3,\quad y'(t)=-3y^2(t)
$$
You can integrate this equation, using the initial condition to get
$$
x(t)=t/3+1, \quad \frac{1}{y(t)}-\frac{1}{1/3}=3t\Rightarrow t=\frac{1}{3y(t)}-1
$$
and you get the equation by replacing $t$ in the $x$ equation
$$
x=\frac{1}{9y}+2/3
$$


text:
Q: WebAPI 2 and RouteDebugger I'm using Vs2012 and installed the Web Tools 2013.1 for VS2012 from here:
http://www.microsoft.com/en-us/download/details.aspx?id=41532
I then proceeded by creating a new WebAPI 2 project and installed RouteDebugger from here:
http://www.nuget.org/packages/WebApiRouteDebugger/
When I try to view the routedebugger page using a browser (locahost:xxxx/rd), nothing is displayed.
However, if I created a new MVC4 application using WebAPI and install the RD package, it works fine.
Is there a way to get RouteDebugger to work with WebAPI 2?


text:
Q: Vulkan flickering for small meshes I am rendering different models. Big models (more than a thousand triangles) are rendered without issue, however small models(a single triangle, or 12 triangles) flicker.
The way I am currently rendering involves 2 passes, so I assume the flickering comes from an absence of proper barriers.
The execution goes:

*

*start to render pass,

*render to texture (image attachment of FB),

*stop pass.

*start pass,

*render to main display

*end pass.

There is only a single global graphics queue. Following the vulkan tutorial, I have a command buffer for every image in my swapchain, and I record commands to each buffer in that list, like so:
    for(auto &cmd : cmd_buffers)
    {
        std::array<vk::ClearValue, 2> clears = {};
        clears[0].color = vk::ClearColorValue(array<float, 4>({0,0,0,0}));
        clears[1].depthStencil = vk::ClearDepthStencilValue(1.0f, 0.0f);
        vk::RenderPassBeginInfo render_pass_info(
            *render_pass, *(framebuffers[index]), {{0,0}, extent},
            clears.size(), clears.data()
        );

        cmd.beginRenderPass(&render_pass_info, vk::SubpassContents::eInline);
        index++;
    }
    /* submit more instructions to the command buffers later */

For the off screen target (FB) I only record a single command buffer.
I call my first render pass as described above, and then, immediately before calling the second render pass, I try waiting on an image barrier:
void RenderTarget::WaitForImage(VulkanImage* image)
{
    vk::ImageMemoryBarrier barrier = {};
    // TODO(undecided): maybe this isn't always true
    barrier.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
    barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
    barrier.srcAccessMask = vk::AccessFlagBits::eShaderWrite;
    barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
    barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    barrier.image = image->GetImage();
    barrier.subresourceRange =
        vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1);

    vk::CommandBuffer command_buffer = h_interface->BeginSingleTimeCommands();
    command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllGraphics,
        vk::PipelineStageFlagBits::eFragmentShader, {}, 0, nullptr, 0,
        nullptr, 1, &barrier);
    h_interface->EndSingleTimeCommands(command_buffer);
}

And then somewhere else in the code I call it:
    display_target.WaitForImage(&image);
    active_target_id = 0;
    display_target.StartFrame();
    render_presentation.AddDrawData(quad_buffer, {uniform_data},
        {{&image, 1}});
    display_target.EndFrame();

Based on the behaviour I have seen, I assume my issue is a synchronization problem, however, the image barrier code doesn't seem to solve the flickering.
Am I using the barrier wrong? Should I look into other possible sources of error (and if so, which)?


text:
Q: How do I print a selected list item from my MySQL database using php? Let's say I have a menu with a category called animals. I access the MySQL database like so for the animals.
include_once 'config.inc';
$mysqli=new mysqli($mysql_host, $user, $password, $database);
$query="select distinct name from animals";
$res=$mysqli->query($query);
while ($row=$res->fetch_assoc()) {
    print "{$row['name']}";
echo "</li>", "<li>";

I can get all the animals to print as list items with no problem. Now I want to use php to print out the animal that I click on. However, when I call this php file shown below, only the first list item will print properly. Please help
<?php
include_once 'config.inc';
$mysqli=new mysqli($mysql_host, $user, $password, $database);
$query="select distinct name from animals";
$res=$mysqli->query($query);
$row=$res->fetch_assoc();
echo "{$row['name']} selected";

A: Try like this :
if ($res = $mysqli->query($query)) {
   while ($row = mysqli_fetch_assoc($res)) {
        echo $row['name'];
    }
}

A: I am not sure whether my answer is true or not, I am new in PHP, too.
Could you please try this one?
$query = "SELECT distinct name FROM animals";
$query_result = $sqli->query($query);
$query_row = $query_result->fetch_assoc();
$new = $query_row['name'];
echo $new;


text:
Q: Deleting a node from a Binary Search Tree using only a node's key I'm adding some functions/working with a pre-written program (a customer account database), which uses a Binary Search Tree, and I'm trying figure out how and why this remove method works:
    public void deleteCustomer()
    {
        System.out.println("Enter the account number of the customer to be removed.");
        String accountNumber = userInput.next();

        try {
            records.remove(new CustomerAccount(accountNumber));
        }

        catch(ElementNotFoundException e) {
           System.out.println("There is no account with that number.");
        }
    }

Where CustomerAccount is an object that contains the accountNumber field, and records is a BST. The records' remove function looks like this:
    public boolean remove(E target) {
        return delete(target) != null;
    }

and recursively calls a standard looking delete function for a BST. But my question is, what is actually happening with this line?
records.remove(new CustomerAccount(accountNumber));

It's calling the method using a new CustomerAccount? What's actually happening under the hood here? And is this a standard way of dealing with this situation? I've never seen anything like it, but I'm newish to working with data structures so I'm not sure. Any help or clarification would be fantastic, thank you!


text:
Q: SQL to calculate retention curve We have an event table with users registering and playing our games.
So assume we have three fields
timestamp ts
int  userId
int  eventId               (I.e. 1 = Register, 2 = Login)

What we want to calculate is the retention ratio from a given day and onward. A user should be considered active if he have played the last week (i.e. 7 days)
E.g. lets say I want to se the retention curve for users registered 2013-08-01
The output table could be something like
Date         Day     Reg 2013-08-01,  Active,    Retention
2013-08-01   1       24 567           24 567     100%
2013-08-02   2       24 567           24 567     100%
2013-08-03   3       24 567           24 567     100%
2013-08-04   4       24 567           24 567     100%
2013-08-05   5       24 567           24 567     100%
2013-08-05   6       24 567           24 567     100%
2013-08-05   7       24 567           24 567     100%
2013-08-05   8       24 567           24 125     98.2%
2013-08-05   9       24 567           24 027     97.8%
2013-08-05  10       24 567           23 997     97.5%
2013-08-05  11       24 567           23 200     96.3%
2013-08-05  12       24 567           22 890     95.3%
....

My SQL skills are simply to bad! Free beers (Or GT's In Stockholm ...) for anyone who comes up with this SQL!

A: To get the number of active users I would probably try to do something similar to this in Google BigQuery:
SELECT count(distinct U1.userId, 1000000) as activeUser,
       left(U1.startTime, 10) AS day
FROM [YourDataSet.YourTable] as U1
JOIN EACH [YourDataSet.YourTable] as U2 on U1.userId = U2.userId
WHERE U2.startTime = U1.startTime -- if the user came today OR
OR (U2.startTime < U1.startTime AND
    TIMESTAMP(U2.startTime) >= DATE_ADD(TIMESTAMP(U1.startTime), -7, "DAY")) -- if the user came sometime in the past and not more than 7 days
GROUP BY day
ORDER BY day

*Note, in my case the date is a string. For your specific problem you will probably need to add custom conditions to handle your event type. Please also verify the condition to check if it is earlier than 7 days as I have no tested this part.
This query only allow to get the number of active users. For the rest you may need to do it in another query. Maybe there is a way to it all at once with unions or something similar but that would be a really long query. Hope this helps!


text:
Q: Can decoherence time be shorter than Planck time? Decoherence times can be estimated and are inverse functions of mass.  Since there are no upper bounds on mass, can decoherence time be shorter than Planck time?

A: of course, the decoherence time may be - and quite often is - much shorter than the Planck time. There exists no law saying that "all quantities with the units of seconds have to be longer than the Planck time". The only genuine limitation is that "if you try to measure the timing of an event with the precision better than the Planck time, you will fail." This is an entirely different thing.
The decoherence time is the (approximate) time after which the off-diagonal elements of the density matrix between two macroscopically "different" states of a sufficiently macroscopic system decrease to a negligible fraction of its initial value. The processes that drive decoherence - that make the off-diagonal elements drop - are results of interactions of the macroscopic object with the environment. The more strongly the object interacts with the environment and the higher number of environmental degrees of freedom we are forgetting - i.e. tracing over - the more quickly the decoherence proceeds.
Of course that if you talk about Schrödinger's cat that is emitting lots of photons and other things, the decoherence time - for the "dead" and "alive" states - will be tiny. If it is not shorter than the Planck length, it's surely easy to consider just slightly bigger systems for which it will be shorter than the Planck time. The statement that it is shorter than the Planck time doesn't mean that you have been actually able to "see" events in spacetime with a trans-Planckian resolution, so it's no violation of the laws of quantum gravity.
Much more generally, there is a lot of confusion among the laymen about the statement that "distances and times can't be shorter than the Planck scale". We must refine what distances and times we're talking about. Obviously, the statement may only hold for Lorentz-invariant quantities whose units are either seconds or meters. Not all "lengths" and "times" are equal or the same thing. It depends "length of what" or "time of what" you're talking about. Lengths of different things and times of different things have different properties.
Only when the proper distances between some important points or events decrease beneath the Planck length, one may possibly face some contradictions with quantum gravity - or one produces a black hole that damages the experiment. But for example, the wavelength of an electromagnetic wave (which is the same thing as its periodicity in time, multiplied by $c$) can be much shorter than the Planck length. Arbitrarily short-wavelength photons exist; this is guaranteed by the theory of relativity. An observer may be accelerated to a speed that approaches the speed of light arbitrarily closely, and when it's done, the energy of the original photon may increase arbitrarily high - and the wavelength may become arbitrarily short by the Lorentz contraction. Nothing new is happening to such a photon: it's the same photon that had a low frequency in another inertial system.
There can't exist any restriction on the wavelength of waves (of photons etc.). But when proper distances inside an object (formally) drop beneath the Planck length, you may be sure that the laws of geometry have to be severely modified, to say the least; one should use something else than ordinary geometry to describe what is going on and where it is going on. Similarly for times. However, the density matrix linked to a macroscopic body is not a "real object": it is just a set of numbers that can be used to predict probabilities of various observations of the macroscopic body. Such things can change arbitrarily quickly. And indeed, the more massive body you consider, the shorter the decoherence time will be.
(When people misleadingly talk about the "collapse of the wave function", this "process" may also occur even infinitely quickly. It's no violation of relativity because the wave function is not a "real object": it is a set of numbers encoding the probabilities - and phases - of things we can predict. When one carefully checks whether some genuine information may be transmitted faster than light between two distant EPR entangled particles, the answer is a resounding No. This fact - causality - may be proved easily in quantum field theory. So the EPR particles won't allow you to speed up the communication with other galaxies.)
Best wishes
Lubos

A: We should not claim that we understand Planck scale physics enough to answer this question. We can't even claim "there are no upper bounds on mass". Sure, one can gather a lot of mass, but the mass (energy) associated with a degree of freedom (whatever that is in Planck scale physics) could very well be delimited.
In short: we can all speculate, but no-one can can answer this question.


text:
Q: UI Component Form Validation: Pattern method I've got an admin ui_component form which has a listing of fields and I'm adding validation to them.  One I'd like to use a custom pattern. The form in general works, it's just this "pattern" validation that's causing an issue.
So here is the relevant <field> setup from my module_controller_form.xml file:
    <field name="my_custom_filed">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">My Custom Filed</item>
                <item name="dataType" xsi:type="string">text</item>
                <item name="formElement" xsi:type="string">input</item>
                <item name="source" xsi:type="string">model_name</item>
                <item name="dataScope" xsi:type="string">my_custom_field</item>
                <item name="sortOrder" xsi:type="number">1</item>
                <item name="validation" xsi:type="array">
                    <item name="required-entry" xsi:type="boolean">true</item>
                    <item name="no-whitespace" xsi:type="boolean">true</item>
                    <item name="validate-pattern" xsi:type="string">/^[a-z][a-z0-9_.-]$/i</item>
                </item>
            </item>
        </argument>
    </field>

The above generally works.  I get a javascript error about the string /^[a-z][a-z0-9_.-]$/i not having the method test().  According to validation.js I see the content for the pattern validation method as being:
    "pattern": [
        function (value, element, param) {
            return this.optional(element) || param.test(value);
        },
        'Invalid format.'
    ],

When this code runs, it runs with the following invocation:
validations['pattern']('Test String', [element], "/^[a-z][a-z0-9_.-]$/i")

Sadly, it is passing the value of the <item> node as a string, instead of translating that to a RegExp object.
Is there a way to specify the validation pattern from the *_form.xml and have it properly transform the value to a regular expression object?  I haven't really seen any core modules use this validation within their XML declarations, but it seems like it should still work.
UPDATE
I'm still looking into this, trying to find where the form XML for the validation node is translated into the javascript bindings.  Does anyone know where I can start searching for that?

A: This appears to be a core bug within Magento itself.  The string for the regular expression isn't being converted properly using new RegExp() or if you provide a native regular expression (e.g. /[a-z][a-z0-9]+/i) it's not interpreted as such.
I submitted the issue via GitHub and confirmed that it exists in Magento CE 2.1.7 as well as the EE.  Hopefully they fix the bug in the next release.
https://github.com/magento/magento2/issues/9919
EDIT: As of Magento 2.2.2 this has been fixed.


text:
Q: Is there a better way to initalize pointers in c++? Below I have a bit of code for implementing Huffman compression.
What I was curious about was if I could initialize the left and right pointers without including cstdlib, or rather, if I could initialize an empty memory location for storing the left and right without using malloc.
Also, in my combine function, I do not want to use "NULL" for the string parent node of my left and right, but would rather have an empty string. Will I have to make a new constructor for this? I get an error (basic_string::_M_construct null not valid) when I replace "NULL" with nullptr.
#include <string>
#include <cstdlib>

#ifndef PRIORITY_NODE
#define PRIORITY_NODE

namespace Huffman
{
  class PriorityNode
  {
    private:
      std::string key; // The character sequence to compress
      long frequency = 0;  // The frequency of the character sequence
      PriorityNode* left = (PriorityNode*)malloc(sizeof(PriorityNode));
      PriorityNode* right = (PriorityNode*)malloc(sizeof(PriorityNode));

    public:
      PriorityNode(std::string k, long f): frequency(f), key(k){};
      std::string getKey() const{ return key;}
      long getFrequency() const{ return frequency;}
      void setLeft(const PriorityNode& left){*this->left = left;}
      void setRight(const PriorityNode& right){*this->right = right;}
      PriorityNode& getLeft() const{ return *left;}
      PriorityNode& getRight() const{ return *right;}
      friend PriorityNode combine(const PriorityNode& lhs, const PriorityNode& rhs)
      {
        long ret_freq = lhs.getFrequency() + rhs.getFrequency();
        PriorityNode ret = PriorityNode("NULL", ret_freq);
        ret.setLeft(lhs);
        ret.setRight(rhs);
        return ret;
      };
  };
}

#endif

A: So a couple of points.

*

*key is a string, not a pointer. It makes no sense to set it to nullptr, i am guessing "NULL", is just a stand in for when the key has no value. Instead of this, just use an empty string "".

*You should try to avoid this manual memory management for several reasons. First of all you have no destructor, so your memory that you malloc is never freeed meaning you have a memory leak. Secondly, you allocate memory for the sub nodes, even if you do not need to. I would suggest something more like the following:
 class PriorityNode {
 private:
   ...
   std::shared_ptr<PriorityNode> left, right; // Default constructs to nullptr
   ...
   friend PriorityNode combine(const std::shared_ptr<PriorityNode> lhs,
       const std::shared_ptr<PriorityNode> rhs) {
     PriorityNode ret = PriorityNode("", ret_freq);
     ret.setLeft(lhs);
     ret.setRight(rhs);
     return ret;
   };

A: The empty string is "". You can pass that to the existing constructor. std::string doesn't distinguish empty strings and NULL pointers like C strings. It is not allowed to initialize an std::string with a NULL pointer. If you need a separate null state, use std::optional<std::string>.


text:
Q: Adding a DF with a variable number of rows to one with a static number I have a Dataframe that is 25 rows, seen below
structure(list(hc_y = c(250, 250, 250, 250, 250, 275, 275, 275,
275, 275, 300, 300, 300, 300, 300, 325, 325, 325, 325, 325, 350,
350, 350, 350, 350), hc_x = c(-50, -25, 0, 25, 50, -50, -25,
0, 25, 50, -50, -25, 0, 25, 50, -50, -25, 0, 25, 50, -50, -25,
0, 25, 50), opp = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), oaa = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, -25L
))

And I have another dataframe that could have anywhere from 1-25 of those rows when the column opp > 0. For Example, this:
structure(list(hc_x = c(-50, -50, -50, -50, -25, -25, -25, -25,
-25, 0, 0, 0, 0, 25, 25, 25, 25, 50, 50, 50, 50, 50), hc_y = c(250,
300, 325, 350, 250, 275, 300, 325, 350, 250, 300, 325, 350, 250,
275, 325, 350, 250, 275, 300, 325, 350), oaa = c(0.014, 0.084,
0.053, -0.266, 0.281, 0.012, 0.018, 0.017, 0.109, -0.048, 0.017,
0.166, 0.524, -0.544, 0.163, 0.036, 0.412, -0.005, 0.033, 0.061,
1.726, 0.528), opp = c(2, 4, 2, 5, 8, 1, 1, 2, 2, 3, 2, 1, 3,
4, 3, 1, 3, 1, 2, 3, 5, 9)), row.names = c(NA, -22L), groups = structure(list(
    hc_x = c(-50, -25, 0, 25, 50), .rows = structure(list(1:4,
        5:9, 10:13, 14:17, 18:22), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

What I want is to combine these into one dataframe when it is present in the second data set. If it is not present it should maintain the information from the first one, using the grouping vars of hc_y an hc_x.
So the final product should always be 25 rows. How can this be done?

A: I called the dataframes df1 and df2.
left_join(df1,df2)

Is that what you meant? I didnt understand your question


text:
Q: Why does RAND sometimes produce multiple results in a MySQL call? I have table agent which includes 13 agent IDs and agent names.
agent_id|agent_name|
--------|----------|
       1|Jack      |
       2|Jill      |
       3|Jo        |
...

When I run this query...
select agent_name from agent where agent_id = (FLOOR( 1 + RAND( ) * 13 ))

...MySQL sometimes returns 0 names and sometimes returns many names. Since (FLOOR( 1 + RAND( ) * 13 )) on its own always seems to return a single, non-zero integer, I would expect to get a single name back, but this is not the case. On testing the above query, the following number of names are returned on each execution;
Execution | Total Names Returned
1         | 3
2         | 2
3         | 1
4         | 0
5         | 1
6         | 1
7         | 0
8         | 0
9         | 1
10        | 4

Clearly, when one runs...
select agent_name from agent where agent_id = 3

...the same, single, name is returned each time.
I see that the docs explain that

RAND() in a WHERE clause is evaluated for every row (when selecting from one table) or combination of rows (when selecting from a multiple-table join). Thus, for optimizer purposes, RAND() is not a constant value and cannot be used for index optimizations

I am not sure why this would mean that a single call would return many rows.
If I add LIMIT 1
select * from agent a where agent_id = (FLOOR( 1 + RAND() * 13 )) limit 1

...then the query sometimes returns NULL.
Questions

*

*Why does RAND return different numbers of records?

*What is the proper way to return a single random agent?

A: As the documentation says, it is evaluated for each row. It means, the following:

*

*MySQL gets all rows

*For each row, executes RAND() and if RAND() == id, return the row

For example
Get all rows

*

*ID = 1, RAND() = 3, no return

*ID = 2, RAND() = 2, return

*ID = 3, RAND() = 4, no return

*ID = 4, RAND() = 4, return

In this case, you have two results.
If you want to get random agent, maybe better approach would be
SELECT * FROM `agent` ORDER BY RAND() LIMIT 1

A: I assume that your first query is sometimes returning multiple records because RAND() is being evaluted for each record in the query.  If you just want a single random agent, then use:
SELECT agent_name
FROM agent
ORDER BY RAND()
LIMIT 1;

To further explain your current observations, the following expression is being evaluated once per each agent record:
(FLOOR( 1 + RAND( ) * 13 ))

Imagine that for each record, the above happens, by chance, to equal the agent_id.  If so, then your first query would return all 13 records.  By the way, the documentation link you cited basically says this.


text:
Q: How do I find the sum value of an array of objects in a loop? I'm not sure if the wording of my question is accurate based on my description of the problem so please edit if it can be more accurate.
I am trying to build a stamp duty calculator to improve my JS, i have an array of objects with different "bands" and "percents" which I am using to calculate the tax based on a users input. I have attached a image for better understanding

I am displaying the amount of tax for each band in a table and I am trying to find the total tax by finding the sum of all values in the "TAX" column.
Currently it is just displaying the highest value.
I have tried all i can thing off and nothing has worked, how can I fix this?
here is my code,
 $(function (jQuery) {

     (function stampDutyCalculator() {

     var taxbands = [
         {
             min: 0,
             max: 125000,
             percent: 0
         },
         {
             min: 125000,
             max: 250000,
             percent: 0.02
         },
         {
             min: 250000,
             max: 925000,
             percent: 0.05
         },
         {
             min: 925000,
             max: 1500000,
             percent: 0.1
         },
         {
             min: 1500000,
             max: null,
             percent: 0.12
         }
     ];

     var secondTaxbands = [
         {
             min: 0,
             max: 125000,
             percent: 0.03
         },
         {
             min: 125000,
             max: 250000,
             percent: 0.05
         },
         {
             min: 250000,
             max: 925000,
             percent: 0.08
         },
         {
             min: 925000,
             max: 1500000,
             percent: 0.13
         },
         {
             min: 1500000,
             max: null,
             percent: 0.15
         }
     ];

     var tableRow = "
{taxband}	{percent}	{taxable}	{TAX}
",
         table = $("#explained-table"),
         results = $("#results"),
         effectiveRate = $("#effective-rate");

         $('#calculate').on('click', function calculateButton() {
             if ($("#input-value").val() !== '') {
                calculateStampDuty();
             }
         });

         function calculateStampDuty() {

            var bands = taxbands,
                userInput = parseInt($("#input-value").val(), 10),
                row;

            if ($('#second-home').is(':checked')) {
                bands = secondTaxbands;
            }

            if (table.length) {
                table.find("tr:gt(0)").remove();
            }

            var taxableSum = function (x, y) {
                var maxBand = (x !== null) ? Math.min(x, userInput) : maxBand = userInput;
                return maxBand - y;
            },
                TAX = function (taxablesum, x) {
                return (taxablesum * x).toFixed(2);
            },
                effectiverate = function(tax) {
                    return Math.round(tax / userInput * 100).toFixed(1);
            },
                numberWithCommas = function (x) {
                var parts = x.toString().split(".");
                parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                return parts.join(".");
            };

                        for (var i = 0; i < bands.length; i++) { //for loop to loop through array of objects

            var min = bands[i].min, //variables to be used as arguments in functions above, not best practice to declare functions in loop
                max = bands[i].max,
                pct = bands[i].percent,
                taxablesum = taxableSum(max, min),
                tax = TAX(taxablesum, pct),
                eRate = effectiverate(tax);

            if (max !== null) { //replaces template tags with min, max and percent values in object
                row = tableRow.replace("{taxband}", "£" + min + " - " + "£" + max).replace("{percent}", (pct * 100) + "%");
            } else {
                row = tableRow.replace("{taxband}", "£" + min + "+").replace("{percent}", (pct * 100) + "%"); //used for last taxband
            }

            if (taxablesum < 0) {
                row = row.replace("{taxable}", "£" + 0 + ".00").replace("{TAX}", "£" + 0 + ".00");
            }   else if (userInput > 1500000) {
                    row = row.replace("{taxable}", "£" + numberWithCommas(taxablesum)).replace("{TAX}", "£" + numberWithCommas(tax));
                    results.text("£" + numberWithCommas(tax));
                    effectiveRate.text(eRate + "%");
            }   else if (userInput > 925000) {
                    row = row.replace("{taxable}", "£" + numberWithCommas(taxablesum)).replace("{TAX}", "£" + numberWithCommas(tax));
                    results.text("£" + numberWithCommas(tax));
                    effectiveRate.text(eRate + "%");
            }   else if (userInput > 250000) {
                    row = row.replace("{taxable}", "£" + numberWithCommas(taxablesum)).replace("{TAX}", "£" + numberWithCommas(tax));
                    results.text("£" + numberWithCommas(tax));
                    effectiveRate.text(eRate + "%");
            }   else if (userInput > 125000) {
                    row = row.replace("{taxable}", "£" + numberWithCommas(taxablesum)).replace("{TAX}", "£" + numberWithCommas(tax));
                    results.text("£" + numberWithCommas(tax));
                    effectiveRate.text(eRate + "%");
            }   else {
                    row = row.replace("{taxable}", "£" + userInput).replace("{TAX}", "£" + numberWithCommas(tax));
                    results.text("£" + (numberWithCommas(tax) * 0));
                    effectiveRate.text(eRate * 0 + "%");
            }

            table.append(row);

            console.log(Number(tax) );
        }
         }

     }());
 });

EDIT
here is a fiddle https://jsfiddle.net/p6c1w5r3/
some of buttons functionality is not completed yet,  I wanted to get the calculations correct first

A: Check this fiddle. https://jsfiddle.net/p6c1w5r3/7/
Basically we create another variable outside the loop called totalTax. Then inside the loop we add the tax value to this variable.
Finally, you should not set the label text every time, instead set it once at the end.
Oh btw, your tax calculation returns weird values when amount is less than 20000.

A: So i found the solution, after playing around with it a bit, the main problem was rooted in the taxablesum function returning negative numbers which was resolved with this piece of code
return Math.max(0, maxBand - min);

here is a link to the fiddle https://jsfiddle.net/nnyawjob/
Thanks for pointing me in the right direction

A: The error seems to be that in your tax calculation function you are receiving a negative value ( i didn't look deeper into it to check why thats the case ) but you can avoid that with this little helper function: Math.abs(x)
I have updated your js fiddle and it seems to work now (at least its displaying some tax value)
TAX = function (taxablesum, x) { //takes taxablesum function as parameater to calculate overall tax
    return (Math.abs(taxablesum) * x).toFixed(2);
},

https://jsfiddle.net/p6c1w5r3/1/
EDIT
this update contains a console log of the total_tax (the summed up taxes)
Hope this helps
https://jsfiddle.net/p6c1w5r3/4/


text:
Q: Eclipse android project - can't import libraries I'm quite new to android dev.
I'm starting a project in android studio, but I'm looking at some examples of other old apps, that seem to be only running on eclipse.
When I download these old apps I always get in eclipse some kind of missing package reference within the code, in this case it is complaining that the library com.jaalee.sdk and other are missing.
But looking at the project the library seems there.
Clearly I'm doing something wrong, how can I solve this issue?
Does Java/eclipse have some kind of package manager distribution like in c# Nuget packages?

A: hey what I am getting is that you haven't installed the com.jaalee.sdk package ,try to delete it and reinstall it once again.
let me know what happens,it works or not,else I will try to solve it once more.
also visit this link ,and see if it can be helpful:-https://www.eclipse.org/forums/index.php/t/814360/


text:
Q: Not removing aged data per HISTORY_RETENTION_PERIOD policy Environment: SQL Server 2017 Enterprise running on Windows Server 2016 Standard
Test Case
Create 2 identical temporal tables (differ only by name) where 1 table has HISTORY_RETENTION_PERIOD set to 1 day. The other table is set to INFINITE.
CODE:
CREATE TABLE dbo.TemporalPurgeTestNew
(   TemporalPurgeTestNewId          int             IDENTITY(1,1)
,   InsertedDate                    datetime2(0)
,   ModifiedDate                    datetime2(0)
,   UpdateNum                       int
,   CONSTRAINT  pk_TemporalPurgeTestNew
        PRIMARY KEY (TemporalPurgeTestNewId)
,   SysStartTime        datetime2 GENERATED ALWAYS AS ROW START NOT NULL
,   SysEndTime          datetime2 GENERATED ALWAYS AS ROW END   NOT NULL
 ,  PERIOD FOR SYSTEM_TIME (SysStartTime,SysEndTime))
 WITH (SYSTEM_VERSIONING = ON
    (   HISTORY_TABLE = dbo.TemporalPurgeTestNewHistory
    ,   DATA_CONSISTENCY_CHECK = ON
    ,   HISTORY_RETENTION_PERIOD = 1 DAY
    ));

GO

CREATE TABLE dbo.TemporalPurgeTestExistTbl
(   TemporalPurgeTestNewId          int             IDENTITY(1,1)
,   InsertedDate                    datetime2(0)
,   ModifiedDate                    datetime2(0)
,   UpdateNum                       int
,   CONSTRAINT  pk_TemporalPurgeTestExistTbl
        PRIMARY KEY (TemporalPurgeTestNewId)
,   SysStartTime        datetime2 GENERATED ALWAYS AS ROW START NOT NULL
,   SysEndTime          datetime2 GENERATED ALWAYS AS ROW END   NOT NULL
 ,  PERIOD FOR SYSTEM_TIME (SysStartTime,SysEndTime))
 WITH (SYSTEM_VERSIONING = ON
    (   HISTORY_TABLE = dbo.TemporalPurgeTestExistTblHistory
    ));

GO

Inserted 1 record in each table
Create a SQL Server Agent Job to modify the record in each table and let job run for 3 days.
On the 3rd day, verify table with retention period of 1 day has first day of data purged in associated history table and the 2nd history table still contain data from day one.
Alter 2nd table to set retention period to 1 day
CODE:
ALTER TABLE dbo.TemporalPurgeTestExistTbl
SET (SYSTEM_VERSIONING = ON
    (   HISTORY_TABLE = dbo.TemporalPurgeTestExistTblHistory
    ,   DATA_CONSISTENCY_CHECK = ON
    ,   HISTORY_RETENTION_PERIOD = 1 DAY
    ));

EXPECTED: data will be purged from 2nd historical table in same manner as 1st temporal table.
ACTUAL: aged data in 2nd historical table is not removed per retention policy set.
Is this expected behavior or am I missing a step in purging data in the second temporal table.

A: UPDATE:
I had the wrong assumption regarding Historical table purge.
I was expected the oldest data to be removed from table, but SQL Server does not guarantee order of data be be removed.
When I check by count of record, I can see data being removed.


text:
Q: Merging Shuffled DF with new output DF - Pandas I'm trying to merge two data frames; "shuffled" DF1 that is used to derive (predicted outputs) DF2. I was able to merge them together; however, the end results are always "not shuffled" DF1 merged with DF2. Therefore, giving a mismatch to the DF3.
df1 = shuffle(pd.read_csv("C:/Users/.."))

filename = ('C:/Users/..')
loaded_model = pickle.load(open(filename, 'rb'))

df2 = loaded_model.predict(df1)

df3= pd.merge(df1, df2, left_index=True, right_index=True)

Here's an example the problem.:

df1        df1 (Shuffled)
 0         3
 1         2
 2         1
 3         0

df2
0
0
0
1

expected df3 = (shuffled df1) + df2:
df1   df2
3     0
2     0
1     0
0     1

however, im getting:
df1   df2
0     0
1     0
2     0
3     1

Thanks in advance for the time and effort!


text:
Q: TouchableHighlight OnPress is not calling a function I'm making an app in React Native and i have a problem that i don't understand.
In fact, when i press a button of my list, the onPress property related to this button don't call my function.
_onPressButton=() => {
   Alert.alert("Lol");
}

_renderRow (rowData, sectionID) {
return (
  <TouchableOpacity style={styles.row} onPress={() => this._onPressButton}>
    <Text style={styles.boldLabel}>{rowData.name}</Text>
    <Text style={styles.label}>{rowData.art}</Text>
  </TouchableOpacity>
)
}

This two functions are in my class, outside the render(). There is the render :
render () {
return (
  <View style={styles.container}>
    <ListView
      renderSectionHeader={this._renderHeader}
      contentContainerStyle={styles.listContent}
      dataSource={this.state.dataSource}
      renderRow={this._renderRow}
      renderFooter={this._renderFooter}
      enableEmptySections
      pageSize={15}
    />
  </View>
  )
 }
}

So when I press my button, nothing happens :/. Is someone have an idea please?
Thanks for reading !

A: You have not invoked the _onPressButton function.
You can just pass this function on the onPress handler without using the arrow function, like this:
 onPress={this._onPressButton}

If you want to pass any parameters then you can wrap it around an arrow function.
onPress={() => {this._onPressButton('someParams')}}

P.S Your current code calls the onPress handler but does not invoke your _onPressButton function
 onPress={() => {this._onPressButton}} // _onPressButton is not invoked
 you have to invoke it as:

 {() => {this._onPressButton()}}

A: I think the correct way is to have both renderRow& onRowPress both binded on
constructor like this:
  constructor (props) {
    super(props)

    this.renderRow = this.renderRow.bind(this)
    this.onRowPress = this.onRowPress.bind(this)

  }

Then on renderRow
  renderRow (rowData) {
    return (
      <TouchableOpacity onPress={() => this.onRowPress(rowData)} >

      </TouchableOpacity>
    )
  }


text:
Q: Strange bar at top of my MacVim? There's a bar atop my MacVim where every time I open multiple buffers in one window, it lists them like so:

This would be fine, except if I then type ":bn" to get to the next buffer, the bar stops being accurate. It's showing a duplicate entry for 'contact.html' and no entry for 'bio.html':

This bar would be useful if it worked properly. But if it won't then I would like to just get rid of it. Problem is, I don't know how it got there.
So, does anyone know how to either fix this or get rid of it?
My .vimrc is here, if it helps: https://github.com/austintrose/Vim-Files. I couldn't find anything in my .vimrc related to it though. :-/
Thanks!

A: That looks like the "text mode" tab line. Normally, the tabs would be displayed in a GUI-based tab line, but this line (from your .vimrc):
    set guioptions=

removes the e option from guioptions which inhibits the GUI tabs and reverts to "text mode" tabs. The description of the e option of guioptions (:help 'go-e') has this to say:

Add tab pages when indicated with 'showtabline'.
  …
  When 'e' is missing a non-GUI tab pages line may be used.

If you want to disable the tab line, then you should probably just set showtabline to 0 so that it will always be disabled:
set showtabline=0

You can put this in your if has("gui_running") section if you only want this to apply to your GUI instances of Vim, or you can do it unconditionally to also disable the tab line in tty-based instances of Vim, too.
Alternatively, if you want to have GUI-based tabs, then make sure guioptions includes e, and showtabline is non-zero:
set guioptions=e  " instead of clearing this, set it to only `e`
set showtabline=1 " one is the default value

Incidentally, you can navigate the tabs with :tabnext and :tabprevious (in normal mode, gt and gT, respectively).


text:
Q: Filtering products depends user choice I got product page with option to filter by size\model\price and sort.
I did succeed make this work but with like 5-6 useEffect and it looks very massy.
I need some hints on how to make it work without 5-6 useEffects because I tried really hard and didnt make it.
I am using redux toolkit .
So filters values are coming from redux-store
  const { size, brand, price, sort } = useSelector((state) => state.filter);

products data coming from my backend
  const { loading, error, data } = useQuery(GET_PRODUCTS);

and this is how I did it with so many use effects...
 useEffect(() => {
    if (sort.length > 0) {
      if (sort.includes('price-highest')) {
        setFilteredProducts((filteredList) =>
          filteredList.slice().sort((a, b) => b.price - a.price)
        );
      } else {
        setFilteredProducts((filteredList) =>
          filteredList.slice().sort((a, b) => a.price - b.price)
        );
      }
    }
  }, [data?.getProducts, sort, size, brand, price]);

  useEffect(() => {
    if (size.length > 0) {
      setFilteredProducts((list) =>
        list.filter((product) => {
          return product.size.includes(Number(...size));
        })
      );
    }
  }, [data?.getProducts, data, size, brand, price]);

  useEffect(() => {
    if (brand.length > 0) {
      setFilteredProducts((list) =>
        list.filter((product) => {
          return product.brand.includes(...brand);
        })
      );
    }
  }, [data?.getProducts, brand, size, price]);

  useEffect(() => {
    if (price.length > 0) {
      setFilteredProducts((list) =>
        list.filter((product) => {
          return product.price > price[0][0] && product.price < price[0][1];
        })
      );
    }
  }, [data?.getProducts, price, brand, size]);

redux filters:

A: I think there is nothing wrong about putting everything in one effect. The only benefit of using multiple effects with different dependency arrays is, that in case only one parameter changes, some operations can be skipped.
But I think that is not true for your use case, since if one filter parameter changes, you have to re-calculate all filters and sort again. The only benefit you have would be to avoid re-filtering if only sort parameters change.
Even then, the performance gains of using multiple effects would likely be neglectable. The product list comes from the backend, so I think we can safely assume it is not huge - maybe hundreds of elements, but not millions or billions. The filter operations are cheap and we can perform the sort step last.
So just use one useEffect hook with the combined dependencies.
 useEffect(() => {

    const applySort = (filteredList) => (sort.length === 0)
       ? filteredList
       : sort.includes('price.highest')
       ? filteredList.slice().sort((a, b) => b.price - a.price)
       : filteredList.slice().sort((a, b) => a.price - b.price);

    const sizePredicate = (product) => (size.length === 0)
      || product.size.includes(Number(...size));

    const brandPredicate = (product) => (brand.length === 0)
       || product.brand.includes(Number(...brand));

    const pricePredicate = (product) => (price.length === 0)
       || product.price > price[0][0]
       && product.price < price[0][1];

    setFilteredProducts(
      applySort(
        data.getProducts()
          .filter(sizePredicate)
          .filter(brandPredicate)
          .filter(pricePredicate)
        )
      );

  }, [data.getProducts(), sort, price, brand, size]);


text:
Q: Calculate this triple integral over D $$\iiint \sqrt{10+y^2-x^2} \,dx \,dy \, dz$$ over the region bounded by $D$:
$D=\{(x,y,z)\mid x^2+z^2\le y^2+10,x^2+y^2\le 9\}$
So It's a cylinder intersecting a hyperboloid.
Is It correct to say that :
$$-3\le x \le 3$$
$$-3\le y \le 3$$
$$-\sqrt{2y^2-1} \le z \le \sqrt{2y^2-1}$$
?
And in the case, I want to use Cylindrical coordinates :
$$0\le \theta \le 2\pi$$
$$0 \le r \le 3$$
$$-\sqrt{2r^2\cos^2(\theta)-1}\le z \le \sqrt{2r^2cos^2(\theta)-1}$$
?
I think I got it wrong because the integral its kinda hard.

*

*And in the case I can use cylindrical coordinates , how can I simplify the $f(x,y,z)$ ?

A: First of all we see from $x^2+y^2=9$ that $y$ lives in $J_y=[-3,3]$.

*

*Fix $y$ in $J_y=[-3,3]$. Then $x$ lives in the interval $J_x(y)=\left [\ -\sqrt{9-y^2},\
+\sqrt{9-y^2}\ \right]$.

*

*Fix now also $x$ in the above allowed interval $J_x(y)$. Then $y^2+10-x^2\ge y^2-10-9=y^2-1\ge 1>0$, so we always have a section of $D$ in the line with the fixed values $x,y$ for the first two coordinates, ant $z$ takes values in the interval $J_z(x,y)=\left[\ -\sqrt{y^2+10-x^2},\
+\sqrt{y^2+10-x^2}\ \right]$.

Now we can compute using Fubini:
$$
\begin{aligned}
&\iiint_D\sqrt{10+y^2-x^2}\;dx\;dy\;dz
\\
&\qquad=
\int_{y\in[-3,3]}dy
\int_{x\in J_x(y)}dx
\int_{z\in J_z(x,y)}\sqrt{10+y^2-x^2}\;dz
\\
&\qquad=
\int_{y\in[-3,3]}dy
\int_{x\in J_x(y)}dx
\cdot \left(\text{length of $J_z(x,y)$}\right)\cdot\sqrt{10+y^2-x^2}
\\
&\qquad=
\int_{y\in[-3,3]}dy
\int_{x\in J_x(y)}dx
\cdot 2\sqrt{10+y^2-x^2}\cdot\sqrt{10+y^2-x^2}
\\
&\qquad=
2\int_{y\in[-3,3]}dy
\int_{x\in J_x(y)}dx
\cdot (10+y^2-x^2)
\\
&\qquad=
2\int_{y\in[-3,3]}dy
\cdot
\left[\ 10x + xy^2-\frac 13x^3\ \right]
_{x=-\sqrt{9-y^2}}
^{x=+\sqrt{9-y^2}}
\\
&\qquad=
4
\int_{y\in[-3,3]}dy
\cdot
\sqrt{9-y^2}\cdot
\left( \ 10 + y^2-\frac 13(9-y^2)\ \right)
\\
&\qquad=
4
\int_{-3}^3
\sqrt{9-y^2}\cdot
\left( \ 7 + \frac 43y^2\ \right)\; dy
\\
&\qquad\qquad\text{Substitution: } y=3\sin t\ ,
\\
&\qquad=
4
\int_{-\pi/2}^{\pi/2}
3\cos t\cdot
\left( \ 7 + \frac 43\cdot 9\sin^2 t\ \right)\; 3\cos t\; dt
\\
&\qquad=
4\cdot 3^2\cdot 2
\int_0^{\pi/2}
\cos^2 t\cdot
\left( \ 7 + 12\sin^2 t\ \right)\; dt
\\
&\qquad=180\pi\ .
\end{aligned}
$$
Computer check, here sage:
sage: integral(
....:     sqrt(10+y^2-x^2), z, -sqrt(10+y^2-x^2), +sqrt(10+y^2-x^2) )
-2*x^2 + 2*y^2 + 20

sage: integral( integral(
....:     sqrt(10+y^2-x^2), z, -sqrt(10+y^2-x^2), +sqrt(10+y^2-x^2) ),
....:   x, -sqrt(9-y^2), +sqrt(9-y^2) )
4/3*(4*y^2 + 21)*sqrt(-y^2 + 9)

sage: integral( integral( integral(
....:     sqrt(10+y^2-x^2), z, -sqrt(10+y^2-x^2), +sqrt(10+y^2-x^2) ),
....:   x, -sqrt(9-y^2), +sqrt(9-y^2) ),
....: y, -3, 3 )
180*pi

Later edit:
Using cylindrical coordinates is possible, and this leads to a similar computation. I was avoiding this first because using $x=r\cos t$, $y=r\sin t$ we do not have an immediat simplification for $\sqrt{10+y^2-x^2}\ge 1$.
Note however that the correct condition for $z$, after we fix $x,y$ and/or after we fix the corresponding values for $r,t$, is
$$
\begin{aligned}
|z| &\le \sqrt{10+y^2-x^2}\ ,\text{ respectively}\\
|z| &\le \sqrt{10+r^2(\sin^2 t-\cos^2 t)}
=\sqrt{10-r^2\cos2t}
\ ,
\end{aligned}
$$
so we would have to write
$$
\begin{aligned}
&\iiint_D\sqrt{10+y^2-x^2}\;dx\;dy\;dz
\\
&\qquad=
\int_{(x,y)\in\text{Disk of radius $3$ centered in origin}}dx\;dy
\int_{z\in J_z(x,y)}\sqrt{10+y^2-x^2}\;dz
\\
&\qquad=
\int_{(r,t)\in[-3,3]\times[0,2\pi]}r\;dr\;dt
\int_{z\in [-\sqrt{10-r^2\cos 2t},\ +\sqrt{10-r^2\cos 2t}]}
\sqrt{10-r^2\cos 2t}\;dz
\\
&\qquad=
\int_{(r,t)\in[-3,3]\times[0,2\pi]}r\;dr\;dt
\cdot(\text{ length of $[-\sqrt{10-r^2\cos 2t},\ +\sqrt{10-r^2\cos 2t}]$ })\cdot
\sqrt{10-r^2\cos 2t}
\\
&\qquad=
\int_{(r,t)\in[-3,3]\times[0,2\pi]}r\;dr\;dt
\cdot2(10-r^2\cos 2t)
\\
&\qquad=
\int_{(r,t)\in[-3,3]\times[0,2\pi]}r\;dr\;dt
\cdot2\cdot 10
\\
&\qquad\qquad\text{ since the integral of $\cos 2t$ vanishes on $[0,2\pi]$,}
\\
&\qquad=
\int_0^32\pi\cdot r\;dr
\cdot2\cdot 10
\\
&\qquad=
2\pi\cdot \frac 92 \cdot2\cdot 10
\\
&\qquad=
180\pi\ .
\end{aligned}
$$


text:
Q: Why does the performance of the HttpWebRequest object improve while using Fiddler? I'm getting some very strange behaviour with HttpWebRequest I hope someone can help me with. I have a console app which does some aggregation work by by using the HttpWebRequest object to retrieve the contents of a target website. Due to the nature of the requirement the app is multithreaded and attempts to make anywhere between 10 and 30 simultaneous connections (I've been experimenting with a range of values). The actual web request is structured as follows:
var req = (HttpWebRequest)WebRequest.Create(url);
WebResponse resp = req.GetResponse();
Stream s = resp.GetResponseStream();
var sr = new StreamReader(s, Encoding.ASCII);
string doc = sr.ReadToEnd();
sr.Close();
resp.Close();
return doc;

Anyway, the strange behaviour is that under normal circumstances the app is achieving around 120 requests per minute but if I open up Fiddler it jumps to about 600. Using Windows 7 Resource Monitor I can see the network activity increase accordingly. The TCP connections for the console process now list the remote address as "IPv4 loopback" rather than the target server IP address (expected). I did wonder about the max number of simultaneous HTTP requests allowed by the machine but changing this in the registry does not seem to make a difference.
So the question is; what is it about running Fiddler which suddenly increases the throughput five-fold and how can I achieve this natively on the machine without needing to launch another tool?
Thanks!

A: One thing I noticed right away is that you are not implementing using blocks. That adds a randomness factor that might be multiplied by the number of requests, so I suggest you fix that:
var req = WebRequest.Create(url);
using (WebResponse resp = req.GetResponse())
{
    using (Stream s = resp.GetResponseStream())
    {
        using (var sr = new StreamReader(s, Encoding.ASCII))
        {
            return sr.ReadToEnd();
        }
    }
}

Next, FYI, Fiddler acts as a proxy. If your default proxy was set up to use a script to set up the proxy configuration, then I wonder whether having Fiddler running might not remove the time necessary to do the script setup. That might happen only once, rather than on each request.

A: Looks like I've now been able to get the throughput right up (to double that I was getting with Fiddler open actually) by setting the max connections in the App.config:
<system.net>
  <connectionManagement>
    <add address="*" maxconnection="30" />
  </connectionManagement>
</system.net>

Very happy with the result but am still a little mystified as to why having Fiddler open changed the results so dramatically.

A: I had a problem similar to yours and wanted to share my resolution.
In short, I had a console program that was making HTTP requests and would, after 15 minutes or so, timeout. However, if I used Fiddler then I never experienced timeouts, even after having it run for days straight.
I tried setting the maxconnections property in App.config, but that didn't seem to help at all. I then went in and each and every reference to HttpWebRequest, HttpWebResponse, and the stream objects used to read/write data to these objects within using blocks.
That seems to have done the trick. I've been running for almost 24 hours now without a timeout and without Fiddler running.

A: The way you query causes to create a new session for each call, which is overhead, it could be that fiddler adds session to your queries....
try
private static CookieContainer _cookieContainer = new CookieContainer();
_httpWebRequest.CookieContainer = _cookieContainer; //with recycling the cookiecontainer

A: We had the same issue,
set your httpWebRequest.PreAuthenticate to true.
you should not have 401 response anymore, so you'll open less connections...

A: I had the same problem. I downloaded this:
http://www.wowinterface.com/downloads/info13581-LeatrixLatencyFix.html
It was the reason of performance of the HttpWebRequest. It modifies TCPAckFrequency and totally mess up everything. I removed it and now IT WORKS.

A: For me, I was setting request.ProtocolVersion = HttpVersion.Version10;
The default setting for this is HttpVersion.Version11.  When I set this back to the default my requests went much faster without fiddler.
I hope this helps someone else, it's taken me all morning to figure this out!


text:
Q: how to get the TextMeshPro component public class ClickBub : MonoBehaviour {
int x;
int count;
TextMeshPro mytext;
TextMeshPro soretext;
GameObject textobj;
// Use this for initialization
void Start () {
    textobj = this.gameObject.transform.GetChild (0).gameObject;
    mytext = textobj.GetComponent<TextMeshPro>();

in this mytext is a null value. how can i assign the TextMeshValue to the variable?
also says that unity engine can't convert type.

A: Well, the thing is that the Text for TextMeshPro isn't a TextMeshPro Object, but rather a TMP_Text, So if you tried this :
TMP_Text mytext;
void Start () {
    mytext = textobj.GetComponent<TMP_Text>();
}

Now you should get a value in your mytext object.

A: When you do
textobj.GetComponent<TextMeshPro>();

Unity will look for the TextMeshPro component in the object textobj.
According to your code, textobj is the first child of the object that has the ClickBub script. You should first check that this first child has a TextMeshPro component in your editor. To be sure that you access the elements you expect, you can try to print their names:
void Start ()
{
    textobj = this.gameObject.transform.GetChild (0).gameObject;
    Debug.Log(textobj.name);
}

Is it the object you expected?
Then if everything is setup properly but you want to add the TextMeshPro component if it doesn't have it, you can do
void Start ()
{
    textobj = this.gameObject.transform.GetChild (0).gameObject;
    mytext = textobj.GetComponent<TextMeshPro>();
    if(mytext == null)
    {
        mytext = textobj.AddComponent<TextMeshPro>();
    }
}