text:
Q: With so much system resources available, how sure are you your code is tuned? With CPUs being increasingly faster, hard disks spinning, bits flying around so quickly, network speeds increasing as well, it's not that simple to tell bad code from good code like it used to be.
I remember a time when you could optimize a piece of code and undeniably perceive an improvement in performance.  Those days are almost over.  Instead, I guess we now have a set of rules that we follow like "Don't declare variables inside loops" etc.  It's great to adhere to these so that you write good code by default.  But how do you know it can't be improved even further without some tool?
Some may argue that a couple of nanoseconds won't really make that big a difference these days.  The truth is, we are stuck with so many layers that you get a staggering effect.
I'm not saying we should optimize every little millisecond out of our code as that will be expensive and unfeasible.  I believe we have to do our best, given our time constraints, to write efficient code as well.
I'm just interested to know what tools you use to profile and measure performance of code, if at all.

A: I think that optimization should be thought of not as looking at each line of code, but rather, what asymptotic complexity is your algorithm.  For example, using a bubble sort is probably one of the worst sorting algorithms you could use in terms of optimization.  It takes the longest.  Quicksort and mergesort are faster in terms of sorting, and should be always used before a bubble sort.
If you keep optimization always in your mind when designing a solution to a problem, then you should be able to write readable code, which other developers will approve of.  Also, if you are programming in a higher level language that will be compiled before it is run, remember that compilers make some awesome optimizations nowadays that you or I may not think of, and also (more importantly) do not have to worry about.
Stick with a good and low big O(), and it should be optimized pretty good.  If you are working with millions or greater in some type of dataset, then look for a big O(logn) algorithm.  They work great for large tasks, and keep your code optimized.
Let the compilers work on the line by line code optimizations so you can focus on the solutions.
There are times that do warrant line by line optimizations, and if that is the case that you need that much speed, maybe you might want to look into assembly so that you can control every line that is written.

A: There's a big difference between "good" code and "fast" code. They aren't exactly separate from each other either, but "fast" code doesn't mean "good". Often times, "fast" actually means bad code because readability compromises must be made to make it fast.
The way I look at it, hardware is cheap, programmers are expensive. Unless there is a serious performance problem with some piece of code, you should never have to worry about speed. If there are performance problems, you'll notice them. Only when you notice the performance problem on good hardware should you have to worry about optimization (in my opinion)
If you reach the point where your code is slow, but you can't figure out why, I'd use a profiler like ANT, or dotTrace if you're in the .NET world (I'm sure there are others out there for other platforms & languages). They're pretty useful, but I've only ever had one situation where I needed a profiler to identify the problem. It was something that now that I know the issue, I won't need a profiler again to tell me it's a problem because I'll never forget the amount of time I spent trying to optimize it.

A: This is absolutely a valid concern, but not for most developers.  Most developers are concerned with getting a product that works to their employer.  Optimized code is seldom a requirement.
The best way to make sure your code is fast is to benchmark or profile it.  A lot of compiler optimizations create non-intuitive oddities in the performance of a programmer's code, so in the end measurement becomes essential.

A: In my experience, Rational Quantify has given me the best results in terms of code tuning.  It is not free, but it is very fully featured and seems to have given me the most useful results.
In terms of free tools, check out gprof or oprofile, if you are on a Unix environment. They are not as good as some of the commercial tools, but can often point you in the right direction.
On a side note, I am almost always surprised at what profilers turn up the first time I use them. You can have intuition as to where code may be bottlenecking, and it can often be completely wrong.

A: Almost all code I write is plenty fast enough.  On the rare occasions when it isn't, for C, C++, and Objective Caml I use the venerable gprof and the excellent valgrind with its superb visualizer kcachegrind (part of the KDE SDK; don't be fooled by the out-of-date code on sourceforge).
The MLton Standard ML compiler and the Glasgow Haskell Compiler both ship with excellent profilers.
I wish there were a better profiler for Lua.

A: Uh, a profiler maybe? There are ones available for almost all platforms and languages.


text:
Q: Nginx not serving application to the internet My Nginx and Node.js application is not serving my application to the internet. When I try to access http://helloworld.example.com in my browser it cannot connecf.
Here is my helloworld.conf file:
upstream backend {
        server localhost:8000;
        keepalive 32;
}

server {
        listen 80;
        server_name helloworld.example.com;

        location / {
                client_max_body_size 50M;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_http_version 1.1;
                proxy_pass http://backend;
        }
}

Here is my Node app:
var http = require('http');

var hostname = 'localhost';
var port = 8000;

var server = http.createServer((req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Hello World!');
});

server.listen(port, hostname, () => {
        console.log(`Server running at http://${hostname}:${port}`);
});

And heres my service file:
[Unit]
Description=Node.js Application
After=syslog.target network.target

[Service]
Type=simple
User=root
WorkingDirectory=/root
Environment=NODE_ENV=production
ExecStart=/usr/bin/node usr/bin/helloworld.js

Restart=always

[Install]
WantedBy=multi-user.target

The service file status shows active and so does the Nginx config file and the node js app run perfectly. Any help?

A: Try the following configuration, it's from my NGINX server and works fine
server{

    listen 80;

    server_name localhost;

    location / {

        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header   Host               $host:$server_port;
        proxy_set_header   X-Real-IP          $remote_addr;
        proxy_set_header   X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto  $scheme;
    }
}

It listens on port 80 of localhost and for every request it receives, it forwards it to http://localhost:8000.
Not specifying anything except proxy_pass will work too
You can learn more about the directives below proxy_pass from the docs here
To connect the application to the internet you just have to change the server_name property in then config assuming that you domain points correctly to your server.
Changing server_name localhost to server_name helloworld.example.com will make the application available on the internet.

A: To expose your application to the Internet, to host it from home, you need to  make changes to systems outside your local machine.
In a typical setup your local computer is not connected to the internet directly. Instead it goes via a router, which is directly connected to the internet.
To the internet you appear with the address of your router and the internet can address your router by it's address. Normally your router "only" forwards your requests to the internet and accepts the responses. (The technical term here is NAT.) But it does not accept any incoming requests, because the router does not know how to handle the request. (Technically the router also blocks the request because it's Firewall is configured reject request.)
  +------------+                    +-------------+
  | your local |<--- WiFi / LAN ----| your router |<---- the internet
  |   machine  |----            --->|             |----->
  +------------+                    +-------------+

To make your application available to the internet you will need to tell the router to forward request to your local machine. How this is done depends on your Router, but the keyword here is Port Forwarding.
To forward a port you need to specify the port and the protocol to forward, in case of http this is port 80 (from the listen 80) and protocol TCP (the protocol http uses under the hood). Most routers automatically open this port in the Firewall, but for others you have to explicitly configure it. You most likely also have to open the port 80 in the firewall of your local machine, so the forwarding request is not rejected by your local machine.
If you have set up this forwarding other can now access your application via your routers (IP) address, for example http://91.11.84.87, but not via a domain name (yet).
To get a domain name you typically need to buy/rent (register) a domain name from a domain registrar and "attach" your routers address to the domain. (The keyword being DNS.) Getting a domain name is a story of it's own.
Typically your routers IP address changes regularly, so you will need to also update that address for your domain then! If you are in luck your registrar and router both support DynDNS: This way your router automatically updates the address with your registrar.
I hope this helps you into the right directions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PhpStorm very slow I installed the latest version of PhpStorm 2016.3 a while ago. Worked perfectly fine for me, but since a few days it has slowed down heavily. No big projects or files, but the response of the software is impressively slow when typing or using menus.
Does anyone have the some issue? It is strange, never (!) had issues with this before.

A: Try to disable all inspections and, if need, code style checks.
P.S. PHPStorm was and now is very slow under Linux (currently am using version 2016.2). All its versions were slow. Even at powerful computers with SSD. Jamming and sticking is a normal behavior for this program. It's a pity that authors do not pay attention to it. Thanks for those who are helping to make this program free :) Pay 89$ for the good (as a set of features), but very slow IDE is not a good idea.


text:
Q: Is textarea a required field? I'm building a large form that will compile tour schedules of our clients (comedians). Seen here.
Whenever I delete the larger textarea at the bottom, the form stops work, ie. the submit button doesn't do anything.
Anyone why that might be happening? Thanks.
I don't know exactly what would be helpful, but here's the code for the div containing the form:

<form action="http://www.standupexperts.com/cgi-sys/formmail.pl" method="post" name="hgmailer" >
<input type="hidden" name="recipient" value="adam@standupexperts.com">
 <input type="hidden" name="subject" value="FormMail E-Mail">

 Name:X-  <input type="text" name="name" size="20" value="">
                    X.XEmail: <input type="text" name="email" size="30" value="">

                    Cell #: X.<input type="text" name="cell" size="20" value="">
                    Address:X<input type="text" name="address" size="30" value="">

                    Website: <input type="text" name="website" size="20" value="">
                    Video Link:<input type="text" name="videolink" size="30" value="">

    Our avails method

If you cannot use the form below, you can email your schedule. Use our notation system if you want your avails entered sooner.

                    Download our 2013 avails sheet.

For routing purposes, we want to know the dates you are NOT available and what state you'll be on those dates.

Below, an X is already placed on open/available weeks. For booked dates, please enter days booked and the state.

Example:

12-3: X (open)

12-10: X 11-14 NC (open except the 10th thru 14th of Dec in NC)

12-17: 19 OH, 22 IN (open except for the 19th of Dec in OH and the 22nd in IN)

