text:
Q: User Control Event against Form Control Event Here is my situation, I have a user control that have the Leave event:
Private Sub MyControl_Leave(sender As Object, e As EventArgs) Handles Me.Leave
    If Me.Enabled Then
        MsgBox(Property1)
    End If
End Sub

I have this to prevent Leave Event from triggering when the control is Disabled.
Then on my form, the control also has its own Leave event because I need to set some Properties that the Leave Event on the User Control needs.
Private Sub myControlOnForm_Leave(sender As Object, e As EventArgs) Handles MyControlOnForm.Leave
    MyControlOnForm.Property1 = "value1"
End Sub

What happens is the first event that triggers is the one on the User Control and then the one on the form.
Now my problem is, as the code states above, I need the Form Event to trigger first before the User Control Event.
Is there any work around for this?

A: The form needs to call a procedure in the user control after it's finished handling the event. Just remove the Handles Me.leave statement, and the private statement. use the sub from your form to call the controls sub which was intended to handle the event.
Note that I've changed sender As  object to sender As Mycontrol.
Sub MyControl_Leave(sender As Mycontrol, e As EventArgs)
    If Me.Enabled Then
        MsgBox(Property1)
    End If
End Sub

Code on form
Private Sub myControlOnForm_Leave(sender As Mycontrol, e As EventArgs) Handles MyControlOnForm.Leave
    MyControlOnForm.Property1 = "value1"
    sender.MyControl_Leave(sender, e)
End Sub

A:
What happens is the first event that triggers is the one on the User Control and then the one on the form.
Now my problem is, as the code states above, I need the Form Event to
  trigger first before the User Control Event.

First off, you are using the incorrect term in that problem statement.  It is not an event triggering order issue, but rather an issue in order in which the event handlers registered for the UserControl's Leave event execute.
.Net events are a form of syntactic sugar for the invocation of a multicast delegate.  When an event is raised a delegate is invoked and the order in which the handlers are executed is the order in which they were added to the delegate.  You can gain an understanding of this by working through the various "Walkthrough" tutorials located under Events (Visual Basic).
The Leave event is Raised by calling the Overridable OnLeave method inherited from the Control Class that is in the inheritance tree of the UserControl Class.  It is considered bad form for a class to handle its own generated event;  the preferred method is Override the method that raise the event.
In your case, you want the form that subscribes to the event to be notified first so that it can modify a property on the UserControl before some it performs some action in response to Leaving the UserControl.
Public Class UserControl1
    Protected Overrides Sub OnLeave(e As EventArgs)
        MyBase.OnLeave(e)   ' this calls the base method that Raises the event
                            ' all event handlers will run before the subsequent code
                            ' executes
        If Me.Enabled Then
            'do something
        End If
    End Sub
End Class


text:
Q: iframe - scale down webpage by 0.30 but scale mobile webpage by 0.90? Im using the following to scale down webpages in an iframe and it works great for ordinary webpages, but if the webpage is a mobile webpage(and therefor only 320px wide) then I would like to scale it down with -webkit-transform: scale(0.90); instead of 0.30.

I have tryed a lot of stuff from googling to get the width of the page that is loaded in the iframe, to try and calculate and set the width of the iframe to something like (content width * 0.90)
Or if you have any other suggestions? Thanks.

A: If I am understanding your purpose correctly I think you want to avoid scaling down too much on small screens (iPhone??).
You can use @media queries to find the device pixel ratio and write overriding CSS classes for them.
A quick googling landed me on @opticswerve's article here.
EDIT : If you want to go with the device device max width @media queries would still help as noted in the stackoverflow question here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is the v1.02 patch still available for the Dos game Alien Logic? Here's the game in question: Alien Logic (@ Moby Games)
My question is this:
Does anybody know if the patch is still available, and if so, where it can be found? I am looking for the 1.02 patch, which I assume is the latest (and last) official version of the game.
I am working off of the original disc and not a downloaded and compiled zip (as available on some abandonware sites). The version on the disc installs as v1.00
The FAQ on Gamefaqs suggests to get if from the Broderbund support page but the page doesn't seem to be there anymore. The posting date of the FAQ in question is 2007, so it is a bit outdated.
Here is the FAQ at Gamefaqs, if this concerns anyone.

A: Yes the Patch is available here, it's the one called Alien102.zip http://www.gamers.org/pub/archives/uwp-uml/patches/
It seems some people may be wary of downloading the zip file, there are only two things I can say to that, 1st the .txt by the same name there indicates clearly that this is for the right game, it also details the fix etc. I've downloaded the .ZIP myself, and confirm that it is the right file.
I know you now have nothing more than my word on the fact that it's the right file, but, well, it is and this seems to be the only place you can readily get a copy of it too, all other locations are no longer in existence.
I've been a big fan of this game for almost 20 years, so would hate to see the final patch disappear, and giving this answer was actually my sole reason for signing up to this site. I'll be keeping this copy of said file very safe from now on, given that it's now so difficult to find and who knows when it may be gone for good...
My best to any fellow AL fans.

A: It also seems that the patch is known by the version 1.1 and may be found here (PC Gaming Wiki), though the change-log is exactly the same.


text:
Q: active record, use instance variable was defined in before_destroy block Some context:
A company has many users. Whose one is the owner.
You can destroy everyone on the company except the owner.
Destroy the owner, it's like destroy the company. So you must do company.destroy
I prevent destroy user if he is owner, except if you are destroying the company.
My code:
class Company < ActiveRecord::Base
  before_destroy { @bool_allow_owner_be_destroyed = true ; p object_id }

  belongs_to  :owner,     class_name: 'User', foreign_key: 'owner_id'
  has_many    :employees, class_name: 'User', dependent: :destroy

  def can_owner_be_destroyed?
    p @bool_allow_owner_be_destroyed
    p object_id
    !!@bool_allow_owner_be_destroyed
  end
end

class User < ActiveRecord::Base
  belongs_to        :company
  before_destroy    :cancel_if_owner

  def cancel_if_owner
    !self.is_owner? || self.company.can_owner_be_destroyed?
  end
end

My question:
When I call company.destroy I see my debug. I'm passing in before_destroy { @bool_allow_owner_be_destroyed = true ; p object_id } and I see my object_id.
When I passing in can_owner_be_destroyed? method, I have the same object_id, but my @bool_allow_owner_be_destroyed is nil. It's the only place on my code I touch the @bool_allow_owner_be_destroyed variable.
Any ideas?

A: Depending on the order of declaration, your dependent objects can be destroyed before the before_destroy callback is run for the parent object.
You can test this yourself:
class Company < ActiveRecord::Base
  belongs_to  :owner,     class_name: 'User', foreign_key: 'owner_id'
  has_many    :employees, class_name: 'User', dependent: :destroy

  before_destroy do
    @test_variable = "hi"
    puts @test_variable
    puts "Company destroyed"
  end
end

class User < ActiveRecord::Base
  belongs_to        :company

  before_destroy do
    puts company.instance_variable_get(:@test_variable)
    puts "User destroyed"
  end
end

"Company destroyed" will be the last thing printed after all the users are already gone, and you will get an empty string putsed in place of "hi" for each user, because @test_variable has not yet been set. However if you declare that callback before you declare the associations, "Company destroyed" will be printed first, and you should see "hi" printed as each User is destroyed.
If you ask me, that's very unexpected. Callbacks can overcomplicate things and are often overused, how can we guarantee we know exactly what's happening in such a complex execution flow? Ruby has a built-in callback system for descendant objects that is much easier to understand, and very predictable in its behavior: super
class Company
  def destroy(*args, &block)
    @bool_allow_owner_be_destroyed = true
    super
  end
end

Anything you do before the call to super will be guaranteed to run before any of the dependent objects are destroyed or anything else that's triggered by destroy. There's no ambiguity when using super.
To cancel destroy for the owner you could also use super, along with an early return.
class User < ActiveRecord::Base
  belongs_to :company

  def destroy(*args, &block)
    return unless can_be_destroyed?
    super
  end

  def can_be_destroyed?
    !is_owner? || company.can_owner_be_destroyed?
  end
end

Overall I'd suggest that trying to carry state on an ActiveRecord object with an instance variable might get you in trouble at some point, especially if associated objects will rely on that state or you have multiple instances of your app running at the same time.
You could instead make this a db field and persist the change.
class AddAllowOwnerBeDestroyedColumnToCompanies < ActiveRecord::Migration
  def change
    add_column :companies, :allow_owner_be_destroyed, :boolean, default: false
  end
end

class Company < ActiveRecord::Base
  belongs_to  :owner,     class_name: 'User', foreign_key: 'owner_id'
  has_many    :employees, class_name: 'User', dependent: :destroy

  # You won't need this method b/c you now have `#allow_owner_be_destroyed?` for free
  # def can_owner_be_destroyed?
  #  p allow_owner_be_destroyed
  #  p object_id
  #  allow_owner_be_destroyed
  # end

  def destroy(*args, &block)
    update allow_owner_be_destroyed: true
    super
  end
end

class User < ActiveRecord::Base
  belongs_to :company

  def destroy(*args, &block)
    return unless can_be_destroyed?
    super
  end

  def can_be_destroyed?
    !is_owner? || company.allow_owner_be_destroyed?
  end
end


text:
Q: Capturing the close of the browse for file window with JavaScript I am using infile to ask the users to browse for a file on their machine. Is there way to catch if the window is closed without file being selected? For example if x is clicked.
<input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/>

Thanks

A: With the solution from HTML input file selection event not firing upon selecting the same file, I think you can use this:
<input type="file" name="data" id="inFile" />

var fileElem = document.getElementById("inFile");
var fileSelected = null;
fileElem.onclick = function(e) {
    fileSelected = this.value;
    this.value = null;
});
/* or use this in your browse() function:
    fileElem.value = null;
*/
fileElem.onchange = function(e) { // will trigger each time
    handleFileDialog(this.value === fileSelected);
};

function handleFileDialog(changed) {
    // boolean parameter if the value has changed (new select) or not (canceled)
}

A: I think the blur event will do it:
<input
  type="file"
  onchange="changed=true; handleFiles(this)"
  onblur="if(!changed) alert('nothing selected'); changed=false;"
/>

A: What I did is:
 Start timer after the user opens the window, and in that timed function I check every 0.5 sec if the file has been selected with boolean var. I stop the timer as soon as user selects the file or HTML5 DnD occurs.  I hope this helps someone.

