text:
Q: How can I bind Foreground to a property in my ViewModel? I would like to bind the foreground property of a TextBlock to a Property in my ViewModel.
This doesn't work :
Edit
View :
TextBlock
Text="{Binding Path=FullName, Mode=OneWay}"
Foreground="{Binding Path=ForegroundColor}"
Margin="0 5 3 5"

Code behind:
CustomerHeaderViewModel customerHeaderViewModel = new CustomerHeaderViewModel();
customerHeaderViewModel.LoadCustomers();
CustomerHeaderView.DataContext = customerHeaderViewModel;

View Model:
private System.Windows.Media.Brush _foregroundColor;
_foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

public System.Windows.Media.Brush ForegroundColor
{
    get { return _foregroundColor; }
    set { _foregroundColor = value;
        OnPropertyChanged("ForegroundColor");
    }
}

public CustomerHeaderViewModel()
{
ForegroundColor = System.Windows.Media.Brushes.Red;
}

All other properties (Text etc) correctly bind.
What am I doing wrong?

A: This is not a good practice to put UI elements in your view model. Your view model must only encapsulate business locig.
If you want to change the color of anything in your UI that depends on on the value of your textbox, it's a better practice to use data triggers in XAML.
You can do like this :
Viewmodel :
public class MainVm : INotifyPropertyChanged
{
    protected void OnPropertyChanged(string porpName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(porpName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    public string FullName
    {
        get { return "Hello world"; }
    }
}

XAML (Edited to use the color picker, assuming the selected value of his control is named "SelectedValue" and that it returns a Brush object)
    <Grid>
    <TextBlock Text="{Binding Path=FullName, Mode=OneWay}"
               Margin="0 5 3 5" Foreground="{Binding ElementName=colorpicker, Path=SelectedValue}"/>
    <ColorPicker x:Name="colorpicker"/>
</Grid>

A: Check if your solution is like that:
View:
<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:vm="clr-namespace:WpfApplication13"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:MainVM/>
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding Path=FullName, Mode=OneWay}"
                   Foreground="{Binding Path=ForegroundColor}"
                   Margin="0 5 3 5"/>
    </Grid>
</Window>

ViewModel:
public class MainVM : INotifyPropertyChanged
{
    protected void OnPropertyChanged(string porpName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(porpName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private System.Windows.Media.Brush _foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

    public string FullName
    {
        get
        {
            return "Hello world";
        }
    }

    public System.Windows.Media.Brush ForegroundColor
    {
        get { return _foregroundColor; }
        set
        {
            _foregroundColor = value;
            OnPropertyChanged("ForegroundColor");
        }
    }
}

and remember that if you want to set new value for ForegroundColor in VM you sholud do it like that:
ForegroundColor = System.Windows.Media.Brushes.Red;

to raise PropertyChangedEvent
Accordind to new information about your problem, you could try this solution:
CustomerHeaderViewModel.cs
class CustomerHeaderViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Customer> Customers { get; set; }

    public void LoadCustomers()
    {
        ObservableCollection<Customer> customers = new ObservableCollection<Customer>();

        //this is where you would actually call your service
        customers.Add(new Customer { FirstName = "Jim", LastName = "Smith", NumberOfContracts = 23 });
        customers.Add(new Customer { FirstName = "Jane", LastName = "Smith", NumberOfContracts = 22 });
        customers.Add(new Customer { FirstName = "John", LastName = "Tester", NumberOfContracts = 33 });
        customers.Add(new Customer { FirstName = "Robert", LastName = "Smith", NumberOfContracts = 2 });
        customers.Add(new Customer { FirstName = "Hank", LastName = "Jobs", NumberOfContracts = 5 });

        Customers = customers;
    }
    protected void OnPropertyChanged(string porpName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp(this, new PropertyChangedEventArgs(porpName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private System.Windows.Media.Brush _foregroundColor = System.Windows.Media.Brushes.DarkSeaGreen;

    public System.Windows.Media.Brush ForegroundColor
    {
        get { return _foregroundColor; }
        set
        {
            _foregroundColor = value;
            OnPropertyChanged("ForegroundColor");
        }
    }
}

CustomerHeaderView.xaml
<UserControl x:Class="TestMvvm444.Views.CustomerHeaderView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="main">
    <Grid>
        <StackPanel HorizontalAlignment="Left">
            <ItemsControl ItemsSource="{Binding Path=Customers}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Orientation="Horizontal">
                                <TextBox
                                Text="{Binding Path=FirstName, Mode=TwoWay}"
                                Width="100"
                                Margin="3 5 3 5"/>
                                <TextBox
                                Text="{Binding Path=LastName, Mode=TwoWay}"
                                Width="100"
                                Margin="0 5 3 5"/>
                                <TextBlock
                                Text="{Binding Path=FullName, Mode=OneWay}"
                                Foreground="{Binding ElementName=main, Path=DataContext.ForegroundColor}"
                                Margin="0 5 3 5"/>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </Grid>
</UserControl>

In presented scenario the ForegroundColor property resides in CustomerHeaderViewModel.cs so it is value for all customers. In CustomerHeaderView.xaml I added x:Name for UserControl to have a possiblity to refer to DataContext of this element. If you don't want to use x:Name for UserControl, you can try this:
<TextBlock
    Text="{Binding Path=FullName, Mode=OneWay}"
    Foreground="{Binding RelativeSource={RelativeSource FindAncestor,
    AncestorType={x:Type UserControl}}, Path=DataContext.ForegroundColor}"
    Margin="0 5 3 5"/>

Remember that DataContext of this control was set earlier in MainWindow.cs.
MainWindow.cs
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        CustomerHeaderViewModel customerHeaderViewModel = new CustomerHeaderViewModel();
        customerHeaderViewModel.LoadCustomers();
        CustomerHeaderView.DataContext = customerHeaderViewModel;
    }
}


text:
Q: How can I give a user input into terminal after running a terminal command in python? I have a python script that runs a command in terminal using the subprocess module and this command runs another script that asks for a user input. How can I give a user input to terminal from my original python script?
Example:
contents of introduction.sh below
#!/bin/bash
**# Ask the user for their name**
echo Hello, who am I talking to?
read varname
echo It\'s nice to meet you $varname

running introduction.sh would output the following:
user@bash ./introduction.sh
Hello, who am I talking to?
Ryan
It's nice to meet you Ryan

My python script runs introduction.sh in terminal perfectly fine. What I can't figure out how to do is to run introduction.sh with a name such as Ryan as a user input all from my python script.
I tried using the os module to call introduction.sh and then using os again to give the user input as two separate lines. This strategy runs introduction.sh perfectly fine but treats my second input as an undefined variable and does nothing.
My current script testing.py is below.
import subprocess

subprocess.run(["python3", "testing.py"], shell=True, capture_output=True)
subprocess.run(["Ryan"], shell=True, capture_output=True)
print('done')

A: There are a number of ways of doing this with the subprocess package.  Here's a simple way to do so:
import subprocess

process = subprocess.Popen('/tmp/introduction.sh', stdin=subprocess.PIPE)
process.communicate("George".encode())

Result:
Hello, who am I talking to?
It's nice to meet you George

redpajama_set_name: RedPajamaStackExchange


text:
Q: Post optimization needed after deleting rows in a MYSQL Database I have a log table that is currently 10GB. It has a lot of data for the past 2 years, and I really feel at this point I don't need so much in there. Am I wrong to assume it is not good to have years of data in a table (a smaller table is better)?
My tables all have an engine of MYISAM.
I would like to delete all data of 2014 and 2015, and soon i'll do 2016, but i'm concerned about after I run the DELETE statement, what exactly will happen. I understand because it's ISAM there is a lock that will occur where no writing can take place? I would probably delete data by the month, and do it late at night, to minimize this as it's a production DB.
My prime interest, specifically, is this: should I take some sort of action after this deletion? Do I need to manually tell MYSQL to do anything to my table, or is MYSQL going to do all the housekeeping itself, reclaiming everything, reindexing, and ultimately optimizing my table after the 400,000k records I'll be deleting.
Thanks everyone!

A: Plan A:  Use a time-series PARTITIONing of the table so that future deletions are 'instantaneous' because of DROP PARTITION.  More discussion here .  Partitioning only works if you will be deleting all rows older than X.
Plan B:  To avoid lengthy locking, chunk the deletes.  See here .  This is optionally followed by an OPTIMIZE TABLE to reclaim space.
Plan C:  Simply copy over what you want to keep, then abandon the rest.  This is especially good if you need to preserve only a small proportion of the table.
CREATE TABLE new LIKE real;
INSERT INTO new
    SELECT * FROM real
        WHERE ... ;  -- just the newer rows;
RENAME TABLE real TO old, new TO real;   -- instantaneous and atomic
DROP TABLE old;    -- after verifying that all went well.

Note:  The .MYD file contains the data; it will never shrink.  Deletes will leave holes in it.  Further inserts (and opdates) will use the holes in preference to growing the table.  Plans A and C (but not B) will avoid the holes, and truly free up space.

A: Tim and e4c5 have given some good recommendations and I urge them to add their answers.
You can run OPTIMIZE TABLE after doing the deletes. Optimize table will help you with a few things (taken from the docs):

*

*If the table has deleted or split rows, repair the table.

*If the index pages are not sorted, sort them.

*If the table's statistics are not up to date (and the repair could not be accomplished by sorting the index), update them.

According to the docs: http://dev.mysql.com/doc/refman/5.7/en/optimize-table.html

Use OPTIMIZE TABLE in these cases, depending on the type of table:
...
After deleting a large part of a MyISAM or ARCHIVE table, or making
  many changes to a MyISAM or ARCHIVE table with variable-length rows
  (tables that have VARCHAR, VARBINARY, BLOB, or TEXT columns). Deleted
  rows are maintained in a linked list and subsequent INSERT operations
  reuse old row positions. You can use OPTIMIZE TABLE to reclaim the
  unused space and to defragment the data file. After extensive changes
  to a table, this statement may also improve performance of statements
  that use the table, sometimes significantly.


text:
Q: Find all user-installed packages Is there any way to get a list of all user-installed packages on an Ubuntu system, i.e. the packages that were installed on top of the default installed packages?
(The idea is to get a comprehensive list that can be used to install the same packages on a clean Ubuntu installation)

A: Based on the information above, I wrote a short Python script to list packages that were manually installed. See this link.
Feel free to use it although I assume no responsibility for it.
However, feedback and suggestions are always welcome.

A: Check my answer here to a related question: How can I display the list of all packages installed on my Debian system?. Some of the other answers on the question also contain nice suggestions on getting such a list.
This question should be marked a duplicate since the earlier question also covers this question, but it might be useful to have this question stand on its own so it's easier to find.

A: Look at these files,

*

*'/var/log/installer/initial-status.gz' -- your primary installation

*

*this file date would be your installation date (i think)

*'/var/log/dpkg.log' update timeline (this is what you want)

*'/var/log/apt/term.log' -- things apt updated on your system

*'/var/cache/apt/archives/' will contain the deb packages downloaded for installation

Update: use the following two steps for exact list of new installs:

*

*execute: grep -w install /var/log/dpkg.log > full-list.log

*Look at lines beyond the /var/log/installer/initial-status.gz timestamp

Since you want to get a clean installation on another system with these packages, you could even copy the 'deb' files from the 'cache/apt/archives' path to that of the new installation and get them installed in one shot (without downloading them again).

A: Just for grins, I put together a one-liner (here split for clarity) that figures out packages manually installed, excluding those installed initially and any packages automatically installed:
comm -13 \
  <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort) \
  <(comm -23 \
    <(dpkg-query -W -f='${Package}\n' | sed 1d | sort) \
    <(apt-mark showauto | sort) \
  )

