text:
Q: C# Entity Framework Using the Repository and Unit of Work Pattern for Multiple DB Transactions I have defined three tables, Parts, Models and PartModel.
For each Part row, there may be multiple Models row defined, and they are joined in a relationship via the PartModel table.
Parts
ID  PartName
1   Motorcycle
2   Cars

Models
ID  ModelName
1   Suzuki
2   Yamaha
3   Toyota
4   Nissan

PartModel
ID    PartID         ModelID
1       1               1
2       1               2
3       2               3
4       2               4

C# Models
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;

namespace TestApplication.Model
{
    [Table("Parts")]
    public partial class Parts
    {
        [Key]
        public int PartID { get; set; }

        [Required]
        [StringLength(50)]
        public string PartName { get; set; }
    }

    [Table("Models")]
    public partial class Models
    {
        [Key]
        public int ModelID { get; set; }

        [Required]
        [StringLength(50)]
        public string ModelName { get; set; }
    }

    [Table("PartModel")]
    public partial class PartModel
    {
        [Key]
        public int PartModelID { get; set; }

        public int PartID { get; set; }

        public int ModelID { get; set; }
    }
}

And here are my repository classes:
BaseRepository.cs
using System;
using System.Transactions;

namespace TestApplication.Data
{
    public abstract class BaseRepository<TContext> : IDisposable
        where TContext : class, new()
    {
        private readonly bool startedNewUnitOfWork;
        private readonly IUnitOfWork<TContext> unitOfWork;
        private readonly TContext context;
        private bool disposed;

        public BaseRepository()
            : this(null)
        {
        }

        public BaseRepository(IUnitOfWork<TContext> unitOfWork)
        {
            if (unitOfWork == null)
            {
                this.startedNewUnitOfWork = true;
                this.unitOfWork = BeginUnitOfWork();
            }
            else
            {
                this.startedNewUnitOfWork = false;
                this.unitOfWork = unitOfWork;
            }

            this.context = this.unitOfWork.Context;
            this.disposed = false;
        }

        ~BaseRepository()
        {
            this.Dispose(false);
        }

        protected TContext Context
        {
            get
            {
                return this.context;
            }
        }

        public IUnitOfWork<TContext> UnitOfWork
        {
            get
            {
                return this.unitOfWork;
            }
        }

        public void Commit()
        {
            this.unitOfWork.Commit();
        }

        public void Rollback()
        {
            this.unitOfWork.Rollback();
        }

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

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    DisposeManagedResources();
                }

                this.disposed = true;
            }
        }

        protected virtual void DisposeManagedResources()
        {
            if (this.startedNewUnitOfWork && (this.unitOfWork != null))
            {
                this.unitOfWork.Dispose();
            }
        }

        public IUnitOfWork<TContext> BeginUnitOfWork()
        {
            return BeginUnitOfWork(IsolationLevel.ReadCommitted);
        }

        public static IUnitOfWork<TContext> BeginUnitOfWork(IsolationLevel isolationLevel)
        {
            return new UnitOfWorkFactory<TContext>().Create(isolationLevel);
        }
    }
}

IRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace TestApplication.Data
{
    public interface IRepository<TContext, TEntity, TKey>
        where TContext : class
        where TEntity : class
    {
        IUnitOfWork<TContext> UnitOfWork { get; }

        List<TEntity> Find(Expression<Func<TEntity, bool>> predicate = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderByMethod = null, string includePaths = "");
        TEntity FindByID(TKey id);
        List<TEntity> FindAll();
        void Add(TEntity entity, Guid userId);
        void Update(TEntity entity, Guid userId);
        void Remove(TKey id, Guid userId);
        void Remove(TEntity entity, Guid userId);
    }
}

Repository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace TestApplication.Data
{
    public class Repository<TContext, TEntity, TKey> : BaseRepository<TContext>, IRepository<TContext, TEntity, TKey>
        where TContext : class, new()
        where TEntity : class
    {
        private readonly DbSet<TEntity> _dbSet;

        private DbContext CurrentDbContext
        {
            get
            {
                return Context as DbContext;
            }
        }

        public Repository()
            : this(null)
        {
        }

        public Repository(IUnitOfWork<TContext> unitOfWork)
            : base(unitOfWork)
        {
            _dbSet = CurrentDbContext.Set<TEntity>();
        }

        public virtual List<TEntity> Find(Expression<Func<TEntity, bool>> predicate = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderByMethod = null, string includePaths = "")
        {
            IQueryable<TEntity> query = _dbSet;

            if (predicate != null)
                query = query.Where(predicate);

            if (includePaths != null)
            {
                var paths = includePaths.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                query = paths.Aggregate(query, (current, path) => current.Include(path));
            }

            var entities = orderByMethod == null ? query.ToList() : orderByMethod(query).ToList();

            return entities;
        }

        public virtual TEntity FindByID(TKey id)
        {
            var entity = _dbSet.Find(id);

            return entity;
        }

        public virtual List<TEntity> FindAll()
        {
            return Find();
        }

        public virtual void Add(TEntity entity, Guid userId)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            _dbSet.Add(entity);
        }

        public virtual void Update(TEntity entity, Guid userId)
        {
            if (entity == null) throw new ArgumentNullException("entity");

            _dbSet.Attach(entity);
            CurrentDbContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Remove(TKey id, Guid userId)
        {
            var entity = _dbSet.Find(id);
            Remove(entity, userId);
        }

        public virtual void Remove(TEntity entity, Guid userId)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            if (CurrentDbContext.Entry(entity).State == EntityState.Detached)
                _dbSet.Attach(entity);

            _dbSet.Remove(entity);
        }
    }
}

PartsRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestApplication.Model;

namespace TestApplication.Data
{
    public class PartsRepository : Repository<DBContext, Parts, int>
    {
        public PartsRepository() : this(null) { }
        public PartsRepository(IUnitOfWork<DBContext> unitOfWork) : base(unitOfWork) { }
    }
}

ModelsRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestApplication.Model;

namespace TestApplication.Data
{
    public class ModelsRepository : Repository<DBContext, Models, int>
    {
        public ModelsRepository() : this(null) { }
        public ModelsRepository(IUnitOfWork<DBContext> unitOfWork) : base(unitOfWork) { }
    }
}

PartModelRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestApplication.Model;

namespace TestApplication.Data
{
    public class PartModelRepository : Repository<DBContext, PartModel, int>
    {
        public PartModelRepository() : this(null) { }
        public PartModelRepository(IUnitOfWork<DBContext> unitOfWork) : base(unitOfWork) { }

        public PartModel GetPartModelByModelID(ModelID)
        {
            // LINQ Query here to get the PartModel object based on the ModelID
            var q = (from a in this.Context.PartModel.Where(a => a.ModelID == ModelID)
                             select a);
            PartModel partModel = q.FirstOrDefault();
            return partModel;
        }
    }
}

What I need to do is to use the repository to say, for example, I wanted to delete the model 1 (Suzuki), I can perform multiple table delete in a single transaction so that I can be assured that the data will be deleted from both tables Model and PartModel.
Currently, my codes are as follows (this works but notice that I am committing on both Repository calls, which then has the tendency where one transaction may fail but still the changes to the database would be pushed on the other repository call):
public bool DeleteModel(int ModelID)
{
    // Get the PartModel based on the ModelID
    using(PartModelRepository partModelRepo = new PartModelRepository())
    {
        PartModel partModel = partModelRepo.GetPartModelByModelID(ModelID);
        partModelRepo.Remove(partModel, Guid.NewGuid());
        partModel.Commit();
    }

    // Delete the Model
    using(ModelsRepository modelRepo = new ModelsRepository())
    {
        Models model = modelRepo.FindByID(ModelID);
        modelRepo.Remove(model, Guid.NewGuid());
        modelRepo.Commit();
    }
}

How would I be able to translate this so that I can have a single Commit for both DB delete commands?
I tried the following:
public bool DeleteModel(int ModelID)
{
    // Get the PartModel based on the ModelID
    using(ModelsRepository modelsRepo = new ModelsRepository())
    {
        using(PartModelRepository partModelRepo = new PartModelRepository(modelsRepo.UnitOfWork))
        {
            PartModel partModel = partModelRepo.GetPartModelByModelID(ModelID);
            partModelRepo.Remove(partModel, Guid.NewGuid());

            Models model = modelRepo.FindByID(ModelID);
            modelRepo.Remove(model, Guid.NewGuid());
            modelRepo.Commit();
        }
    }
}

But it is throwing an error saying something about FK Constraint Violation.
I do understand that I am deleting the PartModel and the Model, but it seems it can't take both delete actions into a single transaction operation.
Appreciate any input.
UPDATE
As some people have posted here, I have updated my code to utilize Transactions as recommended by Microsoft.
public bool DeleteModel(int ModelID)
    {
        // Get the PartModel based on the ModelID

        using (var transaction = this.Context.Database.BeginTransaction())
        {
            PartModel partModel = this.Context.PartModel.First(s => s.ModelID == ModelID);
            Models model = this.Context.Models.First(s => s.ModelID == ModelID);

            this.Context.PartModel.Remove(partModel);
            this.Context.Models.Remove(model);

            this.Context.SaveChanges();
            transaction.Commit();
        }

        return true;
    }

I traced the database call using MS SQL Profiler and the commands being issued are correct. The issue I am having is that it seems that the changes are not being persisted to the database.
I used a try catch block on the above code, but no error is being thrown, hence, I know that the operation is ok.
Any ideas on where to look further?

A: DbContext is aware of ambient transactions.
To do show, reference System.Transactions in your project and enclose all the actions inside a block like this, which instances a TrasnactionScope:
using(var ts = new TransactinScope())
{
    // inside transaction scope

    // run all the transactional operations here

    // call .Complete to "commit" them all
    ts.Complete();
}

If there is an exception, or you don't call ts.Complete() or you explicitly call ts.Dispose() the transaction, which means all the operations inside the block, is rolled back.
For example, you can modify your public bool DeleteModel(int ModelID) including a using that wraps all the operations, and they'll share the same transaction.
Update:
Just to add more to this answer, since I am mostly performing data related changes, I have opted to use Database.BeginTransaction.

A: You can use .Net's TransactionScope class to do a Multi-database transaction. You'll still have to call SaveChanges() on each context separately within the transaction, but calling Commit() on the outer TransactionScope will do the final commit.
As far as your fk violation, I'd recommend using SqlServer profiler or a DB interceptor to trace the queries EF is executing. Sometimes you need to be more explicit in telling EF to delete dependencies: the trace should make it easy to tell what is t being deleted. Another thing to watch out for is that EF assumes FK relationships are Cascade On Delete by default. If you haven't disabled this in your configuration and EF is not the one generating your DB, then the mismatch can cause EF to assume it needs to issue fewer delete queries than is actually required.