<input type="file" name="data" id="inFile" size="15" style="display:none" onchange="handleFiles(this)"/>

<button dojoType="dijit.form.Button" id="fileSelect" type="button" onmouseup="browse();">Browse</button>

var fileselected = false;
function handleFiles(input){
    fileselected = true;
//use input
}

var interval;
function browse(){
    fileselected = false;
    var fileElem = document.getElementById("inFile");
    fileElem.click();
    interval = setInterval(setdiv, 500);

}
function setdiv(){
    if(!fileselected){
        //do staff until user decides to Dnd or  browse for file again
        clearInterval(interval);
    }
}


text:
Q: Default invalid select option in Angular 2 model-driven forms? Is there any way to achieve an invalid default select option in an Angular 2 model driven form?
I'm looking for something like this:
<select name="DateExpiryMonth" [(ngModel)]="model.DateExpiryMonth" ngControl="dateExpiryMonth" required>
    <option value="" selected="selected" disabled>Month...</option>
    <option *ngFor="let month of months" [value]="month">{{ month }}</option>
</select>

Ideally, the required attribute on the select would ensure that the first <option> would be considered invalid by Angular 2, yet I can't find any documentation that suggests this is possible.
As it stands, the first "Month..." option is considered valid by Angular 2.

A: I don't think this is an ideal solution, but I found that if I set the field in my model to either null or undefined (in your case model.dateExpiryMonth) that angular would consider the form invalid.


text:
Q: SingleOrDefault and FirstOrDefault returning cached data Some previous code I had written used the Find() method to retrieve single entities by their primary key:
return myContext.Products.Find(id)

This worked great because I had this code tucked into a generic class, and each entity had a different field name as its primary key.
But I had to replace the code because I noticed that it was returning cached data, and I need it to return data from the database each call.  Microsoft's documentation confirmed this is the behavior of Find().
So I changed my code to use SingleOrDefault or FirstOrDefault.  I haven't found anything in documentation that states these methods return cached data.
Now I am executing these steps:

*

*Save an entity via EF.

*Execute an UPDATE statement in SSMS to update the recently saved
record's Description field.

*Retrieve the entity into a new entity variable using SingleOrDefault
or FirstOrDefault.

The entities being returned still have the old value in the Description field.
I have run a SQL trace, and verified that the data is being queried during step 3.  This baffles me - if EF is making a round trip to the database, why is it returning cached data?
I've searched online, and most answers apply to the Find() method.  Furthermore, they suggest some solutions that are merely workarounds (dispose the DbContext and instantiate a new one) or solutions that won't work for me (use the AsNoTracking() method).
How can I retrieve my entities from the database and bypass the EF cache?

A: The behaviour you're seeing is described in Microsoft's How Queries Work article under point 3:

*For each item in the result set

a. If this is a tracking query, EF checks if the data represents an entity already in the change tracker for the context instance

*

*If so, the existing entity is returned

It's described a little better in this blog post:

It turns out that Entity Framework uses the Identity Map pattern. This means that once an entity with a given key is loaded in the context's cache, it is never loaded again for as long as that context exists. So when we hit the database a second time to get the customers, it retrieved the updated 851 record from the database, but because customer 851 was already loaded in the context, it ignored the newer record from the database (more details).

All of this is saying that if you make a query, it checks the primary key first to see if it already has it in the cache. If so, it uses what's in the cache.
How do you avoid it? The first is to make sure you're not keeping your DbContext object alive too long. DbContext objects are only designed to be used for one unit of work. Bad things happen if you keep it around too long, like excessive memory consumption.

*

*Do you need to retrieve data to display to the user? Create a DbContext to get the data and discard that DbContext.

*Do you need to update a record? Create a new DbContext, update the record and discard that DbContext.

This is why, when you use EF Core with dependency injection in ASP.NET Core, it is created with a scoped lifetime, so any DbContext object only lives for the life of one HTTP request.
In the rare case you really do need to get fresh data for a record you already have an object for, you can use EntityEntry.Reload()/EntityEntry.ReloadAsync like this:
myContext.Entry(myProduct).Reload();

That doesn't help you if you only know the ID though.
If you really really need to reload an entity that you only have the ID for, you could do something weird like this:
private Product GetProductById(int id) {
    //check if it's in the cache already
    var cachedEntity = myContext.ChangeTracker.Entries<Product>()
                           .FirstOrDefault(p => p.Entity.Id == id);
    if (cachedEntity == null) {
        //not in cache - get it from the database
        return myContext.Products.Find(id);
    } else {
        //we already have it - reload it
        cachedEntity.Reload();
        return cachedEntity.Entity;
    }
}

But again, this should only be used in limited cases, when you've already addressed any cases of long-living DbContext object because unwanted caching isn't the only consequence.

A: Ok, I have the same problem and finally found the answer,
You doing everything right, that's just how EF works.
You can use .AsNoTracking() for your purposes:
return myContext.Products.AsNoTracking().Find(id)

make sure you addedusing Microsoft.EntityFrameworkCore; at the top.
It works like a magic


text:
Q: Crashed VirtualBox in Ubuntu after updates I have Ubuntu 12.04 LTS. After I insert this:sudo apt-get update && sudo apt-get dist-upgrad command in terminal , because I understand wrong! So I received the message below:
text*Kernel driver not installed (rc=-1908)

The VirtualBox Linux kernel driver (vboxdrv) is either not loaded or there is a permission problem with /dev/vboxdrv. Please reinstall the kernel module by executing

/etc/init.d/vboxdrv setup

as root. If it is available in your distribution, you should install the DKMS package first.
This package keeps track of Linux kernel changes and recompiles the vboxdrv kernel module if necessary.

text*Result Code:
NS_ERROR_FAILURE (0x80004005)
Component:
Machine
Interface:
IMachine {22781af3-1c96-4126-9edf-67a020e0e858}

Thanks in Advance!

A: Open a terminal and type the command:
sudo /etc/init.d/vboxdrv setup

as you are asked in the error message.
You will need to do it each time you update your kernel.


text:
Q: Guess the Word Game: Guesses For Secret Word Aren't Being Accepted I'm working in Python 3.x and am fairly new, so I hope what I am asking makes sense. I am supposed to be focusing on for loops and strings for this word-guessing game.
Here's the (jumbled/lengthy/cluttered) code I have so far:
import sys
import random

def Main():
    PlayAgain = "y"
    print("COP 1000 Project 4 - Courtney Kasonic - Guess the Word Game")
    print("I'm thinking of a word; can you guess what it is?")
    while PlayAgain == "y":
        Words = "apple alphabet boomarang cat catharsis define decide elephant fish goat horizon igloo jackelope ketchup loop limousine monkey night octopus potato quick rebel separate test underway violin world yellow zebra".split()
        SecretWord = random.choice(Words)
        MissedLetters = ""
        CorrectLetters = ""
        ChosenWord = GetWord(Words)
        Guess = FiveLetters(CorrectLetters+MissedLetters)
        for Guess in ChosenWord:
            CorrectLetters = CorrectLetters + Guess
        ShowWord(CorrectLetters, ChosenWord)
        for i in ChosenWord:
            CLetters = ""
            if Guess in ChosenWord:
                Blanks = "_" * len(SecretWord)
                for i in range(len(SecretWord)):
                    if SecretWord[i] in CLetters:
                        Blanks = Blanks[i] + SecretWord[i]
                        print(Blanks)
                        print(CLetters)

def GetWord(List):
    SecretWord = random.choice(List)
    return(SecretWord)

**def FiveLetters(LettersGuessed):
    a = 2
    if a > 1:
        print("Enter five letters to check: ",end="")
        Guess = input()
        if len(Guess) != 5:
            print("Please enter five letters.")
        elif Guess in LettersGuessed:
            print("You already guessed that letter.")
        elif Guess not in "abcdefghijklmnopqrstuvwxyz":
            print("Please enter a letter.")
        else:
            return(Guess)**

def ShowWord(CLetters, SecretWord):
    print("\nHere is the word showing the letters that you guessed:\n")
    CLetters = ""
    Blanks = "_" * len(SecretWord)
    for i in range(len(SecretWord)):
        if SecretWord[i] in CLetters:
            Blanks = Blanks[i] + SecretWord[i]
            print(Blanks)
            print(CLetters)
        return(Blanks, SecretWord, CLetters)

def CheckLetters(Letters):
    Letters = "a b c d e f g h i j k l m n o p q r s t u v w x y z".split()
    for Letters in Word:
        print(Letters)
    return(Letters)

Main()

The bolded area is where I am having problems. Only five letters can be entered to "check" to see if they are in the secret word. It will only accept input like "abcde". It will not accept input like "aaaaa" or "muihi" i.e. it won't accept guesses that are not in order or have more than one of the same letter.