This works both in bash and in zsh.

A: This is a hack-job, but it completely works.
First, go to http://releases.ubuntu.com/maverick/ (or whatever version of Ubuntu you're using) and grab the *.manifest file that is associated with the version of Ubuntu you're using.
Then, run the following script (replacing <manifest file>, angle brackets and all, with the path to the file you downloaded. You can always append > output to the end to make a file dump.
diff --suppress-common-lines <(sed 's/ .*//' <manifest file>) <(dpkg --get-selections | sed 's/[ \t].*//') | grep '>' | sed 's/[>] //'

A: Thanks geekosaur, nice code. I used it but it took a while to figure out how to get it working. Here's how I did it in Ubuntu 11.10—it works in the bash terminal:
comm -13 \
  <(gzip -dc /var/log/installer/initial-status.gz | sed -n 's/^Package: //p' | sort) \
  <(comm -23 \
    <(dpkg-query -W -f='${Package}\n' | sed 1d | sort) \
    <(apt-mark showauto | sort) \
  ) > user-installed-packages

Then to add a tab—\t—and install on each line:
sed 's/$/\tinstall/' user-installed-packages >uip

Then on the new machine:
sudo dpkg --set-selections < uip

And to install the packages:
sudo apt-get dselect-upgrade

A: assuming you have a consistent history and use aptitude:
history | grep -e "^.....  aptitude install"
would list only the packages which you installed with aptitude install ... duh

A: Another way to do this is by determining what has been installed based on your "tasks" which determine the base packages to install according to your initial needs.
tasksel --list-tasks

At the very least you'd have server.  However, you may choose to have more.  For each of those tasks you have installed, you can get a list of packages that are installed the following command does it all in one line (broken down for clarity) for the ones I have chosen in my installation:
(tasksel --task-packages server ; \
 tasksel --task-packages openssh-server ; \
 tasksel --task-packages lamp-server) | sort | uniq

A generic approach to the above would be:
(for a in $( tasksel --list-tasks | grep "^i" | awk '{ print $2 }' ) ; \
 do tasksel --task-packages $a; done) | sort | uniq

Now use apt-cache depends --installed -i --recurse <packagename> | grep -v "^ " to get a list of dependencies used by all the packages defined in the task.  This can be done in one line as follows
apt-cache depends --installed -i --recurse \
     $(for a in $( tasksel --list-tasks | \
                   grep "^i" | \
                   awk '{ print $2 }' ) ; \
       do tasksel --task-packages $a; done) | grep -v "^ " | sort | uniq

The following lists all the packages that are installed in your system (not including dependencies).
dpkg --get-selections | grep "[[:space:]]install" | awk '{print $1}'

Now use the comm command to find the ones that are in the second list only (i.e. ignore those that are in both files and just the first file)
comm -13 <(apt-cache depends --installed -i --recurse \
              $(for a in $( tasksel --list-tasks | \
                            grep "^i" | \
                            awk '{ print $2 }' ) ; \
                do tasksel --task-packages $a; done) | grep -v "^ " | sort ) \
         <( dpkg --get-selections | grep "[[:space:]]install" | \
            awk '{print $1}' | sort)


text:
Q: Downloading and saving data with fetch() from authenticated REST I have a React app working with a REST backend built in Python and Flask.  I'm downloading data from a database and saving it as a CSV file through the browser.  I have this working.  What I don't understand, however, is why I had to go beyond the sources I've been reading and mash stuff up to get this to work.  Why haven't I found this outlined better?
Some say all I have to do is set the response header with mimetype and Content-Disposition: attachment; filename=something.csv:

*

*In python using Flask, how can I write out an object for download?

*http://code.stephenmorley.org/php/creating-downloadable-csv-files/

*http://www.jtricks.com/bits/content_disposition.html
Yet, this, alone, was only working with plain links, and not with fetch() and authentication, so I had to go looking for ways to save client data to disk such as this:

*

*Using HTML5/Javascript to generate and save a file
So, my question is either:

*

*Why do I have to do it this way?, or

*What am I missing -- what is the easier way?
It appears that the answer to the first question is that I can't modify request headers (to add the auth token) except through XHR type work.  This appears to be answered (non-answered, really) here:

*

*Adding custom HTTP headers using JavaScript
And, that for some reason, responses to XHR with Content-Disposition: attachment are meaningless.  Is that true?  Is there not a more intrinsic way to manage requests like this in modern browsers?
I feel like I don't understand this enough and that bugs me.
Anyhow, here is the working code I am looking to simplify, if possible:
JS (React):
// https://stackoverflow.com/a/18197511/680464
download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
downloadReport(studyID) {
    fetch(`/api/admin/studies/${studyID}/csv`
    ,   {
            headers: {
                "Authorization": "Bearer " + this.props.authAPI.getToken()
            ,   "Accept": "text/csv"
            }
        }
    )
    .then(this.checkStatus.bind(this))
    .then((response) => response.text())
    .then((responseText) => this.download(`study${studyID}.csv`, responseText))
    .catch((error) => {
        console.error(this.props.location.pathname, error)
    })
}

Python (Flask):
@app.route("/api/admin/studies/<int:study_id>/csv", methods=["GET"])
@admin.login_required
def admin_get_csv(study_id):

    test = [("1","2","3"),("4","5","6")]
    def generate():
        for row in test:
            yield ",".join(row) + "\n"

    return Response(
                generate()
            ,   mimetype="text/csv"
            ,   headers={"Content-Disposition": "attachment; filename=study{0}.csv".format(study_id)}
            )

A: I was forced to come back to this because we just ran into the 2MB limit in Chrome.  Who knew?  (This person, for one: https://craignicol.wordpress.com/2016/07/19/excellent-export-and-the-chrome-url-limit/ posted a couple months after my question here, and whose solution I implemented below.)
Anyhow, I will now attempt to answer my own questions since I have not seen an acceptable answer yet regarding the requested authentication requirement.  (Although, Conrado did provide some useful links otherwise to that requirement.)
As to the questions of: Why I have to do it this way and is there not a more intrinsic way?  The answers appear to be "just because" and "no" respectively.  Not very good answers, I know.  I wish I could explain it more... but I really can't without sticking my foot in my mouth somewhere.  I'm not a network expert and certainly not the right person to explain it.  It just is what it is from what I read.  You just can't fake a stream as a file download while authenticating.
As to: What I am missing and what is the easier way?  Well, there is no easier way.  Sure, I could throw more libraries like FileSaver.js at the code base and let them hide some of this code for me.  But, I don't like a larger tool set than I really need (I'm looking at you, you ridiculous 50MB sites).  I could accomplish the same thing as those libraries by hiding my download() function elsewhere and importing it.  No, that is not easier from my point of view.  Less work maybe to grab a prebuilt function, but not easier in terms of amount of code executed to make a download happen.  Sorry.
But... I was missing something: that thing that led to that 2MB limit in Chrome.  At the time, I didn't really understand how this URI data hack was working that I was using.  I found some code that worked, and used it.  I get it now -- now that I've had more time to read deeper on that part of the problem.  In short, I was missing the blob options versus the URI option.  Sure, blobs have their own limitations with various browsers but, given that my use cases would not have been affected by any of those back in 2016, the blob option would have been a better route to take from the start... and it feels less hacky (and maybe a bit "easier" because of that alone).
Here is my current solution that tries a blob save before falling back to the URI data hack:
JS (React):
saveStreamCSV(filename, text) {
    this.setState({downloadingCSV: false})
    if(window.navigator.msSaveBlob) {
        // IE 10 and later, and Edge.
        var blobObject = new Blob([text], {type: 'text/csv'});
        window.navigator.msSaveBlob(blobObject, filename);
    } else {
        // Everthing else (except old IE).
        // Create a dummy anchor (with a download attribute) to click.
        var anchor = document.createElement('a');
        anchor.download = filename;
        if(window.URL.createObjectURL) {
            // Everything else new.
            var blobObject = new Blob([text], {type: 'text/csv'});
            anchor.href = window.URL.createObjectURL(blobObject);
        } else {
            // Fallback for older browsers (limited to 2MB on post-2010 Chrome).
            // Load up the data into the URI for "download."
            anchor.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(text);
        }
        // Now, click it.
        if (document.createEvent) {
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            anchor.dispatchEvent(event);
        }
        else {
            anchor.click();
        }
    }
}
handleDownloadClick(e) {
    this.setState({downloadingCSV: true})
    fetch(`/api/admin/studies/${this.props.study.id}/csv`
    ,   {
            headers: {
                "Authorization": "Bearer " + this.props.authAPI.getToken()
            ,   "Accept": "text/csv"
            }
        }
    )
    .then((response) => response.text())
    .then((responseText) => this.saveStreamCSV(`study${this.props.study.id}.csv`, responseText))
    .catch((error) => {
        this.setState({downloadingCSV: false})
        console.error("CSV handleDownloadClick:", error)
    })
}

Note: I went this route only because I don't need to worry about all the use cases that FileSaver.js was built for (this is for a feature on the admin app only and not public-facing).

A: In reference to this answer, you can use FileSaver or download.js libraries.
Example:
var saveAs = require('file-saver');

fetch('/download/urf/file', {
  headers: {
    'Content-Type': 'text/csv'
  },
  responseType: 'blob'
}).then(response => response.blob())
  .then(blob => saveAs(blob, 'test.csv'));

A: Tell the browser how to handle your download by using the DOM. Inject the anchor tag with Node.appendChild and let the user click the link.
Download CSV

What you are doing is downloading the file, inserting the already complete request into an anchor tag, and creating a second request by using pom.click() in your code.
Edit: I missed the authorization header. If you like this suggestion, you could put the token in the query string instead.


text:
Q: How to keep a drawn rectangle in the same place as the camera moves around I have this application where a rectangle is drawn in the initial frame. I wanted to know if it is possible to make the rectangle a part of the image from the next frame onwards.
For example in my first frame I would draw something like this but a bit darker
http://imgur.com/zACIiHJ
I want it to become a part of the environment, so that the next time my camera accesses that frame I should see a rectangular box. How to do this using OpenCV?
Edit: My algorithm finds and draws the rectangle in the first frame. I'm trying to keep the rectangle in the same place as the camera moves around and the rectangle need not be always on the white board.

A: What what you are trying to achieve is possible, but its going to take some research and work on your part. One possible solution to your problem is to use Optical Flow (http://en.wikipedia.org/wiki/Optical_flow) analysis to monitor the apparent motion of objects in your cameras view. You could use the resulting optical flow field to apply a "correction" to the positions of the corners of your rectangle between each frame. Here is a link to the OpenCV documentation for their optical flow functions:
http://docs.opencv.org/modules/gpu/doc/video.html
If the particular device you are using has a gyroscope, and gps/ins you might also use this data to supplement the optical flow data. Let me know how it goes, sounds like a really fun project!

A: You need a static rectangle that has nothing to do with what is in the image? Just draw a rectangle on every frame you capture.
    Rect r = Rect( .. );
    rectangle( imageFromCam, r, Scalar( .. ) );

cv::rectangle( )
Rect


text:
Q: ANDROID a layout contains multiple MultiSelectionSpinner I have a xml layout which is having 2 to 3 multiple selection spinner. I have one submit button too.
Then my doubt is how can i get the selected values for each spinner . And the i have to save these values too . So how can i get the selected values. And how can i came to know which is spinner that the user selected , I am able to  get the selected value on public void selectedStrings(List strings) but how i can differentiate which values are for my 1st spinner and for 2nd spinner and 3rd spinner. Do you have any idea..?
My code
    public class DashBoardOne  extends Fragment implements MultiSelectionSpinner.OnMultipleItemsSelectedListener{
         MultiSelectionSpinner multiSelectionSpinnerIndustry,multiSelectionSpinnerLocation;
         List<String> arrayIndustry,arrayLocation;
         Button BtnSubmitAspiration;
        public DashBoardOne() {
            arrayIndustry = new ArrayList<String>();
        }

        public static DashBoardOne newInstance(String text) {
            DashBoardOne dashBoardOne = null;
             // some code
            return dashBoardOne;
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view= inflater.inflate(R.layout.fragment_dashboard, container, false);

            multiSelectionSpinnerIndustry = (MultiSelectionSpinner) view.findViewById(R.id.SpinnerIndustry);
            arrayIndustry=db.fillIndustrySpinner(); // gettting the list for first spinner from db
            arrayLocation=db.fillLocationSpinner();  // gettting the list for 2nd spinner from db

            multiSelectionSpinnerIndustry.setItems(arrayIndustry); //first spinner
            multiSelectionSpinnerIndustry.setListener(this);

            multiSelectionSpinnerLocation.setItems(arrayLocation); // 2nd spinner
            multiSelectionSpinnerLocation.setListener(this);

            BtnSubmitAspiration=(Button)view.findViewById(R.id.BtnSubmitAspiration);

              BtnSubmitAspiration.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // here i have some code to save the data. How can i get the selected values for my each multiSelectionSpinner ?
                }
            });
    }

     @Override
        public void selectedIndices(List<Integer> indices) {
        }
        @Override
        public void selectedStrings(List<String> strings) {
            Toast.makeText(getActivity().ge

tApplicationContext(),
        strings.toString(), Toast.LENGTH_LONG).show();  // here i am able to get the selected strings,
                                                        //But i dont know how to diffrentiate the current value for which spinner
    }
}