text:
Q: Using Firebase clock to timestamp changes We have a dataset in Firebase updated by multiple clients.
We want to track the last modified on datetime of the dataset. We cannot rely on the client setting the modified on datetime as their local clock can be totally out of sync.
Is there a way I could have Firebase tag timestamp to a dataset based on its clock to track last modified on?

A: We're working on some features to support this at the moment, but we don't have a way to do this right now. Note, however, that the IDs created by "push()" are chronologically-ordered, and we compensate for client-side clock skew as best we can when we create them, so if all you're trying to do is make sure some writes to a list occur in order, you can do that with push().
I'd be interested in hearing how you'd like this feature to look. If you have a sec I'd appreciate an email to andrew at firebase...
Update: Firebase now supports setting server timestamps as well as accessing the server time directly on the client. See the documentation here:
https://www.firebase.com/docs/managing-presence.html

A: We're on the same boat...    and I guess sooner or later, many firebase clients will have this issue,  as it's a "new kind" of problem we never had to face in the old "client-server" days.
Out current solution (still in the making) is to estimate the time difference between the client and OUR server on initialization, and them compensate,
So - where we had x = new Date(),
it is now x = ourDateService.now()
our now() function simply does new Date() + diff
This works for us,as we don't need millisecond accuracy, and it's a single-page-app that loads once, so we can do this diff-check and initialize ourDateService on load,   but this solution will not work for everybody (ofcourse, you can store it in the localstorage/cookie and revalidate every day or so).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark 1.6 Data Frame - convert all field values in struct to uppercase Have the following data frame and using Spark 1.6
scala> dfShow.printSchema
root
 |-- email: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- EML: string (nullable = true)
 |    |    |-- EMT: string (nullable = true)

This reads fine from source json. How can I convert the all the values to uppercase? Show on data frame gives
scala> dfShow.show
[{"EML":"a.b@c.COM","EMT":"b"},{"EML":"d.e@x.COM","EMT":"h"}]
[{"EML":"g@g.COM","EMT":"h"},{"EML":"f@f.com","EMT":"x"}]
null
[{"EML":"j@j.org","EMT":"b"},{"EML":"r.r@r.COM","EMT":"t"}]

How do I change the values in 2 fields EML and EMT to be upper case? Would like the fields to look as follows
[{"EML":"A.B@C.COM","EMT":"B"},{"EML":"D.E@X.COM","EMT":"H"}]
[{"EML":"G@G.COM","EMT":"H"},{"EML":"F@F.com","EMT":"X"}]
null
[{"EML":"J@J.org","EMT":"B"},{"EML":"R.R@R.COM","EMT":"T"}]

This is one struct field. I have other struct fields like address (line1,line2,city,state,zip,country) , phone etc. Is there a generic way to convert values for all struct fields to upper?


text:
Q: Onload function to call an action to achieve "Save and Print" through javascript I have a invoice form in which i want to add option to print invoice on form submit. for this i have added a button and made some changes in controller.Here is my code
In invoice form:
<%= form_for @invoice do |f| %>
   :
   **Invoice fields**
   :

 <%= f.submit "Save", :name=>"save", :class=>'btn btn-success' %>
 <%= f.submit "Save & Print", :name=>"save_and_print", :class=>'btn btn-default' %>
<% end %>

And in my controller i did this:
def create
     :
     :
      if params[:save_and_print]
       format.html { redirect_to("/invoices/#{@invoice.id}?save_and_print=1", :notice => 'Invoice  has been saved and printed.') }
       else
        format.html { redirect_to(@invoice, :notice => 'Invoice has been saved.') }
       end
    end

    def show
     :
     :
      respond_to do |format|
       format.pdf do
        template=Invoice.get_template(@company, "Invoice", params[:dlc])
        pdf=InvoicePdf.new(@invoice, view_context, @receipt_vouchers)
        send_data pdf.render, :filename=>"#{@invoice.invoice_number}.pdf",  :disposition=>"inline", :type=>'pdf'
      end
      end
    end

And here is my link to print pdf:
<%= link_to raw('<i class="icon-print"> </i>'), invoice_path(@invoice, :format => 'pdf'), :target=>"_blank", :title=>"Print" %>

I am thinking to create an onload function to trigger generate pdf link on view page load after form submit. Any help would be appreciated.

A: The reason why it is not redirecting to invoice view screen is because of this line if params[:save_and_print],it should be if params[:submit] == "save_and_print"
if params[:submit] == "save_and_print" #here
  format.html { redirect_to("/invoices/#{@invoice.id}?save_and_print=1", :notice => 'Invoice  has been saved and printed.') }
else
  format.html { redirect_to(@invoice, :notice => 'Invoice has been saved.') }
end

You should be accessing the value passed to the submit button through giving params[:submit].

A: I have got a simple solution for my problem. First of all i gave id to  my print pdf link and than call that link on page load. Here is my solution :
<%= link_to raw('<i class="icon-print"> </i>'), invoice_path(@invoice, :format => 'pdf', :dlc=>"no"), :class => 'btn btn-white btn-lg', :id=>"print1-inv", :target=>"_blank", :title=>"Print" %>

and script on show.html.erb:
<% if !params[:save_and_print].blank? && params[:save_and_print]=="1" %>
<script>
  $(document).ready(function(){
    $("#print1-inv")[0].click();
  });
</script>
<% end %>

this code works for me.


text:
Q: Custom customer attributes are not shown at checkout register in Magento 2 I have created custom customer attributes, it is working fine in customer registration form but not shown at checkout register page in Magento 2.

A: customer attributes are display in the customer registration page,
but address fields are display in the both customer registration and checkout page.
Customer attribute feature is a default feature in magento 2 EE.
Stores -> Atrributes

For magento 2 CE have to create attributes using custom module, please follow bellow url https://www.mageplaza.com/magento-2-module-development/magento-2-add-customer-attribute-programmatically.html
as a resource I have added tutorial content here, this for create customer attribute but question is why some attributes didn't display in checkout.

This article will guide you how to create a add customer attribute in Magento 2 programatically. Please follow our previous article to create a simple module which we will use to demo coding for this lesson and how to create the setup script classes. In this article, we will use the sample module Mageplaza_HelloWorld and the InstallDataclass.
Overview of Adding Customer Attribute Programmatically

*

*Step 1: Create setup file InstallData.php

*Step 2: Define the install() method

*Step 3: Create custom attribute

Step 1: Create setup file InstallData.php
Firstly, we will create the InstallData.php file:
File: app/code/Mageplaza/HelloWorld/Setup/InstallData.php
<?php
namespace Mageplaza\HelloWorld\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

}

In this class, we define the EAV setup model which will be use to interact with Magento 2 attribute.
Step 2: Define the install() method
After that, we have to define the install() method and create eav setup model:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    }
    // Next, we will use eavSetup object to add attribute:
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'sample_attribute',
            [
                'type'         => 'varchar',
                'label'        => 'Sample Attribute',
                'input'        => 'text',
                'required'     => false,
                'visible'      => true,
                'user_defined' => true,
                'position'     => 999,
                'system'       => 0,
            ]
        );
}

Step 3: Create custom attribute
Finally, we need to set the forms in which the attributes will be used. In this step, we need define the eavConfig object which allow us to call the attribute back and set the data for it. And the full code to create customer attribute is:
File: app/code/Mageplaza/HelloWorld/Setup/InstallData.php
<?php

namespace Mageplaza\HelloWorld\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Config;
use Magento\Customer\Model\Customer;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig       = $eavConfig;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY,
            'sample_attribute',
            [
                'type'         => 'varchar',
                'label'        => 'Sample Attribute',
                'input'        => 'text',
                'required'     => false,
                'visible'      => true,
                'user_defined' => true,
                'position'     => 999,
                'system'       => 0,
            ]
        );
        $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'sample_attribute');

        // more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
        $sampleAttribute->setData(
            'used_in_forms',
            ['adminhtml_customer']

        );
        $sampleAttribute->save();
    }
}

Now, let run comman line to install the module:

bin/magento setup:upgrade

and

php bin/magento setup:static-content:deploy

Then check the result. It will show like this:


text:
Q: Domain and range of $f(x)=3\sin^{-1}(5x)$ I am trying to determine the domain of $$f(x)=3\sin^{-1}(5x).$$ Since the domain of $g(x)=\sin^{-1}(x)$ is given by the set $\{x\in\mathbb{R}:-1\leq x\leq 1\}$, I understand that the domain of $f$ must satisfy
\begin{align}
-1&\leq5x\leq1 \\
-\frac{1}{5}&\leq x\leq\frac{1}{5}.
\end{align}
I know the range of $g$ is given by the set $\left\{y\in\mathbb{R}:-\frac{\pi}{2}\leq y\leq\frac{\pi}{2}\right\}$, but I am unable to determine the range of $f$. Any suggestions are helpful.

A: Yes, the domain of $f$ is given for all $x\in [-1/5,1/5]$ as you said, that's perfect work.  Now, since as you said the range of $x\mapsto \sin^{-1}x$ is given by $[-\pi/2,\pi/2]$ and the factor $3$ affects the range so the range of $x\mapsto 3\sin^{-1}(5x)$ is given by $y\in [-3\pi/2,3\pi/2]$.


text:
Q: Select column value dependant on the value of another column I need to produce a report and replace all NULL values in a 'NUMBER' column with a value between 1 and 10 dependant on the value of another 'VALUE' column and then total them up.  Some of 'NUMBER' have been included already, but some have not.  Basically, this is what I have -
**NUMBER**   **VALUE**    **DATE**
NULL         Apple        2012-08-01
NULL         Pear         2012-08-01
NULL         Banana
NULL         Apple        2012-08-02
1            Apple
2            Pear         2012-08-04
3            Banana       2012-08-04

What I need to produce is a report that shows something like this -
**NUMBER**    **VALUE**    **TOTAL**    **DATE**
1             Apple        3            2
2             Pear         2            2
3             Banana       2            1

The problem I have is that there is another COUNT within the SQL and I can't work out a way getting everthing to work together.  The current SQL is looks like this -
SELECT    NUMBER,
          VALUE,
          COUNT (NUMBER) AS TOTAL,
          COUNT (DATE) AS DATE

FROM      MY_TABLE

GROUP BY  NUMBER,
          VALUE

Thanks.