I am also having trouble with the underscores. Not sure if the code I have for it up there is correct or not. The letters that are guessed correctly will not replace the appropriate underscore.
Ex: Secret Word = dog. If I guess the letters "mopfe" (though I can't because of issue above) then it will print out "_ _ _" without the "o".

A: You will inevitably ask more questions, assuming you don't want to fail. If you ask those questions on StackOverflow you should probably read the FAQ. Since you are using python you should probably also read the style guide (i.e. PEP 8), it was mentioned in the comments. This code, while incomplete, will get you started.
import sys
import random

def main():
    play_again = "y"
    print("COP 1000 Project 4 - Courtney Kasonic - Guess the Word Game")
    print("I'm thinking of a word; can you guess what it is?")

    words = "apple alphabet boomarang cat catharsis define decide elephant fish goat horizon igloo jackelope ketchup loop limousine monkey night octopus potato quick rebel separate test underway violin world yellow zebra".split()
    secret_word = random.choice(words)
    correct_letters = ""

    while play_again == "y":

        guess = five_letters(correct_letters)

        for letter in guess:
            if letter in secret_word:
                correct_letters += letter

        show_word(correct_letters, secret_word)

def five_letters(letters_guessed):

        guess = raw_input("Enter five letters to check: ")

        if len(guess) != 5:
            print("Please enter five letters.")
        elif guess in letters_guessed:
            print("You already guessed that letter.")
        elif guess not in "abcdefghijklmnopqrstuvwxyz":
            print("Please enter a letter.")
        else:
            return guess

def show_word(correct_letters, secret_word):
    print("\nHere is the word showing the letters that you guessed:\n")
    word_display = ""

    for index, letter in enumerate(secret_word):
        if letter in correct_letters:
            word_display += letter
        else:
            word_display += "_"

    print word_display

if __name__ == "__main__":

    main()


text:
Q: how to update Multiple project in one command I have multiple laravel projects. If I make a custom module for one project and I want that module automatically install to other projects in one way. I don't want to do go to a single project and install modules one by one.. is there any way to update my module in all projects ??
Thanks.


text:
Q: how to create distinct list from 2 fields with XSLT I have a list with values which could be repeated, in example:
<dates>
    <date>
        <month>January</month>
        <year>2015</year>
    </date>

    <date>
        <month>January</month>
        <year>2016</year>
    </date>

    <date>
        <month>February</month>
        <year>2015</year>
    </date>

    <date>
        <month>January</month>
        <year>2016</year>
    </date>
</dates>

Would like to receive list with distinct list:
January 2015
February 2015
January 2016
Not sure is possible and may I edit code below with foreach:

      <xsl:value-of select="distinct-values(.)"/>

or with:

        <xsl:foreach select="//dates/date[not(.preceding::*)]"?

A: Ordering the entities can be achieved with the following XSLT 1.0 template. It eliminates duplicates and sorts by years:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:key name="someDate" match="date" use="concat(month/text(),' ',year/text())" />

  <xsl:template match="/dates">
    <xsl:for-each select="date[generate-id() = generate-id(key('someDate',concat(month/text(),' ',year/text()))[1])]">
      <xsl:sort select="year/text()" />
      <xsl:value-of select="concat(month/text(),' ',year/text())" /><xsl:text>
</xsl:text>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Result is:
<?xml version="1.0"?>
January 2015
February 2015
January 2016

However, it doesn't sort the month's names, it just sorts the years.
If you like to surround the results with li elements, replace the xsl:value-of with

  <xsl:value-of select="concat(month/text(),' ',year/text())" />

A: This shall do:
distinct-values(/dates/date/concat(month, ' ', year))
The xpath is to select the concatenation of month and year, and then select the distinct-values among them.


text:
Q: How can i groupBy using multiple column name? I have a table named as tags. Column name are id,tag_name.
I want to group by by using tag_name .
That will looks like this,
{ beauty,general-health,pregnency } as health.
What will be the sql query?

A: do a subquery
   select...
    from (
    select { beauty,general-health,pregnency } as health
    from table) t
    group by health

A: select * from tags  group by tag_name


text:
Q: Want to change home page url in top nav, but can't figure out how I have built a site with top nav but the url for my home page is incorrect. When I try to use the edit links feature, that home page link disappears. How can I edit this so my users can go to the correct page. Image attached.

A: To update navigation in SharePoint 2013 you'll go to site settings(it's found under the settings gear), then navigation, after you open navigation you'll scroll down a little until you see the section called Structural Navigation. Select the link you want to edit then click on edit and follow the wizard that pops up. Make sure you select the OK button twice or your changes won't be recorded. You click on on the wizard that pops up and at the bottom of the navigation page.


text:
Q: What is the best way to implement optional library dependencies in Rust? I am writing a toy software library in Rust that needs to be able to load images of almost any type into an internal data structure for the image.  It is early days for the Rust ecosystem, and there is no one library/set of bindings that I would trust for this task.
I would ideally like:

*

*Support multiple redundant external libraries that may or may not be available at runtime

*Support multiple redundant external libraries that may or may not be available at compile-time.

*Include at least one fallback implementation that ships with my code.

*Fully encapsulate all of the file loading stuff behind a function that does path -> InternalImage loading.

Is there a best practice way to implement optional dependencies like this in Rust?  Some of the libraries will be Rust, and some of them will probably be C libraries with Rust bindings.

A: Cargo, the Rust package manager, can help with that. It lets you declare optional compile-time dependencies. See the [features] section of Cargo's documentation.
For runtime dependencies I'm not sure. I think std::dynamic_lib could be helpful. See an example of using DynamicLibrary in a previous SO question.


text:
Q: Difference between a Variable and an Object in Objective-C I am some kind of messed up with the following commonly used code :-
NSArray *arrayData = [[NSArray alloc] init];

Problem is someone is telling that arrayData is an object since it is derived from NSArray Collection class but at the some time it is allocated some memory and declared as a pointer variable.
Please clarify whether it's a variable or an object ?

A: arrayData is a variable. It is a reference (pointer) variable, so it refers something.
What it refers to, the target of the pointer, is an object.
In Objective-C all objects are heap allocated, that means, that they are created solely at runtime in heap memory. In such a case you always need a reference to it, which is typically a variable allocated in stack memory.
Try this:
NSMutableString *string = [NSMutableString new]; // A variable string referring a mutable string object;
NSMutableString *string2 = string; // Another variable string2 referring the same (identical) mutable string object.
[string appendString:@"Amin"]; // The object, string refers to is now "string"
NSLog( @"%@", string2 ); // The same (identical) object, referred by another variable is now "string", too.

To make it more complex, C – the base of Objective-C – calls an "object" everything that lives at runtime: Variables, OOP-objects, …

A: In your code snippet arrayData is technically a pointer. It is a pointer to an address in memory whose value contains an object of type NSArray.
Conversationally you can probably get by with referring to it as an "object" but its important to know what is.

Is it a variable?

Its probably also safe to think about the arrayData pointer in your code as a variable that has a scope and that can be manipulated.
You might also be getting tripped up on the -alloc and -init methods..
Very generally speaking...
-alloc: allocates a slot in memory for your NSArray object.
-init: initializes that NSArray object and returns a pointer to that object in memory.
More on working with objects:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html
And Obj-C initialization:
https://www.binpress.com/tutorial/objectivec-lesson-11-object-initialization/76

A: NSArray *arrayData = [[NSArray alloc] init];

There's a lot going on in this statement. The first occurrence of 'NSArray' is telling the compiler to create arrayData as a pointer to this type of object (an NSArray), whereas the second occurrence of 'NSArray' (with the alloc) is passing the 'alloc' message (method) to the NSArray class (i.e. Calling the alloc method). Same word, two completely different meanings.
Conceptually, the first thing that happens is [NSArray alloc] which is calling the (class) method 'alloc' in the 'NSArray' class. This returns an (empty) instance of an NSArray object. We the call the 'init' method in our new, empty object. A pointer to the resultant object is then stored in your 'arrayData' variable, and we tell the compiler that this is a pointer to an NSArray object.
Think of it like this:
NSArray *arrayData;         Create a pointer to an NSArray object.
newArray = [NSArray alloc]; Create an empty NSArray object by calling the class method alloc in NSArray
[newArray init];              Initialise it by calling the object's 'init' method
arrayData = *newArray;        Assign a pointer to it to my variable.

A: *

*It's create object of type array in heap memory. and it's reference created in in stack memory. in your case arrayData is reference stored in stack memory which points your array object in heap memory.

*arrayData is a variable. It is a reference (pointer) variable, so it refers something.

*What it refers to, the target of the pointer, is an object.

A: What is actually happens when you declares NSArray *arrayData = [[NSArray alloc] init];,
It's create object of type array in heap memory. and it's reference created in in stack memory. in your case arrayData is reference stored in stack memory which points your array object in heap memory.

The Object is the instance itself, whereas the Object Variable is the reference to the Object. Here's a contrived example: Object o = new Object(); Object ref1 = o; In his case, there is a single instance of the Object, but it is referenced by two Object Variables: o and ref1

This is the general scenario for object oriented programming and Objective C definitely follows it.

A: In programming, a variable is a name given to a memory location which holds a value, but where the exact value can change over the life of the program.  (If the value can't change, due to language constraints, it's called a constant.  If it could change, but doesn't, it's still a variable.)
An object is not a variable, though it usually contains a few.  The pointer to the object is usually a variable, in that the memory location which contains the pointer to the object may change values over time.  From the programmer's perspective, this is using the same pointer to refer to different objects over the course of the program.

A: NSArray is a class. Here:

*

*NSArray * - type (From left one)

*arrayData - variable name

*[[NSArray alloc] init] - class NSarray, An invocation of a class method

When ever you create any object using alloc/init, its retain count will be increase by one. That means it will occupy some memory. So for memory management you have to take care of that retain count.


text:
Q: typeerror cannot read property 'push' of undefined It gives typeerror cannot read property 'push' of undefined, when data pushing into Array. I want to add data into array for every loop.
if (s > 0) {
    for (let key in result.shiftStatusList) {
        var data = result.shiftStatusList[key];
        this.shiftStatusList = data.status;
        this.shiftName = data.shiftName;
        for (let mod in data.centreStatusList) {
            var moderator = data.centreStatusList[mod]
            this.centreStatusList = moderator.status
            this.moderatorView = true;

            for (let sup in moderator.hallStatusList) {
                var Supervisor = moderator.hallStatusList[sup]
                this.hallStatusList = Supervisor.status;
                this.SupervisorView = true;
                if (this.hallStatusList == "INCOMPLETE") {
                    break;
                }
            }
        }
    }
    this.Shift.push({ shiftStatusList: this.shiftStatusList, shiftName: this.shiftName, centreStatusList: this.centreStatusList, hallStatusList: this.hallStatusList });
}

A: Assign your shift variable to an empty array like below.
Shift: any[] = [];


text:
Q: Multiple levels of have_many in a model I am working with Ruby on Rails (specifically the ActiveRecord) and I am trying to decide whether or not it is a good idea to link my models using multiple levels.
class Student < ActiveRecord::Base
  has_many :student_sections
  has_many :sections, :through => :student_sections
  has_many :courses, :through => :sections
end

It seems like this would work, but I don't have a lot of experience in ActiveRecord. Is there any reason not to do this?

