问:
How to play audio via a USB sound card using c++/libao/alsa on Raspberry Pi?
I get the following from aplay -l, lsusb:

pi@raspberrypi:~ $ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
  Subdevices: 8/8
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
  Subdevice #4: subdevice #4
  Subdevice #5: subdevice #5
  Subdevice #6: subdevice #6
  Subdevice #7: subdevice #7
card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 2: Device_1 [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
pi@raspberrypi:~ $ lsusb
Bus 001 Device 005: ID 046d:c31c Logitech, Inc. Keyboard K120 for Business
Bus 001 Device 008: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 007: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 006: ID 05e3:0606 Genesys Logic, Inc. USB 2.0 Hub / D-Link DUB-H4 USB 2.0 Hub
Bus 001 Device 004: ID 1bcf:0005 Sunplus Innovation Technology Inc.
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
```

<p>I want to play my MP3 via CM108 Audio Controllers with libao. I tried these:</p>

```ao_initialize();
ao_option aoption;
ao_option *poption;
poption = &aoption;
poption->key = (char*)"dev";
poption->value = (char*)"hw:0";
dev = ao_open_live(driver, &format, poption);
    while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
        ao_play(dev, (char *)buffer, done);
```

So sound is played via the Pi successfully. I understand that hw:0 is a sound card of the Pi. What should I use instead of hw:0 if I want to play via the first or second CM108 Audio Controller? I already tried hw:1 and hw:2 and it does not work.

答:
Try to follow below steps to enable audio recording and playback from a usb-sound adapter for rpi with alsa first. With this you can test your USB sound adapters are working correctly as input and output module.I have not tested before a usecase with above mentioned library in C++ code, will give it a try soon. Try by referring to "hw:1" later in your C++ code if it working.

Steps:
1.1) Create/edit file .asoundrc

```<code>$vim .asoundrc
</code>```

If file is not present create it;

```<code>$ touch .asoundrc

$vim .asoundrc
pcm.!default {
        type asym
        playback.pcm "hw:1,0"
        capture.pcm "hw:1,0"
}

ctl.!default {
        type hw
        card 1
}
</code>```

1.2) Edit below line in file alsa.conf;

```<code>$sudo vim /usr/share/alsa/alsa.conf
defaults.ctl.card 0
defaults.pcm.card 0
</code>```

to

```<code>$sudo vim /usr/share/alsa/alsa.conf
defaults.ctl.card 1
defaults.pcm.card 1
</code>```

1.3) Change audio levels/setting using alsamixer utility

```<code>$alsamixer
</code>```

1.4) Command to record audio

```<code>$arecord -D plughw:1 -f S16_LE -r 48000 -d 5 ./testSound.wav
</code>```

1.5) Command to play recorded audio

```<code>$aplay --device=plughw:1,0 ./testSound.wav
</code>```

Body:
I get the following from aplay -l, lsusb:

pi@raspberrypi:~ $ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
  Subdevices: 8/8
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
  Subdevice #4: subdevice #4
  Subdevice #5: subdevice #5
  Subdevice #6: subdevice #6
  Subdevice #7: subdevice #7
card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 2: Device_1 [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
pi@raspberrypi:~ $ lsusb
Bus 001 Device 005: ID 046d:c31c Logitech, Inc. Keyboard K120 for Business
Bus 001 Device 008: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 007: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 006: ID 05e3:0606 Genesys Logic, Inc. USB 2.0 Hub / D-Link DUB-H4 USB 2.0 Hub
Bus 001 Device 004: ID 1bcf:0005 Sunplus Innovation Technology Inc.
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I want to play my MP3 via CM108 Audio Controllers with libao. I tried these:

ao_initialize();
ao_option aoption;
ao_option *poption;
poption = &aoption;
poption->key = (char*)"dev";
poption->value = (char*)"hw:0";
dev = ao_open_live(driver, &format, poption);
    while (mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
        ao_play(dev, (char *)buffer, done);

So sound is played via the Pi successfully. I understand that hw:0 is a sound card of the Pi. What should I use instead of hw:0 if I want to play via the first or second CM108 Audio Controller? I already tried hw:1 and hw:2 and it does not work.

Body:
Try to follow below steps to enable audio recording and playback from a usb-sound adapter for rpi with alsa first. With this you can test your USB sound adapters are working correctly as input and output module.I have not tested before a usecase with above mentioned library in C++ code, will give it a try soon. Try by referring to "hw:1" later in your C++ code if it working.

Steps:
1.1) Create/edit file .asoundrc

$vim .asoundrc

If file is not present create it;

$ touch .asoundrc

$vim .asoundrc
pcm.!default {
        type asym
        playback.pcm "hw:1,0"
        capture.pcm "hw:1,0"
}

ctl.!default {
        type hw
        card 1
}

1.2) Edit below line in file alsa.conf;

$sudo vim /usr/share/alsa/alsa.conf
defaults.ctl.card 0
defaults.pcm.card 0

to

$sudo vim /usr/share/alsa/alsa.conf
defaults.ctl.card 1
defaults.pcm.card 1

1.3) Change audio levels/setting using alsamixer utility

$alsamixer

1.4) Command to record audio

$arecord -D plughw:1 -f S16_LE -r 48000 -d 5 ./testSound.wav

1.5) Command to play recorded audio

$aplay --device=plughw:1,0 ./testSound.wav


来源: stackexchange

问:
get next immediate same date using php

i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

```<code>$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));
</code>```

or

```<code>$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
</code>```

thanks in your advance

答:
I think this may help.

I would consider using DateTime and it's add method for a DateInterval.

```<code>$date = new \DateTime('now', new \DateTimeZone('America/New_York'));
$interval = new \DateInterval('P1M');
$date->add($interval);
</code>```

Here are the supported DateTimeZone values. Make sure to set that to the applicable time zone.

Edit:
DateTime is mutable, so please keep that in mind.

ContentLicense: CC BY-SA 3.0

Title: get next immediate same date using php

Body:
i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));

or

$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

thanks in your advance

Body:
I think this may help.

I would consider using DateTime and it's add method for a DateInterval.

$date = new \DateTime('now', new \DateTimeZone('America/New_York'));
$interval = new \DateInterval('P1M');
$date->add($interval);

Here are the supported DateTimeZone values. Make sure to set that to the applicable time zone.

Edit:
DateTime is mutable, so please keep that in mind.


问:
ConcurrencyExeption on ASP.NET MVC Application

Introduction to the Problem

First of all I tried everything to figure out this problem by no result. I am currently trying to design a repository pattern on my own for the first time.

My application is just a Blog Website and it has some components. I will directly point to the problem for you.

Problem

When I want to update a post through repository system throws an exception (Concurrency Exception) but I am sure that this type of exception occurs when you define a "[TimeStamp]" column type in Post Table. I know how to handle this exception exactly and I am sure nobody is updating the post which I am updating currently because it works on local system. I think no reason to occur this exception except a reason which I don't know and maybe you can help me at this point.

I defined the problem explicitly for you then let's go code blocks;

Components

I have this AdminController

```<code>public class AdminController : Controller
{
    private IDbFactory _dbFactory;
    private IUnitOfWork _unitOfWork;

    private ICategoryRepository _categoryRepository;
    private IPostRepository _postRepository;
    private ITagRepository _tagRepository;

    public ICategoryRepository categoryRepository
    {
        get
        {
            return _categoryRepository ?? (_categoryRepository = new CategoryRepository(HttpContext.GetOwinContext().Get<DbFactory>()));
        }
        set
        {
            _categoryRepository = value;
        }
    }
    public IPostRepository postRepository
    {
        get
        {
            return _postRepository ?? (_postRepository = new PostRepository(HttpContext.GetOwinContext().Get<DbFactory>()));
        }

        set
        {
            _postRepository = value;
        }
    }
    public ITagRepository tagRepository
    {
        get
        {
            return _tagRepository ?? (_tagRepository = new TagRepository(HttpContext.GetOwinContext().Get<DbFactory>()));
        }

        set
        {
            _tagRepository = value;
        }
    }
public IDbFactory dbFactory
    {
        get
        {
            return _dbFactory ?? (_dbFactory =
           HttpContext.GetOwinContext().Get<DbFactory>());
        }
    }
    public IUnitOfWork unitOfWork
    {
        get
        {
            return _unitOfWork ?? (_unitOfWork =
           HttpContext.GetOwinContext().Get<UnitOfWork>());
        }
    }
[HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult UpdatePost([Bind(Include = "IntroText, PostText, CodeText, Header, Author, ImagePath, CategoryID")] ViewPostModel model)
    {
        if (ModelState.IsValid)
        {
            Post post = new Post();
            post = Mapper.Map<ViewPostModel, Post>(model);

            if (model.CodeText != null)
                post.PostText = GetCodedPostText(model.PostText, model.CodeText);

            post.CreatedDate = DateTime.Now.ToShortDateString();
            post.CategoryID = model.CategoryID;
            postRepository.Update(post);
            unitOfWork.SaveChanges(); // Throws and exception (Concurrency Exception)
        }
        ViewBag.Categories = FillCategoriesForDropdownList();
        return RedirectToAction("DetailPost");
    }
}
</code>```

I have this RepositoryBase generic class;

```<code>private IDbFactory dbFactory;
    private AppDbContext context;
    private ICategoryRepository _categoryRepository;
    private IPostRepository _postRepository;
    private ITagRepository _tagRepository;

    //public ICategoryRepository categoryRepository
    //{
    //    get
    //    {
    //        return _categoryRepository ?? (_categoryRepository = new CategoryRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }
    //    set
    //    {
    //        _categoryRepository = value;
    //    }
    //}
    //public IPostRepository postRepository
    //{
    //    get
    //    {
    //        return _postRepository ?? (_postRepository = new PostRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }

    //    set
    //    {
    //        _postRepository = value;
    //    }
    //}
    //public ITagRepository tagRepository
    //{
    //    get
    //    {
    //        return _tagRepository ?? (_tagRepository = new TagRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }

    //    set
    //    {
    //        _tagRepository = value;
    //    }
    //}

    AppDbContext db
    {
        get
        {
            return context ?? (context = dbFactory.Init());
        }
    }

    public ICategoryRepository categoryRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public IPostRepository postRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public ITagRepository tagRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public static UnitOfWork Create()
    {
        return new UnitOfWork(HttpContext.Current.GetOwinContext().Get<DbFactory>());
    }

    public UnitOfWork(IDbFactory _dbFactory)
    {
        dbFactory = _dbFactory;
    }

    public void SaveChanges()
    {
        db.SaveChanges();
    }

    public void Dispose()
    {

    }
}
</code>```

I have this Post Repository;

```<code>public class PostRepository : RepositoryBase<Post>, IPostRepository, IDisposable
{
    public PostRepository(IDbFactory dbFactory) : base(dbFactory) { }

    public static PostRepository Create()
    {
        return new PostRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>());
    }

    public void Dispose()
    {

    }
}
</code>```

I have this Database Initializer;

```<code>public class AppDbInitializer : DropCreateDatabaseAlways<AppDbContext>
{
    protected override void Seed(AppDbContext context)
    {
        SeedIdentity(context);
        SeedTables(context);
        base.Seed(context);
    }

    private void SeedIdentity(AppDbContext context)
    {
        //var userManager = HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();
        //var roleManager = HttpContext.Current.GetOwinContext().Get<AppRoleManager>();
        const string name = "admin@example.com";
        const string password = "SelcuK99.";
        const string roleName = "Admin";

        #region Old
        //var role = roleManager.FindByName(roleName);
        //AppRole role = null;
        //if (role == null)
        //{
        //    role = new AppRole(roleName);
        //    var roleresult = roleManager.Create(role);
        //}
        //AppUser user = null;
        ////var user = userManager.FindByName(name);
        //if (user == null)
        //{
        //    user = new AppUser { UserName = name, Email = name };
        //    var result = userManager.Create(user, password);
        //    result = userManager.SetLockoutEnabled(user.Id, false);
        //}

        //var rolesForUser = userManager.GetRoles(user.Id);
        //if (!rolesForUser.Contains(role.Name))
        //{
        //    var result = userManager.AddToRole(user.Id, role.Name);
        //}
        #endregion

        RoleStore<AppRole> roleStore = new RoleStore<AppRole>(context);
        RoleManager<AppRole> roleManager = new RoleManager<AppRole>(roleStore);
        AppRole role = new AppRole
        {
            Name = roleName
        };
        roleManager.Create(role);

        UserStore<AppUser> userStore = new UserStore<AppUser>(context);
        AppUserManager userManager = new AppUserManager(userStore);
        AppUser user = new AppUser { Email = name, UserName = name};
        userManager.Create(user, password);
        userManager.AddToRole(user.Id, roleName);
    }
}
</code>```

I have this OwinContext startup class;

```<code>    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(AppDbContext.Create);
            app.CreatePerOwinContext(DbFactory.Create);
            app.CreatePerOwinContext(TagRepository.Create);
            app.CreatePerOwinContext(CategoryRepository.Create);
            app.CreatePerOwinContext(PostRepository.Create);
            app.CreatePerOwinContext(UnitOfWork.Create);
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
            app.CreatePerOwinContext<AppSignInManager>(AppSignInManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType =
    DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
    SecurityStampValidator.OnValidateIdentity<AppUserManager, AppUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) =>
    user.GenerateUserIdentityAsync(manager))
                }
            });

  app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
    }
