text:
Q: Grid World representation for a neural network I'm trying to come up with a better representation for the state of a 2-d grid world for a Q-learning algorithm which utilizes a neural network for the Q-function.
In the tutorial, Q-learning with Neural Networks, the grid is represented as a 3-d array of integers (0 or 1). The first and second dimensions represent the position of an object in the grid world.  The third dimension encodes which object it is.
So, for a 4x4 grid with 4 objects in it, you would represent the state with a 3-d array with 64 elements in it (4x4x4). This means that the meural network would have 64 nodes in the input layer so it could accept the state of the grid world as input.
I want to reduce the number of nodes in the Neural Network so that training does not take as long. So, can you represent the grid world as 2-d array of doubles instead?
I tried to represent a 4x4 grid world as a 2-d array of doubles and used different values to represent different objects. For example, I used 0.1 to represent the player and 0.4 to represent the goal. However, when I implemented this the algorithm stopped learning at all.
Right now I think my problem might be that I need to change which activation functions I'm using in my layers. I'm presently using the hyperbolic tangent activation function. My inputs values range from (0 - 1). My output values range from (-1 to 1). I've also tried the sigmoid function.
I realize this is a complex problem to be asking a question about. Any suggestion as to architecture of the network would be appreciated.
UPDATE
There are three variants to the game:
1. The world is static. All objects start in the same place.
2. The player starting position is random. All other objects stay the same.
3. Each grid is totally random.
With more testing I discovered I can complete the first two variants with my 2d array representation. So I think my network architecture might be fine. What I discovered is that my network is now extraordinarily susceptible to catastrophic forgetting (much more so than when I was using the 3d array).  I have to use "experience replay" to make it learn, but even then I still can't complete the third variant.  I'll keep trying.  I'm rather shocked how much of a difference changing the grid world representation made.  It hasn't improved performance at all.

A: Some standard representations are:

*

*Polynomial (usually 1st or 2nd degree): for the 1st degree you will have a 3-dimensional vector, where the first element is the bias (degree 0), the second is the x coordinate and the third is the y coordinate. For higher degrees, you'll have also x^2, y^2, xy .... If the environment changes, you have also to do the same with the objects positions.

*Radial basis functions (or tile coding since the state space is discrete): you'll have a N x N vector (N is the size of the environment) and each basis / tile will tell you if the agent is in the corresponding cell. You can also have less bases / tiles, each one covering more than one cell. Then you can append a polynomial for the objects in the environment (if their location changes).
Anyway, a 64-dimensional input should not be a problem for a NN. I am not sure that a tanh is the best non-linear function to use. If you read the famous DeepMind paper you'll see that they use a rectified linear activation (why? read this).
Also, be sure to use a gradient descent optimizer during backpropagation.
EDIT
There is basically no difference between the 1st and the 2nd version (actually, having a random agent initial position might even speed up the learning). The third version is of course more difficult, as you have to include details about the environment in your state representation.
Anyway, the features I suggest are still the same: polynomial or radial basis functions.
Experience replay is almost mandatory, as described in the DeepMind paper I cite above. Also, you might find beneficial using a second deep network as target for the Q-function. I don't think this is suggested in the tutorial (I might have missed it). Basically the target r + max(a) gamma * Q(s', a) is given by a different network than the Q-network used by your policy. Every C step you copy the parameters of your Q-network to your Q-target-network in order to give consistent targets during temporal difference backups.
These two tricks (experience replay with minibatches and having a separate target network) are what made Deep Q-learning successful. Again, refer to the DeepMind paper for details.
Finally, some crucial aspects you might want to check:

*

*how big are your minibatches?

*how explorative is your policy?

*how many samples with a random policy do you collect before starting to learn?

*how much are you waiting? (it can easily need 500k samples in total to learn)


text:
Q: Non-blocking Dialog box in Applescript I have to write a small script to deploy a patch for our Application. The patch
will replace a couple of files in the application.I decided to depploy the patch using Applescript. The files to be copied are quite large and it takes some time for the files to be copied. I wanted to know if there is any way I can get a dialog box which doesn't block the execution of the script so that I can display some message like Updating.. etc while the patch is applied and then close the dialog box after wards.
Thanks
Shivaprasad

A: There's a scripting addition called Akua Sweets (oldy but goody) that has a display progress command. Get it at osaxen.com. it's in the 'most popular' section at the top of the page.
edit
Oh, bugger, that's only for OS9. It was really useful back in the day, I remember using it a lot (of course everything took a lot longer in those days so progress bars were more in demand).
another edit
You got me inspired, there's a couple of scripts I use that need progress bars, so I went looking and found this scripting addition at http://osaxen.com/files/extrasuites1.1.html
and again
here's a basic tutorial for how to do it in interface builder. I think that's probably the right way to do it.

A: I myself ran into the same problem.  Unfortunately applescript doesn't provide an easy way of implementing a progress bar.
I ended up using the stop loop example found here to build an application.  This guy has a bunch of applescript studio xcode projects to download and mess around with.  It's some really great sample code if you aren't too familiar with applescript studio.

redpajama_set_name: RedPajamaStackExchange


text:
Q: producing all the anagrams from a string python I was thinking about this problem today, and I came with the following pseudocode (Python 3.2) :
def anagrams( string ):

    for c in string:
      anagram = c + anagram( string - {c} ) # remove the char from its position in the string
      print(anagram)

    return

def main():

    word = "abcd"
    anagrams( word )

    return

However, I'd like to know a pythonic way to do this operation:
   anagram = c + anagram( string - {c} )
How could I remove that char from the string? so for example:
"abc" -> 'a' + "bc" -> 'a' + 'b' + "c" -> 'a' + 'b' + 'c' = 'abc'
             + "cb" -> 'a' + 'c' + "b" -> 'a' + 'c' + 'b' = 'acb'
      -> 'b' + "ac" -> 'b' + 'a' + "c" -> 'b' + 'a' + 'c' = 'bac'
             + "ca" -> 'b' + 'c' + "a" -> 'b' + 'c' + 'a' = 'bca'
      -> 'c' + "ba" -> 'c' + 'b' + "a" -> 'c' + 'b' + 'a' = 'cba'
             + "ab" -> 'c' + 'a' + "b" -> 'c' + 'a' + 'b' = 'cab'

Thanks

A: Use the itertools module.
import itertools
perms = [''.join(perm) for perm in itertools.permutations('abc')]

A: Just to note, @sloth's answer gives a slightly unexpected result if the string contains more than one instance of a letter - duplicate permutations:
["".join(perm) for perm in itertools.permutations('aabc')]

Results in:
['aabc',
 'aacb',
 'abac',
 'abca',
 'acab',
 'acba',
 'aabc',
 'aacb',
 'abac',
 'abca',
 'acab',
 'acba',
 'baac',
 'baca',
 'baac',
 'baca',
 'bcaa',
 'bcaa',
 'caab',
 'caba',
 'caab',
 'caba',
 'cbaa',
 'cbaa']

