text:
Q: How can I make consistent-width plots in ggplot (with legends)? I've got a few different categories that I want to plot.  These are different categories, each with their own set of labels, but which makes sense to group together in the document.  The following gives some simple stacked bar chart examples:
df <- data.frame(x=c("a", "b", "c"),
                 y=c("happy", "sad", "ambivalent about life"))
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()

The problem is that with different labels, the legends have different widths, which means the plots have different widths, leading to things looking a bit goofy if I make a table or \subfigure elements.  How can I fix this?
Is there a way to explicitly set the width (absolute or relative) of either the plot or the legend?

A: As @hadley suggests, rbind.gtable should be able to handle this,
  grid.draw(rbind(ggplotGrob(p1), ggplotGrob(p2), size="last"))

however, the layout widths should ideally be size="max", which doesn't cope well with some types of grid units.

A: Edit:  Very easy with egg package
# install.packages("egg")

library(egg)

p1 <- ggplot(data.frame(x=c("a","b","c"),
                        y=c("happy","sad","ambivalent about life")),
             aes(x=factor(0),fill=x)) +
      geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),
                        y=c("happy","sad","ambivalent about life")),
             aes(x=factor(0),fill=y)) +
      geom_bar()

ggarrange(p1,p2, ncol = 1)

Original Udated to ggplot2 2.2.1
Here's a solution that uses functions from the gtable package, and focuses on the widths of the legend boxes. (A  more general solution can be found here.)
library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)

# Your plots
p1 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=x)) + geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=y)) + geom_bar()

# Get the gtables
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

# Set the widths
gA$widths <- gB$widths

# Arrange the two charts.
# The legend boxes are centered
grid.newpage()
grid.arrange(gA, gB, nrow = 2)

If in addition, the legend boxes need to be left justified, and borrowing some code from here written by @Julius
p1 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=x)) + geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=y)) + geom_bar()

# Get the widths
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

# The parts that differs in width
leg1 <- convertX(sum(with(gA$grobs[[15]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[15]], grobs[[1]]$widths)), "mm")

# Set the widths
gA$widths <- gB$widths

# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[15]] <- gtable_add_cols(gA$grobs[[15]], unit(abs(diff(c(leg1, leg2))), "mm"))

# Arrange the two charts
grid.newpage()
grid.arrange(gA, gB, nrow = 2)

Alternative solutions  There are rbind and cbind functions in the gtable package for combining grobs into one grob. For the charts here, the widths should be set using size = "max", but the CRAN version of gtable throws an error.
One option: It should be obvious that the legend in the second plot is wider. Therefore, use the size = "last" option.
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

# Combine the plots
g = rbind(gA, gB, size = "last")

# Draw it
grid.newpage()
grid.draw(g)

Left-aligned legends:
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

# The parts that differs in width
leg1 <- convertX(sum(with(gA$grobs[[15]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[15]], grobs[[1]]$widths)), "mm")

# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[15]] <- gtable_add_cols(gA$grobs[[15]], unit(abs(diff(c(leg1, leg2))), "mm"))

# Combine the plots
g = rbind(gA, gB, size = "last")

# Draw it
grid.newpage()
grid.draw(g)

A second option is to use rbind from Baptiste's gridExtra package
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

# Combine the plots
g = gridExtra::rbind.gtable(gA, gB, size = "max")

# Draw it
grid.newpage()
grid.draw(g)

Left-aligned legends:
# Get the grobs
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

# The parts that differs in width
leg1 <- convertX(sum(with(gA$grobs[[15]], grobs[[1]]$widths)), "mm")
leg2 <- convertX(sum(with(gB$grobs[[15]], grobs[[1]]$widths)), "mm")

# Add an empty column of "abs(diff(widths)) mm" width on the right of
# legend box for gA (the smaller legend box)
gA$grobs[[15]] <- gtable_add_cols(gA$grobs[[15]], unit(abs(diff(c(leg1, leg2))), "mm"))

# Combine the plots
g = gridExtra::rbind.gtable(gA, gB, size = "max")

# Draw it
grid.newpage()
grid.draw(g)

A: Just by chance, I noticed that Arun's solution he had suggested in his comments hasn't been picked up. I feel his simple and efficient approach is really worth to be illustrated.
Arun suggested to move the legend to the top or bottom:
ggplot(df, aes(x=factor(0), fill=x)) + geom_bar() + theme(legend.position = "bottom")
ggplot(df, aes(x=factor(0), fill=y)) + geom_bar() + theme(legend.position = "bottom")

Now, the plots have the same width as requested. In addition, the plot area is equally sized in both cases.
If there are more factors or even longer labels, it might become necessary to play around with the legend, e.g., to display the legend in two ore more rows. theme() and guide_legend() have several parameters to control the position and appearance of legends in ggplot2.

A: I created a little function based on the answer of @Sandy.
same.size.ggplot <- function(vector.string.graph, # a vector of strings which correspond to Robject ggplot graphs
                             reference.string.graph, # a string of a  Robject ggplot graphs where height and/or height will be taken for reference
                             width = T, # if you wanna adapat only the width
                             height = F # if you wanna adapat only the height
) {

  # example: same.size.ggplot(p0rep(c("a", "b"), thre), "a30")

  which(vector.string.graph %in% reference.string.graph)

  newref <- ggplotGrob(get(reference.string.graph))
  ref.width <- newref$widths
  ref.height <- newref$heights

  assign(reference.string.graph, newref, env = parent.frame(1))

  for(i in seq_along(vector.string.graph)) {
    if(vector.string.graph[i] != reference.string.graph) {
      new <- ggplotGrob(get(vector.string.graph[i]))
      if( width ) {
        new$widths <- ref.width
      }
      if( height ) {
        new$heights <- ref.height
      }
      assign(vector.string.graph[i], new, env = parent.frame(1))
    }
  }
}

p1 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=x)) + geom_bar()
p2 <- ggplot(data.frame(x=c("a","b","c"),y=c("happy","sad","ambivalent about life")),aes(x=factor(0),fill=y)) + geom_bar()
p3 <- ggplot(data.frame(x=c("a","b","c"),y=c("Crazy happy","sad","Just follow the flow")),aes(x=factor(0),fill=y)) + geom_bar()

grid.arrange(p1, p2, p3, ncol = 1)

same.size.ggplot(c("p1", "p2", "p3"), "p2") # same as same.size.ggplot(c("p2", "p3"), "p1")

grid.arrange(p1, p2, p3, ncol = 1)

Before

After

A: The cowplot package also has the align_plots function for this purpose (output not shown),
both2 <- align_plots(p1, p2, align="hv", axis="tblr")
p1x <- ggdraw(both2[[1]])
p2x <- ggdraw(both2[[2]])
save_plot("cow1.png", p1x)
save_plot("cow2.png", p2x)

and also plot_grid which saves the plots to the same file.
library(cowplot)
both <- plot_grid(p1, p2, ncol=1, labels = c("A", "B"), align = "v")
save_plot("cow.png", both)

A: You could also use the patchwork-package for that:
require(ggplot2)
require(patchwork)
# data
df = data.frame(x = c("a", "b", "c"),
                y = c("happy", "sad", "ambivalent about life"))
p1 = ggplot(df, aes(x=factor(0), fill=x)) + geom_bar()
p2 = ggplot(df, aes(x=factor(0), fill=y)) + geom_bar()

# Patchwork 1: Does it automatically
p1 / p2

# Patchwork 2: Create a list
l = patchwork::align_patches(p1, p2)


text:
Q: Fetching Captured Image sent through Intent I'm working on a simple project, where I'm suppose to create an application for taking notes. I've sucessfully created the app but now I want to make it possible for the user to take a photo and save it with the note.
I can take the picture, preview it, and then click save.
But the problem is that I'm not able to get the image sent through the intent to my MainActivity class, where the note is suppose to be saved.
So my question is how do I save the note with the picture, please look at the picture that represents how I want my customRow to look like

