text:
Q: How to de-attach an entity from a Context in Entity Framework? I use EF 4.1 with Repository and DbContext.. POCO with T4 template.
For every Repository I use a separate DbContext.
I need to update an object with has a related property, at the moment I receive this error
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

I suppose my problem is beacuse eventObj and candidate are created from different Repositories.
So i'm trying to solve the problem with this code, with no success.
My question?

*

*How do I get rid of this error?

*Is is possible remove the candidate from its context?
public void UpdateAddingCandidate(Event eventObj, Candidate candidate){
    Event updatedEvent = new Event();
    Candidate updatedCandidate = new Candidate();
    updatedEvent = eventObj;
    updatedCandidate = candidate;
    updatedEvent.Candidate = updatedCandidate;
    db.Entry(updatedEvent).State = EntityState.Modified;
}

EDIT
    public void UpdateAddingCandidate(Event eventObj, Candidate candidate)
    {
        /*
        db.Events.AsNoTracking();
        db.Candidates.AsNoTracking();
        */
        db.Entry(eventObj).State = EntityState.Detached;
        db.Entry(candidate).State = EntityState.Detached;

        Event updatedEvent = new Event();
        Candidate updatedCandidate = new Candidate();
        updatedEvent = eventObj;
        updatedCandidate = candidate;
        updatedEvent.Candidate = updatedCandidate;
        db.Entry(updatedEvent).State = EntityState.Detached;
        db.Entry(updatedEvent).State = EntityState.Modified;

    }

A: Instead of only using the repository pattern also use the Unit of Work pattern. That way you have 1 point for every entity you use.
Data/Contracts/IRepository.cs
namespace Data.Contracts
{
    public interface IRepository<T> where T : class
    {
        IQueryable<T> GetAll();
        T GetById(int id);
        void Add(T entity);
        void Update(T entity);
        void Delete(T entity);
        void Delete(int id);
}

Data/Contracts/IUnitOfWork.cs
namespace Data.Contracts
{
    ///
    /// Interface for the "Unit of Work"
    ///
    public interface IUnitOfWork
    {
        // Save pending changes to the data store.
        void Commit();

        // Repositories
        IRepository<Event> Events { get; }
        IRepository<Candidate> Candidates { get; }
    }
}

Data/EFRepository.cs
using System;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using Data.Contracts;

namespace Data
{
    ///
    /// The EF-dependent, generic repository for data access
    ///
    /// <typeparam name="T">Type of entity for this Repository.</typeparam>
    public class EFRepository<T> : IRepository<T> where T : class
    {
        public EFRepository(DbContext dbContext)
        {
            if (dbContext == null)
                throw new ArgumentNullException("dbContext");
            DbContext = dbContext;
            DbSet = DbContext.Set<T>();
        }

        protected DbContext DbContext { get; set; }

        protected DbSet<T> DbSet { get; set; }

        public virtual IQueryable<T> GetAll()
        {
            return DbSet;
        }

        public virtual T GetById(int id)
        {
            //return DbSet.FirstOrDefault(PredicateBuilder.GetByIdPredicate<T>(id));
            return DbSet.Find(id);
        }

        public virtual void Add(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
            if (dbEntityEntry.State != EntityState.Detached)
            {
                dbEntityEntry.State = EntityState.Added;
            }
            else
            {
                DbSet.Add(entity);
            }
        }

        public virtual void Update(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
            if (dbEntityEntry.State == EntityState.Detached)
            {
                DbSet.Attach(entity);
            }
            dbEntityEntry.State = EntityState.Modified;
        }

        public virtual void Delete(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
            if (dbEntityEntry.State != EntityState.Deleted)
            {
                dbEntityEntry.State = EntityState.Deleted;
            }
            else
            {
                DbSet.Attach(entity);
                DbSet.Remove(entity);
            }
        }

        public virtual void Delete(int id)
        {
            var entity = GetById(id);
            if (entity == null) return; // not found; assume already deleted.
            Delete(entity);
        }
    }
}

Data/UnitOfWork.cs
using System;
using Data.Contracts;
using Data.Helpers;
using Models;

namespace Data
{
    ///
    /// The "Unit of Work"
    ///     1) decouples the repos from the controllers
    ///     2) decouples the DbContext and EF from the controllers
    ///     3) manages the UoW
    ///
    /// <remarks>
    /// This class implements the "Unit of Work" pattern in which
    /// the "UoW" serves as a facade for querying and saving to the database.
    /// Querying is delegated to "repositories".
    /// Each repository serves as a container dedicated to a particular
    /// root entity type such as a <see cref="Url"/>.
    /// A repository typically exposes "Get" methods for querying and
    /// will offer add, update, and delete methods if those features are supported.
    /// The repositories rely on their parent UoW to provide the interface to the
    /// data layer (which is the EF DbContext in this example).
    /// </remarks>
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        public UnitOfWork(IRepositoryProvider repositoryProvider)
        {
            CreateDbContext();

            repositoryProvider.DbContext = DbContext;
            RepositoryProvider = repositoryProvider;
        }

        // Repositories
        public IRepository<Event> Events { get { return GetStandardRepo<Event>(); } }
        public IRepository<Candidate> Candidates { get { return GetStandardRepo<Candidate>(); } }

        ///
        /// Save pending changes to the database
        ///
        public void Commit()
        {
            //System.Diagnostics.Debug.WriteLine("Committed");
            DbContext.SaveChanges();
        }

        protected void CreateDbContext()
        {
            DbContext = new UnicornsContext();
        }

        protected IRepositoryProvider RepositoryProvider { get; set; }

        private IRepository<T> GetStandardRepo<T>() where T : class
        {
            return RepositoryProvider.GetRepositoryForEntityType<T>();
        }
        private T GetRepo<T>() where T : class
        {
            return RepositoryProvider.GetRepository<T>();
        }

        private UnicornsContext DbContext { get; set; }

        #region IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (DbContext != null)
                {
                    DbContext.Dispose();
                }
            }
        }

        #endregion
    }
}

Data/Helpers/IRepositoryProvider.cs
using System;
using System.Data.Entity;
using Data.Contracts;

namespace Data.Helpers
{
    ///
    /// Interface for a class that can provide repositories by type.
    /// The class may create the repositories dynamically if it is unable
    /// to find one in its cache of repositories.
    ///
    /// <remarks>
    /// Repositories created by this provider tend to require a <see cref="DbContext"/>
    /// to retrieve data.
    /// </remarks>
    public interface IRepositoryProvider
    {
        ///
        /// Get and set the <see cref="DbContext"/> with which to initialize a repository
        /// if one must be created.
        ///
        DbContext DbContext { get; set; }

        ///
        /// Get an <see cref="IRepository{T}"/> for entity type, T.
        ///
        /// <typeparam name="T">
        /// Root entity type of the <see cref="IRepository{T}"/>.
        /// </typeparam>
        IRepository<T> GetRepositoryForEntityType<T>() where T : class;

        ///
        /// Get a repository of type T.
        ///
        /// <typeparam name="T">
        /// Type of the repository, typically a custom repository interface.
        /// </typeparam>
        /// <param name="factory">
        /// An optional repository creation function that takes a <see cref="DbContext"/>
        /// and returns a repository of T. Used if the repository must be created.
        /// </param>
        /// <remarks>
        /// Looks for the requested repository in its cache, returning if found.
        /// If not found, tries to make one with the factory, fallingback to
        /// a default factory if the factory parameter is null.
        /// </remarks>
        T GetRepository<T>(Func<DbContext, object> factory = null) where T : class;

        ///
        /// Set the repository to return from this provider.
        ///
        /// <remarks>
        /// Set a repository if you don't want this provider to create one.
        /// Useful in testing and when developing without a backend
        /// implementation of the object returned by a repository of type T.
        /// </remarks>
        void SetRepository<T>(T repository);
    }
}

Data/Helpers/RepositoryProvider.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using Data.Contracts;

namespace Data.Helpers
{
    ///
    /// Provides an <see cref="IRepository{T}"/> for a client request.
    ///
    /// <remarks>
    /// Caches repositories of a given type so that repositories are only created once per provider.
    /// There should be a a new provider per client request.
    /// </remarks>
    public class RepositoryProvider : IRepositoryProvider
    {
        public RepositoryProvider(RepositoryFactories repositoryFactories)
        {
            _repositoryFactories = repositoryFactories;
            Repositories = new Dictionary<Type, object>();
        }

        ///
        /// Get and set the <see cref="DbContext"/> with which to initialize a repository
        /// if one must be created.
        ///
        public DbContext DbContext { get; set; }

        ///
        /// Get or create-and-cache the default <see cref="IRepository{T}"/> for an entity of type T.
        ///
        /// <typeparam name="T">
        /// Root entity type of the <see cref="IRepository{T}"/>.
        /// </typeparam>
        /// <remarks>
        /// If can't find repository in cache, use a factory to create one.
        /// </remarks>
        public IRepository<T> GetRepositoryForEntityType<T>() where T : class
        {
            return GetRepository<IRepository<T>>(
                _repositoryFactories.GetRepositoryFactoryForEntityType<T>());
        }