A: This is fine but you should bear in mind that the courses association is effectively only a 'get' association (as opposed to 'get and set').  What i mean by that is that you can say
@student.courses
(after doing neo's fix) to get a list of courses, but you can't do
@student.courses << @course
as rails doesn't have the section info required to make the necessary joins between the student and the course.

A: you need to add :source attribute
has_many :sections, :through => :student_sections, :source => 'your_source'


text:
Q: Difference between the sums of even digits and odd digits in a number I am trying to find the difference between the sum of the even digits and odd digits in a number. My code only works for just one case which is 412 but it doesnt work for numbers such as 23 and 1203.
I dont know why. Here is my code
def digitS(n):
    even = 0
    odd = 0
    while (n!=0):
        for i in range(n):
            if i % 2 == 0:
                even = even + (n%10)
            else:
                odd = odd + (n%10)
            n//=10

    return even - odd
n = 412
print(digitS(n))

A: It is kinda obscure to me, that you want to find the difference between odd and even digits or the difference between odd and even positions?
BTW, I assumed you want to count the former -- your code implementing the latter with some issues in designing.
def digit(n):
   even = 0
   odd = 0
   while (n != 0):
       r = n % 10
       if r % 2 == 0:
          even = even + r
       else:
          odd = odd + r
       n //= 10

   return even - odd

n = 412
print(digit(int(n)))

and a more concise response with the aid of strings!
def digit(n):
   even = [int(i) if int(i) % 2 == 0 else 0 for i in str(n)]
   odd = [int(i) if int(i) % 2 else 0 for i in str(n)]
   return sum(even) - sum(odd)

A: I've made some edits to your code below. What you have attempted is perfectly right, but the for loop is an obstruction and should be removed. Also, from what I understood, you wanted the difference between the odd and even digit sums. For that, you must return the absolute value of even - odd.
def digits(n):
    even = 0
    odd = 0

    while (n!=0):
        if n % 2 == 0:
            even += (n%10)
        else:
            odd += (n%10)
        n //= 10

    return abs(even - odd)

print(digits(412)) # 5
print(digits(23)) # 1

A: Just discard for loop.
def digitS(n):
    even = 0
    odd = 0
    while (n!=0):
        if n % 2 == 0:
            even += (n%10)
        else:
            odd += (n%10)
        n//=10

return even - odd
n = 412
print(digitS(n))

A: I think that you don't need for in 5th line, as you only want to iterate digits instead of whole range of numbers. So for example if number is 1203 you want to check 1, 2, 0 and 3, instead of 0, 1, 2, 3 ... 1201, 1202. Also checking digits is already handled in while(n!=0): n//=10, so for isn't needed.

A: Turn your input to a string, iterate over the elements one by one, check if they are odd or even by turning them to integers et Voila!
def digit(n):
    even = 0
    odd = 0
    string = str(n)
    for i in string:
        if int(i) % 2 == 0:
            even += int(i)
        else:
            odd += int(i)
    return even - odd
n = 282
print(digit(n)) #12

A: I'm not sure what the for loop is meant to do. But here's an example of what you could do instead. Discard the for loop and go through each digit until n == 0.
def digit(n):
    even = 0 # Sum of even numbers
    odd = 0 # Sum of odd numbers
    while (n!=0):
        digit = n%10 # Get the right most digit of the number
        if digit % 2 == 0: # Check if the digit is even or odd
            even = even + digit
        else:
            odd = odd + digit
        n//=10 # Remove the digit from the number

    return even - odd
n = 412
print(digit(n))


text:
Q: Computers are restarting spontaneously and simultaneously, how do I find the cause? I have two computers that spontaneously shut down and rebooted (this happened more than once), both are identical hardware and were installed from the same image (CentOS 5). They are controlling some equipment, and each shutdown is a significant annoyance and waste of money.
The logs don't give any clue, I can only determine that it is not a clean restart, but behaves like a spontaneous loss of power. There is no entry at all that is typical for a controlled shutdown as initiated by init 0 or init 6, just the entries typical for booting the computer. The computers also don't go out completely, but they boot again.
I'm reasonably certain that it is not a human intervening, though I can't be absolutely certain. A power loss or fluctuation is also unlikely as the computers are the only equipment affected each time, and they are also in different parts of the building. There are no cronjobs executing at the time of the shutdowns.
I'm now trying to find out if it is a hardware defect, or a software-initiated problem. But from what I know, a kernel panic should not restart the computer but leave the panic message on the screen.
Which kind of software errors could cause the computer to spontaneously restart without leaving an entry in the logs about the shutdown?
Where should I look to further isolate the problem?

A: My first suspect would be the PSU. If you are not certain it's plenty powerful already, then try one which supports higher power output. Second I would try a different OS install to see if it could be triggered by software.


text:
Q: How to tag an element and use this tag or id later I am building a website and currently, I will display a Card element for any topics I am pulling from the BE.
The BE will send me a Json with id, title, description of each element and for each element I will render a card defined like below:
import React from 'react';
import BlueButton from '../materialdesign/BlueButton'
import TextContents from '../../assets/translations/TextContents';

class ClassCard extends React.Component {

    render() {
        return(

{this.props.title}

{this.props.desc}

                <BlueButton textSize="18" link_href="/" text={TextContents.BookBtn} />

        );
    }
}

export default ClassCard;

For now, I am calling the class as below:

 Test Categories

            <ClassCard title={title1} desc={desc1} pic={Salad} id='123456789'></ClassCard>

id is hard coded for now in order to test it but later it will be replaced by the id pull from the JSON.
What I am looking to do is to pass this id to the ClassCard and then when I click on the Button defined in the ClassCard it redirects you to something like href='/details?id='123456789'.
Then when the details page open, I extract the param id and get the number and can pull the data of this specific id
Any idea?
Regards

A: You can listen onClick event and then you can set window.location.href for the redirect.
handleOnClick(e) {
   window.location.href = `/details?id=${this.props.id}`  // redirect to /details?id=123456789
}

A: You can pass it as a prop!
In your card, just add this into the href.
import React from 'react';
import BlueButton from '../materialdesign/BlueButton'
import TextContents from '../../assets/translations/TextContents';

class ClassCard extends React.Component {

    render() {
        return(

{this.props.title}

{this.props.desc}

                <BlueButton textSize="18" link_href={`/details?id=${this.props.id}`} text={TextContents.BookBtn} />

        );
    }
}

export default ClassCard;

This is grabbing the id, and creating the string that you wanted, Assuming the button component handles it.
Then pass the id's into the card, as you were:

 Test Categories

  <ClassCard title={title1} desc={desc1} pic={Salad} id='123456789'></ClassCard>


text:
Q: Can't CONNECT to Postgresql after upgrading from 8.1? Why can't my users connect to their normal Postgresql databases after upgrading from 8.1 to 8.4? Was a permission lost in the upgrade?

A: The CONNECT privilege was added in Postgresql 8.2 so it is not present in backups from earlier versions. You need to GRANT it after the upgrade like so:
GRANT CONNECT ON DATABASE foo TO bar;


text:
Q: convert database of ruby on rails app from sql server to mysql i had clone a ruby on rails app with sql server, with some code like :
# Gemfile
gem 'tiny_tds'
gem 'activerecord-sqlserver-adapter', '~> 4.2.0'

and database.yml
default: &default
  adapter: sqlserver
  azure: true

development: &development
  <<: *default
  host:     <%= ENV['DATABASE_HOST'] %>
  database: <%= ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_USER'] %>
  password: <%= ENV['DATABASE_PASS'] %>

development_vehicle: &development_vehicle
  <<: *default
  host:     <%= ENV['DATABASE_VEHICLE_HOST'] || ENV['DATABASE_HOST'] %>
  database: <%= ENV['DATABASE_VEHICLE_NAME'] || ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_VEHICLE_USER'] || ENV['DATABASE_USER'] %>
  password: <%= ENV['DATABASE_VEHICLE_PASS'] || ENV['DATABASE_PASS'] %>

development_aspnet: &development_aspnet
  <<: *default
  host:     <%= ENV['DATABASE_ASPNETDB_HOST'] || ENV['DATABASE_HOST'] %>
  database: <%= ENV['DATABASE_ASPNETDB_NAME'] || ENV['DATABASE_NAME'] %>
  username: <%= ENV['DATABASE_ASPNETDB_USER'] || ENV['DATABASE_USER'] %>
  password: <%= ENV['DATABASE_ASPNETDB_PASS'] || ENV['DATABASE_PASS'] %>

db folder like :

but my local use mysql, so i want to use mysql instead to sql server to buil this app
can you help me to convert it ?
thanks!

A: Gemfile
# gem 'tiny_tds'
# gem 'activerecord-sqlserver-adapter', '~> 4.2.0'
gem 'mysql2'

config/database.yml
default: &default
  adapter: mysql2
  pool: 5
  timeout: 5000
  username : root #mysql username
  password : root #mysql password

development:
  <<: *default
  database: db_name

test:
  <<: *default
  database: db_name

production:
  <<: *default
  database: db_name

A: Add mysql2 gem and remove other connection gem required for sql server.
# Gemfile
# gem 'tiny_tds'
# gem 'activerecord-sqlserver-adapter', '~> 4.2.0'
gem 'mysql2'

database.yml
default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  socket: /tmp/mysql.sock

development: &development
  <<: *default
  host:     yourhostfordevelopement # commonly localhost
  database: yourdb # for development
  username: dbusername # commonly root
  password: dbpasseord # password you configured

development_vehicle: &development_vehicle
  <<: *default
  host:     yourhostfordevelopement # commonly localhost
  database: yourdb # for development_vehicle
  username: dbusername # commonly root
  password: dbpasseord # password you configured

development_aspnet: &development_aspnet
  <<: *default
  host:     yourhostfordevelopement # commonly localhost
  database: yourdb # for development_aspnet
  username: dbusername # commonly root
  password: dbpasseord # password you configured


text:
Q: SQLite FullText Index search on 2 terms with AND & OR I have created a Full Text Index and can search terms like this:
SELECT * FROM mytable where myfield MATCH 'Food'

How do I add an AND clause to return records with the word FOOD and DOG ?
I've tried this:
SELECT * FROM mytable where myfield MATCH 'Food' and  myfield MATCH 'Dog'

A: Read the documentation:
SELECT * FROM mytable WHERE myfield MATCH 'Food Dog'


text:
Q: How can a capacitor in a disposable camera shock you? The battery in a disposable camera is usually a single 1.5V AA battery.  It charges a large capacitor.  When the capacitor is fully charged, it will contain a voltage very close to 1.5V correct?
If one was to touch the charged capacitor, it will shock them.  Why is this?  Surely 1.5V can't do that kind of damage, right?

A: Photoflash capacitors are charged to hundreds of volts using various methods (flyback transformer, etc). Don't assume that because the input is a AA battery that there are no greater potentials within the circuit.
The example below was taken from a Texas Instruments application note. This circuit is battery powered yet charges a capacitor to 300V.


text:
Q: Why does python specify IPv4 or IPv6 with SOCK_STREAM or SOCK_DGRAM when it also accepts `proto` in the instantiation of socket objects? Why does python specify IPv4 or IPv6 with SOCK_STREAM or SOCK_DGRAM when it also accepts protocol number arguments in the instantiation of the socket object (nrs 4 and 41 ,see  list of protocol numbers)? (as proto in socket.socket([family[, type[, proto]]])) Doesn't that make the family argument useless?

A: Nope.  Number 4 and 41 in protocol list you linked to clearly state "IPv4 encapsulation" and "IPv6 encapsulation"  You would use IPv4 with IPV6 encapsulation for example to generate packet which are then de-capsulated (unless that's not actually a word) upstream e.g. at an IPv6 over IPv4 tunnel

A: proto in this context refers to the Layer 4 (L4) protocol to use. Most likely this will be IPPROTO_TCP (TCP) or IPPROTO_UDP (UDP). In practice it's unlikely you will need to pass these parameters explicitly very often, as for IP generally SOCK_STREAM implies TCP and SOCK_DGRAM implies UDP.
It could come in handy for instance, however, if say you wanted to implement ICMP support in your program using raw sockets. Then you'd pass SOCK_RAW and IPPROTO_ICMP. Also, keep in mind this is based on the Berkeley sockets API which is designed to handle much more than just IP networking (take a look at all the other AF_* from the socket module to get an idea of what it supports).
In contrast, IPv4/IPv6 is a Layer 3 (L3) protocol and works independently from TCP/UDP.
EDIT:
As to why you see IPv4/IPv6 encapsulation in that list, it's to support protocols like IP in IP or 6in4.  It's not likely you will deal directly with these mechanisms in your program.


text:
Q: How to read buffer object byte by byte in JS Is it possible to read buffer line by line in JS?
I currently have a JS buffer object.
If i do console.log(buff) it will print something like this
<Buffer 0c 00 00 00 99 4e 98 3a f0 9d 09 3b 00 00 00 00 68 48 12 3c f0 77 1f 4a 6c 6c 0a 4a 0f 32 5f 31 31 39 38 36 31 5f 31 33 33 39 33 39 40 fc 11 00 09 00 ... 336 more bytes>

I am wondering if there is a way in Javascript to read this like a stream. I know in python for instance I can read the buffer like a stream byte byte.. something like (below)
buff.read(1)
0c
buff.read(2)
00 00
buff.read(4)
00 99 4e 98

A: I am not sure what your use case is but Buffer implements Uint8Array which effectively makes it iterable. So you can get the values like this
const buffer = Buffer.from("This is string");

for (const b of buffer) {
  console.log(b);
}

You could also consider creating a read function which can do similar thing for you
function read(size) {
  return buffer.slice(0, size);
}

You can use it like this
read(3);

You could also use buffer.keys(), buffer.values() and buffer.entries() to get keys, values and key value respectively using these functions.
Hope this helps.

A: The Buffer documentation shows that Buffer has a subarray method (and also a slice method), either of which can be used directly or to implement a utility method to do this.
Using it directly:
let n = 0;
buff.slice(n, n += 1);
// [0c]
buff.slice(n, n += 2);
// [00, 00]
buff.slice(n, n += 4);
// [00, 99, 4e, 98]

You could encapsulate that into a function if you don't want to keep track of n.


text:
Q: How to estimate model predicted means per group from a GEE model fitted in R? This question is related to a similar post: How can I estimate model predicted means (a.k.a. marginal means, lsmeans, or EM means) from a GEE model fitted in R?
The difference is that I do not only fit categorical predictors but also continuous. This problem could also be a pure coding issue but I would like to use this question to cross-validate my approach as well. Hence, my problem is twofold.

Part 1
First, I fitted a GEE for longitudinal data with multiple observations per ID. In R I use the geepack::geeglm function and update my model with all possible corstr except for "userdefined". Following this post: QIC or QICu for variable selection in GEE-GLM variable selection I compute the QIC of every model and choose the model with the lowest QIC.
Is this a valid approach of selecting a GEE model?

Part 2
Second, and most important to me: I have fitted a GEE using the approach above. Explanatory variables are one categorical variable (i.e. treatment 1/0 [yes/no]) and one continues (between 0 and 1).
Fitting the model is no problem. But now I want to find the estimated mean per group (that is per treatment group).
To calculate the estimated means I am using emmeans::emmeans()because this also returns both LCL and UCL. What I don't understand is: why does emmeans()is using the overall observed mean instead of the group mean?  How can I make sure to compute the estimated group mean (including LCL/UCL)?
I tried to make a minimal reproducible example below. Hope someone can help.
library("geepack")
library("emmeans")
library("dplyr")
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

# Extending to pigs data to create a fourth variable representing the
#treatment group
pigs.extended <- pigs %>% mutate(trt = c(rep("a", 20), rep("b", 9)))

# The observed means for percent by treatment group
pigs.extended %>% group_by(trt) %>% summarise(mean = mean(percent))
#> # A tibble: 2 x 2
#>   trt    mean
#>   <chr> <dbl>
#> 1 a      13.2
#> 2 b      12.3

# The overall mean (wihtout grouping)
pigs.extended %>% summarise(mean = mean(percent))
#>       mean
#> 1 12.93103

# A simple example model
model <- geepack::geeglm(conc ~ percent + trt, id = source, data = pigs.extended)
model
#>
#> Call:
#> geepack::geeglm(formula = conc ~ percent + trt, data = pigs.extended,
#>     id = source)
#>
#> Coefficients:
#> (Intercept)     percent        trtb
#>   20.498948    1.049322   10.703857
#>
#> Degrees of Freedom: 29 Total (i.e. Null);  26 Residual
#>
#> Scale Link:                   identity
#> Estimated Scale Parameters:  [1] 36.67949
#>
#> Correlation:  Structure = independence
#> Number of clusters:   3   Maximum cluster size: 10

# Estimating (overall) mean with emmeans
emmeans(model, "percent")
#>  percent emmean   SE  df asymp.LCL asymp.UCL
#>     12.9   39.4 1.65 Inf      36.2      42.6
#>
#> Results are averaged over the levels of: trt
#> Covariance estimate used: vbeta
#> Confidence level used: 0.95

# why is the percent mean for each group 12.9 and not 13.2 and 12.3?
emmeans(model, "percent", by = "trt")
#> trt = a:
#>  percent emmean    SE  df asymp.LCL asymp.UCL
#>     12.9   34.1 3.252 Inf      27.7      40.4
#>
#> trt = b:
#>  percent emmean    SE  df asymp.LCL asymp.UCL
#>     12.9   44.8 0.327 Inf      44.1      45.4
#>
#> Covariance estimate used: vbeta
#> Confidence level used: 0.95

Created on 2019-02-07 by the reprex
package (v0.2.0).


text:
Q: What type of USB flash disk can be used to boot externally I have a Sandisk Cruzer Switch 8GB on which I have the win10 media creation tool. My computer is running windows 7 professional and I have the Gigabyte Dual Bios and MicroATX motherboard from Gigabyte. I have an intel core duo 2.0. So I attempt to boot from my external device. On startup, I hit F12 to enter that menu. None of them correspond to my USB (I tried them all they all startup normally), and I know that first of all my usb is somehow incompatible. I tried to install the media creation tool on it and it says this type of usb is incompatible. So I just copy it from a friend's usb (which is a fancy warship-shaped usb with no specifications at all from the back) and so when i try to boot from that it does not work.
Short question: What types of usb are compatible with installing OS on them?

A: So I found the following solution after some search: SanDisk Cruzer Switches are a bit of a different architecture. So the computer reads them not as removable storage, but as an external hard-drive. That's why, the media creation tool will never detect them. After that I used any CD RW instead of my USB. By the way, some other USB's don't work as well, like this one which I can't find its model number.


text:
Q: bigquery storage API: Is it possible to stream / save AVRO files directly to Google Cloud Storage? I would like to export a 90 TB BigQuery table to Google Cloud Storage. According to the documentation, BigQuery Storage API (beta) should be the way to go due to export size quotas (e.g., ExtractBytesPerDay) associated with other methods.
The table is date-partitioned, with each partition occupying ~300 GB. I have a Python AI Notebook running on GCP, which runs partitions (in parallel) through this script adapted from the docs.
from google.cloud import bigquery_storage_v1

client = bigquery_storage_v1.BigQueryReadClient()

table = "projects/{}/datasets/{}/tables/{}".format(
    "bigquery-public-data", "usa_names", "usa_1910_current"
) # I am using my private table instead of this one.

requested_session = bigquery_storage_v1.types.ReadSession()
requested_session.table = table
requested_session.data_format = bigquery_storage_v1.enums.DataFormat.AVRO

parent = "projects/{}".format(project_id)
session = client.create_read_session(
    parent,
    requested_session,
    max_stream_count=1,
)
reader = client.read_rows(session.streams[0].name)

# The read stream contains blocks of Avro-encoded bytes. The rows() method
# uses the fastavro library to parse these blocks as an iterable of Python
# dictionaries.

rows = reader.rows(session)

Is it possible to save data from the stream directly to Google Cloud Storage?
I tried saving tables as AVRO files to my AI instance using fastavro and later uploading them to GCS using Blob.upload_from_filename(), but this process is very slow. I was hoping it would be possible to point the stream at my GCS bucket. I experimented with Blob.upload_from_file, but couldn't figure it out.
I cannot decode the whole stream to memory and use Blob.upload_from_string because I don't have over ~300 GB of RAM.
I spent the last two days parsing GCP documentation, but couldn't find anything, so I would appreciate your help, preferably with a code snippet, if at all possible. (If working with another file format is easier, I am all for it.)
Thank you!

A:
Is it possible to save data from the stream directly to Google Cloud Storage?

By itself, the BigQuery Storage API is not capable of writing directly to GCS; you'll need to pair the API with code to parse the data, write it to local storage, and subsequently upload to GCS. This could be code that you write manually, or code from a framework of some kind.
It looks like the code snippet that you've shared processes each partition in a single-threaded fashion, which caps your throughput at the throughput of a single read stream. The storage API is designed to achieve high throughput through parallelism, so it's meant to be used with a parallel processing framework such as Google Cloud Dataflow or Apache Spark. If you'd like to use Dataflow, there's a Google-provided template you can start from; for Spark, you can use the code snippets that David has already shared.

A: An easy way to that would be to use Spark with the the spark-bigquery-connector? It uses the BigQuery Storage API in order to read the table directly into a Spark's DataFrame. You can create a Spark cluster on Dataproc, which is located as the same data centers as BigQuery and GCS, making the read and write speeds much faster.
A code example will look like this:
df = spark.read.format("bigquery") \
  .option("table", "bigquery-public-data.usa_names.usa_1910_current") \
  .load()

df.write.format("avro").save("gs://bucket/path")

You can also filter the data and work on each partition separately:
df = spark.read.format("bigquery") \
  .option("table", "bigquery-public-data.usa_names.usa_1910_current") \
  .option("filter", "the_date='2020-05-12'") \
  .load()

# OR, in case you don't need to give the partition at load

df = spark.read.format("bigquery") \
  .option("table", "bigquery-public-data.usa_names.usa_1910_current") \
  .load()

df.where("the_date='2020-05-12'").write....

Please note that in order to read large amounts of data you would need a sufficiently large cluster.


text:
Q: CaliburnMicro Action does not fire inside data template I want to create some sort of filter, when user clicks the filter button from the app bar it will fire up a popup page with list picker in it. I've googled and tried quite a number of solutions but still cannot get it to work.
Here are my codes:
XAML (MainPageView.xaml)
<phone:PhoneApplicationPage.Resources>
      <DataTemplate x:Key="PivotContentTemplate">
            <phone:Pivot Margin="-12,0,0,0" Title="FOREX NEWS" Height="672">
                <phone:PivotItem Header="filter" FontFamily="{StaticResource PhoneFontFamilySemiLight}" FontSize="32">
                    <StackPanel Margin="12,0,0,0">
                        <toolkit:ListPicker Header="currencies" SelectionMode="Multiple"
                                            micro:Message.Attach="[Event SelectionChanged] = [Action OnCurrenciesChanged($eventArgs)]">
                            <sys:String>gbp</sys:String>
                            <sys:String>eur</sys:String>
                            <sys:String>usd</sys:String>
                        </toolkit:ListPicker>
                    </StackPanel>
                </phone:PivotItem>
            </phone:Pivot>
        </DataTemplate>
<phone:PhoneApplicationPage.Resources>

...
Still inside MainPageView.xaml
<bab:BindableAppBar Grid.Row="2" Mode="Minimized">
    <bab:BindableAppBarButton micro:Message.Attach="[Event Click] = [Action ShowFilter($view, $eventArgs]">

    </bab:BindableAppBarButton>
</bab:BindableAppBar>

MainPageViewModel.cs
public void ShowFilter(object sender, RoutedEventArgs e)
{
    var view= sender as MainPageView;

    CustomMessageBox messageBox = new CustomMessageBox()
    {
        ContentTemplate = (DataTemplate)view.Resources["PivotContentTemplate"],
        LeftButtonContent = "filter",
        RightButtonContent = "cancel",
        IsFullScreen = true // Pivots should always be full-screen.
    };

    messageBox.Dismissed += (s1, e1) =>
    {
        switch (e1.Result)
        {
            case CustomMessageBoxResult.LeftButton:
                // Do something.
                break;
            case CustomMessageBoxResult.RightButton:
                // Do something.
                break;
            case CustomMessageBoxResult.None:
                // Do something.
                break;
            default:
                break;
        }
    };

    messageBox.Show();
}

public void OnCurrenciesChanged(SelectionChangedEventArgs e)
{

}

For your information, I am using Caliburn.Micro and WP Toolkit for the CustomMessageBox and ListPicker.
I received exception No target found for method OnCurrenciesChanged. I only receive the exception when I after I select few items in the list picker and click any of the buttons to save the change. Another thing is that the OnCurrenciesChanged does not get triggered at all.
I think (based on what I read so far) whenever the CustomMessageBox get called, the datacontext its operating at is no longer pointing to the MainPageViewModel thus it could not find the method. But I am not sure how to actually do this.
More details:
Exception happen after I click the left button (checkmark)

Updates
So far I have try the following:
<StackPanel Margin="12,0,0,0" DataContext="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"> //also tried with Self

and I also added this when I instantiate messageBox
        var messageBox = new CustomMessageBox()
        {
            ContentTemplate = (DataTemplate)view.Resources["PivotContentTemplate"],
            DataContext = view.DataContext, // added this
            LeftButtonContent = "filter",
            RightButtonContent = "cancel",
            IsFullScreen = true
        };

The idea is that when the messsagebox is created, the datacontext will be the same as when the view is instantiated. However, it seems that the datacontext does not get inherited by the PickerList

A: Ok so I managed to get this to work. The solution is not pretty and I think it beats the purpose of MVVM at the first place.
Based on http://wp.qmatteoq.com/first-steps-in-caliburn-micro-with-windows-phone-8-how-to-manage-different-datacontext/ , inside a template the DataContext will be different. So, I need to somehow tell ListPicker to use the correct DataContext.
The solution provided by link above doesn't work for me. I think it is because when ListPicker is called inside CustomMessageBox, MainPageViewModel is no longer available or it seems not to be able to find it as suggested by the exception. So as per above code example in the question, even if I set the correct DataContext to the CustomMessageBox, it does not get inherited somehow by the ListPicker.
Here is my solution:
     var messageBox = new CustomMessageBox()
        {
            Name = "FilterCustomMessageBox", // added this
            ContentTemplate = (DataTemplate)view.Resources["PivotContentTemplate"],
            DataContext = view.DataContext,
            LeftButtonContent = "filter",
            RightButtonContent = "cancel",
            IsFullScreen = true
        };

In the XAML, I edited to this
            <toolkit:ListPicker Header="currencies" SelectionMode="Multiple"
                                micro:Action.TargetWithoutContext="{Binding ElementName=FilterCustomMessageBox, Path=DataContext}"
                                micro:Message.Attach="[Event SelectionChanged] = [Action OnCurrenciesChanged($eventArgs)]">

It's ugly because both ViewModel and View need to explicitly know the Name. In WPF, you can just do something like this in the binding to inherit the DataContext of the parent/etc but this is not available for WP.
{Binding DataContext, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}}

If anyone has better workaround, do let me know!


text:
Q: Determine When File No Longer In Use Without Using Process Events Is there a way to determine when a File is no longer in use other than using a Process.Exited(){} event and testing whether the file is locked? Is there a pattern or certain commands we are not using that will handle this better?
Currently, we create the file in the user's temp folder, launch the file in its default program (determined by file extension), then have the file updated if there were changes and deleted after closing.
This works fine for ALL single file launches.
However, we run into an issue when a second, or more, file(s) are opened in certain programs, like Gimp, Word, or Paint.net. They open the file and then pass the files Handle off to the existing process, closing the initial process that was created as the filing process below. Since the original process (file process) closes, the Exited event fires prematurely.
If you place the code below into the Program.cs of a console app project and change the path and file name to an existing file. You can run it and the file should open in its default viewer/editor. A default program may need to be chosen.
We tested this with Word and GIMP to make sure this works. Make sure all WinWord processes(or whatever process for the program that is set as default for the file you decide to test) are closed and run the program with a breakpoint in the exited event. You will notice that it only hits once the program closes and the file is not locked.
However, If you have a word document, or any of the other programs mentioned above, open and then run the program you will notice the Exited event fires immediately after opening the document. In the case of Word Documents, the file is locked, but for GIMP the file is not locked. So, simply determining if the file is locked or not when the process exits are not enough.
So, if it is the only process running, or if it is a program that keeps the process we created, there is no issue. Programs like NotePad keep the process that opens each file and the Exited event fires as expected.
Is there a better way to handle this?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ExampleConsole
{
    class Program
    {
        List<FileSystemWatcher> FileWatchers { get; set; } = new List<FileSystemWatcher>();

        static public bool IsFileChanged { get; set; }
        //replace the following with whatever file you prefer, but GIMP, Word, Paint.Net, and FoxIt PDF Editor
        //are what we have noticed using a single manager processes rather than the process that ran when opening the file.
        static string fileName = "source.gif";
        static string myTempFile = Path.Combine(Path.GetTempPath() + fileName);

        [STAThread]
        static void Main()
        {
            Process fileProcess = Process.Start(new ProcessStartInfo(myTempFile)
            {
                UseShellExecute = true,
                CreateNoWindow = true
            });

            fileProcess.EnableRaisingEvents = true;

            //This is where the issue occurs launching more than 1 Gimp/Word/FoxIt PDF Editor,
            //the "Exited" Event runs when the process that opened the file closes after handing off to a manager process
            fileProcess.Exited += (o, args) =>
            {
                if (CheckFileLock(myTempFile))
                {
                    MessageBox.Show("File is locked.");
                }
                else
                {
                    MessageBox.Show("File is not locked.");
                }
                //If the process exits, we read the changes into memory and save to our database.
                if (IsFileChanged)
                {
                    MessageBox.Show("File would be saved.");
                }

                fileProcess?.Dispose();
            };
#if DEBUG
            try
            {
                //...
            }
            finally
            {
                Console.WriteLine("Press enter to close...");
                Console.ReadLine();
            }
#endif

        }

        public static bool CheckFileLock(string filePath)
        {
            try
            {
                using (File.Open(filePath, FileMode.Open)) { }
            }
            catch (IOException e)
            {
                var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);

                return errorCode == 32 || errorCode == 33;
            }

            return false;
        }
    }
}