If this isn't the desired result, using 'set' will eliminate the dups. Although if you want a list, you'll need to relist (also 'set' doesn't maintain order so use 'sorted'):
sorted(set(["".join(perm) for perm in itertools.permutations("aabc")]))

Results in:
['aabc',
 'aacb',
 'abac',
 'abca',
 'acab',
 'acba',
 'baac',
 'baca',
 'bcaa',
 'caab',
 'caba',
 'cbaa']

A: Why not just use itertools?
>>> import itertools
>>> ["".join(perm) for perm in itertools.permutations("abc")]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

The documentation also contains code how the permutation is done.

Edit:
Without itertools:
def all_perms(elements):
    if len(elements) <=1:
        yield elements
    else:
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                yield perm[:i] + elements[0:1] + perm[i:]

word = "abc"
print list(all_perms(word))

Without itertools and without generators:
def all_perms(elements):
    if len(elements) <=1:
        return elements
    else:
        tmp = []
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                tmp.append(perm[:i] + elements[0:1] + perm[i:])
        return tmp

Result:

['abc', 'bac', 'bca', 'acb', 'cab', 'cba']

A: You can cast the word to a list, run remove and then use join to get it back together again.
word = 'abca'
letters = list(word)
letters.remove('a')  # Only deletes the first 'a'
word = ''.join(letters)

A: Here's some of the suggestions wrapped up to make a new script, called anagram
$ anagram hit
hit
hti
iht
ith
thi
tih

anagram
#!/usr/bin/env python3
import argparse
import itertools
import sys

parser = argparse.ArgumentParser()
parser.add_argument("word", help="A word to generate anagrams for.")
args = parser.parse_args()

perms = [''.join(perm) for perm in itertools.permutations(args.word)]
for perm in perms:
    print(perm)


text:
Q: Operations used in the isomorphism theorem Prove that $\mathbb{R}/ \mathbb{Z}\cong G=\{a+ib \in \mathbb{C}\;:\; a^2+b^2=1\}.$
In my answer I've tried to show that there is an homomorphis between $\mathbb{R}$ and G. I also tried to show that $Ker(f)=\mathbb{Z}$ and to show that f is surjective. My goal is to use the isomorphism theorem. But I coudn't achieve success.
If I define $f: \mathbb{R} \rightarrow G$ given by $\alpha \longmapsto f(\alpha)= \cos(2\pi \alpha)+ i \sin(2\pi \alpha)$ as the same given as a hint in the Herstein book. I made big mistakes early in the begining. I mean, I'm struggling to show that  $\mathbb{Z} = ker(f)$ Let me show you how I wrote:
Let $Kef(f) \subset \mathbb{Z}=\{\alpha\in \mathbb{R}: \; f(\alpha)=1=1+i0\}$. I showed that if $\alpha \in \ker(f) \implies f(\alpha)=1+i0 \implies 1^2+ 0^2=1\in \mathbb{Z}.$
But, how can I proof that $\mathbb{Z}\supset kef(f)$?

A: $a\in Ker(f)$ iff $f(a)=1$ iff $a$ is an integer and hence $\ker(f)=\mathbb{Z}$.
[Answer for your doubt; Observe that if $f(a)=1$ then $a$ should be an integer. For non integral values of $a,$ $\cos 2\pi a$ will not give you $1.$ ]

A: If $\cos(2\pi\alpha)+i\sin(2\pi\alpha)=1$, then $\cos(2\pi\alpha)=1\land\sin(2\pi\alpha)=0\implies\alpha\in\Bbb Z$.


text:
Q: Recover unallocated disk space I would like to recover some unallocated (?) disk space on an external hard drive /dev/disk2 is 1TB but I only see a 250GB partition. Here is a terminal screenshot and a Disk Utility one.

Is there any way I could add the remaining 750 GB to the existing partition disk2s2 or create a new disk2s3?

A: Ended up formatting the whole thing after doing a back-up


text:
Q: how to create an audit trail with Entity framework 5 and MVC 4 I am building an MVC 4 application, using EF 5.
I need to do an audit trail, ie log any changes that end users make.
I have asked this question a few times, but haven't really gotten a satisfying answer before.  So I am adding a lot more details in hoping to get somewhere..
currently I have multiple repositories
ie
 public class AuditZoneRepository : IAuditZoneRepository
    {
        private AISDbContext context = new AISDbContext();

        public int Save(AuditZone model, ModelStateDictionary modelState)
        {
            if (model.Id == 0)
            {
                context.AuditZones.Add(model);
            }
            else
            {
                var recordToUpdate = context.AuditZones.FirstOrDefault(x => x.Id == model.Id);
                if (recordToUpdate != null)
                {
                    recordToUpdate.Description = model.Description;
                    recordToUpdate.Valid = model.Valid;
                    recordToUpdate.ModifiedDate = DateTime.Now;
                }
            }

            try
            {
                context.SaveChanges();
                return 1;
            }
            catch (Exception ex)
            {
                modelState.AddModelError("", "Database error has occured.  Please try again later");
                return -1;
            }
        }
    }

    public class PostcodesRepository : IPostcodesRepository
    {
        private AISDbContext context = new AISDbContext();

        public int Save(Postcodes model, ModelStateDictionary modelState)
        {
            if (model.Id == 0)
            {
                context.Postcodes.Add(model);
            }
            else
            {
                var recordToUpdate = context.Postcodes.FirstOrDefault(x => x.Id == model.Id);
                if (recordToUpdate != null)
                {
                    recordToUpdate.Suburb = model.Suburb;
                    recordToUpdate.State = model.State;
                    recordToUpdate.Postcode = model.Postcode;
                    recordToUpdate.AuditZoneId = model.AuditZoneId;
                    recordToUpdate.ModifiedDate = DateTime.Now;
                }
            }

            try
            {
                context.SaveChanges();
                return 1;
            }
            catch (Exception ex)
            {
                modelState.AddModelError("", "Database error has occured.  Please try again later");
                return -1;
            }
        }

    }

Now I know for me to add the code to check to see if there are any changes i need to add it in the try of the save.  Before the context.SaveChanges().
But currently I have 10 repos.  I don't really want to add code to 10 different places.  As this code will do exactly the same thing.  I want to somehow have a baseclass that the repos inherit from.
any help? any sample code? any pointers?
would be appreciated.  I am sure other people would have done this before
I am mappying my keys, relationships and tables like so
 public class AuditZoneMap : EntityTypeConfiguration<AuditZone>
    {
        public AuditZoneMap()
        {
            // Primary Key
            HasKey(t => t.Id);

            // Properties
            Property(t => t.Description)
                .HasMaxLength(100);

            // Table & Column Mappings
            ToTable("AuditZone");
            Property(t => t.Id).HasColumnName("Id");
            Property(t => t.Description).HasColumnName("Description");
            Property(t => t.Valid).HasColumnName("Valid");
            Property(t => t.CreatedDate).HasColumnName("CreatedDate");
            Property(t => t.CreatedBy).HasColumnName("CreatedBy");
            Property(t => t.ModifiedDate).HasColumnName("ModifiedDate");
            Property(t => t.ModifiedBy).HasColumnName("ModifiedBy");

            // Relationships
            HasOptional(t => t.CreatedByUser)
               .WithMany(t => t.CreatedByAuditZone)
               .HasForeignKey(d => d.CreatedBy);

            HasOptional(t => t.ModifiedByUser)
                .WithMany(t => t.ModifiedByAuditZone)
                .HasForeignKey(d => d.ModifiedBy);

        }
    }

A: Disclaimer: I'm the owner of the project Entity Framework Plus
EF+ has auditing features which support EF5, EF6, and EF Core.
// using Z.EntityFramework.Plus; // Don't forget to include this.

var ctx = new EntityContext();
// ... ctx changes ...

var audit = new Audit();
audit.CreatedBy = "ZZZ Projects"; // Optional
ctx.SaveChanges(audit);

// Access to all auditing information
var entries = audit.Entries;
foreach(var entry in entries)
{
    foreach(var property in entry.Properties)
    {
    }
}

A lot of options are available like an AutoSave in the database.
Documentation: EF+ Audit

A: What I recommend you is to use the ChangeTracker property in EF.
Inside your DBContext.cs you will have this:
public class DBContext : DbContext
    {

        public DBContext () : base("DatabaseName")
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        }

        public DbSet<YourPocoModelNameHere > YourPocoModelNameHere { get; set; }

        // This is overridden to prevent someone from calling SaveChanges without specifying the user making the change
        public override int SaveChanges()
        {
            throw new InvalidOperationException("User ID must be provided");
        }
        public int SaveChanges(int userId)
        {
            // Get all Added/Deleted/Modified entities (not Unmodified or Detached)
            foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == System.Data.EntityState.Added || p.State == System.Data.EntityState.Deleted || p.State == System.Data.EntityState.Modified))
            {
                // For each changed record, get the audit record entries and add them
                foreach (AuditLog x in GetAuditRecordsForChange(ent, userId))
                {
                    this.AuditLogs.Add(x);
                }
            }

            // Call the original SaveChanges(), which will save both the changes made and the audit records
            return base.SaveChanges();
        }

        private List<AuditLog> GetAuditRecordsForChange(DbEntityEntry dbEntry, int userId)
        {
            List<AuditLog> result = new List<AuditLog>();

            DateTime changeTime = DateTime.UtcNow;

            // Get the Table() attribute, if one exists
            //TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;

            TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), true).SingleOrDefault() as TableAttribute;

            // Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
            string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;

            // Get primary key value (If you have more than one key column, this will need to be adjusted)
            var keyNames = dbEntry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).ToList();

            string keyName = keyNames[0].Name; //dbEntry.Entity.GetType().GetProperties().Single(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0).Name;

            if (dbEntry.State == System.Data.EntityState.Added)
            {
                // For Inserts, just add the whole record
                // If the entity implements IDescribableEntity, use the description from Describe(), otherwise use ToString()

                foreach (string propertyName in dbEntry.CurrentValues.PropertyNames)
                {
                    result.Add(new AuditLog()
                    {
                        AuditLogId = Guid.NewGuid(),
                        UserId = userId,
                        EventDateUTC = changeTime,
                        EventType = "A",    // Added
                        TableName = tableName,
                        RecordId = dbEntry.CurrentValues.GetValue<object>(keyName).ToString(),
                        ColumnName = propertyName,
                        NewValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()
                    }
                            );
                }
            }
            else if (dbEntry.State == System.Data.EntityState.Deleted)
            {
                // Same with deletes, do the whole record, and use either the description from Describe() or ToString()
                result.Add(new AuditLog()
                {
                    AuditLogId = Guid.NewGuid(),
                    UserId = userId,
                    EventDateUTC = changeTime,
                    EventType = "D", // Deleted
                    TableName = tableName,
                    RecordId = dbEntry.OriginalValues.GetValue<object>(keyName).ToString(),
                    ColumnName = "*ALL",
                    NewValue = (dbEntry.OriginalValues.ToObject() is IDescribableEntity) ? (dbEntry.OriginalValues.ToObject() as IDescribableEntity).Describe() : dbEntry.OriginalValues.ToObject().ToString()
                }
                    );
            }
            else if (dbEntry.State == System.Data.EntityState.Modified)
            {
                foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
                {
                    // For updates, we only want to capture the columns that actually changed
                    if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName)))
                    {
                        result.Add(new AuditLog()
                        {
                            AuditLogId = Guid.NewGuid(),
                            UserId = userId,
                            EventDateUTC = changeTime,
                            EventType = "M",    // Modified
                            TableName = tableName,
                            RecordId = dbEntry.OriginalValues.GetValue<object>(keyName).ToString(),
                            ColumnName = propertyName,
                            OriginalValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(),
                            NewValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()
                        }
                            );
                    }
                }
            }
            // Otherwise, don't do anything, we don't care about Unchanged or Detached entities

            return result;
        }

    }

This will use the following table in your DB:
USE [databasename]
GO