        ///
        /// Get or create-and-cache a repository of type T.
        ///
        /// <typeparam name="T">
        /// Type of the repository, typically a custom repository interface.
        /// </typeparam>
        /// <param name="factory">
        /// An optional repository creation function that takes a DbContext argument
        /// and returns a repository of T. Used if the repository must be created and
        /// caller wants to specify the specific factory to use rather than one
        /// of the injected <see cref="RepositoryFactories"/>.
        /// </param>
        /// <remarks>
        /// Looks for the requested repository in its cache, returning if found.
        /// If not found, tries to make one using <see cref="MakeRepository{T}"/>.
        /// </remarks>
        public virtual T GetRepository<T>(Func<DbContext, object> factory = null) where T : class
        {
            // Look for T dictionary cache under typeof(T).
            object repoObj;
            Repositories.TryGetValue(typeof(T), out repoObj);
            if (repoObj != null)
            {
                return (T)repoObj;
            }

            // Not found or null; make one, add to dictionary cache, and return it.
            return MakeRepository<T>(factory, DbContext);
        }

        ///
        /// Get the dictionary of repository objects, keyed by repository type.
        ///
        /// <remarks>
        /// Caller must know how to cast the repository object to a useful type.
        ///
This is an extension point. You can register fully made repositories here
        /// and they will be used instead of the ones this provider would otherwise create.

        /// </remarks>
        protected Dictionary<Type, object> Repositories { get; private set; }

        /// Make a repository of type T.
        /// <typeparam name="T">Type of repository to make.</typeparam>
        /// <param name="dbContext">
        /// The <see cref="DbContext"/> with which to initialize the repository.
        /// </param>
        /// <param name="factory">
        /// Factory with <see cref="DbContext"/> argument. Used to make the repository.
        /// If null, gets factory from <see cref="_repositoryFactories"/>.
        /// </param>
        /// <returns></returns>
        protected virtual T MakeRepository<T>(Func<DbContext, object> factory, DbContext dbContext)
        {
            var f = factory ?? _repositoryFactories.GetRepositoryFactory<T>();
            if (f == null)
            {
                throw new NotImplementedException("No factory for repository type, " + typeof(T).FullName);
            }
            var repo = (T)f(dbContext);
            Repositories[typeof(T)] = repo;
            return repo;
        }

        ///
        /// Set the repository for type T that this provider should return.
        ///
        /// <remarks>
        /// Plug in a custom repository if you don't want this provider to create one.
        /// Useful in testing and when developing without a backend
        /// implementation of the object returned by a repository of type T.
        /// </remarks>
        public void SetRepository<T>(T repository)
        {
            Repositories[typeof(T)] = repository;
        }

        ///
        /// The <see cref="RepositoryFactories"/> with which to create a new repository.
        ///
        /// <remarks>
        /// Should be initialized by constructor injection
        /// </remarks>
        private RepositoryFactories _repositoryFactories;
    }
}

Data/Helpers/RepositoryFactories.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using Data.Contracts;

namespace Data.Helpers
{
    ///
    /// A maker of Repositories.
    ///
    /// <remarks>
    /// An instance of this class contains repository factory functions for different types.
    /// Each factory function takes an EF <see cref="DbContext"/> and returns
    /// a repository bound to that DbContext.
    /// <para>
    /// Designed to be a "Singleton", configured at web application start with
    /// all of the factory functions needed to create any type of repository.
    /// Should be thread-safe to use because it is configured at app start,
    /// before any request for a factory, and should be immutable thereafter.
    /// </para>
    /// </remarks>
    public class RepositoryFactories
    {
        ///
        /// Return the runtime repository factory functions,
        /// each one is a factory for a repository of a particular type.
        ///
        /// <remarks>
        /// MODIFY THIS METHOD TO ADD CUSTOM FACTORY FUNCTIONS
        /// </remarks>
        private IDictionary<Type, Func<DbContext, object>> GetFactories()
        {
            return new Dictionary<Type, Func<DbContext, object>>
                {
                   //If you have an custom implementation of an IRepository<T>
                   //{typeof(IArticleRepository), dbContext => new ArticleRepository(dbContext)}
                };
        }

        ///
        /// Constructor that initializes with runtime repository factories
        ///
        public RepositoryFactories()
        {
            _repositoryFactories = GetFactories();
        }

        ///
        /// Constructor that initializes with an arbitrary collection of factories
        ///
        /// <param name="factories">
        /// The repository factory functions for this instance.
        /// </param>
        /// <remarks>
        /// This ctor is primarily useful for testing this class
        /// </remarks>
        public RepositoryFactories(IDictionary<Type, Func<DbContext, object>> factories)
        {
            _repositoryFactories = factories;
        }

        ///
        /// Get the repository factory function for the type.
        ///
        /// <typeparam name="T">Type serving as the repository factory lookup key.</typeparam>
        /// <returns>The repository function if found, else null.</returns>
        /// <remarks>
        /// The type parameter, T, is typically the repository type
        /// but could be any type (e.g., an entity type)
        /// </remarks>
        public Func<DbContext, object> GetRepositoryFactory<T>()
        {

            Func<DbContext, object> factory;
            _repositoryFactories.TryGetValue(typeof(T), out factory);
            return factory;
        }

        ///
        /// Get the factory for <see cref="IRepository{T}"/> where T is an entity type.
        ///
        /// <typeparam name="T">The root type of the repository, typically an entity type.</typeparam>
        /// <returns>
        /// A factory that creates the <see cref="IRepository{T}"/>, given an EF <see cref="DbContext"/>.
        /// </returns>
        /// <remarks>
        /// Looks first for a custom factory in <see cref="_repositoryFactories"/>.
        /// If not, falls back to the <see cref="DefaultEntityRepositoryFactory{T}"/>.
        /// You can substitute an alternative factory for the default one by adding
        /// a repository factory for type "T" to <see cref="_repositoryFactories"/>.
        /// </remarks>
        public Func<DbContext, object> GetRepositoryFactoryForEntityType<T>() where T : class
        {
            return GetRepositoryFactory<T>() ?? DefaultEntityRepositoryFactory<T>();
        }

        ///
        /// Default factory for a <see cref="IRepository{T}"/> where T is an entity.
        ///
        /// <typeparam name="T">Type of the repository's root entity</typeparam>
        protected virtual Func<DbContext, object> DefaultEntityRepositoryFactory<T>() where T : class
        {
            return dbContext => new EFRepository<T>(dbContext);
        }

        ///
        /// Get the dictionary of repository factory functions.
        ///
        /// <remarks>
        /// A dictionary key is a System.Type, typically a repository type.
        /// A value is a repository factory function
        /// that takes a <see cref="DbContext"/> argument and returns
        /// a repository object. Caller must know how to cast it.
        /// </remarks>
        private readonly IDictionary<Type, Func<DbContext, object>> _repositoryFactories;
    }
}

Now if you have this to use your UnitOfWork you can't simply call it because of all the dependencies, if you have used an IoC container before you know that you can simply resolve those dependencies. In my case I used Ninject so the code to set it up would be:
var kernel = new StandardKernel(); // Ninject IoC

kernel.Bind<RepositoryFactories>().To<RepositoryFactories>().InSingletonScope();
kernel.Bind<IRepositoryProvider>().To<RepositoryProvider>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();

Then for your pages you can add a base page class:
Web.BasePage.cs
namespace Web
{
    public abstract class BasePage : System.Web.UI.Page
    {
        // NOT NECESSARY TO DISPOSE THE UOW IN OUR CONTROLLERS
        // Recall that we let IoC inject the Uow into our controllers
        // We can depend upon on IoC to dispose the UoW for us
        protected IUnitOfWork Uow { get; set; }
    }
}

Or in the case of MVC you can add a base controller:
Web/Controllers/BaseController.cs
using System.Web.Mvc;

namespace Site.Controllers
{
    public abstract class BaseController : Controller
    {
        // NOT NECESSARY TO DISPOSE THE UOW IN OUR CONTROLLERS
        // Recall that we let IoC inject the Uow into our controllers
        // We can depend upon on IoC to dispose the UoW for us
        protected IUnitOfWork Uow { get; set; }
    }
}

Then in your code when you want to access you entities it is very easy. You can simply call the UnitOfWork which is available in every page and access the different repositories in it. Because they all share the same DbContext your problem ceases  to exist.

I have made a very simple example of the Unit of Work pattern with support of Ninject for the Inversion of Control.
In my example there is a ASP.NET Webforms AND and ASP.NET MVC4 example
The example is a single page site and every time you load the site it will add an Event to the example database and and Category to the Database, both with random names. (I needed something for the DB so I just made 2 simple pocos). After that the page will display everything in in both lists. Just look into the Mvc4/Controllers/HomeController.cs or WebForms/Default.aspx.cs.
Example on skydrive

A: This error is indeed thrown when the entity you're trying to update is attached to a different objectcontext than the context you're using to update it. Only one objectcontext can track an entity
You can detach objects from it's context by calling:
where context is the context the entity currently is attached to.
using (var context = new UnicornsContext())
{
    var unicorn = new Unicorn { Name = "Franky", PrincessId = 1};
    context.Entry(unicorn).State = EntityState.Detached;
    context.SaveChanges();
}

http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx
And in your implementation:
public void UpdateAddingCandidate(Event eventObj, Candidate candidate)
{
    db.Entry(candidate).State = EntityState.Detached;
    db.SaveChanges();

    eventObj.Candidate = candidate;
    db.Entry(eventObj).State = EntityState.Modified;
    db.SaveChanges();
}

A: Why do you create new instance of Event and Candidate? You could just change the state of these you already have them. If you share the same instance of ObjectContext accross your repositories, you can try to resolve these entities from context with ObjectStateManager.GetObjectStateEntry(string key) ObjectStateManager.


