text:
Q: Improving performance with a array of million records I do have a array with million String objects..
ex:String values [] = new String[10000000]

and I've to reverse all the elements and what is the best way of doing it to improve performance?

A: You are making you task harder than it needs to be by not using the Collections standard library. Instead of an array use a List then use the standard Collections.reverse() method.
List<String> list = Arrays.asList(values);
Collections.reverse(list);


text:
Q: Does the MSBuild SonarQube Runner support C++ projects? We have Visual Studio Solutions which may consist of C# and C++ (CLI) projects. At the moment we are using the C# and C++ Community Plugins together with the SonarRunner to analyse our code.
Now the C# plugin marks the SonarRunner as deprecated. Does someone know if the MSBuild runner can utilize the C++ Community Plugin?
Best Regards.

A: Yes, MSBuild runner uses sonar-runner internally to perform the analysis and publishing of issues to SonarQube server. So everything that sonar-runner supports, should work with MSBuild runner as well. See this thread - Relationship between SonarQube Runner and SonarQube.MSBuild.Runner

redpajama_set_name: RedPajamaStackExchange


text:
Q: asp web api DateTime model binding I'm having quite some trouble with binding DateTimes in web api. Here is the situation. I have a controller that returns a model with a DateTime property. I've set up my web api to use IsoDateFormat and UTC time in the global.asax like this:
        HttpConfiguration config = GlobalConfiguration.Configuration;
        config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
        config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;

The datetime format gets returned to the client in this format:
2013-02-04T11:24:48.91Z
Everything is working great on  that side. But if i post it back in that same format the model binder doesnt recognize that property and leaves it null. What format do input datetimes need to be in order for the default DateTime model binding to work?

A: I have configured my Web API service the way you have specified, and I was able to post a DateTime of the format you have specified.  Do you have [FromBody] for your DateTime parameter? Primitive types are [FromUri] by default.
public DateTime Post([FromBody]DateTime date)
{
    return date;
}

Request:
POST http://localhost/api/values HTTP/1.1
content-type: application/json
Content-Length: 25

"2013-02-04T11:24:48.91Z"

Response:
HTTP/1.1 200 OK
Content-Length: 25
Content-Type: application/json; charset=utf-8

"2013-02-04T11:24:48.91Z"


text:
Q: PHP Regex to match url contains url fragment I have one url fragment: page/login and i need to know if another url fragment contains them.
These, will match:
/admin/page/login/
/admin/page/login
admin/page/login
http://www.dot.com/admin/page/login
/admin/page/login?id=10
/admin/page/login/id/10
/admin/page/login/?id=10
/admin/page/login/user?id=10
/admin/page/login/user/?id=10
page/login
page/login/
page/login/id/10
/page/login/id/10

And these not:
/admin/firstpage/login
admin/page/loginOk
/admin/page/loginOk/id/10
mypage/login/id/10
/mypage/login/id/10
mypage/login

I tried: page\/login[\/\s\?], \/?page\/login[\/\s\?] without any result

A: You can use a word boundary so partial matches aren't matched.
\bpage\/login[\/\s?]

Demo: https://regex101.com/r/yhNsdw/1/
Also if you change your delimiter none of the forward slashes will need to be escaped.


text:
Q: how can compile and execute java file in php? I have two file.

*

*Hello.java

*Index.php
Hello.java
class Hello
{
    public static void main(String args[])
    {
        System.out.println("HelloWorld");
    }
}

Index.php
$file="Hello.java";
exec('javac'.$file,$output,$resultCode);
if ($resultCode===0)
{
    echo "Result: " . $resultCode . "\n";
}
else
{
    echo "fail";
}

It give "Fail" output i want to get "HelloWorld" output on browser.
please help me.

A: You have not provided a space between your command and arguments.
exec('javac'.$file,$output,$resultCode);

should be
exec('javac '.$file,$output,$resultCode);

This part just completed the compiling then you need another exec statement to completed the execution of the program. As suggested by mthmulders
exec("java -cp . Hello", $output,$resultCode);


text:
Q: Remove first useless productions and then unit productions? When transforming a Context-free grammar into Chomsky Normal Form, we first remove null-productions, then unit-productions and then useless productions in this exact order.
I understand that removing null-productions could give raise to unit-productions, that's why unit is removed after null-productions.
I do however not understand what could go wrong if we first removed useless-productions and then unit?

A: If you remove the unit production A → B and that was the only place in the grammar where B was referenced, then B will become unreachable as a result of unit-production elimination, and will need to be removed along with its productions.
That condition requires B to be non-recursive (since a recursive non-terminal refers to itself, and presumably not with a unit production), and any non-terminals referenced in the productions of B will still be referenced, having been absorbed into productions for A.
If the grammar does not have a cycle of unit productions allowing A →* A, then unit productions can be topologically sorted and removed in reverse topological order, which guarantees that the unit production elimination doesn't create a new unit production. That makes it possible to remove newly-unreachable non-terminals as you do the unit-production elimination. But I think that textbook algorithms probably don't do that, which is presumably why your textbook wants you to remove useless productions after the grammar has been converted to CNF. (And, of course, there's nothing stopping a grammar from having a cycle of unit productions. Such a grammar would be ambiguous, making it difficult to use in a parser, but this exercise doesn't require that the grammar be useful in a parser.)
Similarly, if the only production for a non-terminal is an ε-production, then that non-terminal will end up with no productions after null-productions are removed (and it will also be unreachable). Again, that could be handled in a way which doesn't require deferring reachability analysis, but the textbook algorithm probably doesn't do that.


text:
Q: How can a vector field eat a smooth function? I was watching this Frederic Schuller's lecture on Grassmann algebra and de Rham cohomology. I don't understand. At 43:40 it looks like a vector field is eating a smooth function.
The $X_i$ should be a vector field, that is a section of a smooth tangent bundle. So it should map a point on the manifold to one of the point's tangent vectors. But omega is a $0$-$n$ tensor field, that is, a function that takes n vector fields and outputs a smooth function (manifold $\to \mathbb R$). So how can you give the $X_i$ a smooth function when it should eat a point of the manifold? What am I missing?

A: Given $\vec{v} = (v^1,...,v^n) \in \mathbb{R}^n$ and $f: \mathbb{E}^n \to \mathbb{R}$. Then  we define $\vec{v}[f] = \sum_j \frac{\partial f}{\partial x^j} v^j$. Given a vector field $X: U \to \mathbb{R}^n$  we have $X_p \in \mathbb{R}^n_p$. We can choose a basis $e^1_p,...,e^n_p$ at $\mathbb{R}^n_p$ such that,
$$X_p = \sum_i a(i,p) \ e^i_p$$

*

*We then identify $X_p$ with its coordinate form i.e $(a(1,p),...,a(n,p)) \in \mathbb{R}^n$. Then we let $X[f]$ be the vector field such that,

$$ X[f] (p) := X_p[f] = \sum_j \frac{\partial f}{\partial x^j}  \cdot a(j,p)$$

*

*Here we write $[f]$ to be the germ class of $f$. The germ class of a smooth function $f$ at $p$ are all the other smooth functions which agree with $f$ on a neighborhood of $p$. Recall that such functions have the same directional derivative.

*The whole reason behind all this is that it can be shown that derivations at $p$ are isomorphic to the tangent space at a point, which are just vectors. To see this full carried out, see Loring Tu's "Introduction to Manifolds".

A: You can find this in Schuller's lecture on Differential Structure during the aside on derivations and algebras.
Recall that a tangent vector $X_{\gamma,p}\in T_pM$ is nothing but a derivation $D:C^\infty(M)\rightarrow \mathbb{R}$ defined by $X_{\gamma,p}\mapsto X_{\gamma,p}f = (f\circ \gamma)'(0)$.
When you apply $X\in \Gamma(TM)$ to a smooth function on $M$, you obtain a real number for each $p\in M$, i.e. a smooth function on $M$. So a vector field on $M$ is nothing but a derivation $D:C^\infty(M)\rightarrow C^\infty(M)$ defined exactly as in the comments: $X\mapsto Xf$ where $(Xf)(p) = X(p)f=X_{\gamma,p}f$ for all $p\in M$.


text:
Q: Use custom maven plugin to provide compile dependencies for project Is it possible to write a custom maven plugin that defines dependencies that are available in the compile scope of the project using that plugin?
Example:
Using kotlin, I have to define some dependencies in the pom and a build-compiler-plugin that also defines plugin.dependencies.
What I would like to do is write a custom plugin, that uses the kotlin compile but also (somehow) exposes the kotlin-lib dependencies to the compile-scope, so all you have to do is to include one build-plugin and you get the IDE-dependencies + the compile behavior.
It would be similar imho to the build-helpers option to add additional resources to the build, but with additional dependencies.


text:
Q: Is my MVC3 Password Handling Adequate I have read a ton of articles about how to store and compare entered passwords, some old and some new, but all different.  Therefore, I took what I thought to be the best options and implemented the following.
Note that I created my own authentication provider and I am not using nor inheriting from the standard MS MembershipProvider (too bloated).  This is for a lighter volume site that does not need to be "uber-secure", but I would like to follow best practices.  I would just like some validation that I am not doing anything glaring wrong or opening up security holes.  Also, I looked at per-user password salting, but it seemed overly complex for my needs.  Is that a valid assumption?
First, I put the following appSettings key in my web.config, which is returned by my configurationProvider class.
<add key="PasswordEncryptionKey" value="qTnY9lf...40 more random characters here" />

Here is my code that publically Authenticates a user and privatly Checks the stored password against what what was entered as well as Encodes the password when saving.  I have not shown the add or update password methods as they use the same private methods.
public bool Authenticate(string emailAddress, string password, bool setAuthCookie = false)
{
  bool isAuthenticated = false;
  var member = _memberRepository.Find(m => m.Email == emailAddress).SingleOrDefault();
  if (member != null)
  {
    if (CheckPassword(password, member.Password))
    {
      isAuthenticated = true;
      FormsAuthentication.SetAuthCookie(emailAddress, setAuthCookie);
    }
  }
  return isAuthenticated;
}

private bool CheckPassword(string providedPassword, string storedPassword)
{
  return EncodePassword(providedPassword) == storedPassword;
}

private string EncodePassword(string password)
{
  var hash = new HMACSHA1
               {
                 Key = Encoding.ASCII.GetBytes(_configurationProvider.PasswordEncryptionKey)
               };
  string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
  return encodedPassword;
}

My only rules are:

*