text:
Q: How to use readonly property across multiple classes I have created a read-only property(name) in class1. How can I use this name property in class2?
Public Class Class1
ReadOnly Property name() As String
    Get

        Return System.IO.path.GetFileName("C:\Demo\Sample1")

    End Get
End Property

Can I directly carry this name variable value into class2? Need suggestion.

A: You can access this property everywhere where you have a reference to a Object of type Class1. So if your Class2 objects have a reference, they can use it.
For example:
Class Class2
    Property cls1 As New Class1

    Function getClass1Name() As String
        Return cls1.Name
    End Function
End Class

Another option is to make the property shared, because it's a value that is independent of any instance of Class1 that makes sense.
Then you can access it without an instance of Class1 via the class-name:
Class Class1
    Public Shared ReadOnly Property Name As String
        Get
            Return System.IO.Path.GetFileName("C:\Demo\Sample1")
        End Get
    End Property
End Class

Class Class2
    Function getClass1Name() As String
        Return Class1.Name
    End Function
End Class

A: Your Readonly property is still an instance members and cannot be shared without instantiating Class1 and looking at the property definition, it can be Shared. You can make your property Shared and use it in class2
Public Class Class1
Shared Property name() As String
    Get

        Return System.IO.path.GetFileName("C:\Demo\Sample1")

    End Get