/****** Object:  Table [dbo].[auditlog]    Script Date: 06/01/2014 05:56:49 p. m. ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[auditlog](
    [auditlogid] [uniqueidentifier] NOT NULL,
    [userid] [int] NOT NULL,
    [eventdateutc] [datetime] NOT NULL,
    [eventtype] [char](1) NOT NULL,
    [tablename] [nvarchar](100) NOT NULL,
    [recordid] [nvarchar](100) NOT NULL,
    [columnname] [nvarchar](100) NOT NULL,
    [originalvalue] [nvarchar](max) NULL,
    [newvalue] [nvarchar](max) NULL,
 CONSTRAINT [PK_AuditLog] PRIMARY KEY NONCLUSTERED
(
    [auditlogid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[auditlog]  WITH CHECK ADD  CONSTRAINT [FK_auditlog_users] FOREIGN KEY([userid])
REFERENCES [dbo].[users] ([userid])
GO

ALTER TABLE [dbo].[auditlog] CHECK CONSTRAINT [FK_auditlog_users]
GO

With this all set then you will just need to call your dbContext.SaveChanges(here the userId);
Hope this will work for you... I use it in all my applications and works great!
Enjoy it.

Full code found here: https://jmdority.wordpress.com/2011/07/20/using-entity-framework-4-1-dbcontext-change-tracking-for-audit-logging/

A: In Generic repository pattern, we can write a generic event handler for db context savechanges event.
I googled it and gathered few many information.

*

*I dont want to write a sql server trigger

*I dont want to handle savechanges method in each entity.

So i am planning to write generic single method
Db structure that I am using
audit table
CREATE TABLE [dbo].[Audit](
    [Id] [BIGINT] IDENTITY(1,1) NOT NULL,
    [TableName] [nvarchar](250) NULL,
    [Updated By] [nvarchar](100) NULL,
    [Actions] [nvarchar](25) NULL,
    [OldData] [text] NULL,
    [NewData] [text] NULL,
    [Created For] varchar(200) NULL,
    [Updated Date] [datetime] NULL,
 CONSTRAINT [PK_DBAudit] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

2.Update your dbcontext with Audit table entity.
3.Hook generic event handler for Dbcontext savechanges
c# code
    namespace ARMS.Domain
    {
        using System;
        using System.Collections.Generic;
        using System.Collections.ObjectModel;
        using System.Data;
        using System.Data.Objects;
        using System.Linq;
        using System.Text;
        using System.ComponentModel.DataAnnotations;
        public partial class ARMSContext
        {
            Collection<Audit> auditTrailList = new Collection<Audit>();

            partial void OnContextCreated()
            {
                this.SavingChanges += new EventHandler(ArmsEntities_SavingChanges);
            }
            public enum AuditActions
            {
                Added,
                Modified,
                Deleted
            }
            void ArmsEntities_SavingChanges(object sender, EventArgs e)
            {
                auditTrailList.Clear();
                IEnumerable<ObjectStateEntry> changes =
                    this.ObjectStateManager.GetObjectStateEntries(
                    EntityState.Added | EntityState.Deleted | EntityState.Modified);
                foreach (ObjectStateEntry stateEntryEntity in changes)
                {

                        if (!stateEntryEntity.IsRelationship && stateEntryEntity.Entity != null && !(stateEntryEntity.Entity is Audit))
                        {
                            Audit audit = this.GetAudit(stateEntryEntity);
                            auditTrailList.Add(audit);
                        }

                }
                if (auditTrailList.Count > 0)
                {
                    foreach (var audit in auditTrailList)
                    {
                        this.Audits.AddObject(audit);
                    }
                }
            }
            public Audit GetAudit(ObjectStateEntry entry)
            {
                Audit audit = new Audit();

                audit.Updated_By ="Test";
                audit.TableName = entry.EntitySet.ToString();
                audit.Updated_Date = DateTime.Now;
                audit.Created_For = Convert.ToString(entry.Entity);
                audit.Actions = Enum.Parse(typeof(AuditActions),entry.State.ToString(), true).ToString();
                StringBuilder newValues = new StringBuilder();
                StringBuilder oldValues = new StringBuilder();
                if (entry.State == EntityState.Added)
                {
                    SetAddedProperties(entry, newValues);
                    audit.NewData = newValues.ToString();
                }
                else if (entry.State == EntityState.Deleted)
                {   SetDeletedProperties(entry, oldValues);
                    audit.OldData = oldValues.ToString();
                }
                else if (entry.State == EntityState.Modified)
                {
                    SetModifiedProperties(entry, oldValues, newValues);
                    audit.OldData = oldValues.ToString();
                    audit.NewData = newValues.ToString();
                }
                return audit;
            }
            private void SetAddedProperties(ObjectStateEntry entry, StringBuilder newData)
            {
                CurrentValueRecord currentValues = entry.CurrentValues;
                for (int i = 0; i < currentValues.FieldCount; i++)
                {
                    newData.AppendFormat("{0}={1} || ", currentValues.GetName(i), currentValues.GetValue(i));
                }
            }
            private void SetDeletedProperties(ObjectStateEntry entry, StringBuilder oldData)
            {
                foreach (var propertyName in entry.GetModifiedProperties())
                {
                    var oldVal = entry.OriginalValues[propertyName];
                    if (oldVal != null)
                    {
                        oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
                    }
                }
            }
            private void SetModifiedProperties(ObjectStateEntry entry, StringBuilder oldData, StringBuilder newData)
            {
                foreach (var propertyName in entry.GetModifiedProperties())
                {
                    var oldVal = entry.OriginalValues[propertyName];
                    var newVal = entry.CurrentValues[propertyName];
                    if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
                    {
                        newData.AppendFormat("{0}={1} || ", propertyName, newVal);
                        oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
                    }
                }
            }
        }
    }

A: Update:

The most requested feature for EF Core 6.0 was support for SQL Server
temporal tables. As of RC1, temporal table support is now here!
SQL Server temporal tables automatically keep track of all the data
ever stored in a table, even after that data has been updated or
deleted. This is achieved by creating a parallel "history table" into
which timestamped historical data is stored whenever a change is made
to the main table. This allows historical data to be queried, such as
for auditing, or restored, such as for recovery after accidental
mutation or deletion.
EF Core 6.0 supports:

*

*The creation of temporal tables using EF Core migrations

*Transformation of existing tables into temporal tables, again using    migrations

*Querying historical data

*Restoring data from some point in the past

https://devblogs.microsoft.com/dotnet/prime-your-flux-capacitor-sql-server-temporal-tables-in-ef-core-6-0/
Original:
You can do it like this without any external library for Entity Framework Core:
using (var context = new SampleContext())
{
    // Insert a row
    var customer = new Customer();
    customer.FirstName = "John";
    customer.LastName = "doe";
    context.Customers.Add(customer);
    await context.SaveChangesAsync();

    // Update the first customer
    customer.LastName = "Doe";
    await context.SaveChangesAsync();

    // Delete the customer
    context.Customers.Remove(customer);
    await context.SaveChangesAsync();
}

Model:
public class Audit
{
    public int Id { get; set; }
    public string TableName { get; set; }
    public DateTime DateTime { get; set; }
    public string KeyValues { get; set; }
    public string OldValues { get; set; }
    public string NewValues { get; set; }
}

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class SampleContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Audit> Audits { get; set; }
}

DbContext:
public class SampleContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Audit> Audits { get; set; }

    public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
    {
        var auditEntries = OnBeforeSaveChanges();
        var result = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        await OnAfterSaveChanges(auditEntries);
        return result;
    }

    private List<AuditEntry> OnBeforeSaveChanges()
    {
        ChangeTracker.DetectChanges();
        var auditEntries = new List<AuditEntry>();
        foreach (var entry in ChangeTracker.Entries())
        {
            if (entry.Entity is Audit || entry.State == EntityState.Detached || entry.State == EntityState.Unchanged)
                continue;

            var auditEntry = new AuditEntry(entry);
            auditEntry.TableName = entry.Metadata.Relational().TableName;
            auditEntries.Add(auditEntry);

            foreach (var property in entry.Properties)
            {
                if (property.IsTemporary)
                {
                    // value will be generated by the database, get the value after saving
                    auditEntry.TemporaryProperties.Add(property);
                    continue;
                }

                string propertyName = property.Metadata.Name;
                if (property.Metadata.IsPrimaryKey())
                {
                    auditEntry.KeyValues[propertyName] = property.CurrentValue;
                    continue;
                }

                switch (entry.State)
                {
                    case EntityState.Added:
                        auditEntry.NewValues[propertyName] = property.CurrentValue;
                        break;

                    case EntityState.Deleted:
                        auditEntry.OldValues[propertyName] = property.OriginalValue;
                        break;

                    case EntityState.Modified:
                        if (property.IsModified)
                        {
                            auditEntry.OldValues[propertyName] = property.OriginalValue;
                            auditEntry.NewValues[propertyName] = property.CurrentValue;
                        }
                        break;
                }
            }
        }

        // Save audit entities that have all the modifications
        foreach (var auditEntry in auditEntries.Where(_ => !_.HasTemporaryProperties))
        {
            Audits.Add(auditEntry.ToAudit());
        }

        // keep a list of entries where the value of some properties are unknown at this step
        return auditEntries.Where(_ => _.HasTemporaryProperties).ToList();
    }

    private Task OnAfterSaveChanges(List<AuditEntry> auditEntries)
    {
        if (auditEntries == null || auditEntries.Count == 0)
            return Task.CompletedTask

        foreach (var auditEntry in auditEntries)
        {
            // Get the final value of the temporary properties
            foreach (var prop in auditEntry.TemporaryProperties)
            {
                if (prop.Metadata.IsPrimaryKey())
                {
                    auditEntry.KeyValues[prop.Metadata.Name] = prop.CurrentValue;
                }
                else
                {
                    auditEntry.NewValues[prop.Metadata.Name] = prop.CurrentValue;
                }
            }

            // Save the Audit entry
            Audits.Add(auditEntry.ToAudit());
        }

        return SaveChangesAsync();
    }
}

public class AuditEntry
{
    public AuditEntry(EntityEntry entry)
    {
        Entry = entry;
    }

    public EntityEntry Entry { get; }
    public string TableName { get; set; }
    public Dictionary<string, object> KeyValues { get; } = new Dictionary<string, object>();
    public Dictionary<string, object> OldValues { get; } = new Dictionary<string, object>();
    public Dictionary<string, object> NewValues { get; } = new Dictionary<string, object>();
    public List<PropertyEntry> TemporaryProperties { get; } = new List<PropertyEntry>();

    public bool HasTemporaryProperties => TemporaryProperties.Any();

    public Audit ToAudit()
    {
        var audit = new Audit();
        audit.TableName = TableName;
        audit.DateTime = DateTime.UtcNow;
        audit.KeyValues = JsonConvert.SerializeObject(KeyValues);
        audit.OldValues = OldValues.Count == 0 ? null : JsonConvert.SerializeObject(OldValues);
        audit.NewValues = NewValues.Count == 0 ? null : JsonConvert.SerializeObject(NewValues);
        return audit;
    }
}

Source:
https://www.meziantou.net/entity-framework-core-history-audit-table.htm
If you are using Entity Framework 6 or Entity Framework Core you could also use Audit.NET and Audit.EntityFramework written by @thepirat000. This works fine but I like to have a minimum of NuGet dependencies, preferably 0, that are not backed by a large community/corporation and that depends heavily on a single developer.
https://github.com/thepirat000/Audit.NET/graphs/contributors
You can also read more about Slowly changing dimension types and from there create a solution that fits your needs.
If you need entire Entity Framework Snapshot History look at this answer.

A: I found this NuGet package (TrackerEnabledDbContext) and followed these 4 steps:

*

*Install package TrackerEnabledDbContext

*Inherit my DbContext from TrackerContext in TrackerEnabledDbContext namespace
public class ApplicationDbContext :  TrackerContext
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

Add a migration and update my database. Two new tables were created for recording changes (AuditLog and AuditLogDetails).

*Decide which tables you want to track and apply [TrackChanges] attribute to the classes. In case you want to skip tracking for some specific columns, you can apply [SkipTracking] attribute to those columns (properties).

*Whenever you make a change in database, you call DbContext.SaveChanges(). Now you have an overload available for that which takes an integer. This should be the logged-in person's user ID. If you don't pass the user ID, this change will not be recorded into the tracking table.
databaseContext.SaveChanges(userId);

And that's all. Later you can retrieve the logs with this:
var AuditLogs = db.GetLogs<Proyecto>(id).ToList();

A: Create a class for capture the changes or track the changes when entity added, modifies or deleted.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Web;

namespace MVC_AuditTrail.Models
{
    public class AuditTrailFactory
    {
        private DbContext context;

        public AuditTrailFactory(DbContext context)
        {
            this.context = context;
        }
        public Audit GetAudit(DbEntityEntry entry)
        {
            Audit audit = new Audit();
            // var user = (User)HttpContext.Current.Session[":user"];
            audit.UserId = "swapnil";// user.UserName;
            audit.TableName = GetTableName(entry);
            audit.UpdateDate = DateTime.Now;
            audit.TableIdValue = GetKeyValue(entry);

            //entry is Added
            if (entry.State == EntityState.Added)
            {
                var newValues = new StringBuilder();
                SetAddedProperties(entry, newValues);
                audit.NewData = newValues.ToString();
                audit.Actions = AuditActions.I.ToString();
            }
            //entry in deleted
            else if (entry.State == EntityState.Deleted)
            {
                var oldValues = new StringBuilder();
                SetDeletedProperties(entry, oldValues);
                audit.OldData = oldValues.ToString();
                audit.Actions = AuditActions.D.ToString();
            }
            //entry is modified
            else if (entry.State == EntityState.Modified)
            {
                var oldValues = new StringBuilder();
                var newValues = new StringBuilder();
                SetModifiedProperties(entry, oldValues, newValues);
                audit.OldData = oldValues.ToString();
                audit.NewData = newValues.ToString();
                audit.Actions = AuditActions.U.ToString();
            }

            return audit;
        }

        private void SetAddedProperties(DbEntityEntry entry, StringBuilder newData)
        {
            foreach (var propertyName in entry.CurrentValues.PropertyNames)
            {
                var newVal = entry.CurrentValues[propertyName];
                if (newVal != null)
                {
                    newData.AppendFormat("{0}={1} || ", propertyName, newVal);
                }
            }
            if (newData.Length > 0)
                newData = newData.Remove(newData.Length - 3, 3);
        }

        private void SetDeletedProperties(DbEntityEntry entry, StringBuilder oldData)
        {
            DbPropertyValues dbValues = entry.GetDatabaseValues();
            foreach (var propertyName in dbValues.PropertyNames)
            {
                var oldVal = dbValues[propertyName];
                if (oldVal != null)
                {
                    oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
                }
            }
            if (oldData.Length > 0)
                oldData = oldData.Remove(oldData.Length - 3, 3);
        }

        private void SetModifiedProperties(DbEntityEntry entry, StringBuilder oldData, StringBuilder newData)
        {
            DbPropertyValues dbValues = entry.GetDatabaseValues();
            foreach (var propertyName in entry.OriginalValues.PropertyNames)
            {
                var oldVal = dbValues[propertyName];
                var newVal = entry.CurrentValues[propertyName];
                if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
                {
                    newData.AppendFormat("{0}={1} || ", propertyName, newVal);
                    oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
                }
            }
            if (oldData.Length > 0)
                oldData = oldData.Remove(oldData.Length - 3, 3);
            if (newData.Length > 0)
                newData = newData.Remove(newData.Length - 3, 3);
        }

        public long? GetKeyValue(DbEntityEntry entry)
        {
            var objectStateEntry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
            long id = 0;
            if (objectStateEntry.EntityKey.EntityKeyValues != null)
                id = Convert.ToInt64(objectStateEntry.EntityKey.EntityKeyValues[0].Value);

            return id;
        }

        private string GetTableName(DbEntityEntry dbEntry)
        {
            TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
            string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;
            return tableName;
        }
    }

    public enum AuditActions
    {
        I,
        U,
        D
    }
}

Then create audit table entity and context class.
And Override savechanges method in this method get audit changes and save before base entity saved.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;

namespace MVC_AuditTrail.Models
{
    public class Student
    {
        public int StudentID { get; set; }

        public string Name { get; set; }

        public string  mobile { get; set; }
    }

    public  class Audit
    {
        public long Id { get; set; }
        public string TableName { get; set; }
        public string UserId { get; set; }
        public string Actions { get; set; }
        public string OldData { get; set; }
        public string NewData { get; set; }
        public Nullable<long> TableIdValue { get; set; }
        public Nullable<System.DateTime> UpdateDate { get; set; }
    }

    public class StdContext : DbContext
    {
        private AuditTrailFactory auditFactory;
        private List<Audit> auditList = new List<Audit>();
        private List<DbEntityEntry> objectList = new List<DbEntityEntry>();
        public StdContext() : base("stdConnection")
        {
            Database.SetInitializer<StdContext>(new CreateDatabaseIfNotExists<StdContext>());
        }

        public DbSet<Student> Student { get; set; }
        public DbSet<Audit> Audit { get; set; }

        public override int SaveChanges()
        {
            auditList.Clear();
            objectList.Clear();
            auditFactory = new AuditTrailFactory(this);

            var entityList = ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);
            foreach (var entity in entityList)
            {
                Audit audit = auditFactory.GetAudit(entity);
                bool isValid = true;
                if (entity.State == EntityState.Modified && string.IsNullOrWhiteSpace(audit.NewData) && string.IsNullOrWhiteSpace(audit.OldData))
                {
                    isValid = false;
                }
                if (isValid)
                {
                    auditList.Add(audit);
                    objectList.Add(entity);
                }
            }

            var retVal = base.SaveChanges();
            if (auditList.Count > 0)
            {
                int i = 0;
                foreach (var audit in auditList)
                {
                    if (audit.Actions == AuditActions.I.ToString())
                        audit.TableIdValue = auditFactory.GetKeyValue(objectList[i]);
                    this.Audit.Add(audit);
                    i++;
                }

                base.SaveChanges();
            }

            return retVal;
        }
    }
}

A:   public override int SaveChanges()
        {
            var auditEntries = new List<AuditEntry>();

            var modifiedEntities = ChangeTracker.Entries()
                .Where(p => p.State == EntityState.Modified).ToList();

            foreach (var change in modifiedEntities)
            {
                var auditEntry = new AuditEntry(change);
                var primaryKey = GetPrimaryKeys(change);
                auditEntry.TableName = change.Entity.GetType().Name;//get table name
               // var id = change.CurrentValues.GetValue<object>("Id").ToString();//get current id
                auditEntry.EntityId = primaryKey.ToString();
                auditEntry.EntityTypeId = primaryKey.ToString();
                auditEntries.Add(auditEntry);

                foreach (var prop in change.OriginalValues.PropertyNames)
                {
                    if (prop == "Id")
                    {
                        continue;
                    }

                    switch (change.State)
                    {
                        case EntityState.Modified:
                            if ((change.State & EntityState.Modified) != 0)
                            {
                                auditEntry.OldValues[prop] = change.OriginalValues[prop].ToString();
                                auditEntry.NewValues[prop] = change.CurrentValues[prop].ToString();
                            }
                            break;
                    }

                }
                foreach (var auditEntry1 in auditEntries.Where(_ => !_.HasTemporaryProperties))
                {
                    Audits.Add(auditEntry1.ToAudit());
                }
            }
            return base.SaveChanges();
        }

        private object GetPrimaryKeys(DbEntityEntry entry)
        {
            var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);

            return objectStateEntry.EntityKey.EntityKeyValues[0].Value;

        }

A: Another option is to create an audit action attribute to allow methods to be decorated with an attribute describing the audit operation. Just inherit from Attribute and list the information you want to capture in the constructor, then create an interceptor (inherit from castle) to intercept request to a method. The interceptor will invoke the audit service (which is just a simple class that will write the audit message to the database).


text:
Q: How to debug a docmd.transferdatabase statement that does not work (no compiler error, simply does not xfer the data) I'm a new VBA programmer trying to append everything from a TableA in Database1 to a TableA in Database2. I wrote a DoCmd.TransferDatabase statement called in an access macro. The statement executes without any error, but it does not transfer the data.
-->RUNS IN Database1...
DoCmd.TransferDatabase acExport, "Microsoft Access", "I:\Database2.mdb", acTable,
"TableA", "TableA", True

I don't really know how to debug this, because the statement is executing without an error from the compiler and there is no way to "see" what happens once it fires.
-The path/table names are correct because if they are wrong, the compiler throws an error (learned the hard way...!)
What should I do to debug?

A: You used True for the StructureOnly parameter.  From Access' online help topic for TransferDatabase:
Use True (–1) to import or export only the structure of a database table. Use False (0) to import or export the structure of the table and its data. If you leave this argument blank, the default (False) is assumed.
So the moral of that story is use False if you want to transfer TableA and any data it contains.  Use True if you want to transfer only the table structure without any data it contains.


text:
Q: Releasing locks to temp files after ArcPy script crashes in ArcMap? Sometimes when I'm testing an ArcPy script and it ends with exception, ArcMap is still holding locks to some temp files (I run my scripts through ArcMap).
I cannot run the script any more, because it cannot delete/overwrite the temp files and in the end I have to restart ArcMap to release the locks.
Is there a way to do in a more clever fashion?

A: I've just come up with the following construction:
def main():
    # my entire code

if __name__ == "__main__":
    try:
        main()
    except Exception, e:
        import gc
        gc.collect()
        import traceback
        arcpy.AddError(traceback.format_exc())

This way I don't loose any messages and so far all locks have been released properly.

A: You can delete all variables set and cursor rows within a try/except block:
try:

  # your code here

except:
  # delete your variables here
  del myVariable1, myVariable2, myVariable4, row, rows

A: The easiest way might be to just open Windows Task Manager (Alt+Ctrl+Del) and stop the python.exe process after the script crashed. After this the locks should be gone.
When you restart your script, python.exe will be restarted as well.

A: I have not tested this but a GeoNet link by its user john.m.dye that arrived in my mailbox today suggests a way to do this (at least with ArcGIS Pro, but worth investigating for ArcMap equivalency too):

For local file geodatabases, the compact geodatabase tool will
  remove any invalid locks on the geodatabase that might not have been
  properly removed when editing stopped. For Enterprise Geodatabases,
  use the disconnect user tool to kill any active connections users
  have to the database, which should also kill their locks. You can
  follow that up with accept connections to block users from
  reconnecting while you do your thing, call compact geodatabase to
  ensure there are no invalid locks, do what you need to do, then call
  accept connections again to allow users to reconnect.


text:
Q: Override onStop everywhere? Intro:
I have made a fadeout/fadein which fades out the opacity of all views. I want to animate this between switching activities. I now have to add the fadein/fadeout to every onStop/onResume in every activity.
Question: Is it possible to create a custom overridden onStop function and use that in every activity?

A: Create a base activity like this
public abstract class BaseActivity extends Activity {

..................
..................
    @Override
    public void onStop() {
        super.onStop();
        // Do your stuff
    }
....................
...................
}

Now in every activity extend the base actiity like
public class Activity1 extends BaseActivity

A: Yes, you can definitely override the onStop() function.  Make an activity StopperActivity with onStop overrider
@Override
public void onStop() {
    super.onStop();

}

In other activities, just extend this custom activity instead of Activity

A: Create class BaseActivity
for example
class BaseActivity extends Activity
{
   void onResume()
   {
      super.onResume();
       // your code here (Need to write only once for entire app)
   }
   void onStop()
   {
        super.onStop();
       // your code here of onStop (Need to write only once for entire app)
   }
}

And now use this BaseActivity for all your activities in your class.
class MainActivity extends BaseActivity
{
   ...
}
class AnotherActivity extends BaseActivity
{
   ...
}

In this way you will need to write code only once for fadeIn and fadeOut in BaseActivity.

A: This is a suggestion rather than the answer to your questions.
Based on your description, it seems like you want to define a custom transition animation between activities. Why not just define a Style? All you need to do is define windowExitAnimationand windoEnterAnimation in your custom style, and then override windowAnimationStyle.
Check out the developer guide on how how to define your own style Styles and Themes.


text:
Q: Can I determine when a default printer was set on windows We are trying to trace the time a windows default printer was changed and by who or what.
Any ideas?

A: I don't think that is tracked anywhere. For past changes, you might be out of luck.
For future changes, you could try setting up security auditing (via regedit: Permissions->Acvanced->Auditing) on HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows and watch for changes to that key in the Security event log. The amount of security event messages may make tracking difficult, though.


text:
Q: How to have a multicolumn list in markdown I made an R notebook, where I put a model and a list of its parameters:
this is the model
$$
\begin{align}
    & y_{t} = \tau_{t} + c_{t}\\
    & \tau_{t}  = \mu +\tau_{t}+\varepsilon_{t}, \quad \varepsilon_{t} \sim N(0, \sigma^{2}_{\varepsilon})\\
    & c_{t} = \rho_{1} c_{t-1}+\rho_{2} c_{t-2}+\eta_{t}, \quad \eta_{t}\sim N(0, \sigma^{2}_{\eta})
\end{align}
$$

And then I want to put the list of parameters in 5 columns (so 5 columns 2 rows), in LaTeX I would do this:
\begin{multicols}{5}
    \begin{itemize}
    \item $\mu = 0.009$
    \item $\rho_{1} = 1.25$
    \item $\rho_{2} = -0.26$
    \item $\sigma_{\varepsilon} = 0.0007$
    \item $\sigma_{\eta} = 0.0003$
    \item $c_{0} = 0.01$
    \item $c_{1} = -0.01$
    \item $\tau_{1} = 14$
    \item $T = 50,000$
    \item $N = 300$
\end{itemize}
\end{multicols}

with the package multicol, visually is this:

how can I accomplish this in rmd? Is it possible?


text:
Q: Fastest way to find if a Group of potentials exists in a list of all solutions in Python I am attempting this for something other than the example, but I thought this would be the easiest explanation.
Consider you have a chain of potential items and want to find if that exists in a known list of solutions.
    solutions = ['GAT','CAT','GCT']

And you have the potentials of:
    potentials = [['G','T'],['T','A'],['T']]

Such that you would be able to determine that GAT is the only solution that can be created from the potential.
AND
You want to find all potential solutions such that
    potentials = [['G','C','A','T'],['G','C','A','T'],['G','C','A','T']]

Would return ['GAT','CAT','GCT'] since all solutions could be made from the potential.
My current solution simply builds all the combinations using a JOIN and then does an intersection.
Because of the next step, an ideal solution would actually return a the solutions such that viable options from each item was output such that:
    solutions = ['GAT','CAT','GCT']
    potentials = [['G','C','A','T'],['G','C','A'],['A','T']]
    imaginaryfunction(potentials, solutions)

Would return:
     [['G','C'],['C','A'],['T']]

If it matters, in my real world case there are 30-ish "letters", and any given item in the potential list could be up to 8 of those "letters". The solutions list is about 2000 three letter combinations. In an ideal world there is only 1 combination that works, but more typically there are 4 or 5 and it is possible but highly improbable to have have all 2000 be possible.
I have experimented with some pretty wild things ranging from joins, to making a base 30 number out of each combination so that I could just check if the number was in the list to breaking all of the solutions down into a dictionary of dictionaries and seeing if the items were there.
My code loops through this 100s of thousands if not millions of times so even small gains add up fast for me.
Edit/Additional Info:
This is used in several places. I am working with a group that does drug interaction simulations, and for them they are looking at chains which could be attachment/bonding points.
It is also used with a company that does those "Personal Stylist will pick your wardrobe" monthly boxes. (In that case it might be XS,S,M,L,LT,XL,XXL for the first match set, and Red,Green,Blue,Black,White for a second with Sleeve Length for the third) (they don't actually have someone pick what goes in the boxes)
Same block of code is also in my code for NGram Analysis.
Same block of code is in Dating app as Race(s), Gender(s), Age(s), Income(s)

A: Since your set of solutions is quite small (2000) compared to the theoretical number of possible combinations (order of 30^8) I think something like this could work:
solutions = get_possible_solutions()
for i, pset in enumerate(potentials):
    matching_solutions = []
    for sol in solutions:
        if sol[i] in pset:
            matching_solutions.append(sol)
    solutions = matching_solutions # Remove non-matches

This solution iteratively filters the possible solutions using the potentials for the current letter in the item "string".
The inner loop will get smaller every iteration, so this has the potential to be quite fast.
It should at least be a lot faster than doing an explicit intersection between all possible solutions and the input solutions.


text:
Q: html2canvas.js crashing script

  angular.forEach(ids, function (value) {
                var bigCanvas = null; var newWidth = 0; var newHeight = 0; var newMargin = 0;
               // var div = document.querySelector("#" + value);
                var bigCanvas = document.createElement('canvas');
                html2canvas($("#" + value)[0], { canvas: bigCanvas }).then(function (canvas) {
                    var ctx = canvas.getContext('2d');
                    ctx.webkitImageSmoothingEnabled = false;
                    ctx.mozImageSmoothingEnabled = false;
                    ctx.imageSmoothingEnabled = false;
                    ctx.scale(2, 2);
                    var imgsrc = canvas.toDataURL({ format: 'png', quality: 0.01 });
                    var imageData = imgsrc.replace('data:image/png;base64,', '');
                    auditService.auditPostPowerPoint(baseUrl + value, imageData)
                                .then(function (response) {
                                    var res = response.data;
                                    count = count + 1;
                                    if (count == 7) {//below method will be call after 'auditGridData' and 'auditChartImage' will save

                                        auditService.getByFilter("api/auditPowerpointDownload", { plantName: $scope.auditInfo.plant, auditorName: $scope.auditInfo.auditor + "," + $scope.auditInfo.coAuditor })
                                        .then(function (response) {
                                            auditService.download("api/auditPowerPointResultdownload");
                                            $scope.spinnerVisible = false;
                                        });
                                    }
                                }, function (error) {

                                });
                }).catch(function (error) {
                    var err = error;
                    console.log("errror", err);
                });

            });
 <script src="~/Content/App/scripts/commonJS/html2canvas.min.js"></script>

Following is my code not working on internet explorer 9+ .I done implementation part using promise js for supporting promise in internet explorer
step1:

step2:

error in internet explorer :


text:
Q: bundler: command not found: rakep --- while building emberjs todo I'm trying to build the emberjs todos from https://github.com/emberjs/todos.... While executing the command bundle exec rakep build , I got the following error
**bundler: command not found: rakep**

**Install missing gem executables with 'bundle install'**

I'm using Ruby 1.9.3 and i have included the required gems
Gems included by the bundle :
 * bundler (1.0.22
  * chunky_png (1.2
  * compass (0.12.2
  * fssm (0.2.9)
  * json (1.5.4)
  * rack (1.4.1)
  * rake (0.9.2.2)
  * rake-pipeline (0.6.0)
  * rake-pipeline-web-filters(0.6.0)
  * sass (3.2.1)
  * thor (0.14.6)

Can anyone help to trace out the bug ???

A: I realize this question is really old and this is probably not a direct answer, but I ran into a similar problem trying to get the ember_phonegap_starter template up and running (it uses rakep server at some point in the webcast).
Being a complete Ruby newbie and only interested in ember.js rather than learning yet another ecosystem, I ended up cobbling together some commands based on Yuhuda Katz's answer here (link) and some trial and error. Someone might be able to refine this answer further. My steps on a Windows 7 machine:

*

*Install Ruby 2.0.0 from the Ruby installer site.

*Download the Ruby Development Kit.

*Copy the development kit into the c:\ruby200 directory and run the .exe from there.

*Open a command prompt in the c:\ruby200 directory and type:

ruby dk.rb init
ruby dk.rb install

*Now install rakep and friends:

gem install rake-pipeline
gem install rake-pipeline-web-filters
gem install rack
gem install barber

*At this point I was able to run rakep from the command line. I don't know that installing all those other bits are necessary for what you were trying to do.


text:
Q: The decorators Plugin when .version is '2018-09' or not specified, requires a 'decoratorsBeforeExport' option, whose value must be a boolean I am getting the following Babel error

The decorators Plugin when .version is '2018-09' or not specified, requires a 'decoratorsBeforeExport' option, whose value must be a boolean. ..../node_modules/@babel/plugin-proposal-decorators/lib/index.js$inerhits

This is my babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    'react-native-reanimated/plugin',
    [
        "@babel/plugin-proposal-decorators",
        {
            "legacy": true,
            "decoratorsBeforeExport": false // I tried this with true as well -> no luck either
        }
    ]
 ]
};

This are the versions I am using
    ....
"dependencies": {
    "react": "17.0.2",
    "react-native": "0.66.4"
    ...

"devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/plugin-proposal-decorators": "^7.17.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.66.2",
    ...

A: Try this. It worked for me
module.exports = {
    presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
    plugins: [['@babel/plugin-proposal-decorators', { legacy: true }]]

};

A: Make sure to re-run your project when you add these lines. Hot reloading won't work here.
Also, it's good to run $ watchman watch-del-all and npm start -- --reset-cache

A: That error used to be related to an issue on how you installed your '@babel/plugin-proposal-decorators'. Try to reinstall it as a regular dependency, not dev dependency.
More information here: https://github.com/electron-userland/electron-webpack/issues/251#issuecomment-504693323


text:
Q: How to display UIActivityIndicatorView while a SceneKit Scene loads The scene load takes about 7-9 seconds. So I need an activity indicator.
I create the spinner like this:
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    spinner.layer.cornerRadius = 5;
    spinner.opaque = NO;
    spinner.backgroundColor = [UIColor clearColor];
    spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [spinner setColor:[UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]];

Add the sub view like this:
    [sceneView addSubView:spinner];

Tried calling in viewDidLoad:
[spinner startAnimating];
//load the scene
[spinner stopAnimating];

But it spins away forever and scene never loads.
What is the correct way to do this?
I tried this based on @mnuages response:
- (void)renderer:(id<SCNSceneRenderer>)aRenderer willRenderScene:(SCNScene *)scene atTime:(NSTimeInterval)time  {

if ([self spinner] == nil) {
    _spinner = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 250, 250)];
    _spinner.layer.cornerRadius = 5;
    _spinner.opaque = YES;
    _spinner.backgroundColor = [UIColor purpleColor];
    _spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [_spinner setColor:[UIColor colorWithRed:0.6 green:0.8 blue:1.0 alpha:1.0]];
    _spinner.center = self.view.center;

    [self.view addSubview:_spinner];
    [self.view bringSubviewToFront:_spinner];
    [[self spinner] startAnimating];
}

NSLog(@"BEGIN SCENE RENDER %@",scene);

}
- (void)renderer:(id<SCNSceneRenderer>)aRenderer didRenderScene:(SCNScene *)scene atTime:(NSTimeInterval)time  {

[[self spinner] stopAnimating];
[_spinner removeFromSuperview];
_spinner = nil;

NSLog(@"END SCENE RENDER %@", scene);

}
But this gets called repeatedly.  And the spinner doesn't show.   And I still see a blank white screen  (the SCNView's initial white background color set in IB, which is changed later to  gray in the viewDidLoad).

A: you can have a look at SCNSceneRenderer.delegate and -renderer:didRenderScene:atTime:


text:
Q: 18.04 Total Loss of Connectivity (Wifi&Eth) after Update I left my Ubuntu 18.04 to download the new packages from software updater. When I got back I had no more internet connectivity. If I try ping google.com I get
ping: sendmsg: Operation not permitted

I tried to connect via ethernet as well no to avail, I also tried another connection at another house, still to no avail. All my other devices are working fine. So it`s not something that has to do with router (which I tried to reset a couple of times). My router sees my computer in the list of connected devices. When I try to access router from my computer at 192.168.1.1 the connection times out. Everything (gateway, ip, etc) is set to default. I tried flushing the routing table which didn't help (might have created more problems). I've been trying to fix this for a day or so but unfortunately haven't figured it out yet! would appreciate the help
update:ran nmcli device
wlp2s0:connected to NETGEAR 22
"Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter'
wifi (ath9k), B8:EE:65:8B:84:68, hw, mtu 1500
ip4 default
inet4 192.168.1.3/24
route4 0.0.0.0/0
route4 192.168.1.0/24
route4 169.254.0.0/16
inet6 fe80:fd5f:7f15:c5d4:4067/64
route6 ff00::/8
route6 ff80::/64
route6 ff08::/64

enp1s0fi: unavailable
"Realtek RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller"
ethernet (r8169), F8:A9:63:72:7C:82, hw, mtu1500

lo: unmanaged
"lo"
loopback (unknown), 00:00:00:00:00:00, sw, mtu 65536

DNS configuration:
servers: 192.168.1.1
interface: wlp2s0

Edit: seems like a few people are having network issues after updating, might be a kernel update? Did try to boot using 4.15.0-70-generic but no luck.


text:
Q: Are "Live Races" actually dynamically generated levels? In Grid 2, one of the race types is called "Live Race", your engineer informs you that these races can change at any time and you're not provided with a map, which implies that these races are dynamically generated levels.
However, I've found that if I restart one of these races, I always seem, to get an identical track. Is it that these tracks are generated and then reused in the event you restart the race or are these actually not dynamically generated tracks at all?
Are "Live Races" actually dynamically generated levels?

A: Restarting a race doesn't re-load the level. Perhaps the manager's explanation is a little misleading, in that they don't really change at on the fly because they're generated before you play them. The liveroutes stitch together a bunch of 'pieces' of track from an area, and that generation is random, as far as I can tell.
They way I understand it working is that the entire route is planned out when the game is loading the map, and then you race on it, rather than it being done dynamically as you're driving. The route then doesn't change when you just pick "restart" to cut down on load times; if it generated an entirely new layout, you'd be waiting 15 seconds to load when you restart rather than it being instantaneous. If you exit out of the race, back to the menus, and then load it again, the track should be different. You'll likely start in a different spot on the map, but you'll probably recognize some of the corners and areas if you've done a race there prior.

A: They are not dynamic, but predefined. You can check the variations in \tracks\locations\cities\city_name\route#\dynamic_routes.xml
Please note that altering this file will result in loss of Racenet connectivity and therefore no recorded race times or Steam achievements.


text:
Q: CSS animation-play-state issue: Animation jumps back to initial frame when resumed? I got something like following which is a CSS animation that cross-fades between two images:
HTML

CSS
body {
    background: black;
    overflow-y: hidden;
}
#bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
img {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
}
img:last-child {
    -webkit-animation: test 30s infinite alternate;
}
@-webkit-keyframes test {
    from {
        opacity: 1;
    }
    to {
        opacity: 0;
    }
}

And there is a JavaScript snippet like this that toggles the animation on and off periodically:
JavaScript
var state = 'running';

setInterval(function() {
    $('img:last-child').css({
        '-webkit-animation-play-state': state
    });

    state === 'running' ? state = 'paused' : state = 'running';
}, 1000);

The problem is, there is a chance that some display glitch will show up when the animation is resumed ('paused' -> 'running'), and the chance varies depending on the kind of devices you are running the page against.
If you are running the page on some cutting edge machine, things just look pretty smooth; however, if you switch to another browser tab, then switch back, there is a chance that you'll see your animation very obviously jumping back from the middle of the animation to the first frame (that img:last-child's opacity suddenly goes back to 1) and start anew.
On the other hand if you are running against a weak device, you can see the glitch without switching browser tabs: almost every time the animation resumes, there will be a flickering moment when img:last-child's opacity is briefly set to 1 and visually "emerged", before the animation can pick up from its last proper state and continue.
Is this simply a WebKit bug with nothing I can do to avoid, or is there some tricky way to tweak my codes so that this annoying flickering of the initial frame can be dealt with?

A: In java script change the condition value. Dont use playing state. Only use pasued state at the time out 1000s...


text:
Q: How to use async / await with a method returning an ObservableCollection I am writing a WPF application using MVVM pattern. I must say I am not (yet) familiar with the .NET async programming model (just learning it) but was writing multi-threaded applications in C/C++ and Java for many years.
The idea is to start long running queries in a separate thread from the UI thread so I have a chance to display a spinner or progress bar while the operation is running.
Most of my internal service methods return collections or other complex types like DTO's etc. The results are usually bound to user controls such as GridViews, ListViews etc. I always get compiler errors saying that my return types do not contain a definition for 'GetAwaiter'. So I must be doing something wrong.
Here is an example of such a method in my ViewModel that calls a service which does a DB query and returns an ObservableCollection.
    private async void GetInvoices()
    {
        IsOperationRunning = true; //Binding for a RadBusyIndicator
        Invoices = await _uiContractService.GetInvoices(SelectedInvoiceState, SelectedSupplierItem.Id, SelectedInvoiceDateFilter, FilterStartDate, FilterEndDate);
        IsOperationRunning = false;
        RaisePropertyChanged(() => Invoices);
        if (Invoices.Count == 0)
            SendUserInfoMsg($"NO invoices matched your search criteria.", UiUserNotificationMessageType.Warning);
    }

The compiler error in this case is:
ObservableCollection<InvoiceDto>' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'ObservableCollection<InvoiceDto>' could be found
The Invoices collection and the service are declared as
    public ObservableCollection<InvoiceDto> Invoices { get; set; }
    var _uiContractService = SimpleIoc.Default.GetInstance<UiContractService>();

The signature of the service method is as follows:
public ObservableCollection<InvoiceDto> GetInvoices(InvoiceState invoiceState, Guid supplierId, UiInvoiceDateFilters dateType, DateTime begin, DateTime end)

Any help to guide me into the right direction is greatly appreciated.

A:
was writing multi-threaded applications in C/C++ and Java for many years.

This experience is probably misleading you. Asynchronous code is very different than multithreaded code.
await has nothing to do with threads. Or put another way, it doesn't increase the number of threads used; it decreases them.
I recommend you first read my async intro to get an idea of what async/await actually do.
Then, you can proceed one of two ways. The first way is not ideal, but is what you actually asked for:

The idea is to start long running queries in a separate thread from the UI thread so I have a chance to display a spinner or progress bar while the operation is running.

The first approach is to multithread. In this case, you can use async/await as a convenient way to retrieve results from an operation running on another thread (including clean, correct exception stacks):
private async Task GetInvoicesAsync()
{
  IsOperationRunning = true; //Binding for a RadBusyIndicator
  Invoices = await Task.Run(() => _uiContractService.GetInvoices(SelectedInvoiceState, SelectedSupplierItem.Id, SelectedInvoiceDateFilter, FilterStartDate, FilterEndDate));
  IsOperationRunning = false;
  RaisePropertyChanged(() => Invoices);
  if (Invoices.Count == 0)
    SendUserInfoMsg($"NO invoices matched your search criteria.", UiUserNotificationMessageType.Warning);
}

Note that it is the Task.Run that introduces multithreading - it schedules work to the thread pool. The async/await is how the UI thread pretends the operation is asynchronous.
This can be called from an event handler (or ICommand) as such:
public async void EventHandler(object sender, ...)
{
  await GetInvoicesAsync();
}

Note that only event handlers should be async void. See my article on async best practices for more information.

But the first approach isn't ideal, because it's not really asynchronous. It's what I call "fake-asynchronous"; that is, the UI is pretending it's asynchronous, but the actual operation is just synchronously blocking another thread.
When writing true asynchronous code, it's easier to start at the other end - not the top-level UI methods, but the low-level actual API calls. If your services are HTTP services, look into HttpClient; if they're WCF services, regenerate your proxies with asynchronous APIs enabled.
Once you have the lowest-level asynchronous APIs available, start using them. Eventually, you'll end up with an asynchronous GetInvoices:
public async Task<List<InvoiceDto>> GetInvoicesAsync(InvoiceState invoiceState, Guid supplierId, UiInvoiceDateFilters dateType, DateTime begin, DateTime end);

(note that I removed ObservableCollection from your service layer since it is a UI-oriented type)
Then you can call this method as such:
private async Task GetInvoicesAsync()
{
  IsOperationRunning = true; //Binding for a RadBusyIndicator
  Invoices = new ObservableCollection<InvoiceDto>(await _uiContractService.GetInvoicesAsync(SelectedInvoiceState, SelectedSupplierItem.Id, SelectedInvoiceDateFilter, FilterStartDate, FilterEndDate));
  IsOperationRunning = false;
  RaisePropertyChanged(() => Invoices);
  if (Invoices.Count == 0)
    SendUserInfoMsg($"NO invoices matched your search criteria.", UiUserNotificationMessageType.Warning);
}

This time, there's no Task.Run or any other explicit usage of thread pool threads.
For more details, see the "Transform" parts of my brownfield async article.

A: Your code should return a Task.
public Task<ObservableCollection<InvoiceDto>> GetInvoices(InvoiceState invoiceState, Guid supplierId, UiInvoiceDateFilters dateType, DateTime begin, DateTime end)
{
  // your code
}

A: Is GetInvoices doing anything async? If it is, its signature should be:

public async Task<ObservableCollection<InvoiceDto>> GetInvoices(InvoiceState invoiceState, Guid supplierId, UiInvoiceDateFilters dateType, DateTime begin, DateTime end).
If you aren't, then you shouldn't worry about async and remove the async/await keywords from the outer GetInvoices method.
If you want to await something, it should return Task or Task<T>. (I won't even go into async void methods).

A: You con do a "fake" asynchronous task out of your GetInvoices:
public async Task<ObservableCollection<InvoiceDto>> GetInvoicesAsync(InvoiceState invoiceState, Guid supplierId, UiInvoiceDateFilters dateType, DateTime begin, DateTime end)
{
    return await Task.Run( () =>
    {
         return GetInvoices(invoiceState, supplierId, dateType, begin, end);
     });
}

This could be considered bad code, here it's simply to show how you can make it formally await-able by calling the method with Async suffix
Anyway this is wpf, not a asp.net or a web app. So if it's a pure desktop GUI, it would make sense to run a db task in background. It's more problematic if that were on an application server and not on a client..
    Invoices = await _uiContractService.GetInvoicesAsync(SelectedInvoiceState, SelectedSupplierItem.Id, SelectedInvoiceDateFilter, FilterStartDate, FilterEndDate);

Notice that there is a big difference between a wrong and a not ideal thing and that it is not always the case that you can have immediate support for an upgrade to the latest technology.
Another point that you're not asking but looks odd is how you raise property changed.
A much more convenient place is the setter of the property.
 Then you don't need to call it after an assignment unless you are using the underlying private member.
I would have also cleaned the collection before just to enphasize the work in progress but these are personal preferences.


text:
Q: Filter out value in foreach loop if it does not match any values in enum How can I skip a value in a foreach loop if it does not match any of the values in an specific enum. Ex:
public enum IDs
{
    SomeIdOne = 1001,
    SomeIdTwo = 1002,
    SomeIdThree = 1003
}

// one of the list items(7777) does not match what's in the IDs enum
var SomeIds = new List<IDs>() { 1002,7777,1001 };

// skip that item when looping through the list.
foreach (IDs id in SomeIds)
{
    // do things with id
}

In the past I have used LINQ to filter out 0 in a similar situation, can I do something like that here?

A: Try
foreach(var id in SomeIds.Where(x => Enum.IsDefined(typeof(IDs), x)))
{
    //....
}

If SomeIds is a list of integers, add Cast:
foreach(var id in SomeIds.Where(x => Enum.IsDefined(typeof(IDs), x)).Cast<IDs>())


text:
Q: Targeting a tablet without using media queries I'm just wondering if it is possible to target a tablet without using media queries. The reason I ask this is that I already using media queries but I have images that are grayscale on desktop and when hovered they change to the original colour. I have removed the grayscale when the device hits a certain size so it is fine on smaller tablets and mobiles but it is just a bit too small for the ipad and certain tablets when they are landscaped.
Is there any way to target the tablet to turn the filter off without touching the media queries?
Thanks in advance
The website in question is www.garethjweaver.com

A: Have a look at the Mobile ESP framework; specifically the JavaScript one. It can detect individual devices or groups of devices such as tablets.
http://blog.mobileesp.com/
The method most pertaining to what you want to achieve is:
MobileEsp.DetectTierTablet();

It also allows you to pick specific groups of tablets by OS:
MobileEsp.DetectAndroidTablet();
MobileEsp.DetectWebOSTablet();
MobileEsp.DetectIpad();
MobileEsp.DetectMaemoTablet();
MobileEsp.DetectBlackBerryTablet();
MobileEsp.DetectOperaAndroidTablet();

A possible usage scenario:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://www.hand-interactive.com/js/mdetect.js"></script>
<script>
    $(function() {

        if(MobileEsp.DetectTierTablet()) { // if its a tablet this will be true

            $("html").addClass("isTablet"); // this will add the isTablet class to the HTML element

        }
    });
<script>

The example above uses jQuery, which will make things easier for you if you are getting started with JavaScript. With that in place you just need to set up rules for your tablets in your stylesheet like this:
<style>
    body {
        max-width: 1200px;
    }
    .isTablet body {
        max-width: 100%;
    }
</style>

It also has other versions for ASP.NET and PHP so you can do the detection server side.
Here's a fiddle illustrating the functionality outlined above:
Fiddle

A: I get that you don't want to touch the media query, but as far as I can see it feels like your problem can be solved by
@media  (orientation: landscape) { ... }
You want to determine if it's a landscape view..right?
about other usages of media query MDN:media query
if you really don't want to touch it, there is another option is to use javascript. But I think that will be make things more complicated.
Hope my answer helps..:)


text:
Q: AutoCad: Getting 'Invalid object array exception' in Late Binding while copying Objects I have two drawings, dg1 and dg2. I have defined a block 'b1' in dg1 which I want to copy in dg2. It works well in Early Binding but giving error when I try code in late binding. The code in question is:
private void Form1_Load(object sender, EventArgs e)
        {
            AcadApplication m_oAcadApp = null;
            AcadCircle circle = null;
            AcadAcCmColor color = null;
            AcadDocument oSourceFile = null;
            AcadDocument m_oActiveDoc = null;
            try
            {
                object obj = Marshal.GetActiveObject("AutoCAD.Application.17");
                if (obj != null)
                {
                    m_oAcadApp = obj as AcadApplication;
                    m_oActiveDoc = m_oAcadApp.ActiveDocument;
                    foreach (AcadDocument oTempDoc in m_oAcadApp.Documents)
                    {
                        if((@"c:\d1.dwg").ToUpper() == oTempDoc.FullName.ToUpper())
                        {
                            Console.WriteLine(oTempDoc.FullName);
                            oSourceFile = oTempDoc;
                            break;
                        }

                    }
                    try
                    {
                        object[] objCollection = new object[1];
                        objCollection[0] = null;
                        objCollection[0] = oSourceFile.Blocks.Item("b1");
                        oSourceFile.CopyObjects(objCollection, m_oActiveDoc.Blocks);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Opening Blocks " + ex.Message);
                    }

                    /*double[] cen = new double[] { 0, 0, 0 };
                    circle = m_oAcadApp.ActiveDocument.Database.ModelSpace.AddCircle(cen, 2);
                    color = m_oAcadApp.GetInterfaceObject("Autocad.AcCmColor.17") as AcadAcCmColor;
                    color.SetRGB(150, 150, 250);
                    circle.TrueColor = color;
                    m_oAcadApp.ZoomExtents();
                     * */
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("AutoCAD not opened");
            }
            finally
            {
               // if (color != null) Marshal.FinalReleaseComObject(color);
                //if (circle != null) Marshal.FinalReleaseComObject(circle);
                if (m_oAcadApp != null) Marshal.FinalReleaseComObject(m_oAcadApp);
            }
        }