class MultiSelectionSpinner
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class MultiSelectionSpinner extends Spinner implements
        OnMultiChoiceClickListener {

    public interface OnMultipleItemsSelectedListener{
        void selectedIndices(List<Integer> indices);
        void selectedStrings(List<String> strings);
    }
    private OnMultipleItemsSelectedListener listener;

    String[] _items = null;
    boolean[] mSelection = null;
    boolean[] mSelectionAtStart = null;
    String _itemsAtStart = null;

    ArrayAdapter<String> simple_adapter;

    public MultiSelectionSpinner(Context context) {
        super(context);

        simple_adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_spinner_item);
        super.setAdapter(simple_adapter);
    }

    public MultiSelectionSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);

        simple_adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_spinner_item);
        super.setAdapter(simple_adapter);
    }

    public void setListener(OnMultipleItemsSelectedListener listener){
        this.listener = listener;
    }

    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        if (mSelection != null && which < mSelection.length) {
            mSelection[which] = isChecked;
            simple_adapter.clear();
            simple_adapter.add(buildSelectedItemString());
        } else {
            throw new IllegalArgumentException(
                    "Argument 'which' is out of bounds.");
        }
    }

    @Override
    public boolean performClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("Please select!!!");
        builder.setMultiChoiceItems(_items, mSelection, this);
        _itemsAtStart = getSelectedItemsAsString();
        builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                System.arraycopy(mSelection, 0, mSelectionAtStart, 0, mSelection.length);
                listener.selectedIndices(getSelectedIndices());
                listener.selectedStrings(getSelectedStrings());
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                simple_adapter.clear();
                simple_adapter.add(_itemsAtStart);
                System.arraycopy(mSelectionAtStart, 0, mSelection, 0, mSelectionAtStart.length);
            }
        });
        builder.show();
        return true;
    }

    @Override
    public void setAdapter(SpinnerAdapter adapter) {
        throw new RuntimeException(
                "setAdapter is not supported by MultiSelectSpinner.");
    }

    public void setItems(String[] items) {
        _items = items;
        mSelection = new boolean[_items.length];
        mSelectionAtStart = new boolean[_items.length];
        simple_adapter.clear();
        simple_adapter.add(_items[0]);
        Arrays.fill(mSelection, false);
        mSelection[0] = true;
        mSelectionAtStart[0] = true;
    }

    public void setItems(List<String> items) {
        _items = items.toArray(new String[items.size()]);
        mSelection = new boolean[_items.length];
        mSelectionAtStart  = new boolean[_items.length];
        simple_adapter.clear();
        simple_adapter.add(_items[0]);
        Arrays.fill(mSelection, false);
        mSelection[0] = true;
    }

    public void setSelection(String[] selection) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
            mSelectionAtStart[i] = false;
        }
        for (String cell : selection) {
            for (int j = 0; j < _items.length; ++j) {
                if (_items[j].equals(cell)) {
                    mSelection[j] = true;
                    mSelectionAtStart[j] = true;
                }
            }
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public void setSelection(List<String> selection) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
            mSelectionAtStart[i] = false;
        }
        for (String sel : selection) {
            for (int j = 0; j < _items.length; ++j) {
                if (_items[j].equals(sel)) {
                    mSelection[j] = true;
                    mSelectionAtStart[j] = true;
                }
            }
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public void setSelection(int index) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
            mSelectionAtStart[i] = false;
        }
        if (index >= 0 && index < mSelection.length) {
            mSelection[index] = true;
            mSelectionAtStart[index] = true;
        } else {
            throw new IllegalArgumentException("Index " + index
                    + " is out of bounds.");
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public void setSelection(int[] selectedIndices) {
        for (int i = 0; i < mSelection.length; i++) {
            mSelection[i] = false;
            mSelectionAtStart[i] = false;
        }
        for (int index : selectedIndices) {
            if (index >= 0 && index < mSelection.length) {
                mSelection[index] = true;
                mSelectionAtStart[index] = true;
            } else {
                throw new IllegalArgumentException("Index " + index
                        + " is out of bounds.");
            }
        }
        simple_adapter.clear();
        simple_adapter.add(buildSelectedItemString());
    }

    public List<String> getSelectedStrings() {
        List<String> selection = new LinkedList<>();
        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                selection.add(_items[i]);
            }
        }
        return selection;
    }

    public List<Integer> getSelectedIndices() {
        List<Integer> selection = new LinkedList<>();
        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                selection.add(i);
            }
        }
        return selection;
    }

    private String buildSelectedItemString() {
        StringBuilder sb = new StringBuilder();
        boolean foundOne = false;

        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                if (foundOne) {
                    sb.append(", ");
                }
                foundOne = true;

                sb.append(_items[i]);
            }
        }
        return sb.toString();
    }

    public String getSelectedItemsAsString() {
        StringBuilder sb = new StringBuilder();
        boolean foundOne = false;

        for (int i = 0; i < _items.length; ++i) {
            if (mSelection[i]) {
                if (foundOne) {
                    sb.append(", ");
                }
                foundOne = true;
                sb.append(_items[i]);
            }
        }
        return sb.toString();
    }
}

A: You can get selected item for each spinner when button is clicked.Like this
spinner.getSelectedItem().toString();

A: You could set a setOnItemSelectedListener for each spinner and handle items choices on respective arraylists.
Just like that:
Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Good luck.