End Property

and in class2, you can call
Dim class1Name = Class1.name

A: Via an instance of Class1
    Public Class Class2

      Sub New()
            Dim o As New Class1
            Dim s As String  = o.Name

      End Sub

   End Class

Here is something to read on classes.


text:
Q: Derivation of another equation of a sphere In this post: calculating volume of sphere with integration, the OP states that the equation of a sphere is $\sqrt{a^2 - x^2 - y^2}$. I already know that the equation of a circle is $(x-a)^2 + (y-b)^2$, and a sphere's equation similarly is $(x-a)^2 + (y-b)^2 + (z-c)^2$.
How do you derive the equation $\sqrt {a^2 - x^2 - y^2}$ from $(x-a)^2 + (y-b)^2 + (z-c)^2$?
I would appreciate it if you gave me some starting points for this proof, and not a full solution.

A: If the sphere is centered on the origin, you can ignore the constant terms you give as $a,~ b,~ c$ since they will all be 0. Then you are left with
$$x^2 + y^2 + z^2 = r^2 \\
z^2 = r^2-x^2-y^2 \\
z = \pm\sqrt{r^2-x^2-y^2}$$
And that person simply used $a$ instead of $r$.


text:
Q: PHP does not display on HTML page I'm trying to make a dropdown list of genres that a user can select and then view all the series in that genre. Here is my HTML code