*The password must be asynchronously encrypted in the database and can't be decrypted.

*The method should be reasonable safe against dictionary or other attacks (I'm not developing a FDIC insured site, just a basic intranet)

With this, is there anything glaring that I'm missing?

A: I believe your scheme is adequate, but it can be improved upon a little bit.
It seems to me that you have the beginnings of a salting scheme here, with your EncryptionKey that you have in your app.config file.  However, for best security practices, generally people use a different salt for each password, and store the salt alongside the hash in the database.
class MyAuthClass {
  private const int SaltSize = 40;
  private ThreadLocal<HashAlgorithm> Hasher;

  public MyAuthClass ()
  {
    // This is 'ThreadLocal' so your methods which use this are thread-safe.
    Hasher = new ThreadLocal<HashAlgorithm>(
      () => new HMACSHA256(Encoding.ASCII.GetBytes(_configurationProvider.PasswordEncryptionKey)
    );
  }

  public User CreateUser(string email, string password) {
    var rng = new RNGCryptoServiceProvider();
    var pwBytes = Encoding.Unicode.GetBytes(password);
    var salt = new byte[SaltSize];
    rng.GetBytes(salt);

    var hasher = Hasher.Value;
    hasher.TransformBlock(salt, 0, SaltSize, salt, 0);
    hasher.TransformFinalBlock(pwBytes, 0, pwBytes.Length);
    var finalHash = hasher.Hash;
    return new User { UserName = email, PasswordHash = finalHash, Salt = salt };
  }

With a scheme such as this, your passwords are made more complex because if an attacker happened to get the hashes, he'd have to also guess the salt during a brute-force attack.
It's the same philosophy as your EncodingKey in your configuration file, but more secure since each hash has its own salt.  Checking entered passwords is similar:
  public bool IsPasswordCorrect(User u, string attempt)
  {
    var hasher = Hasher.Value;
    var pwBytes = Encoding.Unicode.GetBytes(attempt);
    hasher.TransformBlock(u.Salt, 0, u.Salt.Length, Salt, 0);
    hasher.TransformFinalBlock(pwBytes, 0, pwBytes.Length);
    // LINQ method that checks element equality.
    return hasher.Hash.SequenceEqual(u.PasswordHash);
  }
} // end MyAuthClass

Of course, if you'd rather store the hashes as strings rather than byte arrays, you're welcome to do so.
Just my 2 cents!

A: A few thoughts...

*

*You should use HMACSHA256 or HMACSHA512 instead of HMACSHA1.  .NET4's default hashing algorithm is SHA256 now instead of SHA1.

*When you get the bytes of your encryption key, you use the ASCII encoding, but you're computing the hash using the Unicode encoding.  Keep them consistent - use Unicode.

*Consider salting your hash.

*You say encryption, but you're really hashing.


text:
Q: Disable media key actions on KDE Plasma lock screen It is a neat feature that there is a whitelist for certain key actions while the KDE Plasma lock screen is active. These whitelisted actions include volume and brightness control, and also media key actions. Here's a bit of the story behind it.
And here is a question about how to turn off the media control switches visible at the lock screen.
However, turning off the controls at the lock screen does not prevent the actions of media control keys (play/pause, switch track) to go through to any open applications playing media. This seems like a privacy concern to me.
Is there a way to deactivate media key actions when the lock screen is active? Or can the deactivation of graphical control switches be coupled to a deactivation of media key actions?


text:
Q: How to display a centered background of fixed width I have web pages with a boring white background and all their contents (the website logo and several google charts) are of the fixed width 700px and centered:
    h1,h2,h3,p,div,form {
    text-align: center;
}

I'd like to add a vertically-tiled png image underneath (just a stripe of 1px height), which would display a fixed width 800px of white and the rest should be some other color (like red in the example below) or gradient and should grow
 with the page width:

How do you do it best (i.e. most reliable and for most browsers) with CSS or HTML?

A: You'll need to put your content into a container of 800px in order to achieve both, the red or gradient background and the striped PNG effect. So all your content would then go into a .container div and your styles would be:
body{
   background:#ff0000;
}

.container{
    width:800px;
    margin:0 auto;
    position:relative;
    background:url('/path/to/image/image.png') repeat 0 0;
}

So all your content which currently appears in the body tag, will have to be placed in the .container div tag like so:

        .....

Ideally, if you're targeting a minimum screen resolution of 800 x 600, your .container width should be lesser than 800 to avoid the horizontal scrollbar.
You might also find the links below useful in trying to create both, cross-browser gradients and the PNG:

*

*Stripe Generator - http://www.stripegenerator.com/

*CSS gradient creator - http://www.colorzilla.com/gradient-editor/
The gradient creator above creates gradients using CSS and also has support for IE. In IE however, since the gradients are created using IE filters, it tends to cut any content hidden inside it, instead of allowing it to overflow. You can always also just use an image to create the gradient.
You might also want to consider using CSS PIE, for IE compatibility - http://css3pie.com/
Hope this helps.

A: If you want to add a 1px height image as the backgound, find the below code
/*CSS*/
 body
 {background:#ff0000;}

 .main
 {
  text-align:center;
  width:800px;
  background-image:url('http://i.stack.imgur.com/LNBYu.png');
  background-repeat:y-repeat;
  background-position:center;
  min-height:300px;
 }

/*HTML*/

     Your Content Goes Here

You can see the result as follows.... (Here I'm repeating the 1px height image vertically, so you can see your background is filled with the image)

or Click here to See the Result
Hope this help you !! Any other questions on top of this, pls do comment !


text:
Q: How to build file to be used in Gephi 0.9.1? I have an adjacency matrix obtained by:
n1=4;
f[i_, j_] := If[j > 1, RandomInteger[], RandomInteger[]];
s1 = SparseArray[{{i_, i_} -> 0, {i_, j_} -> f[i, j]}, {n1, n1}];

This matrix contains 0 and 1.
From the matrix, I'd like construct a list of items which contains 3 columns, whose first line is written: source, target and type. Below of the "type" will write "Directed". The elements non-zero of the matriz are connect by lines and column. In this elements non-zero, the number of the line is "source" and the number of the column is "target", as in a graph. The file will be export in format .csv.
For example: If the adjacency matrix is {0,1,0,1}, {1,0,0,1}, {0,1,0,0}, {1,0,1,0} the file wiil be of the type:
Source;Target;Type
1;2;Directed
1;4;Directed
2;1;Directed
2;4;Directed
3;2;Directed
4;1;Directed
4;3;Directed
Can somebody help me?


text:
Q: How can I simplify this Apache rewrite? In ~/public_html/foo I have an .htaccess file which appends a .php extension to non-existing files:
RewriteEngine On
RewriteBase /~august/foo
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule .* $0.php

Ideally, I would like to make this .htaccess file independent of where the project folder foo is stored. Is there a way to rewrite(!) the rules to eliminate /~august/foo?

A: Create a rewrite condition which "extracts" the /~username/projectdir part of the request URI (or an empty string if not present) and prepend it in the rewrite rule:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteCond %{REQUEST_URI} ^(/~[^/]*/[^/]*/)?
RewriteRule (.+?)/*$ %0$1.php


text:
Q: Anchor href being added on URL I have the #all anchor being added at the end of each URL on pages that I am running the below
 list and cant seem to figure out why.  It shows up on page load with no click functions being run.
URL is showing as  http://domain.com/event/event-name/#all
The only thing that references the #all is:

All

Entertainment

        ...

Featured

Question is why does the #all appear on page load for each page having hte above
?


text:
Q: How to understand the "SIZE" output of the command top on FreeBSD I am working on a VPS with 512 of RAM, I installed mysql, run the command top and found that the value of SIZE for mysql is 638M:
last pid:  2023;  load averages:  0.17,  0.19,  0.21                                                                                up 0+03:05:43  19:26:01
27 processes:  1 running, 26 sleeping
CPU:  0.4% user,  0.0% nice,  1.2% system,  0.0% interrupt, 98.4% idle
Mem: 60M Active, 216M Inact, 94M Wired, 59M Buf, 104M Free
Swap: 1024M Total, 1024M Free

  PID USERNAME       THR PRI NICE   SIZE    RES STATE    TIME    WCPU COMMAND
 1324 mysql           30  20    0   638M   168M uwait    2:12   0.00% mysqld

From the man page I got this:
SIZE is the total size of the process (text, data, and stack)
Having only 512M of RAM on the VPS, I though I was consuming all memory but based on the MEM line seems that not:
Mem: 60M Active, 216M Inact, 94M Wired, 59M Buf, 104M Free

Therefore I would like to know what more  detail how the SIZE and RES are calculated and how to  properly interpret them.

A: What you are looking for is the RES column, which is the actual memory (RAM) used by the process. SIZE also includes files that are maped by the process (so if those are large SIZE goes up, but the files are still stored on you hard drive).


text:
Q: How to design a singleton class in C++ on Linux using boost::call_once? I am designing a thread-safe singleton class in C++ on Linux using boost::call_once.
I got the following compiler error:
/tmp/ccLanvZI.o: In function `SingleTon::getInstance()':
singleTon.cpp:(.text._ZN9SingleTon11getInstanceEv[SingleTon::getInstance()]+0x1b): undefined reference to `SingleTon::p'
/tmp/ccLanvZI.o: In function `SingleTon::makeInstance()':
singleTon.cpp:(.text._ZN9SingleTon12makeInstanceEv[SingleTon::makeInstance()]+0x21): undefined reference to `SingleTon::SingleTon()'
singleTon.cpp:(.text._ZN9SingleTon12makeInstanceEv[SingleTon::makeInstance()]+0x2c): undefined reference to `SingleTon::p'
collect2: ld returned 1 exit status
make: *** [singlton] Error 1

After seeing some posts, I still do not know how to handle this error.
How do I change the void (SingleTon::)() to void (*)()?

#include <iostream>
#include <pthread.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/once.hpp>
#include <boost/bind.hpp>
#include <boost/threadpool.hpp>
#include <boost/thread/thread.hpp>

boost::once_flag flag = BOOST_ONCE_INIT;

class SingleTon
{
    private:
        static SingleTon *p;
        SingleTon();
        SingleTon(const SingleTon&);
        SingleTon& operator=(const SingleTon&);
        void makeInstance();

    public:
        SingleTon* getInstance();

        ~SingleTon()
        {
            if (p)
                delete p;
        }
};

void SingleTon::makeInstance()
{
    p = new SingleTon;
    return;
}

SingleTon* SingleTon::getInstance()
{
    boost::call_once( makeInstance  , flag); // error !!!
    return p;
}

int main()
{
    SingleTon *s;
    s = SingleTon::getInstance();
    return 0;
}

A: The error indicates boost::call_once doesn't work on member function pointers. This is because you forgot to make both makeInstance and getInstance static.

A: Why have you written a destructor? Which instance do you plan to destroy?  Oh wait, there's only one, cos it's a singleton, so in that case why does the destructor try to delete the instance? Infinitely recursive failure.
Singletons smell anyway, avoid them.

A: As AardvarkSoup (tasty and nutritious) pointed out, you need makeInstance() and getInstance() to be static.
Also, you need to define SingleTon(), not just declare it, since it's used in makeInstance().
Finally, you need to initialise the static member p, like:
SingleTon* SingleTon::p(nullptr);

This makes the code compile.  However, designing a thread-safe singleton class is non-trivial.  See this question for piles of links to very full explanations as to why you should try and avoid using singletons.


text: Q: Is it posible to create audio file from AudioTrack Streaming in Android? I need to create audio file when the Streaming AudioTrack is being run. I am thinking to create audio file because when I use the MediaRecorder with AudioSource.MIC, some noises in the background were also recorded. I need a clean audio. Anyone knows a way to do this or maybe any idea or solutions?


text:
Q: Why do i get the FB ID without an app request? I debug the AppId with this snippet:
$this->facebook->getUser()

What happens:

*

*The User comes first to my App it outputs: "0"

*The User confirmed the App Request it outputs: "0000123456789"

*The User is deleting the Apprequest in his settings it still outputs: "0000123456789"

someone knows its possible Facebook still sending me his/her App ID...
Normally its ok but for me as developer its like hell to debug or test my application.

A: These seems to be the defaults of the variables used. Make sure that your server address is whitelisted (by you) on facebook application page, and also make sure the configuration you use is correct.


text:
Q: How to mock nested requests? I'm trying to create unit test ans mock it with sinon. Here is my simple app:
var request = require('request');

var MY_CLASS = {
    getData: function (req, res, next) {
        return request.get({
            uri: 'https://xxxx.xxxx.com',
        }, function (error, data) {
            if (error) {
                return next(error, null);
            }

            request.get({
                uri: `https://yyyy.yyyy.com/${data.id}`,
            }, function (error, data) {
                if (error) {
                    return next(error, null);
                }

                return next(null, data);
            });
        });
    }
};

module.exports = MY_CLASS;

Now, how do I properly mock each request in my test suite for getData function? Seems this one will mock both xxxx.com and yyyy.com. In other words I want to mock different response for each one
before(()=>{
    sinon
    .stub(request, 'get')
    .yields(null, {statusCode: 200, id: 10});
});

A: You could you onFirstCall, onSecondCall, onCall(n) etc to implement the behavior.
before(()=>{
    sinon
    .stub(request, 'get')
      .onFirstCall().yields(null, {statusCode: 200, id: 10})
      .onSecondCall().yields(null, {statusCode: 200, id: 11}};
});

Ultimately you could use callsFake(fn) that implements whatever logic you need.


text:
Q: query using the where clause if variables are not null i am trying to query without success, what i am trying to do is that
  ALTER PROCEDURE [dbo].[spPagination] -- ORDER BY id
  @filterCol NVARCHAR(20) = NULL, --<<<<
  @filterValue NVARCHAR(40) = NULL, --<<<<
  @PageNumber INT,
  @PageSize   INT
AS
BEGIN
  SET NOCOUNT ON;
        SELECT      Emp.id , Emp.email, Emp.[firstName], Emp.[lastName], Emp.[salary], Emp.[startDateWork], Emp.age  , Rol.[name] as Role
    FROM        [dbo].tblEmployees5m    Emp
    inner join  [dbo].[tblRoles]        Rol
    ON          Emp.roleId = Rol.id
    WHERE       @filterCol like '%' + @filterValue + '%' --<<<<
    ORDER BY    id
    OFFSET      @PageSize * (@PageNumber - 1) ROWS
    FETCH NEXT  @PageSize ROWS ONLY OPTION (RECOMPILE);

    select count(1) as totalCount from [dbo].tblEmployees5m
END

i am trying to apply filter to the result, according to @filterCol and @filterValue - if they are not NULL then I want to return the results with the where clause (which don't work now).
ELSE, if there 2 values are NULL then don't apply the where clause.
@filterCol will hold the column name.
@filterValue will hold the column value.
how can I achieve that? there is a better way?

A: Here's the code:
ALTER PROCEDURE [dbo].[spPagination] -- ORDER BY id
    @filterCol NVARCHAR(20) = NULL, --<<<<
    @filterValue NVARCHAR(40) = NULL, --<<<<
    @PageNumber INT,
    @PageSize   INT
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL NVARCHAR(MAX)

    SET @SQL = 'SELECT      Emp.id , Emp.email, Emp.[firstName], Emp.[lastName], Emp.[salary], Emp.[startDateWork], Emp.age  , Rol.[name] as Role
    FROM        [dbo].tblEmployees5m    Emp
    inner join  [dbo].[tblRoles]        Rol
    ON          Emp.roleId = Rol.id
    '
    IF @filterCol IS NOT NULL
    BEGIN
        SET @SQL = @SQL + 'WHERE       [' + @filterCol + '] LIKE ''%' + @filterValue + '%'''
    END

    SET @SQL = @SQL + '
    ORDER BY    id
    OFFSET      ' + CAST((@PageSize * (@PageNumber - 1)) AS VARCHAR(50)) + ' ROWS
    FETCH NEXT  ' + CAST(@PageSize AS VARCHAR(25)) + ' ROWS ONLY OPTION (RECOMPILE);'

    EXEC sp_executesql @SQL

    select count(1) as totalCount from [dbo].tblEmployees5m
END

As has been mentioned, dynamic SQL is vulnerable to SQL Injection, so take care when utilising dynamic SQL that you're sufficiently protected against these attacks.
SQL Injection Protection: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet


text:
Q: How to add variables to a dataframe using paste? I have a set of R objects named c1,c2,c3,...,c10 each with same length and like to form a dataframe from these objects. I could do it by df<-data.frame(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10). Is there a more efficient way of doing this, perhaps using paste?
Thanks for your help.

A: data.frame(sapply(paste("c",1:10,sep=""),get))

or,
data.frame(mget(paste("c",1:10,sep=""),.GlobalEnv))


text:
Q: How to check if data already exists on table? so, I have some problem checking if table got some data
So, I coded the following in Mysql
DECLARE ifnumber INT DEFAULT 0;
SELECT CASE WHEN id IS NULL
    THEN 1 ELSE 0 END AS result INTO ifnumber FROM { table } WHERE { column } = { data };
IF ( ifnumber = 1 ) THEN
    blah blah blah
END IF;

It works when the table contains data, but it doesn't when the table is null.
some help?
Ps: I was trying to do an IF with the Exists() function but didn't work for me.

A: EXISTS isn't a function...
But if you just want to check if there's any record matching a WHERE clause in a table, you might indeed use EXISTS.
IF EXISTS (SELECT *
                  FROM elbat
                  WHERE ...) THEN
  ...
END IF;


text:
Q: Why am I getting Error in mounted hook: "TypeError: e is undefined"? I have a pretty straightforward component in vue that executes a function from a mounted hook once the component has loaded.
methods: {
    pushFolders: function() {
      $.each(this.$store.state.folders.subFolders, function(key, value) {

        this.selected.push(value.uuid)

      }.bind(this));
    },
    checkAll: function(){

      this.isSelectedAll = !this.isSelectedAll;
      this.selectedFolders = [];
      if(this.isSelectedAll){ // Check all
        // this.selectedFolders.push(this.selected[key]);
        this.$store.dispatch('SELECT_FOLDERS',this.selected)
      }
    }
  },
  mounted: function() {
    this.pushFolders()
  }

When I load the route the component is on I get this error:
Error in mounted hook: "TypeError: e is undefined"

Can anyone shed some light on this?

A: You can try with nextTick
(solution found here)


text:
Q: Testing Scipy; get "No module named msvccompiler in numpy.distutils; trying from distutils" I'm trying to test my scipy install by installing nose and entering
import scipy
scipy.test('1','10')

I get some 200 errors but one of the more common is:
.... No module named msvccompiler in numpy.distutils; trying from distutils
Missing compiler_cxx fix for MSVCCompiler

I have MS Virtual Studio 2009 installed (required for python 2.7)
Can anyone help me eliminate that error or tell my why I can't?
Thanks

A: You have to do 2 things to make it find the Visual Studio Compiler:

*

*In your environment, set VS90COMNTOOLS=%VS__vvv__COMNTOOLS% where vvv is your installed version. See other related questions on stackoverflow about setup.py and vcvarsall.bat

*Run python from a Visual Studio Developer Command Prompt. VS includes a link for this in the start menu. It sets up all the environment variables you need to run the compilers and related tools from the command line.

A: Best solution to this could be using the Anaconda Python distribution
It has most of the engineering and data analysis packages and automatically sets path of the C++ compiler. You can easily install numpy, scipy, matplotlib etc. using Anaconda. It will not show vcvarshall.bat as well as numpy.core.multiarray error for numpy


text:
Q: Get name of the named range corresponding to the given range How can I get name of the Excel named range from cell range?
For example, I'm naming "A1" cell as "Test" in Excel editor, then I want to get this name in C# from "A1" Excel range.
Following is what I tried but it`s not giving me the result I require.
Xcelrng = (Excel.Range)Excel.Application.Cells[XcelRow, XcelCol];

From any other excel elements like value, formula, address I use, I am also unable to get the name of the named range.

A: If you want to get a range of cells you may try like this:
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range x = (Excel.Range) worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[10,10]);

And if you are looking to get the names then try like this:
Workbook.Sheet.Names("Test").RefersToRange.Value;


text:
Q: deleting data from from firebase and recyclerview I am fairly new to firebase and im scouring the internet and forums about this problem, so the alert dialog is working but its not deleting any data on my firebase realtime database, what i want to happen is to delete the data and also delete the entry of that data in the recyclerview.
heres the code to the adapterview
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

ArrayList<Model> mList;
Context context;
Task<Void> databaseReference;
private DatabaseReference mDatabase;

public MyAdapter(Context context, ArrayList<Model> mList){
    this.mList = mList;
    this.context = context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(context).inflate(R.layout.item , parent, false);
    return new MyViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    Model model = mList.get(position);
    holder.firstname.setText(model.getFirstname());
    holder.lastname.setText(model.getLastname());
    holder.address.setText(model.getAddress());
    holder.mobilenumber.setText(model.getMobilenumber());
    holder.wash.setText(model.getWash());
    holder.dry.setText(model.getDry());
    holder.fold.setText(model.getFold());
    holder.press.setText(model.getPress());
    holder.weight.setText(model.getWeight());
    holder.totalprice.setText(model.getTotalprice());

    holder.buttondelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder=new AlertDialog.Builder(holder.firstname.getContext());
            builder.setTitle("Delete Panel");
            builder.setMessage("Delete...?");

            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String useridd = FirebaseAuth.getInstance().getUid();
                    databaseReference = FirebaseDatabase.getInstance().getReference().child("Soft Orders")
                            .child(useridd).removeValue();
                }
            });

            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });

            builder.show();
        }
   });

}

@Override
public int getItemCount() {
    return mList.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder{

    TextView firstname, lastname, address, mobilenumber, wash, dry, fold, press, weight, totalprice;
    Button buttondelete;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);

        firstname = itemView.findViewById(R.id. Textviewfirstname);
        lastname = itemView.findViewById(R.id. Textviewlastname);
        address = itemView.findViewById(R.id. Textviewaddress);
        mobilenumber = itemView.findViewById(R.id. Textviewmobilenumber);
        wash = itemView.findViewById(R.id. Textviewwash);
        dry = itemView.findViewById(R.id. Textviewdry);
        fold = itemView.findViewById(R.id. Textviewfold);
        press = itemView.findViewById(R.id. Textviewpress);
        weight = itemView.findViewById(R.id. Textviewweight);
        totalprice = itemView.findViewById(R.id. Textviewtotalprice);
        buttondelete = itemView.findViewById(R.id. Buttondelete);

    }
}

}


text:
Q: Ranking batters by average when number of observations (innings) vary This is my first post here and I'm new to this area so please forgive me if I'm asking a naive question.
I want to rank a number of batsmen (e.g., in cricket) by their skill. I'm planning to use batting averages as a measure of skill.
But there are some batsmen who have only been to bat a few times and therefore their average is not a good estimate of performance (I.e., I don't have a very good estimate of their "true" average).
Assuming that, for each batsman, I only have scores of each time he came to bat (e.g., 89 4, 92, 45, ... ).
How could I best sort them?
Thanks in advance.

A: "Best" is impossible to answer since you don't give a criterion you want to optimize (that is, until you define pretty precisely what 'better' is for your purpose, 'best' isn't really possible to judge).
Trying to rank things with very different numbers of (/ precision of) observations is a common problem (think online ratings for movies for example), so you might search around for solutions to quite different problems with the same issue.
I'll present one approach I've seen used:
Take the observed value as as estimate of a population quantity (the batter's true ability*) and so calculate a one-sided interval for the quantity (a lower bound), and then order by that. You could call it an "experience-adjusted average" (or more accurately, inexperience-adjusted), which downrates the average more for less experience.
* This assumes we're not dealing with a shifting target -- if we are (and you'd expect with batting in any sport that it would shift over time), then you might weight by recency as well, such as an exponentially weighted moving average. This will still work with the above suggested approach.
Whether this suits your purpose or not, I can't say, but with a reasonably chosen interval  it often doesn't perform too badly (e.g. perhaps an 75% or an 80% interval might work okay; you can try other values).


text:
Q: How Do I Get Diagnostic Logging On Windows 10 Boot? After resizing and moving partitions I am unable to fully boot Windows.
It boots but then I get stuck on a black screen with a mouse pointer.
I tried Ctrl-Alt-Del and Win+E to bring up the task manager or start a new shell with Windows Explorer but it had no effect.
Win+Ctrl+Shift+B to reload the display driver didn't have an effect either.
The same thing occurs in Safe Mode and automatic repair doesn't fix it.
"A black screen with mouse pointer" doesn't give much to go on to work out what is broken.
How do I enable diagnostic logging during the boot process so that I have a file to inspect for errors?


text:
Q: Nginx try_files not working with domain that appends trailing slash I have a dockerised Django app where nginx uses proxy_pass to send requests to the Django backend. I am looking to pre-publish certain pages that dont change often so Django doesnt have to deal with them.
I am trying to use try_files to check if that page exists locally and pass to Django if not.
Our URL structure requires that all URLs end with a forward slash and we dont use file type suffixes e.g. a page might be www.example.com/hello/. This means the $uri param in nginx in this instance is /hello/ and when try_files looks at that it is expecting a directory due to the trailing slash. If I have a directory with a list of files how do I get try_files to look at them without re-writing the URL to remove the slash as Django requires it?
My nginx conf is below.
server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name example.com;

    root /home/testuser/example;

    location / {
        try_files $uri uri/ @site_root;
    }

    location @site_root {
       proxy_pass         http://127.0.0.1:12345;
    }
}

If I have a file "hello" at /home/testuser/example/hello and call https://www.example.com/hello/ how can I get it to load the file correctly?
P.S. the permissions on the static content folder and its contents are all 777 (for now to rule out permissions issues)
Cheers in advance!

A: You can point the URI /hello/ to a local file called hello or hello.html using try_files, but you must first extract the filename using a regular expression location. See this document for details.
The advantage of using .html is that you will not need to provide the Content-Type of the response.
For example, using hello.html:
root /path/to/root;

location / {
    try_files $uri uri/ @site_root;
}
location ~ ^(?<filename>/.+)/$ {
    try_files $filename.html @site_root;
}
location @site_root {
   proxy_pass  ...;
}

If you prefer to store the local files without an extension, and they are all text/html, you will need to provide the Content-Type. See this document for details.
For example, using hello:
root /path/to/root;

location / {
    try_files $uri uri/ @site_root;
}
location ~ ^(?<filename>/.+)/$ {
    default_type text/html;
    try_files $filename @site_root;
}
location @site_root {
   proxy_pass  ...;
}

A: In my case using NextJS, leaving the final slash causes errors.
So here is the solution I found to make it work nicely:
root /path/to/static/files/directory; # no trailing slash
rewrite ^/(.*)/$ /$1 permanent; # automatically remove the trailing slash

location / {
  try_files $uri $uri.html $uri/index.html /404.html;
  # try the provided uri
  # then try adding .html
  # then try uri/index.html (ex: homepage)
  # finally serve the 404 page
}


text:
Q: How to correctly use the map operator in this Java 8+ application in order to retrieve, modify and update an object on the DB? I am working on a Java 8+ project based on Spring Boot and I am finding some difficulties trying to use a "functional" approach to my code. I admit that I remained at Java 7 approach and I am trying to improve my code with modern construct.
I have this service class method:
/`
 * Deactivate an user retrieved by its user ID
 * @throws NotFoundException
 */
@Override
public Optional<User> deactivateUser(int userId) throws NotFoundException {

    Optional<User> retrievedUser = this.userRepository.findById(userId);

    return Optional.ofNullable(retrievedUser)
            .map((user) -> retrievedUser.get())
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID %s was not found", userId))));
}

As you can see it first retrieve an Optional<User> object using a Spring Data JPA repository.
Then I am trying to use functional approach (using map() operator) to implement the following behavior:

*

*Retrieve the User object contained into the Optional<User> object retrieved using the repository.

*If the retrieved Optional<User> object is not empty --> do some operation before return this object.

*If the retrieved Optional<User> object is empty --> throw the NotFoundException() exception.
I think that point 1 and 3 are ok. The problem is that I am not understanding how to correctly put some logic into the map() function, at the moment I have something like this:
.map((user) -> retrievedUser.get())

What exactly means it? I think that it put the User object retrieved by the retrievedUser.get() into an user variable that is returned. Is it my reasoning correct? (I am absolutely not sure).
My problem is that before to return this User object I need to perform some operation (basically update a field named isActive setting it to false and then update it using the Spring Data JPA save() method). How can I do it? Can you show me an example? I think that for me could be enough an example where I have a multi line function into the map() operator (also a function that first perform the retrievedUser.get() operation and that print it into another line, then I should be able to perform the needed logic by myself).

A: The map method takes a Function object as a parameter. The Function is a generic interface that only has one method that acts like a callback, so in order to achieve your desired result, you have to implement this interface and pass it to the method. To do so, you can implement it by using a lambda expression (which is the way you're trying to do). In this case, the function will be called passing the object found by your repository.
You probably want something like this:
    return Optional.ofNullable(retrievedUser)
        .map((user) -> {
            // do your operation with the object
            return user;
        })
        .map(updatedUser -> userRepository.save(updatedUser))
        .orElseThrow(() -> new NotFoundException(String.format("The user having ID %s was not found", userId))));

Note that inside the lambda expression, you're dealing with the User and not with the Optional<User>, so there's no need to use .get() there.
You should also note that the orElse/orElseThrow kind of functions return an instance of the object and not the Optional, so you'll have to change the return type of your method.
This article is a pretty good read if want to understand what each operation does and how to use them.

A: You can write a function which accept an user and return an user for doing the logic of (2) . For example :
public User processUser(User user) {
    user.setActive(false);
    return user;
}

and then refer to this function in the map operator :
return Optional.ofNullable(retrievedUser
            .map((user) -> processUser(user))
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID %s was not found", userId))));

You can further use method reference to simplify it to:
return Optional.ofNullable(retrievedUser
            .map(this::processUser)
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID %s was not found", userId))));


text:
Q: How to increase django/nxginx/uwsgi page load size limit? I am using nginx and uWsgi with django (using daphne) to serve a simple one page site.
I have reached a point where if I put more html objects on the page it loads to a certain point and does not load the rest. For example if I add a table with 60 rows the site loads the table up to 30 rows and nothing after that table loads. Or if I put 30 cards with text on it on the page, it loads a certain number of cards and does not load the rest of the site. If I only put 15 cards it loads the entire site.
It is literally the html objects after the x amount of cards or rows that don't load. If I tap F-12 the rest of the site is just missing after the x cards or x rows.
There are no errors or anything.
This is what my nginx config looks like:
# build_check_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    server unix:///path/to/build_check.sock; # for a file socket
}

# configuration of the server
server {
    # the port your site will be served on
    listen      80;
    # the domain name it will serve for
    server_name x.xx.xxx.xxx; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 800M;   # adjust to taste
    client_body_timeout 3600;
    client_body_buffer_size 800M;
    sendfile_max_chunk 800M;
    # http and server
    client_header_buffer_size 800M;

    # Django media
    location /media  {
        alias /path/to/site/media;  # your Django project's media files - amend as required
    }

    location /static {
        client_body_timeout 3600;
        client_body_buffer_size 800M;
        client_max_body_size 800M;
        sendfile_max_chunk 800M;

        alias /path/to/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        proxy_read_timeout 600s;
        uwsgi_read_timeout 600s;
        uwsgi_send_timeout 600s;
        client_body_timeout 3600;
        client_body_buffer_size 800M;
        client_max_body_size 800M;
        sendfile_max_chunk 800M;

        uwsgi_pass  django;
        include     /path/to/uwsgi_params; # the uwsgi_params file you installed
    }
}

As you can see I tried pretty much anything that I could find in the documentation regarding size.
This is what my uwsgi.ini file looks like:
# build_check_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /path/to/site
# Django's wsgi file
module          = build_check_site.wsgi:application
# callable = application
# process-related settings
# master
 master          = true
# maximum number of worker processes
processes       = 5
# the socket (use the full path to be safe
socket          = /path/to/build_check.sock
socket-timeout  = 900s
# ... with appropriate permissions - may be needed
chmod-socket    = 666
uid = [redacted]
gid = [redacted]
# clear environment on exit
vacuum          = true
safe-pidfile = /tmp/build_check.pid
limit-as = 900 # limit the project to 900 MB
max-requests = 7000 # respawn processes after serving 5000 requests
daemonize = /path/to/build_check.log
http-timeout = 900s
websockets-max-size = 9000
websocket-max-size = 9000
chunked-input-limit = 1000000
chunked-input-timeout = 400000
post-buffering = 1282900
buffer-size = 12829000
post-buffering-bufsize = 12829000
fastrouter-buffer-size = 12829000
http-buffer-size = 12829000

As you can see, I also tried increasing the size of anything I could find in the uwsgi ini.
If it helps:
When I take a memory snapshot in firefox in the half loaded state the memory shows this: https://s3.eu-central-1.amazonaws.com/cos-dev-attachments/ShareX/notsimon/0123/bJbDoQwdMFwnJFxR.png
And when I take a snapshot in the fully loaded state it shows this: https://s3.eu-central-1.amazonaws.com/cos-dev-attachments/ShareX/notsimon/0123/xxmjIlqpxmgZKICL.png
Any ideas?

A: I had a problem with big formset pages, so pages with many form fields, and solved it changing the following SETTINGS variable:
DATA_UPLOAD_MAX_NUMBER_FIELDS

You can also give a try to this other SETTINGS variable
DATA_UPLOAD_MAX_MEMORY_SIZE


text:
Q: How to create a link for PDF file in Magento How to create a link for a PDF file in Magento?
I have uploaded the PDF file to the catalog, how to create a hyperlink for download?

A: You can take reference from the below link for creating custom download link in magento -
https://meetanshi.com/blog/create-custom-download-link-in-magento-2/


text:
Q: Add 'object' to a stack with expiry timers and get notified when it expires I have a need to reserve an object (JSON) within my app for a period of time (typically 180 seconds) At some point the client may or may not come back and request this object by its key.
The tricky part is that I need to be notified when this object expires so I can return it to the available pool if the client hasn't already requested it.
The obvious solutions are to use something like a timestamp in the database and then a periodic script to check for expired items but this doesn't feel like the nicest solution.
Ideally I'm looking for something like memcache that can call an event when an item expires, surely there is such a product out there?
My current framework is based around python, cherrpy, mongo, memcachce but I'm happy to add to it.

A: I would probably use threading.Timer for this. A Timer object will call a specified function with given arguments after a period of time. So write a function that returns a JSON object to the pool, and start a timer that specifies the specific JSON object that has been reserved. Additionally, you can cancel a timer before it fires, which you will want to do if the client actually requests the object before the reservation expires.
To keep track of the pool, I would probably use a dict where the JSON object is the key and the value is either None if the object is not checked out, or the Timer instance if it is checked out. A separate list could be used to keep track of what object should be given out next; pop() from the end of the list when taking an object out and append() it back on when it's returned. Beware of possible race conditions updating both of these structures!

A: Unless there are other processes that will be using this pool of objects, it doesn't seem there would be a reason to return the expired ones to the pool before you need to allocate a one.  If you check for expired objects and return them to the pool before allocating new ones, that should cover the cleanup adequately.
In order to simplify the cleanup itself, consider creating a list of (expire_time, object) tuples and use bisect.insort() to keep the list ordered by the first value -- the expire time:
que_tuple = (time.time() + EXPIRY_DELAY, obj)
bisect.insort(my_list, que_tuple)

Each time you go to reserve another object, you can check for expired items to return to the pool.  By using the sorted list, you only have to check the 0th element for being expired and then clean the elements in order until you find one that is not expired.  Something like this:
time_to_act, obj = my_list[0]
while time.time() > time_to_act:
    return_to_pool( obj )   # whatever is necessary to clean-up your objects
    my_list.pop(0)
    time_to_act, obj = my_list[0]

If you do decide that you do need to implement a timer, this queue concept will still be useful.  Otherwise, you could have a timer for every object's expiration.  Often, there are a finite number of system timers available and you may find yourself running out of resources.  The expiration queue (my_list) allows for a single timer to announce the next expiring object and the timer would be reset to the new head of the list.
I hope this helps!

A: I am almost sure that a solution around redis expire command should do the needful. It's simple to use. Here is example using Redis cli.
redis> HMSET myhash field1 "Hello" field2 "World"
OK
redis> HGET myhash field1
"Hello"
redis> EXPIRE myhash 180
(integer) 1
redis> HGET myhash field2
"World"
redis> HGET myhash field2 # after 180 secs
(nil)

Further Python has various redis client options. redis-natives-py provides annotation @temporary(after=None, at=None) .
Notification part
Redis wont notify you. May be application have logic to assume expiry after N seconds, and yes you can confirm that anytime with not expensive EXISTS command. Other option might be using greenlets to keep eye on time. Like it creates redis object, sleeps for N second and wakes up confirm with redis and notify. I am suggesting greenlet mainly becuase it is much more lightweight than a Python thread.


text:
Q: Simple modulus question Probably a very simple question but not 100% sure.
If $$\lvert x-y \rvert = \lvert y-z \rvert$$
am I right in saying that
$$z=x$$
?
Thanks

A: No we can't make such an conclusion. We can know that x-y = y-z or x-y=z-y. When x-y =z-y. We can say x=z. But when x-y=y-z, y=(x+z)/2. We can't say x = z.

A: Take a positive value, say $7$. The equation $|x-y|=7$ represents two right lines, $L_1$ and $L_2$, of common slope $1$ passing by $(0,7)\in L_1$ and $(0,-7)\in L_2$ and this is so (changing notation in coordinates) for  $|y-z|=7$. Take now, for example, $y=2$ for these two lines so you have $$|x-2|=|2-z|=7$$ with $x=-5\ne z=9$

A: Two numbers with the same absolute value are equal or of opposite signs.
$$|a|=|b|\iff a=\pm b$$ hence
$$x-y=\pm(y-z),$$
$$x-2y+z=0\lor x=z.$$


text:
Q: djangorestframework-simplejwt not working I'm following a Udemy Course with user administration and I need to install this
pip install djangorestframework-simplejwt

After its installed, I need to add this to settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

But its gives me this error
ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'pkg_resources'.

So far I haven't been been able to find anything on google

A: INSTALLED_APPS = [
    ...
    'rest_framework_simplejwt',
    ...
]

It should be added in INSTALLED_APPS
Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html


text:
Q: How to step debug into std::function user code from C++ functional with GDB? For example, with:
#include <functional>
#include <iostream>

int myfunc(int i){ return i + 1; }

int main() {
    std::function<int(int)> f = myfunc;
    int i = f(1);
    std::cout << i << std::endl;
}

compiled with:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp

if I try to do a step into the call f(1), then it first leads me in to C++ standard library code, and I either have to think really hard and do the right next/step sequence, or be dumb and hit step 17 times before reaching the actual myfunc call.
Is there an easier way to go about this, maybe with some existing GDB/Python script?
This was basically done by Microsoft people for Visual Studio as mentioned at: https://devblogs.microsoft.com/cppblog/improving-the-debugging-experience-for-stdfunction/
I like it that is is possible to step into the stdlibc++ by default in Ubuntu and have already used it before, but it would be awesome if GDB could step into std::function user code by default, and have some other mechanism to go into libstdc++ for this specific case.
I'm tempted to go a bit cheeky and just use the following Python GDB script that repeats a command n times: gdb - perform a command n times which allows me to do:
repeat-cmd 17 s

Related: QtCreator debugger: step into std::function
Tested in Ubuntu 18.04, GDB 8.1, GCC 7.4.

A: The first thing which will not work in your use case is

gdb skip -gfile bits/*.h

As you already mentioned, this will skip also over your code which was called from within the std library.
Next idea: Skipping over functions with "known name". As we have typically std:: in front of the function name a used the following .gdbinit. It looks much better:
sys.path.insert(0, '/usr/share/gcc-9/python/')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)

import gdb
import re

def stop_handler(event):
    frame_name = gdb.selected_frame().name();
    if re.search("(operator new.*)|(^__gnu_cxx::.*)|(^std::.*)", frame_name) != None:
        gdb.execute("step")

gdb.events.stop.connect(stop_handler)
end

I searched now a while to find something to get the current file/line-number combination into python but did not find anything. Is there any python access to the current file name and line number? If so, this will be much simpler in this case. Would be nice if someone can add some info's here!
Remark: in ddd that will work not very well, as an internal step from python will not be recognized by the gui. So the green arrow stays on the last stepped line and not the current one. If someone knows also a trick in such a case, any help is welcome!
UPDATE:
If you use the following as .gdbinit
python
import sys
sys.path.insert(0, '/usr/share/gcc-9/python/')
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (None)

import gdb
import re

def stop_handler(event):
    sal = gdb.selected_frame().find_sal()
    if sal == None:
        gdb.execute("step")
    else:
        symtab = sal.symtab;
        if symtab == None:
            gdb.execute("step")
        else:
            file_name = symtab.fullname();
            if re.search("(.*bits.*)", file_name ) != None:
                gdb.execute("step")

gdb.events.stop.connect(stop_handler)
end

Everything works perfectly on my pc. As an additional hint: If using ddd, you can open the backtrace window and then the green arrow will follow also the python internal gdb steps. That works perfectly for me! Thanks for the question! :-)
Maybe the regexp can be updated to fit for filtering more external libs or to be more selective.

A: Just put break on the line source.cpp: 5
(gdb) b source.cpp:5

and press r(run)
ore before step to f(1) set
s 25

this will lead to the entry into the function
#include <functional>
#include <iostream>

int myfunc(int i) {
    return i + 1;
}

int main() {
    std::function<int(int)> f = myfunc;
    int i = f(1);
    std::cout << i << std::endl;
}


text:
Q: Recommended way to write database query This anything wrong with this database query
select
    abstract_author.name,
    title,
    affiliation_number,
    af_name
from
    abs_affiliation_name,
    abstract_affiliation,
    abstracts_item,
    abstract_author,
    authors_abstract
where
    abstracts_item._id = authors_abstract.abstractsitem_id and
    abstract_author._id = authors_abstract.abstractauthor_id and
    abstract_affiliation._id = abstract_author._id and
    abs_affiliation_name._id =  abstracts_item._id

I'm getting my expected result. But, someone said It's not recommended way or a good practice. Would you please tell me what is recommended way to write my query(I mean which have joins) ?

A: It's not recommended to do your joins in the where clause. Instead it's better to use explicit JOIN conditions. So your query would be
SELECT
  abstract_author.name
, title
, affiliation_number
, af_name
FROM abstracts_item
JOIN authors_abstract ON abstracts_item._id = authors_abstract.abstractsitem_id
JOIN abstract_author ON abtract_author.id = authors_abstract.abstractauthor_id
JOIN abstract_affiliation ON abstract_affiliation._id = abstract_author._id
JOIN abs_affiliation_name ON abs_affiliation_name._id = abstracts_item.id

I'd highly recommend you using aliases on your tables though as you'll avoid confusion. In this example, if you introduced a title field to one of the other tables, the query would most likely break as it would know which table to target. I'd do something like
SELECT
  au.name
, af.title
, af.affiliation_number
, af.af_name
FROM abstracts_item ai
JOIN authors_abstract aa ON ai._id = aa.abstractsitem_id
JOIN abstract_author au ON au.id = aa.abstractauthor_id
JOIN abstract_affiliation af ON af._id = au._id
JOIN abs_affiliation_name an ON an._id = ai.id

You'll need to change the aliases in the select bit though as I've guessed which tables they're from

A: I recommend you to use joins and aliases as below
select aath.name, /*alias*/title, /*alias*/affiliation_number,/*alias*/af_name
from abs_affiliation_name aan
join abstracts_item ai on aan._id =  ai._id
join abstract_affiliation aa on  aa._id = aath._id
join authors_abstract  aAbs on ai._id = aAbs.abstractsitem_id
join abstract_author aath on aath._id = aAbs.abstractauthor_id

A: No there is nothing wrong with your query. It is personal preference, the ANSI-89 impicit joins you have used are however over 20 years out of date, they were replaced in ANSI-92 with explicit JOIN syntax.
Aaron Bertrand has written a compelling article on why in most instances it is prefereable to use the newer join syntax, and the potential pitfalls of using ANSI-89 joins. In most cases the execution plan for both methods will be exactly the same (assuming you haven't accidentally cross joined with implict joins). It is worth noting though that on occassion Oracle will produce different execution plans and the ANSI-89 join syntax can produce the more efficient of the two. (I have seen an example of this posted in response to one of my answers but I can't find it at the moment, you'll have to take my word for it for now). I would not however use this as a reason to always use ANSI-89 joins, another key reason to use the ANSI-92 join syntax is that outer joins can be achieved with ANSI syntax, whereas the outer join syntax on implicit joins varies by DBMS.
e.g. on Oracle
SELECT  *
FROM    a, b
WHERE   a.id = b.id(+)

On SQL-Server (deprecated)
SELECT *
FROM    a, b
WHERE   a.id *= b.id

However, the following works on both:
SELECT  *
FROM    a
        LEFT JOIN b
            ON a.id = b.id

If you always use explicit joins you end up with more consistent (and in my opinion more readable) queries.


text:
Q: How to get Document Names from firestore and save in List and use that list whenever we want? Why its returning null? package com.boomtech.tremendoustrivia;

import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;

public class DocumentName {
    FirebaseFirestore firestore= FirebaseFirestore.getInstance();

   public List<String> getDomumentName() {
        List<String> docunames=new ArrayList<>();
        firestore.collection("Quizquestions").get()
                .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        List<DocumentSnapshot> snapshotList = queryDocumentSnapshots.getDocuments();
                        for (DocumentSnapshot snapshot:snapshotList){
                            docunames.add(snapshot.getId());
                        }
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                    }
                });
        return docunames;
    }
}

Why this code is returning null?
It's not returning the actual List, it's just returning a Null value.
How can I get the document's name and pass it to the string of the list so that I can get it whenever I want.

A: You need to wait before sanding results back  for this use interface
public class DocumentName {
public DocumentName() {
}

FirebaseFirestore firestore= FirebaseFirestore.getInstance();

public void getDomumentName(FirebaseResults firebaseResults) {
    firestore.collection("Quizquestions").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    ArrayList<String> docunames=new ArrayList<>();
                    List<DocumentSnapshot> snapshotList = task.getResult().getDocuments();
                    for (DocumentSnapshot snapshot:snapshotList){
                        docunames.add(snapshot.getId());
                    }
                    firebaseResults.AllDocuments(docunames);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                }
            });
}

interface FirebaseResults{
    void AllDocuments(ArrayList<String> names);
}

}
and Call it like this
new DocumentName().getDomumentName(new DocumentName.FirebaseResults() {
        @Override
        public void AllDocuments(ArrayList<String> names) {

        }
    });