And I get exception: Invalid object array exception while I try to copy a block in other drawing.
How do I do it in late Binding?
I am using Autocad 2009.
The Objective of implement Late Binding for Autocad and copying Object
Thanks

A: You can late-bind cast to an object.
http://www.dicks-clicks.com/excel/olBinding.htm
You can use entities: http://msdn.microsoft.com/en-us/library/gg309272.aspx
or the Dynamic and cast to a similar object definition or property bag, if you will.
In Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online, you can use the Entity class when you work with entities. In Microsoft Dynamics CRM 4.0, you used the DynamicEntity class. When initialized, the Entity class contains the logical name of an entity and a property-bag array of the entity's attributes. This lets you use late binding so that you can work with types such as custom entities and custom attributes that were not available when your application was compiled. Because the entity base class always contains the property bag of attributes and values, the ReturnDynamicsEntities property from Microsoft Dynamics CRM 4.0 is no longer necessary.
The key difference between early and late binding involves type conversion. While early binding provides compile-time checking of all types so that no implicit casts occur, late binding checks types only when the object is created or an action is performed on the type. The Entity class requires types to be explicitly specified to prevent implicit casts.
It might look something like this then
blockCollection[0] = (ACadBlock)oSourceFile.Blocks.Item("b1");


text:
Q: Counting files, directories, etc. in given directory and formatting output on screen Just started a scripting class and could use some help. I am writing a script to inspect the file names of every file and directory in a given directory and accumulate a count of Every file, subdirectory, symlink, old files, graphics files, tmp files, exe files, and total byte count of each file within that directory.
The output needs to be formatted in this way:

*

*Directories n,nnn,nnn

*Files n,nnn,nnn

*etc...

When I run my script, it doesn't seem to count anything because all count items return 0. I am also having issues with formatting the numbers to have comma's. $1 is the directory the user will enter for searching when they run the script ie: ./srpt /etc. To run the search I am using the find command with printf to format the output and piping the output to wc to count the number of lines. I assume this would give me the number of files granted the file names are just one line. There are probably a billion ways to do this and this way might not be the most elegant, but I would appreciate anyone's input.
if [ -d "$1" ]; then
        directories=$(find "$1" -type d -printf "%'d" | wc -l)
        files=$(find "$1" -type f -printf "%'d" | wc -l)
        sym=$(find "$1" -type l -printf "%'d" | wc -l)

etc...
#Printing the output to the terminal
      echo "Directories" $directories
      echo "Files" $files
      echo "Sym links" $sym
      exit 0
else
        echo "[ERROR]: need path to perform search"
        exit 1
fi

My output:
Directories 0
Files 0
Sym Links 0

A: -printf "%'d" does nothing there so the counts are resulting 0, you need to change it with -printf "%p\n" instead.

A: You are needed change your commands to this form:
directories=$(printf "%'d\n" $(find "$1" -type f | wc -l))

printf uses the thousands separator for your current locale, which might be a comma, dot, or nothing at all. You can change locale if you want to force commas.
Also, you can do by such way:
if [ -d "$1" ]; then
    directories=$(find "$1" -type d | wc -l)
    files=$(find "$1" -type f | wc -l)
    sym=$(find "$1" -type l | wc -l)