I have no idea why this happends beacuse I get no errors... And its been driving me nuts.
Any ideas??
Image.class
public void capturePhoto(View view){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, CAPTURE_IMAGE);
    }
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        switch (requestCode){
            case CAPTURE_IMAGE:
                previewCapturedImage();
                break;
        }

    }
    else if (resultCode == RESULT_CANCELED) {
        // user cancelled Image capture
        Toast.makeText(getApplicationContext(),
                "User cancelled image capture", Toast.LENGTH_SHORT)
                .show();
    } else {
        // failed to capture image
        Toast.makeText(getApplicationContext(),
                "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                .show();
    }

}
private void previewCapturedImage() {
    try {
        // bitmap factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 2;

        bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        //Set image here
        imageView.setImageBitmap(bitmap);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

 public void sendImageAsIntent(Boolean isSending){
    if(isSending = false){
       isSending = true;

    }
    if(isSending = true) {
        Intent i = new Intent(CheckOutMemo.this, MainActivity.class);
        i.putExtra("filePath", fileUri.getPath());
        setResult(RESULT_OK,i);
        finish();
    }
}

MainActivity.class
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) {
        return;
    }
    if (requestCode == Image.ADD_REQUEST_CODE) {
        String header = data.getStringExtra("header");
        String bodyText = data.getStringExtra("bodyText");

        filePath = data.getStringExtra("filePath");
        sourceFile = new File(filePath);
        fileName = data.getStringExtra("filePath");
        Uri imageUri = data.getData();
        if(filePath!=null) {
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
                imageIcon.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(MainActivity.this, "FileNoutFoundException MainActivity", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            } catch (IOException e) {
                Toast.makeText(MainActivity.this, "IOException MainActivity", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }

        Memo memo = new Memo(header, bodyText,imageIcon);
        customAdapter.add(memo);
        customAdapter.notifyDataSetChanged();
    } else if (requestCode == Image.EDIT_REQUEST_CODE) {

        int position = data.getIntExtra("position", 0);
        Memo memo = customAdapter.getItem(position);
        memo.header = data.getStringExtra("header");
        memo.bodyText = data.getStringExtra("bodyText");
        customAdapter.notifyDataSetChanged();
    }

}

A: When you do:
Intent i = new Intent(CheckOutMemo.this, MainActivity.class);
i.putExtra("filePath", fileUri.getPath());
startActivity(i);

You are basically asking to create a new instance of MainActivity. To return to the previous activity while setting the result do this instead:
setResult(RESULT_OK, i);
finish();//finishing activity

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lazy module not found in Angular version 11 This app is trying to load the BookModule lazily with this configuration:
const routes: Routes = [
  { path: "", redirectTo: "/books", pathMatch: "full" },
  {
    path: "books",
    loadChildren: "./modules/book/book.module#BookModule",
    canActivate: [AuthGuard]
  },
  { path: "login", component: LoginComponent }
];

And it's producing the error:

Error: Cannot find 'BookModule' in './modules/book/book.module'

Thoughts?

A: Seems like your Angular version is 11.
The lazy loading syntax changed. It is something like this now
const routes: Routes = [
  {
    path: 'items',
    loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
  }
];

So your code should be like this
const routes: Routes = [
  { path: "", redirectTo: "/books", pathMatch: "full" },
  {
    path: "books",
    loadChildren: () => import('./modules/book/book.module').then(m => m.BookModule),
    canActivate: [AuthGuard]
  },
  { path: "login", component: LoginComponent }
];


text:
Q: Using Dependency Injection for classes instantiated at run time I have two classes: ImportBase.cs (Parent) and ImportFleet.cs (Child) which will in the future import a CSV file.  Each child of ImportBase will implement a different implementation of the actual import code.
The approriate child class to use is determined in a Service class where the correct class is instantiated and the import method called.  All is going well up until this point.
The problem is that I also want to Dependency Inject some repository classes into ImportBase and it's inherited classes (as I have attempted in the code below):
ImportBase.cs
namespace WebApi.Services.Import.Investments
{
    interface IImport
    {
        public void Import(IFormFile file, int UserId);
    }

    public abstract class ImportBase : IImport
    {
        public abstract void Import(IFormFile file, int UserId);

        protected List<InvestmentTransactionType> transactionTypes = new();

        protected IInvestmentEntityRepository _investmentEntityRepository;

        public ImportBase(IInvestmentEntityRepository investmentEntityRepository)
        {
            _investmentEntityRepository = investmentEntityRepository;
        }
    }
}

ImportFleet.cs
namespace WebApi.Services.Import.Investments
{
    public class ImportFleet : ImportBase
    {
        public ImportFleet(IInvestmentEntityRepository investmentEntityRepository) : base(investmentEntityRepository)
        {
        }

        public override void Import(IFormFile file, int UserId)
        {
        }
    }
}

InvestmentService.cs
namespace WebApi.Services
{
    public interface IInvestmentService
    {
        public void Import(IFormFile file, int UserId, int InvestmentEntityId);
    }

    public class InvestmentService: IInvestmentService
    {

        public void Import(IFormFile file, int UserId, int InvestmentEntityId)
        {
            IImport importService = null;
            string investmentEntity = ImportBase.determineInvestmentEntityFromCsv(file);

            switch(investmentEntity)
            {
                case "fleet":
                    importService = new ImportFleet();   // problem is here
                    break;
            }

            if (importService != null)
            {
                importService.Import(file, UserId);
            }
        }
    }
}

The problem is the following line:
importService = new ImportKuflink();
Because I only determine which child class to instantiate at run time, I cannot take advantage of DI here.
Under normal circumstances I would make the Import classes a DI based service so all dependencies are available, however I have to create the instance at run time so this I don't think is possible.
Is there a way to accomplish the above?

A: Yes, of course there is a way to accomplish this. But I guess the DI container you are using (like from MS) won't help you here.
I've been fiddling with crap like this for like two years so far and still am busy with it. Two years of creating my own IoC framework.
Usual DI/IoC microkernels follow OCP and other really mandatory concepts and patterns. What I've done is leaving one single small door open. I won't bore you with details. The fundamental idea is that a class must be decorated with the appropriate attributes in code, and then is able to call the microkernel within its constructor (which has been called by a simple "var foo = new Barney();") to let an entity be modified like it had been created by the microkernel.
There is no(t yet a) way to hook into the plain new() code. Some cheer this, some don't. I'm with the cheerleaders here. Why? Side-effects.
Imagine this:
public class SomeNumber
{
    public int SomeValue { get; private set; }

    public SomeNumber()
    {
        SomeValue = 19;
    }
}

Okay? Let's assume you'd modified the new() process by whatever, then another user of your code goes:
Assert.AreEqual(19, someNumberEntity.SomeNumber);

and this code throws an exception, because for whatever reason your modifying code set the number to 7.
Now look at this code (from a unit test):
using System.Reflection;
using Kis.Core.Attributes;

namespace UnitTests_Kis.Core
{
    [KisAware]
    public class KisAwareSimpleClass
    {
        [Property(value: 123)]
        public int ValueToCheck { get; set; } = 0;

        [Property(value: "I am the doctor!")]
        public string Name { get; set; } = "";

        public KisAwareSimpleClass()
        {
            var t = this.GetType();
            var fqtn = t.FullName;
            var ec = new Kis.Core.EntityCreator(Assembly.GetAssembly(t));
            ec.ModifyExistingEntity(fullyQualifiedTypeName: fqtn, existingEntity: this);
        }
    }
}

Clean code isn't always easily readable, but the aspects/attributes will raise coder's awareness.
PS: I posted the unit test code on purpose to show you what's happening.
Short version:
Microkernel.Modify(this);

A: You can inject a factory which has the services injected into it.
public interface IImportFactory
{
    ImportFleet CreateFleetImporter();
}

public class MyImportFactory : IImportFactory
{
    private readonly IMyDependency1 _dependency1;
    private readonly IMyDependency2 _dependency2;

    public MyImportFactory(IMyDependency1 dependency1, IMyDependency2 dependency2)
    {
        _dependency1 = dependency1;
        _dependency2 = dependency2;
    }

    public ImportFleet CreateFleetImporter()
    {
        return new ImportFleet(_dependency1, _dependency2);
    }
}

Then inject the factory as a dependency in your Service class.

A: Here's a simplified version of your code that demonstrates how you can populate an instance of an object from a DI service container.
In your InvestmentService:

*

*Inject the IServiceProvider.

*Use the little known utility ActivatorUtilities to get a fully DI'd instance of your object.

*Make sure you dispose it properly if it implemenents IDisposable.  I've included an async version if you use anything that needs a IAsyncDisposable.

public class InvestmentService : IInvestmentService
{
    private IServiceProvider _serviceProvider;

    public InvestmentService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
        //...
    }

    public Import()
    {
        IImport? importService = null;
        IDisposable? disposable = null;

        var importFleet = ActivatorUtilities.CreateInstance<ImportFleet>(_serviceProvider);
        if (importFleet is IDisposable)
            disposable = importFleet as IDisposable;

        importService = importFleet as IImport;
        // Do whatever you want to do with it

        disposable?.Dispose();
    }

    public async ValueTask ImportAsync()
    {
        IImport? importService = null;
        IDisposable? disposable = null;
        IAsyncDisposable? asyncDisposable = null;

        var importFleet = ActivatorUtilities.CreateInstance<ImportFleet>(_serviceProvider);

        if (importFleet is IDisposable)
            disposable = importFleet as IDisposable;

        if (importFleet is IAsyncDisposable)
            asyncDisposable = importFleet as IAsyncDisposable;

        importService = importFleet as IImport;
        // Do whatever you want to do with it

        disposable?.Dispose();

        if (asyncDisposable is not null)
            await asyncDisposable.DisposeAsync();
    }
}


text:
Q: What is supposed to be in __init__.py I am trying to create a Python package. You can have a look at my awful attempt here.
I have a module called imguralbum.py. It lives in a directory called ImgurAlbumDownloader which I understand is the name of the package -- in terms of what you type in an import statement, e.g.
import ImgurAlbumDownloader

My module contains two classes ImgurAlbumDownloader and ImgurAlbumException. I need to be able to use both of these classes in another module (script). However, I cannot for the life of me work out what I am supposed to put in my __init__.py file to make this so. I realize that this duplicates a lot of previously answered questions, but the advice seems very conflicting.

A: I still have to figure out why (I have some ideas), but this is now working:
from ImgurAlbumDownloader.imguralbum import ImgurAlbumDownloader, ImgurAlbumException

The trick was adding the package name to the module name.

A: It sure sounds to me like you don't actually want a package. It's OK to just use a single module, if your code just does one main thing and all its parts are closely related. Packages are useful when you have distinct parts of your code that might not all be needed at the same time, or when you have so much code that a single module would be very large and hard to find things in.


text:
Q: Vector iterator as a function parameter: what's happening in this code? I'd like to know why is this code legal:
std::vector<int>::iterator & foo(std::vector<int>::iterator & iter) {
    return ++iter;
}

int main() {
    std::vector<int> v = { 1,2,3,4 };

    std::cout << *foo(v.begin()) << std::endl;
}

The function accept a non-const reference to an iterator, but I have not initialized any variables holding that iterator, I simply passed the result of v.begin() as a reference, but the function is able to increase its value, return it, and use the result to print an element of the vector:
Where is the iterator stored?
I'm still learning C++ (Started around 3 weeks ago) so I'm a bit confused, but I have an "idea":
Is a temporary variable initialized just before the call, like when passing a literal to a function that accept a const reference (Example below)?
std::vector<int>::iterator & foo(std::vector<int>::iterator & iter) {
    return ++iter;
}

int main() {
    std::vector<int> v = { 1,2,3,4 };

    std::vector<int>::iterator tempIter = v.begin();
    std::cout << *foo(tempIter) << std::endl;
}

Thanks!


text:
Q: Property of normal matrix's eigenvalue How do I prove that, if $A\in\mathbb{C}^{n\times n}$ is a normal complex matrix (i.e. $AA^H=A^HA$, $A^H$ being the conjugate transpose) and $f$ a rational complex function defined on a subset of the complex plane $\mathbb{C}$ containing all the eigenvalues of $A$, and $\tilde{f}$ is the "matrix equivalent" of $f$, i.e., since $f$ being rational must be a ratio of polynomials, the function that swaps the variable $x$ in $f(x)$ with the matrix, calculating the appropriate powers and considering constants $c$ as $cI$, where $I$ is the identity matrix, and considering negative powers as powers of the inverse matrix, supposing everything works fine (i.e. there are no negative powers of singular matrixes), then there exists an eigenvalue $\lambda$ of $A$ such that:
$$|f(\lambda)|\leq\frac{\|\tilde{f}(A)x\|_2}{\|x\|_2},$$
where $x\in\mathbb{C}^n$ and $\|\cdot\|_2$ is the euclidean complex norm?

A: Let $A\in\mathbb{C}^{n\times n}$ be normal. There is a unitary $Q$ and a diagonal $\Lambda=\mathrm{diag}(\lambda_1,\ldots,\lambda_n)$ such that $A=Q\Lambda Q^*$. For normal matrices (if $f:\mathbb{C}\mapsto\mathbb{C}$ is well-defined on the spectrum of $A$), we have $f(A)=Qf(\Lambda)Q^*$, where $f(\Lambda)=\mathrm{diag}(f(\lambda_1),\ldots,f(\lambda_n))$. Note that $f(A)$ is a normal matrix as well.
For any normal matrix, there is an eigenvalue $\lambda$ such that for all $x\in\mathbb{C}^n$, $|\lambda|\leq\|Ax\|_2/\|x\|_2$. This follows simply from the Courant-Fischer characterization, namely
$$\tag{1}
\lambda_{\min}(A^*A)=\min_{x\neq 0}\frac{x^*(A^*A)x}{x^*x}=\min_{x\neq 0}\frac{\|Ax\|_2^2}{\|x\|_2^2}
$$
and the fact that for a normal matrix $A$,
$$\tag{2}
\lambda_{\min}(A^*A)=|\lambda_{\min}(A)|^2.
$$
Now plug $f(A)$ instead of $A$ to (1) and (2) and it's done.
Note that $f$ does not need to be necessarily a rational function.


text:
Q: Use swiperjs with Vuejs I want to use swiperjs on my vue.js project but I don't know how to import it in. I've try import css and js file in pluginglobal.js but it doesn't work. Any idea how to import it in? since the official site doesn't provide instruction for vue.js.
Thank you for taking your time reading this.


text:
Q: Finding Locations with n Miles of Existing Locations Problem
I have a list of ~5000 locations with latitude and longitude coordinates called A, and a separate subset of this list called B. I want to find all locations from A that are within n miles of any of the locations in B.
Structure
All of this data is stored in a mysql database, and requested via a python script.
Approach
My current approach is to iterate through all locations in B, and request locations within n miles of each location, adding them to the list if they don't exist yet.
This works, but in the worst case, it takes a significant amount of time, and is quite inefficient. I feel like there has to be a better way, but I am at a loss as for how to do it.
Ideas

*

*Load all locations into a list in python, and calculate distances there. This would reduce the number of mysql queries, and likely speed up the operation. It would still be slow though.

A: Load B into a python list and for each calculate maxlat, minlat, maxlong, minlong that everything outside of the box is definitely outside of your radius, if your radius is in nautical miles and lat/long in degrees.  You can then raise an SQL query for points meeting criteria of minlat < lat < maxlat and minlong < long < maxlong.  The resulting points can then be checked for exact distance and added to the in range list if they are in range.
I would suggest doing this in multiple processes.


text:
Q: Next.js script render In my Next.js project I have a script that renders a widget as follows:
      <a
        className="e-widget no-button xdga generic-loader"
        href="https://example"
        rel="nofollow"
      >
        3 lucky winners stand a chance to win…
      </a>
      <Script
        type="text/javascript"
        src="https://widget.gleamjs.io/e.js"
        strategy="afterInteractive"
      ></Script>

The problem is that once this script executes on the initial render, it does not execute again later.
Anyone know how I can get the script to execute multiple times?

A: The issue might be originating from other parts but you can give this a shot:
import React, { FC } from "react";
import Script from "next/script";

interface Props {
  id: string;
}

const Widget: FC<Props> = ({ id }) => {
  return (
    <>
      <a
        className="e-widget no-button xdga generic-loader"
        href="https://example"
        rel="nofollow"
      >
        3 lucky winners stand a chance to win…
      </a>
      <Script
        id={id}
        src="https://widget.gleamjs.io/e.js"
        strategy="afterInteractive"
      />
    </>
  );
};

export default Widget;

A: I managed to solve the problem by forcing the parent component to re-mount, which then causes my Script tag to re execute/render as desired.


text:
Q: Give tqdm a hint about task duration to improve initial accuracy I am using tqdm to track progress when processing 6 large files. Each file is very large and takes about 10 min. During the first 10 min, tqdm is unable to offer an accurate time estimate because it has not collected any data points yet. After the first file is done, the progress report works satisfactorily.
Is there a way to hint tqdm with my own estimate of how long the task will take? For example, something like tqdm(file_list, hint="10 min") would have tqdm start with "60 min remaining" rather than "? min remaining". As it actually progresses through the iterable, it would then update this initial estimate accordingly.


text:
Q: LINQ Group by with two statements Hi is there anyway to write somthing like this
            var r = from i in myList
                group i by i.Number
                    into grp
                    select new
                    {
                        Reported = grp.Select(x => x.CurrentStatus).First(),
                        Number = grp.Key,
                        Sum = grp.Sum(x => x.Details[0].Quantity),
                        Name = grp.Select(x => x.Name).First(),
                        Details = grp.Select(x => x.Details).First(),
                        Descriptions = grp.Select(x => x.Descriptions).First(),
                        AssignmentId = grp.Select(x => x.AssignmentId).First(),
                        Listor = grp.Select(x => x.Number).Count()
                    };

into this
            var r = from i in myList
                group i by i.Number, i.CurrentStatus
                    into grp
                    select new
                    {
                        Reported = grp.Select(x => x.CurrentStatus).First(),
                        Number = grp.Key,
                        Sum = grp.Sum(x => x.Details[0].Quantity),
                        Name = grp.Select(x => x.Name).First(),
                        Details = grp.Select(x => x.Details).First(),
                        Descriptions = grp.Select(x => x.Descriptions).First(),
                        AssignmentId = grp.Select(x => x.AssignmentId).First(),
                        Listor = grp.Select(x => x.Number).Count()
                    };

so that i can group by " group i by i.Number, i.CurrentStatus"

A: Group by an anonymous type:
        var r = from i in myList
            group i by new { i.Number, i.CurrentStatus }
                into grp
                select new
                {
                    Reported = grp.Key.CurrentStatus,
                    Number = grp.Key.Number,
                    Sum = grp.Sum(x => x.Details[0].Quantity),
                    Name = grp.Select(x => x.Name).First(),
                    Details = grp.Select(x => x.Details).First(),
                    Descriptions = grp.Select(x => x.Descriptions).First(),
                    AssignmentId = grp.Select(x => x.AssignmentId).First(),
                    Listor = grp.Select(x => x.Number).Count()
                };


text:
Q: getLargestExpressionResult(a,b) I'm trying to get this function done but something is wrong, it should return 50 for a=5,b=10 or 2  for a=1,b=1. However any other way to write this function would be interesting

function getLargestExpressionResult(a, b) {
  const sum = a + b;
  const prod = a * b;
  const diff = a - b;
  const quot = a \ b;

  let res = sum;

  if (prod > res) res = prod;
  if (diff > res) res = diff;
  if (quot > res) res = quot;

  return res;
}

enter code here

A: You can use Math.max(). It can take multiple parameters and gives you max.
Also for division it is /

function getLargestExpressionResult(a, b) {
  const sum = a + b;
  const prod = a * b;
  const diff = a - b;
  const quot = a / b;

  return Math.max(sum,prod,diff,quot);
}

console.log(getLargestExpressionResult(5, 10))

A: You don't really need to find maximum element on your own, you can simply use Math.max:

const getLargestExpressionResult = (a, b) => Math.max(a * b, a / b, a + b, a - b);

console.log(getLargestExpressionResult(5, 10));
console.log(getLargestExpressionResult(1, 1));

Also should be noticed division is /, not \.
Or if you need to avoid Math usage:

getLargestExpressionResult = (a, b) => {
    const expressionValues = [ a + b, a - b, a * b, a / b ];
    let max = expressionValues[0];
    for (const value of expressionValues) {
        if (value > max) max = value;
    }
    return max;
}

console.log(getLargestExpressionResult(5, 10));
console.log(getLargestExpressionResult(1, 1));


text:
Q: Visual Studio 14 - An exception has been encountered. This may be caused by an extension Getting this error when I open any Javascript file, I'm using visual studio 2015 community, tried reinstalling, repairing, nothing worked, what should I do?
It tells me to check ActivityLog.xml, this is it:
<entry>
    <record>366</record>
    <time>2016/02/03 22:45:31.949</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [ErrorListPackage]</description>
    <guid>{4A9B7E50-AA16-11D0-A8C5-00A0C921A4D2}</guid>
  </entry>
  <entry>
    <record>367</record>
    <time>2016/02/03 22:45:31.980</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [ErrorListPackage]</description>
    <guid>{4A9B7E50-AA16-11D0-A8C5-00A0C921A4D2}</guid>
  </entry>
  <entry>
    <record>368</record>
    <time>2016/02/03 22:45:32.042</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [RoslynPackage]</description>
    <guid>{6CF2E545-6109-4730-8883-CF43D7AEC3E1}</guid>
  </entry>
  <entry>
    <record>369</record>
    <time>2016/02/03 22:45:32.277</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [Microsoft.VisualStudio.LanguageServices.TypeScript.TypeScriptPackage, Microsoft.VisualStudio.LanguageServices.TypeScript, Version=14.0.0.0, Culture=neutral]</description>
    <guid>{2FFE45C4-5C73-493C-B187-F2E955FF875E}</guid>
  </entry>
  <entry>
    <record>370</record>
    <time>2016/02/03 22:45:32.402</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{D62C17C6-44B3-4E5D-B0AA-1C5536E979D9}</guid>
  </entry>
  <entry>
    <record>371</record>
    <time>2016/02/03 22:45:32.402</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [Microsoft.VisualStudio.JSLS.JavaScriptLanguageServicePackage, Microsoft.VisualStudio.JSLS, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]</description>
    <guid>{D62C17C6-44B3-4E5D-B0AA-1C5536E979D9}</guid>
  </entry>
  <entry>
    <record>372</record>
    <time>2016/02/03 22:45:32.402</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [Microsoft.VisualStudio.JSLS.JavaScriptLanguageServicePackage, Microsoft.VisualStudio.JSLS, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]</description>
    <guid>{D62C17C6-44B3-4E5D-B0AA-1C5536E979D9}</guid>
  </entry>
  <entry>
    <record>373</record>
    <time>2016/02/03 22:45:32.449</time>
    <type>Error</type>
    <source>Editor or Editor Extension</source>
    <description>System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Web.Editor, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.Web.Editor, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.VisualStudio.LanguageServices.TypeScript.VsPackage.WpfTextViewConnectionListener.SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection`1 subjectBuffers)
   at Microsoft.VisualStudio.Text.Editor.Implementation.ConnectionManager.<>c__DisplayClass4_1.<.ctor>b__1()
   at Microsoft.VisualStudio.Text.Utilities.GuardedOperations.CallExtensionPoint(Object errorSource, Action call)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
</description>
  </entry>
  <entry>
    <record>374</record>
    <time>2016/02/03 22:45:32.542</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{F1A8554A-C492-4871-92E2-7A5EE5940C00}</guid>
  </entry>
  <entry>
    <record>375</record>
    <time>2016/02/03 22:45:32.542</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [ServicesPackage]</description>
    <guid>{F1A8554A-C492-4871-92E2-7A5EE5940C00}</guid>
  </entry>
  <entry>
    <record>376</record>
    <time>2016/02/03 22:45:32.558</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [ServicesPackage]</description>
    <guid>{F1A8554A-C492-4871-92E2-7A5EE5940C00}</guid>
  </entry>
  <entry>
    <record>377</record>
    <time>2016/02/03 22:45:32.574</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{1E863AE9-93F6-42FD-A301-D3391F876208}</guid>
  </entry>
  <entry>
    <record>378</record>
    <time>2016/02/03 22:45:32.574</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [CommonAzureToolsPackage]</description>
    <guid>{1E863AE9-93F6-42FD-A301-D3391F876208}</guid>
  </entry>
  <entry>
    <record>379</record>
    <time>2016/02/03 22:45:32.652</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{198E76C1-34C0-424D-9957-B3EBD80265FB}</guid>
  </entry>
  <entry>
    <record>380</record>
    <time>2016/02/03 22:45:32.652</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [Microsoft Visual Studio Server Explorer Package]</description>
    <guid>{198E76C1-34C0-424D-9957-B3EBD80265FB}</guid>
  </entry>
  <entry>
    <record>381</record>
    <time>2016/02/03 22:45:32.652</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [Microsoft Visual Studio Server Explorer Package]</description>
    <guid>{198E76C1-34C0-424D-9957-B3EBD80265FB}</guid>
  </entry>
  <entry>
    <record>382</record>
    <time>2016/02/03 22:45:32.667</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [CommonAzureToolsPackage]</description>
    <guid>{1E863AE9-93F6-42FD-A301-D3391F876208}</guid>
  </entry>
  <entry>
    <record>383</record>
    <time>2016/02/03 22:45:32.933</time>
    <type>Information</type>
    <source>VSPackage</source>
    <description>Should automatically check for an update</description>
  </entry>
  <entry>
    <record>384</record>
    <time>2016/02/03 22:45:32.933</time>
    <type>Information</type>
    <source>VSPackage</source>
    <description>Next update check in '85726184' ms </description>
  </entry>
  <entry>
    <record>385</record>
    <time>2016/02/03 22:45:32.964</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{1B437D20-F8FE-11D2-A6AE-00104BCC7269}</guid>
  </entry>
  <entry>
    <record>386</record>
    <time>2016/02/03 22:45:32.980</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [Visual Studio HTM Editor Package]</description>
    <guid>{1B437D20-F8FE-11D2-A6AE-00104BCC7269}</guid>
  </entry>
  <entry>
    <record>387</record>
    <time>2016/02/03 22:45:32.980</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Loading UI library</description>
    <guid>{1B437D20-F8FE-11D2-A6AE-00104BCC7269}</guid>
    <path>C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages*\htmledui.dll</path>
  </entry>
  <entry>
    <record>388</record>
    <time>2016/02/03 22:45:32.980</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [Visual Studio HTM Editor Package]</description>
    <guid>{1B437D20-F8FE-11D2-A6AE-00104BCC7269}</guid>
  </entry>
  <entry>
    <record>389</record>
    <time>2016/02/03 22:45:32.996</time>
    <type>Error</type>
    <source>Color Theme Service</source>
    <description>The color 'Popup' in category 'de7b1121-99a4-4708-aedf-15f40c9b332f' does not exist.</description>
  </entry>
</activity>


text:
Q: Nodemailer: ECONNREFUSED I don't know what I'm missing, I use the Nodemailer example:
var nodemailer = require("nodemailer");

// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
    auth: {
        user: "gmail.user@gmail.com",
        pass: "userpass"
    }
});

// setup e-mail data with unicode symbols
var mailOptions = {
    from: "Fred Foo ✔ <foo@blurdybloop.com>", // sender address
    to: "bar@blurdybloop.com, baz@blurdybloop.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world ✔", // plaintext body
    html: "<b>Hello world ✔</b>" // html body
}

// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response){
    if(error){
        console.log(error);
    }else{
        console.log("Message sent: " + response.message);
    }

    // if you don't want to use this transport object anymore, uncomment following line
    //smtpTransport.close(); // shut down the connection pool, no more messages
});

I just changed the user and pass in auth to my gmail account info (also tried with their values), and I changed the "to" email address to my email address.  I get:
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

What am I missing?  I don't see anything in the documentation that says I need to do anything more than this, so why won't it work?  Thank you in advance.

A: It was a firewall issue.  Turns out there was nothing wrong with the code, I just didn't understand what the error message implied.

A: I was also using a gmail account to send the email, you might need an Application-specific password from google to allow nodemailer to work properly.
https://support.google.com/mail/answer/1173270?hl=en

A: Following step:

*

*Login gmail account.

*Enable pop3 in settings tabs

*Enable less secure apps at: Enable less secure apps for gmail account

*Display Unlock Captcha at: Display unlock Captcha

*Defined email option and sending
var mailOptions = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL
    auth: {
        user: 'gmail_account@gmail.com',
        pass: 'password'
    }
}

mailer = nodemailer.createTransport(mailOptions);

mailer.sendMail({
....
}, function(err, response) {
        if (err) {
             console.log(err);
        }
        console.log(response);
});

Hope this block code help you.

A: ECONNREFUSED inidcates that this is some kind of connection or firewall issue.
Can you connect to smtp.gmail.com port 465 with any other application from the same machine, for example with openssl?
openssl s_client -connect smtp.gmail.com:465

A: if you use new nodemailer version
nodemailer.createTransport({
    host,
    port,
    secure:,
    auth:{
        user,
        pass
    }
})

more see https://github.com/andris9/nodemailer-wellknown

A: In my case I just had to disable my anti virus, Avast.
To white list on avast do this:
These steps may vary according to your Avast version, including the IP used here
1) Open Avast, go to: Menu -> Settings. (It is located on the top right corner)
2) Go to General Tab -> Exceptions -> Add Exception

3) Get the IP of your gmail, it is going to be with the error, I think.

4) Now paste the IP on your exception

Hope it helps.

A: The actual problem fix is that you need to place the SERVICE. Better if you use ENVIRONMENT VARIABLES
            var transporter = nodemailer.createTransport({
                service: process.env.EMAIL_SERVICE,
                auth: {
                    user:process.env.EMAIL_USER,
                    pass:process.env.EMAIL_PASSWORD
                }
            })

A: firewall problem
to block the firewall in order to send email, you need to allow port or disable all port.
allowing specific port:
$ sudo ufw allow 587

to disable firewall
$ sudo ufw disable

$ sudo ufw reset


text:
Q: Does Grand Theft Auto 5 Hitch Lift 1 (Tinkle) random event repeat? Has anyone seen this random event repeat? I've already played it once, and only realized after the amount of money I could have made off of it if it had happened to me later in the game. Some random events do repeat obviously like bike thefts and armored truck robberies, but I'm curious if anyone has seen or read this specific random event repeating? I want this to be available for later in the game too!

A: some times the game dont register them and you can repeat it. I did the tinkle one twice, the second time with over $3.5b invested with each character ;)
 You can verify on Social club if it is registered


text:
Q: Integer as plus/minus combination of three squares Some time ago I came across the following statement in a paper:
"Every integer $k$ has a representation of the form
$k=\pm a^2 \pm b^2 \pm c^2$"
Unfortunately I can't remember where I read it, just wrote it down in my nodes. Moreover, I was not able to find this problem somewhere on the web. Now, I would be interested in a proof, and I suspect it might be rather easy, although I couldn't solve it.

A: Using $a^2-b^2 = (a-b)(a+b)$, we can write :
$pq = (\frac{p+q}{2})^2-(\frac{p-q}{2})^2$
With $p=1$ and $q=k$ or $q=k+1$
$$k=2n+1 \implies k=(n+1)^2−n^2$$
$$k=2n \implies k=(n+1)^2−n^2-1$$


text:
Q: Interesting relationship between the 2D Harmonic Oscillator and Pauli Spin matrices I have an isotropic 2D Harmonic Oscillator in cartesian coordinates
\begin{equation}
H = \frac{p_x^2}{2m} + \frac{p_y^2}{2m} + \frac{1}{2} m\omega^2 (x^2 + y^2)
\end{equation}
In terms of the usual creation and annihilation operators for the $x$ and $y$ modes, $n_x$ and $n_y$ this can be written as
\begin{equation}
H = \hbar\omega(n_x^\dagger n_x + n_y^\dagger n_y + 1)
\end{equation}
Now we can 'construct', three operators that commute with the Hamiltonian, apart from the (trivial) number operators $N_x$ and $N_y$:
\begin{align}
V_x &= a_x^\dagger a_y + a_y^\dagger a_x\\
V_y &= i(a_y^\dagger a_x - a_x^\dagger a_y)\\
V_z &= a_x^\dagger a_x - a_y^\dagger a_y
\end{align}
Now these operators can been proved to satisfy the commutation relations of angular momentum. In fact,
\begin{equation}
V_i = a^\dagger \sigma_i a
\end{equation}
Where $a = \begin{pmatrix} a_x & a_y \end{pmatrix}$ and $\sigma_i$ are the Pauli matrices. This is really surprising to me as I don't see why and how this must be true. Can someone shed some light on this? I think for $2s+1$ dimensions, we can 'construct' such operators using the matrix representations of spin $s$. However, I haven't seen a proof of this.

A: It is well known the operators
$$
\hat C_{ij}=a_i^\dagger a_j\, ,i, j=1,\ldots, n
$$
span the Lie algebra $\mathfrak{u}(n)$.  If you choose $\hat C_{ij}, i\ne j$ and use $h_i= \hat C_{ii}-\hat C_{i+1,i+1}$, you get instead the Lie algebra $\mathfrak{su}(n)$.  Yours is just the special case with $n=2$.
The $n=3$ case is discussed in details in

Fradkin DM. Three-dimensional isotropic harmonic oscillator and
SU$_3$. American Journal of Physics. 1965 Mar;33(3):207-11,

and indeed the connection with harmonic oscillator for general $n$ goes back to

Jauch JM, Hill EL. On the problem of degeneracy in quantum mechanics. Physical Review. 1940 Apr 1;57(7):641.

Note that general representations (not of the fully symmetric type) of $\mathfrak{su}(n)$  having Young diagrams with $m<n$ rows usually start with $U(m\times n)\supset U(m)\otimes U(n)$ so the bosons $a^\dagger_{\alpha i}$, $\alpha=1,\ldots m$, $i=1,\ldots,n$,
etc and the operators
$$
\hat C_{ij}=\sum_\alpha a^\dagger_{\alpha i}a_{\alpha j}\, .
$$

A: The Hamiltonian in question has cylindrical symmetry, and can be transformed to cylindrical coordinates (i.e. $x,y\longrightarrow r, \phi$). The wave function then decomposes into radial and angular part, and the eigenstates obtained called Fock-Darwin states. Interestingly, the solution is simple also works with magnetic field, which affects only the angular momentum. You can google to find more information, e.g., here.
Perhaps another way to see it is in terms of Schwinger bosons (google again), which is a representation of angular momentum in terms of two bosons, i.e., two oscillators.


text:
Q: How to properly stop a separate thread together with shutting down a bokeh server? I'm trying to plot a 'real time' plotting streaming some sensor data using the bokeh server. Meanwhile I want to start a separate theread to 'manipulate' the same data with some file i/o operation to the hard drive.
From multiple sources here and here, I was able to assmeble a script shown below. However when I run bokeh serve --show test.py in the command prompt, the webpage never load. And the server is just frozen. Could anyone please point out what I should do? Thank you for any help.
For simplicity, the blocking_task for the separate thread contains only a time.sleep function. The plot will show up if the last three lines are commented out (they are for the separate thread).
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox

import time
import numpy as np
import datetime as dt
from threading import Thread
import sys

# the function to be called by the separate thread
def blocking_task():
    while True:
        if stop_threads:
            print('thread killed')
            sys.exit()
        time.sleep(0.1)

# the 'stop' button under the plotting
def button_callback():
    global stop_threads
    stop_threads = True

def update():
    data = np.random.rand()
    source.stream(dict(time=[dt.datetime.now()], data=[data]), 100)

doc = curdoc()
stop_threads = False  # a global flag used for stopping the separate thread

source = ColumnDataSource(dict(time=[], data=[]))
fig = figure(x_axis_type='datetime', plot_width=800, plot_height=400)
fig.line(x='time', y='data', source=source)

button = Button(label="Stop", button_type="success")
button.on_click(button_callback)

doc.add_root(column([fig, widgetbox(button, align="center")], sizing_mode='stretch_both'))
doc.add_periodic_callback(callback=update, period_milliseconds=100)

thread = Thread(target=blocking_task)
thread.start()
thread.join()  # I can comment out this line to show the streaming plot, but there is no way to stop the separate thread together with shutting down the server.

A: join() waits for the thread to stop before continuing execution. bokeh serve wraps the whole script in a function that is expected to return, which never happens in your case.
Try removing just the last line and setting daemon=True in the Thread constructor.

A: I will avoid the daemon flag according to the documentation:

Daemon threads are abruptly stopped at shutdown. Their resources (such
  as open files, database transactions, etc.) may not be released
  properly. If you want your threads to stop gracefully, make them
  non-daemonic and use a suitable signalling mechanism such as an Event.

I will instead check the threading.main_thread().is_alive() in the while loop of the child thread
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox

import time
import numpy as np
import datetime as dt
import threading
import sys

def blocking_task():
    while threading.main_thread().is_alive():
        time.sleep(0.1)
    else:
        print('exiting child thread')

def button_callback():
    sys.exit()

def update():
    data = np.random.rand()
    source.stream(dict(time=[dt.datetime.now()], data=[data]), 100)

doc = curdoc()

source = ColumnDataSource(dict(time=[], data=[]))
fig = figure(x_axis_type='datetime', plot_width=800, plot_height=400)
fig.line(x='time', y='data', source=source)

button = Button(label="Stop", button_type="success")
button.on_click(button_callback)

doc.add_root(column([fig, widgetbox(button, align="center")], sizing_mode='stretch_both'))
doc.add_periodic_callback(callback=update, period_milliseconds=100)

thread = threading.Thread(target=blocking_task)
thread.start()


text:
Q: PageFactory Error with Hello World, Interceptor.php Working on the Hello World example here:
alanstorm.com/magento_2_mvvm_mvc
I'm on the "Passing off to the View" step but I get an error with the World.php file when I refresh the page as instructed:

My world.php file is cut & pasted from the example.
The error mentions a "Interceptor.php" but there is no file by that name in the folder the error mentions.

Please advise and thanks.

A: I assume you are in developer mode.
Try one of the following from your Magento root:

*

*php bin/magento cache:flush

*rm -Rf var/generation/*
Sometimes, when you change a class constructor, you may have something left in your Magento's cache or autogenerated files. It happened to me several times.


text:
Q: PHP SimpleXML how to access data I have an XML but I can't seem to access any of the nodes.
When I use the code below I can see it is picking up the data but I can't seem to access the nodes individually.
$xml=simplexml_load_file("uploads/" . $fileName) or die("Error: can't create     object");
echo'<pre>';
print_r($xml);
echo'</pre>';

Here is a sample record.
<CONSOLIDATED_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<INDIVIDUALS>
<INDIVIDUAL   xsi:noNamespaceSchemaLocation="">
<DATAID>110404</DATAID>
<VERSIONNUM>1</VERSIONNUM>
<FIRST_NAME>MOHAMMAD BAQER</FIRST_NAME>
<SECOND_NAME>ZOLQADR</SECOND_NAME>
<UN_LIST_TYPE>Iran</UN_LIST_TYPE>
<REFERENCE_NUMBER>IRi.043</REFERENCE_NUMBER>
<LISTED_ON>2007-03-24</LISTED_ON>
<COMMENTS1>[Old Reference # I.47.D.7]</COMMENTS1>
<DESIGNATION>
<VALUE>General/IRGC officer</VALUE>
<VALUE>Deputy Interior Minister for Security Affairs</VALUE>
</DESIGNATION>
<LIST_TYPE>
<VALUE>UN List</VALUE>
</LIST_TYPE>
<LAST_DAY_UPDATED>
<VALUE>2014-12-17</VALUE>
</LAST_DAY_UPDATED>
<INDIVIDUAL_ALIAS>
<QUALITY>Good</QUALITY>
<ALIAS_NAME>
Mohammad Bakr Zolqadr; Mohammad Bakr Zolkadr; Mohammad Baqer Zolqadir;     Mohammad Baqer Zolqader
</ALIAS_NAME>
</INDIVIDUAL_ALIAS>
<INDIVIDUAL_ADDRESS/>
<INDIVIDUAL_DATE_OF_BIRTH/>
<INDIVIDUAL_PLACE_OF_BIRTH/>
<INDIVIDUAL_DOCUMENT/>
<SORT_KEY>Zolqadr</SORT_KEY>
<SORT_KEY_LAST_MOD>2014-06-18</SORT_KEY_LAST_MOD>
</INDIVIDUAL>

I need to access each of the values, blank or otherwise and put them into variables.
I've been trying all kinds of code here is a very basic example, but I can't seem to access the data
 foreach($xml->children() as $child)
 {
 echo $child->individuals->individual->dataid;
 }

A: You can loop over the INDIVIDUALS array and access member objects like this
foreach($xml->INDIVIDUALS->INDIVIDUAL as $node){
    echo $node->DATAID . PHP_EOL;
}


text:
Q: How to make bootstrap-ui datepicker and timepicker be inline? Is there a way to make bootstrap-ui components appear inline, like so:

I have tried various things but I can't get them all to align. Here is the Plunkr

      <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />

        <button type="button" class="btn btn-default" ng-click="open1()"></button>

UPDATE:
Have tried changing the uib-timepicker tag from div to span, but that breaks the datepicker component: https://plnkr.co/edit/CjBzCthVyoQAVooi5oR7?p=preview
UPDATE2:
To calrify, this question is about this library: https://angular-ui.github.io/bootstrap/
UPDATE3:
Updated the plunkr provided in the accepted answer with relative units: https://plnkr.co/edit/TaoVJZwCjh1uLyz3huk9?p=preview

A: *

*Change the last div tag to span tag.

*Add two new CSS classes:

*

*.buttonClass{ vertical-align:top; }

*.timeClass table:first-child { top:-35px; position:relative; }

*Add button class to span which holds the button,

*Add time class to span that holds time picker.


text:
Q: Show values for Stacked bar plot I would like to show the % values inside the stacked bar.
I have this dataframe: `df=pd.DataFrame(data=([[ 0.13214286,  0.13928571,  0.16      ,  0.13285714,  0.14571429, 0.14714286,  0.14285714], [ 0.11833333,  0.12666667,  0.14833333,  0.13833333,  0.145, 0.17166667,  0.15166667],[ 0.15666667,  0.15666667,  0.14333333,  0.11333333,  0.17, 0.12666667,  0.13333333],[ 0.13333333,  0.16166667,  0.16      ,  0.145     ,  0.14833333,
     0.12333333,  0.12833333], [ 0.1075    ,  0.135     ,  0.105     ,  0.1425    ,  0.1875  ,0.1525    ,  0.17 ],[ 0.13833333,  0.13888889,  0.12944444,  0.14722222,  0.16166667, 0.14611111,  0.13833333],
   [ 0.14714286,  0.145     ,  0.12571429,  0.13      ,  0.15285714,
     0.13714286,  0.16214286],[ 0.147     ,  0.147     ,  0.14      ,  0.154     ,  0.132 , 0.139     ,  0.141     ],[ 0.1445    ,  0.1325    ,  0.146     ,  0.129     ,  0.147 , 0.143     ,  0.158     ],[ 0.145     ,  0.14083333,  0.14583333,  0.13666667,  0.14666667, 0.13916667,  0.14583333],
   [ 0.12375   ,  0.1325    ,  0.14625   ,  0.14375   ,  0.1525    ,
     0.16125   ,  0.14      ], [ 0.142     ,  0.1545    ,  0.137     ,  0.1425    ,  0.169     ,  0.1265    ,  0.1285    ], [ 0.13730769,  0.14      ,  0.15307692,  0.13961538,  0.13846154,  0.15076923,  0.14076923]]),columns=[u'1.Fully agree', u'2.Agree', u'3.Neither agree nor disagree', u'4.Disagree', u'5.Strongly disagree',  u'6.Impossible to answer: not applicable to my work',
   u'7.I prefer not to answer'],index=[u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'H', u'I', u'J', u'K', u'L', u'M'])`

and I am plotting the data:
    likert_colors = ['green','lightgreen','lightyellow','orange','red','lightgrey', 'grey']
ax = df.plot.barh(stacked=True, edgecolor='none',color=likert_colors)

horiz_offset = 1.03
vert_offset = 1.
ax.grid(False)
ax.set_facecolor("white")
ax.legend(bbox_to_anchor=(horiz_offset, vert_offset))

getting this chart:


text:
Q: Maven deploy:file step: automatically deploy to snapshot or to release repository I have the following sections in my pom.xml
  <repositories>
<repository>
  <id>maven-booking-snapshots</id>
  <url>https://artifactory.booking.com/maven-booking-snapshots</url>
</repository>
<repository>
  <id>maven-booking-releases</id>
  <url>https://artifactory.booking.com/maven-booking-releases</url>
</repository>

<distributionManagement>
  <snapshotRepository>
      <id>maven-snapshots</id>
      <name>Snapshot Repository</name>
      <url>https://artifactory.com/maven-snapshots</url>
  </snapshotRepository>
  <repository>
      <id>maven-releases</id>
      <name>Release Repository</name>
      <url>https://artifactory.com/maven-releases</url>
  </repository>
</distributionManagement>

and
 <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
        <configuration>
          <relocations>
            <relocation>
              <pattern>com.google</pattern>
              <shadedPattern>com.shaded.google</shadedPattern>
            </relocation>
            <relocation>
              <pattern>io.netty</pattern>
              <shadedPattern>hidden.io.netty</shadedPattern>
            </relocation>
          </relocations>
          <shadedArtifactAttached>false</shadedArtifactAttached>
        </configuration>
      </execution>
    </executions>
  </plugin>

<plugin>
    <artifactId>maven-deploy-plugin</artifactId>
    <version>2.8.2</version>
    <executions>
    <execution>
      <id>deploy-nodeps</id>
        <goals>
          <goal>deploy-file</goal>
        </goals>
        <phase>deploy</phase>
        <configuration>
          <file>${basedir}/target/original-${project.artifactId}-${project.version}.jar</file>
          <groupId>${project.groupId}</groupId>
          <artifactId>${project.artifactId}</artifactId>
          <version>${project.version}</version>
          <classifier>nodeps</classifier>
          <url>${project.distributionManagement.repository.url}</url>
          <repositoryId>${project.distributionManagement.repository.id}</repositoryId>
        </configuration>
      </execution>
    </executions>
  </plugin>

When I run the mvn deploy:file the file is going to be uploaded always in the release repository and (I think) the problem is that the <repository> tag of the plugin points to project.distributionManagement.repository.url. At the same time, I cannot make it point to the project.distributionManagement.snapshotRepository because I would like that the deployment destination depends on the version of the pom. How can I achieve such flexibility in the run of the deploy plugin?


text:
Q: Why is the following line of code OK in VS2010 but not VS2012? Unity version 2.1.505.0 in both WPF projects. One in 2010 & other in 2012.
In 2010 fine but 2012 I get Error "The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments"???
return this.Container.Resolve<Shell>();

A: Needed to add using for the Unity namespace as well as Prism.UnityExtensions. Answer was here on StackOverflow.


text:
Q: Add template page from plugin - Wordpress I want to add page template from my plugin. So when user go to add new page, in "Template" drop-down menu should appear my template page from plugin. So user will be able to choose my template from plugin for new page.
Template file should be located in my plugin directory.
Is this possible?

A: Check out this well written article on the subject.  It's not a plugin in itself, but rather shows you how to write exactly what you are looking to do inside your own plugin:
http://www.wpexplorer.com/wordpress-page-templates-plugin/


text:
Q: Angular js table filter not working for nested objects I have array of object like -
$scope.objs = [
    {
        'name': 'test',
        'id': '1',
        'config': {
            'processID': 3,
            'hName': 'host'
        }
    },
    {
        'name': 'test2',
        'id': '12',
        'config': {
            'processID': 32,
            'hName': 'host2'
        }
    }
 ];

I have a table representation for it and I want to add filter on each column --

                Name

<input ng-model="search.name"  type="text" placeholder="filter by Name"/>

                ID

<input ng-model="search.id" type="text" placeholder="filter by ID"/>

                ProcessID

<input ng-model="search.config.processID"  type="text" placeholder="filter by pId"/>

                ProcessID

<input ng-model="search.config.hname"  type="text" placeholder="filter by hname"/>

                {{obj.name}}

                {{obj.id}}

                {{obj.config.processID}}

                {{obj.config.hName}}

            - END OF DATA -

It works good for name and ID , but gives some strange behaviour for nested objects like - config.hname and config.processID . for them it works for the very first time and after that it does not work.
Any Idea on this?

A: Well, AngularJS filters only work on arrays (array of objects in your case.) and not on objects. Refer this question


text:
Q: Security Codesigning Framework for iOS, missing Asn1 files? I am trying to do local receipt validation on my iOS application using the following code : https://gist.github.com/sazameki/3026845
However, there are includes in there
#import <Security/SecAsn1Coder.h>
#import <Security/SecAsn1Templates.h>
#import <Security/SecRequirement.h>

That I cannot process, even after adding Security.framework to my xCode project. All the SecAsn1 files are not present in the Security.framework that I'm adding to my project.
I did find the sources of everything I'm requiring here https://opensource.apple.com/source/libsecurity_asn1/libsecurity_asn1-29908/lib/ but there HAS to be a better way than just getting the source from there file after file ?
Any Apple / xCode expert that can give me a hand ? I'm starting to lose sanity over this issue :)
Thanks a bunch!

A: Ok my bad, I realized this was a MacOS sample code and not an iOS sample code.
It seems like these security functions are not available for iOS.
I'll find an alternative.


text:
Q: How to get react-router v4 "staticContext" working with async routes? After I implementing async routes (I use loadable-components) with my react SSR project. I found the staticContext won't work. If I use static route component instead of async component the staticContext works as expectation. Any suggestion for it?
Here's my NotFound page:

import React from 'react';
import Helmet from 'react-helmet';

import styles from './styles.scss';

type Props = { staticContext: Object };

export default ({ staticContext }: Props) => {
  // I assing the 404 status here
  if (staticContext) staticContext.status = '404';

  return (

      <Helmet title="Oops" />

Oops, Page was not found!

  );
};

Then I check the status from my server.js:

...

const staticContext = {};
      const AppComponent = (
        <Provider store={store}>
          {/* Setup React-Router server-side rendering */}
          <StaticRouter location={req.url} context={staticContext}>
            {renderRoutes(routes)}
          </StaticRouter>
        </Provider>
      );

      if (staticContext.url) {
        res.status(301).setHeader('Location', staticContext.url);
        res.end();

        return;
      }

      // Extract loadable state from application tree (loadable-components setup)
      getLoadableState(AppComponent).then(loadableState => {
        const head = Helmet.renderStatic();
        const assets = webpackIsomorphicTools.assets();
        const htmlContent = renderToString(AppComponent);
        const initialState = store.getState();
        const loadableStateTag = loadableState.getScriptTag();

        // I can't get the "404" error
        const status = staticContext.status === '404' ? 404 : 200;

...

react: 16.2.0
react-router: 4.2.2
node: 9.5.0


text:
Q: js works in ios 10 but not 9? I'm coding a page that uses js for accordions and tab switching, but it's not displaying on ios 9? It's works fine on desktop and on my ipad which uses ios 10. Media queries working fine?!? Please help!
This is my script:

I have cursor: pointer; but nothing.

A: I'm assuming you're using iOS 9 Safari or Chrome. iOS 9 Safari/Chrome don't support arrow functions. iOS 10 Safari/Chrome do.
None of your arrow functions need to be arrow functions, so to support earlier versions of iOS, just replace them with function functions. E.g., replace
$(document).ready(() => {

with
$(document).ready(function() {

...and so on.


text:
Q: Compiler error lnk2019 and c4930 using inheritance I'm having an issue compiling my code when I'm using inheritance. I've tried most of everything but no luck compiling
I first have an abstract or 'interface' class
class ImyBase
{
    public:
        ImyBase();
        ImyBase(....);
        virtual ~ImyBase();

        virtual void someFuncs() = 0;
        ....
};

Then I have a class that implements this class.
class myBase : public ImyBase
{
    public:
        myBase();
        myBase(....);
        virtual ~myBase();

        void someFuncs();
        ....
};

Then I have a wrapper class.
class myWrap
{
    public:
        myWrap();
        myWrap(....);
        virtual ~myWrap();

        void someFuncs();
        ....
};

Everything works good in the implementation at this point. But when I try to test the wrapper class, that's where I get the error LNK2019: unresolved external symbol "public: __thiscall ImyBase::ImyBase(void)" (??0ImyBase@@QAE@XZ) referenced in function "public: __thiscall myBase::myBase(void)" (??0myBase@@QAE@XZ)
int main(int argc, char* argv)
{
    myWrap wr;
}

Any help is appreciated! I know its gotta be a dum mistake somewhere...

A: You have no implementation for the base constructor. The options are defining the constructors in an implementation file or, if they're empty, in the class definition itself:
class ImyBase
{
    public:
        ImyBase() {};
        ImyBase(....) {};
        virtual ~ImyBase() {};
};

or mark them as default for C++11:
class ImyBase
{
    public:
        ImyBase() = default;
        ImyBase(....) = default;
        virtual ~ImyBase() = default;
};


text:
Q: Error on Cloud 9 While trying to install and run MEAN stack I have installed the mean stack with bower and grunt on cloud 9 server but every time I try to run:
gwenf1@basejump_voting:~/workspace $ grunt serve

I get the follwing errors:
Running "serve" task

Running "clean:server" (clean) task

Running "env:all" (env) task

Running "concurrent:server" (concurrent) task

Running "injector:scripts" (injector) task
Missing option `template`, using `dest` as template instead
Injecting js files (13 files)

Running "injector:css" (injector) task
Missing option `template`, using `dest` as template instead
Injecting css files (5 files)

Running "wiredep:target" (wiredep) task
client/index.html modified.
Loading "autoprefixer.js" tasks...ERROR
>> Error: Cannot find module 'caniuse-db/features-json/transforms2d'
Warning: Task "autoprefixer" failed. Use --force to continue.

Aborted due to warnings.

Execution Time (2015-08-31 04:28:36 UTC)
loading tasks      173ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 18%
serve               15ms  ▇▇ 2%
clean:server        26ms  ▇▇▇ 3%
env:all             12ms  ▇▇ 1%
concurrent:server   13ms  ▇▇ 1%
injector:scripts   103ms  ▇▇▇▇▇▇▇▇▇▇▇ 11%
injector:css        17ms  ▇▇ 2%
wiredep:target     613ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 63%
Total 976ms

gwenf1@basejump_voting:~/workspace $ grunt serve
Running "serve" task

Running "clean:server" (clean) task

Running "env:all" (env) task

Running "concurrent:server" (concurrent) task

Running "injector:scripts" (injector) task
Missing option `template`, using `dest` as template instead
Injecting js files (13 files)

Running "injector:css" (injector) task
Missing option `template`, using `dest` as template instead
Injecting css files (5 files)

Running "wiredep:target" (wiredep) task
Loading "autoprefixer.js" tasks...ERROR
>> Error: Cannot find module 'caniuse-db/features-json/transforms2d'
Warning: Task "autoprefixer" failed. Use --force to continue.

Aborted due to warnings.

I have tried installing different versions of everything and deleting the workspace and starting over.


text:
Q: How to create a menu in unity to purchase ammo for my weapons I am a student currently creating a zombie FPS game using Unity 3D and I simply want to when I press 'E' on the keyboard, I want a menu to pop up and show the prices of the ammo (I have a pistol9mm and an AK) and when I click on buy, the ammo is purchased and I have more ammo.
Is there any helpful suggestions on how I will approach this scenario please ?

A: So first and most importantly, you have to create the Menu where you are going to buy the ammo from, make the buttons and then script them in a way that when you press them they take money away from the player and then gives him ammo. A single button "Buy ammo" is enough and just a little panel on which the button should stay is needed. After making the menu work, go to the script where you check if the player has pressed the "E" key. Create a new Game Object which holds the Menu where you buy the ammo from and when checking if the player has pressed the "E" key, check if the menu is opened. If it is not, then open the menu, if it is opened, close it. Here is a simple way of doing it.
    public GameObject menu;
    private bool isOpen = false;

    void Update(){
        if(Input.GetKeyDown("E")){ //When "E" key is pressed
            if(isOpen == false){    //If the menu is closed, open it
                isOpen = true;
                menu.SetActive(true)
            }else if(isOpen == true){   //If the menu is opened, close it
                isOpen = false;
                menu.SeyActive(false);
            }
        }
    }

The way it works is, it either sets the menu to active or unactive when you press the "E" key and it's really simple too. Also when you are done with the Menu set it to active so it doesnt apear on the screen when starting the game, just so it will apear after pressing "E" and so players don't have to close it every time.
I hope i helped you, if you have any questions feel free to ask.


text:
Q: Element flickers before disappearing when hidden with .animate({width: 'hide'}), but only on Chrome This problem appears on Chrome/Chromium (on Linux and Windows): when I use JQuery to hide an element with .animate({width: 'hide'}), the element shrinks, then for a fraction of second goes back to it's original size, then disappears instantly.
I made a fiddle: http://jsfiddle.net/FyDWE/4/
On IE9 and Firefox everything works as expected.
Thanks in advance!

A: I wasn't able to come with a workaround (in the case that you must use width: 'hide') but I was able to locate what seems to me be a very strange browser bug when I edited the jQuery fx core to return at the flicker point.
Here is the jsfiddle:
http://jsfiddle.net/FyDWE/9/
When you leave mouse, the animation will start to shrink, and it suddenly resizes to full when it reaches it's end. Now this is your flicker source and it stops there because of the jQuery edit.
If you now edit the style attribute of the .options span element that was being animated you can see it has display: inline-block; overflow-x: hidden; overflow-y: hidden; width: 0px;
Now if you change the width to 1px, (display: inline-block; overflow-x: hidden; overflow-y: hidden; width: 1px; ) it will suddenly completely shrink.
So I think the flicker comes from this: the animation reaches 0px which means sudden fullresize in chrome as shown in the above jsfiddle, and then the element hides. When you try the linked jsfiddle in IE9, the flicker freeze state is normal even with width: 0px there is no black bar like there is in chrome.
edit:
Here's my workaround for the bug in case solution not using width: 'hide' is feasible:
http://jsfiddle.net/FyDWE/10/


text:
Q: I'm trying to install pycups on mac os using the treminal, but I'm getting "building wheel for pycups (setup.py) ... error" $pip install pycups
Collecting pycups
    Using cached pycups-2.0.1.tar.gz (62 kB)
Building wheels for collected packages: pycups
    Building wheel for pycups (setup.py) ... error
    ERROR: Command errored out with exit status 1:
    command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-
    install-_itolwzg/pycups_229a8ad4200041038747d41d5862ab4c/setup.py'"'"'; __file__='"'"'/tmp/pip-
    install-_itolwzg/pycups_229a8ad4200041038747d41d5862ab4c/setup.py'"'"';f=getattr(tokenize,
    '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
    '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-
    29ml6iuu
       cwd: /tmp/pip-install-_itolwzg/pycups_229a8ad4200041038747d41d5862ab4c/
    Complete output (165 lines):
    running bdist_wheel
    running build
    running build_ext
    building 'cups' extension
    creating build
    creating build/temp.linux-x86_64-3.6
    gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DVERSION="2.0.1" -
    I/usr/local/include/python3.6m -c cupsmodule.c -o build/temp.linux-x86_64-3.6/cupsmodule.o
    cupsmodule.c: In function 'cups_enumDests':
    cupsmodule.c:422: warning: implicit declaration of function 'cupsEnumDests'
    cupsmodule.c: In function 'cups_connectDest':
    cupsmodule.c:501: warning: implicit declaration of function 'cupsConnectDest'
    cupsmodule.c:508: warning: assignment makes pointer from integer without a cast
    cupsmodule.c: In function 'PyInit_cups':
    cupsmodule.c:919: error: 'HTTP_STATUS_ERROR' undeclared (first use in this function)
    cupsmodule.c:919: error: (Each undeclared identifier is reported only once
    cupsmodule.c:919: error: for each function it appears in.)
    .....
    error: command 'gcc' failed with exit status 1
    ----------------------------------------
    ERROR: Failed building wheel for pycups
    Running setup.py clean for pycups


text:
Q: Assosiate rects to specific window in pygame in my program i defined main screen. The program will blit new window by clicking on different btn.
i want to undestand if it possible to define many windows and associate to them objects coordinates according the new windows locations.
in other words if it possible to edit "The beginning of the axes" for the object related to new window
for example:

*

*screen display is with width of 1000 and height of 800.

*new window with width,height = 800,800

*screen.blit(new_window,100,0)

the new window will apeare from x0,y0 = 100,0 - x1,y1 = 900,800

*

*i want to create a rect in the new window but not according to screen cords but according to new_window cords where "The beginning of the axes" is the top left of that window.

i pasted the relavant lines for your review.
#before main loop start (this display updating by running in main loop)
screen = screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))

# after main loop start when btn clicked on it
new_window= pygame.Surface((w,h))

#in main loop i use
screen.blit(new_window,(x,y))

if i create a new rect as
window_rect = pygame.Rect(x,y,w,h)

its define x,y coordinates for window_rect according to screen coords and not for new window. how can i associate new rects to new window?(so the new rect coordinate will be acording to new_window)
Note: i know that i can draw on that new window with:
pygame.draw.rect(new_window,color,(window_rect)

in that way it useing the new window coordinate for draw. but i need to define the rect according to new window for other functions

A:
i want to create a rect in the new window but not according to screen cords but according to new_window cords where "The beginning of the axes" is the top left of that window.

Unfortunately, there is no such feature in Pygame. You have to compute the window coordinates yourself. You can do this with pygame.Rect.move.
e.g:: if you have a subwindow with the rectangle sub_window_rect and you have a rectangle inside the subwindow rect_in_sub_window:
sub_window_rect = pygame.Rect(100, 0, 800, 800)
rect_in_sub_window = pygame.Rect(10, 10, 100, 100)

rect_in_window = rect_in_sub_window.move(*sub_window_rect.topleft)

The top left coordinate of rect_in_window is (110, 10).
Converting from window coordinated to subwindow coordinates:
rect_in_sub_window = rect_in_window.move(
    -sub_window_rect.left, -sub_window_rect.top)


text:
Q: Que hace esta línea de código escrito en c#? foreach (var item in Matriz)
{
    caja += string.Format("Nombre: {0} App: {1} Apm: {2} tel: {3}", item[0], item[1], item[2], item[3]+ "\n");
}

Específicamente no entiendo que hacen las llaves {}

A: Recomendaria leer la documentacion
string.Format(String, Object[])
si lo hicieras verias que al tener un array no necesitas definir cada posicion, podrias haber usado
caja += string.Format("Nombre: {0} App: {1} Apm: {2} tel: {3}\n", item);

ya que al usar {x} estas indicando una posicion en la lista de items que asignas por parametro

A: Lo que hace esta linea es parecido que System.out.printf(); en java.
Entonces, el atributo itemes un array de 4 posiciones.
item[0] => es la posición 0 de item en sera Nombre: {0}
item[1] => es la posición 1 de item en sera App: {1}
item[2] => es la posición 2 de item en sera Apm: {2}
item[3] => es la posición 3 de item en sera tel: {3}
Y como es un foreach, puede rellenar un String (en este caso caja), de un array de Matriz. Un saludo.


text:
Q: Create sign out button in master page in ASP.Net I am trying to create a master page with a sign out button. And to clear session on sign out button, I need to wrap that button in a form tag. Pretty straight forward, right?
Problem is that the content page will have their own form tag as well. So, application crashes saying "page can have only one form".
Now, I need to figure out a way to have that sign out button make a server side call without using form tag. How can I achieve this?
As of now, I have two ideas in mind. First is to redirect to an intermediary log out page. Second is to wrap the whole master page in a form, so content page will never need a form tag. Is there a better way to acheive this?


text:
Q: Measure voltage and amperage drawn by an Arduino? so I'm in a green engineering class in high school, and my friend and I have been tasked with a special project, measuring the amount of power drawn by an arduino so that we can determine the energy efficiency of each person's project (automated model homes).
My plan is to run the DC wall power supply through a circuit that will determine the voltage and amperage drawn by the arduino from the DC wall power supply, and then output the power to the Arduino (where it was going originally. The big problem here is that I don't know the equivalent resistance of the Arduino, because it varies as the Arduino does different things (turns on motors, blinks lights, etc.).
As the output of this ammeter/voltmeter circuit I would like to have two leads that output an analog voltage that correlate to amperage and voltage, which I can then read from Arduino code.
The code is not the problem here (duh, this is an EE site), I just don't know enough about circuits to make an ammeter that has an analog output.
For voltage, I thought about just running the positive of the power supply to an analog pin with a 5MOhm resistor in between. Would this work?

A: The best way to do this would be like a real multimeter/ammeter measures current. Put a very low value shunt resistor (<1 ohm) in series with the DC power supply (cut the connection and connect it back together through a resistor). The only thing you have to watch out for in this scenario is that the higher your load, the greater the voltage drop across the shunt.
So, using Ohm's law:
V = IR
Assuming a 20 mA load through a 1 ohm shunt:
V = .02A * 1 ohm = .02mV
So, with a 20 mA load, the shunt drops 20mV. As you can see, using a 1 ohm shunt is particularly convenient because the voltage drop equals the current (20mA results in 20mV drop).
The Arduino has a voltage regulator on board, so as long as the voltage at the Arduino stays above about 6 volts everything should be fine. Keep in mind that this method measures ALL of the current used by the Arduino, including inefficiencies of the linear regulators and the current usage of the AVRs. However, for a rough figure of current consumption this is fine. Remember that power consumption will be the current through the shunt times the wall supply voltage (minus the voltage drop across the shunt, but that will probably be negligible). Since your wall supply voltage is known, you only need a lead showing current.
The fact that you're trying to measure this with an Arduino complicates the issue. You need a common ground between the DC power supply and your measuring Arduino. Depending on the Arduino's power source (if you connect both Arduinos to USB), that means you cannot just choose the more negative lead on the shunt to be ground (doing so would cause a short and probably some smoke). This means you need to design a differential amplifier using an Op-Amp.
This is fairly simple, but I highly recommend you simply use a multimeter to measure the voltage drop across the shunt. This will be both easier to implement and more accurate.


text:
Q: "Two Way Call communications" Private-voice-communication create-a-call Nexmo Number Using (php/Laravel/Voice API) Anybody help me for the following requirements.
i want to make call from web application(PHP/Laravel) to any mobile number from (purchased Nexmo Number). Its like two way communications call.
The scenario assume in the web application(PHP/Laravel) page display the call driver options placed the call icon.
Once customer click the call icon then call to driver number from (purchased Nexmo Number).
i have some doubts,
how the customer can able to speak with driver from web application once click the call icon ?.
Here we need any headphones or speaker connect with computer/laptop from web application once click the call icon to connect speak with driver mobile phone ?.
i checked with the nexmo voice API here one way communication only working fine for me.
For example, text to speech call works for me, the above voice API code run the call automatically reached to destination number from (purchased Nexmo Number).
    'api_key' => '',
    'api_secret' => '',
    'to' => '14083934444',
    'from' => '16169281703',
    'text' => 'Hi Good Morning. How are you. What about you.'
];
$url = 'https://api.nexmo.com/tts/json?' . http_build_query($params);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

In Nexmo, private-voice-communication create-a-call not clearly explained about "Two Way call communications". Kindly help me any one suggestion or provide the sample code using (php/Laravel/API) based to implement the private-voice-communication create-a-call "Two Way communications" from web application to mobile phone.
For marketplace scenarios such as food delivery or taxi and passenger communications, it is useful for users to be able to communicate with one another without exposing their phone numbers.
private-voice-communication


text:
Q: News Feed Database Design Efficiency Greetings All, I've seen similar questions asked before with no conclusive or tested answers.
I'm designing a News Feed system using PHP/MySQL similar to facebooks.  Seeing as this table could grow to be quite large -- any inefficiency could result in a significant bottleneck.
Example Notifications:
(Items in bold are linked objects)

User_A and USER_B commented on User_C's new album.
User_A added a new Vehicle to [his/her] garage.

Initially, I implemented this using excessive columns for Obj1:Type1 | Obj2:Type2 | etc..
It works but I fear it's not nearly scalable enough, now I'm looking to object serialization.
So, for example my new database is set up like so:
News_ID  |  User_ID  |                 News_Desc            |   Timestamp

  2643         904     {User904} and {User890} commented on     SomeTimestamp
                       {User222}'s new {Album724}.

Anything inside {'s represents data that would be serialized using JSON.
Is this a smart (efficient / scalable) way to move forward?
Will it be difficult to separate the serialized data from the rest of the string using regular expressions?

A: What happens if User890 deletes his/her comment? I think you need to be more atomic - possibly storing the type of action (comment) with the actioner (User890), then generate the actual story on the fly, with heavy caching. This would also help the issue of translation, if you extend your site to several markets/audiences.


text:
Q: Having to redeclare an int for a second for loop I am playing around on edabit.com C++ challenges to refresh myself and I was presented with a challenge where I needed to write a function that would, given a vector, return true if all even indices are even and all odd indices are odd. Otherwise return false. The logic and everything of the function was fine. I know there's a few ways to do this but came up with a (I think) creative solution where instead of running through one for loop with a check if the index is odd or even, I instead wrote two subsequent for loops that increment by two each. One starting at 0 and the other starting at 1. Once it finds a mismatch it returns false. Otherwise at the end it will return true. I am coming from JavaScript where you would not need to redeclare the index variable (if using var not let) but this code failed to compile:
bool isSpecialArray(std::vector<int> arr) {
    for(int i = 0; i < arr.size(); i = i + 2){
        if(arr[i] % 2 == 1){
            return false;
        }
    }

    for(i = 1; i < arr.size(); i = i + 2){
        if(arr[i] % 2 == 0){
            return false;
        }
    }

    return true;
}

Stating:
error: use of undeclared identifier 'i'
        for(i = 1; i < arr.size(); i = i + 2){
            ^

And of course declaring int in the second for loop cleared the error and the program executed as expected. I'm guessing this is due to garbage collection, but is there a specific rule in the standard that defines this? Or is this maybe a per compiler thing? My understanding of the garbage collection was that the variable once declared is not cleared from memory until is no longer being used in the current function it is defined in. Is this different due to the scope of the for loop, similar to JavaScript's let?

A: Firstly, JS and C++ have very different models of scopes, and JS is known (sorry) for its bad practices. In C++ the rule is more consistent: the variable is destroyed whenever the program exits the scope. That means that in this code:
for (int i = 0; ; ) {
}

the variable i is defined just for this scope, it cannot be reused in another (not nested) loop, is not seen elsewhere, and the name can be reused or redefined in the inner scopes. This gives you the advantage that it is much easier to control the data flaw and to have less side effects. So the solution for you is to declare another variable i in the second loop:
    for(int i = 1; i < arr.size(); i = i + 2){
        if(arr[i] % 2 == 0){
            return false;
        }
    }

As long as you are from the JS world I would give you more recommendations. First, do not pass the vector by value (unless you realize what you are doing). Pass it by reference or even better by const reference:
bool isSpecialArray(const std::vector<int> &arr) {
   // ...
}

Next, a potentially more efficient and more idiomatic way to increase the index is i += 2.
And the final observation: there is no "creativity" in your solution, but there are drawbacks. This code becomes less cache friendly, and this may be considered as a bad practice.

A: There is no garbage collection in C++, and even if there were, it wouldn't explain your error. The actual cause is simple: variables declared as part of a for loop go out of scope after the loop.

A: variable i in your program was declared inside a block or curly braces ({ }). So, variable i is a local variable which can be used only inside that block.
bool isSpecialArray(std::vector<int> arr) {
    int i;
    for(i = 0; i < arr.size(); i = i + 2){
        if(arr[i] % 2 == 1){
            return false;
        }
    }

    for(i = 1; i < arr.size(); i = i + 2){
        if(arr[i] % 2 == 0){
            return false;
        }
    }

    return true;
}

This is the correct way to do it.

A: c++ does not have garbage collection. Instead, it does deterministic destruction of objects such as i. The way the compiler does this is by cleaning up the object once the scope it's in has ended, and then not allowing you to use that object afterwards.
int main()
{
 {
  int i;
 } // scope of i ends

 cout << i; // error, can't access i here
}

for loops have their own scope, so in your example, the i in the first loop is not accessible in the second loop.


text:
Q: Maven 2 projects depend on one another I have 2 projects, employees and data. The projects represent entities linked to my db.
Each employee has a field linked to a table in data and so my employee pom.xml has a dependency for data. My problem resides here, every data is inserted by an employee and so data also has a dependency on employees. This results in a bi-directional dependency.
Is this possible in maven? My understanding of maven is that this would cause problems.
project employees
@Entity
@Table(name="employees", uniqueConstraints= {
        @UniqueConstraint(columnNames="idEmployees"),
        @UniqueConstraint(columnNames="idCardNumber"),
        @UniqueConstraint(columnNames="niNumber")
})
public class Employee {

@Id
@GeneratedValue
@Column(unique=true, nullable=false, updatable=false)
private int idEmployees;

//other class variables

@ManyToOne(cascade=CascadeType.PERSIST, fetch=FetchType.LAZY)
@JoinColumn(name="niCategoryId", nullable=false, updatable=false)
private NIData niCategory;

//constructors getter and setters
}

data project
@Entity
@Table(name="nidata", uniqueConstraints= {
        @UniqueConstraint(columnNames="idNiData")
})
public class NIData {

@Id
@GeneratedValue
@Column(unique=true, nullable=false, updatable=false)
private int idNiData;

//other class variables

@ManyToOne(cascade=CascadeType.PERSIST, fetch=FetchType.LAZY)
@JoinColumn(name="createdEmployeeId", nullable=false, updatable=false)
private Employee createdEmployee;

//constructors getter and setters
}

As you can see they depend on each other but I want them in different projects as they belong to different schemas. Also I plan to add other schemas that I may not want to expose in every part of the system I am designing but only parts of it.

A: It would be make much more sense to put all entity-related classes in a single Maven module. In this way, all classes can depend on each other. This will also centralize all persisted classes to be maintained in one project.
Indeed Maven does not allow circular dependencies since it would not know which module to build first.


text:
Q: How to find the original file through multiple symlinks? I've run into situations where symlinks point to other symlinks causing me to have to run multiple ls commands to try to trace where the base file is stored.  For example if I want to know the location of java program I run on centos I usually start with /bin/java and have to go 3-4 symlinks deep before I find the actual file's location.
Is there a simple clean command that will trace along all symlinks until it finds a real file and give me the location of the base file?

A: Use realpath, it will expand all symbolic links until a file target.
For example, for me:
> ls -al /usr/bin/java
lrwxrwxrwx 1 root root 22 Jul 13  2019 /usr/bin/java -> /etc/alternatives/java
> realpath /usr/bin/java
/usr/lib64/jvm/java-11-openjdk-11/bin/java

Also readlink alone would give the direct target, while readlink -f will give the final file:
> readlink /usr/bin/java
/etc/alternatives/java
> readlink -f /usr/bin/java
/usr/lib64/jvm/java-11-openjdk-11/bin/java


text:
Q: How to check if openssl or cryptopp is installed and use the library that actually exists in the system (is installed)? I wrote function that encrypts/decrypts a buffer (2 versions of the same function - first, with cryptopp, second - with openssl).
I would like to make something like this:
#if defined OPENSSL
   run_aes_openssl(...);
#elif defined CRYPTOPP
   run_aes_crytopp(...);
#else
    error(...);
#end

Is it possible?

A: It's not quite that simple. In order to find that a macro is defined, you have to include the header that defines that macro. And C doesn't have anything like "include foo.h iff it exists"; it has to exist otherwise there is a compilation error.
Normally this would be sorted out by a script that you run before compilation. Your script checks locations like /usr/include, /usr/local/include, etc., to see if the OpenSSL headers are there; and then it outputs a Makefile which contains in the CFLAGS -DHAVE_OPENSSL. Then your code can check for that macro.
This is quite a bit of hullabaloo, to keep things simple you could require the user to manually edit a file , e.g. distribute your project with something called user_config.h that the user is supposed to edit before compiling, to specify where they put OpenSSL and so on.
There is a preset system called GNU Autoconf which contains a script that checks your system for everything under the sun.  This has its advantages and disadvantages; it makes things easier for plebs downloading your source code, but it is bloaty and can be hard work for yourself.

A:
How to check if openssl or cryptopp is installed and use the library that actually exists in the system (is installed)?

If your application was built on the system it is running, then the code you have shown is OK. Presumably, the build system will detect both OpenSSL and Crypto++. In the case both are available, it looks like your code will favor OpenSSL.
If you application is built elsewhere and needs to check at runtime, then you will need dlopen, dlsym, dlclose and friends.
In the case of runtime checking, its probably best to build a dispatch table and call through it. For example, you might have a table with function pointers to your internal run_aes_openssl, run_aes_crytopp, etc.
Upon startup, you populate the table based on the results of dlopen. If you find OpenSSL, then you populate your table with the OpenSSL gear. If you find Crypto++, then you populate your table with the Crypto++ gear.

C++ can be painful to use with dlopen and friends because of name mangling. Worse, the mangling differs between distributions and runtime library versions. For example, here's a function to generate a private RSA key:
RSA::PrivateKey key;
key.GenerateRandomWithKeySize(prng, 1024);

And here's the corresponding function names on Mac OS X. Debian and Red Hat will likely be different.
$ nm cryptopp-test.exe | grep -i GenerateRandom | grep -i RSA
00000001000c7d80 T __ZN8CryptoPP21InvertibleRSAFunction14GenerateRandomERNS_21RandomNumberGeneratorERKNS_14NameValuePairsE
00000001000c8eb0 T __ZThn120_N8CryptoPP21InvertibleRSAFunction14GenerateRandomERNS_21RandomNumberGeneratorERKNS_14NameValuePairsE