text:
Q: nservicebus workers detached after cluster failover Background:
We are currently trying to move to the failover cluster distributor model and are seeing some issues when failing over the cluster from one distributor to another. In our lab environment we have set everything up as per David Boike's blog post. We have 3 servers for this exercise, 2 Dist boxes and 1 worker.
I see the worker initially register to the distributor and it processes messages fine until I initiate a failover test. Once I failover from one node to another, the worker appears to be detached and no longer processes messages. The messages still come in and sit in the clustered MSMQ queue.
I had to restart the nServiceBus Host windows service on the worker to get things going again.
Question:
Is there a setting that controls how often the worker subscribes to the distributor in case of cluster failover?
Thanks for the help


text:
Q: What are these kind of web links called: 'docs.soliditylang.org'? I know how to create something like http://www.website-name.com/xyz, but I wish to create a link, like http://www.xyz.website-name.com. I have been searching for this for sometime now, and unable to find any answer. Can someone please help, as I am new to web development?

A: I think you are looking for something called - subdomain. Maybe this would help: Subdomains


text:
Q: Convert binary ( integer and fraction) from VHDL to decimal, negative value in C code I have a 14-bit data that is fed from FPGA in vhdl, The NIos II processor reads the 14-bit data from FPGA and do some processing tasks, where Nios II system is programmed in C code
The 14-bit data can be positive, zero or negative. In Altera compiler, I can only define the data to be 8,16 or 32. So I define this to be 16 bit data.
First, I need to check if the data is negative, if it is negative, I need to pad the first two MSB to be bit '1' so the system detects it as negative value instead of positive value.
Second, I need to compute the real value of this binary representation into a decimal value of BOTH integer and fraction.
I learned from this link (Correct algorithm to convert binary floating point "1101.11" into decimal (13.75)?) that I could convert a binary (consists of both integer and fraction) to decimal values.
To be specified, I am able to use this code quoted from this link (Correct algorithm to convert binary floating point "1101.11" into decimal (13.75)?) , reproduced as below:
#include <stdio.h>
#include <math.h>