We are unable to work with just the day of the week (3/11: Thurs-Sun)

    2013 Avails/Schedule

    1/07: <input type="text" name="1/07__" size="20" value="X">

    1/14: <input type="text" name="1/14__" size="20" value="X">

    1/21: <input type="text" name="1/21__" size="20" value="X">

    1/28: <input type="text" name="1/28__" size="20" value="X">

    2/04: <input type="text" name="2/04__" size="20" value="X">

    2/11: <input type="text" name="2/11__" size="20" value="X">

    2/18: <input type="text" name="2/18__" size="20" value="X">

    2/25: <input type="text" name="2/25__" size="20" value="X">

    3/04: <input type="text" name="3/04__" size="20" value="X">

    3/11: <input type="text" name="3/11__" size="20" value="X">

    3/18: <input type="text" name="3/18__" size="20" value="X">

    3/25: <input type="text" name="3/25__" size="20" value="X">

    4/01: <input type="text" name="4/01__" size="20" value="X">

    4/08: <input type="text" name="4/08__" size="20" value="X">

    4/15: <input type="text" name="4/15__" size="20" value="X">

    4/22: <input type="text" name="4/22__" size="20" value="X">

    4/29: <input type="text" name="4/29__" size="20" value="X">

    5/06: <input type="text" name="5/06__" size="20" value="X">

    5/13: <input type="text" name="5/13__" size="20" value="X">

    5/20: <input type="text" name="5/20__" size="20" value="X">

    5/27: <input type="text" name="5/27__" size="20" value="X">

    6/03: <input type="text" name="6/03__" size="20" value="X">

    6/10: <input type="text" name="6/10__" size="20" value="X">

    6/17: <input type="text" name="6/17__" size="20" value="X">

    6/24: <input type="text" name="6/24__" size="20" value="X">

    7/01: <input type="text" name="7/01__" size="20" value="X">

    7/08: <input type="text" name="7/08__" size="20" value="X">

    7/15: <input type="text" name="7/15__" size="20" value="X">

    7/22: <input type="text" name="7/22__" size="20" value="X">

    7/29: <input type="text" name="7/29__" size="20" value="X">

    8/05: <input type="text" name="8/05__" size="20" value="X">

    8/12: <input type="text" name="8/12__" size="20" value="X">

    8/19: <input type="text" name="8/19__" size="20" value="X">

    8/26: <input type="text" name="8/26__" size="20" value="X">

    9/02: <input type="text" name="9/02__" size="20" value="X">

    9/09: <input type="text" name="9/09__" size="20" value="X">

    9/16: <input type="text" name="9/16__" size="20" value="X">

    9/23: <input type="text" name="9/23__" size="20" value="X">

    9/30: <input type="text" name="9/30__" size="20" value="X">

    10/07: <input type="text" name="10/07__" size="19" value="X">

    10/14: <input type="text" name="10/14__" size="19" value="X">

    10/21: <input type="text" name="10/21__" size="19" value="X">

    10/28: <input type="text" name="10/28__" size="19" value="X">

    11/04: <input type="text" name="11/04__" size="19" value="X">

    11/11: <input type="text" name="11/11__" size="19" value="X">

    11/18: <input type="text" name="11/18__" size="19" value="X">

    11/25: <input type="text" name="11/25__" size="19" value="X">

    12/02: <input type="text" name="12/02__" size="19" value="X">

    12/09: <input type="text" name="12/09__" size="19" value="X">

    12/16: <input type="text" name="12/16__" size="19" value="X">

    12/23: <input type="text" name="12/23__" size="19" value="X">

    NYE:..   <input type="text" name="NYE__" size="19" value="X">

    Anything else you want to add?

    <textarea name="comment" cols="50" rows="6"></textarea>
    <input type="button" value="SUBMIT" onclick="hgsubmit();" >
    <input type="hidden" name="redirect" value="http://www.standupexperts.com">

</form>

A:  else if (/\S+/.test(document.hgmailer.comment.value) == false)
   alert ("Your email content is needed.");

If you remove the textarea from the form, document.hgmailer.comment no longer exists, and therefore its .value causes an error. So, if you want to delete the textarea, you must also delete this check from your JavaScript.

A: It is possible that the formmail.pl expects a comment field without which the submission fails validation and is ignored.
Now ideally you would modify the formmail.pl to make this comment field optional. You can also remove the text area and replace it with a <input type="hidden" name="comment" value="" /> field, that will include an empty comment field with every submission.
###Somewhat off-topic###
On the surface this setup does not look very secure to me. Without adequate security, this form could end up being abused by spammers. The main issues are that the target email address is sent from a hidden variable which spammers can easily modify. The subject as well as the contents are also coming from the form. Unless the formmail.pl has some anti-spam measures, and those are configured correctly, you would do well to either add the security or use a different script.
Never mind that, I checked and it only emails local addresses so very little chance of spam.

A: In the html above, if you change the submit button <input> from button to submit.it wouldn't halt.also try this in firebug or chrome element inspector.
change
<input type="button" value="SUBMIT" onclick="hgsubmit();" >

to
<input type="submit" value="SUBMIT" onclick="hgsubmit();" >

also edit javascript to prevent twice server requestion.let the html mark up do the stuff.


text:
Q: Any Real uniformly continuous function on bounded set is bounded I know that this question is answered already. But I am not convincing with that argument. Please Help me
What I think is as follows:
$E$ is bounded set therefore by Bolzano Weierstrass property it has convergent sub sequence which must be Cauchy. The function
$f$ is uniformly continuous function, so it preserve Cauchy sequence under it.
Let $x_{n_k}$ be a Cauchy sub sequence then $f(x_{n_k})$ is also Cauchy sequence.
On contrary assume that  given function is unbounded Then can I write directly $f(x_{n_k})$ must not be Cauchy then.
Because Unbounded sequence have no Cauchy sub sequence.
But I was not convincing with this case as there is sequence {1,1,1,2,1,3,...} which is unbounded still had Cauchy sub sequence.
Any help will be appreciated.
Thanks A lot

A: You gave an example of an unbounded sequence with a convergent, hence Cauchy, subsequence.  This is irrelevant.  No such sequence is in the bounded set $E$.
Furthermore, the proof simply relies on the fact that if $f$ were unbounded there must be an unbounded sequence $(f(x_{n}))$ such that any subsequence $(f(x_{n_k}))$ is also unbounded.  In particular, there exists a sequence $(x_n)$ in $E$ such that $|f(x_n)| > n$ for all $n$, and for any subsequence $(x_{n_k})$ we have $|f(x_n)| > n_k \geqslant k$ for all $k$.
However, the bounded sequence $(x_n)$ has a Cauchy subsequence $(x_{n_k})$ such that $(f(x_{n_k}))$ is also Cauchy, a contradiction. Again, your counterexample does not enter the picture.


text:
Q: asp.net mvc A network-related or instance-specific error occurred I'm trying to set up a asp.net mvc with portable areas (in seperate projects) and a generic repository.
I use a IContext interface to generate the database for each context that implements that interface:
public class Context : DbContext
    {
        public List<IContext> Contexts {get;set;}

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            foreach (IContext context in Contexts)
                context.Setup(modelBuilder);
        }
    }

and the implementation of IContext:
public class TaskListContext : Context, IContext
    {
        public DbSet<Task> Tasks { get; set; }

        void IContext.Setup(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Task>().ToTable("Tasks");
            modelBuilder.Entity<Task>().HasKey(task => task.Id);
        }
    }

When I run this code:
Context context = new Context();
            context.Contexts = new List<IContext>();
            context.Contexts.Add(new ModuleContext());

            String assemblyPath = ControllerContext.HttpContext.Server.MapPath(String.Format("~/bin/{0}", "TaskList.dll")); //it is in a seperate project.

            Assembly assembly = Assembly.LoadFrom(assemblyPath);

            var contexts = from t in assembly.GetExportedTypes()
                              where typeof(IContext).IsAssignableFrom(t)
                              select t;
            foreach (Type t in contexts)
            {
                IContext cont = (IContext)Activator.CreateInstance(t);
                context.Contexts.Add(cont);
            }

            context.Database.CreateIfNotExists();

The database and the tables are created as expected.
But when I want to query the db with a repository pattern I get an error.
The query:
TaskListRepository Rep = new TaskListRepository();
            var task = Rep.FindBy(t => t.Id==2);

The repository:
public class TaskListRepository : GenericRepository<TaskListContext, Task>, ITaskListRepository
    {
    }

The abstract repository:
public abstract class GenericRepository<C, T> :
    IGenericRepository<T>
        where T : class
        where C : DbContext, new()
    {

        private C _entities = new C();

        public C ConcreteContext
        {

            get { return _entities; }
            set { _entities = value; }
        }

        public virtual IQueryable<T> GetAll()
        {
            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {

            IQueryable<T> query = _entities.Set<T>().Where(predicate);
            return query;
        }

        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }

        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = System.Data.EntityState.Modified;
        }

        public virtual void Save()
        {
            _entities.SaveChanges();
        }
    }

Then I get this error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Stack Trace:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +6351920
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +412
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity) +6366506
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject) +180
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +6366917
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +6366793
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +352
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +831
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +49
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +6368598
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +78
   System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +2194
   System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +89
   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +6372110
   System.Data.SqlClient.SqlConnection.Open() +300
   System.Data.SqlClient.SqlProviderServices.UsingConnection(SqlConnection sqlConnection, Action`1 act) +132
   System.Data.SqlClient.SqlProviderServices.UsingMasterConnection(SqlConnection sqlConnection, Action`1 act) +3981391
   System.Data.SqlClient.SqlProviderServices.GetDbProviderManifestToken(DbConnection connection) +10513049
   System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +44

[ProviderIncompatibleException: The provider did not return a ProviderManifestToken string.]
   System.Data.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection) +11121429
   System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +94

[ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.]
   System.Data.Entity.ModelConfiguration.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked(DbProviderServices providerServices, DbConnection connection) +357
   System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +108
   System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +118
   System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +237
   System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +279
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +888
   System.Data.Entity.Internal.InternalContext.Initialize() +50
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +45
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +151
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +50
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +140
   System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +135
   MonackFr.Repository.GenericRepository`2.FindBy(Expression`1 predicate) in D:\code\MonackFr\MonackFr\MonackFr.Library\Repository\GenericRepository.cs:34
   MonackFr.Mvc.Areas.TaskList.Controllers.TaskController.Index() in D:\code\MonackFr\MonackFr\MonackFr.Mvc\MonackFr.Mvc\Areas\TaskList\Controllers\TaskController.cs:18
   lambda_method(Closure , ControllerBase , Object[] ) +113
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +261
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +34
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +129
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +954935
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +955452
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +20
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +67
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +20
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +53
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +20
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +54
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375

Connection String:
<connectionStrings>
      <add name="Context" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=monackfr;User Id=sa;Password=*******" />
  </connectionStrings>

I really don't see it anymore? Does anyone know what's going wrong? The connectionstring should be correct: it is making the database and tables.
Regards,
Willem

A: EF has a lots of useful conventions. One of them is that EF tries to find out the connection string automatically.
If you haven't specify otherwise and there is no connection string in your config file EF will creates one with the DB name based on the DbContext type's name.
So when you use Context it can find your connection string with name="Context" in your config. But when you use TaskListContext it could not find a connection string with name='TaskListContext' so it will geneate a connection string for you which will result in the exception what you get.
To avoid this you can add a new connection string with the name='TaskListContext' in your app/web.config
Or you can use one of the DbContext contructor overloads to specify the connection excplicitly. With your current design it should look like this:
public class Context : DbContext
{
    public Context()
    {
    }

    public Context(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }

    //.. rest of Context
}

public class TaskListContext : Context, IContext
{
    public TaskListContext() : base("Context")
    {
    }

     //.. rest of TaskListContext
}

With this modification in all the IContext derived types EF will use the same connection string named "Context" from your config file for every DbContext.


text:
Q: Slim Framework Routing with asset files (eg. css files) not rendered I am having this problem of rendering a view for this route on Slim Framework:
Here is my application directory structure:
|--project
    |--public
       |--assets
            |--css
                |--main.css
       |--index.php
       |--.htaccess
    |--app
        |--asset
            |--route.php
        |--controllers
            |--HomeController
            |--AuthController
        |--models
        |--views
            |--auth
                |--signup.php
            |--home
                |--index.php
        |--bootstrap.php

With the route:
$app->get('/[{home}]', 'app\controllers\HomeController:index')->setName('home');

everything works fine with the all assets files (in the css folder of the public folder) included and the uri for the css file is
http://localhost:8081/slim-auth/public/assets/css/main.css

But with the route:
$app->get('/auth/signup', 'app\controllers\AuthController:getSignUp')->setName('auth.signup');

There is  404 error accessing the css file where the browser tries to access the css file via the uri:
http://localhost:8081/slim-auth/public/auth/assets/css/main.css

instead of:
http://localhost:8081/slim-auth/public/assets/css/main.css

although the content of the requested route was displayed, the css was not rendered with the 404 response status
After changing the route to:
$app->get('/signup', 'app\controllers\AuthController:getSignUp')->setName('auth.signup');

Everything seems to work fine like the case of the home route.
Please is there anyway I could go around this? I'll really appreciate if this could be solved asap.


text:
Q: Changing the structure of the datatable with specific conditions I have a datatable prdData like this
productid        text                    linenumber    typenumber
100              this is the                 0             2
100              description of a1           2             2
200              this is the name of a2      0             0
100              this is the name of a1      0             0
200              shortdescription of a2      0             1

In this table product data is stored. Product number, product name, short description, Long description are the data stored.If the typenumber is 0 its name, if 1 its short description, and if 2 its long description. And each of these data may come in different lines if the value is long. each line can be identified by linenumber for first line it will be 0 next 2 and so on. I want to convert this DataTable to another datattable like this
productId   name                    shortdescription             longdescription
100         this is the name of a1                               this is the description of a1
200         this is the name of a2   shortdescription of a2

Can any one tell me how I can achieve this?

A: You can group rows by product, and then group product's rows by their type:
var query = from r in table.AsEnumerable()
            group r by r.Field<int>("productid") into g
            let types = g.GroupBy(r => r.Field<int>("typenumber"))
            select new {
               productId = g.Key,
               name = GetText(types.FirstOrDefault(t => t.Key == 0)),
               shortdescription = GetText(types.FirstOrDefault(t => t.Key == 2)),
               longdescription = GetText(types.FirstOrDefault(t => t.Key == 1))
         };

Where helper method just orders type rows by line number and returns concatenated text
private static string GetText(IEnumerable<DataRow> rows)
{
    if (rows == null)
        return null;

    var query = from r in rows
                orderby r.Field<int>("linenumber")
                select r.Field<string>("text");

    return String.Join(" ", query);
}

Output:
[
  {
    productId: 100,
    name: "this is the name of a1",
    shortdescription: "this is the description of a1",
    longdescription: null
  },
  {
    productId: 200,
    name: "this is the name of a2",
    shortdescription: null,
    longdescription: "shortdescription of a2"
  }
]

You can build new DataTable manually or with this CopyToDataTable method. You also can build Xml with Linq to Xml:
var xdoc = new XDocument(new XElement("products",
              from p in query
              select new XElement("product",
                  new XAttribute("productId", p.productId),
                  new XElement("name", p.name),
                  new XElement("shortDescription", p.shortdescription),
                  new XElement("longDescription", p.longdescription))));

Output:
<products>
  <product productId="100">
    <name>this is the name of a1</name>
    <shortDescription>this is the description of a1</shortDescription>
    <longDescription />
  </product>
  <product productId="200">
    <name>this is the name of a2</name>
    <shortDescription />
    <longDescription>shortdescription of a2</longDescription>
  </product>
</products>

Or (maybe) simpler solution - instead of anonymous type usage, create custom class which can be easily serialized to xml.


text:
Q: How to traverse in decimal search tree? (Java) (has at most 10 children instead of 2) I was wondering how do you actually traverse the decimal search tree?
This is given by my teacher

A decimal search tree contains unique values just like a binary search tree, but instead of having at most two children each node has at most ten children.If the objects being saved in the tree have a sorting key that is a non-negative whole number with a known maximum number of digits (k), then every operation reduces to O(k), because each layer of the tree represents a different digit in the key. The layers of the tree are in Most Significant Digit (MSD) order, with the most significant digit at the top and the least significant digit at the bottom of the tree.Eachnode of a decimal search tree ismade up of a value and a 10-element array of children. All branch nodes have a null value, and allleaf nodesthat contain a non-null valuehave a children arrayfilled with nulls. This puts all of the actual data at the lowest level in the tree.

*

*contains(key) –returns true if a value with the given key exists in the tree, false if not

*get(key) –returns the value at the given key, or null if it does not exist

*etc.

private class DecimalNode<E> {

    /**
     * the value stored in this node - will be null for all nodes except
     * the lowest-level leaf nodes
     */
    public E value;

    /**
     * the array used to store the children of this node
     */
    public DecimalNode[] children;

    /**
     * Default constructor.
     */
    public DecimalNode() {
        children = new DecimalNode[10];
    }