text:
Q: Why my gradient descent seems to diverge "pair-wise"? Why my gradient descent seems to diverge "pair-wise"?
I've checked the algorithms and they work for golden section line search and "small step parameter".
However, when trying to get the algo to diverge, I notice that the results indicate that the divergence occurs "pair-wise". The components flip on every iteration (although they're not entirely the same, they show slow improvement).

Function is:
$$f(x,y)=x^2+y^2+x+2y$$
Does this have some symmetry that'd explain this?

Reproducing code:
https://pastebin.com/QM4twYLy


text:
Q: Angular session timeout and management Is there any way to manage user session using Angularjs?, I mean::

*

*Session timeout - when system is idle.

*Alerts when session is near to expire with option to resume session.

*Redirect (or any other action) when trying to make a request if session has expired.

Could be Interceptors one good option to solve this problem? Can you provide an example?

A: Try ng-idle. It's simple component where you can set the timeout and warning time before the timeout is reached. Then you can query server for user logout or something similar.
myApp.config(function(IdleProvider, KeepaliveProvider) {
  IdleProvider.idle(900); // 15 min
  IdleProvider.timeout(60);
  KeepaliveProvider.interval(600); // heartbeat every 10 min
  KeepaliveProvider.http('/api/heartbeat'); // URL that makes sure session is alive
});

myApp.run(function($rootScope, Idle) {
  Idle.watch();
  $rootScope.$on('IdleStart', function() { /* Display modal warning or sth */ });
  $rootScope.$on('IdleTimeout', function() { /* Logout user */ });
});

In the above configuration, when user is idle for 900s (does not move mouse, press any key or button etc), warning is being displayed. It will then wait 60s and log out user (send request to a server that possibly destroys server session).
In order to make sure server session does not expire (even if everything user is doing is moving mouse) the Keepalive service will send a request to the server every 10 minutes. This time has to less than server session expiration time.
Checkout the demo.

A: Here are some implementations:
https://github.com/witoldsz/angular-http-auth
https://github.com/angular-app/angular-app/tree/master/client/src/common/security

A: I have been using ng-idle for some time now for below requirement.
Our requirement was when the user is idle for 60 mins. After 55 mins show pop up with the confirmation box saying do you want to continue your session or not(I have used sweet alert).
If the user click on continue then reset the idle time else log out forcefully by calling broadcast method.
Configuration has to be done in app.js when the users log-in inside app.config like below
app.config(['KeepaliveProvider', 'IdleProvider', function (KeepaliveProvider, IdleProvider) {
IdleProvider.idle(TimeOut.firstAPiCall);--It will call Idle On method
IdleProvider.timeout(TimeOut.SessionTimeOut);--It will be called when the total time is (TimeOut.firstAPiCall +TimeOut.SessionTimeOut)
KeepaliveProvider.interval(TimeOut.interval);}]) --It will be called like a heart beat for mentioned timeout until the idle start has not occured.

Below is the code for showing pop-up
   $scope.$on('IdleStart', function () {
    $scope.$broadcast('SessionIdleUpdate', 'IdleStart', TimeOut.FirstApicall);
    $rootScope.idleTimerSession = setTimeout(function () {
        console.log("pop up appeared on : " + new Date())
        $scope.timedout = SweetAlert.swal({
            title: "Alert",
            text: "Your session is about to expire in 5 minutes, Do you want to continue?",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DDDDD",
            confirmButtonText: "CONTINUE",
            cancelButtonText: "No"
        }, function (isConfirm) {
            if (isConfirm) {
                clearTimeout(idleTimer);
            }
            else {
                console.log("pop up closed from confirm on  : " + new Date())
                $scope.$broadcast('SessionTimeOutLogOut', null);
                Idle.unwatch();
                $scope.started = false;
            }
        });

        //This check is to handle idle pop up if it appears and user doesnt perform any action it will simply logout.
        var idleTimer = setTimeout(function () {

            swal.close();
            $scope.$broadcast('SessionTimeOutLogOut', null);
            Idle.unwatch();
            $scope.timedout = null;
        }, (TimeOut.sessionTimeOut) * 1000);
    }, (TimeOut.idleTimeOut - TimeOut.idleCheckDuration) * 1000);-- Time out is added to hold the pop up for that much duration . Because once the idle start is occured you wont be able to call the API

});

Below is the code for handling idle end event:
  $scope.$on('IdleEnd', function () {
        $scope.$broadcast('SessionIdleUpdate', 'IdleEnd', 0));
    clearTimeout($rootScope.idleTimerSession);
    closeModals();
});

Below is the code for Time Out  it will be called after ---(TimeOut.firstAPiCall +TimeOut.SessionTimeOut)
  $scope.$on('IdleTimeout', function (forceLogout) {

        swal.close();
        $scope.$broadcast('SessionTimeOutLogOut', null);
        Idle.unwatch();

});


text:
Q: fetch two rows with one id in linq to sql c# im new to linq to sql. my query is about fetch two more rows with one site number using the search button.There is a link between the tables using foreign key.
Let me clear the database which look like.
Hi,
I have Four tables tbl_user, tbl_Site,tbl_usersite and tbl_credentials.
Table columns:

*

*tbl_Site          : SiteId, SiteName, SiteNumb

*tbl_Credentials   : CredId, Username,Password

*tbl_User          : UserId, CredIdFK, Forename , Surname

*tbl_Usersite      : UsersiteID, Site_IdFK, User_IdFk
Table relationship:

*

*(tbl_Usersite) table is to link the table (tbl_User and tbl_Site)

*In tbl_user table Cred_Id is the FK
Site sample data:
SiteId, SiteName, SiteNumb

*

*10 , XXXX , 1234

*11 , YYYY , 5436

*12 , ZZZZ , 3789

Credentials Sample data:
CredId, Username, Password

*

*10,  google, yahoo

*11,  Blog , Forum

*12,  Date , Time

*13,  Linq , Sql

*14,  Total , Cost

User sample data:
UserId, CredId, Forename, Surname

*

*187 , 10 , Sarah , Thomas

*196 , 11 , Mark , Hill

*195 , 12 , Peter, Hodge

*197 , 13 , Brad , Pitt

*198 , 14 , Brown , Thomas

Usersite sample data:
UsersiteId , SiteId , UserId

*

*1 , 10 , 187

*2 , 10 , 196

*3 , 10 , 195

*4 , 11 , 197