double convert(const char binary[]){
  int bi,i;
  int len = 0;
  int dot = -1;
  double result = 0;

  for(bi = 0; binary[bi] != '\0'; bi++){
    if(binary[bi] == '.'){
      dot = bi;
    }
    len++;
  }
  if(dot == -1)
    dot=len;

  for(i = dot; i >= 0 ; i--){
    if (binary[i] == '1'){
      result += (double) pow(2,(dot-i-1));
    }
  }
  for(i=dot; binary[i] != '\0'; i++){
    if (binary[i] == '1'){
      result += 1.0/(double) pow(2.0,(double)(i-dot));
    }
  }
  return result;
}

int main()
{
   char  bin[] = "1101.11";
   char  bin1[] = "1101";
   char  bin2[] = "1101.";
   char  bin3[] = ".11";

   printf("%s -> %f\n",bin, convert(bin));
   printf("%s -> %f\n",bin1, convert(bin1));
   printf("%s -> %f\n",bin2, convert(bin2));
   printf("%s -> %f\n",bin3, convert(bin3));

   return 0;
}

I am wondering if this code can be used to check for negative value? I did try with a binary string of 11111101.11 and it gives the output of 253.75...
I have two questions:

*

*What are the modifications I need to do in order to read a negative value?

I know that I can do the bit shift (as below) to check if the msb is 1, if it is 1, I know it is negative value...
if (14bit_data & 0x2000) //if true, it is negative value