and replace echo to printf
#Printing the output to the terminal

  printf "%s %'d\n" "Directories" $directories
  printf "%s %'d\n" "Files" $files
  printf "%s %'d\n" "Sym links" $sym

The error was happened, because you mixed up two different command - the bash's printf and the find's -printf.
For the find's -printf the "%'d" format is incorrect. The singular quote is not allowed and %d is file's depth in the directory tree. You can find all -printf options in the man find, by typing: /printf format.
By the way, it needed to add \n to both printf (bash's and find's): "%d\n", otherwise they will print the all output in the one line.


text:
Q: How do I color conditionally in a density plot? I am trying to make a density plot and mark part of the region based on the X value. The following snippet mostly works but has a weird angled cut-off between regions. How do I fix it?
np.random.seed(0)
df = pd.DataFrame({'x': np.random.normal(size=1000)})

(alt.Chart(df).
 transform_density('x', as_=['val', 'density']).
 transform_calculate(crit='(datum.val < -1.96) | (datum.val > 1.96)').
 mark_area().encode(
    x='val:Q',
    y=alt.Y('density:Q', impute={'value': 0}),
    color='crit:N'
 )
)

A: This happens because the area mark tries to interpolate linearly from where the blue and orange region ends to the bottom of the x-axis for each section of the area. If you set interpolate='step' you will see that the border is sharp (removing impute will improve it for the area). You can try to upsample the data to have the interpolation happen over such a small distance that it appears to be a straight vertical line and the areas look connected, more details in the answer to this question How to correctly shift the baseline in an area plot to a particular y location and change the fill color correspondingly, in Altair? .
Another solution is to layer the middle portion on top of the entire density plot:
import numpy as np
import pandas as pd
import altair as alt