*5 , 12 , 198
The Client Enter the SiteNumber in the textBox and by clicking the search button. They should get Username , Password, UserId, ForeName and Surname. and my sample code in the button click event is
protected void btnsearch_Click(object sender, EventArgs e)
{
     string Site = txtsitenumb.Text;

    SiteDataContext sitenumb = new SiteDataContext();

     try
        {
            var siteID = (from sn in sitenumb.tbl_sites
                       where sn.site_number == Site
                       select sn.site_id_PK).First();

             var UserID = (from sn2 in sitenumb.tbl_usersites
                      **where sn2.usersite_site_id_FK == siteID
                         select  sn2.usersite_user_id_FK).First();**

             // Where the Star Marked area doesnt give the result
                if there is an access for more than one Site for the single User

             var CredID = (from sn3 in sitenumb.tbl_users
                       where sn3.user_id_PK == UserID
                       select sn3.user_credentials_id_FK).First();

            var UserName = (from sn4 in sitenumb.tbl_credentials
                            where sn4.credentials_id_PK == CredID
                            select sn4.credentials_username).First();

            var PassWord = (from sn5 in sitenumb.tbl_credentials
                            where sn5.credentials_id_PK == CredID
                            select sn5.credentials_password).First();

            var FirstName = (from sn6 in sitenumb.tbl_users
                             where sn6.user_id_PK == UserId
                             select sn6.user_forename).First();

            var Lastname = (from sn7 in sitenumb.tbl_users
                            where sn7.user_id_PK == UserId
                            select sn7.user_surname).First();

            fields s = new fields();
            s.UserName = UserName;
            s.Password = PassWord;
            s.UserId = UserID .ToString();
            s.FirstName = FirstName;
            s.LastName = Lastname;

                data.Add(s);
                ViewState["idata"] = data;

                gridview1.DataSource = data;
                gridview1.DataBind();

        }
        catch (Exception)
        {
            Label1.Text = "File Not Found";

        }

  protected void Page_Load(object sender, EventArgs e)
{

        this.Form.DefaultButton = this.btnsearch.UniqueID;

        data = ViewState["idata"] as List<fields>;
        if (data == null)
            data = new List<fields>();

}
[Serializable]
public class fields
{
    public string UserName { get; set; }
    public string Password { get; set; }
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string TimeZone { get; set; }

}

This code works fine if it is Single Site access for Single User. Please help me to display the User associate with all the sites.
** For Example:**
If the user enters SiteNumb 1234(Siteid 10). It has to display all the Three(UserId: 187,196,195) users details.. please reply ASAP..
Many Thanks

A: This might help...
var UserID = (from sn2 in sitenumb.tbl_usersites
             where sn2.usersite_site_id_FK == siteID
             select  sn2.usersite_user_id_FK).First();
//Here you will get only single UserId
var UserIds = (from sn2 in sitenumb.tbl_usersites
              where sn2.usersite_site_id_FK == siteID
              select  sn2.usersite_user_id_FK).ToList()
// Here you will get all the UserIds of that particular site

A: As you have shown your database entries,there may be more than one users having access on a particular site..First()  return the single row.Therefore you should modify your code to get the list by using ToList() method.
For example, you can modify the code to get all users for the particular site id as:-
 var UserID = (from sn2 in sitenumb.tbl_usersites
                      where sn2.usersite_site_id_FK == siteID
                         select  sn2.usersite_user_id_FK).ToList();

you can modify your code accordingly


text:
Q: List of targets supported by binutils I am following a website ( http://wiki.osdev.org/GCC_Cross-Compiler ) to learn how to cross compile some code for different architectures. So, the first step is to download and compile Binutils for a specific target.
The site say to assign the varible TARGET with i686-elf because then the binutils will be able to handle code in the format specified by $TARGET.
export PREFIX="$HOME/opt/cross"
export TARGET=i686-elf
export PATH="$PREFIX/bin:$PATH"

So, my question is that
Can i get a list of targets that is supported by Binutils?
If the variable TARGET can contain anything or must be something that is supported by Binutils i.e would there be an error during compiling the source code of binutils, if the TARGET is something that binutils doesnt understand?

A: Never saw an answer for this question, so I'll give it the ol college attempt for those coming from various search engines. If one downloads or clones binutils from sourceware
git clone git://sourceware.org/git/binutils-gdb.git

And then reads this explanation of binutils
https://sourceware.org/binutils/binutils-porting-guide.txt

You will find the answer.

TL;DR
Read the contents of config.bfd within the bfd directory

All the supported targets are listed within
cd /path/to/git/clone/of/binutils/bfd

Notice the files with elf32-[SOME_NAME].c and elf64-[SOME_NAME].c in the above mentioned directory, those are your supported targets.
Ex
elf32-cr16.c

would translate to,
--target=cr16-elf


text:
Q: Copy Paste Special Value - Vlookup Edition I am an accountant dealing with lots of financial statements.
I typically use a vlookup to pull in numbers from another spreadsheet into my template containing the desired format. The best solution has been for me to

*

*Copy my Vlookup formula

*Select the whole template

*F5-> Special-> Search for Blanks

*Copy paste special formulas

Here's my problem. My desired template contains sum formulas etc that I do not want to lose. However, after I copy paste special formula and try to copy paste special value, I cannot as Excel says it cannot work on multiple selections. Then it becomes a painful task going through line by line and converting the vlookup into a value. Any solutions?

A: Well, VBA is the gold standard for this kind of problem:  "gruntwork" that needs to not be "gruntwork." However, there is somewhat of a workaround available to you.
First, to clarify your question, I believe your approach is meant to paste the formula (singular) into multiple cells, and then it acts upon information relative to those cells producing different results (probably) in all the cells it is present in. You then want to copy those (different) results and paste them (in one step) as values. And it is at the point where you attempt to copy these for that last step that Excel balks. Choosing a big block is unacceptable as it would include your desired subtotal formulas and so turn them to values as well upon pasting.
No way around that. People have been asking for some time now for Excel to overcome that, but Excel has a feature wherein non-contiguous cells can be copied and pasted as a contiguous set of data... BUT... if it cannot figure out how to render what you want copied, it stops you right at the start and refuses to go onward.
So, here's the deal...
Conceptually, this is in keeping with the idea of a template, so it shouldn't be too obnxious. Highlight all the cells and paste special the formulas. Let Excel calculate and then start the macro recorder (click the little camera looking icon in the absolute lower left corner of the screen by the word "Ready") and give it a name and a shortcut key combo (if desired). When that dialogue box goes away, start the work. For every cell, one by one, you will press F2, notice that the cursor is at the absolute end of the entire formula in the cell, press Ctrl-Shift-Home to highlight everything in the cell, then immediately press F9 and notice the whole formula is evaluated and replaced with its result. Then press Enter which moves you to the next highlighted cell (handy that). Repeat for every cell until the highlight returns to the first cell you did it for (actually, it doesn't matter if you go on too far and do a couple twice, just don't stop short). Do be careful pressing keys so you don't break the highlighting. The click the rather different looking icon down where the camera looking thing was to end the recording.
It IS a solution using VBA but takes no knowledge of actual VBA to do it. That's my wiggle-room... At this point you have a template with a macro and must save it as an XLSM type file:  in this case, as an XLTM file. Well, if you had it as an actual formal template. If you're like me, you have a bunch of "templates" that just have normal XLSX file types and in that case, XLSM would be fine.
Further issues:  if you distribute the filled in templates, just do all this, then save the results as an XLSX file, the doing of which will dump the macro so the client will not have either a macro workbook which many would not like, nor will see you worked smarter, not harder and try to lower your rates! Presumably YOU have no problems with a macro file, but if you do, you can save the macro to your Personal workbook so it is available always but is not in your template.
Also, if you bring up the macro editor, you can see how it did its magic and see how easily you could insert lines for new cells getting the VLOOKUP() formula, or remove lines for cells no longer getting it.
Finally, to really future-proof the macro, select the cell with your VLOOKUP() formul, then start the macro recorder, as above, but your first step will be to copy that cell (just use Ctrl-C perhaps) and your second to perform the F5 highlighting the blank cells for the formula, then Paste|Special|Formula to the highlighted cells. THEN you begin the cycle of F2, Ctrl-Shift-Home, F9, and Enter to go through the cells. That way the whole thing is done for you. Personally... I'm a throwback who'd prefer to do that easy first part by hand, then have the macro do the rest, but no one should live that way, right?
So... the workaround does still use a macro, but you won't have to do the VBA yourself so I'm calling it even there. You can have the macro in the template, or not, as needed, and in any case, not pass anything involving it on to clients so I'm calling it win there. Finally, whichever approach above is taken (just getting values in the end or having it do the whole step of work), you aren't doing it piece by piece, so a win there too.
(But if you don't mind VBA, it could all be done in 3-4 lines I'd say, since written VBA can use vastly more effective commands than the macro recorder is able to risk.)


text:
Q: How do I use CSSTransitionGroup on children columns immediately under a row? I'm using Bootstrap's grid system in my ReactJS project. Under a row, I have multiple columns (col-md-4) which I want to animate as they are added to or removed from the row as the component state changes. But Using CSSTransitionGroup immediately under a row to let the columns render as children leaves a span under the row and above the columns ruining the columns' left float.

    <ReactCSSTransitionGroup
        transitionName={`fadeIn`}
        transitionEnterTimeout={200}
        transitionLeaveTimeout={200}>

           {list.map(user => { return (

            )})}
     </ReactCSSTransitionGroup>

YIELDS:

                ...

What is the correct approach to this?

A: Solved : just add className="row" in CSSTransitionGroup element
Sample code Here:
<CSSTransitionGroup
    transitionName="item"
    transitionEnterTimeout={500}
    transitionLeaveTimeout={300}
    className="row">

      {myIndustries}

</CSSTransitionGroup>


text:
Q: Verifying that a billiard system satisfies the twist condition. I'm numerically studying a 2D billiard system whose domain is a unit outer circle with an inner elliptical scatterer of variable geometry. EDIT: Both the circle and ellipse share a common centre.
From my readings, I understand that the 'twist condition' is an important assumption to understand the evolution of the systems phase section, and its behaviour with varying geometrical parameters.
For the case where the trajectory only hits the outer circular boundary it's easy to show, by the boundary's convexity, that this condition is obeyed.
However, I'm at a loss as to a mathematically rigourous way to demonstrate that it is obeyed (or disobeyed!) in the case where the particle hits the inner ellipse (mixed dynamics manifest in this case)
Any suggestions or pointers would be gratefully received.
Thankyou in advance !


text:
Q: oVirt - Running VMs into a Subnet I am trying to run VMs (and Pools) into a NAT. To reach this target I have:

*

*created a new Network in the Cluster;

*checked "Create on external provider" check box;

*selected ovirt-provider-ovn;

*entered (in the "Subnet" tab) Name, CIDR, gateway and DNS.

*assigned the network to a VM

When I run the VM, it is correctly getting the subnet IP, but it is completely isolated. Cannot either ping the Gateway or the DNS server.
What am I missing?

A: As per RHV 4.3 documentation, you can only create isolated OVN networks through oVirt API or routed OVN networks through Neutron API. Source NAT is not (yet) implemented

If you add Open Virtual Network (OVN) (ovirt-provider-ovn) as an external network provider, multiple subnets can be connected to each other by routers. To manage these routers, you can use the OpenStack Networking API v2.0. Please note, however, that ovirt-provider-ovn has a limitation: Source NAT (enable_snat in the OpenStack API) is not implemented.

source: https://red.ht/33V7ObK


text:
Q: How to calculate percentiles from z-scores We often get reference tables to match z-scores with equivalent percentiles.
Can anyone help me calculate percentiles from z-scores? What's the formula?
Thank you.

A: The following formula can be found in the Handbook of Mathematical Functions
$$\hat{Z}\left ( x \right )=\left ( b_1t+b_2t^2+b_3t^3+b_4t^4+b_5t^5 \right )+\varepsilon \left ( x \right )$$
Where $t={1}/{\left (1+px \right)}$, $\left | \varepsilon (x) \right |< 7.5\times 10^{-8}$, $p=.2316419$, $b_1=.319381530$, $b_2=-.356563782$, $b_3=1.781477937$, $b_4=-1.821255978$, and $b_5=1.330274429$.
Most modern software that allows the user to calculate the percentile from the $Z_{score}$ provide more accurate results than this old approximation.


text:
Q: How do I install graphviz 2.29 in 12.04? In my ubuntu 12.04, the graphviz is not the latest version(2.29). I need some features available in the latest version of graphviz.
I tried to install the graphviz version 2.29, which requires libgraphviz4(>=2.18).
I anyhow installed libgraphviz4 and installed graphviz 2.29. For that I have to remove packages libcdt4 and libpathplan4.
Now whenever I try to generate graph, I get some problems:
For e.g.:
dot -Kfdp -n -Tpng -o samplePOS.png forcePOS.dot

It says:
dot: error while loading shared libraries: libgvc.so.6: cannot open
shared object file: No such file or directory

neato -Tps -o sample_1.ps sourcedot.gv

It says:
neato: error while loading shared libraries: libgvc.so.6: cannot open
shared object file: No such file or directory

So, I am looking for some ways so that I can run graphviz 2.29 in my ubuntu 12.04.

A: Ubuntu 12.04 here.
What worked for me is:

*

*Remove the following packages
sudo apt-get remove libcdt4

sudo apt-get remove libpathplan4

*Install libgraphviz4
http://www.graphviz.org/Download_linux_ubuntu.php

*Install graphviz
sudo apt-get install graphviz

A: First a warning for using PPA (mainly unstable)

*

*Are PPA's safe to add to my system and what are some "red flags" to watch out for?
The below PPA: ppa:dperry/ppa-graphviz-test is an unstable PPA. So, you are given warning.
Use this commands in a terminal to install the unstable 2.29 version of graphviz.
sudo apt-add-repository ppa:dperry/ppa-graphviz-test
sudo apt-get update
sudo apt-get autoremove graphviz
sudo apt-get install graphviz

If you get this error "graphviz : Depends: libgraphviz4 (>= 2.18) but it is not going to be installed", run the following
sudo apt-get remove libcdt4
sudo apt-get remove libpathplan4
sudo apt-get install graphviz

A: Since you mess with some libraries i advice you to remove graphviz and install again
sudo apt-get remove graphviz
sudo apt-get remove graphviz-dev
sudo apt-get remove graphviz-doc
sudo apt-get install graphviz

This is a same situation for other user


text:
Q: Combinations Proof Show that $2^n = \sum_{i=0}^n \binom ni$.
I tried expanding $\sum_{i=0}^n \binom ni$ into sum of: $\frac{n!}{(n-r)!r!}$, and found the common ratio and then used the sum formula, but I did not get to $2^n$.

A: Consider the expansion of $(x+1)^n$. This looks like:
$$ x^n + nx^{n-1} + \cdots + nx + 1$$
So how do we get the coefficients of the intermediate terms? They are just the number of different way to choose $k\; x$ terms (and $n-k\; 1$ terms) out of the $n$ brackets $(x+1)\cdots(x+1)$. So
$$(x+1)^n = \sum_{k=0}^n{n \choose k}x^k$$
Now set $x=1$.

A: HINT: Try expanding $2^n = (1+1)^n$ using the Binomial Formula. Do you notice any simularities between your problem and this expansion?

A: Well, you also just use induction over $n$, so
$$
2^n = \sum_{i=0}^n \binom ni \tag1
$$
clearly holds for $n=1$ (or even for $n=0$), since
$$
2^1=\sum_{i=0}^1 \binom 1i=\binom 10+\binom11=1+1=2
$$
Now we want to show that
$$
2^{n+1} = \sum_{i=0}^{n+1} \binom {n+1}i
$$
holds by using our assumption $(1)$. We have by using the Pascal identity
$$
{n \choose k}={n-1 \choose k-1}+{n-1 \choose k}
$$
to show the following
$$
2^{n+1}=\sum_{i=0}^{n+1} \binom {n+1}i=1+\sum_{i=1}^{n} \bigg(\binom {n}{i-1}+\binom {n}{i}\bigg)+1
$$
which gives us
\begin{align}
1+\sum_{i=1}^{n} \binom {n}{i-1}+\sum_{i=1}^{n}\binom {n}{i}+1&=\binom nn+\sum_{i=1}^{n} \binom {n}{i-1}+\sum_{i=1}^{n}\binom {n}{i}+\binom n0\\
&=\sum_{i=1}^{n+1} \binom {n}{i-1}+\sum_{i=0}^{n}\binom {n}{i}\tag 2\\
&=\sum_{i=0}^{n} \binom {n}{i}+\sum_{i=0}^{n}\binom {n}{i}=2^n+2^n=2^{n+1} \tag3
\end{align}
while we used an index shift in $(2)$ and our induction assumption in $(3)$. So we eventually proved by induction
$$
2^n = \sum_{i=0}^n \binom ni
$$

A: Method 1: Use binomial theorem
$$(x+y)^n = \sum_{k=0}^{n} \binom{n}{k} x^k y^{n-k}$$
Choose $$x=y=1$$ to get
$$(1+1)^n = \sum_{k=0}^{n} \binom{n}{k} 1^k 1^{n-k}$$

Method 2: Use induction

*

*Prove $$2^0 = \sum_{k=0}^{0} \binom{0}{k}$$

*Prove for n=1,2,...
$$2^{n-1} = \sum_{k=0}^{n-1} \binom{n}{k} \to 2^n = \sum_{k=0}^{n} \binom{n}{k}$$
This comes down to proving
$$2\binom{n-1}{0} + ... + 2\binom{n-1}{n-1} = \binom{n}{0} + ... + \binom{n}{n}$$

Method 3: Use counting argument
Consider creating a sandwich having to decide which of $n$ items you're going to include.
Say item 1 is lettuce. item 2 is tomato. item 3 is patty. item 4 is ketchup and so on until item n is cheese.
You could go through each item and decide whether or not to add it (2 choices per item). By the multiplication rule of counting, the number ways to do this is $2^n$.
That's the LHS. As for the RHS,
you can choose none out of the n items. You can choose one of the n items. You can choose two of the n items. So on until you can choose n of the n items.
Since these are mutually exclusive cases, by the addition rule of counting, the number of ways to do this is:
$$\binom{n}{0} + \binom{n}{1} + ... + \binom{n}{n}$$

A: Using the identities
$$\begin{align*}
\binom{n+1}{r} &= \binom{n}{r-1} + \binom{n}{r}&&(1\le r \le n)\\
\binom{n}0 &= \binom{n}{n} = 1
\end{align*}$$
and prove by induction that your result is true for all integers $n\ge 0$:
$$
\sum^{n+1}_{r=0}\binom{n+1}{r} = \binom{n+1}0 + \sum^{n}_{r=1}\binom{n+1}{r} + \binom{n+1}{n+1}
$$


text:
Q: Configuring production.rb file to send emails with Rails 4 I am stuck with sending emails in Rails. I need to send password reset or activation account emails using Devise gem. Thanks Devise has email sending functionality builtin. I only need to configure sender. I have googled and found many tutorials on how to do that. Here are the things I still don't understand as many tutorials do not talk about them much:
Any tutorial comes with something like that:
config.action_mailer.default_url_options = { :host => 'gmail.com' }

config.active_support.deprecation = :notify

config.action_mailer.delivery_method = :smtp
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"

# SMTP settings
ActionMailer::Base.smtp_settings = {
    :port           => 587,
    :address        => 'smtp.gmail.com',
    :domain         => 'gmail.com',
    :user_name      => ENV['username'],
    :password       => ENV['password'],
    :authentication => :plain,
}

So unclear things for me are:
1) what is :host, can I use localhost?, in example it is gmail.com. Do I need to set up some gmail server or whatever.
2) what is :domain, again is it my site domain? or using just gmail.com is fine?
3) What is user_name and password?
So the general question is do I need to install some server for mail on my production server and so on, people on this tutorials skip this part. Who sends my email? Rails app server? or separate smtp server?