A: If I understood your question correctly, this query will return the totals you desire:
WITH ValueCount AS
(
   SELECT mt.Value, COUNT(1) AS Total
   FROM #My_Table AS mt
   GROUP BY mt.Value
)
, DateCount AS
(
   SELECT mt.Value, COUNT(1) AS DateTotal
   FROM #My_Table AS mt
   WHERE mt.MyDate IS NOT NULL
   GROUP BY mt.Value
)
SELECT mt.Number, vc.Value, vc.Total, dc.DateTotal
FROM ValueCount AS vc
INNER JOIN #My_Table AS mt ON vc.Value = mt.Value
INNER JOIN DateCount AS dc ON vc.Value = dc.Value
WHERE mt.Number IS NOT NULL
ORDER BY mt.Number ASC;

I broke up totaling the Value from the Date because you were looking for different criteria.  If you do not like the look of the Common Table Expression (CTE), you can accomplish this with multiple queries, or sub-queries as well.
When using a CTE, the preceeding query must end with a semi-colon.


text:
Q: Pausing / Resuming Handler post delayed I am trying to start an activity after a delay of 2 seconds . The code -
runnable = new Runnable() {
        @Override
        public void run() {
            final Intent i = new Intent(PreviewCoordinatesActivity.this,
                    StylePreviewActivity.class);
            i.putExtra(AppConstants.IMAGEPATH, sImagePath);
            moveNextToAndFinish(i);
        }
    };
    handler.postDelayed(runnable, DELAY);

I want to pause the operation when the activity is paused and resume the operation once the activity comes back to foreground .
At present i am just removing the callback when the activity is paused -
@Override
protected void onPause() {
    super.onPause();
    if (handler != null) {
        if (runnable != null)
            handler.removeCallbacks(runnable);
    }

}

A: Here's the implementation I used:
private static final long PAUSED_TIME_UNSET = 0L;

private Handler delayHandler;
private long pausedTime;
private List<Message> pendingMessages;
private Map<Message, Long> messageTimeMap;

//this should not be called while paused
protected Runnable runAfterDelay(Runnable toRun, long delayMillis) {
    if (delayHandler == null) {
        delayHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                pendingMessages.remove(msg);
                if (msg.obj instanceof Runnable) {
                    ((Runnable) msg.obj).run();
                }
                return true;
            }
        });
    }
    Message m = Message.obtain();
    m.obj = toRun;
    pendingMessages.add(m);
    delayHandler.sendMessageDelayed(m, delayMillis);
    return toRun;
}

protected void cancelDelayedRunnable(Runnable runnable) {
    for (Iterator<Message> iter = pendingMessages.iterator(); iter.hasNext(); ) {
        Message msg = iter.next();
        if (msg.obj == runnable) {
            iter.remove();
            break; //assume all runnables are unique
        }
    }
    delayHandler.removeCallbacksAndMessages(runnable);
}

protected void cancelAllDelayedRunnables() {
    if (delayHandler != null) {
        delayHandler.removeCallbacksAndMessages(null);
        delayHandler = null;
    }
    pendingMessages.clear();
}

public void pause() {
    if (delayHandler != null && pausedTime == PAUSED_TIME_UNSET) {
        pausedTime = SystemClock.uptimeMillis();

        //need to copy the Messages because their data will get cleared in removeCallbacksAndMessages
        List<Message> copiedMessages = new ArrayList<Message>();
        for (Message msg : pendingMessages) {
            Message copy = Message.obtain();
            copy.obj = msg.obj;
            messageTimeMap.put(copy, msg.getWhen()); //remember the time since unable to set directly on Message
            copiedMessages.add(copy);
        }
        //remove all messages from the handler
        delayHandler.removeCallbacksAndMessages(null);
        pendingMessages.clear();

        pendingMessages.addAll(copiedMessages);
    }
}

public void resume() {
    if (delayHandler != null && pausedTime != PAUSED_TIME_UNSET) {
        for (Message msg : pendingMessages) {
            long msgWhen = messageTimeMap.get(msg);
            long timeLeftForMessage = msgWhen - pausedTime;
            delayHandler.sendMessageDelayed(msg, timeLeftForMessage);
        }
        messageTimeMap.clear();
        pausedTime = PAUSED_TIME_UNSET;
    }
}


text:
Q: Ampscript %%[IF]%% statement woes I want to check if a personalization attribute is empty before I output it, but I cannot get the Ampscript to work.
Here's my code:
%%[IF Length("Provider Rating") > 0) THEN]%%

Rating:
%%Provider Rating%%

%%[ENDIF]%%