    /**
     * A convenience method to create a new node at the given
     * index of the current node.
     *
     * @param index the index of the children array where the new
     * node should be stored
     */
    public void makeChild(int index) {
        children[index] = new DecimalNode();
    }

I am working on contains and get method. The constructor is given by my teacher.
/**
     * Constructor.
     *
     * @param digitCount the largest number of digits a sorting key will
     * contain in this sorted decimal map
     */
    public SortedDecimalMap(int digitCount) {
        root = new DecimalNode();
        this.digitCount = digitCount;
    }

@Override
public boolean contains(int key) {
    DecimalNode node = root;
    for(int i = 0; i < digitCount; i++)
    {
        if (node.children[i].equals(key)){
            return true;
        }
    }
    return false;
}

@Override
public E get(int key) {
    DecimalNode node = root;
    for (int i = 0; i < digitCount; i++) {
            if (node.children[i].children[key] != null) {
                return  (E) node.value;
            }
    }
    return null;
}

I have no idea how to traverse through the tree


text:
Q: How to hide sidebar warning "The value of the local variable is not used" in Eclipse? The "The value of the local variable is not used" warning is really annoying as it hide breakpoints in the sidebar. The variable in question also gets underlined to highlight this warning so the sidebar icon is fairly redundant.
So is there any way to hide this warning in the sidebar?

A: @SuppressWarnings("unused")
Add the above line of code before main() it will suppress all the warning of this kind in the whole program. for example
public class CLineInput
{
    @SuppressWarnings("unused")
    public static void main(String[] args)
    {

You can also add this exactly above the declaration of the variable which is creating the warning, this will work only for the warning of that particular variable not for the whole program. for example
   public class Error4
{

    public static void main(String[] args)
    {
        int a[] = {5,10};
        int b = 5;
        try
        {
            @SuppressWarnings("unused")     // It will hide the warning, The value of the local variable x is not used.
            int x = a[2] / b - a[1];
        }
        catch (ArithmeticException e)
        {
            System.out.println ("Division by zero");
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Array index error");
        }
        catch(ArrayStoreException e)
        {
            System.out.println("Wrong data type");
        }
        int y = a[1] / a[0];
        System.out.println("y = " + y);

    }

}

A: *

*Windows > preferences

*Java > Compiler > Error/Warnings

*Open "Unnecessary code" group

*change "Value of local variable is not used" from "Warning" to "Ignore"
It will require a new build and it's done.
Of course, you must aware that you are ignoring that option and potentially increasing memory consumption and leaving clutter in your code.


text:
Q: how to solve client connector error in python? I have the code below
and I'm writing a bot for discord
but I get error
"Exception has occurred: ClientConnectorError                                                Cannot connect to host discord.com:443 ssl:default [The specified network name is no longer available]"
in the last line
code:
import discord
import os

client = discord.Client()

@client.event

async def ready1():
  print('we have logged in')

@client.event

async def hello(message):
  if message.author==client.user:
    return
  if message.content.contains('hello'):
    await message.channel.send('hello')

client.run(token)

A: I just re-generate the token and it worked


text:
Q: Python - grouping words into sets of 3 I'm trying to create a multidimensional array that contains the words in a string - the word before that word (unless at the beginning of the string, blank), the word, and the following word (unless at the end of the string, blank)
I've tried the following code:
def parse_group_words(text):
    groups = []
    words = re_sub("[^\w]", " ",  text).split()
    number_words = len(words)
    for i in xrange(number_words):
        print i
        if i == 0:
            groups[i][0] = ""
            groups[i][1] = words[i]
            groups[i][2] = words[i+1]
        if i > 0 and i != number_words:
            groups[i][0] = words[i-1]
            groups[i][1] = words[i]
            groups[i][2] = words[i+1]
        if i == number_words:
            groups[i][0] = words[i-1]
            groups[i][1] = words[i]
            groups[i][2] = ""
    print groups

print parse_group_words("this is an example of text are you ready")

But I'm getting:
0

Traceback (most recent call last):
  File "/home/akf/program.py", line 82, in <module>
    print parse_group_words("this is an example of text are you ready")
  File "/home/akf/program.py", line 69, in parse_group_words
    groups[i][0] = ""
IndexError: list index out of range

Any idea how to fix this?

A: Here's a generic way to do it for arbitrary sized windows, using Python collections and itertools:
import re
import collections
import itertools

def window(seq, n=3):
    d = collections.deque(maxlen=n)
    for x in itertools.chain(('', ), seq, ('', )):
        d.append(x)
        if len(d) >= n:
            yield tuple(d)

def windows(text, n=3):
    return list(window((x.group() for x in re.finditer(r'\w+', text)), n=n))

A: What about...:
import itertools, re

def parse_group_words(text):
    groups = []
    words = re.finditer(r'\w+', text)
    prv, cur, nxt = itertools.tee(words, 3)
    next(cur); next(nxt); next(nxt)
    for previous, current, thenext in itertools.izip(prv, cur, nxt):
        # in Py 3, use `zip` in lieu of itertools.izip
        groups.append([previous.group(0), current.group(0), thenext.group(0)])
    print(groups)

parse_group_words('tanto va la gatta al lardo che ci lascia')

This is almost what you require -- it emits:
[['tanto', 'va', 'la'], ['va', 'la', 'gatta'], ['la', 'gatta', 'al'], ['gatta', 'al', 'lardo'], ['al', 'lardo', 'che'], ['lardo', 'che', 'ci'], ['che', 'ci', 'lascia']]

...missing the last-required group ['ci', 'lascia', ''].
To fix it, just before the print, you could add:
groups.append([groups[-1][1], groups[-1][2], ''])

This feels like a midly-unsavory hack -- I can't easily find an elegant way to have this last group "just emerge" from the general logic of the rest of the function.


text:
Q: Soap service header I created web service to accept this soap request.
I tested and Its working fine without header
if I add header still working  for s:mustUnderstand="0" but
if I change  it to 1 it's breaking

Action s:mustUnderstand="1"

in order to accept header what changes I need to do on my web service?
Thanks in advance
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">   <s:Header>
        <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://www.xxxx-ccc.co.uk/Integration/SaveApplication</Action> </s:Header>

<s:Body>  applicant>
          <title>Mr</title>
          <forename>dd</forename>
          <surname>ee</surname>
          <address>
            <street1>ppp</street1>
            <town>dd</town>
            <county>cc</county>
            <postcode>rtrtr</postcode>
          </address>
        </applicant>
</s:Body> </s:Envelope>

This is my web service code
 [WebService(Namespace = "http://www.xxxx-ccc.co.uk/Integration/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 [System.ComponentModel.ToolboxItem(false)]
    public class CG_ADNContact : System.Web.Services.WebService
    {

        [WebMethod(Description = "")]
        public XmlDocument SaveApplication()
        { //Do some thing }

}

A: The http://schemas.microsoft.com/ws/2005/05/addressing/none namespace is not valid for an Action element. It should never be in a soap message. Where did you get the message from? Did you perhaps copy it from a wcf trace log?
If the mustUnderstand attribute is set to true (or 1), this basically means that the element in question has to be part of the service contract. You can control this with the MustUnderstand property of the MessageHeader attribute.
See here For an example service contract that uses this attribute.


text:
Q: How to execute many functions one after the other I'd like to execute many function after the other. Each function returns True or False. So if one function returns True, I'd like to execute the next one. etc...
All the functions don't have necessary the same arguments.
Now i have something like :
res=function1()
if res:
   res=function2()
   if res:
      res=function2()

And it goes on and on for like 20 functions. Is there a better way to do this ?
Thank you in advance...

A: Well, you can define your own way to do this, but I would do that like that:
my_functions = (
    (my_func1, [2, 5], {'kwarg1': 'val1'}),
    # ...
)

for function, args, kwargs in my_functions:
    if not function(*args, **kwargs):
        break

Edited according to the comment. Great insight!

A: I'd probably use partial to make zero-argument functions that you can loop over (instead of some kind of structure with the function and its arguments):
functions = [
    functools.partial(func1, arg1a, arg1b),
    functools.partial(func2),
    functools.partial(func3, keyword_a=kwarg3a, keyword_b=kwarg3b)
]

Then, instead of putting it into a list and iterating over it, you can just call all:
retval = all(func() for func in (
    functools.partial(func1, arg1a, arg1b),
    functools.partial(func2),
    functools.partial(func3, keyword_a=kwarg3a, keyword_b=kwarg3b)
))

That will return False as soon as one of the functions returns False (or anything false-y), or run all of the functions and return True if they all return True (or anything true-y). As the docs say, it's equivalent to:
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

It's worth comparing the partials to the tuples in the other answer, which serve as pseudo-partials, both in how they're defined and in how they're called:
f1 = functools.partial(func, arg1, arg2, kw1=kwarg1, kw2=kwarg2)
f2 = (func1, (arg1a, arg1b), {'kw1': kwarg1, 'kw2': kwarg2 })

f1()
f2[0](*f2[1], **f2[2])

Obviously you can (and should, as aemdy's answer does) make the call more readable with tuple-unpacking, but it's still never going to be as simple as using a real partial.

A: You can take advantage of the short-circuiting behaviour of the and operator:
function1() and function2() and function3() and ...

function2 will only be called if function1 returned True, function3 will only be called if function1 and function2 returned True, and so on.
It's not necessarily very Pythonic, though.
Since you're always assigning to res, you can also just keep the ifs flat:
res = function1()

if res:
    res = function2()

if res:
    res = function3()

That could considered more readable, but it does waste a lot of vertical space. At least you aren't nesting ifs two dozen deep, though.

A: There's no need to get too complicated:
res = function1()
res = res and function2()
res = res and function3()
...

This looks a little odd, but will do what you want, without having to twist around the function calls themselves into lists of dictionaries or something. It's just a longer way of writing Cairnarvon's answer:
res = (
   function1() and
   function2() and
   function3() and
   ...
   )


text:
Q: Swipe a mapkit away from view By default, when swipe a mapkit view, the map moves. This is great.
If I want to move away from the map view and load another viewcontroller's view, how do I accomplish that? I could add a button to do that, but I'd like to use gesture.
Thanks
THE FOLLOWING CODE WORKED:
(1) In the map view controller's header file, I added UIGestureRecognizerDelegate to support its protocol
(2) In map view controller's .m file , I added
- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
   shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

(3) In map view controllers viewDidLoad method I added:
UISwipeGestureRecognizer *leftSwipe =
[[[UISwipeGestureRecognizer alloc]
  initWithTarget:self action:@selector(leftSwipeReceiver:)] autorelease];
leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
leftSwipe.delegate = self;
[self.view addGestureRecognizer:leftSwipe];

(4) This follow function is called for a left-swipe
- (void)leftSwipeReceiver:(UIGestureRecognizer *)recognizer
{
    NSLog(@"leftSwipeReceiver:");

}


text:
Q: Snowflake snowpipe files are not auto ingesting after adding file into AWS s3 I have created snowpipe for one of snowflake table. Source file will be landed in AWS S3 bucket at periodical time, So followed below steps to create snowpipe:

*

*Created external stage

*Queried the files using "PUT" command (Able to see the list of available files in result panel)

*Created snowpipe

*Configured SQS notification on top of S3 bucket

*Added one sample file and its noy loaded automatically

*Altered snowpipe using following command:
alter pipe snowpipe_content refresh;

*The file got added into snowflake target table after some time.

Can someone please help me to figure out what I missed on snowpipe setup

A: Follow the below setps to trouble shoot your snowpipe:
Step: I : Check the status of your snowpipe:
SELECT SYSTEM$PIPE_STATUS('pipe_name');
Make sure your pipe status is RUNNING
Step: II: Check copy history for the table associated with snowpipe:
select
*
from
table(information_schema.copy_history(table_name=>'table_name', start_time=> dateadd(hours, -1, current_timestamp())));
Ensure the file is not loaded from the list / errored.

Step III: Validate your snowpipe load
select
*
from
table(validate_pipe_load(
pipe_name=>'pipe_name',
start_time=>dateadd(hour, -1, current_timestamp()))
);
If above steps looks good, Might be issue with your SQS notification set up:
Follow the snowflake article by referring below link:
Snowflake KB


text:
Q: Spring MVC controller - getPathInfo() is null I have worked servlet that need to convert to Spring MVC controller to have access spring beans etc. Why in normal servlet request.getPathInfo() return not null, but in Spring Controller i get null value ? I know i can use @PathVariable, but wonder why the results of this method is the difference?
@RequestMapping(value = {"/test", "/test/*"})
public void test(HttpServletRequest req, HttpServletResponse res) {

    log.info(req.getPathInfo() == null); // true!

    if (req.getMethod().equalsIgnoreCase("get")) {
        // analogue to doGet...
    } else {
        // analogue to doPost...
    }

}

A: I think the solution is in the javadoc of getPathInfo()

The extra path information follows the servlet path but precedes the
  query string and will start with a "/" character.

In case of Spring the servlet path is the full path hence if you call getServletPath() it will always return the full URI and getPathInfo() will return nothing.


text:
Q: Expected value of re-flipping a coin This is a simplification and slight modification of an interview question which I found online.
Quesiton: You flip 3 coins and if you get HHH or TTT you will win \$X. How much are you willing to pay for this game?
Solution: Since my chances of winning is $\frac{1}{4}$, I would pay \$$\frac{X}{4}$ to play this game.
Follow Up 1: What if you can have an option to re-flip any of the coins?
Solution: I still have $\frac{1}{4}$ chances of winning plus for any other outcomes I have $\frac{1}{2}$ chances of winning, so I am willing to pay \$$\frac{3*X}{4}$ to play this game.
Follow Up 2: What if you can re-flip a certain coin, let's say the last one
Solution: I still have $\frac{1}{4}$ chances plus if I get HHT or TTH I will re-flip. The chances I get HHT or TTH is $\frac{1}{4}$ and the chances that I win after re-flipping is $\frac{1}{8}$, so I am willing to pay \$$\frac{3*X}{8}$ to play this game.
Is my logic correct for all the above?

A: The first one and the last one are correct. The second is not correct.
For the second one, there is $\frac{1}{4}$ chance that we get $3H$ or $3T$ and $\frac{3}{4}$ chance that we get $2H, 1T$ or $2T,1H$. Given the option that we can re-flip a coin, we would re-flip the coin that we have one of. So if we had $2H,1T$ and we re-flip the coin that had $T$, there is $\frac12$ chance that we get $H$ and we win $ \$X$. Similarly for the case $2T, 1H$.
So expected win value $ = \displaystyle \left(\frac14 + \frac12 \cdot \frac34 \right) \cdot X = \frac{5X}{8}$.


text:
Q: Crop image in HTML5 I am using below given fiddle to apply zoom in and zoom out on my canvas image, but when i zoom out my image it shows multiple images slices. This problem does not show in fiddle possibly because its image background is white.
If any one knows how to solve this problem kindly give an idea about it. Thanks

A: It sounds like you forget to clear your canvas between each draw:
http://www.w3schools.com/tags/canvas_clearrect.asp

A: context.clearRect(0, 0, canvas.width, canvas.height);

Note that for clearRect you need to either have an untransformed context, or keep track of your actual boundaries.


text:
Q: Visual Studio 2015 installation issue - SqlDom_amd64\SqlDom.msi I am trying to install Visual Studio 2015, however, after several steps, Installer pops up one message as below,

I cleared %temp% files however,it did not work either yet. It is not package issue because that this package was installed successfully in another WIN7 system.

A: The real problem is that your windows is missing some Microsoft certificates, to verify if this is the case:

*

*Open certification manager (Win+R -> certmgr.msc)

*Go to "Trusted Root Certification Authorities" -> "Certificates"

*Check for:

*

*"Microsoft Root Certificate Authority"

*"Microsoft Root Certificate Authority 2010"

*"Microsoft Root Certificate Authority 2011".

*You most likely don't have all of them from some reason.

On other PC that is connected to the internet and receiving Microsoft updates:

*

*Check again for these certificates, you most likely see them.

*Export them to SST file.

*Import the SST file (that contain the 3 certificates) in the first PC.

Install again, now it will work :-)
I believe that this will also fix some Visual Studio 2013 SDKDDKVer.h and related errors.

A: I faced this problem yesterday only and didn't found the exact solution but some work-arounds that did the job.
I faced issues in installing following components using vs_community.exe:-
 - SqlDom_amd64
 - TSqlLanguageService
 - CT/AzureMobileServicesSdkV2.0
 - Win10_UniversalCRTSDK
     - Headers Libraries and sources
 - WcfDataServices
 - Win81_SDK
 - SQLSysClrTypes
 - SQLSysClrTypes_amd64
 - SharedManagementObjects_x86
 - SharedManagementObjects_amd64
TRICK:
 - Since, choosing the location that has that package didn't help so I clicked SKIP PACKAGE-option for all packages listed above.
 - And, then manually ran set-up/msi-installers for above listed packages.
 - Some got successfully installed like 'SqlDom_amd64' and few others
 - But to my bad luck, for some it was kind of crashing during extraction so I thought msi-installer might actually got corrupted for some.
 - So, for the left ones, I've to choose 'Repair'-option of 'vs_community.exe' and opt for 'Download packages from Internet'.
 - Finally, set-up got successful and everything is working fine.
I understand its a work-around and not a solution but it serves the purpose with a limitation that it needs internet-connection for some packages.

A: Download first sqldom manually and al the other packages will be downloaded automatically.


text:
Q: How to stop sending multiple mails to single MailId I'm trying to send an email to the user. I have used the javax.mail.* and javax.mail.internet.* packages and successfully sent an email, but the problem is that it is sending multiple emails for a single mail ID. How can I make it send only once?
My code:
public void sendEmail(){

     System.out.println("called "+j+" time");

     emailIDs.add(emailID);

     to = emailID;

     MimeMessage message = new MimeMessage(session1);

     // Set From: header field of the header.
     try {

         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.

         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field

         message.setSubject(notifyName[j]+" "+"Document Alert Mail!");

         // Send the actual HTML message, as big as you like

         message.setContent("
document created on "+createdOn+" is coming to expire
",
                            "text/html" );

         // Send message
         Transport.send(message);

         System.out.println("Message Sent Successfully....");
     }

     catch(Exception e){

         e.printStackTrace();
     }
 }

A: You should provide argument in your function. It seems that you have added emailID element as many times as you call sendEmail() function. Every time you call the function, you should clean your emailIDs or you just need to send email to the last element.
Here I send only one recipient:
public void sendEmail(String emailID){

 System.out.println("called "+j+" time");

 emailIDs.add(emailID);

     to = emailID;

     MimeMessage message = new MimeMessage(session1);

     // Set From: header field of the header.
     try{

     message.setFrom(new InternetAddress(from));

     // Set To: header field of the header.

     message.addRecipient(Message.RecipientType.TO,
                              new InternetAddress(to));

     // Set Subject: header field

     message.setSubject(notifyName[j]+" "+"Document Alert Mail!");

     // Send the actual HTML message, as big as you like

     message.setContent("
document created on "+createdOn+" is coming to expire
",
                        "text/html" );

     // Send message
     Transport.send(message);

     System.out.println("Message Sent Successfully....");
     }

     catch(Exception e){

         e.printStackTrace();
     }
}


text:
Q: Discretization of second order nonlinear ODE using finite difference approximation not correct I have the differential equation
$$y'' + x(y^2)' - 2y^2 = g(x) \Longleftrightarrow y'' + x2yy'-2y^2 = g(x).$$
Using finite-difference approximations
$$y''(x_m) \approx \frac{Y_{m-1} - 2Y_m + Y_{m+1}}{\Delta x^2},$$
$$y'(x_m) \approx \frac{Y_{m+1} - Y_{m-1}}{2\Delta x},$$
$$y(x_m) \approx Y_m,$$
I get
$$\frac{Y_{m-1} - 2Y_m + Y_{m+1}}{\Delta x^2} + \frac{x_m}{\Delta x}Y_m(Y_{m+1}-Y_{m-1}) - 2Y_m^2 = g(x_m).$$
However, the answer is supposed to be

Why is the second term in my answer wrong?

A: In the second version they are using a finite difference representation of the term $y^2$:
$$
(y^2)' \approx \frac{y^2_{m + 1} - y^2_{m - 1}}{2\Delta x} \tag{1}
$$
While you are using a finite representation of $2y y'$:
$$
2y y' \approx 2y_m\frac{y_{m + 1} - y_{m - 1}}{2\Delta x} \tag{2}
$$
But they are equivalent, if you take (if the solution $y$ is smooth enough you can do approximate the value at a node with the average of its neighbor nodes)
$$
y_m \approx \frac{y_{m + 1} + y_{m - 1}}{2} \tag{3}
$$
Then Eq. (2) becomes
$$
2yy' \approx 2y_m\frac{y_{m + 1} - y_{m - 1}}{2\Delta x} \approx (y_{m + 1} + y_{m - 1})\frac{y_{m + 1} - y_{m - 1}}{2\Delta x} = \frac{y^2_{m + 1} - y^2_{m - 1}}{2\Delta x} \approx (y^2)'
$$


text:
Q: Counter cache for scopes I've set up some counter_caches in my app before but only for simple belongs_to relationships.
I'm doing a lot of queries like
user.collections.got.count

where got is a scope in my collection model
belongs_to :user
scope :got, -> { where(status: 'Got') }

Can I set up a counter_cache to count the number of user.collections that are marked as "got"?
The problem I see is that counter_cache only updates with create or destroy but not update actions. Is there a good method for this?

A: you can add a after_save callback to the Collection class and do the counter cache manipulation by yourself.
class Collection < ActiveRecord::Base
  belongs_to :user

  after_save :update_got_counter

  def update_got_counter
    if changed_attributes.has_key?('status')
      # do the cache manipulation here
      User.increment_counter(:collections_get_count, user.id)
      or
      User.decrement_counter(:collections_get_count, user.id)
    end
  end
end


text:
Q: Convert Google ProtocolBuffer.ProtocolMessage to JSON in Python I am attempting to convert a google.net.proto.ProtocolBuffer.ProtocolMessage (which is protobuf v1) implemented in this class to a JSON string.  I have tried several utilities that claim to be able to convert protocol buffers, but all of them appear to be exclusive to protobuf v2.
Does anyone have insight into how a v1 protobuf object could be converted to JSON?
Thanks!

A: Protobufs v1 as never officially released publicly, but leaked out as part of the App Engine SDK. As such, you're unlikely to find any tools built around it. Moreover, the v1 API never really supported things like converting to JSON -- the concept of reflection was a major improvement introduced by v2. In the v1 days, any "generic" algorithms (e.g. converting a protobuf to text) had to inspect the serialized bytes rather than the parsed object.
That said, one simple thing you can do is serialize the v1 protobuf object and then parse it into a v2 object. The wire formats are the same. From there, you can use all the usual v2 tools to do whatever you want with the data.
However, in order to generate a v2 object, you of course need the original .proto file. I couldn't find this file in the repository to which you linked, although I only looked briefly. It's possible that the original .proto file was not released publicly, in which case your only option would be to reverse-engineer it by looking at the generated source code, which is tedious.


text:
Q: Why setting percentage padding (and height) dont work in elements inside flexbox in FF See the fiddle: http://jsfiddle.net/4E2bV/793/
.imageContainer {
    position: relative;
    width: 23%;
    padding-bottom: 23%;
    float: left;
    height: 0;
    margin: 1%;
}

img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
}
body{
    display: flex;
}

On FF the items inside body have padding equals 0 - on other browsers it is properly 23% for bottom padding
Is there any workaround to use a percentage values in FF?
On Chrome and IE it works ok.

A: You fiddle doesn't work on my FF at all. I needed to change it to webkit-flex, like this:
body{
   display: -webkit-flex;
}

Then it works exactly as in Chrome, no problem with padding.
My FF version: 28.0
My Chrome ver: 37.0.2062.120 m

A: Yes, sorry I misunderstood.
Try NOT to use body as the flex-container. Use a div inside of it instead, surrounding all images. I also altered the css for .imageContainer and .img quite a bit into something I think looks nice. Cute kitties by the way :-)
Here's the code (works both on Chrome and FF):


text:
Q: Internet Explorer box-shadow artefacts on animation I am making a simple jobs site to test my skills in web development and in IE when i dynamically change the content o the page the bottom box shadow leaves some copies of it...
This is after i dynamically change the content:

Can anyone tell me why this happens. Is it a normal behavior for IE?
Here is some HTML code:

            All jobs

            Agriculture
            +

Agriculture, Forestry and Fishing

Landscape Architect

            Education
            +

College/University

Independent Learning

Libraries

Preschool

            Government
            +

City

County

Federal

University of Wisconsin System

            Information Technology
            +

Computer - Hardware

Computer - Software

Computer Service and Call Center

            Labor

And the css code:
    #categories-menu {
    clear: left;
    float: left;
    margin-top: 20px;
    width: 25%;
    background-color: rgba(0, 153, 204, 0.1);
    border: 1px dashed;
    box-shadow: 0 0 10px rgba(50, 50, 50, 0.78);
    padding: 0 20px;
}

A: So i desperately searched the web for a solution. And looks like the box-shadou artefacts are a knoun issue in IE10. It wa easly fixable in IE9 with an overflow: hidden on the shaddowed elemen. But in IE10 it can't be fixed anymore.
A workaround would be to remove the shadow before the animation and add it back after the animation is completed.


text:
Q: Returning a pointer to a function in C syntax In one of the answer to How do function pointers in C work? one user explains how to use function pointers in return values. Here's the code in question:
// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int

int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

For me the way you declare the functionFactory function is very weird - it seems to me that you mix up the return type (pointer to a function) and the function name itself (functionFactory).
For example, when we write a simple function that returns a square of its argument we write something like
int square(int n){
    return n*n;
}

Clearly, the type of what we return is on the left and then we write the function name and then what parameters it accepts. So when we return a pointer to a function why don't we write something like:
( int (*function)(int, int) ) functionFactory(int n) { ...

Here the return type (which is a pointer to a function) and its details (e.g. what the function that we point to returns and what it accepts as parameters) is clearly on the left separated and the name of the functionFactory function itself is to the right. To me my version seems much more logical and clear, why don't we write it like that?

A: This falls out of how declarator syntax works.  It may help to think in terms of substitution.  Here's one way to look it:
T    f   (); // f is a function returning T
     |
     v
T  (*p)  (); // p is a pointer to a function returning T
     |
     v
T  (*q())(); // q is a function returning a pointer to a function returning T

So we start with the function declarator f().  Then we replace f with the pointer (*p), giving us the declarator (*p)().  Finally we replace p with the function q(), giving us the declarator (*q())().
Edit
You may hear people talk about the "spiral rule" when reading hairy declarators.  While it's more of a guideline than an actual rule, it falls out of the following precedence rules:
T *a[N];    // a is an array of pointer to T
T (*a)[N];  // a is a pointer to an array of T
T *f();     // f is a function returning T
T (*f)();   // f is a pointer to a function returning T

The postfix [] and () operators have higher precedence than unary *, hence the need for parentheses when declaring pointers to arrays or functions.  So when we read T (*q())();, we start from the leftmost identifier q and "spiral" outwards:
    +-----------+
    | +-------+ |
    | | +---+ | |
    | | |   | | |
    T ( * q ()) ()
      | | | | | |
      | | +-+ | |
      | +-----+ |
      +---------+

Breaking it down piece by piece:
    q        -- q is a
    q()      -- function returning
   *q()      -- pointer to
  (*q())()   -- function returning
T (*q())();  -- T

You cannot declare arrays of function type, nor can you declare functions to return array types:
T a[N]();    // NOT ALLOWED
T f()[N];    // NOT ALLOWED

so in any combination of function and array types, a pointer will always be involved, so the spiral rule holds.

A: The following code declares a variable named func to be a pointer to a function that returns an int and takes two ints as parameters:
int (*func)(int, int);

This syntax mimics the syntax how functions are declared in C:
int func(int, int);

See how similar that is? In fact functions in C are just like variables pointing to functions, e.g. see this sample:
int funcA(int a, int b) { ... }
int (*funcB)(int, int) = funcA;

It plays no role through the rest of the code if you call funcA(a,b) or funcB(a,b), does it? So even though funcB is a variable and funcA a function, the truth is, there's a function somewhere in memory and funcA and funcB are both pointers to the address of the function code.
If you want to nitpick, funcA is a constant and funcB is a variable, so the compiler output for a call to funcA will be different than for funcB; also in one case it is a direct call and in one case an indirect call, as the destination of funcB can change over time. This is also what the asterisk is saying, "I'm not a function, I'm a pointer to a function".
It's important to note that in C the asterisk is always next to the variable name to mark that a pointer variable, so how else would you like to write it instead? Like this?
// Careful! Wrong!
int (int, int) *func;

Does that look more readable to you? Or maybe like that?
// Careful! Wrong!
int ()(int, int) *func;

This syntax is not very clear either and it doesn't mimic any other existing C syntax. If you work a lot with function pointers, pass them around and store them in variables, you should declare an own type for your function pointer:
#include  <stdio.h>

int sum ( int a, int b ) {
    return (a + b);
}

typedef int (* MathFuncType)(int, int);

MathFuncType getSumFunc ( ) {
    return ∑
}

int main(void) {
    MathFuncType func = getSumFunc();
    printf("%d\n", func(3, 8));
    return 0;
}

http://rextester.com/GEKR20461


text:
Q: Is there a benefit in writing code contract instead of straight up check logic code? We are building business application not API for others to use, in this case, I prefer to use our validation logic in the if/then/throw model. I was told, it is better to use Code Contracts. I do not see any benefits, is there any obvious benefits that I am not seeing? I see problem using code contracts since it is static method call and also there is some code injection happens after the compile phase.
Thanks

A: There are two obvious benefits:
(1) The code is much easier to read.
 Contract.Requires(someParam != null && someParam.SomeValue != 0);

versus
if (someParam != null && someParam.SomeValue != 0)
    throw new ArgumentNullException("someParam", someParam, "someParam can't be null and someParam.SomeValue can't be zero.");

Also, with Code Contracts, the predicate code is automatically put into the failure message so you don't need to write an explicit message like you do with normal exceptions.
(2) You can run Code Contracts static analysis on the code and it can find errors for you.
There are some less obvious benefits:
(3) You can generate documentation for the code contracts in the XML doc files.
(4) You can use Contract.Ensures() to express postconditional constraints. This allows you to avoid a lot of code like if (item.Property1 != null && item.Property1.Property2 != null) ... because you will know that neither Property or Property2 can be null.
(5) The code contracts form a block that is clearly separate from the rest of the code.


text:
Q: How to add elements to IList collection using a function I'm just trying to understand an example of WPF treeview.
My goal ist to populate a treeview with some items, stored in a List.
This is the example:
public class Person
{
    readonly List<Person> _children = new List<Person>();
    public IList<Person> Children
    {
        get { return _children; }
    }

    public string Name { get; set; }
}

//Some added nodes:
    public static Person GetFamilyTree()
    {
        // In a real app this method would access a database.
        return new Person
        {
            Name = "David Weatherbeam",
            Children =
            {
                new Person
                {
                    Name="Alberto Weatherbeam",
                    Children=
                    {
                        new Person
                        {
                            Name="Zena Hairmonger",
                            Children=
                            {
                                new Person
                                {
                                    Name="Sarah Applifunk",
                                }
                            }
                        },
                        new Person
                        {
                            Name="Jenny van Machoqueen",
                            Children=
                            {
                                new Person
                                {
                                    Name="Nick van Machoqueen",
                                },
                                new Person
                                {
                                    Name="Matilda Porcupinicus",
                                },
                                new Person
                                {
                                    Name="Bronco van Machoqueen",
                                }
                            }
                        }
                    }
                }

            }
        };
    }

So far it works.
Now I'd like to replace the static persons unter the first parent node with a list that I created before, reading a file.
XDocument ecad = XDocument.Load(openFileDialog.FileName);

GlobalVar.persons = new List<Persons>();    //globally available list
Person person = null;

//Einlesen der XML-Datei in lokale Variable (Model)
foreach(XElement elem in ecad.Descendants("Variable"))
{
    if (elem.Element("Name") != null)
    {
        person = new Person(){ Name = elem.Element("Name").Value };
        persons.Add(person);
    }
}

Now I'd like to add these Persons to a root-person
//GlobalVar.List<Persons> persons
public static Person GetFamilyTree()
{
    return new Person{
        Name = "Family",
        Children = persons
    }
}

So how can I replace the Children = new... with the function that reads the data from file?
I'm really confused

A:
What I think is confusing, Children is a readonly property but with the "static Children" it works, with the IList it doesn't (because of readonly). Can someone explain the difference, please?

Your GetFamilyTree() method uses a nested object initializer. Please refer to Jon Skeet's answer here for more information.
If you intend to read data from some source and then set the Children property, you should add a setter to it. You can also remove the backing field:
public class Person
{
    public IList<Person> Children { get; set; } = new List<Person>();
    public string Name { get; set; }
}


text:
Q: How to extract each line from a file, into separate files in Linux Shell Script How to extract each line from a file, into separate files in Linux
Example :
If the file content 10 rows, it will be 10 files.
if File contents
12345
1uthste
128766
First-line should move to 1.txt
Second-line should move to 2.txt
like this goes on.


text:
Q: How to skip /dev/sda1: clean in booting system? When I start system I see black display with message:
/dev/sda1: clean....blocks

How to skip this step and run Ubuntu? It takes over 3 hours to check HDD 500 gb

A: NOTE: Your question is off-topic for this site. It should be on Ask Ubuntu. But to make things easier, I will answer it here.
Use your favorite text editor to open /etc/fstab (WARNING: Be very careful when editing this file. It controls how your system mounts filesystems on boot).
Find the line for /dev/sda1 At the end of the line, you should see a 1, or 2. Change this to a 0. This tells the system to not run fsck whenever it boots.

A: *

*ctrl+alt+f2 or f3

*login with your account

*type sudo apt-get update (enter password when prompted)

*type sudo apt-get install xserver-xorg-video-intel

*reboot


text:
Q: sql query to select a character by default when the column datatype is int select B_id,amount,amount_paid,case when gr!=0 then gr else '-' end as goods_returned from tbl_addbill;

i even don't know if it is possible or not ,the datatype of column(gr) is int and i want to select (-) when gr !=0,However my query below is working fine,can anyone please tell me how to do this
select B_id,amount,amount_paid,case when gr!=0 then gr else 1 end as goods_returned from tbl_addbill;

A: You can convert gr to a string when gr!=0, for instance case when gr!=0 then CONCAT(gr,'') else '-' end ... (yes, I'm concatenating with an empty string; this converts gr to a string).


text:
Q: How to change function implementation for automatically generated partial class? Visual Studio automatically generated a partial class in my project, containing a function whose implementation I want to change.
Is this doable without losing the changes I made whenever the class is automatically generated again?
Example:
Partial Public Class INO_Opportunity
    Private Function IsLocalFileSystemWebService(ByVal url As String) As Boolean
        ' Here I want to add code

        ' All the following code is generated by VS:
        If ((url Is Nothing) OrElse (url Is String.Empty)) Then
            Return False
        End If

        Dim wsUri As System.Uri = New System.Uri(url)

        If ((wsUri.Port >= 1024) AndAlso (String.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) = 0)) Then
            Return True
        End If

        Return False
    End Function
End Class


text:
Q: Wiping out the development environment Will the three commands

*

*sudo rm -fr /Applications/Xcode.app/

*sudo rm -fr /Library/Developer/

*rm -fr ~/Library/Developer/
completely and safely discard the development environment on macOS for a once-a-decade start-from-fresh-during-major-release upgrade of macOS?
Update
Rather than delete, I renamed the folders in question. The folders have been refilled just fine during update to Big Sur, but renaming, and hence presumably also deleting, is problematic. I am now in an infinite loop of getting the messages "An update is available for your Mac", "Command Line Tools for Xcode 12.4". Yet after clicking "Update Now" and waiting for its completion, the message returns, and another update proceeds, downloading seemingly from scratch.
Update 2
Although /usr/bin/git --version says xcodebuild: error: SDK "macosx10.15" cannot be located., git: error: .. failed, and xcode-select: Failed to locate 'git', requesting installation of command line developer tools., running sudo /usr/bin/git --version runs fine (and reports git version 2.24.3 (Apple Git-128)).
The problem then appears to be that after renaming (and even now that I've restored the renaming) the license agreement is marked as not signed, but git doesn't say so.
Update 3
(Re-)Agreeing to the license agreement from the Terminal by running sudo xcodebuild -license does not help. /usr/bin/git still says "macosx10.15" cannot be located. and xcode-select: Failed to locate 'git'.
And agreeing under the sudo identity is indeed necessary. Attempting xcodebuild -license gives Agreeing to the Xcode/iOS license requires admin privileges, please run "sudo xcodebuild -license" and then retry this command.

A: No, I wouldn't recommend using that method. At the same time, you're risking deleting too much, and not actually deleting the whole thing.
For quite some time now, Xcode can actually be uninstalled simply by dragging the Xcode app from the Applications folder and into the Trash. This will quite significantly delete most of its footprint.
On older systems, you could also open a Terminal and run the following command to uninstall Xcode developer tools:
sudo /Developer/Library/uninstall-devtools –mode=all

A: These days, yes (almost). Xcode has been self-contained for years and you've got most of the directories. The only bits you're missing are com.apple.dt.* files in:

*

*~/Library/Preferences

*/Library/LaunchDaemons

*/Library/PrivilegedHelperTools


text:
Q: Show compactness of a set given by inequalities Show that the subset $A=\{(x_1,...,x_n)\in\Bbb R^n |−1≤x_1 ≤x_2 ≤···≤x_n ≤1\}$ is compact.
A is contain in an open cover as it is contained in $\Bbb R^n$.
Therefore there exists a finite sub cover which is the union of the open balls centred at $x_i$ for $i \in I$ with radius $>2$ implying compactedness. Am I on the right track or where have i gone wrong?

A: You should proceed using Heine-Borel theorem. The set you presented is clearly bounded, and it is closed, therefore, it is compact.
To check that it is closed, simply consider any point $y\notin A$. Then, see that for a sufficient small neighborhood of $y$, $V_y$, then $V_y \subset \mathbb{R}^n\setminus A$. This will follow simply assuming that one of the inequalities defining $A$ does not hold, and seeing that it will not hold for points near $y$.


text:
Q: accumulate not working in Scheme Lang R5RS I solved a problem which involved using map and accumulate but it gave me this error: "accumulate: undefined;" cannot reference undefined identifier.
This is my code:
;Procedure to test it with
(define (double x)
   (* 2 x))

(define (my-map proc sequence)
   (accumulate (lambda (x y) (cons (proc x) y)) '() sequence))

Please can anyone tell me how to fix this problem?

A: The procedure accumulate is not defined in R5RS. But it's simple enough to define your own:
(define (accumulate proc init lst)
  (if (null? lst)
      init
      (proc (car lst)
            (accumulate proc init (cdr lst)))))

For future reference, accumulate is also known as foldr, fold-right, inject or reduce in other programming languages, consult your interpreter's documentation for more details.


text:
Q: scroll to div using useRef in map method i am using useRef to scroll to specific div but it is not working in map method's case (probably because of id) , so can anyone tell me how to provide id. it is taking last element in map method right now.
this is element to which i want to scroll to.
  {allMessages?.map((message) => (

{message.data.text}

          ))}

this is filtered data in which i am getting filtered messages and clicks on specific div.
{filteredMsg?.map((item) => (

 goToFilterData(item.data.id)}
                    key={item.data.id}
                  >
                    {item.data.text}

                ))}

this is what i have done with useRef yet -
 const scrollToRef = (ref) => window.scrollTo(0, ref.current.offsetTop);
  const goToFilterData = (id) => {
    scrollToRef(filterRef);
  };

A: Just pass an id to every element that maybe should scroll into the view.
{allMessages?.map((message) => (
    // the element you want to scroll to
    <div id={`message_${message.someUniqueIdentifier}`} />
))}

Pass the identifier to the scroll function.
{filteredMsg?.map((item) => (

 goToFilterData(item.data.someUniqueIdentifier)}>
       {item.data.text}

))}

Query the element and make it scroll into the view.
const goToFilterData = (uniqueIdentifier) => {
  const element = document.getElementById('message_' + uniqueIdentifier);
  element.scrollIntoView()
};

Note: ofc you could handle this with a lot of single refs and pass them, but this should just work fine.


text:
Q: Update panel not working when validation group is used I have following thing in update panel:
<asp:UpdatePanel ID="upAddProduct" runat="server" UpdateMode="Conditional">
        <ContentTemplate>

                        <asp:Label ID="lblCaption" runat="server"></asp:Label>
                        :

                        <asp:TextBox ID="txtValue" runat="server" ValidationGroup="NewValues"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="regInvData" ControlToValidate="txtValue" ErrorMessage="*"
                            runat="server" ValidationGroup="NewValues"></asp:RequiredFieldValidator>
                        <asp:HiddenField runat="server" ID="hdColType" />
                        <asp:HiddenField runat="server" ID="hdnSku" />

                        <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click"
                            ValidationGroup="NewValues" />

        </ContentTemplate>
</asp:UpdatePanel>

When i click on submit button in above code, btnSubmit_Click does not gets called.
When i removes  ValidationGroup="NewValues"
function gets called.
Before keeping it in update panel everything was working fine.
How to use validationgroup in above case ?
Please help me.

A: Try this,
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:Label ID="lblCaption" runat="server"></asp:Label>

<asp:TextBox ID="txtValue" runat="server" ValidationGroup="NewValues">
 </asp:TextBox>
<asp:RequiredFieldValidator ID="regInvData" ControlToValidate="txtValue"
ErrorMessage="*"
 runat="server" ValidationGroup="NewValues"></asp:RequiredFieldValidator>
<asp:HiddenField runat="server" ID="hdColType" />
<asp:HiddenField runat="server" ID="hdnSku" />

<asp:Button ID="btnSubmit" Text="Submit" runat="server"
OnClick="btnSubmit_Click"  ValidationGroup="NewValues"

</ContentTemplate>
</asp:UpdatePanel>

It works for me


text:
Q: Event-B, formal modelling : How to affect all the elements of a set to a relation I'm having quite a lot of troubles with Event-B..
I'd like to make a relation from a group of client to a client number each
I have a relation of that type :
cli(PERSON) = NAT1        (Person is a finite set)
and in an event I have a subset of person
where group <: PERSON

and I'd like to affect to the cli relation what I'd write intuitively :
! x . x : group | cli(x) = numcli

Am I modelling it the right way? Is there any method to get the affectation I'd like to get?

A: I'm a little bit guessing what you want to achieve: cli maps a person to a number:
VARIABLES
  cli
INVARIANTS
  cli : PERSON +-> NAT1

You want an event (let's call it ev) that assigns to a group of persons (called group) the same number:
ev = ANY
  group, numcli
WHERE
  group <: PERSON
  numcli : NAT1
THEN
  cli := cli <+ (group**{numcli})
END

group ** {numcli} is a set of pairs (a relation) where the first element is an element of group and the second is numcli. The operator <+ (relational override) removes all elements from cli where the first element if one of its right operand and adds the right operand. I.e. mappings of group in cli are replaced or added to a mapping to numcli.


text:
Q: Pygame holding down key I am trying to make a fun program with a guy who opens his mouth whenever a press space. The problem is he only opens it for .1 seconds and then it closes again. I want to make it so that the mouth is open whenever i hold space.
Code:
    import pygame
pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Open The Mouth")
clock = pygame.time.Clock()

faceImg = pygame.image.load("face_shut.png")
faceOpenImg = pygame.image.load("face_open.png")
def face(x,y):
    gameDisplay.blit(faceImg,(face_x,face_y))
def faceOpen(x,y):
    gameDisplay.blit(faceOpenImg,(faceOpen_x,faceOpen_y))

faceOpen_x = (1)
faceOpen_y = (1)

face_x = (1)
face_y = (1)

programRunning = True

while programRunning:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            programRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                faceOpen(faceOpen_x,faceOpen_y)
                pygame.display.update()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                face(face_x,face_y)
                pygame.display.update()

    face(face_x,face_y)
    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

A: The issue appears to be here:
while programRunning:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            programRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                faceOpen(faceOpen_x,faceOpen_y)
                pygame.display.update()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                face(face_x,face_y)
                pygame.display.update()

    #  Here, always drawn closed at the end of the while
    face(face_x,face_y)
    pygame.display.update()
    clock.tick(60)

Regardless of what's being set in the while, you are redrawing the face as closed at the end.
How about this instead:
# Drawn before the loop starts
face(face_x,face_y)
pygame.display.update()

while programRunning:
    for event in pygame.event.get():
        event_occurred = True
        if event.type == pygame.QUIT:
            programRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                faceOpen(faceOpen_x,faceOpen_y)
                pygame.display.update()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                face(face_x,face_y)
                pygame.display.update()

    clock.tick(60)


text:
Q: Get custom taxonomy value of post and output posts in same taxonomy I'm trying to show related videos on my single post template. I've set up a custom taxonomy called 'sub-category' in Posts. I want to get the sub-category of the current post and loop through any posts with the same sub-category, outputting them to the page.
Any ideas on the best way of achieving this?

A: try with this function
function get_posts_in_taxonomy($post_type, $taxonomy, $term_id, $include_children=false, $limit)
{
$args = [
    'post_type'      => $post_type,
    'posts_per_page' => $limit,
    'tax_query' => [
        [
            'taxonomy'         => $taxonomy,
            'terms'            => $term_id,
            'include_children' => $include_children
        ],
    ],
    // Rest of your arguments
];

$posts = new WP_Query( $args );

if($posts->have_posts()) {
    while($posts->have_posts()) {
        $posts->the_post();

        //code todo here

    }
}
} //end func

A: function get_the_terms( $post, $taxonomy ) {
if ( ! $post = get_post( $post ) ) {
    return false;
}

$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
    $terms = wp_get_object_terms( $post->ID, $taxonomy );
    if ( ! is_wp_error( $terms ) ) {
        $term_ids = wp_list_pluck( $terms, 'term_id' );
        wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
    }
}

/**
 * Filters the list of terms attached to the given post.
 *
 * @since 3.1.0
 *
 * @param WP_Term[]|WP_Error $terms    Array of attached terms, or WP_Error on failure.
 * @param int                $post_id  Post ID.
 * @param string             $taxonomy Name of the taxonomy.
 */
$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );

if ( empty( $terms ) ) {
    return false;
}

return $terms;}

A: I think I confused myself on this actually, here's how I did it:
$_terms = wp_get_post_terms($post->ID, 'sub-category', array("fields" => "all"));
        foreach ($_terms as $term) :
            $term_slug = $term->slug;
            $_posts = new WP_Query( array(
                        'post_type'         => 'post',
                        'posts_per_page'    => 4,
                        'tax_query' => array(
                            array(
                                'taxonomy' => 'sub-category',
                                'field'    => 'slug',
                                'terms'    => $term_slug,
                            ),
                        ),
                    ));
            if( $_posts->have_posts() ) :
                while ( $_posts->have_posts() ) : $_posts->the_post();
                    //Output
                endwhile;
            endif;
            wp_reset_postdata();
            endforeach;


text:
Q: RegEx match of a string Im working and a fun project with c# and now I have a problem with my RegEx.  I have tried some varitations but didnt found a solution for this. I want a RegEx for this string "##Test1##".
So I have tried this RegEx here:
[\#]{2}[a-zA-Z0-9]{1,}[\#]{2}

And its working fine but my problem is that,
When passed "###Test1###" the RegEx ignores the first and last # and matches on the inner "##Test1##".
But I dont want that.
The RegEx only should match to this string ##Test1##.
Hopefully here are some guys who can help me with that problem.
Greetings,

A: If the regular expression should only match the string you've specified, here's your regular expression:
^##Test1##$

If you want it to match a string like "##(any digit or letter here)##", then this will work:
^##[a-zA-Z0-9]+##$

This will match strings like
##abc##
##123##

but not
###xxx###     <-- 3 #'s

I think the main part you're looking for here are these two symbols:
+------------------- matches the beginning of the string
|                +-- matches the end of the string
v                v
^##[a-zA-Z0-9]+##$

These two will make sure you're not searching to the string to see if your pattern exists inside it, but you're instead checking if the string matches the pattern completely.

A: This will match the required string when standing alone, and also if it is embedded in a longer character sequence:
[^#]*##[a-zA-Z0-9]+##[^#]*

Hello##World##! -> matches=true
##World##       -> matches=true

Hello##World### -> matches=false
###World###     -> matches=false

A: Well, thats because is contained inside, so is obviously right. What about with "excluding" characters like at the end/beginning .^#* but obviosly that only works if you want to avoid just that character...


text:
Q: using object in another js file I am getting my hands on node.js and I am trying to understand the whole require/exports thing. I have the following main app.js file:
/app.js

var express  = require('express'),
    http     = require('http'),
    redis    = require('redis'),
    routes   = require('./routes'),

var app    = express(),
    client = redis.createClient();

// some more stuff here...
// and my routes

app.get('/', routes.index);

then, I have the routes file:
exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};

I can of course use the client object on my app.js file, but how can I use the same object in my routes?

A: The easiest way is to export a function from your routes file that takes a client, and returns an object with your routes:
exports = module.exports = function (client) {
    return {
        index: function (req, res) {
            // use client here, as needed
            res.render('index', { title: 'Express' });
        }
    };
};

Then from app.js:
var client = redis.createClient(),
    routes = require('./routes')(client);

A: Since req and res are already being passed around by Express, you can attach client to one or both in a custom middleware:
app.use(function (req, res, next) {
  req.client = res.client = client;
  next();
});

Note that order does matter with middleware, so this will need to be before app.use(app.router);.
But, then you can access the client within any route handlers:
exports.index = function(req, res){
  req.client.get(..., function (err, ...) {
    res.render('index', { title: 'Express' });
  });
};