A: 1) host is a variable used to generate links to your site in the email (see comment).
2) domain is the sending domain of the email, if you have your own domain you could put your domain there.
3) user name and password are the credentials of your gmail account (or the account that you send mails from). If you have your own smtp relay server set up you can use information for that.
This will likely only work for a minimal number of emails sent, you need to look into a professional service that delivers your emails if you intend on sending more than about 100 per month.


text:
Q: Incorrect datetime value while saving data to MySql I faced a strange problem about saving java Date object to MySql db. Here is the error I get:
Incorrect datetime value: '1970-01-01 02:55:00' for column 'start_time' at row 1

My sql script
CREATE TABLE `schedules` (
            `id` bigint(20) NOT NULL AUTO_INCREMENT,
            `start_time` timestamp NOT NULL,
            `end_time` timestamp NOT NULL,
            PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8

Part of my entity:
 @Column(name = "start_time")
 private Date startTime;

When I try to do something like
String time = "02:55"
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
scheduleEntity.setStartTime(sdf.parse(time));

repository.save(scheduleEntity);

It falls with error. But when I use "16:00" string for parsing it works perfectly. I use Spring Boot, Spring Data with Hibernate. Can someone help me?

A: Apparently, you want to store only a time portion in your table, yet you use timestamp data type, which stores both date and time and has other special features as well.
If you want to store time only, then use MySQL's time data type:

MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or 'HHH:MM:SS' format for large hours values). TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

The linked documentation contains a link that explains how time literals are interpreted.

A: Your column type is TIMESTAMP
11.3.1 The DATE, DATETIME, and TIMESTAMP Types

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

Solution
you can change start_time and end_time columns type to DATETIME directly in DB or drop table and change you entity like this
@Column(name = "start_time", columnDefinition="DATETIME")
@Temporal(TemporalType.TIMESTAMP)
private Date startTime;

hope it will help


text:
Q: Jenkins Server cannot compile because no heap space could reserved I have a big problem with my jenkins server: I Cant build a maven project, because the java vm cannot start:
Checkout:workspace / /var/lib/jenkins/jobs/SchwarzGoldTool/workspace - hudson.remoting.LocalChannel@b7193fc
Using strategy: Default
Last Built Revision: Revision c2d18fd7a5d7f112163e9440a8e7256a44e32f46 (origin/HEAD, origin/master)
Checkout:workspace / /var/lib/jenkins/jobs/SchwarzGoldTool/workspace - hudson.remoting.LocalChannel@b7193fc
Fetching changes from 1 remote Git repository
Fetching upstream changes from git://.../tsc.git
Seen branch in repository origin/HEAD
Seen branch in repository origin/master
Commencing build of Revision 2b4654302e8222509db5808c9071ec95daf0b495 (origin/HEAD, origin/master)
Checking out Revision 2b4654302e8222509db5808c9071ec95daf0b495 (origin/HEAD, origin/master)
Warning : There are multiple branch changesets here
Parsing POMs
Modules changed, recalculating dependency graph
[SchwarzGoldTool] $ java -Xmx512M -Xms512M -cp /var/lib/jenkins/plugins/maven-plugin/WEB-INF/lib/maven3-agent-1.2.jar:/var/lib/jenkins/tools/Maven_3.0.3/boot/plexus-classworlds-2.4.jar org.jvnet.hudson.maven3.agent.Maven3Main /var/lib/jenkins/tools/Maven_3.0.3 /var/run/jenkins/war/WEB-INF/lib/remoting-2.11.jar /var/lib/jenkins/plugins/maven-plugin/WEB-INF/lib/maven3-interceptor-1.2.jar 58359
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
ERROR: Failed to launch Maven. Exit code = 1
Finished: FAILURE

I tried to add -Xmx and -Xms to the VM (as you can see) but that doesnt work either... someone has a idea whats going on there?

A: The problem is caused by Jenkins failed to reserve enough heap space to kick off a maven build. From what you said, it seems like there are few things which share your VM limit, (I included the estimation of the memory required to run each process)

*

*The VM's OS   (~200~300mb)

*Jenkins       (~min 256mb)

*Webcontainers (~256~512mb)

*etc. (~100mb)

My memory estimation is rather conservative, but still, it's easily adds up to over 1gb, which leave the available heap for Jenkins to reserve to less than the Xms (512m), hence, failed to kick off a build
Ideally you should increase the softlimit on your VM to a higher value. If that is not feasible, my advice will be to reduce the memory management of the build by change the job configuration in Jenkins to something like this, (Xmx512m, Xms128m) so that Jenkins can kick off a build with only 128m free heap. But this setting may cause out of memory error in the later stage, when the build required a heap which is below Xmx but above the available heap.
Alternatively, you can memory manage other processes I mentioned above or you can setup some configure the virtual memory on your VM.


text:
Q: Cannot obtain information about the node because the specified selector does not match any node in the DOM tree I am working with testCafe for the first time and I am trying to write a test that clicks the name of a specific patient in a list of patients displayed.
The error that I am getting is as follows:

Cannot obtain information about the node because the specified
selector does not match any node in the DOM tree.

| Selector('[data-cy=Name]')

This is the actual code block:
test
  .meta({
    code: '4.1',
    action: 'From Patient Summaries screen, click a patient name'.
    expected: 'Should take user to the weekly Patient Overview screen'
  })
  .page(url)
  ('4.1', async t => {
    await LoginPageObject.loginAsDoctor();

    const patients = Selector('[data-cy=Patients]');
    const settingsMenuItem = Selector('[data-cy=name]');

    await t.expect(patients.visible).ok().click(patients);
    await t.expect(Selector('[data-cy=table-row-0]').visible).ok()

    await t.expect(settingsMenuItem.textContent)
      .contains("Charles Shetland")
      .click(settingsMenuItem);

    await VnVScreenshot(t, '4.1', fixtureName);
  });

I tried doing const settingsMenuItem = Selector('td [data-cy=Name]'); and .contains("Shetland,Charles") as that's technically how the name is listed.
But I am still getting the same error for Selector('td [data-cy=Name]').
The way the DOM hierarchy looks is:
div
 table
  thead
  tbody
   tr
    td

A: It's difficult to determine the exact cause of the error without a sample. However, I found the incorrect code in the following lines:
await t.expect(settingsMenuItem.textContent)
      .contains("Charles Shetland")
      .click(settingsMenuItem);

If you want to click an item with specified text, you need to use the withText method:
https://testcafe.io/documentation/402740/reference/test-api/selector/withtext
await t.click(settingsMenuItem.withText('Charles Shetland'))