</code>```

Here is AppDbContext

```<code>public class AppDbContext : IdentityDbContext<AppUser>
    {
        public AppDbContext() : base("AppDbContext", throwIfV1Schema: false) { }

        public static AppDbContext Create()
        {
            return new AppDbContext();
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Tag> Tags { get; set; }

        static AppDbContext()
        {
            Database.SetInitializer(new AppDbInitializer());
        }

        //protected override void OnModelCreating(DbModelBuilder modelBuilder)
        //{
        //    modelBuilder.Configurations.Add(new CategoryConfiguration());
        //    modelBuilder.Configurations.Add(new PostConfiguration());
        //}
    }
</code>```

I have this Post class

```<code>public class Post : BaseEntity, IAudit
    {
        public int CategoryID { get; set; }
        public string IntroText { get; set; }
        public string PostText { get; set; }
        public string CodeText { get; set; }
        public string Header { get; set; }
        public string Author { get; set; }
        public string ImagePath { get; set; }
        public string CreatedDate { get; set; }
        public string UpdatedDate { get; set; }
        public virtual ICollection<PostTagMapping> PostTags { get; set; }
        public Category Category { get; set; }
    }
</code>```

and finaly I have this ViewPostModel;

```<code>public class ViewPostModel : BaseEntity
    {
        public string PostText { get; set; }
        public string IntroText { get; set; }
        public string CodeText { get; set; }
        public string Author { get; set; }
        public string Header { get; set; }
        public string ImagePath { get; set; }
        public DateTime? CreatedDate { get; set; }
        public DateTime? UpdatedDate { get; set; }
        public int CategoryID { get; set; }
    }
</code>```

I forget to give you the DbFactory;

```<code>public class DbFactory : Disposable, IDbFactory
    {
        private AppDbContext context;

        public static DbFactory Create()
        {
            return new DbFactory();
        }

        public AppDbContext Init()
        {
            int a;
            if (context == null)
                a = 5;
            return (HttpContext.Current.GetOwinContext().Get<AppDbContext>());
        }

        protected override void DisposeCore()
        {
            if (context != null)
                context.Dispose();
        }
    }
</code>```

I give you everything to solve this issue.

Here is my assumptions and questions ##

Maybe somewhere there could be a race condition but how is that possible I am using static DbContext ?

Maybe there are two running DbContext instances but how is that possible again I am using static DbContext ?

Here is the details of the Exception

InnerException Message:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

StackTrace:

```<code>at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at HybridBlog.Model.RepositoryBase`1.Update(TEntity entity) in D:\MVC_Projects\TrialProjects\HybridBlog\HybridBlog.Model\RepositoryBase.cs:line 71
   at HybridBlog.Web.Controllers.AdminController.UpdatePost(ViewPostModel model) in D:\MVC_Projects\TrialProjects\HybridBlog\HybridBlog.Web\Controllers\AdminController.cs:line 153
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
</code>```

BaseEntity.cs

```<code>private IDbFactory dbFactory;
    private AppDbContext context;
    private ICategoryRepository _categoryRepository;
    private IPostRepository _postRepository;
    private ITagRepository _tagRepository;

    //public ICategoryRepository categoryRepository
    //{
    //    get
    //    {
    //        return _categoryRepository ?? (_categoryRepository = new CategoryRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }
    //    set
    //    {
    //        _categoryRepository = value;
    //    }
    //}
    //public IPostRepository postRepository
    //{
    //    get
    //    {
    //        return _postRepository ?? (_postRepository = new PostRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }

    //    set
    //    {
    //        _postRepository = value;
    //    }
    //}
    //public ITagRepository tagRepository
    //{
    //    get
    //    {
    //        return _tagRepository ?? (_tagRepository = new TagRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }

    //    set
    //    {
    //        _tagRepository = value;
    //    }
    //}

    AppDbContext db
    {
        get
        {
            return context ?? (context = dbFactory.Init());
        }
    }

    public ICategoryRepository categoryRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public IPostRepository postRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public ITagRepository tagRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public static UnitOfWork Create()
    {
        return new UnitOfWork(HttpContext.Current.GetOwinContext().Get<DbFactory>());
    }

    public UnitOfWork(IDbFactory _dbFactory)
    {
        dbFactory = _dbFactory;
    }

    public void SaveChanges()
    {
        db.SaveChanges();
    }

    public void Dispose()
    {

    }
}
</code>```0

答:
I strongly suspect you aren't setting post.ID in your update method. You can verify this by checking the value of post.ID prior to the postRepository.Update(post); call.

I suspect you need to change:

```<code>public ActionResult UpdatePost([Bind(Include = "IntroText, PostText, CodeText, Header, Author, ImagePath, CategoryID")] ViewPostModel model)
{
</code>```

to:

```<code>public ActionResult UpdatePost([Bind(Include = "ID, IntroText, PostText, CodeText, Header, Author, ImagePath, CategoryID")] ViewPostModel model)
{
</code>```

Body:
Introduction to the Problem

First of all I tried everything to figure out this problem by no result. I am currently trying to design a repository pattern on my own for the first time.

My application is just a Blog Website and it has some components. I will directly point to the problem for you.

Problem

When I want to update a post through repository system throws an exception (Concurrency Exception) but I am sure that this type of exception occurs when you define a "[TimeStamp]" column type in Post Table. I know how to handle this exception exactly and I am sure nobody is updating the post which I am updating currently because it works on local system. I think no reason to occur this exception except a reason which I don't know and maybe you can help me at this point.

I defined the problem explicitly for you then let's go code blocks;

Components

I have this AdminController

public class AdminController : Controller
{
    private IDbFactory _dbFactory;
    private IUnitOfWork _unitOfWork;

    private ICategoryRepository _categoryRepository;
    private IPostRepository _postRepository;
    private ITagRepository _tagRepository;

    public ICategoryRepository categoryRepository
    {
        get
        {
            return _categoryRepository ?? (_categoryRepository = new CategoryRepository(HttpContext.GetOwinContext().Get<DbFactory>()));
        }
        set
        {
            _categoryRepository = value;
        }
    }
    public IPostRepository postRepository
    {
        get
        {
            return _postRepository ?? (_postRepository = new PostRepository(HttpContext.GetOwinContext().Get<DbFactory>()));
        }

        set
        {
            _postRepository = value;
        }
    }
    public ITagRepository tagRepository
    {
        get
        {
            return _tagRepository ?? (_tagRepository = new TagRepository(HttpContext.GetOwinContext().Get<DbFactory>()));
        }

        set
        {
            _tagRepository = value;
        }
    }
public IDbFactory dbFactory
    {
        get
        {
            return _dbFactory ?? (_dbFactory =
           HttpContext.GetOwinContext().Get<DbFactory>());
        }
    }
    public IUnitOfWork unitOfWork
    {
        get
        {
            return _unitOfWork ?? (_unitOfWork =
           HttpContext.GetOwinContext().Get<UnitOfWork>());
        }
    }
[HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult UpdatePost([Bind(Include = "IntroText, PostText, CodeText, Header, Author, ImagePath, CategoryID")] ViewPostModel model)
    {
        if (ModelState.IsValid)
        {
            Post post = new Post();
            post = Mapper.Map<ViewPostModel, Post>(model);

            if (model.CodeText != null)
                post.PostText = GetCodedPostText(model.PostText, model.CodeText);

            post.CreatedDate = DateTime.Now.ToShortDateString();
            post.CategoryID = model.CategoryID;
            postRepository.Update(post);
            unitOfWork.SaveChanges(); // Throws and exception (Concurrency Exception)
        }
        ViewBag.Categories = FillCategoriesForDropdownList();
        return RedirectToAction("DetailPost");
    }
}

I have this RepositoryBase generic class;

private IDbFactory dbFactory;
    private AppDbContext context;
    private ICategoryRepository _categoryRepository;
    private IPostRepository _postRepository;
    private ITagRepository _tagRepository;

    //public ICategoryRepository categoryRepository
    //{
    //    get
    //    {
    //        return _categoryRepository ?? (_categoryRepository = new CategoryRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }
    //    set
    //    {
    //        _categoryRepository = value;
    //    }
    //}
    //public IPostRepository postRepository
    //{
    //    get
    //    {
    //        return _postRepository ?? (_postRepository = new PostRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }

    //    set
    //    {
    //        _postRepository = value;
    //    }
    //}
    //public ITagRepository tagRepository
    //{
    //    get
    //    {
    //        return _tagRepository ?? (_tagRepository = new TagRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>()));
    //    }

    //    set
    //    {
    //        _tagRepository = value;
    //    }
    //}

    AppDbContext db
    {
        get
        {
            return context ?? (context = dbFactory.Init());
        }
    }

    public ICategoryRepository categoryRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public IPostRepository postRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public ITagRepository tagRepository
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public static UnitOfWork Create()
    {
        return new UnitOfWork(HttpContext.Current.GetOwinContext().Get<DbFactory>());
    }

    public UnitOfWork(IDbFactory _dbFactory)
    {
        dbFactory = _dbFactory;
    }

    public void SaveChanges()
    {
        db.SaveChanges();
    }

    public void Dispose()
    {

    }
}

I have this Post Repository;

public class PostRepository : RepositoryBase<Post>, IPostRepository, IDisposable
{
    public PostRepository(IDbFactory dbFactory) : base(dbFactory) { }

    public static PostRepository Create()
    {
        return new PostRepository(HttpContext.Current.GetOwinContext().Get<DbFactory>());
    }

    public void Dispose()
    {

    }
}

I have this Database Initializer;

public class AppDbInitializer : DropCreateDatabaseAlways<AppDbContext>
{
    protected override void Seed(AppDbContext context)
    {
        SeedIdentity(context);
        SeedTables(context);
        base.Seed(context);
    }

    private void SeedIdentity(AppDbContext context)
    {
        //var userManager = HttpContext.Current.GetOwinContext().GetUserManager<AppUserManager>();
        //var roleManager = HttpContext.Current.GetOwinContext().Get<AppRoleManager>();
        const string name = "admin@example.com";
        const string password = "SelcuK99.";
        const string roleName = "Admin";

        #region Old
        //var role = roleManager.FindByName(roleName);
        //AppRole role = null;
        //if (role == null)
        //{
        //    role = new AppRole(roleName);
        //    var roleresult = roleManager.Create(role);
        //}
        //AppUser user = null;
        ////var user = userManager.FindByName(name);
        //if (user == null)
        //{
        //    user = new AppUser { UserName = name, Email = name };
        //    var result = userManager.Create(user, password);
        //    result = userManager.SetLockoutEnabled(user.Id, false);
        //}

        //var rolesForUser = userManager.GetRoles(user.Id);
        //if (!rolesForUser.Contains(role.Name))
        //{
        //    var result = userManager.AddToRole(user.Id, role.Name);
        //}
        #endregion

        RoleStore<AppRole> roleStore = new RoleStore<AppRole>(context);
        RoleManager<AppRole> roleManager = new RoleManager<AppRole>(roleStore);
        AppRole role = new AppRole
        {
            Name = roleName
        };
        roleManager.Create(role);

        UserStore<AppUser> userStore = new UserStore<AppUser>(context);
        AppUserManager userManager = new AppUserManager(userStore);
        AppUser user = new AppUser { Email = name, UserName = name};
        userManager.Create(user, password);
        userManager.AddToRole(user.Id, roleName);
    }
}

I have this OwinContext startup class;

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(AppDbContext.Create);
            app.CreatePerOwinContext(DbFactory.Create);
            app.CreatePerOwinContext(TagRepository.Create);
            app.CreatePerOwinContext(CategoryRepository.Create);
            app.CreatePerOwinContext(PostRepository.Create);
            app.CreatePerOwinContext(UnitOfWork.Create);
            app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
            app.CreatePerOwinContext<AppSignInManager>(AppSignInManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType =
    DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
    SecurityStampValidator.OnValidateIdentity<AppUserManager, AppUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) =>
    user.GenerateUserIdentityAsync(manager))
                }
            });

  app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        }
    }