The issue is, since it involves fraction part (but not only integer), it confused me a bit if the method still works...

*If the binary number is originally not in string format, is there any way I could convert it to string? The binary number is originally fed from a fpga block written in VHDL say, 14 bits, with msb as the sign bit, the following 6 bits are the magnitude for integer and the last 6 bits are the magnitude for fractional part. I need the decimal value in C code for Altera Nios II processor.

A: OK so I m focusing on the fact that you want to reuse the algorithm you mention at the beginning of your question and assume that the binary representation you have for your signed number is Two's complement but I`m not really sure according to your comments that the input you have is the same than the one used by the algorithm
First pad the 2 MSB to have a 16 bit representation
16bit_data = (14_bit_data & 0x2000) ? ( 14_bit_data | 0xC000) : 14_bit_data ;

In case value is positive then value will remained unchanged and if negative this will be the correct two`s complement representation on 16bits.
For fractionnal part everything is the same compared to algorithm you mentionned in your question.
For integer part everything is the same except the treatment of MSB.
For unsigned number MSB (ie bit[15]) represents pow(2,15-6) ( 6 is the width of frationnal part ) whereas for signed number in Two`s complement representation it represents -pow(2,15-6) meaning that algorithm become
/* integer part operation */
while(p >= 1)
{
  rem = (int)fmod(p, 10);
  p = (int)(p / 10);
  dec = dec + rem * pow(2, t) * (9 != t ? 1 : -1);
  ++t;
}