If this does not help, please prepare a sample that demonstrates the issue.
Please note that you can use the TestCafe Experimental Debug functionality to execute a selector in IDE or chrome nodejs console. Refer to the following article for details:
https://testcafe.io/documentation/402639/reference/command-line-interface#--experimental-debug

A: So the way I was able to resole it is with some testCafe magic.
What I did was change the data-cy="Name", to data-cy="call_Shetland Charles".
I was not sure at first but that allowed me to go from this:
const settingsMenuItem = Selector('[data-cy=Name]');

To this:
const settingsMenuItem = Selector('[data-cy*=Charles]');

And testCafe was able to identify what patient I wanted it to click on.


text:
Q: How to show main report with empty linked subreports in Crystal Reports? I have a Crystal Reports report which contains a main report and three subreports. The data tables used in subreports are linked with main report's data table. In subreports also I've given linking.
Now when I have data in subreports, all comes out fine. But if there is no data in subreports, the main report is also shown as blank.
How to make the main report show results despite (some) sub reports being empty?

A: Subreports only run after the main report has retrieved it's data.  So unless you have set up some fairly complex suppression conditions using shared variables, there is no way that a linked subreport can 'blank' the main report.  You can confirm this by running the same report criteria with all of the subreports deleted.  You will likely still have the same blank main report. The cause is more likely to be an inner join in the main report.
And there is one final possibility that I hope no one finds insulting.  Depending on how the subreports are arranged, it could be possible that adding the subreports causes the first page to be blank while the report starts on the second page. This is caused by the 'keep together' properties of sections and groups.  I have had clients call me to troubleshoot blank reports when the data was on page 2.


text:
Q: how to specify the terminal width in mysql CLI I'm using the mysql CLI, however the result displays always wraps around on my terminal screen. is there any way to specify to mysql the size of my terminal screen?

A: I couldn't find resize command but stty cols 150 worked for me. You would have to execute this command in the bash terminal before you enter mysql command line client.

A: MySQL doesn't seem to have any settings for terminal linesize.  If you're on a system with ksh or bash, try the following before launching the mysql command shell:
eval `resize`

[note the quotes are backticks] This should set the $COLUMNS and $LINES shell variables to the size of your window and ensure that the xterm knows how big it is.


text:
Q: Node.js app , for streaming videos ,how to captured from some other ip .? the app will be hosted on a LAN. Whenever someone opens up the app. Two options appear on the screen. You can either set up your own stream or subscribe to someone else's stream for watching a video .
The stream is an video buffer, that is being played on either your browser or on the person's browser whose stream you are subscribing to.
For playing video, we can simply use the HTML5 player .
For subscribing to someone else's stream, i should make a textbox in which an IP address would be entered and a button to start fetching the stream.
Can someone help in help me in deciding , best approach , of doing so ?
TIA


text:
Q: error handling on get_meta_tags() and redirection limits? I'm using get_meta_tags() in a script and on certain URLs it fails out with (as an example)...
Warning:  get_meta_tags(http://www.kodak.com/) [function.get-meta-tags]: failed to open stream: Redirection limit reached...
Is it possible to just skip over any result that throws an error? Or should I just use @get_meta_tags() instead?
function getMeta()
{
    $tags = get_meta_tags($this->link); //INSERT INTEGRITY CHECK HERE?
    $keywords = $tags['keywords'];

    if(count($keywords))
    {
        preg_match_all('/(?<=^|,)\s*((?:[^\s,]+\s*){1,4})(?=\s*(?:,|$))/', $keywords, $m);
        $this->keywords = array_slice($m[1], 0, 15);
    }
}

A: You could use the error suppression operator - the @ character - directly before the call to get_meta_tags(). This has the effect of turning all error reporting off for that line only, but it's generally regarded as a bad practice, only to be used when you other options are all exhausted.
Your first reaction to this should be to try to pass a canonical URL to get_meta_tags() where possible - i.e. you should try to pass the URL at the end of the redirection chain: for example, link to http://www.php.net/manual/en/language.types.array.php rather than http://php.net/array. If $this-link comes from a source out of your control, however, using error suppression might be your best bet:
You can use it as follows:
$tags = @get_meta_tags($this->link);

This is functionally the same as this:
$errorLevel = error_reporting(0);
$tags = get_meta_tags($this->link);
error_reporting($errorLevel);

You'll need to change the rest of your code to deal with the $tags variable not containing an array of meta tags.

A: I don't agree with using error suppressing, but there are a few exceptions it does come in handy.
function getMeta()
{
    if ($tags = @get_meta_tags($this->link)) {
        $keywords = $tags['keywords'];

        if (count($keywords)) {
            preg_match_all('/(?<=^|,)\s*((?:[^\s,]+\s*){1,4})(?=\s*(?:,|$))/', $keywords, $m);
            $this->keywords = array_slice($m[1], 0, 15);
        }
    } else {
        // Catch error
    }
}

Be warned that the @ error suppressor will suppress all errors, not just exceeded redirect limit. See docs

A: This one suppress  all errors, but does exactly thing you're looking for
function getMeta()
{
    $tags = @get_meta_tags($this->link); //INSERT INTEGRITY CHECK HERE?
    if (!$tags){
        //handle your error
    }

    $keywords = $tags['keywords'];

    if(count($keywords))
    {
        preg_match_all('/(?<=^|,)\s*((?:[^\s,]+\s*){1,4})(?=\s*(?:,|$))/', $keywords, $m);
        $this->keywords = array_slice($m[1], 0, 15);
    }
}


text:
Q: How to get values from a Messaging.Email object I have code which builds a list of Messaging.Email objects to be sent out based on various conditions. The problem is I want to be able to write a test which asserts that these email factory methods I've written are properly populating the fields (e.g. bccAddresses, toAddresses, etc). What I'm getting back is:
Messaging.SingleEmailMessage[
  getBccAddresses=(support@widgets.com);
  getCcAddresses=null;
  getCharset=null;
  getDocumentAttachments=null;
  getFileAttachments=null;
  getHtmlBody=null;
  getInReplyTo=null;
  getPlainTextBody=Test;
  getReferences=null;
  getTargetObjectId=null;
  getTemplateId=null;
  getToAddresses=(jim);
  getWhatId=null;
  isUserMail=false;
]

However, when I try to get one of these values I receive the following error:
Messaging.Email[] result = buildEmailList(testViolationList);
System.debug(result[0].getBccAddresses());
Method does not exist or incorrect signature: [Messaging.Email].getBccAddresses()

To give more context, what I am doing is generating a list Case objects which have violated our SLA in some way (violationList). buildEmailList() takes in this violation list and builds emails to people who should be notified for each level of SLA violation. I would just like to confirm in my tests that the proper email addresses are being included within the correct fields of the email objects that are returned.
Am I missing something here or are there simply no getters defined for Messaging.Email objects? There doesn't appear to be according to any of the Apex documentation for Messaging objects. If that's the case is there any other way I can test the contents of this object?
UPDATE: Hack/Solution
As a work around I've come up with the method below. However, it seems quite hacky.
Messaging.Email[] result = buildEmailList(testViolationList);
String email = JSON.serialize(result[0]);
Map<String, Object> emailContents = (Map<String, Object>) JSON.deserializeUntyped(email);
System.debug(emailContents.get('bccAddresses'));

Can anyone confirm that there is no better way to do this?

A: I think I figured this one out. If you need to build a list of email objects to send out, they need to be stored within a Messaging.SingleEmailMessage[].
The documentation for Messaging.sendEmail() states that it takes in a Messaging.Email[] as it's first argument. Since this is the case I wrote my email factory method to return a Messaging.Email[] containing all of the Messaging.SingleEmailMessage that it has generated.
The problem is that once a Messaging.SingleEmailMessage object is added to a Messaging.Email[], you can no longer use the getter methods which are available for the object. However, the getter methods are still accessible if you add each email object to a Messaging.SingleEmailMessage[]. It's not listed in the documentation but I've found that Messaging.sendEmail() will also accept a Messaging.SingleEmailMessage[].
Messaging.SingleEmailMessage email = new Messaging.SingleEmailmessage();
email.setToAddresses(new String[] {'jasonsims87@gmail.com'});
email.setPlainTextBody('test body');
email.setSubject('test');

Messaging.Email[] emailList = new Messaging.Email[] {email};
Messaging.sendEmail(emailList);               // < Will send successfully.
System.debug(emailList[0].getToAddresses());  // < but getter method will fail.

Messaging.SingleEmailMessage[] emailList = new Messaging.SingleEmailMessage[] {email};
Messaging.sendEmail(emailList);               // < Will also send successfully.
System.debug(emailList[0].getToAddresses());  // < And getter method succeeds.


text:
Q: Comment about type theory in Lawvere and Rosebrugh's Sets for Mathematics The Foreword to Sets for Mathematics (second section, titled Organization) contains the following comment, about the differences between ETCS and other foundations of mathematics:

Each map needs both an explicit domain and an explicit codomain (not
  just a domain, as in previous formulations of set theory, and not just
  a codomain, as in type theory).

I understand the remark about set theory: a function as a set of ordered pairs determines its domain but not its codomain.
But what do the authors mean when they say a function in type theory has an explicit codomain but not an explicit domain?
A term of the simple type $A \rightarrow B$ has both an explicit domain and codomain. A term of a dependent type $\Pi x:A.B(x)$ arguably has an explicit domain but not a codomain (since its codomain would need to be something like $\bigcup x:A.B(x)$, which does not exist as a type in Martin-Löf Type Theory).

A: I believe the point is that a term $x:A$ of type theory is interpreted categorically as an arbitrary morphism into $A$.


text:
Q: Python: pickle creates module import error I have a python script which uses pickle that I've been running for weeks.  I recently installed dropbox so that I could run the script on machine A, pickle the data to dropbox, and then load the data from dropbox onto machine B.  So, I used to write to a file in the path of the script, now I write to a separate file synced by dropbox.
When I go to load the data, I get the following error:
data = pickle.load(f)
ModuleNotFoundError: No module named 'pandas._libs'

However, this prior line works fine:
import pandas as pd

In fact, if I run the script that's dumping (rather than loading) data, it also runs successfully.
I've also verified the path is correct using sys.path.
What could be the problem?

A: As mentioned in comments, this is a pandas version issue.  Your pickle file was created by pickling objects containing a newer version or pandas, and the system unpickling that file contains an older version of pandas.
To be more precise, pandas._libs first appeared in:

commit 648ae4f03622d8eafe1ca3b833bd6a99f56bece4
  Author: Jeff Reback
   Date:   Tue Mar 7 18:21:18 2017 -0500
BLD: consolidate remaining extensions
  moves extensions to pandas/_libs, which holds the extension code
  and also the generated builds (as its importable).

... which first appears in version 0.20.  It stands to reason that your pickle file was created with a version of pandas >= 0.20, and the unpickle system has version < 0.20.


text:
Q: Is there a way to control alias names in Slick? I'm starting out using Slick for a legacy db and I want to drive stuff by very simple unit tests on the generated queries. The alias names chosen by Slick is a bit annoying and I would very much like to be able to control them. Is there a way?
A failing test is probably clearer than prose:

[info] QueriesSpec:
[info] ActivityGroup
[info] - should join with Crmcategory *** FAILED ***
[info]   "select [x2."id", x2."name", x2."crmcode", x3."name" from "activitygroup" x2, "crmcategory" x3 where x3."id" = x2."crmcategory"]" did not equal "select [ag."id", ag."name", ag."crmcode", c."name" FROM activitygroup ag, crmcategory c where ag.crmcategory = c.id]" (QueriesSpec.scala:9)


text:
Q: Polymorphic this in TypeScript I'm trying to do what I think is a "textbook" use case for polymorphic this and it isn't working and I just can't figure this out.  Imagine I have some abstract base class that is cloneable, e.g.:
abstract class X {
    abstract clone(): this;
}

Now I want to implement a base class that provides a clone implementation:
class Y extends X {
    constructor(private x: number) { super() }
    clone(): this { return new Y(this.x + 1); }
}

When I do this, I get an error that says Type Y is not assignable to type 'this'.  I'm totally confused.  All I want to convey here is the type constraint that if a subclass of X has its clone method invoked, that the type of the thing that you will get back will be identical to the subtype.  Isn't this exactly what polymorphic this is for?  What am I doing wrong here?
Here is a link to this code in the TypeScript playground.

A: I've marked artem's answer as the correct one because he seems to be correct that it really isn't possible to do this in a 100% safe way.
However, there is a way to get the compiler to enforce the type constraint I wanted.  So, I decided to include this answer in case it is useful to people.  The only downside of my approach is that it is slightly unsafe for exactly the reasons that artem points out, i.e., that somebody could extend your classes without providing an implementation of clone and create a situation where the returned value would not really be what you claim it is.
My solution was to just add a cast.  Again, this is unsafe in general.  But if you never extend from the classes, it works fine as far as I can tell.  So my solution was:
class Y extends X {
    constructor(private x: number) { super() }
    clone(): this {
        return new Y(this.x + 1) as this;
    }
}

You can see a complete version that compiles here.

A: No, as things are right now, it's not a supported use case for this type. A method with this return type should return an instance of derived class even if this method is not overridden in the derived class - see code in this answer for an example that justifies this.
In other words, given abstract clone(): this declaration, this code must be valid even if Z does not override clone itself, but you implementation of clone in Y breaks it.
class Z extends Y {
    f() {
        let c: Z = this.clone();
    }
}

So it looks like a method with this return type should always return this.
UPDATE: I found an open issue with this use case on github, marked as 'accepting pull requests'. I'm not sure however if they really intend to support it, or plan to fix cloneNode in their compiler in some other way.


text:
Q: Get count of items in ArrayList based on property on type I'm trying to get a count of how many Items are of itemTypeId 1
Item
public class Item {
  private int itemTypeId;

  public int getItemTypeId() {
    return this.itemTypeId;
  }
}

So for example lets say we have 4 instances of the above.  2 of them have an itemTypeId of 1.  Then and we add them to an ArrayList:
ArrayList<Item> items = new Array<>();
items.push(item1);
items.push(item2);
items.push(item3);
items.push(item4);

I need to get the count of how many items have an itemTypeId of 1:
Integer quantityOfTypeOne = ???

This did not work, it says equals() is not a method it recognizes
Integer quantityOfTypeOne = items.stream().filter(item -> item.getItemTypeId().equals(1).collect(Collectors.toList()));

and I tried == which I think is not a good way to compare integers anyway:
Integer quantityOfTypeOne = items.stream().filter(item -> item.getItemTypeId() == 1).collect(Collectors.toList()));