Here is AppDbContext

public class AppDbContext : IdentityDbContext<AppUser>
    {
        public AppDbContext() : base("AppDbContext", throwIfV1Schema: false) { }

        public static AppDbContext Create()
        {
            return new AppDbContext();
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Post> Posts { get; set; }
        public DbSet<Tag> Tags { get; set; }

        static AppDbContext()
        {
            Database.SetInitializer(new AppDbInitializer());
        }

        //protected override void OnModelCreating(DbModelBuilder modelBuilder)
        //{
        //    modelBuilder.Configurations.Add(new CategoryConfiguration());
        //    modelBuilder.Configurations.Add(new PostConfiguration());
        //}
    }

I have this Post class

public class Post : BaseEntity, IAudit
    {
        public int CategoryID { get; set; }
        public string IntroText { get; set; }
        public string PostText { get; set; }
        public string CodeText { get; set; }
        public string Header { get; set; }
        public string Author { get; set; }
        public string ImagePath { get; set; }
        public string CreatedDate { get; set; }
        public string UpdatedDate { get; set; }
        public virtual ICollection<PostTagMapping> PostTags { get; set; }
        public Category Category { get; set; }
    }

and finaly I have this ViewPostModel;

public class ViewPostModel : BaseEntity
    {
        public string PostText { get; set; }
        public string IntroText { get; set; }
        public string CodeText { get; set; }
        public string Author { get; set; }
        public string Header { get; set; }
        public string ImagePath { get; set; }
        public DateTime? CreatedDate { get; set; }
        public DateTime? UpdatedDate { get; set; }
        public int CategoryID { get; set; }
    }

I forget to give you the DbFactory;

public class DbFactory : Disposable, IDbFactory
    {
        private AppDbContext context;

        public static DbFactory Create()
        {
            return new DbFactory();
        }

        public AppDbContext Init()
        {
            int a;
            if (context == null)
                a = 5;
            return (HttpContext.Current.GetOwinContext().Get<AppDbContext>());
        }

        protected override void DisposeCore()
        {
            if (context != null)
                context.Dispose();
        }
    }

I give you everything to solve this issue.

Here is my assumptions and questions ##

Maybe somewhere there could be a race condition but how is that possible I am using static DbContext ?

Maybe there are two running DbContext instances but how is that possible again I am using static DbContext ?

Here is the details of the Exception

InnerException Message:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

StackTrace:

at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at HybridBlog.Model.RepositoryBase`1.Update(TEntity entity) in D:\MVC_Projects\TrialProjects\HybridBlog\HybridBlog.Model\RepositoryBase.cs:line 71
   at HybridBlog.Web.Controllers.AdminController.UpdatePost(ViewPostModel model) in D:\MVC_Projects\TrialProjects\HybridBlog\HybridBlog.Web\Controllers\AdminController.cs:line 153
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()

BaseEntity.cs

public class BaseEntity
    {
        public int ID { get; set; }
    }

Body:
I strongly suspect you aren't setting post.ID in your update method. You can verify this by checking the value of post.ID prior to the postRepository.Update(post); call.

I suspect you need to change:

public ActionResult UpdatePost([Bind(Include = "IntroText, PostText, CodeText, Header, Author, ImagePath, CategoryID")] ViewPostModel model)
{

to:

public ActionResult UpdatePost([Bind(Include = "ID, IntroText, PostText, CodeText, Header, Author, ImagePath, CategoryID")] ViewPostModel model)
{


问:
MySQL - Stored Procedure
I need to fetch data from the stored procedure and present it in a dashboard. So the background for this is.

For every select query in the Stored procedure will return only one record I've around 10 queries like that. Apart from that I've also a query which will return say some 5 rows in the same stored procedure.

I want this 5 records to be presented as 1 line along with the other queries in the same stored procedure.

Example:

CALL dashboard_proc() Will return

```<code>Date       Amount    total_orders
1-1-2017   500.00    50
</code>```

A part from above output I want to append another select query to the same stored procedure (dashboard_proc). The other query which will return

```<code>Place      Total
Hyderabad    100
Bangalore    100
Chennai      200
Mumbai       100
</code>```

And I need below

```<code>Date      Amount  total_orders  Hyderabad  Bangalore  Chennai  Mumbai
1-1-2016  500.00     50            100       100        200      100
</code>```

答:
Based on your inputs:

First Part of the report has only one record so I have used the below structure

```<code> CREATE TABLE `ResultPart1` (
  `ReportDate` date NOT NULL,
  `Amount` float DEFAULT NULL,
  `total_orders` int(11) DEFAULT NULL
)
</code>```

insert into ResultPart1 select '2017-01-01',   500.00  ,  50;

2. Second Part of the report will have distinct Places, here the places used are single word and no keyword used.

```<code> CREATE TABLE `ResultPart2` (
       `Place` varchar(50) NOT NULL,
      `Total` int(11) DEFAULT NULL
    )
</code>```

```<code>insert into  ResultPart2()
Select 'Hyderabad',    100 union
Select 'Bangalore' ,   100 union
Select 'Chennai'    ,  200 union
Select 'Mumbai'      , 100;
</code>```

3. Create Stored Procedure

```<code>CREATE PROCEDURE `new_procedureDashboard`()
BEGIN

Declare vPlaceCount int;
Declare vquery varchar(1000);
declare vPlace varchar(1000);
declare vPlaceTotal int;
-- select * from ResultPart1;
-- Select * from ResultPart2;

CREATE TEMPORARY TABLE IF NOT EXISTS Table_ResultPart2
(
   Id int NOT NULL AUTO_INCREMENT,
   Place varchar(100),
   PlaceTotal int ,
   PRIMARY KEY (id)
);
insert into Table_ResultPart2(Place,PlaceTotal)
Select distinct Place,Total from ResultPart2;

SET vPlaceCount=(Select count(*)from Table_ResultPart2);
WHILE vPlaceCount>0 DO
        SET vPlace=(Select Place from Table_ResultPart2 where Id=vPlaceCount);
        SET vPlaceTotal=(Select PlaceTotal from Table_ResultPart2 where Id=vPlaceCount);
        SET vquery=concat("", "alter table ResultPart1 add " ,vPlace ," int ;");
        Select vquery into @AddColumn;
        PREPARE stmt FROM  @AddColumn;
        -- Select @AddColumn;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET vquery="";

       --   Select vPlace,vPlaceTotal;
        -- Update
        SET SQL_SAFE_UPDATES = 0;
        SET vquery=concat("", "update ResultPart1 SET " ,vPlace ," = " ,vPlaceTotal ," where 1=1 ;");

        Select vquery into @UpdateColumn;
        -- select @UpdateColumn;
        PREPARE stmt1 FROM  @UpdateColumn;
        -- Select @AddColumn;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
        SET SQL_SAFE_UPDATES = 1;

        SET vPlaceCount=vPlaceCount-1;
        SET vPlace="" ;
END WHILE;
Select * from ResultPart1;
drop TEMPORARY TABLE IF EXISTS Table_ResultPart2;
END
</code>```

Explanation:
Added the required column in the main resultant table using loop, and updated the values of the newly place(added) column using the loop. You will require to make changes in your stored procedure as I have used permanent tables (ResultPart1 and ResultPart2 ) .

4. Result

Alter Statements to drop column Just in case you want to rerun the stored procedure.

```<code>alter table ResultPart1 drop column Hyderabad;
alter table ResultPart1 drop column Bangalore;
alter table ResultPart1 drop column Chennai;
alter table ResultPart1 drop column Mumbai;
</code>```

Title: MySQL - Stored Procedure

Body:
I need to fetch data from the stored procedure and present it in a dashboard. So the background for this is.

For every select query in the Stored procedure will return only one record I've around 10 queries like that. Apart from that I've also a query which will return say some 5 rows in the same stored procedure.

I want this 5 records to be presented as 1 line along with the other queries in the same stored procedure.

Example:

CALL dashboard_proc() Will return

Date       Amount    total_orders
1-1-2017   500.00    50

A part from above output I want to append another select query to the same stored procedure (dashboard_proc). The other query which will return

Place      Total
Hyderabad    100
Bangalore    100
Chennai      200
Mumbai       100

And I need below

Date      Amount  total_orders  Hyderabad  Bangalore  Chennai  Mumbai
1-1-2016  500.00     50            100       100        200      100

Body:
Based on your inputs:

First Part of the report has only one record so I have used the below structure

 CREATE TABLE `ResultPart1` (
  `ReportDate` date NOT NULL,
  `Amount` float DEFAULT NULL,
  `total_orders` int(11) DEFAULT NULL
)

insert into ResultPart1 select '2017-01-01',   500.00  ,  50;

2. Second Part of the report will have distinct Places, here the places used are single word and no keyword used.

 CREATE TABLE `ResultPart2` (
       `Place` varchar(50) NOT NULL,
      `Total` int(11) DEFAULT NULL
    )

insert into  ResultPart2()
Select 'Hyderabad',    100 union
Select 'Bangalore' ,   100 union
Select 'Chennai'    ,  200 union
Select 'Mumbai'      , 100;

3. Create Stored Procedure

CREATE PROCEDURE `new_procedureDashboard`()
BEGIN

Declare vPlaceCount int;
Declare vquery varchar(1000);
declare vPlace varchar(1000);
declare vPlaceTotal int;
-- select * from ResultPart1;
-- Select * from ResultPart2;

CREATE TEMPORARY TABLE IF NOT EXISTS Table_ResultPart2
(
   Id int NOT NULL AUTO_INCREMENT,
   Place varchar(100),
   PlaceTotal int ,
   PRIMARY KEY (id)
);
insert into Table_ResultPart2(Place,PlaceTotal)
Select distinct Place,Total from ResultPart2;

SET vPlaceCount=(Select count(*)from Table_ResultPart2);
WHILE vPlaceCount>0 DO
        SET vPlace=(Select Place from Table_ResultPart2 where Id=vPlaceCount);
        SET vPlaceTotal=(Select PlaceTotal from Table_ResultPart2 where Id=vPlaceCount);
        SET vquery=concat("", "alter table ResultPart1 add " ,vPlace ," int ;");
        Select vquery into @AddColumn;
        PREPARE stmt FROM  @AddColumn;
        -- Select @AddColumn;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        SET vquery="";

       --   Select vPlace,vPlaceTotal;
        -- Update
        SET SQL_SAFE_UPDATES = 0;
        SET vquery=concat("", "update ResultPart1 SET " ,vPlace ," = " ,vPlaceTotal ," where 1=1 ;");

        Select vquery into @UpdateColumn;
        -- select @UpdateColumn;
        PREPARE stmt1 FROM  @UpdateColumn;
        -- Select @AddColumn;
        EXECUTE stmt1;
        DEALLOCATE PREPARE stmt1;
        SET SQL_SAFE_UPDATES = 1;

        SET vPlaceCount=vPlaceCount-1;
        SET vPlace="" ;
END WHILE;
Select * from ResultPart1;
drop TEMPORARY TABLE IF EXISTS Table_ResultPart2;
END

Explanation:
Added the required column in the main resultant table using loop, and updated the values of the newly place(added) column using the loop. You will require to make changes in your stored procedure as I have used permanent tables (ResultPart1 and ResultPart2 ) .

4. Result

Alter Statements to drop column Just in case you want to rerun the stored procedure.

alter table ResultPart1 drop column Hyderabad;
alter table ResultPart1 drop column Bangalore;
alter table ResultPart1 drop column Chennai;
alter table ResultPart1 drop column Mumbai;


问:
How to find all the subclasses of a class given its name?
I need a working approach of getting all classes that are inherited from a base class in Python.</p>

答:
Here's a version without recursion:

```<code>def get_subclasses_gen(cls):

    def _subclasses(classes, seen):
        while True:
            subclasses = sum((x.__subclasses__() for x in classes), [])
            yield from classes
            yield from seen
            found = []
            if not subclasses:
                return

            classes = subclasses
            seen = found

    return _subclasses([cls], [])
</code>```

This differs from other implementations in that it returns the original class.
This is because it makes the code simpler and:

```<code>class Ham(object):
    pass

assert(issubclass(Ham, Ham)) # True
</code>```

If get_subclasses_gen looks a bit weird that's because it was created by converting a tail-recursive implementation into a looping generator:

```<code>def get_subclasses(cls):

    def _subclasses(classes, seen):
        subclasses = sum(*(frozenset(x.__subclasses__()) for x in classes))
        found = classes + seen
        if not subclasses:
            return found

        return _subclasses(subclasses, found)

    return _subclasses([cls], [])
</code>```

Body:
Here's a version without recursion:

def get_subclasses_gen(cls):

    def _subclasses(classes, seen):
        while True:
            subclasses = sum((x.__subclasses__() for x in classes), [])
            yield from classes
            yield from seen
            found = []
            if not subclasses:
                return

            classes = subclasses
            seen = found

    return _subclasses([cls], [])

This differs from other implementations in that it returns the original class.
This is because it makes the code simpler and:

class Ham(object):
    pass

assert(issubclass(Ham, Ham)) # True

If get_subclasses_gen looks a bit weird that's because it was created by converting a tail-recursive implementation into a looping generator:

def get_subclasses(cls):

    def _subclasses(classes, seen):
        subclasses = sum(*(frozenset(x.__subclasses__()) for x in classes))
        found = classes + seen
        if not subclasses:
            return found

        return _subclasses(subclasses, found)

    return _subclasses([cls], [])


问:
Using phonegap audio api in gwt
I am wanting to use the phonegap audio api in GWT using JSNI.I cannot figure out how to code the methods in JSNI.

Wondering if anyone know of any tutorials.They javascript methods are really pretty simple.

http://docs.phonegap.com/phonegap_media_media.md.html

答:
Basically it sounds like it would be something like this:

```<code>public final class Media extends JavaScriptObject {
  protected Media() {}

  public static native final Media newInstance(String src, Command command) /*-{
    var callback = function() { command.execute(); };
    return new Media(src, callback);
  }-*/;

  public native final void getCurrentPosition(AsyncCallback<String> command) /*-{
    var callback = function(position) { command.onSuccess('' + position); };
    this.getCurrentPosition(callback);
  }-*/;
  public native final void play() /*-{
    this.play();
  }-*/;
  //... more methods here
}
</code>```

Usage:

```<code>Media m = Media.newInstance("http://www.example.com/src.mp3", new Command() {
  @Override
  public void execute() {
    // Code executed after Media is created.
  }
});
m.getCurrentPosition(new AsyncCallback<String>() {
  @Override
  public void onSuccess(String position) {
    Window.alert(position);
  }
});
m.play();
</code>```

That's a rough sketch, if you know more about what the type being passed to the callback is you can do nicer things like have it be an int or another JS Overlay Type.

The API is kind of weird because everything is apparently asynchronous, but that's life.

Once you've gotten the hang of writing GWT JSNI bindings it's pretty straightforward.

If you end up getting further down this road, it would be awesome if you open-sourced your GWT wrapper library so other GWT developers could write some iPhone/Android apps.

ContentLicense: CC BY-SA 2.5

Title: Using phonegap audio api in gwt

Body:
Basically it sounds like it would be something like this:

public final class Media extends JavaScriptObject {
  protected Media() {}

  public static native final Media newInstance(String src, Command command) /*-{
    var callback = function() { command.execute(); };
    return new Media(src, callback);
  }-*/;

  public native final void getCurrentPosition(AsyncCallback<String> command) /*-{
    var callback = function(position) { command.onSuccess('' + position); };
    this.getCurrentPosition(callback);
  }-*/;
  public native final void play() /*-{
    this.play();
  }-*/;
  //... more methods here
}

Usage:

Media m = Media.newInstance("http://www.example.com/src.mp3", new Command() {
  @Override
  public void execute() {
    // Code executed after Media is created.
  }
});
m.getCurrentPosition(new AsyncCallback<String>() {
  @Override
  public void onSuccess(String position) {
    Window.alert(position);
  }
});
m.play();

That's a rough sketch, if you know more about what the type being passed to the callback is you can do nicer things like have it be an int or another JS Overlay Type.

The API is kind of weird because everything is apparently asynchronous, but that's life.

Once you've gotten the hang of writing GWT JSNI bindings it's pretty straightforward.

If you end up getting further down this road, it would be awesome if you open-sourced your GWT wrapper library so other GWT developers could write some iPhone/Android apps.


问:
Issue passing the data from one form to another
Overview:

Passing the data from one form to another.

This is a WinForm application which has two forms, named form1 and PostCodeForm.  I need to pass data from the short-lived form PostcodeForm back to Form1 through a clickEvent, then close the form. The values are stored into dataTable in PostcodeSearch class, and to access them I:

Loop through dataTable in PostCodeForm

```<code>for (var item = 0; item < retreiveResults.Count; item++)
{
    var num = dataGridView2.Rows.Add();
    dataGridView2.Rows[num].Cells[0].Value = retreiveResults[item].City;
    dataGridView2.Rows[num].Cells[1].Value = retreiveResults[item].District;
    dataGridView2.Rows[num].Cells[2].Value = retreiveResults[item].HouseName;
</code>```

Created an instance of Form1 in PostCodeForm:

```<code>Form1 formIndi = new Form1();
</code>```

Then created some local variables which are initialized just before the end of the loop in PostCodeForm

```<code>var _City_Cell = dataGridView2.Rows[num].Cells[0].Value;
var _District_Cell = dataGridView2.Rows[num].Cells[1].Value;
var _HouseName_Cell = dataGridView2.Rows[num].Cells[2].Value;
</code>```

Then to pass them to Form1 (in PostCodeForm):

```<code>formIndi.txt_City.Text = _StreetName_Cell.ToString();
formIndi.txt_HouseName.Text = _HouseName_Cell.ToString();
formIndi.txt_ District.Text = _District_Cell.ToString();
</code>```

I need to pass the data back to the main form and store it in the relevant textBoxes.

Issue

My issue is that none of my textBoxes are updating with given values but when I debug the Vars inside the postCodeForm I can see the values, so I have no idea why then the TextBoxes are not displaying the values, as I have always passed data from form to form this way.

答:
As @Ferus7 pointed out you're creating a new instance of Form1 instead of updating the values in your main form.

```<code>//new instance with new text boxes and values
Form1 formIndi = new Form1();
//updates the control in the new form, doesn't affect the caller.
formIndi.txt_City.Text = _StreetName_Cell.ToString();
</code>```

If you want to retrieve values from PostcodeForm, there're multiple ways to do that. One option is to declare properties/methods in PostcodeForm and to retrieve values through them:

```<code>//declaration in PostcodeForm
class PostcodeForm {
//...
public string StreetName {get; private set;}

//after data retrieval
StreetName = _StreetName_Cell.ToString();

//call PostcodeForm from Form1
postcodeForm = new PostcodeForm();
postcodeForm.ShowDialog();
//after that, get the value
txt_City.Text = postcodeForm.StreetName;
</code>```

Another way is to pass the reference of Form1 to PostcodeForm:

```<code>class PostcodeForm {
//declare field
private final Form1 parent;
//create a constructor that accepts `Form1`
PostcodeForm(Form1 parent)
{
    this.parent = parent;
    //... (InitializeComponents, etc.)
}

//update parent as necessary
parent.txt_City.Text = postcodeForm.StreetName;

//Sample call from Form1
postcodeForm = new PostcodeForm(this);
postcodeForm.ShowDialog();
</code>```

Body:
Overview:

Passing the data from one form to another.

This is a WinForm application which has two forms, named form1 and PostCodeForm.  I need to pass data from the short-lived form PostcodeForm back to Form1 through a clickEvent, then close the form. The values are stored into dataTable in PostcodeSearch class, and to access them I:

Loop through dataTable in PostCodeForm

for (var item = 0; item < retreiveResults.Count; item++)
{
    var num = dataGridView2.Rows.Add();
    dataGridView2.Rows[num].Cells[0].Value = retreiveResults[item].City;
    dataGridView2.Rows[num].Cells[1].Value = retreiveResults[item].District;
    dataGridView2.Rows[num].Cells[2].Value = retreiveResults[item].HouseName;

Created an instance of Form1 in PostCodeForm:

Form1 formIndi = new Form1();

Then created some local variables which are initialized just before the end of the loop in PostCodeForm

var _City_Cell = dataGridView2.Rows[num].Cells[0].Value;
var _District_Cell = dataGridView2.Rows[num].Cells[1].Value;
var _HouseName_Cell = dataGridView2.Rows[num].Cells[2].Value;

Then to pass them to Form1 (in PostCodeForm):

formIndi.txt_City.Text = _StreetName_Cell.ToString();
formIndi.txt_HouseName.Text = _HouseName_Cell.ToString();
formIndi.txt_ District.Text = _District_Cell.ToString();

I need to pass the data back to the main form and store it in the relevant textBoxes.

Issue

My issue is that none of my textBoxes are updating with given values but when I debug the Vars inside the postCodeForm I can see the values, so I have no idea why then the TextBoxes are not displaying the values, as I have always passed data from form to form this way.

Body:
As @Ferus7 pointed out you're creating a new instance of Form1 instead of updating the values in your main form.

//new instance with new text boxes and values
Form1 formIndi = new Form1();
//updates the control in the new form, doesn't affect the caller.
formIndi.txt_City.Text = _StreetName_Cell.ToString();

If you want to retrieve values from PostcodeForm, there're multiple ways to do that. One option is to declare properties/methods in PostcodeForm and to retrieve values through them:

//declaration in PostcodeForm
class PostcodeForm {
//...
public string StreetName {get; private set;}

//after data retrieval
StreetName = _StreetName_Cell.ToString();

//call PostcodeForm from Form1
postcodeForm = new PostcodeForm();
postcodeForm.ShowDialog();
//after that, get the value
txt_City.Text = postcodeForm.StreetName;

Another way is to pass the reference of Form1 to PostcodeForm:

class PostcodeForm {
//declare field
private final Form1 parent;
//create a constructor that accepts `Form1`
PostcodeForm(Form1 parent)
{
    this.parent = parent;
    //... (InitializeComponents, etc.)
}

//update parent as necessary
parent.txt_City.Text = postcodeForm.StreetName;

//Sample call from Form1
postcodeForm = new PostcodeForm(this);
postcodeForm.ShowDialog();


问:
why wont the elif in my while loop work?
i just started learning python and tried making a basic while loop, but when i run it,it doesnt run the elif statement i.e. if the userguess is == "tiger" it doesnt print "almost"..
as im new to this any explanation would be appreciated. thanks</p>

```<code>animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
</code>```

答:
It's because you're calling raw_input twice before you reach the if block. So the user will have to enter two animals before any checking occurs.

```<code>guess an animal: tiger
guess an animal: tiger
almost, try again:
guess an animal:
</code>```

If you want the user to only have to guess once, move the second raw_input to the end of the loop.

```<code>animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
  userguess = raw_input("guess an animal: ")
</code>```

Alternatively, leave the second raw_input call where it is, and replace the first call with a dummy value.

```<code>animal = "lion"
userguess = None

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
</code>```

You could also remove the initial assignment entirely, along with the while loop's conditional. As is, The condition is never triggering anyway because you always break before reaching the end of the block when animal is "lion".

```<code>animal = "lion"

while True:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
</code>```

The second and third ways may be preferable to the first, because they ensure that "you got it" will be printed even when the user guesses "lion" on their first try.

Body:
i just started learning python and tried making a basic while loop, but when i run it,it doesnt run the elif statement i.e. if the userguess is == "tiger" it doesnt print "almost"..
as im new to this any explanation would be appreciated. thanks

animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

Body:
It's because you're calling raw_input twice before you reach the if block. So the user will have to enter two animals before any checking occurs.

guess an animal: tiger
guess an animal: tiger
almost, try again:
guess an animal:

If you want the user to only have to guess once, move the second raw_input to the end of the loop.

animal = "lion"
userguess = raw_input("guess an animal: ")

while userguess != animal:
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")
  userguess = raw_input("guess an animal: ")

Alternatively, leave the second raw_input call where it is, and replace the first call with a dummy value.

animal = "lion"
userguess = None

while userguess != animal:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

You could also remove the initial assignment entirely, along with the while loop's conditional. As is, The condition is never triggering anyway because you always break before reaching the end of the block when animal is "lion".

animal = "lion"

while True:
  userguess = raw_input("guess an animal: ")
  if userguess == animal:
    print("you got it")
    break
  elif userguess == "tiger":
    print("almost, try again: ")
  else:
    print("try again: ")

The second and third ways may be preferable to the first, because they ensure that "you got it" will be printed even when the user guesses "lion" on their first try.


问:
iOS - AVAssetExportSession unknown error -12769
It seems that AVFoundation cannot accept one of my videos. I really don't know why. It works with other videos, but not this one.

I'm not even modifying the video, I'm just doing a composition with the video track, and exporting it with the preset "AVAssetExportPresetHighestQuality".

I get this error :

```<code>Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x60000045a8e0 {Error Domain=NSOSStatusErrorDomain Code=-12769 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12769), NSLocalizedDescription=The operation could not be completed}
</code>```

Do you know if there is something wrong in my code, or if the video is just not supported by AVFoundation ?

Here's the project on Github (it just exports the video to the camera roll) :

https://github.com/moonshaped/ExportSessionCrash

Or if you don't want to use Github :

Here's the video :

Dropbox link : https://www.dropbox.com/s/twgah26gqgsv9y9/localStoreTempVideoPath.mp4?dl=0

Or WeTransfer link : https://wetransfer.com/downloads/8f8ab257068461a2c9a051542610725220170606122640/8d934c

And here's the code :

```<code>- (void)exportVideo:(AVAsset *)videoAsset
      videoDuration:(Float64)videoAssetDuration
                 to:(NSString *)resultPath{

    [Utilities deleteFileIfExists:resultPath];

    AVMutableComposition *mainComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *compositionVideoTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                                preferredTrackID:kCMPersistentTrackID_Invalid];

    int timeScale = 100000;
    int videoDurationI = (int) (videoAssetDuration * (float) timeScale);
    CMTime videoDuration = CMTimeMake(videoDurationI, timeScale);
    CMTimeRange videoTimeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);

    NSArray<AVAssetTrack *> *videoTracks = [videoAsset tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack *videoTrack = [videoTracks objectAtIndex:0];

    [compositionVideoTrack insertTimeRange:videoTimeRange
                                   ofTrack:videoTrack
                                    atTime:kCMTimeZero
                                     error:nil];

    NSURL *outptVideoUrl = [NSURL fileURLWithPath:resultPath];
    self.exporter = [[AVAssetExportSession alloc] initWithAsset:mainComposition
                                                     presetName:AVAssetExportPresetHighestQuality];

    self.exporter.outputURL = outptVideoUrl;
    self.exporter.outputFileType = AVFileTypeMPEG4;
    self.exporter.shouldOptimizeForNetworkUse = YES;

    [self.exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (self.exporter.status) {
                case AVAssetExportSessionStatusFailed:{
                    @throw [NSException exceptionWithName:@"failed export"
                                                   reason:[self.exporter.error description]
                                                 userInfo:nil];
                }
                case AVAssetExportSessionStatusCancelled:
                    @throw [NSException exceptionWithName:@"cancelled export"
                                                   reason:@"Export cancelled"
                                                 userInfo:nil];

                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"Export finished");
                }
                    break;

                default:
                    break;
            }
        });
    }];
}
</code>```

答: The device you are trying to test is not able to decode it. Please try it on some newer devices e.g. iPhone 6. I tested your media on iPad simulator iOS10.3 and it worked fine there so it must be something to do with encoding.</p>

Body:
It seems that AVFoundation cannot accept one of my videos. I really don't know why. It works with other videos, but not this one.

I'm not even modifying the video, I'm just doing a composition with the video track, and exporting it with the preset "AVAssetExportPresetHighestQuality".

I get this error :

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x60000045a8e0 {Error Domain=NSOSStatusErrorDomain Code=-12769 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12769), NSLocalizedDescription=The operation could not be completed}

Do you know if there is something wrong in my code, or if the video is just not supported by AVFoundation ?

Here's the project on Github (it just exports the video to the camera roll) :

https://github.com/moonshaped/ExportSessionCrash

Or if you don't want to use Github :

Here's the video :

Dropbox link : https://www.dropbox.com/s/twgah26gqgsv9y9/localStoreTempVideoPath.mp4?dl=0

Or WeTransfer link : https://wetransfer.com/downloads/8f8ab257068461a2c9a051542610725220170606122640/8d934c

And here's the code :

- (void)exportVideo:(AVAsset *)videoAsset
      videoDuration:(Float64)videoAssetDuration
                 to:(NSString *)resultPath{

    [Utilities deleteFileIfExists:resultPath];

    AVMutableComposition *mainComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *compositionVideoTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                                preferredTrackID:kCMPersistentTrackID_Invalid];

    int timeScale = 100000;
    int videoDurationI = (int) (videoAssetDuration * (float) timeScale);
    CMTime videoDuration = CMTimeMake(videoDurationI, timeScale);
    CMTimeRange videoTimeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);

    NSArray<AVAssetTrack *> *videoTracks = [videoAsset tracksWithMediaType:AVMediaTypeVideo];
    AVAssetTrack *videoTrack = [videoTracks objectAtIndex:0];

    [compositionVideoTrack insertTimeRange:videoTimeRange
                                   ofTrack:videoTrack
                                    atTime:kCMTimeZero
                                     error:nil];

    NSURL *outptVideoUrl = [NSURL fileURLWithPath:resultPath];
    self.exporter = [[AVAssetExportSession alloc] initWithAsset:mainComposition
                                                     presetName:AVAssetExportPresetHighestQuality];

    self.exporter.outputURL = outptVideoUrl;
    self.exporter.outputFileType = AVFileTypeMPEG4;
    self.exporter.shouldOptimizeForNetworkUse = YES;

    [self.exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (self.exporter.status) {
                case AVAssetExportSessionStatusFailed:{
                    @throw [NSException exceptionWithName:@"failed export"
                                                   reason:[self.exporter.error description]
                                                 userInfo:nil];
                }
                case AVAssetExportSessionStatusCancelled:
                    @throw [NSException exceptionWithName:@"cancelled export"
                                                   reason:@"Export cancelled"
                                                 userInfo:nil];

                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"Export finished");
                }
                    break;

                default:
                    break;
            }
        });
    }];
}


问:
Converting array of stringified key value pairs to hash in Ruby
I have some key-value pair strings in an array:

```<code>array = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]
</code>```

I need to convert it to a hash:

```<code>hash = { "Name" => "abc", "Id" => "123", "Interest" => "Rock Climbing" }
</code>```

I must be doing something wrong because I'm getting weird mappings with my .shift.split resulting in {"Name=abc"=>"Id=123"}.

答:
Try this</p>

```<code>array.map {|s| s.split('=')}.to_h