or said differently if you don`t want * operator
/* integer part operation */
while(p >= 1)
{
  rem = (int)fmod(p, 10);
  p = (int)(p / 10);
  if( 9 != t)
  {
     dec = dec + rem * pow(2, t);
  }
  else
  {
     dec = dec - rem * pow(2, t);
  }
  ++t;
}

For the second algorithm that you mention, considering you format if dot == 11 and i == 0 we are at MSB ( 10 integer bits followed by dot) so the code become
for(i = dot - 1; i >= 0 ; i--)
{
   if (binary[i] == '1')
   {
       if(11 != dot || i)
       {
           result += (double) pow(2,(dot-i-1));
       }
       else
       {
           // result -= (double) pow(2,(dot-i-1));
           // Due to your number format i == 0 and dot == 11 so
          result -= 512
       }
   }
}

WARNING : in brice algorithm the input is character string like "11011.101" whereas according to your description you have an integer input so I`m not sure that this algorithm is suited to your case

A: I think this should work:
float convert14BitsToFloat(int16_t in)
{
    /* Sign-extend in, since it is 14 bits */
    if (in & 0x2000) in |= 0xC000;

    /* convert to float with 6 decimal places (64 = 2^6) */
    return (float)in / 64.0f;
}

To convert any number to string, I would use sprintf. Be aware it may significantly increase the size of your application. If you don't need the float and what to keep a small application, you should make your own conversion function.