A: Please use == for comparing primitive integers.
int quantityOfTypeOne  = items.stream().filter(item -> item.getItemTypeId()==1).collect(Collectors.toList()).size();

Learn more about Operators in Java.

A: You said you only want the count, so a simple reducing stream is idiomatic:
items.stream()
  .mapToInt(Item::getItemTypeId)
  .filter(id -> id == 1)
  .count()

A: I got it working even simpler with:
items.stream().filter(item -> item.getItemTypeId() == 1).count()


text:
Q: $(this).prop('property') vs. this.property Given jQuery's philosophy of write less, do more, I'm always surprised when I see this:
$(this).prop('checked')

… instead of this:
this.checked

Looking at the latest jQuery source, prop() provides convenience for these two gotchas:

*

*$(elem).prop('for') is equivalent to elem.htmlFor.

*$(elem).prop('class') is equivalent to elem.className.

It also normalizes tabIndex to:

*

*0 for tabbable elements without a tab index.

*-1 for non-tabbable elements.

prop() is certainly useful for setting properties for multiple elements at once, and for chaining properties on a single element.
But is there any advantage (other than idiomatic) to use prop() to set or retrieve a single property on a single element except when normalizing tabIndex – specifically when you have a reference to the element (such as this in a callback)?

A: .prop as a getter has no real advantage, in fact, it is less performant than directly accessing the property.
The real utility of .prop is when used as a setter.
If you read the DOC, there is 3 way of setting something with .prop.

.prop(prop, value)
The first way has no advantage for a single element(except maybe if there is compatibility issue).
In fact this.check = true; is the same as $(this).prop('checked', true), but faster.
If you have a set of element though, there is an advantage. You don't have to manually loop all elements, jQuery does it for you.

.prop({prop : value[, prop : value, ...]});
The second way is useful when you have multiple properties to change. Instead of listing every properties you want to change like that :
this.prop1=true;
this.prop2=true;
this.prop3=true;
this.prop4=true;

You can pass an object like that :
$(this).prop({
    prop1 : true,
    prop2 : true,
    prop3 : true,
    prop4 : true
});

.prop(prop, callback)
The third way is in my opinion my favorite one. Using a callback function allow you to set every element individually on a set of condition. The callback receive 2 arguments: the index and the old value.
A good example of the use of a function is to reverse the state of every checkbox:
$('checkbox').prop('checked', function(_, old){
    return !old;
});


text:
Q: android how to use multiple switch widgets According to references, ToggleButtons and Switches are supposed to be used with an OnCheckedChangeListener or with a function like onToggleClicked(View view).
However, both ways return void and the inner if statement, which is either if (on) or if (checked), or if (isChecked), doesn't let me to set a usable variable. The same applies for radio buttons.
I have an app where I'd like to calculate daily energy requirements of intensive care patients. I need to use multiple switches; and all these selectors jointly affect a calculation. An example formula is:
1784 + (5 * weight) - (11 * age) + (244 if male) + (239 if trauma patient) + (804 if burn patient)
Below is an example including a single switch. Ididn't include my solution for all the switches/parameters, since that's too many code clutter:
public double calculateBMI(View view) {
  EditText getHeight = (EditText)findViewById(R.id.height);  // find the widget
  String height_as_string = getHeight.getText().toString();  // get the string
  int height = Integer.parseInt(height_as_string);           // convert to integer

  Switch gender = (Switch)findViewById(R.id.gender);         // find the switch

  double heightConvertedToInch = height / 2.54;  // convert height to inch
  // calculate ideal body weight
  if(gender.isChecked()){                        // gender is male
    double idealBodyWeight = 106 + ( 6 * heightConvertedToInch );
    return idealBodyWeight;
  } else {                                       // gender is female
    double idealBodyWeight = 100 + ( 5 * heightConvertedToInch );
    return idealBodyWeight;
  }
}

A:
According to references, ToggleButtons and Switches are supposed to be used with an OnCheckedChangeListener or with a function like onToggleClicked(View view).

Those are event listeners, if you need to take immediate action based upon the change of the state of the compound button, such as enabling/disabling other widgets. They are not needed otherwise.

What is the proper way to handle this situation?

Call isChecked() on each CompoundButton (whether ToggleButton or Switch or CheckBox or whatever), and use that information to "affect a calculation".


text:
Q: VB.NET: Retrive an image (blob) from MySQL DB I've a field called "Foto" in MySQL DB. This field is a blob. When I used SQL Server, the following code worked:
    Dim conn As New MySqlConnection
    conn.ConnectionString = ConnectionString
    Dim cmd As New MySqlCommand
    cmd.Connection = conn
    conn.Open()
    cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"
    Dim reader As MySqlDataReader

        reader = cmd.ExecuteReader
        While reader.Read
            If (IsDBNull(reader("Foto"))) Then
                frmCartaIdentitaView.pctImage.Image = Nothing
            Else
                Dim byteImage() As Byte = reader("Foto")
                Dim frmImageView stmFoto As New System.IO.MemoryStream(byteImage)
                frmImageView.pctImage.Image = Image.FromStream(stmFoto)
                frmImageView.pctImage.SizeMode = PictureBoxSizeMode.Zoom
                frmImageView.Show()
            End If
        End While

But now that I'm using mysql, is produced the following error: invalid parameter.

A: If your ID field is an integer, see if this gets you past that error.  Instead of this:
cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"

Try this:
cmd.CommandText = "SELECT Foto FROM MyTable WHERE ID = " & ctype(int32,IDtxt).ToString

A: I had the same problem. I got this error when the BLOB column was empty, then
I solved this way:
Sorry, but I found this post just now
Dim conn As New MySqlConnection
conn.ConnectionString = ConnectionString
Dim cmd As New MySqlCommand
cmd.Connection = conn
conn.Open()
cmd.CommandText = "SELECT Foto, length(Foto) AS picLen FROM MyTable WHERE ID = '" & IDtxt.ToString & "'"
Dim reader As MySqlDataReader

    reader = cmd.ExecuteReader
    While reader.Read
        If (reader("picLen "))=0 Then
            frmCartaIdentitaView.pctImage.Image = Nothing
        Else
            Dim byteImage() As Byte = reader("Foto")
            Dim frmImageView stmFoto As New System.IO.MemoryStream(byteImage)
            frmImageView.pctImage.Image = Image.FromStream(stmFoto)
            frmImageView.pctImage.SizeMode = PictureBoxSizeMode.Zoom
            frmImageView.Show()
        End If
    End While