=> {"Name "=>" abc", "Id "=>" 123", "Interest "=>" Rock Climbing"}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some key-value pair strings in an array:

array = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]

I need to convert it to a hash:

hash = { "Name" => "abc", "Id" => "123", "Interest" => "Rock Climbing" }

I must be doing something wrong because I'm getting weird mappings with my .shift.split resulting in {"Name=abc"=>"Id=123"}.

Body:
Try this

array.map {|s| s.split('=')}.to_h

=> {"Name "=>" abc", "Id "=>" 123", "Interest "=>" Rock Climbing"}


问:
How to pass parameter from ActionResult to JsonResult?
How can I pass the Id parameter(I already pass in the Id parameter) from ActionResult to JsonResult? Because now I cannot pass in the Id data to JsonResult parameter, so it cannot hit the following JsonResult code.

I using angularjs to display the List of table.

```<code>[HttpGet]
public ActionResult ManageCustomerStocks(Int64 Id)
{
    return View();
}

public JsonResult GetStocksByCustomerId(Int64 Id)
{
   List<CustomerStocksVM> model = new List<CustomerStocksVM>();
   var stocks = _repositories.GetStocksByClientProfileId(Id);

   var result = from stock in stocks
               select new StocksVM()
               {
                   Code = stock.Code,
                    Name = stock.Name
               };

    model = result.ToList();

    return Json(new
    {
        customerstocks = model
    },JsonRequestBehavior.AllowGet);
}
</code>```

