text:
Q: Jquery LocationPicker plugin - inputBinding with external function I want to change inputBindings values through external function.For example
I have two inputs whose ids are "lati" and "longi" respectively.
When I change values of both inputs manually ,marker goes to the direction I typed.
But when I try to change their values through an external function by clicking an anchor,such as
function(){
$("#lati").val("41.014552663073545");
...

marker does go to the point I changed.
So,how to move marker through external function

A: Instead of only changing the values of lati and longi (which probably does not affect the already declared marker), if you want to use the existing marker and change it's location only you probably want to first change the value then in your external function do something like the following:
var newLatLng = new google.maps.LatLng(lati, longi);
marker.setPosition(newLatLng);

A: For those searching:
$('#map').locationpicker({
    location: {latitude: position.coords.latitude, longitude: position.coords.longitude},
});

where position.coords.latitude and position.coords.longitude are your latitude and longitude values which you can set and #map being the id of the div that was originally set up with .locationpicker()


text:
Q: loop over data frame and create new rows I have a data set that has two columns. AccountName and AccountNumber. It has 35 rows. I want to create a new dataframe with AccountName, AccountNumber, and LocationNumber. LocationNumber is stored in another data frame with 1 column that has 350 rows.
so basically for each account name and number, foreach location number, add another row with the account name + number + location number. so if I have 35 account numbers and 350 locations, the end goal is to have 12,250 rows. i've tried using for loop to no avail.
accounts (name | number)
STR EXP-VACATION ESTIMATE-0200900   200900
STR EXP-HOLIDAY PAY-0200920 200920
STR EXP-SICK PAY-0200930    200930
STR EXP-MISC TIME PAID,NOT WORKED-0200990   200990

locations:
Lo.702-002
Lo.702-003
Lo.702-004
Lo.702-005

end result for EACH of the account numbers
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-002
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-003
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-004
STR EXP-VACATION ESTIMATE-0200900   200900 Lo.702-005

the PHP code that would produce the results I want:
foreach($accounts as $name => $number) {
    foreach($locations as $location) {
        echo sprintf("%s,%s,%s\n", $name, $number, $location);
    }
}

A: My solution:
acc.run <- function() {
  locFileName <- 'location-list.csv'
  accFileName <- 'account-list.csv'

  locations <- read.csv(locFileName, sep=',', quote='\"', header=T)

  accounts <- read.csv(accFileName, sep=',', quote='\"', header=T)

  #Add row numbers
  accounts$rowNum <- 1:nrow(accounts)

  merged <- merge(accounts, locations)

  sorted <- merged[order(merged$rowNum), ]

  final <- sorted[, !(names(sorted) %in% c('rowNum'))]

  # Random file extension to prevent duplicate/overwriting
  rExt <- paste(round(runif(6,10,100)), sep='', collapse='')

  write.csv(final, paste('accounts-concat', rExt, '.csv', sep='', collapse=''), row.names=F)
}

let me know how I can improve this?

A: Here's an edited version of my original answer,
modified to incorporate your test information.
Does this meet your needs?
# Generate some usable test data
accounts <- read.csv(text = "
AccountName|AccountNumber
STR EXP-VACATION ESTIMATE-0200900|200900
STR EXP-HOLIDAY PAY-0200920|200920
STR EXP-SICK PAY-0200930|200930
STR EXP-MISC TIME PAID,NOT WORKED-0200990|200990
", sep = "|")

locations <- read.table(header = TRUE, text = "
Location
Lo.702-002
Lo.702-003
Lo.702-004
Lo.702-005
")$Location

# Combine the data into wide format
df <- cbind(accounts, locations = t(locations))
# Restructure the data in long format
reshape(df, varying = grep("locations", names(df)), direction = "long" )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Errors state is not updating on first click I am making a form to update addresses. When the user clicks on the submit button, the form isn't being submitted but after the click the errors are updated correctly and the form submits fine. Here is what im working with

 const [errors, setErrors] = React.useState({
    firstName: '',
    lastName: '',
    streetAddress: '',
    streetAddress2: '',
    city: '',
    zipCode: ''
  });

  const validateRequiredFields = () => {
    let inputError = {};
    Object.keys(user).forEach(
      (key) => {
        inputError = { ...inputError, ...RequiredValidation(user, key) };
      }
    );

    setErrors({ ...errors, ...inputError });

The Validation returns inputError which takes in the values and sets to null instead of empty strings if theres no error. When I console.log this it returns the correct format. Also if there is errors, the errors are updated correctly on first click. Having looked into this I saw that most recent state isn't always fetched which I believe is my problem & the other threads I looked into recommended something like this although I don't know if thats how I am supposed to set it up.
setErrors({ ...errors, ...inputError }, () => {
    setErrors({ ...errors, ...inputError });
    });

A: Use

setErrors((prevErrors) => ({ ...prevErrors, ...inputError }));


text:
Q: Different Bootstappers for Caliburn.Micro I have seen an override of the Caliburn.Micro bootstrapper that facilitates the use of MEF on the Caliburn.Micro site. The override is
public class MefBootstrapper : BootstrapperBase
{
    private CompositionContainer container;

    public MefBootstrapper() { Start(); }

    protected override void Configure()
    {
        container = CompositionHost.Initialize(
            new AggregateCatalog(
                AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()
                )
            );

        var batch = new CompositionBatch();
        batch.AddExportedValue<IWindowManager>(new WindowManager());
        batch.AddExportedValue<IEventAggregator>(new EventAggregator());
        batch.AddExportedValue(container);
        container.Compose(batch);
    }

    protected override object GetInstance(Type serviceType, string key)
    {
        string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
        var exports = container.GetExportedValues<object>(contract);
        if (exports.Any())
            return exports.First();
        throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
    }

    protected override IEnumerable<object> GetAllInstances(Type serviceType)
    {
        return container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
    }

    protected override void BuildUp(object instance)
    {
        container.SatisfyImportsOnce(instance);
    }

    protected override void OnStartup(object sender, StartupEventArgs e)
    {
        DisplayRootViewFor<IShell>();
    }
}

Now, I have read about Caliburn.Micros SimpleContainer for IOC
public class AppBootstrapper : BootstrapperBase
{
     SimpleContainer container;

     public AppBootstrapper() { Start(); }

     protected override void Configure()
     {
         container = new SimpleContainer();
         container.Singleton<IWindowManager, WindowManager>();
         container.Singleton<IEventAggregator, EventAggregator>();
         container.PerRequest<IShell, ShellViewModel>();
     }

     protected override object GetInstance(Type service, string key)
     {
         var instance = container.GetInstance(service, key);
         if (instance != null)
             return instance;
         throw new InvalidOperationException("Could not locate any instances.");
     }

     protected override IEnumerable<object> GetAllInstances(Type service)
     {
         return container.GetAllInstances(service);
     }

     protected override void BuildUp(object instance)
     {
         container.BuildUp(instance);
     }

     protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
     {
         DisplayRootViewFor<IShell>();
     }
}

I have read MSDN docs on CompositionContainer but I am confused as to how to build the bootstrapper to configure both IOC and MEF support. Is this just a matter of combining the code in the two bootstrappers above and if so what do I return from the GetInstance override?
Thanks for your time.

A: MAF is probably what you are thinking of... It is also described in that msdn link.  And the differences between the 2.
As Steve pointed out you probably don't want to have both SimpleContainer and MEF co-existing that and I am sure the IoC static class would probably have a heart attack.  I actually would use MEF for larger projects for doing DI/IoC.  It can be a help or a burden at times due its power.  one of the limitations MEF has is open generics it dies horribly when trying do open generics, supposedly there are external projects that help mitigate.
there were a couple of projects around that integrate MAF with MEF


text:
Q: Use form to create object with subcomponents in Angular 5 I am building a form to create an account.
The account model has an address component.
the address has it's own model.
How would you create a new account object with a fully-instantiated address component in the front end?
account-create.component.html
<form [formGroup]="newForm" (ngSubmit)="createAccount()">

        <input type="text" class="form-control" placeholder="Account Name" formControlName="name">

            Account name is required

    //address portion goes here

        <button class="btn btn-success" type="submit">Register</button>

</form>

account-create.compoent.ts
import...

@Component({
  selector: 'app-account-create',
  templateUrl: './account-create.component.html',
  styleUrls: ['./account-create.component.css']
})

export class AccountCreateComponent implements OnInit {
  @Output()
  cancelCreateNew = new EventEmitter();
  account: Account;
  newForm: FormGroup;

  constructor(
    private accountService: AccountService,
    http: HttpClient,
    @Inject("BASE_URL") baseurl: string,
    private router: Router,
    private alertify: AlertifyService,
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.createNewForm();
  }

  createNewForm() {
    this.newForm = this.fb.group({
      name: ["", [Validators.required]]
      //address???
    });
  }

  createAccount() {
    this.account = Object.assign({}, this.newForm.value);
    this.accountService.createAccount(this.account).subscribe(() => {
      this.alertify.success("Account creation successful");
      },
      error => {
        this.alertify.error(error);
      },
      () => {
        this.router.navigate([`/accounts/${this.account.id}`]);
      });
  }
}

_models\account.ts
import { Address } from "./address";

export interface Account {
  id: number;
  name: string;
  address?: Address;
}

_models\address.ts
export interface Address {
  id: number;
  addressLine1: string;
  addressLine2?: string;
  addressLine3?: string;
  city: string;
  state: string;
  zip: string;
}

A: In retrospect, it is easy.  Here is how I did it in my project:
private convertFormToSong(rawSong: {owner: string, title: string, composer: string, \
    key: string, data: string, meta: string}): Song {
      return new Song(rawSong.owner, rawSong.title, rawSong.composer, rawSong.key, \
          JSON.parse(rawSong.data), JSON.parse(rawSong.meta));
  }

Then, you call it like this:
updateSong(index: number, newSong: FormGroup) {
    const song = this.convertFormToSong(newSong.value);
    ...

And that stems from this call:
onSave() {
    if (this.editMode) {
      this.songsService.updateSong(this.id, this.songForm);
    } else {
      this.songsService.addSong(this.songForm);
    }
    this.onCancel();
  }

Action captured from this:
<form [formGroup]="songForm" (ngSubmit)="onSave()">


text:
Q: Optimize Dict values(List) Multiplication I have Two dictionary elements as follows: Initial (25 key-Value pairs) Results (100 Key-Value Pairs)
Initial: {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0],....... 24: [0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0]}

Results: {'0': [360, 0, 0, 0, 0, 1, 0, 0, 3, 3, 0, 0, 15, 0, 14, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 2, 0, 0, 0, 0, 1, 0, 3, 3, 1, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 2, 0, 1, 0, 0, 3, 1, 0, 1, 0, 0, 0, 1, 2, 0, 2, 0, 0, 0, 137, 21, 78, 65, 241, 31, 30, 88, 152, 3, 13, 67, 31, 145, 132, 37, 1, 107, 120, 171, 39, 35, 31, 8, 24, 0, 0, 0, 0, 0],......'100': [183, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 2, 8, 1, 3, 1, 0, 3, 3, 0, 1, 1, 3, 2, 1, 1, 4, 0, 2, 1, 3, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 76, 10, 25, 33, 121, 14, 6, 40, 62, 2, 5, 34, 23, 66, 61, 28, 1, 56, 46, 69, 23, 10, 14, 1, 13, 1, 0, 0, 0, 0]}

In each iteration I multiply each value of Results dictionary to one value in Initial dictionary and call a function passing the product which will fetch me another value and I iterate this through the entire Initial dictionary  Values. I am doing this using below code:
for z in Initial.keys():
        for i in sorted(Results.keys()):
            result = {i :[x*y for x, y in zip(Initial[z], Results[i])]}

One complete cycle is taking about 1 minute and I will need to perform at least 5000 cycles to observe the final results. Any suggestions on improving the performance/Optimization of code would be much appreciated.

A: Your values are lists and therefore you have to multiply one element at a time. You can cast your values (lists) to arrays first and then use vectorized multiplication thereby removing the use of list comprehension and element wise multiplication as follows
# Converting the values to arrays once for all
Initial = {k:np.array(v) for k,v in Initial.items()}
Results = {k:np.array(v) for k,v in Results.items()}

# Now just using vectorized multipliction
for z in Initial.keys():
    for i in sorted(Results.keys()):
        result = {i :Initial[z] * Results[i]}

Since you did not provide complete data, I tried your code for some 1 million iterations and found the vectorized code much faster. Try it out on your original data and see if you get a speed up (which you should).

Test case for comparing times
Your list comprehension version took 1 minute 6 seconds
for ii in range(500000):
    for z in Initial.keys():
        for i in sorted(Results.keys()):
            result = {i :[x*y for x, y in zip(Initial[z], Results[i])]}

The following vectorized operation took 2.9 seconds
for ii in range(500000):
    for z in Initial.keys():
        for i in sorted(Results.keys()):
            result = {i :Initial[z] * Results[i]}


text:
Q: At what point PostgreSQL begin recovery I'm going to make backups from a standby server. I use the following commands to create binary backup:
psql -c 'select pg_xlog_replay_pause()'
tar c data --exclude=pg_xlog/* | lzop --fast > /mnt/nfs/backup/xxxx.tar.lzop
psql -c 'select pg_xlog_replay_resume()'

All WAL logs from master database are stored on external storage for several days and recovery using these logs works great. However, backup becomes invalid after logs are cleaned. The solution is to copy all needed WAL logs starting from some point until the last log when backup is done.
The question is what is the first file?
pg_controldata shows:
pg_control version number:            942
Catalog version number:               201409291
Database system identifier:           6185091942558520564
Database cluster state:               in archive recovery
pg_control last modified:             Thu 08 Oct 2015 03:14:23 PM UTC
Latest checkpoint location:           1C41/F662E1F8
Prior checkpoint location:            1C41/B4435EE8
Latest checkpoint's REDO location:    1C41/DE003400
Latest checkpoint's REDO WAL file:    0000000200001C41000000DE
Latest checkpoint's TimeLineID:       2
Latest checkpoint's PrevTimeLineID:   2
Latest checkpoint's full_page_writes: on
Latest checkpoint's NextXID:          0/3550951620
Latest checkpoint's NextOID:          83806
Latest checkpoint's NextMultiXactId:  1
Latest checkpoint's NextMultiOffset:  0
Latest checkpoint's oldestXID:        3152230057
Latest checkpoint's oldestXID's DB:   16385
Latest checkpoint's oldestActiveXID:  3550951620
Latest checkpoint's oldestMultiXid:   1
Latest checkpoint's oldestMulti's DB: 16385
Time of latest checkpoint:            Thu 08 Oct 2015 03:10:44 PM UTC
Fake LSN counter for unlogged rels:   0/1
Minimum recovery ending location:     1C42/4CC934E0

So what is the first file? AFAIK PostgreSQL always begin recovery from a checkpoint. I have tried to restore several backups and noticed that PostgreSQL starts recovery from Prior checkpoint location. Is this always true? What's the difference between Prior checkpoint location and Latest checkpoint location?
According to pg_controldata:
First file: 1C41/B4
Minimum last file: 1C42/4C (Must be greater of equal to `Minimum recovery ending location`)

Am I right?

A: You need from the "last checkpoint's redo location" - the first WAL for which is identified with "last checkpoint's REDO WAL file" - through to the WAL segment containing "minimum recovery ending location" on timeline "Last checkpoint's TimeLineID".
In your example that'd be from LSN 1C41/DE003400 through to 1C42/4CC934E0, both on TimeLineID 2.
That corresponds to WAL segments 0000000200001C41000000DE through 0000000200001C42????????.


text:
Q: Set input as invalid I have two inputs, e.g.
pass:       <input type="password" name="pass" required/>
pass again:  <input type="password" name="pass2" required/>

and I want to compare these inputs, and if they match, set input as valid. I tried this, but I think that prop('valid', true); does not work:
$(document).ready(function() {
    $('input[name=pass2]').keyup(function() {
        if($('input[name=pass]').val() == $('input[name=pass2]').val()) {
            $('#pass_hint').empty();
            $('#pass_hint').html('match');
            $(this).prop('valid', true);
        } else {
            $('#pass_hint').empty();
            $('#pass_hint').html('mismatch');
            $(this).prop('invalid', true);
        }
    });
});

I create a registration form and if passwords are not the same, input field is invalid and I can´t submit this and show me some hint. ...and I don´t know how I set this input as invalid

A: In the HTMLInputElement interface, there is no such property as valid or invalid.
You can use the setCustomValidity(error) method with native form validation.
As for your script, here's a demo that should work in all HTML5 compliant browsers:

$('input[name=pass2]').keyup(function () {
    'use strict';

    if ($('input[name=pass]').val() === $(this).val()) {
        $('#pass_hint').html('match');
        this.setCustomValidity('');
    } else {
        $('#pass_hint').html('mismatch');
        this.setCustomValidity('Passwords must match');
    }
});

<form action='#'>

Password:
        <input name=pass type=password required>

Verify:
        <input name=pass2 type=password required>

    <button type=submit>Submit</button>
</form>


text:
Q: How to calculate the sum of numbers which are each increased exponentially? My maths is terrible (sorry!) I cannot work out what should be a simple equation for a game of mine.
In the game, I have a price for an item which you can purchase an unlimited amount of times - each time you buy it, the price goes up.
Let's say the item costs $5 to buy. Here, I'll buy it 10 times:
5+20+45+80+125+180+245+320+405+500 = $1925 total cost to buy 10 times.
What I am trying to accomplish next, is to provide Buy x10, Buy x20, etc. buttons which will work out the cost for buying it 10 times in one go.
Here's my code currently which will result in the above prices:
    public function CalcuatePrice(timesAlreadyPurchased:Number,timesToBuy:int=1):Number {
        var price:Number;
        var basePrice:Number = 5;
        var multiplier:Number;

        //Always need at least 1 (items actually start at purchased 0 times)
        timesAlreadyPurchased += 1;

        //Apply iterations
        if (timesToBuy!=1){
            multiplier = (timesToBuy * (timesToBuy + timesAlreadyPurchased)) / 2;
        } else {
            multiplier = timesAlreadyPurchased;
        }

        price = basePrice * multiplier;

        return price;
    }

Currently, this will only work when timesToBuy is 1. The issue is on line:
multiplier = (timesToBuy * (timesToBuy + baseMultiplier)) / 2;

I'm just unsure what equation to use to get "timesToBuy = 10", to return a value of $1925 when "timesAlreadyPurchased = 0".
Additionally - anyone know what this type of equation is called in Mathematics? Sum of exponential series perhaps? Thank you.

A: Looks like an arithmetic progression.

The price increases by 15, 25, 35, 45 etc, so the price of the n-th buy can be expressed as a recurrence relation:

Solve this by substitution:

Nice simple expression. Last step used a formula from here. e.g. for n = 3 (the 3rd buy) the price is 5 * 3^2 = 45 as expected.

To get the total price, of course just sum these up:

Using another formula from the same page linked above.
Test for 5 buys:

*

*Original: 5 + 20 + 45 + 80 + 125 = 275

*Formula: 5 / 6 * 5 * 6 * 11 = 275

Update – formula in "pseudocode":
price = (5.0 / 6.0) * timesToBuy * (timesToBuy + 1) * (2 * timesToBuy + 1);


text:
Q: Need to extend IF formula to include conditions in multiple cells Good afternoon world,
I am trying to use IF formulas to include conditions in multiple cells for determining output. So far, I have gotten the following formula to begin behaving the way I want:
=IF(D2="","Engagement",IF(D2<TODAY(),"Stabilization",""))

However I'd like to include all of the following additional conditions:

*

*If E2 is blank, then F2="Engagement" (DONE)

*If E2 is before TODAY, then F2="Stabilization" (DONE)

*If D2 is blank, then F2="Intake"

*If C2="Check-In", then F2="Maintenance"

(See https://docs.google.com/spreadsheets/d/1CJKiDNPUWMMUbLLb-UDA6iRA2PBnlMHDsEB9vELe0Rk/edit?usp=sharing for reference)
Thanks!

A: Try this in E2. You can move the if statements around to get them in your priority/goes first.
=IF(D2="","Engagement",
IF(AND(D2<TODAY(),C2>TODAY()-DATE(0,7,0)),"Maintenance",
IF(C2="","Intake",
IF(D2<TODAY(),"Engagement",""))))


text:
Q: Auto Update Columns in DataGrid in WPF Hello  i m using List as datasource in WPF C#. there are feilds like Rate , weight , Quantity .
My need is to update Quantity automatically when i change value of rate or weight.....
All i need when i update rate , bags, weight then amount or respective quantity change automatically...
My Code ....
XAML :
<DataGrid Name="dataGridItem" LoadingRow="dataGridItem_LoadingRow" Binding.XmlNamespaceManager="{Binding}"  HorizontalAlignment="Left" Margin="10,100,0,0" VerticalAlignment="Top" Height="292" Width="740" AutoGenerateColumns="False" CanUserAddRows="False">
        <DataGrid.RowHeaderTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=Header}"/>
            </DataTemplate>
        </DataGrid.RowHeaderTemplate>
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding I_ID}" Visibility="Hidden"></DataGridTextColumn>
            <DataGridTextColumn Header="Code" Binding="{Binding I_Code}"></DataGridTextColumn>
            <DataGridTextColumn Header="Grade" Binding="{Binding I_Grade}"></DataGridTextColumn>
            <DataGridTextColumn Header="Particulars" Binding="{Binding I_Name}"></DataGridTextColumn>
            <DataGridTextColumn Header="Rate" Binding="{Binding I_Rate}"></DataGridTextColumn>
            <DataGridTextColumn Header="Bags" Binding="{Binding I_BAGS}"></DataGridTextColumn>
            <DataGridTextColumn Header="Weight" Binding="{Binding I_WEIGHT_BAGS}"></DataGridTextColumn>
            <DataGridTextColumn Header="Quantity" Binding="{Binding I_QUANTITY}"></DataGridTextColumn>
            <DataGridTextColumn Header="Amount" Binding="{Binding I_Amount}"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

C# :
public class cls_INVOICE_ITEM
{
    public int _I_ID;
    public string _I_Code;
    public string _I_Grade;
    public string _I_Name;
    public decimal _I_Rate;
    public decimal _I_BAGS = 0;
    public decimal _I_WEIGHT_BAGS = 0;
    public decimal _I_QUANTITY;
    public decimal _I_RATE = 0;
    public decimal _I_Amount;
    public int I_ID { get { return _I_ID; } set { _I_ID = value; } }
    public string I_Code { get { return _I_Code; } set { _I_Code = value; } }
    public string I_Grade { get { return _I_Grade; } set { _I_Grade = value; } }
    public string I_Name { get { return _I_Name; } set { _I_Name = value; } }
    public decimal I_Rate { get { return _I_Rate; } set { _I_Rate = value; } }
    public decimal I_BAGS { get { return _I_BAGS; } set { _I_BAGS = value; } }
    public decimal I_WEIGHT_BAGS { get { return _I_WEIGHT_BAGS; } set { _I_WEIGHT_BAGS = value; } }
    public decimal I_QUANTITY { get { return I_BAGS * I_WEIGHT_BAGS; } set { _I_QUANTITY = I_BAGS * I_WEIGHT_BAGS; } }
    public decimal I_Amount { get { return I_BAGS * I_WEIGHT_BAGS * I_Rate; } set { _I_Amount = I_BAGS * I_WEIGHT_BAGS * I_Rate; } }
}

static List<cls_INVOICE_ITEM> lstIOrder = new List<cls_INVOICE_ITEM>();

DataTable DT = BLL.Get_Item_By_ItemCode(txtItemCode.Text);

Function Which BindData :

        if(DT.Rows.Count > 0)
        {
            lstIOrder.Add(new cls_INVOICE_ITEM() { I_ID = int.Parse((DT.Rows[0]["I_ID"].ToString())), I_Code = DT.Rows[0]["I_Code"].ToString(), I_Grade = DT.Rows[0]["I_Grade"].ToString(), I_Name = DT.Rows[0]["I_Name"].ToString() });
        }
        dataGridItem.ItemsSource = null;
        dataGridItem.ItemsSource = lstIOrder;


text:
Q: Cannot remove Evolution indicator I normally use Thunderbird as my email client, but the other day I accidentally started up evolution.
Now the envelope icon in the indicator area contains information about both Thunderbird and Evolution. Since I'm not using Evolution, I tried to get rid of the Evolution information by uninstalling the evolution-indicator package, but this didn't help. I still have both Thunderbird and Evolution listed when I click the envelope icon. (And, yes, I did restart the computer.)
The /usr/share/indicators/messages/applications/ directory only contains Thunderbird and Empathy, not Evolution.
How do I get rid of the Evolution information?

A: Run the below command on terminal to remove  evolution package,
sudo apt-get remove evolution

Or you may run the below command to remove only the evolution indicator on top-panel,
sudo apt-get remove evolution-indicator


text:
Q: GetManifestResourceStream Returning Different Versions of Embedded XML File Background
Coded UI Test Case is accessing an XML configuration file embedded in a DLL created by the development team.  The test case verifies the UI is displaying the same configuration values provided in the XML file.  (The UI is supposed to be loading configuration from this XML file).
The test case gains access to the XML file as follows:
Assembly assemblyWithResource = Assembly.LoadFrom(assemblyFile: @"C:\Program Files (x86)\Install Location\DevCreated.dll");
Stream stream = assemblyWithResource.GetManifestResourceStream(name: ConfigFileName.xml);

When the test case executes, the stream returned from the GetManifestResourceStream call is not correct. The test case fails because the UI value does not match the XML config value.  The UI is showing what is in the current version of the XML file (correct).  The stream returned from the executing code is from an older version of the XML file (wrong).
This is one of the first test cases written while hammering out architecture/framework plans so it had been executing without issue for over a year.
Debug
Reproducibility
Only able to reproduce the problem by running the test case through MTM on the test VM environment.  Unable to reproduce running the test case on my personal computer, running the test case through MTM on another configured test VM or my usual go-to for trial/error deubg - ripping the guts of a test case into a console app.  I like to do that so I don't have to mess with the overhead of checking in code and deploying (and can easily pass code back to the dev team without them having to deal with it either).
Running the code where the test case is getting the XML file from the DLL (two lines shown above) in a plain old console app on the same test VM where the original test case fails returns the correct XML file contents.
Differences in Deployed Test Case Code vs Console App Code
Initially focused on what was different between the MTM executed test case and the console app because they could be run on the same VM.  Looked at the following information for the Assembly:

*

*Location, CodeBase, HostContext, GlobalAssemblyCache, PermissionSet

*Dumped the array from GetManifestResourceNames and the ResourceLocation for the ManifestResourceInfo

None of the assembly attributes that were looked at were different. It looks as if the test case code and console app code are loading the same DLL from the same location and accessing the same embedded file name but obtaining different versions of the file.
Spent time digging in TFS and did find the version of dev code that contains the same XML file that the MTM executed test case is loading - it's about 6 weeks old.  It was changed 3 weeks ago and has been failing ever since.  This established a time period based on changesets.
There are no other XML files embedded in this DLL to look at.  XML files embedded in other DLLs that have seen changes during the same time period appear to be loading correctly.
The DLL is not located in the GAC, all other DLLs not part of the installed version were removed from the VM.
On the dev side the XML file is setup with a Build Action of Embedded Resource, does not copy to the output directory.
I've done a nominal amount of additional research to learn more about how the GetManifestResourceStream call works - it seems if there are any issues at all this will return a null Stream (not a different file) and how embedded files are included in an assembly.
Questions
What to try next? I'm trying to narrow down a focus to continue digging:

*

*Is this an issue that stems from how the dev team has built this DLL?

*Is it an issue with how the DLL is included/packaged with the installer?  (Currently uninstalling and planning to copy/paste application and DLLs from the drop folder for the build to eliminate the installer.)

*Is it an environment issue on the VM where the test case is executing?

*Is it an issue with how the application is being deployed to the VM for testing?

*Is it an issue with how the test cases are deployed to the VM for testing? DLL hell?

The VM will be re-imaged soon, at which point I fear this problem is going to go away.  It's a pretty big concern of mine because we didn't realize the test case  was using the wrong version of an XML file.
Update
In the process of trying to not use the installer any copy/paste the application and DLLs onto the test VM, something IIS related got messed up and I ended up re-doing most things IIS related on the VM.  Never did get the copy/paste to work (because of IIS/configuration stuff) so reinstalled the application and now I no longer see the test case fail.  What about IIS would have anything to do with embedded files in a DLL?


text: Q: How to tell if SSL socket incomming request is a POST request? I am using the SSLServerSocketFactory in which HTTPS data will come through incoming requests. Is there any way that I can tell that the request was a POST request? I do have a JSON mapping that will indicate whether or not the request was a POST. However, I was wondering if there was a way to tell from the Object itself.


text:
Q: React Native: call a function after getting the permission I just need to call a function after getting the location permission.
This is my code:
  componentDidMount() {
    this.samplePermissionRequest();
    alert('componentDidMount');
  }

  samplePermissionRequest=()=>{
    async function requestLocationPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            'title': 'Cool Location tracking App Permission',
            'message': 'This Cool App needs access to your location '
          }
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          this.justStart();
          alert("You can use the app");
        } else {
          alert("You can not use the app");
        }
      } catch (err) {
        console.warn(err);
      }
    }
    requestLocationPermission();
  }

  justStart=()=>{
      alert("start with permission");
  }

When I run this code, I only get the dialog of the first alert ( alert('componentDidMount') ).
If I remove the line "this.justStart();", then the second alert is displayed as well. So the problem is that "this.justStart();" doesn't work.
Why?

A: you have to work with Promise object, you can change your code like this:
componentDidMount() {
    this.requestLocationPermission().then(
        alert('componentDidMount')
    );
}

async requestLocationPermission() {
    return PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
            'title': 'Cool Location tracking App Permission',
            'message': 'This Cool App needs access to your location '
        }
    ).then(granted => {
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            this.justStart();
            alert("You can use the app");
        } else {
            alert("You can not use the app");
        }
    }).catch(e => console.warn(e));
}

on Promise that async methods return you can use .then and .catch

A: Because this will be undefined inside your requestLocationPermission function.
Hence this.justStart() will throw type error which will be caught by your try/catch statement.
Solution 1,
Bind this when you call requestLocationPermission.

requestLocationPermission.call(this);

Solution 2,
Remove function requestLocationPermission and directly use samplePermissionRequest instead of using inner function and calling it again.
async samplePermissionRequest = () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Cool Location tracking App Permission',
          'message': 'This Cool App needs access to your location '
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.justStart();
        alert("You can use the app");
      } else {
        alert("You can not use the app");
      }
    } catch (err) {
      console.warn(err);
    }
  }

Hope it helps.


text:
Q: Why android does not clean up memory after finishing activity? In my case I have tow activities called A(Main Activity) and B (Child Activity).
A will start B (B having some image loading stuff using Glide image  library).
If I get the memory allocation using android memory monitor, I can clearly see the memory allocation grows.That is totally fine because we are doing some Image related things in activity B.Image Attached.

So my problem is if I pressed back button in Activity B it will come to activity A and allocated memory will not be cleared.Memory allocation will still in same amount.
Is this normal android behaviour ?
If not how can I manually clean up memory ?
I manually run GC as follows but same result no luck :(.
In activity B
    @Override
    protected void onDestroy() {
       super.onDestroy();
       System.gc();
    }

A: 1) OnDestroy is called when finish(); is called, simply pressing back button won't call this method, unless you program it to do so.
2) System.gc(); in onDestroy won't work, since your activity B is still active at onDestroy. You should call this from other Activity once the activity B is completely terminated.
3) Activity will remain on memory even onDestroy is called, if you leak your activities context to long lived object/thread/etc. (Memory leak)
Note: calling System.gc(); does not simply free your memory, it might not execute GC depending on the situation. See details here: Why is it bad practice to call System.gc()?


text:
Q: Why is this button not aligning properly in html? I have the following html snippet for a submit button:
<input style="height: 30px; width: 120px" type="submit" align="right" name="" value="Submit">

but it is not aligning to the right at all (or middle which is what I want). The align tag doesnt seem to be doing anything why is this the case?

A: There is no align attribute for the input element. You should use a validator before wondering why markup doesn't work as you expect.
Use CSS for presentation.
You probably want to use either text-align on the parent element or float

A: The align attribute of HTML has been deprecated ages ago. As a good practice all the styling should be done by CSS and not HTML, like:
<input style="height: 30px; width: 120px; float: right" type="submit" name="" value="Submit">

even a better practice - avoid inline CSS
<style>
input[type=submit] { height: 30px; width: 120px; float: right; }
</style>

<input type="submit" name="" value="Submit" />


text:
Q: how to count number of items in an array android How can I count the number of items in an array in android?
here is the code that dose not work
if (vehicleList.length = 1){
     //do something
                     }

can anyone help?

A: Use == for comparison..
if (vehicleList.length == 1){
     //do something
 }

A: You are trying to assign a value to vehiclelist.length. Use == instead which will compare the two values.

A: if vehicleList is an arrayList the try like this
if (vehicleList.size() == 1){
     //do something
}


text:
Q: Override content from column "is_in_stock" in WooCommerce admin product list I try to override content from column "is_in_stock" in WooCommerce admin product list.
For this I currently use:
<?php
add_action('manage_product_posts_custom_column', 'stock_override' );

function stock_override($column_name){
    global $post;
    $product = wc_get_product($post->ID);
    if( $product->is_type('variable')){
        if ($column_name == 'is_in_stock') {
            echo 'own text';
        }
    }
}
?>

But this does not overriding the default content but add my text to this. The default content is the stock status onstock, backorder or out of stock.
I created an custom product type and I want override the content in the colum is_in_stock if the producttype is equal to variable. If is not equal echo the default from WooCommerce.
I can remove the whole column and add my own column but then I have no default content if the producttype is not equal.
Who can help me a little?

A: There is no need to delete the default column and replace it with a new one, you could just use the woocommerce_admin_stock_html filter where you have access to the $product object.
That way you can add your own text/statuses to the existing column.
So you get:
// Admin product list: is_in_stock
function filter_woocommerce_admin_stock_html( $stock_html, $product ) {
    // Condition
    if ( $product->is_type('variable') ) {
        $stock_html = '<mark class="someclass" style="background:transparent none; color:#33ccff; font-weight:700; line-height:1;">' . __( 'My text', 'woocommerce' ) . '</mark>';
    }

    return $stock_html;
}
add_filter( 'woocommerce_admin_stock_html', 'filter_woocommerce_admin_stock_html', 10, 2 );


text:
Q: Riemann integrability of the following function. I have the following assignment problem on which I have been stuck for over a week now.
Let $f: [a,b] \rightarrow \mathbb{R}$ be function such that there is a number $K>0$ such that
$\sum_{j=1}^{n}|f(a_j)-f(a_{j-1})| \leq K$
whenever $\{a=a_o < a_1 < ... < a_n = b\}$ is a partition of $[a,b]$. Show that $f$ is integrable on $[a,b]$.
I have tried using the Cauchy criterion to establish integrability. But I don't know how to proceed. Here's what I tried. Begin with two arbitrary tagged partitions $P = \{[x_{k-1},x_k]\}_{k=1}^{n}$ and $Q = \{[y_{k-1},y_k]\}_{k=1}^{n}$ of $[a,b]$. We obviously have
$\begin{align*}
|R(f,P) - R(f,Q)| &= |\sum_{k=1}^{n}f(x_k^*)(x_k - x_{k-1}) - \sum_{k=1}^{n}f(y_k^*)(y_k - y_{k-1})|\\
&\leq |\sum_{k=1}^{n}f(x_k^*)(x_k - x_{k-1})| + |\sum_{k=1}^{n}f(y_k^*)(y_k - y_{k-1})|\\
&\leq \sum_{k=1}^{n}|f(x_k^*)|\cdot||P|| + \sum_{k=1}^{n}|f(y_k^*)|\cdot||Q||
\end{align*}$
Here, $x_k^*$ and $y_k^*$ are the tags of $P$ and $Q$, and $||P||$ and $||Q||$ are their norms. Now I don't know how to link the last line above with the condition given in the problem. Any hints would be very helpful.

A: Here is a direct approach which avoids any mention of functions of bounded variation.
Let $\epsilon>0$ be pre-assigned and let $n$ be a positive integer such that $K/n<\epsilon/3$. Let us define a partition $$P_n=\{x_0,x_1,\dots,x_n\} $$ by $$x_j=a+j\cdot\frac{b-a} {n} $$ so that each subinterval $[x_{j-1},x_j]$ is of the same length $(b-a) /n$.
Let us observe that if the function $f$ satisfies the conditions given in question then it is bounded on $[a, b] $. And then we can define $$M_j=\sup\, \{f(x) \mid x\in[x_{j-1},x_j]\}, m_j=\inf\, \{f(x) \mid x\in[x_{j-1},x_j]\} $$ Also let the points $a_j, b_j\in[x_{j-1},x_j]$ be such that $$0\leq M_j-f(a_j) <\frac{\epsilon} {3(b-a)},0\leq f(b_j) - m_j<\frac{\epsilon} {3(b-a)}$$ Such points exists because of the way $M_j, m_j$ are defined. We now consider the difference between upper sum $$U(f, P_n) =\sum_{j=1}^{n}M_j(x_j-x_{j-1})$$ and the lower sum $$L(f, P_n) =\sum_{j=1}^{n}m_j(x_j-x_{j-1})$$ We have
\begin{align}
U(f, P_n) - L(f, P_n) & =\sum_{j=1}^n (M_j-m_j) (x_j-x_{j-1})\notag\\
&=\left|\sum_{j=1}^n(M_j-f(a_j)+f(b_j)-m_j+f(a_j)-f(b_j))(x_j-x_{j-1})\right|\notag\\
&\leq\sum_{j=1}^n (M_j-f(a_j)) (x_j-x_{j-1})+\sum_{j=1}^{n}(f(b_j)-m_j)(x_j-x_{j-1})+\sum_{j=1}^n|f(a_j)-f(b_j)|(x_j-x_{j-1})\notag\\
&<\frac{\epsilon}{3(b-a)}\cdot(b-a)+\frac{\epsilon}{3(b-a)}\cdot(b-a) +\frac{K} {n} \notag\\
&<\epsilon
\end{align}
By Darboux criterion $f$ is Riemann integrable on $[a, b] $.

A: Regardless on how you define the Riemann integral ((1) through refinement of partitions or (2) through smallness if partition size $\|P\|$) one effective way to verify existence of the Riemann integral in the setting you describe is by comparing the upper and lower Darboux sums for a common partition $\mathcal{P}=\{a=x_0<\ldots <x_n=b\}$.
From your posting, it seems that you are defining the integral is by method (2), that is:

A bounded function $f$ on $[a,b]$ is Riemann integrable if the limit
$$\lim_{\|P\|\rightarrow0}S(f,\mathcal{P},\{t^*_j\})=\lim_{\|P\|\rightarrow0}\sum^n_{j=1}f(t_k)(x_{j-1}-x_j)$$
exists and is independent of the tags $\tau=\{t_k: x_{k-1}\leq t_k\leq x_j, \, 1\leq k\leq n\}$.

Meaning that there exists a number $A$ such that for any $\varepsilon>0$, there is $\delta>0$ such that for any partition $P$ with $\|P\|<\delta$ and any set of tags $\tau$ adapted to $P$
$$|S(f,P,\tau)-A|<\delta$$
Let's proceed then in within this framework.
For a subinterval $I_j:=[x_{j-1},x_j]$ of the partition $\mathcal{P}$ denote $M_j=\sup\{f(t): t\in I_j\}$ and $m_j=\inf\{f(t):t\in I_j\}$. The Darboux sums related the partition $\mathcal{P}$ are defined as
\begin{align}
U(f,\mathcal{P})=\sum^n_{j=1}M_j(x_j-x_{j-1}),\qquad L(f,\mathcal{P})=\sum^n_{j=1}m_j(x_j-x_{j-1})
\end{align}
Darboux's criteria in your framework states that the existence of the integral $A=\int^b_af$ is equivalent to
$$\lim_{\|\mathcal{P}\|\rightarrow0}U(f,\mathcal{P})-L(f,\mathcal{P})=0$$
Suppose then that $f$ satisfies $\sum^n_{j=1}|f(x_j)-f(x_{j-1})|\leq K$ for any partition $\mathcal{P}=\{a=x_0<\ldots<x_n=b\}$.
For the moment, fix a partition $\mathcal{P}$. Notice that for each subinterval $I_j-[x_{j-1},x_j]$
$$0\leq M_j-m_j=\sup\{|f(t)-f(s): t,s\in I_j\}$$
Given $\varepsilon>0$ choose for each subinterval $I_j$ points $t_j,s_j\in I_j$ such that
$$M_j-m_j -\tfrac{\varepsilon}{2n}<|f(t_j)-f(s_j)|$$
This can e done by definition of the supremum. Observe that
$$(M_j-m_j)(x_j-x_{j-1})\leq \big(|f(t_j)-f(s_j)|+\tfrac{\varepsilon}{2n}\big)(x_j-x_{j-1})<\big(|f(t_j)-f(s_j)|+\tfrac{\varepsilon}{2n}\big)\|P\|$$
Adding over $j$ yields
$$U(f,\mathcal{P})-L(f,\mathcal{P})\leq \Big(\sum^n_{j=1}|f(t_j)-f(s_j)|\Big)\|\mathcal{P}\|+\tfrac{\varepsilon}{2}\|\mathcal{P}\|
$$
By considering the augmented partition $\mathcal{P}'=\mathcal{P}\cup\{s_j,t_j:1\leq j\leq n\}=\{a=x'_0<x'_1<\ldots<x'_{n'}=b\}$ and noticing that $x_{j-1}\leq s_j,t_j\leq x_j$ it is easy to see that
$$\sum^n_{j=1}|f(t_j)-f(s_j)|\leq \sum^{n'}_{j=1}|f(x'_j)-f(x'_{j-1})|\leq K$$
Finally, by choosing partitions $\mathcal{P}$ for which $\|\mathcal{P}\|<1$ and $\|\mathcal{P}\|<\tfrac{\varepsilon}{2K}$ we obtain that
$$U(f,\mathcal{P})-L(f,\mathcal{P})<\varepsilon$$
This shows that $$\lim_{\|\mathcal{P}\|\rightarrow0}U(f,\mathcal{P})-L(f,\mathcal{P})=0$$

Notes:

*

*A separate but similar proof can be obtained in the framework (1) of partition refinements.

*It is well known (but requires some work) that frameworks (1) and (2) are equivalent.

*The condition $\sum^n_{j=1}|f(x_j)-f(x_{j-1})|\leq K$  for all partitions $\mathcal{P}=\{a=x_0<\ldots < x_n=b\}$ is known as saying that $f$ has finite variation on $[a,b]$. This means that $f$ can be expressed as the difference of two bounded monotone nondecreasing functions. Knowledge of tis would simplify the proof considerably as bounded monotone functions are easily seen to be Riemann integrable.


text:
Q: Make crontab work at 0 hour I try to execute some command like this:
*/10 0,1 * * * $BPY some_script.py
Meaning I want to run it every 10 minutes between 0:00 and 1:00.
BUT: I see in my /var/log/cron that it is not executed. And more: it is the only one task being not executed (so my cron works well in other cases). Operating sysyem is Debian GNU/Linux 6.0.
What am I doing wrong? Is zero a bad hour?
update: $BPY just holds path to python executable. Other commands also use it and it runs fine.
Well, if it was a realy bad command - it would at least appear in /var/log/cron
update 2: The script works fine with other hours (for example, * * * * * perfectly runs it every minute and it does exactly what I want)

A: It looks like the cron does not have $BPY defined.  Is it some_script.py that needs to be executed?  What's the purpose of $BPY?  Also, you should probably need the full path of the script, not just the script's name itself.
Assuming that some_script.py is the real intended executed script, then try just executing that (with the full path!!)
In your comments below this answer, you said the $BPY is Python's path.  Instead of doing that, you should use a shebang to specify the full path of the interpreter that is to be used.  A common shebang specifying python is:  #!/usr/bin/python.  This should be the first line of your some_script.py file.
As far as the syntax...
Cron format is a simple, yet powerful and flexible way to define time and frequency of various actions.
cron format consists of fields separated by white spaces:

[Min] [Hr] [Day of Month] [Month of Year] [Day of Week]

The following diagram shows what it consists of:

* * * * *
| | | | |
| | | | +---- Day of the Week   (range: 0-6, 0 standing for Sunday; Mon,Tue, etc.
| | | |                          Most OS's recognize Sunday as 0 or 7)
| | | +------ Month of the Year (range: 1-12 or Jan, Feb, etc)
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

Any of these 6 fields may be an asterisk (*). This would mean the entire range of possible values, i.e. each minute, each hour, etc. In the first four fields.
Any field may contain a list of values separated by commas, (e.g. 1,3,7) or a range of values (two integers separated by a hyphen, e.g. 1-5).
After an asterisk (*) or a range of values, you can use character / to specify that values are repeated over and over with a certain interval between them. For example, you can write 0-23/2 in the Hour field to specify that some action should be performed every two hours (it will have the same effect as 0,2,4,6,8,10,12,14,16,18,20,22).  A value of */4 in the Minute field means that the action should be performed every 4 minutes. 1-30/3 means the same as 1,4,7,10,13,16,19,22,25,28.
In Month and Day of Week fields, you can use names of months or days of weeks abbreviated to first three letters (Jan,Feb,...,Dec or Mon,Tue,...,Sun) instead of their numeric values.
Alternatively, you can use special keywords in lieu of the first 5 fields specified above:

string         meaning
------         -------
@reboot        Run once, at startup.
@yearly        Run once a year, "0 0 1 1 *".
@annually      (same as @yearly)
@monthly       Run once a month, "0 0 1 * *".
@weekly        Run once a week, "0 0 * * 0".
@daily         Run once a day, "0 0 * * *".
@midnight      (same as @daily)
@hourly        Run once an hour, "0 * * * *".

This alternate format is not supported in older, proprietary operating systems like SCO Unix.


text:
Q: java [deprecation] readLine() in DataInputStream has been deprecated? I wrote a java sever socket,it could connect postgresql and return values,but when I compile javac -deprecation SQLServer.java
And why warning cannot work?
It didn't have any error.How can I fix it?
SQLServer.java:66: warning: [deprecation] readLine() in DataInputStream has been     deprecated
                            query = in.readLine();
                                      ^
1 warning

code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;

public class SQLServer extends Thread{
    public static final int MYPORT = 6700;
    ServerSocket listen_socket;

        public SQLServer(){
        try{
            listen_socket = new ServerSocket (MYPORT);
        }
        catch(IOException e) {System.err.println(e);}
        this.start();
    }
    public void run(){
        try{
            while(true)
            {
                Socket client_socket = listen_socket.accept();
                SQLConnection c = new SQLConnection (client_socket);
            }
        }
        catch(IOException e) {System.err.println(e);}
    }
    public static void main(String[] argv){
       new SQLServer();
    }
}
class SQLConnection extends Thread{
    protected Socket client;
    protected DataInputStream in;
    protected PrintStream out;
    protected String query;

    public SQLConnection (Socket client_socket){
        client = client_socket;
        try{
            in = new DataInputStream(client.getInputStream());
            out = new PrintStream (client.getOutputStream());
        }
        catch(IOException e) {
            System.err.println(e);
            try {client.close();}
            catch (IOException e2) {};
            return;
        }
        this.start();

    }

    public void run(){
        try{
            query = in.readLine();
            System.out.println("read query string <" + query + ">");
            do_sql();
            //out.println(d.toString());
        }
        catch (IOException e) {}
        finally{
            try {client.close();}
            catch (IOException e) {};
        }
    }
        public void do_sql(){
        Connection con; // database connection object
        Statement stmt; // SQL statement object
        ResultSet rs;   // SQL query results
        ResultSetMetaData rsmd;
        boolean more;   // "more rows found" switch
        String dsn = "jdbc:postgresql://localhost/postgres";
        String user = "postgres";
        String password = "123456";
        String record;
        int colcount, i;

        try{
            Class.forName ("org.postgresql.Driver");
            con = DriverManager.getConnection(dsn, user, password);

            stmt = con.createStatement();

            rs = stmt.executeQuery(query);

            more = rs.next();
            if (!more) {
                out.println("No rows found.");
                return;
            }
            rsmd = rs.getMetaData();
            colcount = rsmd.getColumnCount();
            System.out.println(colcount + " columns in result set");

            while (more) {
                //build result string
                record = "";
                for (i=1; i <= colcount; i++){
                   record = record.concat(rs.getString(i) + "  ");
                }
            out.println(record);
            System.out.println(record);
            more = rs.next();
        }
        rs.close();
        stmt.close();
        con.commit();
        con.close();
        }
        catch (Exception e)
        {
          System.out.println("Exception occurred" + e.toString());
        }
       }
}

A: From DataInputStream#readLine javadoc:

Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
    DataInputStream d = new DataInputStream(in);

with:
    BufferedReader d = new BufferedReader(new InputStreamReader(in));

A: The method was deprecated because Streams are meant to be treating bytes, to treat text we have since a long time Readers & Writers as they offer the functionality to use encodings.
if you want text to be read try wrapping your stream into a reader
BufferedReader r = new BufferedReader(new InputStreamreader(your data stream, optional encoding parameter like "UTF-8"))

r.readLine();

A: This is what the Java API says:

Deprecated.
  This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:

     DataInputStream d = new DataInputStream(in);

with:
     BufferedReader d
          = new BufferedReader(new InputStreamReader(in));


text:
Q: DataTable's NewRow() method causes re-evaluation of LINQ expression after being used as a BindingSource with AsDataView() In the following code, I have a LINQ expression that produces an EnumerableRowCollection(Of DataRow) that is eventually used in a BindingSource.
The first time the code loops, it's fine.  However, once the BindingSource for the first Control has been set using AsDataView() on the IEnumerable, the next time the NewRow() method on the DataTable is called, it re-evaluates the LINQ expression.
Option Explicit On
Option Infer Off
Option Strict On

Public Class Form1
    Dim ds As New DataSet()

    Private Sub Form1_Load( sender As Object,  e As EventArgs) Handles MyBase.Load
        ds.Tables.Add("Table1")

        Dim comparisonInteger As Integer = 12
        ds.Tables("Table1").Columns.Add("ID", GetType(Integer))
        ds.Tables("Table1").Columns.Add("IntegerValue", GetType(Integer))
        ds.Tables("Table1").Columns.Add("StringValue", GetType(String))

        ds.Tables("Table1").Rows.Add({1, 47, "row 1"})
        ds.Tables("Table1").Rows.Add({2, 2, "row 1"})
        ds.Tables("Table1").Rows.Add({3, 7, "row 1"})
        ds.Tables("Table1").Rows.Add({4, 6, "row 1"})

        For i As Integer = 0 To 2
            Dim iterator As Integer = i
            Dim tb As New TextBox()

            CreateNewRowIfMissing(comparisonInteger+i)

            Dim dataValue As EnumerableRowCollection(Of DataRow) =  ds.Tables("Table1").AsEnumerable() _
                                                                        .Where(Function(v) DirectCast(v("IntegerValue"), Integer) = comparisonInteger + iterator)

            Dim bs As New BindingSource(dataValue.AsDataView(), Nothing)
            Dim b As New Binding("Text", bs, "IntegerValue")
            b.DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
            tb.DataBindings.Add(b)

            tb.Location = New Point(10, 10 * Me.Controls.Count+1)

            Me.Controls.Add(tb)
        Next
    End Sub

    Private Sub CreateNewRowIfMissing(comparisonInteger As Integer)

        If  ds.Tables("Table1").AsEnumerable() _
                .Where(Function(v) DirectCast(v("IntegerValue"), Integer) = comparisonInteger) _
                .Count() = 0

            ds.Tables("Table1").Rows.Add(ds.Tables("Table1").NewRow()) 'Prompts the dataValue IEnumerable to begin evaluating again.
            ds.Tables("Table1").Rows(ds.Tables("Table1").Rows.Count-1)("ID") = ds.Tables("Table1").Rows.Count
            ds.Tables("Table1").Rows(ds.Tables("Table1").Rows.Count-1)("IntegerValue") = comparisonInteger
            ds.Tables("Table1").Rows(ds.Tables("Table1").Rows.Count-1)("StringValue") = "row" & ds.Tables("Table1").Rows.Count.ToString()
        End If
    End Sub
End Class

To clarify, I used to use a standard DataView with a RowFilter as the BindingSource, which worked:
Dim dv As New DataView(ds.Tables("Table1"))
dv.RowFilter = "IntegerValue=" & (comparisonInteger+iteratorValue)

However I felt it might be nicer to make use of LINQ instead.
So, what's going on here?  Why is the LINQ expression the DataView was based on being re-evaluated on the call to the DataTable's NewRow() method?  Is there any way I can prevent this?
I had hoped that AsDataView() would have produced a DataView that would behave in the same way as the above two lines.
As potential work-around, I've found that I can use this as the BindingSource's DataSource:
New DataView(dataValue.AsEnumerable().CopyToDataTable())
However, I'm concerned about potential performance with such a line in the future, and that I might as well use the DataView with the RowFilter rather than the LINQ if it required the above line.

A: It's the normal behavior of DataTableExtensions.AsEnumerable() and it's documented:

The enumerable object returned by the AsEnumerable method is
  permanently bound to the DataTable that produced it. Multiple calls to
  the AsEnumerable method will return multiple, independent queryable
  objects that are all bound to the source DataTable.

Also the normal behavior of DataView which is also documented:

The DataView does not store data, but instead represents a connected
  view of its corresponding DataTable.

When you call DataTable.AsEnumemarble() method, the EnumerableRowCollection<DatRow> which returns by the method keeps a reference to the original DataTable and then use it each time you call EnumerableRowCollection(Of T).AsDataView() method and returns rows of original DataTable which is used to create the collection.
So in your example dataValue.AsDataView() which you used as DataSource of the BindingSource always returns current rows of DataTable when a ListChanged event raised.
But if you assign new DataView(data.AsEnumerable().CopyToDataTable()) to DataSource of the BindingSource, since you are using a different DataTable by calling CopyToDataTable, changing the original DataTable doesn't have any impact on the data source which is completely unaware of the original DataTable. In fact its enough to use below statement as DataSource of the BindingSource:
bs.DataSource = dataValue.CopyToDataTable()

Example
Put a DataGridView and 3 buttons on a Form, then handle Click event of buttons like below.
DataTable dt;
EnumerableRowCollection<DataRow> data;
BindingSource bs;
private void button1_Click(object sender, EventArgs e)
{
    dt = new DataTable();
    dt.Columns.Add("A", typeof(int));
    for (int i = 0; i < 5; i++)
        dt.Rows.Add(i);
    data = dt.AsEnumerable().Where(x => x.Field<int>(0) >= 3);
    bs = new BindingSource();
    bs.DataSource = data.AsDataView();
    bs.RaiseListChangedEvents = true;
    this.dataGridView1.DataSource = bs;
}
private void button2_Click(object sender, EventArgs e)
{
    dt.Rows.Add(dt.AsEnumerable().Max(x => x.Field<int>(0)) + 1);
}
private void button3_Click(object sender, EventArgs e)
{
    var row = data.Where(x => x.Field<int>(0) == 3).First();
    row[0] = 333;
    MessageBox.Show(dt.Rows[3][0].ToString());
}

Test 1

*

*Click on Button1, the DataGridView will show 3, 4 in column A.

*Click on Button2, new row with 5 as value of column A will be added and shown immediately in grid. Also it shows a MessageBox which shows 3 as count of items in data.

*Click on Button3, 3 will be changed to 333 and immediately will be shown in grid. Also it shows 333 as value of cell in data table.

Result → by turning on ListChanged and using AsDataView you will see changes immediately in grid.
Test 2

*

*Turn off raising ListChanged using bs.RaiseListChangedEvents = false;

*Click on Button1 will act like test 1.

*Click on Button2 will no more shows new record immediately. While it shows 3 as count of rows in data.

*Click on Button3 will no more shows edited value immediately. While the messagebox shows the data has been changed in DataTable.

Result → If you turn off ListChanged event, the changed will not be shown in the list immediately.
Test 3

*

*Use bs.DataSource = data.CopyToDataTable();

*Set bs.RaiseListChangedEvents = true;

*Click on Button1 to fill grid.

*Click on Button2 doesn't have any impact on grid, but shows 3 as number of rows.

*Click on Button3 doesn't have any impact on grid, but shows 333 as value of data table.

Result → AsDataTable creates a new DataTable which is not related to original DataTable.

A: It looks like whenever the underlying DataTable is updated, the LINQ expression for the DataView is automatically re-evaluated.  This means that the LINQ was being re-evaluated when the new row was added to the DataTable, rather than on the call to NewRow().  This wasn't immediately obvious to me as I was doing both actions in a single line: ds.Tables("Table1").Rows.Add(ds.Tables("Table1").NewRow())
@RezaAghaei mentioned that the ListChanged event will get raised if the underlying DataTable is updated.  Through testing, it seems that if the DataView is created from a LINQ expression, it re-valuates the LINQ before the ListChanged event is raised, if the underlying DataTable is updated.
As a consequence of this, setting the BindingSource's RaiseListChangedEvents property won't stop the evaluation of the LINQ, and as the evaluation happens prior to the ListChanged event raised, there appears to be no other event that can be handled to cancel the behaviour, so I don't think it's possible to stop this from happening.
However, now that I understand what it's doing, it makes sense for the underlying LINQ expression to be re-evaluated when the row itself is added to the DataTable, so it probably wouldn't be a good idea to stop it anyway.
It was causing some bother for me though as the new row I was adding was not fully set-up, resulting in an InvalidCastException.  However, in my example above, I merely needed to make sure that the new row is fully set-up before adding it to the DataTable.  Thus, when the LINQ is re-evaluated, the row contains valid data and the expression runs without error.
So, in the example above, the CreateNewRowIfMissing() method merely needs to be adjusted to the following:
Private Sub CreateNewRowIfMissing(comparisonInteger As Integer)

    If  ds.Tables("Table1").AsEnumerable() _
            .Where(Function(v) DirectCast(v("IntegerValue"), Integer) = comparisonInteger) _
            .Count() = 0

        Dim newRow As DataRow = ds.Tables("Table1").NewRow()

        newRow("ID") = ds.Tables("Table1").Rows.Count
        newRow("IntegerValue") = comparisonInteger
        newRow("StringValue") = "row" & ds.Tables("Table1").Rows.Count.ToString()

        ds.Tables("Table1").Rows.Add(newRow) 'Prompts the dataValue IEnumerable to begin evaluating again.
    End If
End Sub

This ensures that the new row is only added to the DataTable after it is ready and contains valid data.  As  result, when it is finally added, the LINQ expression re-evaluates and doesn't throw an InvalidCastException.


text:
Q: Comments to Projects and Users I'm just new to rails and I'm trying to put together a comment feature on my app. However I'm getting the now annoying
Couldn't find Project without an ID

Routes.rb
  resources :projects do
    resources :comments
  end

User model.
  has_many :projects, dependent: :destroy
  has_many :comments

Project model.
  belong_to :user
  has_many :comments , dependent: :destroy

Comments model.
  belongs_to :user
  belongs_to :project

Comments controller.
class CommentsController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]

def create
   @project = Project.find(params[:project_id])
   @comment = @project.comments.build(comment_params)
   @comment.user_id = current_user.id
       if @comment.save
      flash[:success] = "Comment created!"
      redirect_to @project
    else
      flash.now[:danger] = "Sorry! your comment was not created"
    end
  end

 def destroy
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
end

end

Result
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"+/UjIRKAjE+DAATW6eV48xjX+6WW6a/y7Q8DS+nLeCnM8nzwpdzW1FuGXtXVpCGFS0vPivvMi7jvus9IQcjLjA==", "comment"=>{"body"=>""}, "commit"=>"Comment"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
Completed 404 Not Found in 24ms (ActiveRecord: 1.3ms)

ActiveRecord::RecordNotFound (Couldn't find Project without an ID):

---- Update 1 -------
<%= form_for(@comment) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_area :body, placeholder: "Write here" %>

  <%= f.submit "comment", class: "btn btn-primary" %>
<% end %>

Any ideas?

A: I don't know what's written on your form_url. But, definitely it is missing the project_id. So, I suggest you to use the following code:
<%= form_for [@project, @comment] do |f| %>

It'll create a POST request in root/projects/2/comments

A: Thanks all for your posts below is the right solution
<%= form_for ([@project , @comment]) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_area :body, placeholder: "Compose new micropost..." %>

  <%= f.submit "Comment", class: "btn btn-primary" %>
<% end %>

Params
  def comment_params
    params.require(:comment).permit(:body,:project_id,:user_id)
end


text:
Q: Gulp Loop Renders locale tag Incorrectly in Nunjucks Template I've created a gulp task to generate four pages based on the same template, for different languages / locales. The locales are: en-US, en-CA, en-NZ and en-AU. Previously, it was just a simple task written four times - once for each locale, with manual changes written in.
en-AU is the base URL (with no prefix), and the others are website.com/en-us/ etc.
Here is the Gulp task:
let localeList = Object.keys(config.locales);
let localePaths = Object.values(config.locales);

gulp.task('contentful:blog-page', () => {
    return loadBlogArticles()
      .then((res) => {
        for ( locale in localeList ) {
            var path = `pages/${localePaths[locale].toLowerCase()}`

            if (localeList[locale] === 'enAU') {
                path = 'pages'
            }

            gulp.src('pages/templates/blog.njk')
            .pipe(data(() => ({ items: res.items.map(toBlogArticle(res.includes.Entry, res.includes.Asset)), locale: config.locales[localeList[locale]] })))
            .pipe(nunjucksRender({ path: [config.paths.pages.templates] }))
            .pipe(gulp.dest(path))
        }
      }
      )
      .catch((err) => Promise.reject(new Error(`failed fetching blog articles from contentful: ${err.message ? err.message : JSON.stringify(err)}`)))
});

While it's generated all pages in their correct subdirectories, it's the locale: config.locales[localeList[locale]] that's giving me issues.
It sets all the locales to en-US on the blog page, but if I add console.log(config.locales[localeList[locale]]) to the loop, it prints them out separately as it should. This is very puzzling.
Any help would be appreciated!

A: It was a closure error - adding let localeKey = localeList[locale] and replacing other instances of localeList[locale] with localeKey seemed to solve the issue.
Solved thanks to Lesha's comment below


text:
Q: Counting number of objects within a field of mongodb console.log(game.gameQuestions);

The above code outputs:
 [Object, Object, Object].

I would like to somehow count the number of objects.  When I try
console.log(game.gameQuestions.count());

The console outputs :
Exception from Deps recompute function: TypeError: undefined is not a function

Additionally if I try:
console.log(game.gameQuestions.length());

The console outputs :
Exception from Deps recompute function: TypeError: number is not a function

How do I count the number of objects within an attribute?

A: A fetched document from mongodb is just a JavaScript object without any magic applied. game.gameQuestions is an array, so it will have a length property. Length is a positive integer, which explains your last error. This should work:
console.log(game.gameQuestions.length);


text:
Q: JSON ARRAY decoding in android I have got this form server(php) end and unable to decode this using android(java). Can you please help me anyway?
{
    "status": "success",
    "message": [
        {
            "name": "abc abc abc",
            "new_book_id": "49",
            "h_p_y": "8 iso, new 345, 1234",
            "comment": "1",
            "rating": 5,
            "image_link": "http://www.yahoo.com/cou/images/view.jpg",
            "comment_array": [
                {
                    "com": "good like",
                    "name": "android"
                }
            ]
        },
        {
            "name": "cdb cdbcdv",
            "new_book_id": "1234",
            "h_p_y": "345 wert",
            "comment": "1",
            "rating": 3,
            "image_link": "http://www.yahoo.com/cou/images/view.jpg",
            "comment_array": [
                {
                    "com": "I took my wife for her first ever swim.  great value for the price ",
                    "name": "Guest User"
                },
                {
                    "com": "",
                    "name": "Guest User"
                }
            ]
        }
    ],
    "totalsize": 10
}

I can't able to get elements (com, name) from comment array.
I am trying this to decode in android end:
row = new JSONObject(jsonResult);
data = row.getJSONArray("message");
for (int i = 0; i < data.length(); i++) {
    HashMap<String, String> storeValues = new HashMap<String, String>();
    row = data.getJSONObject(i);
    data1 = row.getJSONArray("comment_array");

    for(int k=0;k<data1.length();k++){
        Toast.makeText(getApplicationContext(), "hellow"+k, Toast.LENGTH_SHORT).show();
    }

    storeValues.put(NAME, row.getString("name"));
    storeValues.put(ABC,row.getString("h_p_y"));
    storeValues.put(IMAGE_URL, row.getString("image_link"));
    storeValues.put(RATING,row.getString("rating"));
    storeValues.put(COMMENT,row.getString("comment"));
    storeValues.put(new_book_id,row.getString("new_book_id"));
}

Logcat
09-09 05:53:38.001: I/Choreographer(3377): Skipped 224 frames!  The application may be doing too much work on its main thread.
09-09 05:53:38.032: D/dalvikvm(3377): GC_CONCURRENT freed 194K, 11% free 2979K/3320K, paused 70ms+16ms, total 145ms
09-09 05:53:38.041: D/dalvikvm(3377): WAIT_FOR_CONCURRENT_GC blocked 17ms
09-09 05:53:38.401: D/dalvikvm(3377): GC_CONCURRENT freed 341K, 16% free 3049K/3592K, paused 71ms+93ms, total 216ms
09-09 05:53:38.401: D/dalvikvm(3377): WAIT_FOR_CONCURRENT_GC blocked 134ms
09-09 05:53:38.770: D/dalvikvm(3377): GC_CONCURRENT freed 190K, 11% free 3293K/3684K, paused 89ms+6ms, total 188ms
09-09 05:53:38.770: D/dalvikvm(3377): WAIT_FOR_CONCURRENT_GC blocked 27ms
09-09 05:53:39.171: D/dalvikvm(3377): GC_CONCURRENT freed 445K, 17% free 3296K/3928K, paused 70ms+101ms, total 232ms
09-09 05:53:39.171: D/dalvikvm(3377): WAIT_FOR_CONCURRENT_GC blocked 15ms
09-09 05:53:39.840: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:40.041: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:40.100: I/Choreographer(3377): Skipped 56 frames!  The application may be doing too much work on its main thread.
09-09 05:53:40.131: I/Choreographer(290): Skipped 41 frames!  The application may be doing too much work on its main thread.
09-09 05:53:40.210: I/Choreographer(290): Skipped 30 frames!  The application may be doing too much work on its main thread.
09-09 05:53:40.890: I/Choreographer(290): Skipped 50 frames!  The application may be doing too much work on its main thread.
09-09 05:53:41.901: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:41.911: I/Choreographer(3377): Skipped 50 frames!  The application may be doing too much work on its main thread.
09-09 05:53:41.991: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:42.065: I/Choreographer(3377): Skipped 45 frames!  The application may be doing too much work on its main thread.
09-09 05:53:42.210: I/Choreographer(290): Skipped 55 frames!  The application may be doing too much work on its main thread.
09-09 05:53:42.855: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:43.951: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:44.111: I/Choreographer(290): Skipped 53 frames!  The application may be doing too much work on its main thread.
09-09 05:53:44.780: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:46.019: I/Choreographer(3377): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:46.050: I/Choreographer(290): Skipped 68 frames!  The application may be doing too much work on its main thread.
09-09 05:53:46.080: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:46.905: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:46.997: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:48.102: I/Choreographer(3377): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:48.130: I/Choreographer(290): Skipped 66 frames!  The application may be doing too much work on its main thread.
09-09 05:53:48.151: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:49.015: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:50.186: I/Choreographer(3377): Skipped 44 frames!  The application may be doing too much work on its main thread.
09-09 05:53:50.221: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:50.221: I/Choreographer(290): Skipped 69 frames!  The application may be doing too much work on its main thread.
09-09 05:53:51.106: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:52.210: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:53.013: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:54.252: I/Choreographer(3377): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:54.281: I/Choreographer(290): Skipped 67 frames!  The application may be doing too much work on its main thread.
09-09 05:53:54.290: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:55.173: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:56.351: I/Choreographer(3377): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:56.381: I/Choreographer(290): Skipped 68 frames!  The application may be doing too much work on its main thread.
09-09 05:53:56.410: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:56.601: I/Choreographer(290): Skipped 58 frames!  The application may be doing too much work on its main thread.
09-09 05:53:57.233: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:58.422: I/Choreographer(3377): Skipped 44 frames!  The application may be doing too much work on its main thread.
09-09 05:53:58.461: I/Choreographer(290): Skipped 68 frames!  The application may be doing too much work on its main thread.
09-09 05:53:58.461: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:53:58.627: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:53:59.280: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:00.113: I/Choreographer(353): Skipped 45 frames!  The application may be doing too much work on its main thread.
09-09 05:54:00.473: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:00.473: I/Choreographer(3377): Skipped 46 frames!  The application may be doing too much work on its main thread.
09-09 05:54:00.520: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:00.610: I/Choreographer(290): Skipped 51 frames!  The application may be doing too much work on its main thread.
09-09 05:54:00.610: I/Choreographer(3377): Skipped 53 frames!  The application may be doing too much work on its main thread.
09-09 05:54:01.360: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:02.501: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:03.360: I/Choreographer(290): Skipped 50 frames!  The application may be doing too much work on its main thread.
09-09 05:54:03.448: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:04.621: I/Choreographer(3377): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:04.661: I/Choreographer(290): Skipped 69 frames!  The application may be doing too much work on its main thread.
09-09 05:54:04.671: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:05.502: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:06.679: I/Choreographer(3377): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:06.711: I/Choreographer(290): Skipped 66 frames!  The application may be doing too much work on its main thread.
09-09 05:54:06.740: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:06.881: I/Choreographer(290): Skipped 57 frames!  The application may be doing too much work on its main thread.
09-09 05:54:07.568: I/Choreographer(290): Skipped 44 frames!  The application may be doing too much work on its main thread.
09-09 05:54:07.661: I/Choreographer(290): Skipped 44 frames!  The application may be doing too much work on its main thread.
09-09 05:54:08.741: I/Choreographer(290): Skipped 34 frames!  The application may be doing too much work on its main thread.
09-09 05:54:08.770: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:08.961: D/dalvikvm(3377): GC_CONCURRENT freed 326K, 15% free 3362K/3920K, paused 5ms+7ms, total 282ms
09-09 05:54:10.784: I/Choreographer(3377): Skipped 44 frames!  The application may be doing too much work on its main thread.
09-09 05:54:10.810: I/Choreographer(290): Skipped 66 frames!  The application may be doing too much work on its main thread.
09-09 05:54:10.821: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:11.629: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:12.840: E/SurfaceFlinger(37): ro.sf.lcd_density must be defined as a build property
09-09 05:54:12.980: I/Choreographer(290): Skipped 55 frames!  The application may be doing too much work on its main thread.
09-09 05:54:13.700: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:14.936: I/Choreographer(290): Skipped 43 frames!  The application may be doing too much work on its main thread.
09-09 05:54:15.010: I/Choreographer(290): Skipped 45 frames!  The application may be doing too much work on its main thread.

Thanks in advance.

A: To parse the json. try the below
You have this
data1 = row.getJSONArray("comment_array");

for(int k=0;k<data1.length();k++){
    Toast.makeText(getApplicationContext(), "hellow"+k, Toast.LENGTH_SHORT).show();
}

But where are you parsing the json array. All you are doing is display a toast.
    try
    {
      JSONObject jsonobject = new JSONObject(jsonresult);
      JSONArray jarray = (JSONArray) jsonobject.getJSONArray("message");
      for(int i=0;i<jarray.length();i++)
      {
             JSONObject jb = (JSONObject)jarray.get(i);
             String bookid =  jb.getString("new_book_id");
             JSONArray comment = (JSONArray)jb.getJSONArray("comment_array");
             for(int j=0;j<comment.length();j++)
             {
             JSONObject jb2 = (JSONObject)comment.get(j);
             String com = jb2.getString("com");
             String name = jb2.getString("name");
             Log.i("name is",name);
             }
      }
   }catch(Exception e)
   {

   }


text:
Q: Firestre Subcollection I am trying to add INSTITUTE NAME in 1 collection. then in another collection I want to add its EMAIL ID of that institute name and email can be multiple.
What I tried
const registerRef = collection(db, 'instituteList');
  const userRef = collection(db, 'usersList');

    addDoc(registerRef, { institute })
          .then(function (registerRef) {
            addDoc(doc(userRef, registerRef.id), { email })
          })

My Problem:-
I am getting this ..
Document references must have an even number of segments, but.. has 3
Please help me with this.

A: The firestore data model follows an alternating pattern of collections and documents. You cannot nest a collection under collection, or document under document. That's why document references always an even number of references.
You need to change your database model in order to meet this condition of firestore. Learn more about the firestore data model here

A: The error means that you have wrong db.collection("/one" + uid + "/three") syntax.
Also try Using 2 addDoc properties, one for adding institute name and one for emailId so your code will be:
 const registerRef = collection(db, 'instituteList');
  const userRef = collection(db, 'usersList');

addDoc(registerRef, {
    instituteName: institute,
  });
  addDoc(userRef, {
    emailId: email,
  });


text:
Q: CSV to JSON list of arrays My csv is like this, only have numbers. No headers. I have to identify the name of each column in the javascprit (node.js) code.
1364.00,0.15,0.36,-0.13,-3.24,-0.42,-0.15,0.90,0.00,-0.01,0.02,0.26,0.01,-0.04
1374.00,0.30,0.76,-0.25,-3.25,-0.41,-0.13,0.91,0.00,-0.00,0.02,0.26,0.01,-0.04
1384.00,0.45,1.08,-0.35,-3.17,-0.41,-0.10,1.00,-0.00,-0.01,0.02,0.26,0.01,-0.07

node js code

    const csvFilePath = "test - Cópia.csv"

    const csvtojsonV2=require('csvtojson')
    csvtojsonV2({
        noheader:true,
        checkType:true,
        headers:["Time","Yaw","Pitch","Roll","Heading","Ax", "Ay", "Az","Gx","Gy", "Gz", "Mx", "My", "Mz"],
        colParser:{
            "column1": Int32Array,
            "column2":Int32Array,
            "column3":Int32Array,
            "column4":Int32Array,
            "column5":Int32Array,
            "column6":Int32Array,
            "column7":Int32Array,
            "column8":Int32Array,
            "column9":Int32Array,
            "column10":Int32Array,
            "column11":Int32Array,
            "column12":Int32Array,
            "column13":Int32Array,
            "column14":Int32Array},

    })
    .fromFile(csvFilePath)
    .then((json) => {
        console.log(json)
    })

and the result that i obtain with the code above is this json:
[
      {
        Time: 1364,
        Yaw: 0.15,
        Pitch: 0.36,
        Roll: -0.13,
        Heading: -3.24,
        Ax: -0.42,
        Ay: -0.15,
        Az: 0.9,
        Gx: 0,
        Gy: -0.01,
        Gz: 0.02,
        Mx: 0.26,
        My: 0.01,
        Mz: -0.04
      },
      {
        Time: 1374,
        Yaw: 0.3,
        Pitch: 0.76,
        Roll: -0.25,
        Heading: -3.25,
        Ax: -0.41,
        Ay: -0.13,
        Az: 0.91,
        Gx: 0,
        Gy: -0,
        Gz: 0.02,
        Mx: 0.26,
        My: 0.01,
        Mz: -0.04
      },
      {
        Time: 1384,
        Yaw: 0.45,
        Pitch: 1.08,
        Roll: -0.35,
        Heading: -3.17,
        Ax: -0.41,
        Ay: -0.1,
        Az: 1,
        Gx: -0,
        Gy: -0.01,
        Gz: 0.02,
        Mx: 0.26,
        My: 0.01,
        Mz: -0.07
      }
    ]

I want a little different, like this(bewlow: Each Column a dictionary of arrays.
{"Time": [1364.0, 1374.0, 1384.0],
"Yaw": [0.15, 0.3, 0.45],
"Pitch": [0.36, 0.76, 1.08],
"Heading": [-0.13, -0.25, -0.35],
"Roll": [-3.24, -3.25, -3.17],
"Ax": [-0.42, -0.41, -0.41],
"Ay": [-0.15, -0.13, -0.1],
"Az": [0.9, 0.91, 1.0],
"Gx": [0.0, 0.0, -0.0],
"Gy": [-0.01, -0.0, -0.01],
"Gz": [0.02, 0.02, 0.02],
"Mx": [0.26, 0.26, 0.26],
"My": [0.01, 0.01, 0.01],
"Mz": [-0.04, -0.04, -0.07]}

A: First method
Using your code, which uses the csvtojson library, you can just add this:
    const csvFilePath = "test - Cópia.csv"

    const csvtojsonV2=require('csvtojson')
    csvtojsonV2({
        noheader:true,
        checkType:true,
        headers:["Time","Yaw","Pitch","Roll","Heading","Ax", "Ay", "Az","Gx","Gy", "Gz", "Mx", "My", "Mz"],
        colParser:{
            "column1": Int32Array,
            "column2":Int32Array,
            "column3":Int32Array,
            "column4":Int32Array,
            "column5":Int32Array,
            "column6":Int32Array,
            "column7":Int32Array,
            "column8":Int32Array,
            "column9":Int32Array,
            "column10":Int32Array,
            "column11":Int32Array,
            "column12":Int32Array,
            "column13":Int32Array,
            "column14":Int32Array},

    })
    .fromFile(csvFilePath)
    .then((json) => {
       const RESULT = json.reduce((acc, v, i) => {
          for (const [key, value] of Object.entries(v)) {
            if (!acc[key]) acc[key] = [];
            acc[key].push(value);
          }
          return acc;
        }, {});
       console.log(RESULT)
    })

What it does is to accumulate the data in acc variable, using each rows' keys these keys being the header, as you can see in acc[key].push(value), the if (!acc[key]) acc[key] = [] is to make sure the heading is initializied with an empty array in the acc variable (accumulator);
Second method
This doesn't use any library:

// Arbitrary data (from you example).
const DATA = `1364.00,0.15,0.36,-0.13,-3.24,-0.42,-0.15,0.90,0.00,-0.01,0.02,0.26,0.01,-0.04
1374.00,0.30,0.76,-0.25,-3.25,-0.41,-0.13,0.91,0.00,-0.00,0.02,0.26,0.01,-0.04
1384.00,0.45,1.08,-0.35,-3.17,-0.41,-0.10,1.00,-0.00,-0.01,0.02,0.26,0.01,-0.07
`.trim().split('\n').map(row => row.split(','));

const HEADERS = ["Time", "Yaw", "Pitch", "Roll", "Heading", "Ax", "Ay", "Az", "Gx", "Gy", "Gz", "Mx", "My", "Mz"];

const RESULT = {};

// Assign every heading to the result.
for (const HEADING of HEADERS) RESULT[HEADING] = [];

DATA.map(row =>
  // Each row → each column, number of columns === number of headers
  row.map((column, i) =>
    RESULT[HEADERS[i]]
    .push(Number(column))
  )
);

console.log(RESULT);

Explanation of each step:

*

*Assuming that the CSV's contents separates rows with "\n" and the preferred column separator is ",", I set up an arbitrary data contents;

*A constant HEADERS is created, the headers must be the same length of the CSV's data columns;

*A constant RESULT is created, this will store the result of the parsed data to JSON.

*We initialize the keys of RESULT with the defined HEADERS with an empty array;

*We map the data from each row then each column, using the column's index to refer to the current heading in our HEADERS array, since the length of the columns are expected to be equal to the length of the HEADERS constant.

If you must keep the trailing zeroes (e.g.: 15.00) of the numbers, then you can just remove Number() method from Number(column) inside the .push() method before inserting into the result array.


text:
Q: Rotation for TextView I have a simple view with included TextView on RelativeLayout
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:textSize="21sp"
    android:rotation="-20"
/>

and it works well on slider view, but when I'm trying to include it to list adapter it has gone.
I tried to wrap this TextView to LinearLayout and set it programmatically, but it hasn't helped.
How can I rotate my view? What is it a sort of problem? Thank for any help.


text:
Q: Pandas is turning some empty values to None I have a script that takes a DF from google sheet via the API, all is working fine but i need to replace all the empty cells in one column with -1 as a string, for that i´m using this code
data = pd.DataFrame.from_records(values_data)
data['Column_name'] = data['Column_name'].replace('', '-1')

That works in most of the cases, but in some cases pandas don´t replace the value and if i print the content of the cell it says is None, but in the g-sheet the cell is empty as the rest


text:
Q: Use an array of values to query Firestore and setup a snapshot listener Here is my problem:
I have a firestore collection that has a number of documents.  There are about 500 documents generated/updated every hour and saved to the collection.
I would like to query the collection and setup a real-time snapshot listener for a subset of document IDs, that are provided by the client.
I think maybe I could to something like this (this syntax is likely not correct...just trying to get a feel for if it's even possible...but isn't the "in" limited to an array of 10 items? ):
const subbedDocs = ["doc1","doc2","doc3","doc4","doc5"]
docsRef.where('docID', 'in', subbedDocs).onSnapshot((doc) => {
   handleSnapshot(doc);
   });

I'm sorry, that code probably doesn't make sense....I'm still trying to learn all the ins and outs of Firestore.
Essentially, what I am trying to do is take an array of ID's and setup a .onSnapshot listener for those ID's.  This list of IDs could be upwards of 40-50 items.  Is this even possible?  I am trying to avoid just setting up a listener on the whole collection and filtering out things I am not "subscribed" too as that seems wasteful from a resources perspective.

A: If you have the doc IDs in your array (it looks like you have) you can loop over them and start a listener during that:
const subbedDocs = ["doc1", "doc2", "doc3", "doc4", "doc5"];

for (let i = 0; i < subbedDocs.length; i++) {
  const docID = subbedDocs[i];

  docsRef.doc(docID).onSnapshot((doc) => {
    handleSnapshot(doc);
  });
}

It would be better to listen to a query and all filtered docs at once. But if you want to listen to each of them with a explicit listener that would do the trick.

A: As you've discovered, Firestore's in operator only allows up to 10 entries in the array.  I'm also guessing you've added the docID as a field in the document, since I don't believe 'docID references the actual documentid.
I would not take this approach, because of the 10-entry limitation.  What I would do is, as the client is selecting documents to follow, set a field (same in each document) to a unique Id for the client, so your query completely avoids the limitation.  You can allow an unlimited number of Client listeners (up to implementation limits of Firestore) if you add that client ID into an array (called something like "ListenerArray") [again, as the client is selecting them].  Your query would be more like:
docsRef.where('ListenerArray', 'array-contains', clientID).onSnapshot((doc) => {
   handleSnapshot(doc);
   })

array-contains checks a single value against all entries in a document array, without limit.  Every client can mark any number of documents to subscribe to.


text:
Q: Does XMLHttpRequest.onreadystatechange still gets called under the hood when we use Promises? Let us say I am using a Promisified API for making an Ajax Request, even then the event-loop would still call the plain old XMLHttpRequest.onreadystatechange right?
I mean Promisfying is a nice way to write code in a sequential style, but under the hood what happens is still the plain old mechanisms right? A bit like the class syntax in ECMASCRIPT 6. In other words, the core API's are still the same?
I can't see how we can register a Promise directly to an event-loop, because there should be some logic should be there which would "resolve" or "reject", so a simple wrapper has to exists [that can be implemented a promise too, I don't know if it would lead to too much promises]?

A:
Let us say I am using a Promisified API for making an Ajax Request, even then the event-loop would still call the plain old XMLHttpRequest.onreadystatechange right?

There are several ways to make Ajax requests.
A library which wrapped a promise around XHR could use a readystatechange event. It could use load and error events.
A promise-based Ajax library could avoid XHR entirely.
It could use JSONP.
fetch is supported natively in browsers, is promise based, and doesn't go near XHR.

A bit like the class syntax in ECMASCRIPT 6. In other words, the core API's are still the same?

No.
Promises are a standardised API, not just different syntax to do the same things as existing code.