Select a Genre to View

<form id="form1" method="post" action="view_process.php">

<?php include("dropdown.php"); ?>

<input style="display:none" type="submit" id="sub"/>
</form>

And then here is my PHP for the drop down:
<?php
require_once 'login_sec217.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password,
$db_database);
if (!$db_server) die("Unable to connect to MySQL: " .
mysqli_error($db_server));

$query = "SELECT genre_name FROM genres;";
$results = mysqli_query($db_server, $query);
if(!$results)
die("Query Error: "  . mysqli_error($db_server));
else {
echo "<select id=\"opt\" name=\"name\"onchange=\"showButton()\">";
echo "<option value=\"none\">please select</option>";
while($row=mysqli_fetch_assoc($results))
{
foreach($row as $key=>$value) ${$key}=$value;
echo "<option value=\"&genre_name\">$genre_name</option>";
}
echo "</select>";
}
?>

and for my table of the results:
<?php
foreach($_POST as $key=>$value) ${key}=$value;
require_once 'login_sec217.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password,
$db_database);
if (!$db_server) die("Unable to connect to MySQL: " .
mysqli_error($db_server));
$query = "SELECT s.series_title, s.series_author_last, s.series_author_first
FROM series s INNER JOIN
genrelink.l ON s.series_id = l.series_id INNER JOIN genres g ON g.genre_id =
l.genre_id WHERE g.genre_name
= '$name';";
$result = mysqli_query($db_server,$query);
?>

Title
Author Last Name
Author First Name

<?php
$row = mysqli_fetch_row($result);
echo "$row[0]	";
echo "$row[1]	";
echo "$row[2]	";
?>

The PHP seems to operate perfectly standing alone, but when I put them on the webpage...nothing appears. The database is connecting but something with the insertion into the HTML page is screwing with this? Any thoughts would be awesome.

A: change your code like this

<input type="checkbox" name="genre[]" value="1" />Action
<input type="checkbox" name="genre[]" value="2" />Adventure

<input type="checkbox" name="genre[]" value="3" />Comedy
<input type="checkbox" name="genre[]" value="4" />Coming of Age

<input type="checkbox" name="genre[]" value="5" />Dark fantasy
<input type="checkbox" name="genre[]" value="6" />Drama

<input type="checkbox" name="genre[]" value="7" />Fantasy


text:
Q: How to read a file in SML line by line I want to write a function that reads a text file line by line. ie, read the first line until EOL and then treat this as a string, and repeat this until the text ends.
I have managed only this much till now:
fun read file =
let val is = TextIO.openIn file
in
end

A: You can use TextIO.inputLine : instream -> string option for this. Using refs you can do something like
let
  val stream = TextIO.openIn file
  val done = ref false
in
  while not (!done) do
    case TextIO.inputLine stream of
      SOME s => print s
    | NONE => done := true
end

You can also use the functions in TextIO.StreamIO.


text:
Q: Copy data from Parquet file to a table in Azure Synapse by using Polybase T-SQL failing when using a partition column I tried to copy a parquet file to a table in Azure Synapse by using Polybase T-SQL. Here is an example:
data = [["Jean", 15, "Tennis"], ["Jane", 20, "Yoga"], ["Linda", 35, "Yoga"], ["Linda", 35, "Tennis"]]
columns = ["Name", "Age", "Sport"]
df = spark.createDataFrame(data, columns)

Then I save the  dataframe as a parquet file by partitioning by the column "Sport":
df\
.write\
.option("header", True)\
.partitionBy("Sport")\
.format("parquet")\
.mode("overwrite")\
.save("/mnt/test_partition_polybase.parquet")

Then I use Polybase T-SQL for copying from a parquet file to a table in Synapse:
IF OBJECT_ID(N'EVENTSTORE.TEST') IS NOT NULL BEGIN DROP EXTERNAL TABLE EVENTSTORE.TEST END
CREATE EXTERNAL TABLE EVENTSTORE.TEST(
    [Name] NVARCHAR(250),
    [Age] BIGINT,
    [SPORT] NVARCHAR(250)
    )
 WITH (DATA_SOURCE = [my_data_source],LOCATION = N'test_partition_polybase.parquet',FILE_FORMAT = [SynapseParquetFormat],REJECT_TYPE = VALUE,REJECT_VALUE = 0)

I get the error:

External file access failed due to internal error: 'File
test_partition_polybase.parquet/Sport=Tennis/part-00000-tid-5109481329839379912-631db0ad-cd52-4f9e-acf6-76828a8aa4eb-67-1.c000.snappy.parquet:
HdfsBridge::CreateRecordReader - Unexpected error encountered creating
the record reader: HadoopExecutionException: Column count mismatch.
Source file has 2 columns, external table definition has 3 columns

It's because the partitioned column "Sport" is not in the partitioned file. How can I solve this issue?

A: I finally solved my problem by creating a duplicated column:
df\
.withColumn("part_Sport", F.col("Sport"))\
.write\
.option("header", True)\
.partitionBy("part_Sport")\
.format("parquet")\
.mode("overwrite")\
.save("/mnt/test_partition_polybase.parquet")

I don't know if it is the best solution but that's the only one I have found.


text:
Q: How to filter RecycleView Using Kotlin I'm new to the Kotlin programing language and Dealing with the recyclerView is kinda hard to understand so I have used Groupie Library, But there is no enough documentation or tutorials on how to deal with this library.
coming straight to the point I have a recycler view contains data that I added to the adapter, and I want to filter that data using the searchView, I don't know how to get the list or the Text out of that groupAdapter or the items that inside of them to perform filter.
here is the XML Layout of my Fragment
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.SearchFragment"
    android:background="@color/backgroundGray">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            android:id="@+id/include4"
            layout="@layout/fragment_search_toolbar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycleview_search"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:divider="@null"
            android:background="@color/backgroundGray"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/include4"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:listitem="@layout/search_row"/>

    </androidx.constraintlayout.widget.ConstraintLayout>

</FrameLayout>

seachView XML Layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.SearchView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/searchView"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginBottom="10dp"
    app:queryHint="Looking For Stores.."
    app:iconifiedByDefault="false"
    android:layoutDirection="rtl"
    android:clickable="true"
    android:elevation="4dp"
    android:gravity="end"
    app:queryBackground="@null"
    android:textAlignment="textEnd"
    tools:ignore="KeyboardInaccessibleWidget,UnusedAttribute"
    android:background="@drawable/searchview_background">

</androidx.appcompat.widget.SearchView>

and this is my Fragment Class
class SearchFragment : Fragment() {

    lateinit var searchView: android.widget.SearchView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_search, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        searchView = view.findViewById(R.id.searchView)
        val adapter = GroupAdapter<GroupieViewHolder>()
        recycleview_search.adapter = StoresItems()

        adapter.add(Stores(R.drawable.ic_kfc, "KFC", 15.581010, 32.569032))
        adapter.add(Stores(R.drawable.ic_pizzahut, "Pizza Hut", 15.581050, 32.569002))
        adapter.add(Stores(R.drawable.ic_dominos, "Dominos Pizza", 15.581560, 32.512002))

        adapter.setOnItemClickListener { item, view ->
            val storesItem = item as Stores
            val  intent = Intent(view.context, OrderActivity::class.java)

            intent.putExtra("storename", storesItem.storename)
            startActivity(intent)
        }

        searchView.setOnCloseListener(object: SearchView.OnQueryTextListener,
            SearchView.OnCloseListener {
            override fun onQueryTextSubmit(p0: String?): Boolean {
               return false
            }

            override fun onQueryTextChange(p0: String?): Boolean {
                return false
            }
       })
    }

}
 class Stores(val img: Int, val storename: String , val latitude: Double, val longitude: Double) : Item<GroupieViewHolder>() {
        override fun getLayout(): Int {
            return R.layout.search_row
        }

        override fun bind(viewHolder: GroupieViewHolder, position: Int) {

            viewHolder.itemView.storeName.text = storename
            viewHolder.itemView.storeImage.setImageResource(img)
        }
    }

A: Let's look at it from another point of view:
The concept is, you have a List<Things> that your RecyclerView/Adapter show.
You produce a keyword (search) that should reduce that list. How you filter this list, where you filter it, where you store it, etc. is (and should be) irrelevant to the RecyclerView/Adapter.
Their responsibilities are different (recycle views for performance reasons, and adapt/bind them to "Views" respectively), not search/filter a list. You haven't posted your Adapter code, but in essence:
When you submit a search query, you "filter" the list in any way you see fit, producing a new list with the filtered results, and pass this onto the adapter. The adapter will then calculate what needs to be done to display the new list.
Bonus points if you use a ListAdapter<T, K> which implements a DiffUtil.ItemCallback since that means you can do adapter.submitList(newFilteredList), sit back, and relax.
In other words, separate the responsibilities, searching, filtering is not part of the adapter/recyclerview.