Javascript:

```<code>var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.reverse = true;
    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    $http({
        method: 'POST',
        url: 'GetStocksByCustomer'
    })
    .then(function (response) {
        console.log(response);
        $scope.customerstocks = response.data.customerstocks ;

    }, function (error) {
        console.log(error);
    });
}]);
</code>```

答:
If you want to GET something from the backend, use http.get instead:

javascript:

```<code> function  GetStocksByCustomerId(id) {
    return $http.get("GetStocksByCustomer", { params: { "id":
   id} })
   .then(function (response) {
       return response.data
    })
    .catch();
}
</code>```

Set your http calls in an angular service

Body:
How can I pass the Id parameter(I already pass in the Id parameter) from ActionResult to JsonResult? Because now I cannot pass in the Id data to JsonResult parameter, so it cannot hit the following JsonResult code.

I using angularjs to display the List of table.

[HttpGet]
public ActionResult ManageCustomerStocks(Int64 Id)
{
    return View();
}

public JsonResult GetStocksByCustomerId(Int64 Id)
{
   List<CustomerStocksVM> model = new List<CustomerStocksVM>();
   var stocks = _repositories.GetStocksByClientProfileId(Id);

   var result = from stock in stocks
               select new StocksVM()
               {
                   Code = stock.Code,
                    Name = stock.Name
               };

    model = result.ToList();

    return Json(new
    {
        customerstocks = model
    },JsonRequestBehavior.AllowGet);
}