text:
Q: How expensive is to have a lot of processes, spawned by multiprocessing module? I have an application where I have 2 sub-processes (RabbitMQ consumer and RabbitMQ producer) that are constantly running ( most of the time they idle). But also I need to spawn another N number of sub-processes (lets call it Worker process) based on condition of RabbitMQ consumer process.
So Worker processes are very lightweight and don't do a lot of computation, but the work whey do takes a long time ( up to an hour ). The machine itself would have no more then 4 CPU cores. I'm planning to run the app on CentOS. So the question: is it OK to have a lot ( I expect from 1 to 20 ) lightweight processes like this that would come and go, and most of the time would idle?
My first thought was to create one sub-process (Worker process ) and than use threads inside. But I've heard people where having difficulties mixing multiprocessing and threading module together. is it true?
By the way, my app is in Python 2.7 and to spawn sub-processes I use multiprocessing module.

A: Based on your description, I would suggest that you should just go ahead and create multiple processes for your ~20 jobs.  The multiprocessing API makes this very easy, and your most precious resource is your own time.  The complexity of concurrent programming can get out of hand very quickly so you need all the help you can get.
Details
If your worker processes are I/O bound, then there is (arguably) no CPU impact to having many processes.  My Windows currently lists 145 processes running, though we would consider the machine to be idle.  Just make sure that either your code calls time.sleep(x) periodically, where x is a "reasonable" pause time for polling, or you are using a library that does it for you, such as multiprocessing's connection object with its .poll(x) method.
If your worker processes are CPU bound, then I'm afraid you are better off setting up a process pool with a size equal to your free CPUs, and then push jobs onto a queue and let the processes in the pool take jobs off the queue.  multiprocessing supports this paradigm pretty well.
It gets tricky when the workers could be both CPU bound and I/O bound at different times.  In this case I would suggest that you keep one process reserved (dedicated) for CPU work, and let it take jobs off a queue, and then let many other (I/O) processes create the jobs and push them onto the work queue. If the work is coming in faster than your one CPU core can handle, you either add a second dedicated core, or you set a maxsize on the queue and let your I/O workers monitor queue size to know whether new work can be added.
If you have a great many workers that are I/O bound, then you have to start looking at event-based frameworks such as asyncio, Twisted, gevent, eventlet, greenlet and so on.  This is because there is a reserve memory cost for each OS thread or process spawned, and once you get into thousands of instances that reserve space begins to add up; the event-based systems on the other hand do not spawn multiple threads, they just loop over the I/O device interface and accumulate data based on events. You can support a really huge number of concurrent connections with event-based networking.
On Windows, there is an excellent article of the measured limits of multiple threads and processes here.  A quick scan of the document tells me a limit of ~10k was found for maximum number of processes.  I have seen this mentioned elsewhere as The 10k problem but I don't have a reference available to me right now.
If you have a great many workers that are CPU bound, then you have to work with distributed computing, pushing jobs to various separate machines.  multiprocessing supports this too via the Manager API, but I have no personal experience with this. ZeroMQ appears to be popular right now for handling distributed messaging.


text:
Q: Poset dimension change when adding a point If a single point is added or removed from a poset, its dimension stays the same or changes by $1$. How to prove it?
I heard that it could be proven using Łoś's theorem, but, despite trying, I can't obtain a proof from this hint (nor any other proof).
My motivation is mainly to understand how Łoś's theorem works by looking at its application to a problem which isn't very general, yet non-trivial. (Other answers, not relying on Łoś's theorem, are welcome too, though, enabling comparison possibly giving better understanding of what the application of Łoś's theorem actually contributes here.)


text:
Q: mongoose error: model.find() no longer accept call back Here is my full app.js code.
//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require("lodash");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true});

const itemsSchema = {
  name: String
};

const Item = mongoose.model("Item", itemsSchema);

const item1 = new Item({
  name: "Welcome to your todolist!"
});

const item2 = new Item({
  name: "Hit the + button to add a new item."
});

const item3 = new Item({
  name: "<-- Hit this to delete an item."
});

const defaultItems = [item1, item2, item3];

const listSchema = {
  name: String,
  items: [itemsSchema]
};

const List = mongoose.model("List", listSchema);

app.get("/", function(req, res) {
  Item.find({}, function(err, foundItems){

      if (foundItems.length === 0) {
        Item.insertMany(defaultItems, function(err){
          if (err) {
            console.log(err);
          } else {
            console.log("Successfully savevd default items to DB.");
          }
        });
        res.redirect("/");
      } else {
        res.render("list", {listTitle: "Today", newListItems: foundItems});
      }
  });
});

app.get("/:customListName", function(req, res){
  const customListName = _.capitalize(req.params.customListName);

  List.findOne({name: customListName}, function(err, foundList){
    if (!err){
      if (!foundList){
        //Create a new list
        const list = new List({
          name: customListName,
          items: defaultItems
        });

        list.save();
        res.redirect("/" + customListName);
      } else {
      //Show an existing list
        res.render("list", {listTitle: foundList.name, newListItems: foundList.items});
      }
    }
  });
});

app.post("/", function(req, res){
  const itemName = req.body.newItem;
  const listName = req.body.list;

  const item = new Item({
    name: itemName
  });

  if (listName === "Today"){
    item.save();
    res.redirect("/");
  } else {
    List.findOne({name: listName}, function(err, foundList){
      foundList.items.push(item);
      foundList.save();
      res.redirect("/" + listName);
    });
  }
});

app.post("/delete", function(req, res){
  const checkedItemId = req.body.checkbox;
  const listName = req.body.listName;

  if (listName === "Today") {
    Item.findByIdAndRemove(checkedItemId, function(err){
      if (!err) {
        console.log("Successfully deleted checked item.");
        res.redirect("/");
      }
    });
  } else {
    List.findOneAndUpdate({name: listName}, {$pull: {items: {_id: checkedItemId}}}, function(err, foundList){
      if (!err){
        res.redirect("/" + listName);
      }
    });
  }
});

app.get("/about", function(req, res){
  res.render("about");
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

Cannot understand where the error is!
The error is:
Model.find() no longer accept a call back.

A: The error message is self-explanatory: A callback function is a function that you pass as an argument to another function, and that will be called/executed later on after a certain event.
In your specific case, the find method doesn't accept anymore callback functions so you need to remove function(err, foundItems)... from Item.find:
Item.find({}, function(err, foundItems){
  // Code
});

For more info about it, kindly check this link to the docs


text:
Q: Javascript Changing values in arrays in while loop Say I have arrays inside an array:
time = 0
arr = [[1,2,3], [4,5,6], [7,8,9]]

And I try to log the arr in each while loop
while (time<3){
  currentarr = JSON.parse(JSON.stringify(arr))

  for(i=0;i<currentarr.length;i++){
      for(j=0; j<currentarr[i].length; j++){

          if(currentarr[i][j]>2){
             arr[i][j]++
          }

      }
  }
  console.log(arr)
  time++
}

My problem is that each while loop gave me the same arr (the end result after three loops):
[[1, 2, 6],[7, 8, 9],[10, 11, 12]]

instead of for each time:
[[1, 2, 4],[5, 6, 7],[8, 9, 10]]
[[1, 2, 5],[6, 7, 8],[9, 10, 11]]
[[1, 2, 6],[7, 8, 9],[10, 11, 12]]

I just begin learning Javascript and I can't figure out which part went wrong... Thanks in advance!

A: 1 - It's important to use ;. Even if your code works in the environment that you are executing now, there are a lot of engines that won't be happy about that.
2 - Your while loop does not change any iteration inside it. If you pay attention, your time variable is not accessed any time. It's only used in the condition on the while loop and your time++ addition. It's only serving as a counter for your while loop, but it's not used anywhere inside your for loops as index for the arrays.
So you are basically executing the whole code inside your while loop 3 times, exactly the same, every time.
3 - Your first line currentarr = JSON.parse(JSON.stringify(arr)) creates a representation of your arr variable on that particular moment. Then you execute a comparison using this currentarr variable, on the line if(currentarr[i][j]>2){, but you add plus 1 on your original arr variable: arr[i][j]++.
I really doubt that's what you really intended.

A: Your code works as you expect. Your browser appears to be live-updating the logs.
From the MDN page on console.log():

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.

Also, from the same page:

Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))).
This way you are sure you are seeing the value of obj at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want.

This isn't related to your question, but I recommend you declare your variables. For example, instead of
for (i = 0; i < currentarr.length; i++)

do
for (let i = 0; i < currentarr.length; i++)


text:
Q: JQuery val() undefined for textarea with variable selector I can use .text() to get the original text, but updated text isn't being grabbed with the .val() command. Any ideas?
function submitText(subText){ //import submit button id
var boxID="txtArea_"+subText; //rename so that it is the textArea id
alert(boxID); //Alerts as the correct id
alert($("#".boxID).val()); //still undefined
}

HTML is
<textarea id="txtArea_29__KPIs_0" style="width:100%;">First Comment                 </textarea>