np.random.seed(0)
df = pd.DataFrame({'x': np.random.normal(size=1000)})

chart = (
    alt.Chart(df)
    .transform_density('x', as_=['x', 'density'])
    .mark_area(color='coral')
    .encode(x='x', y=alt.Y('density:Q')))

chart + (
    chart
    .mark_area(color='steelblue')
    .transform_filter('(datum.x > -1.96) & (datum.x < 1.96)'))


text:
Q: samsung soft keyboard bug with $ character I noticed that when users type the $ character in an EditText a space is added.  For instance user types:
abcd$

however
abcd $

is entered in the EditText.  I've verified the issue on a Note 4 running Android 5.1.1 and an S6 Edge running Android 6.0.1. This is particularly problematic for password fields when users use the $ character in their password because it results in user login failures.
I've verified the issue doesn't exist in the emulator for the Nexus 5X running Android 5.1 and so I suspect this is a bug limited to the Samsung soft keyboard.
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true" />

see this video for a demo of a Note 4 running 5.1.1
Any suggestions or work-arounds would be greatly appreciated.
Added a TextWatcher:
        editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            Log.d(TAG, "New text: '" + s + "'");
        }
    });

This is from the log on the Note 4:
06-10 12:50:55.082 15187-15187/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'h'
06-10 12:50:55.237 15187-15187/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hs'
06-10 12:50:55.372 15187-15187/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hsh'
06-10 12:50:55.592 15187-15187/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hshf'
06-10 12:50:57.077 15187-15187/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hshf $'

when typing hshf$
This is from the Nexus 5X running in the emulator:
06-10 13:01:05.801 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'h'
06-10 13:01:06.421 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hs'
06-10 13:01:06.524 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hs'
06-10 13:01:08.848 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hsh'
06-10 13:01:09.803 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hshf'
06-10 13:01:09.908 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hshf'
06-10 13:01:13.902 3032-3032/test.apps.android.vp.org.keyboardtest D/MainActivity: New text: 'hshf$'