Javascript:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.reverse = true;
    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    $http({
        method: 'POST',
        url: 'GetStocksByCustomer'
    })
    .then(function (response) {
        console.log(response);
        $scope.customerstocks = response.data.customerstocks ;

    }, function (error) {
        console.log(error);
    });
}]);

Body:
If you want to GET something from the backend, use http.get instead:

javascript:

 function  GetStocksByCustomerId(id) {
    return $http.get("GetStocksByCustomer", { params: { "id":
   id} })
   .then(function (response) {
       return response.data
    })
    .catch();
}

Set your http calls in an angular service


问:
Java Math.sin Math.cos Math.tan Giving answer in Radian
I was trying to use the Math library in Java where Math.sin(90) gives me result 0.8939966636005579 I search on StackOverflow about this and came to know that the value is) in radian so I used below code to convert it to a degree.

```<code>Double deg;
deg = Math.toDegrees(value);
</code>```

The value of sin(90) in degree is 1 but the above code returns 51.222235723088794 what should I do to get an accurate result?

Result should be like for sin(90) :: 1

答:
The trigonometric function take their argument in radian, their value is a ratio of lengths and thus dimensionless. You have to employ

```<code>value = Math.cos(Math.toRadians(angleInDegree))
</code>```

etc. to get the trig. values for angles measured in degrees.