First alert is returning "txtArea_29__KPIs_0", the second is undefined

A: You have used php strings concatenation. Use + operator instead.
Correct way is: $("#"+boxID).val();
Ways of string concatenation in js:
var a = 'a';
var b = 'b';

var result = a+b;
var result = [a,b].join('');
var result = a.concat(b);

A: You should concatenate
alert($("#"+boxID).val()); //still undefined

A: This should be
alert($("#" + boxID).val());

instead of alert($("#".boxID).val());

A: Use "+" sign to concatenate jquery selector instead of the "."
alert($("#" + boxID).val());


text:
Q: How to assign a number to array and display it in the listview? I have two activities. In first I put a list of items with a ListView. In the second, I want to put a list of items too, but the contents of which will depend on the position of the element, which was pressed in the first Activitу. Here is the code of the first ListView Activity:
public class ListView1 extends Activity implements OnClickListener {
    private ListView lv1;
    private String cats[];

//some code

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        Bundle bundle = getIntent().getExtras();
        final String category = bundle.getString("category");

        lv1 = (ListView) findViewById(R.id.listView);

            ArrayAdapter<CharSequence> adapter = ArrayAdapter
                    .createFromResource(this, R.array.first_list,
                            R.layout.list_items);
            lv1.setAdapter(adapter);
            cats = getResources().getStringArray(R.array.first_list);

        lv1.setTextFilterEnabled(true);
        lv1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> a, View v, int position,
                    long id) {
                String defStrID = new Integer(position).toString();

                Intent intent = new Intent();
                intent.setClass(ListView1.this, ListView2.class);

                Bundle b = new Bundle();
                b.putString("defStrID", defStrID);
                intent.putExtras(b);

                startActivity(intent);
            }
        });
    }
}

This is the code which gets position of element in the list:
String defStrID = new Integer(position).toString();

I get it in the second ListView with:
Bundle bundle = getIntent().getExtras();
String elementID = bundle.getString("defStrID");

and I have some arrays in arrays.xml for the second ListView. For example:
R.array.category1
R.array.category2
R.array.category3
R.array.category4

or arrays like this (it's not very important):
String category1[] = { //some items here }
String category2[] = { //some items here }
etc.

As an example, only a few arrays, actually more, so I do not want to use the if else construction. How to do it another way, I do not know. The second ListView activity will be the same as the first one, except for the described above.

Second activity:
public class List2 extends ListActivity {
    private ListView lv1;
    private String category1[] = {"Name1", "Name2"};
    private String category2[] = {"Surname1", "Surname2"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        ;
        String elementID = bundle.getString("defStrID");
        String arrayName = "category" + elementID;
        int id = getResources().getIdentifier(arrayName, "array",
                this.getPackageName());
        Log.v("LOOK_FOR_ME", "category" + " and the id i got is " + id);
        String[] stats = getResources().getStringArray(id);
        lv1.setAdapter(new ArrayAdapter<String>(this, R.layout.list_items,
                stats));
    }
}

A: In your second Activity get the id from the other activity:
Bundle bundle = getIntent().getExtras();
String elementID = bundle.getString("defStrID");

If your arrays have the name categoryX(x -number) then build a String with the array name:
String arrayName = "category" + elementID;

Then you can get the id of that particular array like this:
int id = getResources().getIdentifier(arrayName, "array", getPackageName());

and finally get the String array and put it in the adapter:
String[] stats = getResources().getStringArray(id);

Also keep in mind that the position in the list start at 0 so name your array starting with 0;


text:
Q: Click on any ui-sref on dashboard show li active in ul li I am trying to create a dashboard where dashboard is abstract state and subdashboard is the very next child state for the dashboard.

Here view details of users use to go to state dashboard.tables. But the problem is that, the html element li is not opening / getting active.

Though the state is changed, that particular element is not getting active which is under datatables

In the above image, I have done manually open to just illustrate my query.
That is click / change of any state should be get active in the side menu and show as active. Any help will be great
Here is my code,

 Data Tables

Tables

Here are my routes
  r.state("dashboard",{abstract:"true",templateUrl:"partials/dashboard.html"})
  r.state("dashboard.subdashboard",{url:"/dashboard",templateUrl:"partials/subdashboard.html"})
  r.state("dashboard.tables",{url:"/tables",templateUrl:"partials/tables.html"});

Also as said by LouieAlmeda I have written, but as it wont work i removed it.
and also ng-class i have tested but no use

A: Can you try:

Tables


text:
Q: UNIX Beginner: grep save to a file doesn't work Am a beginner in unix and I have just landed into a snag. The bash app I am working on is very simple and is one that can add contacts, and remove contacts (based on first and last name). Below is a part of my code, and for some reason, the grep displays the remaining contacts fine when excluding the (>contacts_file), but doesn't save to the file when including (>contacts_file). It instead leaves the 'contacts_file' blank. How can I fix this? Or is there a better way to search contacts in a contact's file? format in contacts_file is: firstname lastname
echo "[Remove a contact]"
echo "First Name: "
read first0
echo "Last Name: "
read last0
grep -vw -e "$first0 $last0" contacts_file >contacts_file

A: You cannot direct output to the same file in which you are grepping.
The reason is that the shell opens that output file for writing and hence makes it empty.
The solution is to direct output to a temp file and then move the temp file to contacts_file if you want to replace it.


text:
Q: App inventor emulator fails to appear on a Mac OSX 10.8.4 I plan on teaching my High-School students how to build apps using App Inventor but the emulator doesn't show up in the student account of the Mac mini with the latest OSX.
The emulator does show up in my administrator account ( same computer) but it's not appearing in the student account. I usually enable Parental Controls for the student account and from my admin account I give access to specific applications that can be used in the student account.
The Java downloads fine and I am able to open it in the student account but the Android emulator is not showing up at all.
Any ideas other than making an admin account for students? ( not ideal)

A:
I'm using a Mac, the emulator won't open, and there is no error
  message.
There's a permissions issue on shared Macs in that results in the
  first person to log in being able to use the emulator, but subsequent
  people cannot. If that's what you're seeing, you can fix it by logging
  in as an administrator and deleting the directory /tmp/android. You'll
  have to do this each time a new person logs in.
  - Source


text:
Q: Prove that the interval [a, b] does not have measure zero I want to prove that $[0,1]$ does not have measure zero but the book says $``$Explain why the following observation is not a solution to the problem: Every open interval that contains $[a,b]$ has length $> b-a",$ which was exactly identical to my initial reasoning.
Why is this bad reasoning?

A: To see why this reasoning doesn't work, this following statement is true but does not imply that the set is not of measure 0.
Every open interval that contains all the rationals in $[0,1]$, or $\mathbb{Q} \cap [0,1]$, is of length $> 1 - \epsilon$, but the rationals are of measure 0.

A: twnly has given an example that shows acceptance of the reasoning can lead to a false result. This might be sufficient to answer the book's question (it will depend on how your teacher interprets "Explain why", which should be made clear in advance if the answer is to be graded for credit), but here's an explanation that is a bit more constructive (in the mathematical sense) because I'll point out where and how the argument breaks down. (Later: In a later comment @Bungo has given essentially the same explanation.)

(Technical comment for others) The reason I say "constructive" is that I'm thinking analogously of situations where one proves the existence of a mathematical object by a constructive existence proof rather than by a non-constructive existence proof. The answer twnly gave is analogous to a non-constructive existence proof.

To show that $[0,1]$ doesn't have measure zero, you have to show there exists $\delta > 0$ such that no matter how you cover the set with COUNTABLY MANY open intervals, the sum of the lengths of the intervals in your covering is $\geq \delta$ (or equivalently, $> \delta).$ The argument you're presenting only shows $\delta$ exists no matter how you cover $[0,1]$ with a SINGLE open interval. Specifically, any positive real number $\leq 1$ can be a choice for $\delta.$ Thus, there still remains to be proved that no such $\delta$ exists for coverings of $[0,1]$ by two open intervals, and no such $\delta$ exists for coverings of $[0,1]$ by three open intervals, and …, and no such $\delta$ exists for coverings of $[0,1]$ by countably many open intervals. Thus, not all of the cases that need to be considered have been considered (whether by a correct argument or by an incorrect argument).

Technical Note: There are 4 versions of what "countable cover" could mean, depending on whether (a) "countable" means "countable or finite" OR "countably infinite", and (b) "cover" means a set of open intervals OR a sequence of open intervals. All 4 versions are equivalent for the purpose of defining Lebesgue measure. For example, any finite sequence of open intervals can be replaced with a countably infinite sequence of open intervals having the same union and the same sum of lengths by including countably many occurrences of the empty set. Also, if the coverings have to be sets of open intervals and we have appropriate sequences of open intervals available, then finite or infinite repetitions of open intervals in a sequence of open intervals can be replaced with one occurrence for each case of repetition, and the duplicates that originally appeared can be replaced with countably many open intervals, all different from each other and different from any open intervals already appearing, such that the sum of the lengths of the replacement intervals is arbitrarily small. An actual complete proof that all 4 versions are equivalent can be done by proving $\;2 \cdot {4 \choose 2} = 12\;$ implications (Version 1 implies Version 2, Version 2 implies Version 1, Version 1 implies Version 3, Version 3 implies Version 1, Version 2 implies Version 3, etc.), but in practice one usually tries to arrange things so that only 4 implications are needed --- Version 1 implies Version 2 implies Version 3 implies Version 4. Occasionally more than 4 implications might be proved in such situations, say Version 1 implies Version 2 implies Version 3 AND Version 2 implies Version 4 AND Version 4 implies Version 2, such as when some of the implications have proofs that are of special interest.


text:
Q: How do I add localForage to my web app without using a packing manager Hey I need to add localForage to my web app without using Yarn, NPM, bower or any other package managers. How would I add the api organically. I am using ASP.net

A: From the documentation:

Download the latest localForage from GitHub, or install with npm:

and

To use localForage, just drop a single JavaScript file into your page:
<script src="localforage/dist/localforage.js"></script>
<script>localforage.getItem('something', myCallback);</script>


text:
Q: OSError: [Errno 22] Invalid argument in PyCharm I have got following code which works in google colab but unfortunately not in PyCharm:
https://stackoverflow.com/a/72197385/18745566
I got this Error:
OSError: [Errno 22] Invalid argument
Can anyone help me?
Thanks a lot

A: You can try File -> Settings -> Project: -> Project Structure -> Click on Timestamp (folder) -> Click on Mark as Sources -> Apply -> OK.
I hope it help you!