Is this because my attribute has a space in it?  If so, what should I do?  Here is the error:
Errors found in the email HTML Body.
Category : AMP Script
Functions and Custom Objects:("

Error 1: Script IF Statement Invalid
An error occurred when attempting to resolve a script expression. See inner exception for detail. Script Expression: 0) MemberID: 1002582 JobID: 0 An unrecognized expression appears in a script block. Script Expression: 0) MemberID: 1002582 JobID: 0
Invalid Content:
IF Length("Provider Rating") > 0) THEN]%% Rating: %%Provider Rating%% %%[

Errors found in the email Text Body.
Category : AMP Script
Functions and Custom Objects:("

Error 1: Script IF Statement Invalid
An error occurred when attempting to resolve a script expression. See inner exception for detail. Script Expression: 0) MemberID: 1002582 JobID: 0 An unrecognized expression appears in a script block. Script Expression: 0) MemberID: 1002582 JobID: 0
Invalid Content:
IF Length("Provider Rating") > 0) THEN]%% Rating: %%Provider Rating%% %%[

Thanks!
Neil

A: Try it as this:
%%[IF Length([Provider Rating]) > 0 THEN]%%

Rating:
    %%Provider Rating%%

%%[ENDIF]%%

Passing it in with the quotes makes it a string. Use the brackets for spaced attribute names.
Hindsight - make your attributes without spaces.
Updated
The above code snippet is working for me as well. Glad it's working for you.

A: You've got an extra parenthesis in there. And you need brackets around any personalization string containing spaces.  This should work:
%%[ IF Length([Provider Rating]) > 0 THEN ]%%

Rating:
  %%Provider Rating%%

%%[ENDIF]%%

Here's the syntax guide.


text:
Q: Why Java program not terminating The code below checks the usage of ExecutorCompletionService from Java Concurrency framework (the IDE being used is Netbeans).
But the program doesn't terminate. Why?
Code:
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;

public class TestFuture {

    public static void main(String... args) throws InterruptedException, ExecutionException {
        Executor ex = Executors.newCachedThreadPool();
        CompletionService<Long> cs = new ExecutorCompletionService<Long>(ex);
        cs.submit(new Worker());
        cs.submit(new Worker());
        cs.submit(new Worker());
        for (int i = 0; i < 3; i++) {
            long l = cs.take().get();
            //utilize the result
            System.out.println(l);
        }
    }
}

class Worker implements Callable {

    @Override
    public Long call() throws Exception {
        //do some task and return back
        return System.currentTimeMillis();
    }
}

A: Threads in thread pool will keep running when main is finished. That's why JVM won't shut down. You need to either use daemon-threads, or shutdown the pool explicitly.
Here's an example:
ExecutorService ex = Executors.newCachedThreadPool();
// do all your submission work here
ex.shutdown();


text:
Q: .htaccess redirect question I have a slight problem with .htaccess redirect.
I have a dynamic site with 2 levels of variables - content="type -(alpha)" and ID="number" but this is very not seo friendly what I really would like to create is a rewrite rule that generates a "friendly" url for serach engines & users alike.  Very much like WordPress does.
Each ID is already unique (obviously) and on creation is creating a unique "permalink" field so for example ID=1 has a "permalink field" as "2009/10/27/page title" and ID=100 would be "2010/10/27 page title".
I would like folder/wall.php?content=type&ID=number to redirect to folder/permalink.php/html/htm (don't mind a non dynamic extension)
Any clues? - this is not right (I know) but it also "breaks" my css file
RewriteEngine On

RewriteRule wall/content/(.*)/ID/(.*)/ wall.php?content=$1&ID=$2
RewriteRule wall/content/(.*)/ID/(.*) wall.php?content=$1&ID=$2

A: You need to make sure you have a URL convention that won't conflict with other files on the server. For example, if your page is displaying "Products" and you don't have an actual folder in the root of your server called /products/, you could do this
RewriteEngine On
RewriteRule ^products/([^/\.]+)/([^/\.]+)/?$ wall.php?content=$1&id=$2 [L,NC,QSA]

Replace "products" in this example with whatever name is most appropriate for what your wall.php page does.
This would equate to the following URL
www.yoursite.com/products/title/29/

Which would rewrite to
www.yoursite.com/wall.php?content=title&id=29


text:
Q: Do my other local computers need a static IP when I use port forwarding? If I change my main computer to static and port forward to get a server hosted, does that mean that I need to change the rest of the laptops and computer on the network to static to get them to connect to the internet?

A: Port forwarding alone does not affect the way of how you assign addresses to devices in your LAN.
When you setup port forwarding you instruct a router to accept packets on a specific port and route them to some port of some device in the LAN.
The device which should receive these packets must have an IP address and it should be known beforehand when you setup port forwarding. So the address should be constant. It does not matter how this address is being assigned. Having a constant address can be achieved in two ways:

*

*Static IP address. When network interface goes up the device knows what its IP address, subnet mask and default router. So the device sets it appropriately.

*Dynamic IP address with static lease. This means the device itself does not know what its network settings are. It asks a DHCP server for those settings. There is a way to configure DHCP server in the way that it will reserve a particular IP address for a host with particular MAC address. This means even being dynamically assigned, the address will be the same every time. Furthermore, DHCP server can be instructed to give a lease with no expiration. Basically, at this point it will be sort of "static" address. The device will ask for a lease when its network interface goes up and as long as it stays up the device will keep same address and will not try to renew the lease.

Rest of the devices in your LAN can have either static or dynamic addresses. Setting up a port forwarding on the router will not affect communication inside your LAN.
For example, you forward port 80 from router to A. Address of A should be known to router and should not be changing over time. B and C can have static or dynamic addresses regardless of port forwarding.
           router
             |
             |
       -------------
       |     |     |
       |     |     |
       A     B     C

A: No. This is not need. The firewall will keep connections for client machines. Only for servers is necessary to have static IP as router should know the exact IP all the time to forward the proper packages. But you can avoid static IP adding DHCP reservation, based on the MAC address of server and the server will receive always the same IP


text:
Q: cmus not working on Arch Linux When I try to run cmus from the terminal , I got this
bhaskar@ArchLinux_12:18:39_Mon May 20:~>cmus
cmus: /usr/lib/libsystemd.so.0: version LIBSYSTEMD_243' not found (required by cmus)

A: It was me. Because of systemd bug, I masked few packages and never get back to the bug tracker to see that bug got fixed in some time. So, I unmasked those packages and update those and cmus start working like a charm.
Updated packages : systemd systemd-libs sysvcompat
But, somebody somewhere pointed out to me that some component is optionally built with systemd and that why the problem, that can be eliminated, if you decided to do it yourself. But, unfortunately, I pull down system package and it was built with that dependency.
If you use cmus on Arch, you have to go with "their" options or build it yourself.


text:
Q: How to remove time from object in python I have a column with dates but the column type is object, it is not a timestamp. I want to convert the whole column so that it has the datetime format but to do this I need to first remove the time, because I only want the dates.
Example:
Transaction_date
07/10/2019:08:00:00 PM
07/23/2019:08:00:00 PM
3/15/2021

In the first two rows of the transaction_date column, I just want to keep the date and remove the time. This column is still of the type object. I want to convert it into datetime. How do I do that?

A: Use str.split to remove time and convert to datetime:
>>> pd.to_datetime(df['Transaction_date'].str.split(':', n=1).str[0])
0   2019-07-10
1   2019-07-23
2   2021-03-15
Name: Transaction_date, dtype: datetime64[ns]

Note from @ThePyGuy about n=1 to limit number of splits in output and avoid unnecessary splits.

A: If you only have a handful of date formats in your data, you could create a function that tries converting each format sequentially into a datetime via pd.to_datetime(). E.g. for the 2 formats in your post.
def convert_to_datetime(x):
    try:
        return pd.to_datetime(x, format="%m/%d/%Y:%H:%M:%S %p")
    except ValueError:
        pass

    try:
        return pd.to_datetime(x, format="%m/%d/%Y")
    except Exception as e:
        raise e

    return

Then you could use apply to apply it to each row, to convert to columns into a datetime columns. Then you can take the date part directly using .dt.date:
df['TransactionDate'] = df['TransactionDate'].apply(convert_to_datetime)
df['TransactionDate'] = pd.to_datetime(df['TransactionDate'].dt.date)


text:
Q: Check if a geo location falls within two geo locations So,I'm trying to create an applications, where the user sets his destination on a map - let's say from Home to work-, then (with the help of google maps)a direction line shows on the map to guide the user to his destination, or to work in our example .
What I'm trying to achieve here is that I want the app to show any coffee house that is going to be on the user's way to work,or slightly around it, but I'm not sure how to tackle this head scratcher .
Is there a way to know if a point (C) , falls within a straight line between A and b ? or falls close by factor(x) to the line between A and B ?

A: I created a gist which is a Swift translation of locationIndexOnEdgeOrPath function and all the other required functions present in PolyUtil.java.
The parameters you need to pass are the co-ordinates of the point you want to check and the array of points that represent the path. (Your case only includes start and end point, so just pass those two)
The other parameters needed are closed which represents whether a line should be drawn from the last point to first point in order to close the loop; geodesic which means if the earth's curvature should be taken into consideration.
Finally, toleranceEarth is the last parameter where you need to specify how close to the path is considered being on the path.


text:
Q: decomposition group and inertia group, the minimal polynomial,surjectivity of the map $D_{M/P}\rightarrow Gal$ Can anyone explain the underlined sentence?
For notation, A:Dedekind domain, K=Frac(A), L/K:Galois extension, B:The integral closure of A in L, M:A maximal ideal of B, P:The intersection of M and A (hence the maximal ideal of A), $D_{M/P}$ :the decomposition group.
I reckon the way we take $\alpha$ is the key, but cannot make it to the conclusion, 'we find that the only non-zero roots of...'.
I read some of the close questions already answered but none of them was using this type of logic.
Thank you in advance.

A: Let me expand on the highlighted part:
$g(y)$ is the min. polynomial of $\overline{\alpha}$ over $A/P$, so it has to divide the polynomial $\overline{f}(y)=f(y) \,\mathrm{mod}\, P$, since $\overline{\alpha}$ is a root of $\overline{f}(y)$ (and $\overline{f}(y)$ is nonzero, take $f(y)$ monic). From this and the expression $f(y)=\prod_H(y-\sigma(\alpha))$ it follows that the roots of $g(y)$ are just some of the roots $\sigma(\alpha)$ taken modulo $M$, and the goal is to identify which ones.
Now $\alpha$ was chosen so that $\alpha \in \sigma(M)$ whenever $\sigma \notin D_{M/P}$, i.e. $\sigma(M)\neq M$. Applying $\sigma^{-1}$, we have that $\sigma^{-1}(\alpha) \in M$ whenever $\sigma(M)\neq M$. Changing $\sigma^{-1}$ to $\sigma$ (note that $\sigma^{-1} \notin D_{M/P}$ iff $\sigma \notin D_{M/P}$), we have that $\sigma(\alpha) \in M $ whenever $\sigma \notin D_{M/P}$. And conversely, we have $\alpha \notin M$ (because $\overline{\alpha} \neq 0$), so given any $\sigma \in D_{M/P}$, we have that $\sigma(\alpha) \notin \sigma(M)=M$. So altogether: $\sigma(\alpha) \,\mathrm{mod}\,M$ is nonzero iff $\sigma \in D_{M/P}$. So the roots of $g(y)$ can come only from these, i.e. in the form $\overline{\sigma}(\overline{\alpha})$ (because $g(y)$ cannot have $0$ as a root, it's the min. poly. of $\overline{\alpha}$). And all of them has to be roots for Galois reasons (all the maps $\overline{\sigma}$ are elements of the Galois group of the residue field, and $\overline{\alpha}$ is a root of $g(y)$).
Hope this helps.


text:
Q: javascript/jquery- how to determine if a list/checkbox allows multiple values to be selected or not I am trying to parse through a typical form using jquery. I want to obtain all details about the various fields in the form- viz field name, field type (eg radio/checkbox/list)...
How do I determine if a field allows multiple values to be selected? (eg in check box or list box)?
If this cannot be done using jquery, then can it be done using pure javascript? I already have with me a ref to the element for which this (whether multiple values are allowed or not) has to be determined...

A: Surround your control with some <div>   as:
<div id="testCheck">
                <input type="checkbox" checked="checked" value="1" />
                <input type="checkbox" checked="checked" value="2" />
                <input type="checkbox" checked="checked" value="3" />
                <input type="checkbox" checked="checked" value="4" />
                <input type="checkbox" checked="checked" value="5" />
                <input type="checkbox" checked="checked" value="6" />
                <input type="checkbox" checked="checked" value="7" />
                <input type="checkbox" checked="checked" value="8" />
    </div>

and check the selected or unselected elements using follwwing jquery code snippet. .size() will return the no of checked item and you can get the value of selected items by .val().
//Write your code when Document is loaded or some element click
 $(document).ready(function() {
                $("#testChk").click(function() {
                    alert($("#testCheck :checked").size());
                    //function to print the value of each checked checkboxes
                    $("#testCheck :checked").each(function() {
                        alert("value = " + $(this).val());
                });

for more help follow these links:
How can I know which radio button is selected via jQuery?
have a look on jquery selector. you should watch bottom itms :password, :reset etc that you need to use.
http://api.jquery.com/category/selectors/
http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html
Handling Checkboxes, Radio Buttons and Select Options in jQuery
Hope this help you little bit...


text:
Q: Even after fetching float value from Firebase, Toast displays value null DatabaseReference dr1 = FirebaseDatabase.getInstance().getReference().child("users");
    dr1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot ds : dataSnapshot.getChildren())
            {
                if(userID.equals(ds.child("userIDOriginal").getValue().toString()))
                {
                    monthlyBudget = Float.parseFloat(ds.child("userMonthlyBudget").getValue().toString());
                }
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
    Toast.makeText(getActivity(),""+monthlyBudget,Toast.LENGTH_LONG).show();

This is code fetching float value from firebase database,Toast shows correct value when placed inside, but shows null value when placed outside the ValueEventListener.Can anyone suggest solution? Thanks in advance.


text:
Q: How to get the height in pixels in pure javascript? I have got a forum with the following HTML structure:

Contents

Contents

Contents

Basically, I need to set the height of #main to the height of the document minus the height of the other 2 elements. The problem is I have to do it without jquery. I googled the problem and found the clientHeight method, but it returns the height as a number, while I need it as pixels.
So, the question is:

Is there any way to get the height in pixels in pure javascript?

A: The property .clientHeight will return a number (the height in pixels).
In your case, below is the code to reset the height of div#main. Note that we're adding a "px" at the end for .style.height to work:

document.getElementById('main').style.height = parseInt(window.innerHeight) -
document.getElementById('header').clientHeight +
document.getElementById('footer').clientHeight + "px";

CONTENT

CONTENT

CONTENT


text:
Q: Images in list do not float correctly I'm trying to make a list of images, 2 per row.
The uneven rows (1, 3, 5, etc.) should have a small image first, and a wide one second. The even rows (2, 4, 6, 8, etc.) should have the wide image first and the smaller one second.
I'm now at row 3, and I cannot get the small image to the left for whatever reason. As you can see in the image below it floats to the right.
My code is very basic, and Dreamweaver displays it correctly in its Split function.
HTML:

CSS
#portfolio-screen       {margin-top: 8px; width: 768px; height: 602px; background-color:#37322d; overflow: auto;}
#portfolio-screen li    {margin-top: 8px; margin-left: 8px; float: left;}

For some reason it is not allowed to post images, so I have supplied a link to one: http://oi51.tinypic.com/b63vkk.jpg

A: First, you have a broken  in there.
Secondly, make sure your unorder list has Margin and padding of 0
Lastly, mess with JSfiddle:
http://jsfiddle.net/Riskbreaker/NT4DS/10/
Instead of floats try inline-block

A: You can try something like this - the CSS height for the images could be removed for your size needs.
HTML

CSS:
img {
 height:20px;
}
.imgSmall {
 width:228px;
}
.imgLarge {
 width: 500px;
}
#portfolio-screen {
 margin: 0;
 padding: 0;
 width: 768px;
 height: 602px;
 background-color:#37322d;
}
#portfolio-screen ul {
 margin: 0;
 padding: 15px;
 width: 768px;
}
#portfolio-screen li {
 margin-top: 8px;
 margin-left: 8px;
 display: inline-block;
}
#portfolio-screen li:nth-child(odd) {
 margin:0;
}

JS Fiddle: http://jsfiddle.net/5qREV/


text:
Q: How to render a building using Three.js extrusion method? I'm trying to render a 3D building procedurally using Three.js. One of the ways this is done is by extruding a square/rectangle. See Fig. 19 here: http://www.gamesitb.com/SurveyProcedural.pdf
I've looked at the Three.js documentation for the ExtrudeGeometry API, but its usage isn't very clear. Have searched the web and this forum for possible examples/code snippets - in vain! Any pointers on this would be helpful. Thanks.

A: The first place to look is in this example that is provided in the THREE.js zip.
examples/webgl_geometry_shapes.html
The next bits are for example purposes.
The key points are that you create a series of Vector2 (lines 144-165 in the file I've mentioned) that define the corners of the building.
var californiaPts = [];
californiaPts.push( new THREE.Vector2 ( 610, 320 ) );
californiaPts.push( new THREE.Vector2 ( 450, 300 ) );
californiaPts.push( new THREE.Vector2 ( 392, 392 ) );
californiaPts.push( new THREE.Vector2 ( 266, 438 ) );

The next step is to convert those lines to a THREE.Shape (line 167)
var californiaShape = new THREE.Shape( californiaPts );

Then you want to extrude the shape.
var extrudeSettings = { amount: 20 }; // bevelSegments: 2, steps: 2 , bevelSegments: 5, bevelSize: 8, bevelThickness:5

var geometry = californiaShape.extrude(extrudeSettings);

At this point you'd have an extrusion of the shape that is a geometry object so it can be turned into a mesh and you can apply a material to it.


text:
Q: Differences and relations between CFTs defined on the complex plane and CFTs defined on the torus? What are the differences and relations between CFTs defined on the complex plane and CFTs defined on the torus? Are they supposed to be the same CFTs?
I think they should have the same spectra of operators and OPE coefficients. But what about the correlation functions? If I consider the CFTs on the cylinder, then the correlation functions on the cylinder can be obtained from the correlations from the complex plane by a conformal transformation, but what about correlation functions on the torus?
I think another question is how does the topology of the spacetime affect the theory?
Am I missing something?

A: A CFT on any surface must have an associative OPE. This constrains both the spectrum and the OPE coefficients. This condition is enough for the CFT to be consistent on the plane, but not on the torus. On the torus you have the extra condition of modular invariance of the one-point function (which implies modular invariance of the partition function).
So any CFT that exists on the torus also exists on the plane, but there are CFTs that exist on the plane and not on the torus. A trivial example is a CFT whose only primary field is the identity field, which exists on the plane for any value of the central charge $c$, but is modular invariant only if $c=0$.
The plane and the torus are not related by conformal transformations. Actually, not all toruses are conformally related to one another. (For two toruses to be conformally related, they need to have the same value of a complex parameter called the modulus.) So in principle there might be CFTs that exist on some but not all toruses, although I do not know any example.


text:
Q: What should I do to set a variable in function by user in __name__ == "__main__" in python? my_list = [1,2,3,4,3,5]
cheak = []
def duplicate(any_list):
    for things in any_list:
        if things not in cheak:
            cheak.append(things)
        else:
             pass
    return cheak

if __name__ == "__main__":
    duplicate(my_list)

I want the user to tell which list to remove duplicate, how can I do with this.

A: if __name__ == "__main__":
    my_list = [1,2,3,4,3,5]
    duplicate(my_list)

You have to assign my_list before passing it to duplicate. Outside the loop.

A: IIUC you need:
def duplicate(any_list):
    cheak = []
    for things in any_list:
        if things not in cheak:
            cheak.append(things)
        else:
             pass
    return cheak

if __name__ == "__main__":
    my_list = [1,2,3,4,3,5]
    duplicate(my_list)

A: The following code is what you need:
def duplicate(any_list):
    '''remove duplicates from list'''

    cheak = []
    for things in any_list:
        if things not in cheak:
            cheak.append(things)
    return cheak

def mainFun():
    my_list = [1,2,3,4,3,5]
    print(duplicate(my_list))

if __name__ == "__main__":
    mainFun()

Output:
[1, 2, 3, 4, 5]

Note also that the else condition is not required.
A faster implementation and more Pythonic for what you want to do:
def duplicate(any_alist):
    '''remove duplicates from list'''

    return list(set(any_alist))

A: I have written two types of solution.

*

*The duplicate function uses a local variable (func_loc_cheak)(in function scope) and return the content of this local list.

*The duplicate_glob function uses a global variable (cheak_global) and it doesn't return anything because you can use this global variable without variable assignment.
I have added several print to see the behaviors and differences between the functions.
Code:
cheak_global = []

def duplicate_glob(any_list):
    for things in any_list:
        if things not in cheak_global:
            cheak_global.append(things)

def duplicate(any_list):
    func_loc_cheak = []
    for things in any_list:
        if things not in func_loc_cheak:
            func_loc_cheak.append(things)
    return func_loc_cheak

if __name__ == "__main__":
    # Test lists.
    my_list = [1, 2, 3, 4, 3, 5]
    my_other_list = [8, 9, 0]

    result = duplicate(my_list)
    print("After first function call: {}".format(result))

    result = duplicate(my_other_list)
    print("After second function call: {}".format(result))

    print("Content of 'cheak_global' before function call: {}".format(cheak_global))

    duplicate_glob(my_list)
    print("Content of 'cheak_global' after first function call: {}".format(cheak_global))

    duplicate_glob(my_other_list)
    print("Content of 'cheak_global' after second function call: {}".format(cheak_global))

Output:
>>> python3 test.py
After first function call: [1, 2, 3, 4, 5]
After second function call: [8, 9, 0]
Content of 'cheak_global' before function call: []
Content of 'cheak_global' after first function call: [1, 2, 3, 4, 5]
Content of 'cheak_global' after second function call: [1, 2, 3, 4, 5, 8, 9, 0]


text:
Q: How to disable default Callout view from mapkit? I need to disable default callout view from map kit, I'm using customised callout view and now Its getting both view when i click on the pin icon.
 func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView){
    let customView = (NSBundle.mainBundle().loadNibNamed("CustomCalloutView", owner: self, options: nil))[0] as! CustomCalloutView;

    let button = UIButton(frame: CGRectMake(0, 0, 100, 50))
    button.addTarget(self, action: Selector("buttonPressed:"), forControlEvents: .TouchUpInside)

    button.userInteractionEnabled = true
    button.backgroundColor = UIColor.greenColor()

    customView.addSubview(button) // assuming you're in a view controller

    self.view.addSubview(customView)
}

A: Finally I've got solution.
just comment out the "Title" and "Description" from MKAnnotation object custom class.


text:
Q: Intermediate Text in Combinatorics? I'm currently attending a somewhat disorganized seminar on combinatorics that follows no textbook. So far we have covered the orbit-stabilizer theorem, some recursion, and we're heading into the Möbius inversion formula.
Can anyone suggest a text that approaches combinatorics at this level for a 2nd-3rd year undergrad who already knows some algebra and the more basic combinatorics like combinations, permutations, stars-and-bars, generating functions? Most introductory combinatorics books I've found are more suited to a discrete math class and cover stuff which I already know. I'm looking for something to supplement this lecture. Thank you.

A: I can't say I can predict what direction your seminar will head in, but an amazing one-stop-shop for combinatorics is Richard Stanley's Enumerative Combinatorics (both volumes). You will learn a tremendous amount if you get through both of these (and the revised version of volume 1 is currently available online!). In particular Volume I has a thorough discussion of Möbius inversion.

A: I did a reading course in Combinatorics while a PhD student, and we used van Lint and Wilson which I thought was very hard, but very good.  You don't need any more background than you already have, and you will learn a ton from this text.
It's definitely not as well-known as the other suggested texts, but it many ways it's superior.  (Although Concrete Mathematics is a better book overall for its sheer beauty.)

A: I think Stanley's Enumerative Combinatorics is not an "intermediate" level book, it's the canonical advanced book on combinatorics.
I'd recommend Aigner's  "A Course on Enumeration" (from Springer's GTM series)
for a lighter level (but certainly beyond apples and oranges) go A Walk Through Combinatorics (Miklos Bona) or Combinatorics: Topics, Techcniques and Algorithms (Cameron)

A: If you read French, you must read Analyse Combinatoire of L. Comtet at PUF edition. It's two short books full of fascinating materials.

A: How about Concrete Mathematics?


text:
Q: BiquadFilterNode (Web Audio API) keeps increasing its volume gradually I have an issue with BiquadFilterNode (Web Audio API).
I made a simple audio program that repeats noise in every one bar.
The issue is when I connect a BiquadFilterNode to the noise, its volume keeps increasing gradually.
Could anyone kindly point out why the gradual volume increase is happening?
Many thanks!
Webpage running the program:
https://abirdwhale.github.io/javascript-web-audio-api-sketches/sequencers/test-biquadfilter-issue/
GitHub repository to recreate the issue:
https://github.com/abirdwhale/javascript-web-audio-api-sketches/tree/main/sequencers/test-biquadfilter-issue
HTML:
<!-- <!DOCTYPE html> -->
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="css/app.css">
</head>
<body>
    <button id="play-button">Play/Pause</button>
    <script type="module" src="js/app.js"></script>
</body>
</html>

JavaScript:
"use strict";

// for cross browser
const AudioContext = window.AudioContext || window.webkitaudioCtx;
const audioCtx = new AudioContext();

let futureTickTime = audioCtx.currentTime;
let counter = 1;
let tempo = 120;
let secondsPerBeat = 60 / tempo;
let counterTimeValue = (secondsPerBeat / 4); // 16th note

// Noise volume
let noiseVolume = audioCtx.createGain();
noiseVolume.gain.value = 0.001; //Noise volume before send to FX

// Noise parameters
let noiseDuration = 1.; //Duration of Noise
let bandHz = 100;

function playNoise(time, playing) {
  if (playing) {
    const bufferSize = audioCtx.sampleRate * noiseDuration; // set the time of the note
    const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate); // create an empty buffer
    const data = buffer.getChannelData(0); // get data

    // fill the buffer with noise
    for (let i = 0; i < bufferSize; i++) {
      data[i] = Math.random() * 2 - 1;
    }

    // create a buffer source for our created data
    const noise = audioCtx.createBufferSource();
    noise.buffer = buffer;

    const bandpass = audioCtx.createBiquadFilter();
    bandpass.type = 'bandpass';
    bandpass.frequency.value = bandHz;

    // connect our graph
    noise.connect(noiseVolume);
    // 1. without a bandpass filter
    // noiseVolume.connect(audioCtx.destination);
    // 2. with a bandpass filter
    noiseVolume.connect(bandpass).connect(audioCtx.destination);
    if (counter === 1) {
      noise.start(time);
      // noise.stop(time + noiseDuration);
    }
  }
}

const lookahead = 25.0; // How frequently to call scheduling function (in milliseconds)
const scheduleAheadTime = 0.1; // How far ahead to schedule audio (sec)

function playTick() {
  console.log("This 16th note is: " + counter);
  console.log("16th is: " + counterTimeValue);
  console.log("futureTickTime: " + futureTickTime);
  console.log("Web Audio Time: " + audioCtx.currentTime);
  counter += 1;
  futureTickTime += counterTimeValue;
  console.log("futureTickTime: " + futureTickTime);

  if (counter > 16) {
    counter = 1;
  }
}

function scheduler() {
  if (futureTickTime < audioCtx.currentTime + scheduleAheadTime) {
    playNoise(futureTickTime, true);
    playTick();
  }
  window.setTimeout(scheduler, lookahead);
}

scheduler();

document.getElementById("play-button").addEventListener("click", function () {

  if (audioCtx.state !== "running") {
    console.log("it's not running well");
    audioCtx.resume();
  } else {
    console.log("it's running");
    audioCtx.suspend();
    console.log(audioCtx.state);
  }
});

A: OK, taking BiquadFilterNode setup out of the playNoise function solved the issue. I don't understand why placing the setup inside the function was causing the issue, though.
Fixed JavaScript:
"use strict";

// for cross browser
const AudioContext = window.AudioContext || window.webkitaudioCtx;
const audioCtx = new AudioContext();

let futureTickTime = audioCtx.currentTime;
let counter = 1;
let tempo = 120;
let secondsPerBeat = 60 / tempo;
let counterTimeValue = (secondsPerBeat / 4); // 16th note

// Noise volume
let noiseVolume = audioCtx.createGain();
noiseVolume.gain.value = 0.1; //Noise volume before send to FX

// Noise parameters
let noiseDuration = 1.; //Duration of Noise
let bandHz = 100;

// Biquad filter setup
const bandpass = audioCtx.createBiquadFilter();
bandpass.type = 'bandpass';
bandpass.frequency.value = bandHz;

function playNoise(time, playing) {
  if (playing) {
    const bufferSize = audioCtx.sampleRate * noiseDuration; // set the time of the note
    const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate); // create an empty buffer
    const data = buffer.getChannelData(0); // get data

    // fill the buffer with noise
    for (let i = 0; i < bufferSize; i++) {
      data[i] = Math.random() * 2 - 1;
    }

    // create a buffer source for our created data
    const noise = audioCtx.createBufferSource();
    noise.buffer = buffer;

    // connect our graph
    noise.connect(noiseVolume);
    // 1. without a bandpass filter
    // noiseVolume.connect(audioCtx.destination);
    // 2. with a bandpass filter
    noiseVolume.connect(bandpass).connect(audioCtx.destination);
    if (counter === 1) {
      // bandpass.gain.setValueAtTime(-40, time);
      noise.start(time);
      // noise.stop(time + noiseDuration);
    }
  }
}

const lookahead = 25.0; // How frequently to call scheduling function (in milliseconds)
const scheduleAheadTime = 0.1; // How far ahead to schedule audio (sec)

function playTick() {
  console.log("This 16th note is: " + counter);
  console.log("16th is: " + counterTimeValue);
  console.log("futureTickTime: " + futureTickTime);
  console.log("Web Audio Time: " + audioCtx.currentTime);
  counter += 1;
  futureTickTime += counterTimeValue;
  console.log("futureTickTime: " + futureTickTime);

  if (counter > 16) {
    counter = 1;
  }
}

function scheduler() {
  if (futureTickTime < audioCtx.currentTime + scheduleAheadTime) {
    playNoise(futureTickTime, true);
    playTick();
  }
  window.setTimeout(scheduler, lookahead);
}

scheduler();

document.getElementById("play-button").addEventListener("click", function () {

  if (audioCtx.state !== "running") {
    console.log("it's not running well");
    audioCtx.resume();
  } else {
    console.log("it's running");
    audioCtx.suspend();
    console.log(audioCtx.state);
  }
});


text:
Q: how to visualise and delete trailing newline at the end of file in vim\nvim Sometimes I need to edit files which should not end with a newline.
However vim\nvim by default do not visualise in any way the newline character at the end of file. Therefore I am not able to:

*

*visually confirm if the file has a newline character at the end or not

*remove that character

Are there any setting which would allow me to see the tailing newline character and edit it in the same way as any other characters?
For example, after create 2 files as follows:
echo test > file-with-newline
echo -n test > file-without-newline

opening first one with nvim file-with-newline shows:
test
~
~
file-with-newline

opening second one with nvim file-without-newline shows:
test
~
~
file-without-newline

Navigating with the cursor to the end of line in either case yields the same result (the cursor stops after last visible character: t). There is no way to tell if the newline is there or not, let alone remove it using familiar commands used to remove ordinary characters (or newlines within the file).

A: You can enable the option :help 'list':
:set list

to show that "newline character" as a $ at the end of the line (among other things):

Note, however, that the option doesn't make the character "editable" in any way.

A:
if the file has a newline character at the end or not

:set eol?
endofline

remove that character

:set noeol nofixeol
:update


text:
Q: How to style span radio buttons with CSS without images I have tried to style these radio buttons with css but i can not figure out why it will not style. I am trying to have a 30px by 30px radio button with a 3px blue border and the inside of the radio button white with a black dot that is the checked one. Any help would be appreciated.

           Motorhome

 <input type="radio" name="RVCategory" value="Motorhome" checked="checked">

           Trailer

 <input type="radio" name="RVCategory" value="Trailer">

A: Hint 1, always include enough code to replicate your problem. Once finding the fiddle it was easily fixed.
Point 1 : Use the label tag  and use it corectly. You are using a span where you should be using label. To associate label with a form element use the for attribute with an Id from the form element. It is the label that gives the user something to click on here.
Point 2: Ordering is important with CSS selectors. If your selector is input + label the label tag must come after the input
Point 3: Learn the realtionship with position:releative and position:absolute
Finaly, the solution:

.wpcf7-form-control-wrap.RVCategory {
  max-width: 400px;
  margin: 94px auto 0 auto;
}

.wpcf7-list-item label {
  position: relative;
}

.wpcf7-list-item-label,
.wpcf7-list-item last {
  font-size: 20px;
}

.wpcf7-form-control-wrap.RVCategory input[type="radio"] {
  position: absolute;
  opacity: 0;
  -moz-opacity: 0;
  -webkit-opacity: 0;
  -o-opacity: 0;
}

.wpcf7-form-control-wrap.RVCategory input[type="radio"]+label:before {
  content: "";
  /*Note inline-block*/
  display: inline-block;
  top: 2px;
  height: 14px;
  width: 14px;
  background: white;
  border: 1px solid gray;
  box-shadow: inset 0px 0px 0px 2px white;
  -webkit-box-shadow: inset 0px 0px 0px 2px white;
  -moz-box-shadow: inset 0px 0px 0px 2px white;
  -o-box-shadow: inset 0px 0px 0px 2px white;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  -o-border-radius: 8px;
}

.wpcf7-form-control-wrap.RVCategory input[type="radio"]:checked+label:before {
  background: #ef8700;
}

            <input type="radio" name="RVCategory" value="Motorhome" checked="checked" id="rdoMotorHome">

            Motorhome

            <input type="radio" name="RVCategory" value="Trailer" id="rdoTrailer">
            Trailer

A: You can change the size but you can't add a border around a radio button with CSS unless you want a square border - and in that case it would be the element around the button, not styled on the button itself. To change the size of the button, your class needs to go with the input tag. Put your class where the inline style is in the example below.
 <input type="radio" name="RVCategory" value="Motorhome" checked="checked" style="width:30px;height:30px;">

A: Below is the code for your reference, this will help you.

[type="radio"] {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px; margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}

label {
  display: block;
  cursor: pointer;
  line-height: 2;
  font-size: 20px;
}

[type="radio"] + span:before {
  content: '';
  display: inline-block;
  width: 15px;
  height: 15px;
  vertical-align: -0.25em;
  border-radius: 10px;
  border: 3px solid #fff;
  box-shadow: 0 0 0 3px #000;
  margin-right: 0.75em;
  transition: 0.5s ease all;
}

[type="radio"]:checked + span:before {
  background: black;
  box-shadow: 0 0 0 0.25em #000;
}

<input type="radio" value="Motorhome" name="Test" id="Motorhome"> Motorhome

<input type="radio" value="Trailer" name="Test" id="Trailer"> Trailer


text:
Q: How to GetResponse from site after loading all html content? Sorry for my English. I try to get HTML content from this page https://www.scoreboard.com/game/berankis-ricardas-king-kevin-2018/WC4oWAqE/#h2h;all. In result my code return HTML which doesn't have time to loading.
static string GetHtml(string site)
    {
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(site);
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        using (StreamReader stream = new StreamReader(
            resp.GetResponseStream(), Encoding.UTF8))
        {
            return stream.ReadToEnd();
        }
    }

For example I want to get innerHTML from id="tab-match-head-2-head", because this block loads after few second, I can't get content from there.
How can I wait while all content will be loaded and then GetResponse this? It's like a window.onload in js but from other site. I really have no idea how to do this, please help.

A: If I get your question correctly, There is no need for headless browser.
Juts hit F12 in your browser and see the network activity
var url = "https://d.scoreboard.com/x/feed/d_hh_WC4oWAqE_en-usa_1"; //<===
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Headers.Add("x-fsign","SW9D1eZo"); //<===
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

using (StreamReader stream = new StreamReader(
    resp.GetResponseStream(), Encoding.UTF8))
{
    return stream.ReadToEnd();
}


text:
Q: Unsupported major.minor version Exception for sonar-scanner I am trying to analyze my source code using SonarQube. I am trying to use sonar-scanner as my tool to run analysis from command line. I followed the guidelines presented in this documentation article: http://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner
When I try to test the installation by running sonar-scanner -h I am getting the following error:
➜  ~ sonar-scanner -h
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/sonarsource/scanner/cli/Main : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

From the error it looks like its not finding the right version for JAVA/JRE to run the cli tool. My understanding was that the tool should work with any Java 1.7+ version. I am using Oracle JDK 1.7.0_55. I also tried using OpenJDK 1.8 but I am still getting the same error. I also checked my JAVA_HOME variable is set to the right JDK directory.
Any help in the right direction is appreciated.

A: this have been already answered at length here : Unsupported major.minor version 52.0 and here : How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
the rationale is that you're trying to execute Sonar on a Java 7 or lower when the sonar classes have been compiled for java 8 thus triggering this error.

A: After Struggling with this for a while, I found the cause of the problem. The CLI is looking at your JAVA_HOME path variable to figure out the version of Java it needs to use. even tough the default java and javac commands were pointing to JDK 8, setting the JAVA_HOME environment variable to your JDK 8 root directory solved the issue.
Hope this helps other folks facing similar issue.


text:
Q: Redirect visitors to another page if accessed directly using PHP I have a register.php page, which allows visitors to register to become certain users. If they meet all requirements set by the form validation, they will be redirect to another page, called thankyou.php page.
My question is if anyone tries to visit the thankyou.php page directly without going through/ from the register.php page, then it should redirect them back to the register.php page again.
Note: I know how to use the $_session = array(); for the logged-in users, and header() function very well. Once again, the question here requires some kind of research on how to restrict visitors from accessing thankyou.php directly (because visitors have not become users of the website yet).
Please don't guide me in jquery or javascript or any other languages. I need your help in php.
Thank you!

A: In register.php you can set a key in the $_SESSION. For example
$_SESSION['justRegistered'] = true;

And the check for it in thankyou.php
if (!empty($_SESSION['justRegistered'])) {
    unset($_SESSION['justRegistered']);
    // Say Thank You
} else {
    header('Location: ... register.php');
}

A: You have to check first if the $_SESSION variable associated with the correct redirect to thankyou.php is setted.
After that, you have to check if the user $_SERVER['HTTP_REFERER'] meets the requirements, that is if $_SERVER['HTTP_REFERER'] (that contains the referral url) ends with register.php and the domain is your domain.
I suggest you to do something like (I'm assuming you defined a constant YOUR_HOST and used a session variable ok. Change it with yours as well):
if(empty($_SESSION['ok']) || empty($_SERVER['HTTP_REFERER'])) {
    die(header('Location /register.php'));
}

$url = parse_url($_SERVER['HTTP_REFERER']);
if($url['host'] !== YOUR_HOST || $url['path'] !== 'register.php') {
    die(header('Location /register.php'));
}
// else show the thankyou page content

A: you can check $_SERVER['HTTP_REFERRER'] in your thankyou.php .
if($_SERVER['HTTP_REFERRER'] != 'your referrer page'){
  header('location: yourtarget.php');
  die();
}

also using session is better way .

A: One simple way for acheiving what you want is to send a session variable from register.php to thankyou.php. Sessions are a good way for permissions.
In register.php -> $_SESSION['myvariable'] = 'something'. then in thankyou.php you'll have access to the session variable and if the variable is set then you can stay in that page or do whatever you'll like. Keep in mind that you'll have to resume the session with session_start() in each page.


text:
Q: Apply svg transform matrix to text font-size I have an svg text element with the transform attribute. I need to apply the transform to the text. I was able to get the correctly transformed x,y values of the element by applying the matrix to the coordinates. But there's no way I can apply the matrix to a single value (i.e. text size)? I tried using the size twice for applying the transform but that does not produce right result.
So how to apply the svg transform matrix to text font-size?
I am using Inkscape inkex.transform modules apply_to_point function.
Update: Here is the Inkscape code snippet:
selections = self.svg.selection
for s in selections:
    transStr = s.get('transform')
    if(transStr is not None):
        tr = inkex.transform.Transform(transStr)
        x = s.get('x')
        y = s.get('y')
        if(x is not None and y is not None):
            # apply transform to coordinates
            co = tr.apply_to_point((x, y))
            s.pop('transform')
            s.set('x', str(co[0]))
            s.set('y', str(co[1]))
            stStr = s.get('style')
            if(stStr is not None):
                style = inkex.styles.Style.parse_str(stStr)
                sizeStr = style.get('font-size')
                if(sizeStr is not None):
                    m = re.match('([0-9.]+)(.*)', sizeStr)
                    if(len(m.groups()) > 1):
                        size = m[1]
                        # apply transform to size
                        # but this returns a tuple of 2
                        # we need only one.
                        # And even taking one element from tuple
                        # this doesn't work.
                        style['font-size'] = str(tr.apply_to_point((size, size)))
                s.set('style', style)


text:
Q: When Importing packages must the file name only be one word? When I'm importing packages/custom modules the import statement only accepts single word input.  I looked up the Packages info in the Python Docs and the example there only has one word imports. Are multi-word imports possible?
This works:
import Histogram

But this doesn't:
import File existence check

A: You could use the builtin __import__, but it'd probably be better to not have spaces in the name.
package = __import__("Name with spaces")

A: Don't use space when you want to name something. Use Camelcase like FileExistenceCheck or go with File_existence_check. I don't know if it would work just seen from the syntax but anyway you should not do it!


text:
Q: How do you print raw UTF-8 characters from their numbers? Say I wanted to print a ÿ (latin small y with diaeresis) from its Unicode/UTF-8 number of U+00FF or hex of c3 bf. How can I do that in PHP?
The reason is that I need to be able to create certain UTF-8 Characters is for testing in my regex and string functions. However, since I have less than 200 keys on my keyboard I can't type them - and since many times I am stuck in an ASCII only world - I need to be able to create them bases solely off of their ASCII safe, UTF-8 character code.
Note: In order for it show correctly in a browser I know that the first step is
header('Content-Type: text/html; charset=utf-8');

A: well you have everything you need.
Hex values being recognized in double-quoted strings as well
echo "\xc3\xbf";

A: Solution 1 with a small pack function
<?php

function chr_utf8($n,$f='C*'){
return $n<(1<<7)?chr($n):($n<1<<11?pack($f,192|$n>>6,1<<7|191&$n):
($n<(1<<16)?pack($f,224|$n>>12,1<<7|63&$n>>6,1<<7|63&$n):
($n<(1<<20|1<<16)?pack($f,240|$n>>18,1<<7|63&$n>>12,1<<7|63&$n>>6,1<<7|63&$n):'')));
}

echo chr_utf8(9405).chr_utf8(9402).chr_utf8(9409).chr_utf8(9409).chr_utf8(9412);

//Output ⒽⒺⓁⓁⓄ

Check it in https://eval.in/748062 …
Solution 2 with json_decode
<?php

$utf8_char='["';
for($number=0;$number<55296;$number++)
$utf8_char.='\u'.substr('000'.strtoupper(dechex($number)),-4).'","';
$utf8_char=json_decode(substr($utf8_char,0,-2).']');

echo $utf8_char[9405].$utf8_char[9402].$utf8_char[9409].$utf8_char[9409].$utf8_char[9412];

//Output ⒽⒺⓁⓁⓄ


text:
Q: JSP page Reload In my spring mvc application,I am facing a problem of page reloading on every request.Is there any way to restrict that.To be more specific,When I return the name of index.jsp page from controller it will obviously reload the page.How Can I restrict that thing in the index.jsp page.Suppose some part of the page is required to interact with Database and it should be shown on the same index.jsp page as well.How I can achieve this requirement without reloading the index.jsp page completely.Could you please provide me some example for that.

A: You can use Filter for that. I am not providing any code here, just try to explain the concept.
Filters have a wide array of uses; the Servlet 2.3 specification suggests the following uses:

*

*authentication filters

*logging and auditing filters

*image conversion filters

*data compression filters

*encryption filters

*tokenizing filters

*filters that trigger resource access events

*XSL/T filters that transform XML content

*MIME-type chain filters

Use a Filter when you want to filter and/or modify requests based on specific conditions.
Use a Servlet when you want to control, preprocess and/or postprocess requests.
Filter are best suited for authorization, because it can be configured to run for all pages of a site. So you only need one filter to protect all your pages.
Useful Links:

*

*filter tutorial

*filter in detail

*referred answer

*Oracle tutorial on Filter

A: sorry if i missunderstanding you!
i don't know what do you want to do but i can imagine the following solution.
first direct call to jsp should check a session value, if not exists, redirect from jsp to servlet, in the servlet do what you wand and finally put this session value, and redirect back to jsp.
a good concept depends on what you want to do exactly. You can manage this issue using a PhaseListener or a Filter. but if you just want to manage this one redirect, then no need of Filter or PhaseListener


text:
Q: How To select from combobox with selenium c#? How to change default value dropdown or combobox list to others value?
i want to change allshow to onlyactive

<form method="post" action="">

First Name:<input type="text" size="12" maxlength="12" name="Fname">

Last Name:<input type="text" size="12" maxlength="36" name="Lname">

Gender:

Male:<input type="radio" value="Male" name="gender">

Female:<input type="radio" value="Female" name="gender">

Favorite Food:

Steak:<input type="checkbox" value="Steak" name="food[]">

Pizza:<input type="checkbox" value="Pizza" name="food[]">

Chicken:<input type="checkbox" value="Chicken" name="food[]">

            Status :
            <select class="uk-select js-select2 select2-hidden-accessible" name="search[active]" data-select2-id="7" tabindex="-1" aria-hidden="true">
                    <option value="" data-select2-id="9">AllShow</option>
                        <option value="1" data-select2-id="17">onlyactive</option>
                                    <option value="2" data-select2-id="18">onlyinactive</option>
            </select>
            AllShow

</form>

IWebDriver driver = new FirefoxDriver(service);
IWebElement comboBox = driver.FindElement(By.Name("search[active]"));
comboBox.Click();

use this code:
    // select the drop down list
    var education = driver.FindElement(By.Name("education"));
    //create select element object
    var selectElement = new SelectElement(education);

but error

The type or namespace name 'SelectElement' could not be found (are you
  missing a using directive or an assembly reference?)

Selenium.WebDriver.3.141.0

A: I believe that you're missing assembly reference, SelectElement class is available at namespace OpenQA.Selenium.Support.UI.
Nuget:

https://www.nuget.org/packages/Selenium.Support/3.141.0

Then it should works.
using OpenQA.Selenium.Support.UI;

var comboBox = driver.FindElement(By.Name("search[active]"));
new SelectElement(comboBox).SelectByText("onlyactive");

EDIT:
SelectByText providing the text of the option to be selected. If your combobox doesn't contains specified text value, then it will throw NoSuchElementException.


text:
Q: Generate event on click of outer div in backbone.js How to generate click event on only outer div but not on click of its children
var TodoView = Backbone.View.extend({
    template: _.template(''),
    events: {
        'click #main-content li': 'AccordionChangingIcons', //For user li click event
    },
});

This is HTML code.

title1-goes-here

   Content goes here1 check here

A: Backbone uses event delegation to attach event listeners which is in some situations a bit more complicated to work with than whith events bound directly.
Event delegation in both jQuery and Zepto (you didn't specify if you use either one in your Backbone app, but I assume you do) works like this:
$( some_element ).on( event, selector, function(){} )

In Backbone some_element is views el element reference, event and selector are, in your example, click and #main-content li. So the click event listener is attached to view's el, and when you click anywhere within your view the event is fired, then jQuery/Zepto checks if the element clicked matches selector passed. This of course makes it impossible to listen to events on elements outside view's el element.
Now to the point: events passed to callback functions in these libraries are normalized, but include a reference to the original (browser's native) event object. You can use both to check what was really clicked on and if you want to take action.
In your example you only want to proceed if event.currentTarget === event.originalEvent.target. currentTarget is in the libraries' normalized event object and always refers to your li. originalEvent.target is the browser's native event target and refers to the element which was actually clicked on, which will refer to the deepest nested node in the tree beginning at li. So if both point to li, then the user has clicked on it, a not any of its children.
Fiddle: http://jsfiddle.net/ZAbpD/1/

A: I think the problem can be solved like this:
How do I detect a click outside an element?
Either by creating a separate view for the outer area or by attaching an outer-event via jquery:
var TodoView = Backbone.View.extend({
    template: _.template(''),
    events: {
        'click #main-content li': 'AccordionChangingIcons', //For user li click event
    },
    initialize: function() {
        $("html").on("click", this.outsideClick);
    },
    outsideClick: function() {
        //handle outside click
    },
    AccordionChangingIcons: function(event) {
        event.stopPropagation();
    }
});


text:
Q: Parsing Command Line Options I have written some code, which prints a command line help:
int main(int argc, char **argv)

    printf("$ ./porfolio6 --help \n"
      "Usage: ./portfolio6 options [FILENAME]\n"

       " -h --help Dsiplay this usage information.\n"
       " -n --num Display my student number.\n"
       " -c --chars Print number of characters in FILENAME.\n"
       " -w --words Print number of words in FILENAME.\n"
       " -l --lines Print number of lines in FILENAME.\n"
       " -f --file FILENAME Read from file.\n");
}

I would like to know how to make these options actually work. Currently they just printout without doing what the option requires.
@Apoorv
@Carl Norum
My updated version of the code is like this but I am still having a few problems with getting everything to show up on the terminal as options
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

void print_usage() {
 printf("Usage: ./portfolio6 options [FILENAME] \n");
}

int main(int arg, char *argc[]) {

int opt =0;
int help = -1, num = -1, chars = -1, words = -1, lines = -1, file = -1;

static struct option long_options[] = {

{"help", required_argument, 0, 'h' },
{"num", required_argument, 0, 'n' },
{"chars", required_argument, 0, 'c' },
{"words", required_argument, 0, 'w' },
{"lines", required_argument, 0, 'l' },
{"file", required_argument, 0, 'f' },
};

 int long_index =0;
while((opt= getopt_long(argc, argv,"hncwl:f:",
             long_options, &long_index )) != -1 {

 switch (opt) {
 case 'h' : /* -h or --h */
 help = 1;
 break;

 case 'n' : /* -n or --n */
 num = 1;
 break;

 case 'c' : /* -c or --c */
 chars = 1;
 break;

 case 'w' : /* -w or --w */
 words = 1;
 break;

 case 'l' : /* -l or --l */
 lines = 1;
 break;

 case 'f' : /* -f or --f */
 file = 1;
 break;
 }
}

A: You're looking for getopt_long(3). There's an example in that man page that covers everything you need to know.


text:
Q: Container match children AND grandchildren width I have a container that has many children and grandchildren. My goal is to have the container's width match it's children/grandchildren. (CSS at the bottom)
The easy version looks like this, a parent with some children and it grows/shrinks dependent on the children: http://jsfiddle.net/6qWg6/5/

child 1

child 2

child 3

child 4

The difficulty arises when I add grandchildren: http://jsfiddle.net/6qWg6/4/

child 1

child 2

child 3

child 4

child 1

child 2

child 3

child 4

child 5

child 7

child 8

child 9

child 10

When I add grandchildren the container goes to a width of 100%, which I don't want. How can I add grandchildren while still having my containers width match it's descendants?
#container {
    float: left;
    border: 1px solid blue;
    display: inline-block;
    padding: 5px;
}

#child_container {
    float: left;
    border: 1px solid red;
    padding: 5px;
}

.child {
    width: 100px;
    float: left;
    border: 1px solid black;
}

A: There you go, I updated your fiddle
http://jsfiddle.net/6qWg6/7/
CSS
#container {
    float: left;
    border: 1px solid blue;
    display: inline;
    padding: 5px;
}

#child_container {
    display: inline;
}

.child {
    width: 100px;
    float: left;
    border: 1px solid black;
    display: table-cell;
}

HTML

child 1

child 2

child 3

child 4

child 1

child 2

child 3

child 4

child 5

child 7

child 8

child 9

child 10


text:
Q: Are extra localizations in Apple's ResearchKit causing the iOS App Store to incorrectly assume that our app is localized for many extra languages? We just release an app based on Apple's ResearchKit.  In the App Store, the listing indicates that the app supports many different languages, although we only specified two in the metadata in iTunesConnect.
This question,  Change iOS App List of Supported Languages in App Store, seems to indicate that the extra languages could have been automatically detected because there are .lproj folders in a third-party framework that our app uses.  ResearchKit does have many .lproj folders for localization.
Has anyone else with a ResearchKit app run into this?  Is the only solution to pull these extra folders out of the ResearchKit framework?

A: You're correct. You'll need to remove the localizations for languages you don't support in your app.


text:
Q: Parallelization using shared memory [bigmemory] I'm experiencing some difficulties when trying to make it work a parallel scenario [doSNOW], with involves the use of shared memory [bigmemory]. The summary is that I get the following error "Error in { : task 1 failed - "cannot open the connection"" in some of the foreach workers. More specifically, checking the cluster output log, it is related to "'/temp/x_bigmatrix.desc': Permission denied" like if there were some problem with a concurrent access to the big.matrix descriptor file.
Please excuse me, but because the code is a bit complex I'm not including a reproducible example but going to try to explain what's the workflow with the main points.
I have a matrix X, which is converted into big.matrix through:
x_bigmatrix <- as.big.matrix(x_matrix,
                             type = "double",
                             separated = FALSE,
                             backingfile = "x_bigmatrix.bin",
                             descriptorfile = "x_bigmatrix.desc",
                             backingpath = "./temp/")

Then, I initialize the sock cluster with doSNOW [I'm on Windows 10 x64]:
cl <- parallel::makeCluster(N-1, outfile= "output.log")
registerDoSNOW(cl)

(showConnections() shows properly the registered connections)
Now I have to explain that I have the main loop (foreach) for each worker and then, there is an inner loop where each worker loops over the rows in X. The main idea is that, within the main corpus, each worker is fed with chunks of data sequentially through the inner loop and then, each worker may store some of these observations but instead of store the observations themselves; they store the row indexes for posterior retrieval. In order to complicate even more the things, each worker modifies an associated R6 class environment where the indices are stored. I say this because the access to the big.matrix descriptor file takes places in two different places: the main foreach loop and within each R6 environment. The foreach main corpus is the following:
workersOutput <- foreach(worker = workers, .verbose = TRUE) %dopar% {
    # In the main foreach loop I don't include the .packages argument because
    # I do source with all the needed libraries at the beginning of the loop
    source(libs)

    # I attach the big.matrix using attach.big.matrix and the descriptor file
    x_bigmatrix <- attach.big.matrix("./temp/x_bigmatrix.desc")

    # Now the inner for loop is going to loop over the rows in X.
    # Each worker can store some of these indices for posterior retrieval
    for (i in seq(1, nrow(X)) {
        # Each R6 object associated with each worker is modified, storing indices...
        # Within these environments, there is read-only access through a getter using the same
        # procedure that above: x_bigmatrix <- attach.big.matrix("./temp/x_bigmatrix.desc")
    }
}
stopCluster(cl)

The problem occurs in the inner loop when trying to access the big.matrix backed in file. Because if I change the behaviour in these environments to store explicitly the observations instead of the row indices (thus, there is no access to the descriptor file within these objects anymore), then it works without any problem. Also, if I run it without parallelization [registerDoSEQ()] but storing the row indices in the objects, there is also no errors. So the problem takes place if I mix parallelization and double accessing to the shared big.matrix within the different R6 environments. The weird thing is that some of the workers can run for longer time than others, and even in the end at least one finish its run... So that makes me think about the problem with a concurrent access to the big.matrix descriptor file.
Am I failing at some basics here?

A: If the problem is a concurrent access to the big.matrix descriptor file, you can just pass the descriptor object (with describe) rather than the descriptor file which contains the object.
Explanation:
When attaching from the descriptor file, it first creates the big.matrix.descriptor object and then attach the big.matrix from this object. So, if you use directly the object, it will be copied to all your clusters and you can attach the big.matrix from them.


text:
Q: How can I parse json to enum with typescript I have a json string like this.
   {
     "type": "A",
     "desc": "AAA"
   }
or
   {
     "type": "B",
     "desc": "BBB"
   }
etc.

How can I use enum to parse it with typescript? I can do it like this, but how to handle with desc field?
enum Type {
   A = "A",
   B = "B"
}

A: You may try using a type. Something like this
type Item {
 type: "A" | "B";
 desc: string;
}

A: If the properties are related, i.e. type fully defines the value of desc, you can create a union type like this:
type Item =
  { type: "A", desc: "AAA" } |
  { type: "B", desc: "BBB" };


text:
Q: making node.js net client In all the examples of creating a client for node.js built-in net module I don't see how they get net to run on the client with out downloading it??
surely if my client-side code starts like this:
var net = require('net');
var client = net.connect({port: 8124},function(){
   console.log('client connected');
   client.write('world!\r\n');
   });

then first i must write:
<script src="some strange node path to net ??"></script>

am i correct? how do I do this? btw: node.js is installed in my root on my server not local

A: I believe there's a bit of confusion here. The client example code you're showing is meant to run in node, not in the browser. That makes node a client of another (node or otherwise) TCP server.
If you want node to be the client and connect to another server over TCP, then run the code you're pasting. The net module is bundled with node, you're good to go.
If, however, you want your browser to talk to a node server then this would have to be over websockets (a streaming binary protocol over http, this is not plain-vanilla TCP). You would have to have a websockets module in the server, not plain net.
Just to be clear: net is simply node's interface to TCP sockets.