Body:
I was trying to use the Math library in Java where Math.sin(90) gives me result 0.8939966636005579 I search on StackOverflow about this and came to know that the value is) in radian so I used below code to convert it to a degree.

Double deg;
deg = Math.toDegrees(value);

The value of sin(90) in degree is 1 but the above code returns 51.222235723088794 what should I do to get an accurate result?

Result should be like for sin(90) :: 1

Body:
The trigonometric function take their argument in radian, their value is a ratio of lengths and thus dimensionless. You have to employ

value = Math.cos(Math.toRadians(angleInDegree))

etc. to get the trig. values for angles measured in degrees.


问:
How to call object from one class to another in C#
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

```<code>namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}
</code>```

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

```<code>        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }
</code>```

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

答:
This is how you do it.  Apologies for a major blunder in the earlier answer. This one has the connection surrounded by a using.</p>

```<code> namespace rsDeployer.Common.SQLServerCommunication
    {
       public class ConsumerClass
       {
           public void QueryExecution(string SQLQuery)
           {

           var profile = new RsProfile();
           var rsConnectionCreator = new RSDatabaseConnectionCreator(profile);
               using(var sqlConnection = rsConnectionCreator.CreateConnection(...Parameters here...)){
                      SqlCommand command = new SqlCommand(SQLQuery, sqlConnection );

                }
                var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
                      file.WriteLine(command);
                      file.Close();
           }
       }
    }
</code>```

Body:
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

Body:
This is how you do it.  Apologies for a major blunder in the earlier answer. This one has the connection surrounded by a using.

 namespace rsDeployer.Common.SQLServerCommunication
    {
       public class ConsumerClass
       {
           public void QueryExecution(string SQLQuery)
           {

           var profile = new RsProfile();
           var rsConnectionCreator = new RSDatabaseConnectionCreator(profile);
               using(var sqlConnection = rsConnectionCreator.CreateConnection(...Parameters here...)){
                      SqlCommand command = new SqlCommand(SQLQuery, sqlConnection );

                }
                var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
                      file.WriteLine(command);
                      file.Close();
           }
       }
    }