text:
Q: Can I use duplicate detection to cancel a scheduled Azure service bus message? I'm trying to come up with the best way to schedule a message for an Azure service bus queue or topic while leaving the option open for immediately sending a message instead of the scheduled message. I want to make sure I can protect myself against creating a duplicate message if I try to send the replacement message right at or after the scheduled time of the first message.
If you turn on duplicate detection and both messages have the same MessageId, does sending the second message prior to the scheduled enqueueing time of the first effectively cancel the scheduled message? Also, is it safe to assume that the second message will be ignored if the scheduled message is successfully queued first?

A:
If you turn on duplicate detection and both messages have the same MessageId, does sending the second message prior to the scheduled enqueueing time of the first effectively cancel the scheduled message?

I do a test with the following sample code, and find that the second message will be ignored.
var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

for (int i = 0; i < 2; i++)
{
    if (i == 0)
    {
        client.SendAsync(new BrokeredMessage("testmes1") { MessageId = "test1", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddSeconds(60) }).Wait();
    }
    else
    {
        client.SendAsync(new BrokeredMessage("testmes2") { MessageId = "test1" }).Wait();
    }

}

receive messages from the queue:
client.OnMessage(message =>
{
    Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
    Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
});

output:

If you'd like to cancel a scheduled Message, you can try to call CancelScheduledMessageAsync() method before that scheduled Message becomes active.
client.CancelScheduledMessageAsync(sequenceNumber).Wait();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asymptotic forms of Bessel function I want to replace Bessel functions by asymptotic forms, so the question is: can I find the best ones with help of Mathematica? And if it's possible, how can I do it?
Update
How can I get with Series the asymptotic form for the large real arguments? According to wiki (http://en.wikipedia.org/wiki/Bessel_function#Asymptotic_forms) it must be:
$\quad \quad J_n(z)=\sqrt{\frac{2}{\pi z}}  \left(e^{\left|
   \Im(z)\right| } O\left(\frac{1}{\left| z\right|
   }\right)+\cos \left(\frac{\pi  n}{2}-z-\frac{\pi
   }{4}\right)\right)$
Moreover, though this equation is true, a better approximations may be available for complex $z$. For example, $J_0(z)$, when z is near the negative real line, is approximated better by
$\quad \quad J_0(z) \sim{\sqrt{\frac{-2}{\pi z }}  \cos \left(z+\frac{\pi }{4}\right)}$ than by  $J_0(z) \sim{\sqrt{\frac{2}{\pi z }}  \cos \left(z-\frac{\pi }{4}\right)}$.
Instead of something like that, for the input
Series[BesselJ[0, x], {x, 100 + 3 I, 1}]

I get output of the form
SeriesData[x, Complex[100, 3],
  {BesselJ[0, Complex[100, 3]], -BesselJ[1,Complex[100, 3]]}, 0, 2, 1]

What am I doing wrong?

A: Your equation for the asymptotic form has a sign error. The correct result is produced by Mathematica:
Normal@Series[BesselJ[n, z], {z, Infinity, 0}]

$$\sqrt{\frac{2}{\pi }}
   \sqrt{\frac{1}{z}} \cos
   \left(\frac{\pi  n}{2}-z+\frac{\pi
   }{4}\right)$$

A version of this with additional corrections is found in the documentation, as I said in the comments. The other result for $z$ near the negative real line is actually just a special case of this, after you correct the sign error. Alternatively, you can do asymptotic expansions in other infinite directions like this:
Normal@Series[BesselJ[n, z], {z, DirectedInfinity[1 + I], 0}]

$$i \sqrt{\frac{2}{\pi }} e^{i \pi  n}
   \sqrt{\frac{1}{z}} \cos
   \left(\frac{\pi  n}{2}+z+\frac{\pi
   }{4}\right)$$


text:
Q: HTML5 webpage linking to another webpage on my hard drive I searched both in stackoverflow and online for an answer to my question but everything I seemed to find, did not work. I have two webpages both saved in the same folder on my local hard drive. I am trying to link the first webpage to the second webpage. I created the following link attempting to do this,

*Noah's First Day
Using Google Chrome, I get the following error message when I click on the link in my first webpage (attempting to link to the second webpage);
This webpage is not found
ERR_FILE_NOT_FOUND
I have tried changing my protocol from file:/// to ftp:/// to http:///. In each case, I get the same message. Can anyone help me in determining what I am doing wrong?
Thank you in advance!


text:
Q: replace data after last delimiter of every line using sed or awk I have a text file A.txt, all lines in which have the same number of fields separated by pipe | delimiter.  I need to replace , with | for the data after the last delimiter of each line.
Example:
1,2|3,4|5|6,7,8
1,8|4|6,5,3|4,5

Desired output, (only replace , with | after last delimiter):
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5

How to achieve this using sed or awk?

A: With awk:
awk 'BEGIN{FS=OFS="|"} gsub(",", "|", $NF)'

*

*BEGIN{FS=OFS="|"} sets both the input and output field delimiter as literal |

*gsub(",", "|", $NF) substitute all (gsub()) ,s with | in the last field ($NF)
Example:
$ awk 'BEGIN{FS=OFS="|"} gsub(",", "|", $NF)' <<<'1,2|3,4|5|6,7,8'
1,2|3,4|5|6|7|8

$ awk 'BEGIN{FS=OFS="|"} gsub(",", "|", $NF)' <<<'1,8|4|6,5,3|4,5'
1,8|4|6,5,3|4|5

A: $ cat ip.txt
1,2|3,4|5|6,7,8
1,8|4|6,5,3|4,5

with sed
$ sed -E ':a s/^(.*\|[^,]+),([^|]+)$/\1|\2/g; ta' ip.txt
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5

*

*:a and ta to loop sed command until there is a match found

*^(.*\|[^,]+) from start of line to | followed by non, characters. * and + will try to match as much as possible

*, match a comma

*([^|]+)$ after the comma, there should not be any | character till end of line

with perl
$ perl -F'\|' -lane '$F[-1] =~ tr/,/|/; print join "|",@F' ip.txt
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5

*

*-F'\|' split input line on | and save to @F array

*$F[-1] =~ tr/,/|/; for last element of array, replace all , with |

*print join "|",@F print the modified @F array with | as separator

And for some regex magic:
$ perl -pe 's/.*\|(*SKIP)(*F)|,/|/g' ip.txt
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5

*

*.*\|(*SKIP)(*F) skip the pattern until last |

*then replace all , with |


text:
Q: Moving a table over a background CSS I have tried to position #box1 under #table1    I try to move it however it doesn't move.  What am I doing wrong.
 I am new to css.
Edit: I put in my html
    <!DOCTYPE html>

    <title>Assignment 1</title>
    <meta charset="utf-8">

Name

Number

                WEB PAGE ELEMENTS

                Html
                Marks beginning and ending of a web page (closing tags needed)

                Head
                Used to enclose elements not apart of the main page (closing tags needed)

                Title
                Included in the <head> section, appears in the title bar of the browser (closing tags needed)

                Body
                Includes content that is visible in the browser (closing tag needed)

                Meta
                Allows passage of information about the page to user agents(self-closing tag)

This is the CSS along with my html.
I really want to get good at this and the assistance is appreciated.

A: I've made some modifications to clean up your code. Forewarning: you will need to dumb this down, do not directly give this assignment to your instructor as-is unless they are clueless about anything but the visual output (and if they are leave that college immediately and become self-taught!). Do not rely heavily on the CSS level 2 position property, if they haven't taught you about the CSS level 1 float then you're going to suffer a potentially permanent inability to code CSS competently.
If you want to learn how to use CSS correctly start with the basics...
http://www.jabcreations.com/web/css/nested-divisible-elements
That being said, this does what you wanted, the page content scrolls while the gigantic bordered division element doesn't.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<title>Assignment 1</title>

Name

Number

WEB PAGE ELEMENTS

WEB PAGE ELEMENTS

Html	Marks beginning and ending of a web page (closing tags needed)

Head	Used to enclose elements not apart of the main page (closing tags needed)

Title	Included in the <head> section, appears in the title bar of the browser (closing tags needed)

Body	Includes content that is visible in the browser (closing tag needed)

Meta	Allows passage of information about the page to user agents(self-closing tag)


text:
Q: Removing a GET-Attribute in DJANGO request variable In my request variable I have GET: <QueryDict: {'order_by': ['id'], 'del': ['11']}>
How can I remove the 'del':['11']?
I tried several things to delete the 'del'. I think the delattr is maybee the right way but e.g. with delattr(request.GET,'del') I got an error message.


text:
Q: Optimizing loop I'm trying to implement a tool that groups certain strings based on the lemmas of their words. During the initialization I make a dictionary for each possible group containing a list of words that would group into this key. This is what I have so far:
public Dictionary<string, HashSet<string>> Sets { get; set; }

private void Initialize(IStemmer stemmer)
{
    // Stemming of keywords and groups
    var keywordStems = new Dictionary<string, List<string>>();
    var groupStems = new Dictionary<string, List<string>>();

    foreach (string keyword in Keywords)
    {
        keywordStems.Add(keyword, CreateLemmas(keyword, stemmer));
        foreach (string subset in CreateSubsets(keyword))
        {
            if (subset.Length > 1 && !groupStems.ContainsKey(subset))
            {
                groupStems.Add(subset, CreateLemmas(subset, stemmer));
            }
        }
    }

    // Initialize all viable sets
    // This is the slow part
    foreach (string gr in groupStems.Keys)
    {
        var grStems = groupStems[gr];
        var grKeywords = new HashSet<string>((from kw in Keywords
                                                where grStems.All(keywordStems[kw].Contains)
                                                select kw));
        if (grKeywords.Count >= Settings.MinCount)
        {
            Sets.Add(gr, grKeywords);
        }
    }
}

Is there any way that I can speed the bottleneck of this method up?

A: The answer of @mjwills is a good idea. It seems likely that this is the most expensive operation:
var grKeywords = new HashSet<string>((
  from kw in Keywords
  where grStems.All(keywordStems[kw].Contains)
  select kw));

The suggestion is to optimize the Contains by taking advantage of the fact that the stems are a set.  But if they're a set then why are we repeatedly asking for containment at all?  They're a set; do set operations. The question is "what are the keywords such that every member of the grStem set is contained within the keyword's stem set". "Is every member of this set contained in that set" is the subset operation.
var grKeywords = new HashSet<string>((
  from kw in Keywords
  where grStems.IsSubsetOf(keywordStems[kw])
  select kw));

The implementation of IsSubsetOf is optimized for common scenarios like "both operands are sets". And it takes early outs; if your group stems set is larger than the keyword stem set then you don't need to check every element; one of them is going to be missing. But your original algorithm checks every element anyways, even when you could bail early and save all that time.

A: And again @mjwills has a good idea which I'll suggest some possible improvements to. The idea here is to execute the query, cache the results in an array, and only later realize it as a hash set, if necessary:
foreach (var entry in groupStems)
{
    var grStems = entry.Value;
    var grKeywords = (WHATEVER).ToArray();
    if (grKeywords.Length >= Settings.MinCount)
        Sets.Add(entry.Key, new HashSet<string>(grKeywords));
}

First: I actually doubt that avoiding the unnnecessary hash set construction by replacing it with unnecessary array constructions is a win. Measure it and see.
Second: ToList can be faster than ToArray because a list can be constructed before you know the size of the query result set. ToArray basically has to do a ToList first, and then copy the results into an exactly-sized array. So if ToArray is not a win, ToList might be. Or not. Measure it.
Third: I note that the whole thing can be rewritten into a query should you prefer that style.
var q = from entry in groupStems
        let grStems = entry.Value
        let grKeywords = new HashSet<string>(WHATEVER)
        where grKeywords.Count >= Settings.MinCount
        select (entry.Key, grKeywords);
var result = q.ToDictionary( ... and so on ... )

That's probably not faster, but it might be easier to reason about.

A: One suggestion would be to change:
var keywordStems = new Dictionary<string, List<string>>();

to:
var keywordStems = new Dictionary<string, HashSet<string>>();

That should have an impact due to your later Contains call:
var grKeywords = new HashSet<string>((from kw in Keywords
                                                where grStems.All(keywordStems[kw].Contains)
                                                select kw));

because Contains is generally faster on a HashSet than a List.
Also consider changing:
foreach (string gr in groupStems.Keys)
{
    var grStems = groupStems[gr];
    var grKeywords = new HashSet<string>((from kw in Keywords
                                            where grStems.All(keywordStems[kw].Contains)
                                            select kw));
    if (grKeywords.Count >= Settings.MinCount)
    {
        Sets.Add(gr, grKeywords);
    }
}

to:
foreach (var entry in groupStems)
{
    var grStems = entry.Value;
    var grKeywords = (from kw in Keywords
                                          where grStems.All(keywordStems[kw].Contains)
                                          select kw).ToArray();
    if (grKeywords.Length >= Settings.MinCount)
    {
        Sets.Add(entry.Key, new HashSet<string>(grKeywords));
    }
}

By shifting the HashSet initialization (which is relatively expensive compared to initializing an Array) into the if statement then you may improve performance if the if is entered relatively rarely (in your comments you state it is entered roughly 25% of the time).


text:
Q: Reload payment methods when change address field is there any way to reload the payment Methods when change Address field.
for example if the customer change the Region i want the payment methods to reloaded.
as we want to make COD not working in Alaska. "Hide COD when select Alaska".


text:
Q: Adding Gstreamer support to an android NDK project I've installed the latest android SDK bundle as well as the latest android NDK on windows 7.
I've set up my environment and am able to run the hellojni example from the NDK installation package.
But when i try to add Gstreamer support according to the creating new projects section of the gstreamer android tutorial page, I get this error when i try to build my project:
GStreamer      : [COMPILE] => gst-build/gstreamer_android.c
gst-build/gstreamer_android.c:1:17: fatal error: jni.h: No such file or directory
compilation terminated.
E:/GstreamerAndroid/sdk/share/gst-android/ndk-build//gstreamer.mk:167: recipe for
target `gst-build/gstreamer_android.o' failed
make: *** [gst-build/gstreamer_android.o] Error 1

I tried a few solutions such as setting my path variable to the jni.h in NDK (eg. ndkr8e\platforms\android-14\arch-arm\usr\include) but nothing works.
Can anyone suggest any other solutions?
EDIT: As suggested my iljan, i downloaded an older version of the android NDK (r8d), and i got my project to compile. But i don't understand whether the problem was from my side or a bug in the NDK version. Any thoughts?

A: The same problem for me with the NDK version r8e:
I have set up the environment (eclipse, android sdk, ndk, cygwin) and successfuly compiled the hello-jni. But the Gstreamer Tutorial1 won't compile.
My NDK install path was "C:\android\android-ndk-r8e"
But I was lucky enough to have previous ndk installed elsewhere on my disk, so I just copied it next to the never install, all files from:
"C:\Program Files\Android\ndk\android-ndk-r8d" to "C:\android\android-ndk-r8d" and changed NDK location path in Eclipse: Window->Preferences->Android->NDK to this new folder.
Voila! It compiles now.

A: Following the comment to this issue, seems that adding
...
LOCAL_LDLIBS := -llog

SYSROOT := /opt/android-ndk-r8e/platforms/android-14/arch-arm/

include $(BUILD_SHARED_LIBRARY)
...

all work fine.


text:
Q: Making a countdown timer in C++ I have a console application that is intended to only run on windows. It is written in C++. Is there any way to wait 60 seconds (and show remaining time on screen) and then continue code flow?
I've tried different solutions from the internet, but none of them worked. Either they don't work, or they don't display the time correctly.

A: //Please note that this is Windows specific code
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
    int counter = 60; //amount of seconds
    Sleep(1000);
    while (counter >= 1)
    {
        cout << "\rTime remaining: " << counter << flush;
        Sleep(1000);
        counter--;
    }
}

A: You can use sleep() system call to sleep for 60 seconds.
You can follow this link for how to set 60 seconds timer using system call Timer in C++ using system calls.

A: possible use Waitable Timer Objects with perion set to 1 second for this task. possible implementation
VOID CALLBACK TimerAPCProc(
                           __in_opt  LPVOID /*lpArgToCompletionRoutine*/,
                           __in      DWORD /*dwTimerLowValue*/,
                           __in      DWORD /*dwTimerHighValue*/
                           )
{
}

void CountDown(ULONG Seconds, COORD dwCursorPosition)
{
    if (HANDLE hTimer = CreateWaitableTimer(0, 0, 0))
    {
        static LARGE_INTEGER DueTime = { (ULONG)-1, -1};//just now
        ULONGLONG _t = GetTickCount64() + Seconds*1000, t;
        if (SetWaitableTimer(hTimer, &DueTime, 1000, TimerAPCProc, 0, FALSE))
        {
            HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
            do
            {
                SleepEx(INFINITE, TRUE);
                t = GetTickCount64();
                if (t >= _t)
                {
                    break;
                }
                if (SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition))
                {
                    WCHAR sz[8];
                    WriteConsoleW(hConsoleOutput,
                        sz, swprintf(sz, L"%02u..", (ULONG)((_t - t)/1000)), 0, 0);
                }
            } while (TRUE);
        }
        CloseHandle(hTimer);
    }
}
    COORD dwCursorPosition = { };
    CountDown(60, dwCursorPosition);

A: this might be of some help, it's not entirely clear what the question is but this is a countdown timer from 10 seconds, you can change the seconds and add minutes as well as hours.
#include <iomanip>
#include <iostream>
using namespace std;
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
  #endif
 int main()
 {
   for (int sec = 10; sec < 11; sec--)
 {
      cout << setw(2) << sec;
      cout.flush();

      sleep(1);
      cout << '\r';
      if (sec == 0)
      {
      cout << "boom" << endl;
      }
      if (sec <1)
      break;
    }
  }

A: In c++ you can use countdown. please go through with the following logic which will allow you to show remaining time on the screen.
for(int min=m;min>0;min--)  //here m is the total minits as per ur requirements
{
for(int sec=59;sec>=;sec--)
{
sleep(1);                   // here you can assign any value in sleep according to your requirements.
cout<<"\r"<<min<<"\t"<<sec;
}
}

if you need more help on this then please follow the link here
Hope it will work, please let me know that it is working in your case or not? or if you need any help.
Thanks!


text:
Q: How to use variables from another class file This is code inside Proizvod.cs file
namespace mateo_zadatak
{
    class Proizvod
    {

        public string Šifra = "šifra";
        public string Naziv = "naziv";
        public string Proizvođač = "proizvođač";
        public float Cijena;
        public int Količina;
        private float Ukupno;
        private int Popust;
        private float UkupnoPopust;

        private void variable()
        {
           Ukupno = Cijena * Količina;
           {
              if (Količina < 10)
              {
                 Popust = 0;
              }
              else if (Količina > 9 && Količina < 31)
              {
                 Popust = 5;
              }
              else Popust = 10;
           }

        }
    }
}

I have to use this variables in Form1.cs file , because i will need some calculations from datagrid. How to connect those two files?

A: A Form is just a class - Add public properties/members to the Form and access them from a reference to the form.

A: Make your class public, and make sure you include Proizvod.cs file into your project or add a reference to it from your project.

A: There are no "Global" variables in C# but what you can do is create a new Class with Static variables and assign/use them.  For example:
public static class GlobalVariables
{
    public static int IntVariable;
    public static string StringVariable;
}

And then you can reference them as GlobalVariables.IntVariable and GlobalVariables.StringVariable.

A: You can use public properties instead of variables from another class

A: Perhaps I'm missing something, but:
public class Form1 : ...
{
    public Proizvod Foo;

    Form1()
    {
        Foo = new Proizvod();
    }

    SomeMethod()
    {
        MessageBox.Show(Foo.Naziv);
    }
}


text:
Q: Bitwise Command Make bad access error I'm coding an application to hide an image information into another image! I do that by removing 4 low level bits from the first image and adding 4 high level bits from second image!
Here is my code:
    CGImageRef publicImage = _publicImageView.image.CGImage;
CFDataRef thePublicData;
thePublicData = CGDataProviderCopyData(CGImageGetDataProvider(publicImage));
UInt8 *publicPixelData = (UInt8 *) CFDataGetBytePtr(thePublicData);
int publicDataLength = CFDataGetLength(thePublicData);

//__________________________________________________________________________

CGImageRef secretImage = _secretImageView.image.CGImage;
CFDataRef theSecretData;
theSecretData = CGDataProviderCopyData(CGImageGetDataProvider(secretImage));
UInt8 *secretPixelData = (UInt8 *) CFDataGetBytePtr(theSecretData);
int secretDataLength = CFDataGetLength(theSecretData);

int red = 0;
int green = 1;
int blue = 2;

for (int index = 0 ; index < publicDataLength && index < secretDataLength; index +=4) {

    uint pRed = publicPixelData [index + red] % 0x10;
    publicPixelData [index + red] -= pRed;

    uint sRed = secretPixelData [index + red] / 0x10;
    publicPixelData[index + red] += sRed;

    uint pGreen = publicPixelData [index + green] % 0x10;
    publicPixelData [index + green] -= pGreen;

    uint sGreen = secretPixelData [index + green] / 0x10;
    publicPixelData[index + green] += sGreen;

    uint pBlue = publicPixelData [index + blue] % 0x10;
    publicPixelData [index + blue] -= pBlue;

    uint sBlue = secretPixelData [index + blue] / 0x10;
    publicPixelData[index + blue] += sBlue;

}

CGContextRef context;
context = CGBitmapContextCreate(publicPixelData,
                                CGImageGetWidth(publicImage),
                                CGImageGetHeight(publicImage),
                                8,
                                CGImageGetBytesPerRow(publicImage),
                                CGImageGetColorSpace(publicImage),
                                kCGImageAlphaPremultipliedLast);

CGImageRef newCGImage = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newCGImage];

CGContextRelease(context);
CFRelease(thePublicData);
CGImageRelease(newCGImage);

_hideEffectImageView.image = newImage;

To recover Second image, I shift the bits of "__hideEffectImageView" data to high level place!
Here is this code:
    CGImageRef stganoImage = _hideEffectImageView.image.CGImage;
CFDataRef stganoData;
stganoData = CGDataProviderCopyData(CGImageGetDataProvider(stganoImage));
UInt8 *steganoPixelData = (UInt8 *) CFDataGetBytePtr(stganoData);
int publicDataLength = CFDataGetLength(stganoData);

   //__________________________________________________________________________
 //   CGImageRef secretImage;
 //   CFDataRef   theSecretData;
 //   UInt8 *secretPixelData = (UInt8 *)CFDataGetBytePtr(stganoData);

    int red = 0;
    int green = 1;
    int blue = 2;

    for (int index = 0 ; index < publicDataLength; index +=4) {

        steganoPixelData [index + red] = steganoPixelData [index + red] << 0x4 ;
        steganoPixelData [index + green] = steganoPixelData [index + red] << 0x4 ;
        steganoPixelData [index + blue] = steganoPixelData [index + red] << 0x4 ;
    }

    CGContextRef context;
    context = CGBitmapContextCreate(steganoPixelData,
                                    CGImageGetWidth(stganoImage),
                                    CGImageGetHeight(stganoImage),
                                    8,
                                    CGImageGetBytesPerRow(stganoImage),
                                    CGImageGetColorSpace(stganoImage),
                                    kCGImageAlphaPremultipliedLast);

    CGImageRef newCGImage = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:newCGImage];

    CGContextRelease(context);
    CFRelease(stganoData);
    CGImageRelease(newCGImage);

    _recoverSecretImage.image = newImage;

In some images I get the "EXC_BAD_ACCESS(Code = 2" and Address ...) in the line with code "steganoPixelData [index + red] = steganoPixelData [index + red] << 0x4 ;"
I need to know Why this error appears in some of images and how can I fix it.
So thanks...

A: Something in this is probably nil. There is most possible explanation. Please log out to the console your steganoPixelData. I'm pretty sure that can be nil, because your operation is allowed and you've got only one data structure in this equation: steganoPixelData[index + red] <<= 0x4
Maybe your image is nil? Check that. Something is probably deallocated.


text:
Q: Learning C++, looking for a clarification on this project from a book The goal here was to create a program that found and output all the prime numbers between 1 and 100. I've noticed I have a tendency to complicate things and create inefficient code, and I'm pretty sure I did that here as well. The initial code is mine, and everything that I've put between the comment tags is the code given in the book as a solution.
// Find all prime numbers between 1 and 100

#include <iostream>
#include <cmath>
using namespace std;

    int main()
    {
        int counter; // loop counter
        int count_two; // counter for second loop
        int val; // equals the number of count, used in division to check for primes
        bool check;

        check = true;

        for(counter = 1; counter <= 100; counter++){
            val = counter;
                for(count_two = 2; count_two <= 9; count_two++){
                    if((val % count_two) == !(check)){
                        cout << val << " is a prime number.\n";
                }
          }
    }
    return 0;
}
// program didn't work properly because of needless complication; all that needs to be checked for is whether a number is divisible by two

/*
*********correct code***********
#include <iostream>
using namespace std;
int main()
{
    int i, j;
    bool isprime;
    for(i=1; i < 100; i++) {
        isprime = true;
    // see if the number is evenly divisible
    for(j=2; j <= i/2; j++)
    // if it is, then it is not prime
        if((i%j) == 0) isprime = false;
        if(isprime) cout << i << " is prime.\n";
}
return 0;
}
********************************
*/

From what I can gather, I was on a reasonably correct path here. I think I complicated things with the double loop and overuse of variables, which probably led to the program working incorrectly -- I can post the output if need be, but it's certainly wrong.
My question is basically this: where exactly did I go wrong? I don't need somebody to redo this because I'd like to correct the code myself, but I've looked at this for a while and can't quite figure out why mine isn't working. Also, since I'm brand new to this, any input on syntax/readability would be helpful as well. Thanks in advance.

A: As it is, your code says a number is prime if it is divisible by any of the numbers from 2 to 9. You'll want a bool variable somewhere to require that it's all and not any, and you'll also need to change this line:
if((val % count_two) == !(check)){

Since check = true, this resolves as follows:
if ((val % count_two) == !true){

and
if ((val % count_two) == false){

and
if ((val % count_two) == 0){

(Notice how the value false is converted to 0. Some languages would give a compile error here. C++ converts it into an integer).
This in fact does the opposite of what you want. Instead, write this, which is correct and clearer:
if (val % count_two != 0) {

Finally, one thing you can do for readability (and convenience!) is to write i, j, and k instead of counter, count_two, and count_three. Those three letters are universally recognized by programmers as loop counters.

A: In addition to the points made above:

*

*You seemed to think you didn't need to have 2 loops. You do need them both.

*Currently, in your code, the upper range of the inner loop is in-dependent on the value of your outer loop. But this is not correct; you need to test divisibility up the the sqrt(outer_loop_value). You'll note in your "correct" code they use half of the outer_loop_value - this could be a performance trade off but strictly speaking you need to test up to sqrt(). But consider that your outer loop was up to 7, your inner loop is testing division all the way up to 9 and 7 is in that range. Which means 7 would be reported as not prime.

*In your "correct" code the indenting makes the code harder to interpret. The inner for loop only has a single instruction. That loop loops through all possible divisors. This is unnecessary it could break out at the first point that the mod is zero. But the point is that the if(isprime) cout << i << " is prime.\n"; is happening in the outer loop, not the inner loop. In your (un-commented) code you have put that in the inner loop and this results in multiple responses per outer loop value.

*Stylistically there is no need to copy the counter into a new val variable.


text:
Q: C code retaining chars from prior setting I've got a bit of C code that is running in an Objective-C application. I snagged this code off the internet.
static void extract_app_name(const char *all_arguments, char **app_name) {
    char *full_path, *app_end, *app_begin; //, *app_name_temp;
    size_t diff;

    if (all_arguments == NULL || app_name == NULL) {
        return;
    }

    full_path = (char*)all_arguments + sizeof(int);

    app_end = strcasestr(full_path, ".app");
    if (app_end == NULL) {
        app_begin = strrchr(full_path, '/');
        if (app_begin != NULL) {
            *app_name = malloc(app_begin+1);
            *app_name = strdup(app_begin+1);
        } else {
            *app_name = strdup(full_path);
        }
    } else {
        app_begin = app_end;
        while (*(--app_begin) != '/') {}
        diff = app_end - app_begin;
        char *app_name_temp[diff]; // = malloc(diff);
        *app_name_temp = malloc(diff);
        *app_name = malloc(diff);
        strncpy(*app_name_temp, app_begin+1, diff-1);
        app_name_temp[diff]='\0';
        app_name = strcpy(*app_name, *app_name_temp);
    }
}

The intent of this code is to extract the application name from a full path. If the application is named with a .app extension, it pulls the name from whatever proceeds the .app.
For example, the following:
extract_app_name("/Applications/Google Chrome.app/Contents/Versions/16.0.912.63/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper", &app_name);
NSLog(@"First App is: %s", app_name);

extract_app_name("/System/Library/Frameworks/QuickLook.framework/Resources/quicklookd.app/Contents/MacOS/quicklookd", &app_name);
NSLog(@"Next App is: %s", app_name);

extract_app_name("/System/Library/CoreServices/Dock.app/Contents/XPCServices/com.apple.dock.extra.xpc/Contents/MacOS/com.apple.dock.extra", &app_name);
NSLog(@"Next App is: %s", app_name);

extract_app_name("/Applications/Tiny", &app_name);
NSLog(@"Next App is: %s", app_name);

Should output this:
First App is: Google Chrome
Next App is: quicklookd
Next App is: Dock
Next app is: Tiny

Generally, that's correct. But if I run the app 4-5 times back to back, my output will sometimes not always work out. Sometimes the second app which should output quicklookd, will actually dump quicklookdome (it retains part of the first app's name).
I suspect it has to do with the variable not being initialized properly and retaining what's already at that spot in memory. I just don't know C well enough to pin-point it.

A: Here it is, fixed and simplified:
    static void extract_app_name(const char *all_arguments, char **app_name) {
        char *full_path, *app_end, *app_begin; //, *app_name_temp;
        size_t diff;

        if (all_arguments == NULL || app_name == NULL) {
            return;
        }

        full_path = (char*)all_arguments + sizeof(int);

        app_end = strcasestr(full_path, ".app");
        if (app_end == NULL) {
            app_begin = strrchr(full_path, '/');
            if (app_begin != NULL)
                *app_name = strdup(app_begin+1);
            else
                *app_name = strdup(full_path);
        } else {
            app_begin = app_end;
            while (*(--app_begin) != '/') {}
            diff = app_end - app_begin;
            *app_name = malloc(diff);
            strncpy(*app_name, app_begin+1, diff-1);
        }
    }

Note that your code has a memory leak. The caller to extract_app_name should free the string when it's done with it.


text:
Q: nested selectors with & (amperstand) are not working I have the following code
.myclass {
  &::-webkit-etc {...}
  &::-moz-etc {...}
}

the properties (...) are the same for both selectors so I did
.myclass {
  &::-webkit-etc,
  &::-moz-etc {...}
}

the first version works fine but for some reason the second one doesn't.
I'm using the scss in my JSX like this
import css from './styles.scss'

...

<div className={css.myclass}>...


text:
Q: Subclass inheriting variables from Parent (Python) I'm a little confused as to how to directly inherit variables from a parent class' __init__ function. For instance, I have the following:
class BaselineModels:
    def __init__(self):
        self.logpath = './log/models/'
        self.mpath = './models/'

I then create a subclass which has its own __init__ and calls super(), but I can't seem to access self.mpath. I know it's something to do with self being bound to the class instance, but how would I go about achieving this functionality as I have a good number of subclasses for which I don't want to replicate these path variables.
The reason I want this is that I call functions from this parent class from within my subclass which uses the parent's class self variables (csv_to_df is a member of the parent class):
def csv_to_df(self) -> tuple:
        """Reads in CSV file declared in __init__ (self.rpath) and converts it to a number of Pandas DataFrames.

        Returns:
            tuple: Returns tuple of Pandas DataFrames; user features, item features and
                interactions between items.

        """

        df = pd.read_csv(self.rpath, sep='\t')
        return df

Calling this from the subclass results in
Traceback (most recent call last):
  File "model_baselines.py", line 480, in <module>
    als.run()
  File "model_baselines.py", line 366, in run
    df = self.csv_to_df()
  File "model_baselines.py", line 46, in csv_to_df
    df = pd.read_csv(self.rpath, sep='\t')
AttributeError: 'ALS' object has no attribute 'rpath'

Subclass definition
class ALS(BaselineModels):
    def __init__(self):
        super()
        self.model_name = 'als'

    def run(self):
        df = self.csv_to_df()

I call als.run() from the bottom the file.
EDIT: Updated to include subclass definition

A: You have to call the __init__() method of the super() object.  Something like this:
class BaselineModels:
    def __init__(self):
        self.logpath = './log/models/'
        self.mpath = './models/'

class ALS(BaselineModels):
    def __init__(self):
        super().__init__()
        self.model_name = 'als'

    def run(self):
        df = self.csv_to_df()

als = ALS()
als.mpath
# returns:
'./models/'

A: You can follow this method also.
class BaselineModels:
    def __init__(self):
        self.logpath = './log/models/'
        self.mpath = './models/'

class ALS(BaselineModels):
    def __init__(self):
        super(ALS, self).__init__()
        self.model_name = 'als'

    def run(self):
        df = self.csv_to_df()

als = ALS()
als.mpath
# returns:
'./models/'


text:
Q: How do I rollback app-engine deployment I have an Appengine connected android project (eclipse). I am trying to deploy it as I have done countless times. But this time I am getting the following error.

Unable to update app: Error posting to URL:
  https://appengine.google.com/api/appversion/create?app_id=myappid&version=1&
  409 Conflict Another transaction by user myusername is already in
  progress for app: s~myappid, version: 1. That user can undo the
  transaction with "appcfg rollback".
See the deployment console for more details Unable to update app:
  Error posting to URL:
  https://appengine.google.com/api/appversion/create?app_id=myappid&version=1&
  409 Conflict Another transaction by user myusername is already in
  progress for app: s~myappid, version: 1. That user can undo the
  transaction with "appcfg rollback".

So I open my osx terminal and navigate to the folder of my project. When I type
appcfg.py rollback .

I get a terminal error that

appcfg.py: error: Directory does not contain an app.yaml configuration
  file

Thanks for any direction.
Update
I think I finally found out where it is but now I am getting permission denied when I do
/Applications/eclipse/plugins/com.google.appengine.eclipse.sdkbundle_1.9.3/appengine-java-sdk-1.9.3/bin/appcfg.sh rollback war

A: Since you are using Mac, try
appcfg.sh rollback

A: You can also avoid having to specify your app directory (as it doesn't seen to work for you), by specifying your app id and version in the command itself:
appcfg.py rollback -A your_app_id -V your_app_version

If you have multiple modules then you will need to specify that too with the -M switch.

A: You will probably find you don't have execute permissions on appcfg
So, if you change to your SDK directory and run
chmod 755 appcfg.sh
Then
appcfg.sh rollback <path_to_app>/war
should work.  If not, you may have a WebContent directory, in which case use the path to that. Essentially, appcfg wants to see the WEB-INF directory which contains your appengine-web.xml for the module you're rolling back.

A: On MAC -
in terminal, goto where  your sdk directory  - /Users/user/Desktop/eclipse/plugins/com.google.appengine.eclipse.sdkbundle_1.9.20/appengine-java-sdk-1.9.20/bin
do

chmod 777 *

run

bash appcfg.sh rollback /Users/user/Desktop/builder/war

The last parameter is the location of the war inside your project

A: I had the same problem. I solved it using this command on mac:
python /usr/local/bin/appcfg.py -verbose --no_cookies --email=account@gmail.com --passin rollback directoryname
where directoryname was the folder where the app.yaml is located. For my case, it was on dropbox folder. so firstly I went to that directory using terminal then I pasted: python /usr/local/bin/appcfg.py -verbose --no_cookies --email=account@gmail.com --passin app
where app defines file name app.yaml

A: This is for java project using app engine
This happens your previous deployment not successfully deployed

go to app engine sdk
C:\Program Files (x86)\Google\appengine-java-sdk-1.9.49\bin

then add

syntax: appcfg.sh rollback your project war folder

Example:  appcfg.sh rollback E:myproject\war
Enough!!!

A: For Windows user,
Syntax: "<appengine sdk bin folder path>\appcfg" rollback "<war path of your project"

Example: "C:\Users\user\.m2\repository\com\google\appengine\appengine-java-
sdk\1.9.44\appengine-java-sdk\appengine-java-sdk-1.9.44\bin\appcfg" rollback "D:\helloworld\war"

Output of the above will be something like this,
********************************************************
There is a new version of the SDK available.
-----------
Latest SDK:
Release: 1.9.49
Timestamp: Wed Jan 18 23:03:47 IST 2017
API versions: [1.0]

-----------
Your SDK:
Release: 1.9.44
Timestamp: Sat Aug 20 03:11:38 IST 2016
API versions: [1.0]

-----------
Please visit https://developers.google.com/appengine/downloads for the latest SD
K.
********************************************************
Reading application configuration data...

Beginning interaction for module default...
0% Rolling back the update.
Success.
Cleaning up temporary files for module default...

A: Just an FYI on this: I was using the Eclipse java plugin on Mac (so otherwise didn't have the SDK anywhere), found the command file by digging into the Eclipse package there etc, but predictably enough it didn't run. So I just downloaded the appengine Java SDK, unzipped it, went into bin, ran ./appcfg rollback my/proj command as you see here.
Leave that terminal window open, do not close it, read on...
It opens a web browser and tells you in a very bare bones way to "copy a code and return to the application". I haven't had to roll back a deploy in quite some time, but I don't remember this step. Anyway, I had no idea what that meant until I happened to look at the terminal where I ran the appcfg command, which was now waiting for me to paste in that code. Then all was well.


text:
Q: Print the first line of multiple files using Batch I've done a batch file to print the first line of multiple files using batch. But it only prints the first line of one of the files, but as many times as the number of files i have.
I mean, it does the FOR loop as many times as the number of files that I have but the variable firstline always have the same value.
I know I'm missing something stupid, I've been trying different combinations for hours and looking at stackoverflow entries for hours without result.
This is my code:

for %%F in (*.trn) do set /p firstline=<%%F & echo %firstline%

A: The critical part that is missing is the call statement inside the FOR loop (yes, it was indeed something stupid). I can confirm that the "quick fix" will print the first line of each file, as requested:
for %%F in (*.trn) do set /p firstline=<%%F & call echo %%firstline%%

The suggestion about Delayed Variable Expansion is a good one. That version will look like this:
setlocal enabledelayedexpansion
for %%F in (*.trn) do set /p firstline=<%%F & echo !firstline!
endlocal

A: Thank you @Compo and @Jonathan for your answers, you helped me to finish the program.
In fact, this question was a part of the program, I share the final program, maybe it's useful for someone looking for a similar solution.
I was doing a program that, if the number in the first line, of the files in a directory, is greater than 46000, it copy the file to another directory. This is the final version:
setlocal EnableDelayedExpansion
For %%A In (*.trn) Do Set/P firstline=<%%A & if !firstline! GTR 46000 move "c:\temp\number\B1\%%A" "c:\temp\number\B2\%%A"


text:
Q: Large data submit changes I'm sorry that my english might not be appropriate.
My solution is Silverlight which uses WCF RIA service SP1.
I'm trying to submit change entity which have large string.
When it doesn't have large string, submit change's result is success.
But when it contains large string, submit change fails with this error.
"An existing connection was forcibly closed by the remote host"
I thought it is problem about timeout, so I tried below code. But it doesn't work.
            ChannelFactory<BatchContext.IBatchServiceContract> channel = ((WebDomainClient<BatchContext.IBatchServiceContract>)this.DomainClient).ChannelFactory;
            channel.Endpoint.Binding.OpenTimeout = new TimeSpan(0, 30, 0);
            channel.Endpoint.Binding.CloseTimeout = new TimeSpan(0, 30, 0);
            channel.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 30, 0);
            channel.Endpoint.Binding.SendTimeout = new TimeSpan(0, 30, 0);

What should I do?
Thank you!!

A: First of all, you should know that sometimes the exception you see may not be the real exception, expecially in WCF, so I suggest you use WCF Serivce Trace to find out the real exception.
And I think your problem may be familiar to this one: wcf max message size.


text:
Q: Bootstrap selectpicker - All options have a tick I am having a strange problem with bootstrap select option. I want to show the tick when the option is selected but the problem is that all the options have the tick "Ok" showed even if it is not clicked.
this is a screenshot of the problem:

This is my code:
$(document).ready(function() {
    $('.selectpicker').selectpicker({
        style : 'btn-info',
        size : 4,
        iconBase: 'glyphicon',
        tickIcon: 'glyphicon-ok'
    });
});

        Are you ok?
        <select class="selectpicker" name="object_example" >
            <option value="1">True</option>
            <option value="2">False</option>
        </select>

The tick is always there..

A: So the problem was in bootstrap-select.js and bootstrap-select.css files.
I re-download them from Here and now it works.
I also needed to change the class name to:
class="selectpicker show-tick form-control"


text:
Q: combine date and time into a single datetime I have a date and time control, which I would like to concatenate
var startDate = jQuery('#startDatepicker').find("input").val();
var startTime = jQuery('#startTimepicker').find("input").val();

I have another var field which has data as below:
var targetTime = new Date().setMinutes(-5).valueOf();

startDatepicker has the value as : 02/06/2017
startTimepicker, currentTime has the value as : 05:17 am
targetTime has the value as: 1486374940591
I want to concatenate startdate and starttime in the format of targetTime. How to concatenate the start date and start time?
Thanks

A: Pass your date and time to this function. It will return the Date object. Use getTime() on that to get the desired result. Codepen example.
function getAsDate(day, time)
{
 var hours = Number(time.match(/^(\d+)/)[1]);
 var minutes = Number(time.match(/:(\d+)/)[1]);
 var AMPM = time.match(/\s(.*)$/)[1];
 if(AMPM == "pm" && hours<12) hours = hours+12;
 if(AMPM == "am" && hours==12) hours = hours-12;
 var sHours = hours.toString();
 var sMinutes = minutes.toString();
 if(hours<10) sHours = "0" + sHours;
 if(minutes<10) sMinutes = "0" + sMinutes;
 time = sHours + ":" + sMinutes + ":00";
 var d = new Date(day);
 var n = d.toISOString().substring(0,10);
 var newDate = new Date(n+"T"+time);
 return newDate;
}

A: This do what you need
var date = new Date(startDate + ' ' + startTime);

jQuery('#startDatepicker, #startTimepicker').on('input', function() {
  var startDate = jQuery('#startDatepicker').val();
  var startTime = jQuery('#startTimepicker').val();
  var date = new Date(startDate + ' ' + startTime);
  console.log(date)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Date
<input id="startDatepicker">Time
<input id="startTimepicker">


text:
Q: Get my Wifi Password (It's saved as dots, how can I see it) in WinXP? I can't use Wirelesskeyview, my anti-virus keeps deleting it and I can't disable it.  Is there another way to get it?

A: Start in safe mode then try the wireless key view program

A: Try Cain & Abel. It has a nice local password recovery for wireless passwords.

A: It's a while since I've needed to use something like this, but http://www.nirsoft.net/utils/bullets_password_view.html lets you view password fields in windows that are asterisk protected.


text:
Q: Filter element stored in variable by class I have an elements stored in a variable (var body). These elements take the form of:

 or

I would like pass 'body' into a function and only return the element passed into it if its class is 'img'.

A: If I understand correctly:
$(body).hasClass('img');

or maybe:
$(body).filter('.img');


text:
Q: Entity Framework how to setup relationships with Inheritance types I currently have the following classes in my EF based project. Data is stored in a SQL Database using the Table per Hierarchy (TPH) configuration :
class Lot {
    Building building
    ...
}

class Building {
     string name {get; set;}
     string address {get; set;}
     string discriminator {get; set;}
     ...
}

class House : Building {
    ...
}

class Employee: {
     Building building {get; set;}
     Person person {get; set;}
     string jobName {get; set;}
}

class Shop: Building {
     List<Employee> employees {get; set;}
     Person owner {get; set;}
     ...
}

class Factory: Building {
     List<Employee> employees {get; set;}
     List<Machine> equipment {get; set;}
     ...
}

I setup my ef model this way using Ardalis clean architecture configuration classes:
...
builder.HasMany(x => ((Shop)x).employees).WithOne(x => x.building);
builder.HasDiscriminator(x => x.discriminator)
  .HasValue<House>("House")
  .HasValue<Shop>("Shop")
  .HasValue<Factory>("Factory");

Finally in my lot specification where I need to access all the informations I include all the stuff I should need to access
Query.Include(x => x.building).ThenInclude(x => (x as Shop).employees).ThenInclude(x => x.person)

My relationships between the Lot and Building works properly, but the one between Shop and Employees doesn't. Would you have any idea how to make it work? I need an employee list in both Shop and Factory and both are too different to be in a same class.
I tried to make a ModelBuilder for the Shop class specifically that would define the relationship between Shop but it also didn't worked properly. I also try to swap between different type of cast for Building to Shop.


text:
Q: How to display a loading image until a gridview is fully loaded without Ajax Toolkit? QUESTION
Can anyone suggest how a loading image  can be displayed until a gridview is fully loaded?
This gridview is to be rendered on page load. There must be a simple solution to detect when gridview is loading/loaded so a simple toggle between load image and gridview visibility can be achieved.
Please do not suggest using any of the Ajax toolkit methods unless the desired code can be isolated and used standalone. I have found the toolkit to be easy on implementation but bloated and slow on performance. I do not wish to include any scripts, files or code in my release package that is not going to be used.
ASP.NET

      <asp:GridView ID="gv" runat="Server" AutoGenerateColumns="False" EnableModelValidation="False">
        'content...
      </asp:GridView>

VB
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'connection info

    If Not IsPostBack Then
      Me.Bindgv()
    End If
  End Sub

  Private Sub Bindgv()
    'Load gridview
  End Sub

POSSIBILITIES
I am open to any suggestions however I was attemting to implement a solution using jquery page methods but need assistance to follow through.
JAVASCRIPT
$(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateGV",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    success: function() {
      // Run return method.
    }
  });
});

VB.NET
Imports System.Web.Services

Public Partial Class _Default
    Inherits System.Web.UI.Page

    <WebMethod(EnableSession := False)> _
    Public Shared Function UpdateGV() As String
         Return
         Me.Bindgv()
    End Function
End Class

A: You can achieve this using jquery, there is a jquery block UI project on github and you could just use that one to block the grid view without using ajax.
here is the code you will need to do this, and it' tested and works fine like below:
Step 1 add these two lines in your page head

Step 2 an extension jquery after the codes above:

Step 3 in my case I bind my grid view using a button , but you could always use any other controls as well:

<asp:Button ID="Button1" runat="server" Text="Bind Grid View"
            ClientIDMode="Static" OnClick="Button1_Click" />

        <asp:GridView ID="GridView1" runat="server" Width="100%">
        </asp:GridView>

Step 4 bind the grid view on button clicked

    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable tblCourse = myAccount.GetEnroledCourse("arpl4113");

        //Bind courses
        GridView1.DataSource = tblCourse;
        GridView1.DataBind();
    }

and that's it, NO AJAX Toolkit (only jQuery) so the result will be look like this:

A trick to do the above solution at the page load
First of all this is NOT a function on Page_Load event on server side but on the client side ;-)
So to achieve this you need to have a hidden control to keep a value on page view-state and also make the same button hidden to trigger it on page load. and a little changes on the extension jQuery above. Done!
Step 1. Add the css below to your page header:

Step 2. Add a hidden field plus make your button hidden like this:
    <asp:HiddenField ID="hidTrigger" runat="server" ClientIDMode="Static" Value="" />
    <asp:Button ID="btnHidden" runat="server" ClientIDMode="Static"
                OnClick="btnHidden_Click" CssClass="hidden" />

        <asp:GridView ID="GridView1" runat="server"></asp:GridView>

Step 3. Make this changes on your extension script like below:

That's it! and your button click on the code behind remains the same as before, in this example I only change the name of the button. no code on Page_Load event though.
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnHidden_Click(object sender, EventArgs e)
    {
        DataTable tblCourse = myAccount.GetEnroledCourse("arpl4113");

        //Bind courses
        GridView1.DataSource = tblCourse;
        GridView1.DataBind();
    }

I hope it helps you.

A: As you are not willing to use the ASP.NET Update panel which is designed to handle the kind of requirement you have. Using jquery AJAX and using the web method to update the Grid will not work as you expect because you need to update the viewstate and other information. One of the solution that you can apply is showing the modal dialog box till your page is completed loaded  its html which includes your Grid data.

A: I would implement this by using a web api controller that returns the appropriate data and then simply try to load the data on document.ready with jquery. Something along the lines of this (Will be posting the answer in c# but it should be simple enough to translate):
 public class TableDataController : ApiController
  {
     public IEnumerable<SimplePocoForOneTableRow> Get()
     {
        var tableData = GetTableDataFromSomewhere();

        return tableData;
     }
  }

To learn more about how to setup a WebApiController in a web forms project, please refer to this article.
I would implement the HTML something like this:

And the jquery to load the data and present it in the table would look something like this:

To tidy the string concatenation of the jQuery up a bit you could use a template like handlebars, but it's not strictly necessary.

A: You should load grid in another page and call that page in a div on parent page and display required loading image while loading div as per below code:
  $(document).ready(function()
   {
 $("#loader").show();
 $.ajax({
    type: "GET",
    url: "LoadGrid.aspx",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    success: function(data) {
        $("#loader").hide();
       $(#dvgrid).html(data);
    },
    // it's good to have an error fallback
    error: function(jqhxr, stat, err) {
       $("#loader").hide();
 $(#dvgrid).html('');
       $("#error").show();
    }
  });
});

In LoadGrid.aspx you should load grid by normal C# code. and simply your parent page will call the LoadGrid.aspx and rendered html will display in parent div with loading image...

A: From your code :
$(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateGV",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    success: function() {
      // Run return method.
    },
    // add these lines
    beforeSend:function {
       //this will show your image loader
       $("$Loader").css("display","block");
    },
    complete:function {
       //this will hide your image loader provided that you give an id named Loader to your image
       $("$Loader").css("display","none");
    }
  });
});

A: Use beforeSend in conjunction with success and error like so:
$(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateGV",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    beforeSend: function() {
        $("#loader").show();
    },
    success: function() {
        $("#loader").hide();
        // Run return method.
    },
    // it's good to have an error fallback
    error: function(jqhxr, stat, err) {
       $("#loader").hide();
       $("#error").show();
    }
  });
});

(provided you have  and )
complete fires after success and error so using both success and error instead of complete and error assures no overlap.
Hope this was what you were looking for!


text:
Q: Skip expressjs middlewares in unit test I'm attempting to "skip" all of the middleware(s) in my App.ts for express.
I'm unit testing a specific route and I don't care about all of the logging / other logic that occurs in the app.ts middlewares.
It does not seem that there is a way to skip over these middlewares and instead I have to mock/stub all of the services/etc used?

A: You may implement a logic to not attach middlewares if your environment is test, however this approach is not good as in future you might want to write some middleware which you want to test out.
In your app.js you can list out middlewares which you want to attach in test environment then.
You can use stub to stubs your middleware to and assert if they were invoked or called with correct arguments.


text:
Q: Mockito's @After and verifyNoMoreInteractions I want to make sure every test verifies all the interactions with its mocks, so I just added a method annotated with @After with a verifyNoMoreInteractions with all the mocks as arguments.
@After
public void after(){
  verifyNoMoreInteractions(mock1,mock2,mock3,...)
}

It works, but if an interaction occurs where none was expected, how can you know which test is the problematic one?

A: @After is executed right after each test of this class finished execution. Regardless if the test failed or not. Then if errors happen in the @After method it could cover/hide the errors happened in the test method...
Note that @AfterClass Is executed after all tests of this class finished execution.
Generally speaking I found it is a good style to have a behavioural Test split in three parts- call it A/A/A or call it Given/When/Then
Arrange / Given part:
Setup up objects and behaviour
Act or When:
Execute implementation
Assert or Then:
Verify behaviour and results (Hint: this is where the verifyNoMoreInteractions goes)

A: You're misusing method verifyNoMoreInteractions(). It should be called inside each test you want to verify.
From the other hand @After is supposed to be used for cleaning/closing the resourses used by your test methods.
What you need is a custom TestWatcher rule. See below an example of such rule:
public class VerifyNoMoreInteractionsRule extends TestWatcher {

    private final List<Object> mocks = new ArrayList<>();

    public void add(Object mock){
        mocks.add(mock);
    }

    @Override
    protected void succeeded(Description description) {
        verifyNoMoreInteractions(mocks.toArray());
    }

}

Then you can use it in your unit tests:
@RunWith(MockitoJUnitRunner.class)
public class VerifyTest {

    @Rule
    public VerifyNoMoreInteractionsRule noMoreInteractionsRule = new VerifyNoMoreInteractionsRule();

    @Mock
    private YourMock yourMock;

    @Mock
    private AnotherMock anotherMock;

    @Before
    public void setUp(){
        // Register the mocks you want to verify after each test
        noMoreInteractionsRule.add(yourMock);
        noMoreInteractionsRule.add(anotherMock);
    }

    @Test
    public void test(){
        // Put your ordinary test code here
    }

}

The rule will be applied to each test.

A: For JUnit5 it can be done using AfterEachMethodAdapter where you check whether the test has thrown an exception. If yes, no mocks are verified:
public class MockAwareTest {

    @RegisterExtension
    public MockVerifier mockVerifier = new MockVerifier();

    @BeforeEach
    void setUp() {
        mockVerifier.addMocks(...);
    }

}

And the MockVerifier:
public class MockVerifier implements AfterEachMethodAdapter {

    private final List<Object> mocks = new LinkedList<>();

    public void addMocks(final Object... mock) {
        mocks.addAll(asList(mock));
    }

    @Override
    public void invokeAfterEachMethod(
            final ExtensionContext context,
            final ExtensionRegistry registry) {
        // if the test didn't fail, check the mocks
        if (context.getExecutionException().isEmpty()) {
            verifyNoMoreInteractions(mocks.toArray());
        }
    }

}


text:
Q: How to run firebase emulators for local development with functions, triggers on remote db? I'm building a firebase API with cloud functions and want to reach my production Database for local testing.
My problem :

When I launch my two firebase emulator (functions and firestore) with
firebase emulators:start

1- My custom API endpoints run on http://localhost:5001 (this works)
2- My triggers reaches a local dababase on http://localhost:8080 whereas I didn't set FIRESTORE_EMULATOR_HOST=localhost:8080 (I want to reach my production database)
OR
When I launch only my "functions emulator" with
firebase emulators:start --only function

...but my triggers are not reached, probably because of this warning
i  functions[userOnCreate]: function ignored because the firestore emulator does not exist or is not running.

On the other side I'm building a reactjs App also with firebase running on localhost:3000
I call my local API from this app with firebase SDK. To reach my emulator, I add the line :
firebase.functions.useFunctionsEmulator('http://localhost:5001');

A: The local emulators don't work with actual cloud-hosted instances of databases.  Everything must be local.
You are always free to file a feature request.

A: you have to use firebase serve instead for firebase emulators:start