text:
Q: C++ Any advice on tracking down Access Violations? I've been having issues trying to track down an Access Violation in my program.  It occurs when the destructor is called for the third time, exactly when the destructor appears to finish.
I've spent hours trying to track this down so I'm looking for further advice on things I can do.  I'm creating the class instance with new and delete operators.  The Visual Studio output window shows:
First-chance exception at 0x60e3ad84 (msvcp100d.dll) in WebCollationAgent.exe: 0xC0000005: Access violation writing location 0xabababab.
Unhandled exception at 0x60e3ad84 (msvcp100d.dll) in WebCollationAgent.exe: 0xC0000005: Access violation writing location 0xabababab.
Is there anything I can do to try and find out what was in those memory locations?
The call stack window shows the following (in reverse order as I've pasted it in to chronological order, earliest to latest):
Program.exe!Network::`scalar deleting destructor'()  + 0x2b bytes   C++

Program.exe!std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >::~basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >()  Line 754 + 0xf bytes    C++

Program.exe!std::_String_val<wchar_t,std::allocator<wchar_t> >::~_String_val<wchar_t,std::allocator<wchar_t> >()  Line 478 + 0xb bytes  C++

msvcp100d.dll!std::_Container_base12::_Orphan_all()  Line 214 + 0x5 bytes   C++

My best guess at this information is that there's some sort of string variable causing the issue?  Does anyone have any advice on interpreting this information?
Any other pieces of advice would also be useful, thanks in advance.
I'm coding under Windows 7 and using Visual Studio 2010 Professional.

A: I've had success tracking memory bugs before using BoundsChecker (now part of Borland DevPartner). There are a number of similar products that might also help: HeapAgent, and Rational Purify. These seem to be much like ValGrind, but work on Windows.
Here are 3 open source alternatives that might assist:

*

*DUMA (by the looks of it, you'll have to build it for Windows yourself, but the README contains some notes on doing that)

*XMEM

*elephant
I have no idea how these perform, but they sound very promising, and look like they all work on Windows in one way or another.
This Microsoft page on managing memory errors might also help, and also has links to setting Memory breakpoints, which might help you find out when your data is first being deleted or altered. Good luck!

A: Use the Microsoft Heap Debugging stuff and hope yours is one of the cases for which it was designed.  Purify would be the next step after that.
It's built into Visual Studio and is helpful in some cases.  If it works it sure beats giving IBM two or three pockets full of cash for Purify.
You can find the info here
TL;DR
In main, do this

int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
// Turn On (OR) - Keep freed memory blocks in the
// heap's linked list and mark them as freed
tmpFlag |= _CRTDBG_DELAY_FREE_MEM_DF;

// Turn on memory checking at each heap operation
tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF;

// Set the new state for the flag
_CrtSetDbgFlag( tmpFlag );

You can toggle the _CRTDBG_CHECK_ALWAYS_DF flag at different places if it runs too slow.  However, I'd run it a few times with each heap op checked in order to get a feel for where the problem occurs.

A: I wrote this blog with some tips
http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/02/06/6-_2200_Pointers_2200_-on-Debugging-Unmanaged-Code.aspx
The main thing you need to do is to get the crash or exception to happen while the code with the bug is still on the stack.  A lot of times you get Access Violation some time after the code with the bug has executed and returned and it may actually be a long time later (in computer time).  In that case, it's almost impossible to figure it out.
In your case, with the problem flagged in delete, it's a strong indicator that the heap is corrupt, and two common reasons in C++ are double-delete and mixing up array deletion (using delete when you should use delete[] or the other way around).
If you can reproduce it with simple code, I would look for the two problems above.  Otherwise, download the Microsoft Debugging Tools and use gflags +hpa -i program.exe to make the heap much more sensitive to corruption (it will report the error much more quickly).


text:
Q: How to assign an integer value to an imageView in Android Studio? I am creating a feedback app where a user has to click one of the 5 imageViews (1-5 rating) based on his/her experience. My primary aim is to extract the integer value of this rating from the imageView click and push it to a SQLite database.
I am trying to use setTag() and getTag() but to no avail. Any help would be much appreciated. Thanks in advance.
activity_main.xml -
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="99dp"
        android:layout_marginLeft="99dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="172dp"
        android:layout_marginRight="172dp"
        android:layout_marginBottom="151dp"
        android:text="Name"
        android:textSize="22sp"
        app:layout_constraintBottom_toTopOf="@+id/imageView1"
        app:layout_constraintEnd_toStartOf="@+id/editTextPersonName"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextPersonName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="172dp"
        android:layout_marginLeft="172dp"
        android:layout_marginTop="54dp"
        android:ems="10"
        android:hint="Full Name"
        android:inputType="textPersonName"
        app:layout_constraintStart_toEndOf="@+id/textViewName"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="92dp"
        android:layout_height="103dp"
        android:layout_marginStart="35dp"
        android:layout_marginLeft="35dp"
        android:layout_marginTop="151dp"
        android:layout_marginEnd="47dp"
        android:layout_marginRight="47dp"
        android:tag="1"
        app:layout_constraintEnd_toStartOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textViewName"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="92dp"
        android:layout_height="103dp"
        android:layout_marginStart="60dp"
        android:layout_marginLeft="60dp"
        android:layout_marginBottom="64dp"
        android:tag="4"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView3"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/imageView5"
        android:layout_width="92dp"
        android:layout_height="103dp"
        android:layout_marginStart="46dp"
        android:layout_marginLeft="46dp"
        android:layout_marginEnd="40dp"
        android:layout_marginRight="40dp"
        android:layout_marginBottom="64dp"
        android:tag="5"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.833"
        app:layout_constraintStart_toEndOf="@+id/imageView4"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="92dp"
        android:layout_height="103dp"
        android:layout_marginStart="48dp"
        android:layout_marginLeft="48dp"
        android:layout_marginBottom="63dp"
        android:tag="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView1"
        tools:srcCompat="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="92dp"
        android:layout_height="103dp"
        android:layout_marginStart="53dp"
        android:layout_marginLeft="53dp"
        android:layout_marginTop="80dp"
        android:layout_marginEnd="49dp"
        android:layout_marginRight="49dp"
        android:tag="3"
        app:layout_constraintEnd_toStartOf="@+id/imageView4"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="333dp"
        android:layout_marginLeft="333dp"
        android:layout_marginTop="41dp"
        android:layout_marginEnd="340dp"
        android:layout_marginRight="340dp"
        android:layout_marginBottom="75dp"
        android:text="Were you satisfied with our hygiene standards?"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/imageView3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextPersonName" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java -
public class MainActivity extends AppCompatActivity {

    EditText name;
    ImageView oneStar;
    ImageView twoStar;
    ImageView threeStar;
    ImageView fourStar;
    ImageView fiveStar;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText) findViewById(R.id.editTextPersonName);
        oneStar = (ImageView) findViewById(R.id.imageView1);
        oneStar.setTag(1);
        oneStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = name.getText().toString()+"\n";
                Toast.makeText(MainActivity.this, (Integer) oneStar.getTag(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

A: Try to replace oneStar.getTag() with view.getTag()

A: If you want to get the tag, and display it as a Toast message, the instead of casting it into an Integer object convert it to String using .toString method.

A: Second parameter of Toast.makeText is interger, but you can't pass any integer. It must be the resource Id of a string (R.string.your_string). Remove "(Integer)" and it should solve your problem.
I don't know exactly what are your requirements and in case you missed it, there is a build in rating barin Android. You can check the tutorial here

A: it is less code and less error prone if you just add this to ImageView: android:onClick="imageViewClick", and create a handler in MainActivity like this:
        public void imageViewClick(View view) {
            String username = name.getText().toString()+"\n";
            Toast.makeText(MainActivity.this, (Integer)view.getTag(),Toast.LENGTH_SHORT).show();
        }


text:
Q: Android app freezing and causing ANR I am getting ANR on my application and it freezes the app, when I pulled out anr/traces.txt I see the ANR is thrown by this:
InputDispatcher" prio=10 tid=22 MONITOR
     | group="main" sCount=1 dsCount=0 obj=0x41b49f78 self=0x5f584d98
     | sysTid=547 nice=-8 sched=0/0 cgrp=[fopen-error:2] handle=1599621384
     | state=S schedstat=( 0 0 0 ) utm=42 stm=86 core=0
     at    com.android.server.am.ActivityManagerService.inputDispatchingTimedOut(ActivityManagerService.java:~8670)
  - waiting to lock <0x419b0d38> (a com.android.server.am.ActivityManagerService) held by tid=8 (Binder_1)
  at com.android.server.am.ActivityRecord.keyDispatchingTimedOut(ActivityRecord.java:968)
  at com.android.server.am.ActivityRecord$Token.keyDispatchingTimedOut(ActivityRecord.java:310)
  at com.android.server.wm.InputMonitor.notifyANR(InputMonitor.java:132)
  at com.android.server.input.InputManagerService.notifyANR(InputManagerService.java:1297)
  at dalvik.system.NativeStart.run(Native Method)

How do I fix this issue.


text:
Q: Friends and nested classes Ok I'm totally frazzled on this. Code is begin to swim around the screen...must sleep.
So! Ok, troubled by nested classes and friends.
here is the pseudo-code
   class A{
     public:
          //constructor
          // member functions
     private:
          class B{
          //private
          int a();
          };

          class C{
          //private
          int b();
          };
   };

So once an object of type A has been created, I would like it to access a() and b(). I know that I have to use a friend function for this. So where should I put friend class A. Is that the right expression?.

A: If you would like to access a() and b() from within class A you need to place the friend declaration inside of class B and class C. However, a() and b() are not members of class A so you cannot access them in the way you are thinking. Instead you also need to add forwarding functions to A.
class A
{
public:
    //constructor
    // member functions
private:
    class B
    {
        //private
        int a();

        friend A;    // <-- make A a friend
    };

    class C
    {
        //private
        int b();

        friend A;    // <-- make A a friend
    };

public:

    // forwarding function for a
    int a()
    {
        return bdata_.a();
    }

    // forwarding function for b
    int b()
    {
        return cdata_.b();
    }

private:
    B bdata_;
    C cdata_;
};