问:
Core Data not saving a relationship that has been deleted
I have a "to->many" relationship in Core Data with no inverse relationship and the delete rule set to both "Nullify" and "No action" (by that I mean I've tried both with no avail)

Basically I have a MergedStation whose property subStations points to many Station objects: MergedStation.subStation -->> Station

When I call [mergedStation addSubStationsObject:newStation]; (which is dynamically created) everything works great and a new station is added, everything is refreshed and saved correctly so that the next time I open the program, all is right.

However, when I call [mergedStation removeSubStationsObject:stationToRemove]; (also dynamically created), everything deletes correctly only for the current program session.  If I close the program and open it again, it's like I didn't change anything.  I have the exact same methods called after both the add and remove methods:

```<code>[self.managedObjectContext refreshObject:station mergeChanges:YES];

[self.managedObjectContext processPendingChanges];

[self.managedObjectContext saveAndPrintErrors];
</code>```

I have also tried different combinations of that above code to get it to work.  Any help is appreciated!

Joe

答:
Ugh. I've spent too much time on a problem closely related to this. In my case, I was adding entities to a to-many relationship and losing those changes after relaunching my app. Adding the inverse relationship is what solved the problem, but I don't understand why. I mean, I see why inverse relationships are a good thing, but they should be mandated or at least default by Core Data if a one-way relationship is as useless as it seems to be.

Thanks to Erik P above for giving me the clue I needed! Add those inverse relationships!

Body:
I have a "to->many" relationship in Core Data with no inverse relationship and the delete rule set to both "Nullify" and "No action" (by that I mean I've tried both with no avail)

Basically I have a MergedStation whose property subStations points to many Station objects: MergedStation.subStation -->> Station

When I call [mergedStation addSubStationsObject:newStation]; (which is dynamically created) everything works great and a new station is added, everything is refreshed and saved correctly so that the next time I open the program, all is right.

However, when I call [mergedStation removeSubStationsObject:stationToRemove]; (also dynamically created), everything deletes correctly only for the current program session.  If I close the program and open it again, it's like I didn't change anything.  I have the exact same methods called after both the add and remove methods:

[self.managedObjectContext refreshObject:station mergeChanges:YES];

[self.managedObjectContext processPendingChanges];

[self.managedObjectContext saveAndPrintErrors];

I have also tried different combinations of that above code to get it to work.  Any help is appreciated!

Joe


问:
Get the pid of a running playbook for use within the playbook
When we run a playbook, with verbose output enabled, in the ansible logs we can see something like this:

2016-02-03 12:51:58,235 p=4105 u=root |  PLAY RECAP

I guess that the p=4105 is the pid of the playbook when it ran.

Is there a way to get this pid inside the playbook during its runtime (as a variable for example)?

答:
You can define the PID for localhost using the set_fact module with a lookup filter.

```<code>- hosts: localhost
  tasks:
    - set_fact:
        pid: "{{ lookup('pipe', 'echo $PPID') }}"
</code>```

And later on you can reference the PID via the hostvars dictionary.

```<code>- hosts: remote
  tasks:
    - debug: var=hostvars.localhost.pid
</code>```

Body:
You can define the PID for localhost using the set_fact module with a lookup filter.

- hosts: localhost
  tasks:
    - set_fact:
        pid: "{{ lookup('pipe', 'echo $PPID') }}"

And later on you can reference the PID via the hostvars dictionary.

- hosts: remote
  tasks:
    - debug: var=hostvars.localhost.pid


问:
How to reduce the size of mp3 file in Android created using MediaRecorder
My app creates audio files using MediaRecorder class and I need to upload these created files to a server. Therefore I need these files to be of minimum size so that they can be easily uploaded.
Size reduction may include some degradation of quality.</p>

答: you should use .amr file format in place of MP3, because its auto create the reduced size file compare to mp3.


问:
PATCH Async requests with Windows.Web.Http.HttpClient class
I need to do a PATCH request with the Windows.Web.Http.HttpClient class and there is no official documentation on how to do it. How can I do this?

答:
For it to work you need to pass the content like that:</p>

```<code>HttpContent httpContent = new StringContent("Your JSON-String", Encoding.UTF8, "application/json-patch+json");
</code>```

Body:
For it to work you need to pass the content like that:

HttpContent httpContent = new StringContent("Your JSON-String", Encoding.UTF8, "application/json-patch+json");


问:
Threedimensional bwdist function for octave
The Image Package from octave offers a bwdist function which is different to Matlab's bwdist(Link) as it works only on twodimensional matrices and not on 3dimensional ones.

Is there a similar function to Matlabs bwdist function that can also handle threedimensional matrices?

答:
No, just write one yourself, e.g.

```<code>function Out = bwdist3D (Obj)
  Obj        = logical (Obj);
  ObjSize    = size (Obj);
  ObjIndices = find (Obj == true);
  [X, Y, Z] = ndgrid (1 : ObjSize(1), 1 : ObjSize(2), 1 : ObjSize(3));

  Out = zeros ([ObjSize, length(ObjIndices)]);
  for Iter = 1 : length (ObjIndices)
    [x, y, z] = ind2sub (ObjSize, ObjIndices(Iter));
    Out(:, :, :, Iter) = sqrt ((X - x).^2 + (Y - y).^2 + (Z - z).^2 );
  end

  Out = min (Out, [], 4);
end
</code>```

The only downside is that it won't be as optimised, but it should do the trick.

PS: Note this is for guidance only; clearly the above function is lacking all the necessary input checks / sanitisation any proper function should have.

EDIT: fully vectorised version of the above

```<code>function Out = bwdist3D (Obj)
  [X, Y, Z] = ndgrid (1 : size (Obj, 1), 1 : size (Obj, 2), 1 : size (Obj, 3));
  [x, y, z] = ind2sub (size(Obj), reshape(find(Obj>0), [1,1,1,sum(Obj(:)>0)]));
  Out = min (sqrt((X-x).^2 + (Y-y).^2 + (Z-z).^2), [] ,4);
end
</code>```

PS: code-golf at its finest :p

Body:
No, just write one yourself, e.g.

function Out = bwdist3D (Obj)
  Obj        = logical (Obj);
  ObjSize    = size (Obj);
  ObjIndices = find (Obj == true);
  [X, Y, Z] = ndgrid (1 : ObjSize(1), 1 : ObjSize(2), 1 : ObjSize(3));

  Out = zeros ([ObjSize, length(ObjIndices)]);
  for Iter = 1 : length (ObjIndices)
    [x, y, z] = ind2sub (ObjSize, ObjIndices(Iter));
    Out(:, :, :, Iter) = sqrt ((X - x).^2 + (Y - y).^2 + (Z - z).^2 );
  end

  Out = min (Out, [], 4);
end

The only downside is that it won't be as optimised, but it should do the trick.

PS: Note this is for guidance only; clearly the above function is lacking all the necessary input checks / sanitisation any proper function should have.

EDIT: fully vectorised version of the above

function Out = bwdist3D (Obj)
  [X, Y, Z] = ndgrid (1 : size (Obj, 1), 1 : size (Obj, 2), 1 : size (Obj, 3));
  [x, y, z] = ind2sub (size(Obj), reshape(find(Obj>0), [1,1,1,sum(Obj(:)>0)]));
  Out = min (sqrt((X-x).^2 + (Y-y).^2 + (Z-z).^2), [] ,4);
end

PS: code-golf at its finest :p


问:
What is the mistake i'm making?
I'm learning python from Learn Python The Hard Way. This is one of the exercises given, but my output doesn't matches the What You Should See section. Here is the output snap. The 2nd line is printed in number 3 and the 3rd line isn't printed at all.

Here is my code:

```<code>from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)
print "First let's print the whole file:\n"

print_all(current_file)

print "now let's rewind, kind of like tape."

rewind(current_file)

print "Let's print three lines: "

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)
</code>```

Is there some problem with readline() in my system? This isn't the first time this happens.

答:
Your test.txt file contains several blank lines. You have to delete them, particularly between line1 and line2. It will solve your problem.

Without empty line :

```<code>First let's print the whole file:

this is line1.Say hello.
this is line2. This must be printed!!
this is line3.This is cool!Print please

now let's rewind, kind of like tape.
Let's print three lines:
1 this is line1.Say hello.

2 this is line2. This must be printed!!

3 this is line3.This is cool!Print please
</code>```

In your case (with empty line), you simply print the empty line starting with "2" (which means that the global variable current_line is effectively incremented):

```<code>First let's print the whole file:

this is line1.Say hello.

this is line2. This must be printed!!

this is line3.This is cool!Print please

now let's rewind, kind of like tape.
Let's print three lines:
1 this is line1.Say hello.

2

3 this is line2. This must be printed!!
</code>```

Title: What is the mistake i'm making?

Body:
I'm learning python from Learn Python The Hard Way. This is one of the exercises given, but my output doesn't matches the What You Should See section. Here is the output snap. The 2nd line is printed in number 3 and the 3rd line isn't printed at all.

Here is my code:

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)
print "First let's print the whole file:\n"

print_all(current_file)

print "now let's rewind, kind of like tape."

rewind(current_file)

print "Let's print three lines: "

current_line = 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

current_line += 1
print_a_line(current_line, current_file)

Is there some problem with readline() in my system? This isn't the first time this happens.

Body:
Your test.txt file contains several blank lines. You have to delete them, particularly between line1 and line2. It will solve your problem.

Without empty line :

First let's print the whole file:

this is line1.Say hello.
this is line2. This must be printed!!
this is line3.This is cool!Print please

now let's rewind, kind of like tape.
Let's print three lines:
1 this is line1.Say hello.

2 this is line2. This must be printed!!

3 this is line3.This is cool!Print please

In your case (with empty line), you simply print the empty line starting with "2" (which means that the global variable current_line is effectively incremented):

First let's print the whole file:

this is line1.Say hello.

this is line2. This must be printed!!

this is line3.This is cool!Print please

now let's rewind, kind of like tape.
Let's print three lines:
1 this is line1.Say hello.

2

3 this is line2. This must be printed!!


答:
Adapted from Print two-dimensional array in spiral order</p>

```<code>import itertools

arr = [[2,  3,  5,  9, 10],
       [8,  7,  1, 11, 13],
       [0,  4,  6, 21, 22],
       [12, 19, 17, 18, 25],
       [14, 15, 16, 23, 24]]

def transpose_and_yield_top(arr):
    while arr:
        yield arr[0]
        arr = list(zip(*arr[1:]))[::-1]

rotated = list(itertools.chain(*transpose_and_yield_top(arr)))
</code>```

Title: Python: 2D to 1D list in clockwise direction?

Body:
I am a bit newbie to Python and I am looking for a function that will convert any n x n 2D list to a 1D list in clockwise direction.

For example:

When n = 3

list = [[2, 3, 5],[ 8, 7, 1],[ 0, 4, 6]]

or

list = [[2, 3, 5]
       ,[8, 7, 1]
       ,[0, 4, 6]]

would become

result = [2, 3, 5, 1, 6, 4, 0, 8, 7]

and when n = 5

list = [[2, 3, 5, 9, 10],[ 8, 7, 1, 11, 13],[ 0, 4, 6, 21, 22], [12, 19, 17, 18, 25], [14, 15, 16, 23, 24]]

or

list = [[  2,  3,  5,  9, 10]
       ,[  8,  7,  1, 11, 13]
       ,[  0,  4,  6, 21, 22]
       ,[ 12, 19, 17, 18, 25]
      , [ 14, 15, 16, 23, 24]]

would become

result = [2, 3, 5, 9, 10, 13, 22, 25, 24, 23, 16, 15, 14, 12, 0, 8, 7, 1, 11, 21, 18, 17, 19, 4, 6]

How can I efficiently do that for any value of nxn ??

Body:
Adapted from Print two-dimensional array in spiral order

import itertools

arr = [[2,  3,  5,  9, 10],
       [8,  7,  1, 11, 13],
       [0,  4,  6, 21, 22],
       [12, 19, 17, 18, 25],
       [14, 15, 16, 23, 24]]

def transpose_and_yield_top(arr):
    while arr:
        yield arr[0]
        arr = list(zip(*arr[1:]))[::-1]

rotated = list(itertools.chain(*transpose_and_yield_top(arr)))


问:
Placing "Add to cart" button on homepage in Magento
I'm trying to develop a shopping portal in Magento. At homepage, I want to show "add to cart" button next to every product shown there. Home Page is a simple static CMS page.
When i tried this code,

```<code><button class="button btn-cart" title="Add to Cart" onclick="setLocation('/n/magento/checkout/cart/add/product/644/qty/1')" type="button"><span><span>Add to Cart</span></span></button>
</code>```

where 644 is product id, page was redirected to cart page, but product is not being added in the cart. I tried it in firefox, chrome and IE as well but with nothing. I searched through many sites for this, but couldn't find anything useful.
If anyone could help regarding this, it will be of great help. Thanks in advance.

答:
It's working, try this:</p>

```<code>$product = Mage::getModel('catalog/product')->load(1);

echo '<a href=' . Mage::helper('checkout/cart')->getAddUrl($product) .'>CONFIRM AND PROCEED TO CHECKOUT </a>';
</code>```

Body:
I'm trying to develop a shopping portal in Magento. At homepage, I want to show "add to cart" button next to every product shown there. Home Page is a simple static CMS page.
When i tried this code,

<button class="button btn-cart" title="Add to Cart" onclick="setLocation('/n/magento/checkout/cart/add/product/644/qty/1')" type="button">Add to Cart</button>

where 644 is product id, page was redirected to cart page, but product is not being added in the cart. I tried it in firefox, chrome and IE as well but with nothing. I searched through many sites for this, but couldn't find anything useful.
If anyone could help regarding this, it will be of great help. Thanks in advance.

Body:
It's working, try this:

$product = Mage::getModel('catalog/product')->load(1);

echo '<a href=' . Mage::helper('checkout/cart')->getAddUrl($product) .'>CONFIRM AND PROCEED TO CHECKOUT </a>';