text:
Q: How to call scope methods defined in the link function from a directive's controller Here's a Plunker - I want "To be replaced" to be replaced by "Replacement".
My problem is as follows. I have two directives, myTabs and myPane In myTabs' link function, I add a method to its isolate scope called setValue. Now, I want myPane to be able to set the value, so I added a method setValue to myTabs' controller that basically calls the scope's method. However, because the controller function is run before the link function, the scope's method can't be accessed.
For the complete code, see the Plunker, but here are the relevant parts:
Directives:
angular.module('docsTabsExample', [])
.directive('myTabs', function() {
  return {
    transclude: true,
    scope: {},
    controller: function($scope) {
      this.setValue = $scope.setValue;
    },
    link: function(scope, element, attrs){
      scope.value = 'To be replaced';
      scope.setValue = function(value){
        scope.value = value;
      };
    },
    templateUrl: 'my-tabs.html'
  };
})
.directive('myPane', function() {
  return {
    require: '^myTabs',
    transclude: true,
    scope: {
    },
    link: function(scope, element, attrs, tabsCtrl) {
      tabsCtrl.setValue('Replacement');
    }
  };
});

HTML:

<my-tabs>
<my-pane>
   One pane
</my-pane>
<my-pane title="World">
   Another pane
</my-pane>
</my-tabs>

When run, in the console you can see Error: tabsCtrl.setValue is not a function.
Now, just to make sure I'm not headed too much in the wrong direction already, I should describe my actual problem. I'm writing a directive that requires ngModel, and that has a nested directive. Since I can only access ngModel's controller in the link function, the setValue() method can only be added to the scope there, but I need the controller to expose the API to the nested directive, which is why I'm trying to do this.setValue = $scope.setValue;.

A: You really just need to let the directives controller manage access to $scope.
When the controller is created it will have the same scope that the directive does, so you could rework the controller code to look like this:
controller: function($scope) {

 //Snip...

 this.setValue = function(value){
   $scope.value = value;
 };
}

With that logic moved to the controller, you can safely remove the scope function from your directive. However, there is an order of operation problem that you need to solve.
By default, a link: function(){} is a Post Linking function, which will execute AFTER all the child directives have been linked. You can solve this by moving the logic to a Pre Linking function because that executes BEFORE the child directives have been linked.
link: {
  pre: function(scope, element, attrs){
   scope.value = 'To be replaced';
   //No need for function here
  }
}

Now your nested directives can simply execute the method on the controller, which will in turn set the appropriate value on scope. Nothing there needs to change.
Here is a Plunker with those changes: http://plnkr.co/edit/ERf24t93rm1pmr8avyV1?p=preview
UPDATE
Ok, so here is a complete example to show how you can use ngModel from within a child directive in order to affect the actual bound model. You can see that changes are updated in both the <input> bound to progressValue as well as the actual custom control.
And in case you want to play with this on your own, here is a Plunker: http://plnkr.co/edit/zdzm0l4THlCDTvdP4ne3?p=preview

(function() {

  var template = '
' +
    '

' +
    '
' +
    '
' +
    '' +
    '
' +
    '
' +
    '
';

  function ParentWithModelDirective() {
    return {
      restrict: 'E',
      require: 'ngModel',
      template: template,
      transclude: true,
      replace: true,
      scope: {},
      link: {
        pre: function(scope, elem, attrs, ngModel) {
          var progressBar = elem.find('div').find('div'),
            label = progressBar.find('span');

          ngModel.$parsers.push(function(viewValue) {
            var numValue = 0;

            if (angular.isString(viewValue)) {
              viewValue = viewValue.replace('%', '');
            }

            numValue = parseInt(viewValue);

            return isNaN(numValue) ? 0 : numValue;
          });

          ngModel.$formatters.push(function(value) {
            return ngModel.$isEmpty(value) ? 'N/A' : value.toString() + '%';
          });

          ngModel.$render = function() {
            progressBar.css('width', ngModel.$viewValue);
            progressBar.attr('aria-valuenow',
                             ngModel.$isEmpty(ngModel.$modelValue) ?
                             0 :
                             ngModel.$modelValue);
            label.text(ngModel.$viewValue);
          };
        }
      }
    };
  }

  function ChildOfParentDirective() {
    return {
      restrict: 'E',
      require: '^ngModel',
      template: "<button type='button' class='btn btn-success'>Complete</button>",
      scope: {},
      link: function(scope, elem, attrs, ngModel) {

        function listener() {
          ngModel.$setViewValue('100%', 'click');
          ngModel.$render();
        }

        elem.on('click', listener);
      }
    };
  }

  function AnotherChildOfParentDirective() {
    return {
      restrict: 'E',
      require: '^ngModel',
      template: "<button type='button' class='btn btn-warning'>Reset</button>",
      scope: {},
      link: function(scope, elem, attrs, ngModel) {
        function listener() {
          ngModel.$setViewValue('0%', 'click');
          ngModel.$render();
        }

        elem.on('click', listener);
      }
    };
  }

  angular.module('sample-app', [])
    .directive('parentWithModel', ParentWithModelDirective)
    .directive('childOfParent', ChildOfParentDirective)
    .directive('anotherChildOfParent', AnotherChildOfParentDirective)

}());

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"
      rel="stylesheet" />

Sample App

        Progress Value
        <input type="text" class="form-control" ng-model="progressValue" />

      <parent-with-model ng-model="progressValue">

progressValue = {{progressValue}}

        <child-of-parent></child-of-parent>
        <another-child-of-parent></another-child-of-parent>

      </parent-with-model>

by Techno Fattie

A: Why do you need an ngModel on myTabs?  If you don't you can just move the setValue function straight up to the controller to solve your problem.


text:
Q: send a cookie with XMLHTTPRequest (TVMLJS) I am developing an application for my AppleTV. The App will read movies from an online website that hasn't developed any API for this kind of thing.
I use XMLHTTPRequest to get the different URLs and have the user search for his movie, etc... Everything is working fine, except for a single request. To get the movie URL, I have to send a get request to a specific address (let's say http://example.com/getmovie.html) with a constant cookie (let's say mycookie=cookie).
I've tried using setRequestHeader:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.withCredentials = true;
xhr.setRequestHeader('Cookie', 'mycookie=cookie');
xhr.send();

But no cookie seems to be sent.
I also tried setting the cookie with Document.cookie like I would have probably done in a "normal" js script (running in my browser) but no luck either.
This is extremely frustrating, especially since I'm stuck so close to the end of my app.
I guess cross-origin might be the issue but I'm able to get URLs without issues if I don't have to set cookies, so I am a bit lost there.
Please let me know how I can get http://example.com/getmovie.html with a specific cookie header.
Thanks for your help

A: In case someone has the same issue:
I didn't find a solution to sending a cookie with javascript. However, in my situation, the origin of the request didn't matter, only the cookie did. My solution was then to create a PHP file receiving the destination URL and the cookie content as parameters, and then sending the get request with the cookie as a request header. (more information about how to do so here: PHP GET Request, sending headers).
In my javascript I then use XMLHttpRequest to connect to my PHP file (hosted online) with simple get parameters and I then receive the response from the PHP. That trick of course won't work if the origin of the request matters (except if you host your file at home I guess, but in my case I want my application to work even if my WAMP isn't on).

A: Well... the problem here is the line xhr.setRequestHeader('Cookie', 'mycookie=cookie'); line just because the 'Cookie' header is reserved for the client browser to send the stored cookies. This means you are trying to do what the browser already does. When you send a any request, the client browser automatlycally will take all the cookies related to the site you are requesting and put them on the 'Cookie' header, you don't need to do anything else, if your cookie exist in your browser, it will be send.

A: Cordova how to send session cookie, allow credentials with XMLhttprequest:
// JS
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/ajax.php', true);
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
        // alert(xhr.responseText);
        // Get header from php server request if you want for something
        var cookie = xhr.getResponseHeader("Cookie");
        // alert("Cookie: " + cookie);
    }
}
xhr.send();

// Php
// You can add cookie to header and get with (session works without it)
header('Cookie: PHPSESSID='.$_COOKIE['PHPSESSID']);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');

A: im sorry to inform you but the xmlHTTPRequest function of javascript does not allow a cookie header to be set for security reasons as shown here: Why cookies and set-cookie headers can't be set while making xmlhttprequest using setRequestHeader? the best way i could see you making that get request would be to a proxy server that you would be running. I believe that it is built this way to prevent you from setting cookies on domains that you do not own, furthermore i do not see an alternate resolution to this problem as no were in the docs i looked at was cookie persistence or management mentioned

redpajama_set_name: RedPajamaStackExchange


text:
Q: $this->user->hasPermission('access','catalog/product') not working I want to hide the menu option from admin menu according to current user login. I have tried the following code:
$this->user->hasPermission('access','catalog/product');

but it is not working. How should this be done?

A: We can hide the acccess of admin side by making user group. Go to
System-> User-> User group

then add a new gropu here & assign access role that you wants to access this kind of users. Going to attach an image here

I hope this will help you.


text:
Q: Laravel order by distance from longitude latitude I need to list offers based by merchant distance and I want to do it as much as possible by using the laravel query builder. My current code looks like this:
$data['offers']= Offer::
whereHas('merchants', function (Builder $query) {
    $query->where('dd_merchant', '=', '1')->where('status', '=', 'Open');
})
->where('status', '=', 'Loaded')
->where("start", "<=", date("Y-m-d"))
->where("end", ">=", date("Y-m-d"))
->orderBy('title','ASC')
->paginate(20);

What I have tried so far is the following:
$circle_radius = 3959;
$max_distance = 100;
$lat = $customer->latitude;
$lng = $customer->longitude;
$now = date("Y-m-d");

$data['offers']= DB::table(Offer::raw('(SELECT o.*, m.latitude, m.longitude, (' . $circle_radius . ' * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) *
cos(radians(longitude) - radians(' . $lng . ')) +
sin(radians(' . $lat . ')) * sin(radians(latitude))))
AS distance
FROM offers as o
LEFT JOIN merchants as m on o.mid = m.mid) AS distances'))
->where([['distance','<',$max_distance],['status','Loaded'],['start','<=',$now],['end','>=',$now],['m.dd_merchant','=',1],['m.status','=','Open']])
->orderBy('distance','ASC')
->get();

But it makes no sense that Laravel does not have some kind of a build in function for this.
Is there a better way of doing it without relaying on RAW?
If Laravel does not support a clean way to void raw, maby theres a composer plugin to extend support for a better way?

A: To solve this in a clean way, I used netsells/laravel-geoscope
composer require netsells/laravel-geoscope
php artisan vendor:publish --tag=geoscope

In the model that contains the longitude and latitude col I added the GeoScopeTrait
use Netsells\GeoScope\Traits\GeoScopeTrait;

class Merchants extends Model
{
    use GeoScopeTrait;
    //
}

My query then looked like this:
$data['offers']= Offer::
whereHas('merchants', function (Builder $query) {
    $customer = DB::table('customers')->where('user_id', '=', Auth::user()->id)->get();
    $query->where('dd_merchant', '=', '1')
    ->where('status', '=', 'Open');
    if (isset($customer->latitude) && isset($customer->longitude)){
        $query->addDistanceFromField($customer->latitude, $customer->longitude);
    }
})
->with("merchants")
->where('status', '=', 'Loaded')
->where("start", "<=", date("Y-m-d"))
->where("end", ">=", date("Y-m-d"))
->paginate(20);

It looks a lot cleaner than using raw functions to achieve the same result!


text:
Q: A partial outer product Here is an example of what I want to do:
Suppose I have a collection of samples S = {s1, s2, s3, ...}. I want to construct the correlation matrix (and yes, this might already be built in, but this is just an example). The obvious way of doing this is by doing Outer[Correlation, S, S], but obviously this does (slightly more than) twice the amount of work necessary. There are ugly ways to fix this, for example, defining a function
 corr[i_, j_]:= If[i>j, Correlation[S[[i]], S[[j]]], 0]

but this does not appeal (and it is also space-wasteful). Is there an elegant solution?

A: S = {s1, s2, s3, s4};
ls = SparseArray[{i_, j_} :> Correlation[S[[i]], S[[j]]] /; i > j,
ConstantArray[Length@S,2]] // Quiet;

ls//Normal

(* {{0, 0, 0, 0}, {Correlation[s2, s1], 0, 0, 0}, {Correlation[s3, s1],
Correlation[s3, s2], 0, 0}, {Correlation[s4, s1],
Correlation[s4, s2], Correlation[s4, s3], 0}} *)

this is same as:
ls = Outer[Correlation, S, S] // Quiet;
Do[If[i <= j, ls[[i, j]] = 0], {i, 4}, {j, 4}];
ls
(* {{0, 0, 0, 0}, {Correlation[s2, s1], 0, 0, 0}, {Correlation[s3, s1],
Correlation[s3, s2], 0, 0}, {Correlation[s4, s1],
Correlation[s4, s2], Correlation[s4, s3], 0}} *)


text:
Q: How to load a registry free COM dll in plugin dll which is loaded by third party application? I have got the registry free COM working with a sample application following the steps given here. https://msdn.microsoft.com/en-us/library/ms973913.aspx[^]
Now I need to load the same reg free COM from a dll and not from an application directly. I tried making a manifest file for a dll, but it can't find the dll. Is that possible to change the application maniest to assembly manifest of my plugin dll and load reg free COM from there?
I didn't find much information on this scenario.
Thanks.


text:
Q: Dynamic class declaration, using variable to name class and variable reference to dynamic class I need to generate 1000+ classes from a list.
1) In my case, my list is NOT user specified. The content can be trusted, I build the list content myself. Therefore I can use eval() without introducing security risk. However, I would like to know if there are alternatives way of doing entry = eval(c_class)()
2) Instead of re-using the entry variable, I would like to build variables names from the class_list_names. I.e.: rak_entry = rak()  ...  bak_entry = bak() .
exec("entry_"+c_class +" = eval(c_class)()")

Are there other ways than to use exec with eval?
Here's my code
class_list_names = ['rak', 'bak', 'sak', 'mak']

class pattern_class(object):
    generic_attr = "bla"

def declare(classname):
    globals()[classname] = type(classname, (pattern_class,), {'__tablename__' : classname+"_daily_history"})

for c_class in class_list_names:
    declare(c_class)
    entry = eval(c_class)()
    print(entry)
    print(entry.__tablename__)
    print(entry.generic_attr)

output
<__main__.rak object at 0x0242D950>
rak_daily_history
bla
<__main__.bak object at 0x0242DA10>
bak_daily_history
bla
<__main__.sak object at 0x0242D9B0>
sak_daily_history
bla
<__main__.mak object at 0x0242D950>
mak_daily_history
bla

Regards

A: Make declare to return generated class.
class pattern_class(object):
    generic_attr = "bla"

def declare(classname):
    return type(classname, (pattern_class,), {'__tablename__' : classname+"_daily_history"})

class_list_names = ['rak', 'bak', 'sak', 'mak']
for name in class_list_names:
    cls = declare(name)
    globals()[name + '_entry'] = cls()

print rak_entry.__tablename__, bak_entry.__tablename__, sak_entry.__tablename__, mak_entry.__tablename__


text:
Q: Why does polynomial factorization generalize to matrices I'm reading about linear algebra and I came across with the following theorem where I have a problem convincing myself:

Theorem 2.1 $\,$ Every linear operator on a finite-dimensional complex vector space has an eigenvalue.
Proof:
To show that $T$ (our linear operator on $V$) has an
  eigenvalue, fix any nonzero vector $v \in V$. The vectors $v, Tv,
 T^2v,..., T^nv$ cannot be linearly independent, because $V$ has
  dimension $n$ and we have $n + 1$ vectors. Thus there exist complex
  numbers $a_0,...,a_n$, not all $0$, such that
$$a_0v + a_1Tv + ··· + a_nT^nv = 0.$$ Make the $a$'s the coefficients
  of a polynomial, which can be written in factored form as $$a_0 + a_1z
 + ··· + a_nz^n = c(z − r_1)\cdots(z − r_m),$$ where $c$ is a non-zero complex number, each $r_j$ is complex, and the equation holds for all
  complex $z$. We then have
$${\color{red}{ 0=(a_0I + a_1T + ··· + a_nT^n)v= c(T − r_1I)\cdots(T −
 r_mI)v}},$$ which means that $T − r_j$ I is not injective for at least
  one $j$. In other words, $T$ has an eigenvalue.$\;\blacksquare$

I'm having trouble with the factorized form of the matrix polynomial (in red). I understood that the factorization holds for a polynomial by the fundamental theorem of algebra but why does this also hold for matrices?
In other words, why is the the part I highlighted true? Does such an factorization always exist?
Could I have some help to see this? Thank you =)
P.S. here is my reference (page 3).
UPDATE:
Someone else also has asked the same question before it seems.

A: What matters is that the matrices involved, namely powers of $T$, commute with each other. With that in mind, the legitimacy of the factorisation should be clear: just think about expanding the brackets using the associative and distributive properties of matrix multiplication. A more sophisticated argument can be obtained by viewing the equation in terms of an action of the polynomial ring $\mathbb{C}[x]$, in which factorisation is more familiar.

A: This follows simply from the universal property of polynomial rings, which implies that any polynomial equation in $\, R[x]\,$ will persist when "evaluated" into any ring where the images of the constants commute with the image of $x$ (which is precisely the condition necessary for such a map to be a ring homomorphism).
Indeed, a polynomial ring is designed precisely to have this property, i.e. it is the most general ("free") ring that contains $\,R\,$ and a new element $\,x\,$ that commutes with all elements of $R$. Because we use only the ring axioms and constant commutativity when proving polynomial equations, such proofs persist in said ring images where constant commutativity persists.
This is true in your example because constants $\,r\,$ map to a constant matrices $\,rI\,$ which commute with $\,T = $ image of $x$.
This implies that all familiar polynomial equations (e.g. Binomial Theorem and difference of squares factorization) persist to be true when evaluated into any ring where the constants commute with the indeterminates. Ditto for many other ubiquitous polynomial equations, e.g. cyclotomic polynomial factorizations, polynomial Bezout identities for the gcd, resultants, etc. Therefore such equations represent universal laws (identities), modulo said constant commutativity.
These ideas are brought to the fore when one studies $(R-)$algebras, which are rings containing a central image of $R$, i.e. where the images of elements of $R$ commute with everything. Any polynomial equation that holds true in $\,R[x_1,\ldots,x_n]\,$ will persist to be true when evaluated into any $R$-algebra, i.e. it is an identity (law) of $R$ algebras. In fact it is easy to show that an equation holds true in $\,R[x_1,\ldots,x_n]\,$ iff it is true in all all $R$ algebras. Hence the equations that hold true $\,R[x_1,\ldots,x_n]\,$ are precisely the identities (universal laws) of $R$-algebras.

A: An explanation is that the polynomials in a given matrix  $A$
constitute a commutative subring $\mathbb{K}[A]$ of the ring of matrices, and can be considered as an image of the ring of polynomials $\mathbb{K}[X]$ , thus you can consider that in this subring, you work exactly as in $\mathbb{K}[X]$.
In fact, $\mathbb{K}[A]$ is isomorphic to the quotient ring $\mathbb{K}[X]/(m(X))$   where $m(X)$ is a minimal polynomial for matrix $A$.
Edit : let us take an example (the matrix has been borrowed from (https://www.youtube.com/watch?v=FecegfvA-Pg)).
Consider matrix $A=\begin{pmatrix}0&-2&-2\\1&3&1\\0&0&2\end{pmatrix}$ whose characteristic polynomial is $$c(X)=X^3+X^2+1$$
Using Cayley-Hamilton theorem, one has $$c(A)=A^3+A^2+I=0$$ (think to replace 1 by $I$!), otherwise said, each time you meet $A^3$ in a computation, you can replace it by $-A^2-I$. These leads to a systematic degree lowering: any polynomial of any degree in $A$ can be brought to a (unique) form as an (at most) 2nd degree polynomial, for example $A^5+A=A^3A^2+A=(-A^2-I)A+A=-A^3=-A^2-I$. But in fact, in this case there is lower degree combination of powers of $A$ that is annihilated, more precisely $$m(A)=A^2-3A+2I=0 \ \ \ (1)$$ ($m(X)=X^2-3X+2$ is called the/a minimal polynomial). Thus in fact, the degree lowering makes that any polynomial $P(A)$ in $A$ can be written a first degree polynomial $\pi(A)$. This transformation can be considered as a linear mapping, i.e., an homomorphism between linear spaces (note that I have changed $A$ into $X$).
$$\varphi: \ \ \begin{cases}P(X) \longrightarrow \pi(X)\\ \mathbb{K}[X] \longrightarrow \mathbb{K}_1[X]\end{cases}$$
(denoting by $\mathbb{K}_1[X]$ the vector space of polynomials of degree at most 1)
Note that the kernel of this mapping is the set $M$ of polynomials multiples of $m(x)$. You may know that taking classes modulo the kernel leads to an isomorphism (but may be not yet). The definition of $M$ sounds like a principal ideal. This is not astonishing because linear mapping $\varphi$ can also - fruitfully - be considered as a ring mapping (homomorphism between rings) with the following multiplication rule (because of relationship (1)):
$$(aX+b)(a'X+b')=aa'(3X-2I)+...=(3aa'+ab'+a'b)X+(bb'-2aa')$$
The quotient space, like for vector spaces, would yield an isomorphism.
Remark: the unifying structure for vector spaces that are also rings with a certain compatibility relationship betwen the rules is that of an algebra structure.


text:
Q: lastinsertId() not working with execute() while it works with exec()? here is my complete php code except configuration file which contains only server information. this code through execution error while working with prepare to prevent sql injection and do not returns lastinserted id. Is there any solution to prevent sql injection by preparing statement and return last inserted id simultaneously.
<?php
$root = dirname(dirname(__FILE__));
require_once "$root/core/config/config.php";
class engine {
//constructing database connection based on configuration parameters
function __construct() {

    if(DB_SERVER!="" && DB_USERNAME!="" && DB_PASSWORD!="" && DB_NAME!="") {
        try {
            $this->conn = new PDO('mysql:host='.DB_SERVER.'; dbname='.DB_NAME, DB_USERNAME, DB_PASSWORD);
            //$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); PDO::ERRMODE_EXCEPTION for testing db errors
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    } else {
        $url = pathinfo($_SERVER["PHP_SELF"], PATHINFO_DIRNAME) . "/" . $path;
        $url = preg_replace("/\/\/+/", "/", $url);
        $url = "http://" . $_SERVER["SERVER_NAME"] . $url;
        die("no database login");
    }
}

Here problem occures, if i prepare statement before execution it do not returns lastinsertid. through an error lastinsertid method error
//function to insert data in given table
public function insert($postcol, $postval, $table){
    $sql="INSERT INTO ".$table;
    $sql.=" ".$postcol;
    $sql.=" VALUES ".$postval;
    $stmt = $this->conn->prepare($sql);
    $stmt->execute();
    $lastid = $stmt->lastInsertId();
    return($lastid);
}

If above function changed to direct execution it works fine as follows
//function to insert data in given table
public function insert($postcol, $postval, $table){
    $sql="INSERT INTO ".$table;
    $sql.=" ".$postcol;
    $sql.=" VALUES ".$postval;
    $stmt = $this->conn->exec($sql);
    $lastid = $stmt->lastInsertId();
    return($lastid);
}

below code is to strip inputs and forward data to insert function
public function formpro($post,$table,$action){
    switch($action){
        case "insert" :
        $numItems = count($post);
        $i = 0;
        $col="(";
        $val="(";
        foreach($post as $key=>$value) {
          if(++$i != $numItems) {
            $col.="`".$key."`, ";
            if(is_numeric($val)){
                $val.=$value.", ";
            }
            else{
            $val.="'".$value."', ";
                }
          }
          else{
            $col.="`".$key."`";
             if(is_numeric($val)){
                $val.=$value;
            }
            else{
            $val.="'".$value."'";
                }
          }
        }
        $col.=")";
        $val.=")";
        return(engine::insert($col,$val,$table));
    }
}
}
//to check class worked following data processed
$arr=array("user_name"=>"addya", "full_name"=>"ananda bhat", "password"=>"fattos", "rank"=>"3");
$engine=new engine();
echo($engine->formpro($arr,"users","insert"));

A: lastInsertId() is not a method of PDOStatement, it's only a method of PDO. So even though you're using a statement to execute the query, you still have to call lastInsertId() on the connection.
public function insert($postcol, $postval, $table){
    $sql="INSERT INTO ".$table;
    $sql.=" ".$postcol;
    $sql.=" VALUES ".$postval;
    $stmt = $this->conn->prepare($sql);
    $stmt->execute();
    $lastid = $this->conn->lastInsertId();
    return($lastid);
}


text:
Q: Automatically extract qBittorrent downloads I want to automatically extract torrents downloaded with qBittorrent into the same directory.
I have a bat F:\extrator.bat that contains.
    @ECHO off
    timeout /t 10 /nobreak
    set arg1=%1
    set arg2=%2
    shift
    shift
    "C:\Program Files\WinRAR\WinRAR.exe" x "%arg1%" "%arg2%"

I call this from qBittorrent on download completion with
"F:\extractor.bat" "%F*.rar" "%F"
The qBittorrent log shows the args passed as
arg1 = F:\Torrent\Finished\downloadname*.rar
arg2 = F:\Torrent\Finished\downloadname
However Winrar reports an error stating that
C:\Windows\System32\"F:\Torrent\Finished\downloadname*.rar" could not be found.
WinRar seems to add C:\Windows\System32\ to the beginning of arg1.
Anyone have any ideas why this is happening?

A: Got it to work.
qBittorrent command was F:\Extractor.bat %F\*.rar %F
extractor.bat placed in root of F
Contains following script:-
timeout /t 10 /nobreak
set "arg1=%~1"
echo "%arg1%"
set "arg2=%2"
shift
shift
"C:\Program Files\WinRAR\WinRAR.exe" x "%arg1%" "%arg2%"

This successfully extracts the archive into the same directory.

A: Based on previous answers, I distilled and customized the following command:
"C:\Program Files\WinRAR\WinRAR.exe" x -ibck -inul -o+ %F\*.rar %F

*

*-ibck will run WinRar in the background

*-inul will ignore any potential errors that will be thrown. E.g. "No rar file was found"

*-o+ will override all files that already exists; -o- will skip these.

More info about the command line syntax and switches used by WinRar can be found here:
https://www.winrar-france.fr/winrar_instructions_for_use/source/html/HELPCommandLineSyntax.htm


text:
Q: Typescript method querystring to object I am making a method to convert querystring to object. The method works well, but typing is reporting an error.
https://jsfiddle.net/h723zuen/2/
const fromQueryString = <
  T extends {
    [x: string]: string | number | boolean | string[] | number[] | boolean[];
  }
>(
  querystring: string,
) => {
  const out: {
    [x: string]: string | number | boolean | string[] | number[] | boolean[];
  } = {};
  const arr = querystring.split('&');

  arr.forEach((a) => {
    const [key, value] = a.split('=');
    console.log(key, toValue(value), out, key in out);
    if (!!key && !!value) {
      if (key in out) {
        out[key] = Array.isArray(out[key])
          ? out[key].push(toValue(value))
          : [out[key], toValue(value)];
      } else {
        out[key] = toValue(value);
      }
      console.log(out);
    }
  });

  return out as T;
};
function toValue(mix: string) {
  const str = decodeURIComponent(mix);
  if (str === 'false') return false;
  if (str === 'true') return true;
  return +str * 0 === 0 ? +str : str;
}

A: From my understanding, Typescript still contains some glitches which is sometimes pretty hard to understand.
For example which is pretty connected to your case:
// (1)
// doesn't work since Typescript can't infer (string | number) as element
type Foo = string[] | number[];
const foo: Foo = [];
foo.push(1); // you would see error here as we push a number element

// (2)
// Works as expected
type Baz = Array<string | number>;
const baz: Baz = [];
baz.push(1);

Back to your case, I would suggest you to convert your type as case (2). Here is your code after converted:
// simplify things by group things again
type BaseType = string | number | boolean;
type BaseObj = Record<string, BaseType | BaseType[]>;

const fromQueryString = <T extends BaseObj>(
  querystring: string,
) => {
  const out: BaseObj = {};

  const arr = querystring.split('&');

  arr.forEach((a) => {
    const [key, value] = a.split('=');
    console.log(key, toValue(value), out, key in out);
    if (!!key && !!value) {
      if (key in out) {
        const v = out[key];
        out[key] = Array.isArray(v)
          ? v.push(toValue(value))
          : [v, toValue(value)];
      } else {
        out[key] = toValue(value);
      }
      console.log(out);
    }
  });

  return out as T;
};

function toValue(mix: string) {
  const str = decodeURIComponent(mix);
  if (str === 'false') return false;
  if (str === 'true') return true;
  return +str * 0 === 0 ? +str : str;
}


text:
Q: Logarithm question, does $\ln \sqrt{7}$ equal to zero? I got this from my workbook solution, was able to solve the question for the most part but stuck in the last sentence.
$$7(\ln\left|x+\sqrt{x^2-7}\right|-\ln\sqrt{7}) + c  =  7 \ln\left|x+\sqrt{x^2-7}\right|  + c$$
Does this means that $-\ln\sqrt{7} = 0$? but when I use a calculator it doesn't give me $0$.
The original question is $\int \frac{7}{\sqrt{x^2-7}} \,dx$.

A: It just got absorbed into the $C$. Since $C$ is any constant, $C'=C-7\ln(\sqrt{7})$ works just as well. The author is just being sloppy in calling them the same thing.


text:
Q: How to Ignore files with a given prefix? Using astyle, I want to make it skip the files generated by qt's MOC as for some reason this files make astyle crash.
I'm using a simple convention of using the moc_ prefix for those files.
Is there a way to globally configure astyle to ignore those files?
Which other strategy do you use to tackle this issue?

A: Try using the "--exclude" option to skip processing specific files or directories.
Here is a link to the astyle documentation (search for exclude):
http://astyle.sourceforge.net/astyle.html


text:
Q: How to define a schema with 'NumberLong' or 'NumberInt' type when use mongoose? Now I use mongoose to define a schema like below:
const schema = new Schema({
    roleId:Number,
    type:Number,
    _id:false
});

What I actually want to fulfill is to create a document whose field roleId's type is NumberLong and field type's type is NumberInt. However, the new document's fields created with this schema are all with
 type of NumberInt.
After reading the mongoose's docs, I still have no idea to define schema with different number types.
So, if there is any solution to solve my problem?

A: SchemaType stores a number value, with restrictions. Mongoose does not natively support long and double datatypes for example, although MongoDB does. However, Mongoose can be extended using plugins to support these other types.
You can use "mongoose-long" npm for the purpose.


text:
Q: Simplify expression involving real or imaginary part of complex rational function Basically I want simplify the following so that the real or imaginary operator do not appear:
$$\Im \prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i}$$
or
$$\Re \prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i}$$
where $z = x+iy$ is complex and $x_i$ is real. The $l_i$ can be any real number. Is such a form readily obtained?

A: Such a form is easily obtained if you allow the conjugate operator.
For any complex $z$, $\Re(z)=\frac 12(z+\overline z)$ and $\Im(z)=\frac 1{2i}(z-\overline z)$. Therefore we can write
$$\begin{align}
\Re \left(\prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i}\right)
  &= \frac 12\left( \prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i} +
     \overline{\prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i}} \right) \\[2ex]
  &= \frac 12\left( \prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i} +
     \prod_{i=1}^{N-1} \left( \overline z-x_i\right)^{l_i} \right)
\end{align}$$
since the $x_i$ and $l_i$ are real, and similarly
$$\begin{align}
\Im \left(\prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i}\right)
  &= \frac 1{2i}\left( \prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i} -
     \overline{\prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i}} \right) \\[2ex]
  &= \frac 1{2i}\left( \prod_{i=1}^{N-1} \left(  z-x_i\right)^{l_i} -
     \prod_{i=1}^{N-1} \left( \overline z-x_i\right)^{l_i} \right)
\end{align}$$
You will need something like the conjugate operator to get the imaginary part (and thus the real part), since the complex numbers are isomorphic to their conjugates under the usual operations of addition, multiplication, and so on.


text:
Q: Basic HTML5/Canvas Setup. Browser issues I have this basic HTML5/Canvas setup. It works fine in Chrome and Firefox. However, I am having these browser issues:

*

*If I load the page about ten times in IE8, it will typically work at
least once... I know this sounds strange; I can only guess it has
something to do with the order the JavaScript is being executed(?).

*The text does not appear in my iTouch.

Edit: I am having some formatting issues with this code.  Excanvas is used (but not seen below).
<!DOCTYPE html>
<html lang="en">
<head>

<!--[if IE]><script type="text/javascript" src="js/excanvas.js"></script><![endif]-->

<script type="text/javascript">

    function addBox(x, y, text){
        context.font = '17px Arial';

        context.textBaseline = 'top';
        context.fillStyle      = 'black';
        context.fillText  (text, x, y);
    }

    function resetCanvas(){
        c = document.getElementById("myCanvas");
        context=c.getContext("2d");

        c.width = 450;
        context=c.getContext("2d");

        //Draw Picture Frame around Canvas
        context.lineWidth = 5;
        context.strokeStyle="blue";
        context.strokeRect(5,3,430,430);
    }

    $(document).ready(function() {
        resetCanvas();
        addBox(200, 200,'hello');
    });
</script>

</head>
<body>

    <canvas id="myCanvas" width="900" height="450" >Your browser does not support the canvas element.</canvas>
</body>
</html>

A: *

*IE8 doesn't support canvas, so whatever you're seeing it's not a canvas issue

*Are you sure your iTouch has the Arial font available?  What happens if you try sans-serif instead?


text:
Q: JavaScript logic - Parsing a textarea I need to take a textbox that is full of formatted info about accounts and then sort it somehow. I would like to know if it would be ideal (I'm trying to make this as efficient as possible) to parse the info into a two dimensional array, or if I should make account objects that will hold info in fields.
The program is simply meant to format the data so that it can be printed out without having to copy/paste.
So far I have...
function generateOutputfvoc()
{
    var accountLines = document.getElementById('accountLines').value;
    var accountLinesTemp = accountLines.split(/[\s]/);

    for(var i = 0; i < accountLinesTemp.length; i++)
    {
        if(accountLinesTemp[i].match(/

Edit (1-18-13): Here is an example input. It is basically text copied from a web CRM tool. Note, this example input is something I typed up randomly.
P8B000001234567     stackoverflow   Thing   12522225555     444         Active 2005-02-26   CO1000123456
P8B000001234568     stackoverflow   Another Thing       444         Active  2005-02-26  CO1000123456
P8B000001234569     stackoverflow   Another Thing       556         Active  2005-02-26  CO1000123456

I would like my program to take the text and simply output the text like this:
P8B000001234567 stackoverflow Thing         12522225555 444 Active 2005-02-26 CO1000123456
P8B000001234568 stackoverflow Another Thing             444 Active 2005-02-26 CO1000123456
P8B000001234569 stackoverflow Another Thing             556 Active 2005-02-26 CO1000123456

Also, I would like to know if I should use jQuery variables. I asked this because I have been looking online a lot and I found examples that use code that looks like this:
$check=fcompcheck();
if($check)
{
    $output=document.frm1.type.value+" / ";
    $output=$output+"Something - "+document.frm1.disco.value+" / ";

Note the: $output variable. The dollar sign indicates a jQuery variable, right?
Thank you for any help you might be able to offer me.
Update (1-19-13): I've taken a shot at it, but I'm making slow progress. I'm used to programming Java and my JavaScript looks too similar, I can tell I'm makings errors.
I'm taking it one step at a time. Here is the logic I'm using now.

*

*Person pastes text into text box and pushes the generate button

*Program takes the contents of the text box and parses it into a large array, removing only whitespace

*Program then searches for patterns in the text and begins passing values into variables

I am trying to get the program to simply identify the pattern "Summary section collapse Name" because these four words should always be in this sequence. Once it identifies this it will pass the next two array values into first and last name variables. Here's some of the code:
var contactNameFirst, contactNameLast;

// Parse the input box into an array
var inputArr = document.getElementById('inputBox').value.split(/[\s]/);

for(var i = 0; i < inputArr.length; i++)
{
    if(inputArr[i] == "Summary" && inputArr[i - 1] == "section" && inputArr[i - 2] == "Collapse" && inputArr[i + 1] == "Name")
    {
        if(inputArr[i + 2] != "Details")
        {
            contactNameFirst = inputArr[i + 2];
        }
        else
        {
            contactNameFirst = "";
        }
        if(inputArr[i + 3] != "Details")
        {
            contactNameLast = inputArr[i + 3];
        }
        else
        {
            contactNameLast = "";
        }
    }
}

document.getElementById('contactNameOutput').innerHTML = contactNameFirst + " " + contactNameLast;

Also, should I create a new post for this now, or keep editing this one?

A: Your accountLinesTemp is an Array of String, you could use the Array.sort function to sort your array as expected, and then use Array.join to get the full String if necessary.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort on MDN for more information.


text:
Q: Access variable inside an non-return function from other package without global variable Is there a method to access a function result, which I have applied another function onto it. For example:
win32gui.EnumWindows(a_function, extra)

The EnumWindows will iterate all top-level window and passing hwnd into the a_function.
If I set some condition to grep the hwnd I want, we need to yield the hwnd id
Is there a method to access some return/yield from a_function. Instead of the function EnumWindows will grep the return.

A: EnumWindows doesn't return anything. The way results are usually retrieved from it is often to make the callback function store data in a global. There's an example of doing that in this question.
Another way is to pass a mutable container object (such as a list) as the extra argument, which will then be passed to the callback as its second argument each time it's called (the first argument is a window handle).
Here's an example using the second technique which passes a local list object to EnumWindows() which the callback function modifies, but only if the window is visible.
import win32gui

def my_callback(hwnd, list_object):
    if win32gui.IsWindowVisible(hwnd):
        title = win32gui.GetWindowText(hwnd)
        if title:
            list_object.append(title)

def print_windows_titles():
    my_list = []  # local variable

    win32gui.EnumWindows(my_callback, my_list)  # populates my_list

    # print result of calling EnumWindows
    print('Titles of Visible Windows:')
    for window_title in my_list:
        print('  {!r}'.format(window_title))

print_windows_titles()


text:
Q: Topology $\tau(\frac{1}{n})$ Defined as $\tau(\frac{1}{n}) = \{A\subset \mathbb{R} : (\exists N \in \mathbb{N}) \forall(n\in \mathbb{N},n\geq N) \frac{1}{n} \in A\} \cup \{\emptyset
\}$ was previously proven to be a topology.
Consider $\mathbb{R}$ with the topology $\tau(\frac{1}{n})$. Take $A = [-1,\frac{1}{5}]$, find $A^{o},A^{a},\overline{A}$. Take $A = (1,2)$, find $A^{o},A^{a},\overline{A}$. (A-interior, A-accumulation, A-closure)
My definitions: Let G be an open set
$x\in A^{o} \iff \exists G\in \tau$ $: x\in G\subset A$
$x\in A^{a} \iff \forall(G\in \tau,x\in G)$ $\exists y \neq x : y\in G\subset A$
$x\in \overline{A} \iff \forall(G\in \tau,x\in G)$ $\exists y : y\in G\cap A$
I know that there is an n$\in\mathbb{N}$ (namely n$\geq 5$) that makes $A$ an open topology so I can see that I WTS that $A\subset A^{o}$. I also have a BIG Theorem (Sister) that I can use which states that $A$ is open $\iff A^{o} = A$ which may be the quick route here since I'm pretty sure that $A^{o} = [-1,\frac{1}{5}]$ but please correct me if I am wrong.
For $A^{a}$ I understand the definition and I know that I need to let $G$ be an open set of unions with a tail end of $\frac{1}{n}$ and then intersect that with $A$ to create an open set $G$ where $y\in G$ and $x\in G$ but $y\neq x$ but I am struggling to do this so any help is appreciated.
The closure seems that it would be done similary to the accumulation point although that it just states that there $\exists x,y\in G$ so I was thinking those could be equal and that ultimately $A=\overline{A}$.
Any help is appreciated. Thanks!

A: For obvious reasons, let $A=[-1,1/5]$ and $B=(1,2)$.
Notice that $A\in\tau(\frac{1}{n})$ and therefore $A^{\circ}=A=[-1,1/5]$.
Besides, let $x\in\mathbb R$ and let $G\in\tau(\frac{1}{n})$ be an neighborhood of $x$.
Then $1/n\in G\cap A$ for some (and thus every) large enough $n$ and therefore $x\in A^a$.
Thus $A^a = \mathbb R$ and $\overline{A}=\mathbb R$.
For $B$, notice that $\mathbb R\setminus B =(-\infty,1]\cup[2,\infty)$ belongs to $\tau(\frac{1}{n})$, so $B$ is closed and therefore $\overline{B}=B=(1,2)$.
Also, if $x\in B^{\circ}$, then there exists $G\in\tau(\frac1n)$ such that $x\in G\subseteq B$ and therefore $1/n\in B$ for some (and thus every) large enough $n$, which is a contradiction.
So $B^{\circ} = \emptyset$.
Can you show that $B^a = \emptyset$ using analogous arguments?

 For $x\in\mathbb R$ we can always let $G = \{x\} \cup \{1/n : n\geq 2\} \in \tau(\frac1n)$ and notice that $G\cap B\subseteq \{x\}$. Thus $x$ is not $B$-accumulation.


text:
Q: Correct usage of nodetool repair command What is the right method to run nodetool repair command?
In a 3-node Cassandra cluster in single datacenter, should we run nodetool repair or nodetool repair -pr ?
As per the Cassandra apache document http://cassandra.apache.org/doc/latest/operating/repair.html,
"By default, repair will operate on all token ranges replicated by the node you're running repair on, which will cause duplicate work if you run it on every node. The -pr flag will only repair the "primary" ranges on a node, so you can repair your entire cluster by running nodetool repair -pr on each node in a single datacenter."
Running "nodetool repair" takes more than 5 mins.But running "nodetool repair -pr" takes lesser time.So,I want to know if "nodetool repair -pr" is the correct choice for 3-node Cassandra cluster in single datacenter.
Please advice.

A: Notice that if you use -pr, do not use -inc at the same time because these two are not recommended to be used together. So basically like other people suggests, before 2.2, on each node you can just run nodetool repair -pr; whereas, after 2.2, you'd better use nodetool repair -pr -full to suppress the incremental repair.

A: If you run repair periodically, the best way is to run -pr option, thus repairing only the primary token range. In that way, the whole ring will be repaired.
But if you didn't run repair until now, probably the best way will be to run a full repair and then maintenance repairs using -pr option.
Also, note that depending on your cassandra version, the repair behavior is changed. The default repair in 2.2 and afterwards is incremental. If you want to trigger a full repair you have to explicitly use -full option. For versions prior to 2.2, check the documentation.


text:
Q: Why is AddOLEObject so slow in MS Word I am programmatically inserting OLE objects into a MS Word table using the following method call:
table.Cell(row, column).Range.InlineShapes.AddOLEObject(CLASS, FILE, ...)

The problem is that the call is too slow. It takes more than a second to add an OLE object to the document. What could slowing this down? I am sure it is dependent on the application associated with the object? Any ideas to speed it up, even a little? Thanks.

A: Doing an OLE insertion is never really fast because there is a lot involved (for example, unless you are inserting as an icon, a display image of the object will be needed).
It's likely to be much quicker if the object is created by an in-process object (cf. one of the old ActiveX forms controls).
If you're using an object server such as Excel, Word has to start Excel for each insertion. Not quick. You may be able to speed things up by starting the server independently at the beginning, and by switching off screen updates in Word, but I think you'll need to run some performance tests.


text:
Q: nginx regex with multiple options I would to make a Regex (I use Nginx) to have something like this :
Example of output :
/m/signup
/en/signup
/fr/m/signup
/en/m/signup

I tried something like this :
rewrite ^/(m|(fr|en)|(fr|en)\/m)/(signup|otherpage)$ /$2.php?p=$1 last;

the parameter "p" should be either "m", or "en", or "fr", or "fr/m" for example.
but it doesn't want to work..
Any idea ?

A: You can use
^/((?:en|fr)/m|m|(?:en|fr))/(signup|otherpage)$

See the regex demo
I used this instead of (m|(fr|en)|(fr|en)\/m):

*

*(?:en|fr)/m - either en or fr followed with /m

*| - or...

*m - just m

*| - or...

*(?:en|fr) - eitherenorfr`


text:
Q: How can we give the value dynamically in VIEW of sql I created on view in that i want a dynamic value which is entered by user in front end
 ROUND((sysdate - io.movementdate), 2) AS TotalDays,

In above line it is taking sysdate but i want the date which is entered by user

A: A value cannot have input.
You should create a stored procedure that returns a query result, like a view. But in a stored you can provide input parameters.
For example (assuming your db vendor is SqlServer):
CREATE PROCEDURE [dbo].[testProcedure]
@param int
WITH EXEC AS CALLER
AS
SELECT * FROM YourTable WHERE id = @param;
GO

And you can call this with:
exec testProcedure 34;

Where 34 is the value you want to pass.


text:
Q: One GeoJSON file will not load in Leaflet but the others will I'm 98% percent done with this map and have validated all of my GeoJSON files at GeoJSONLint.
I've got 5 files, 4 of which are turned on/off using a checkbox in the sidebar; three work just fine but one will not and I have no idea where I'm going wrong. It's the 16_decrease file that's giving me trouble.
The questionable code:
<!DOCTYPE html>

<title>Lyons LC Change</title>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />

Land Cover Change Near Lyons

Tiles

  <button id="tile1">OpenTopoMap</button>

  <button id="tile2">Pioneer</button>

Selections

2006

  <input id="06increase" type="checkbox" value="06increase">Increase

2011

  <input id="11decrease" type="checkbox" value="11decrease">Decrease

2016

  <input id="16increase" type="checkbox" value="16increase">Increase

  <input id="16decrease" type="checkbox" value="16decrease">Decrease

Summary

Lorum Ipsum


text:
Q: How to collect individual results of the threads within a block? In my Kernel, the threads are processing a small part of an array in global memory.
After processing I would also like to set a flag indicating that the result of the calculation is zero for all threads within a block:
__global__ void kernel( int *a, bool *blockIsNull) {
  int tid = blockIdx.x * blockDim.x + threadIdx.x;
  int result = 0;
  // {...} Here calculate result
  a[tid] = result;

  // some code here, but I don't know, that's my question...
  if (condition)
    blockIsNull[blockIdx.x] = true; // if all threads have returned result==0
}

Each individual thread owns the information. But I don't find an efficient way to collect it.
For example, I could have a counter in shared memory that is atomically incremented by each thread when result==0. So when the counter reaches blockDim.x it means that all threads have returned zero. Althought not tested, I am afraid that this solution will have a negative impact on performance (atomic functions are slow).
A zero result does not occur very often, so it is very unlikely to have zeros for all threads within a block. I would like to find a solution that has little impact on the performance in the general case.
What would be your recommendation ?

A: It sounds like you want to perform a block level reduction of the condition value across a block. Just about all CUDA hardware supports a set of very useful warp voting primitives. You could use the __all() warp vote to determine that each warp of threads satisfied the condition, and then use __all() again to check whether all warps satisfy the condition. In code, it might look like this:
__global__ void kernel( int *a, bool *blockIsNull) {

    // assume that threads per block is <= 1024
    __shared__ volatile int blockcondition[32];
    int laneid = threadIdx.x % 32;
    int warpid = threadIdx.x / 32;

    // Set each condition value to non zero to begin
    if (warpid == 0) {
        blockcondition[threadIdx.x] = 1;
    }
    __syncthreads();

    //
    // your code goes here
    //

    // warpcondition holds the vote from each warp
    int warpcondition = __all(condition);

    // First thread in each warp loads the warp vote to shared memory
    if (laneid == 0) {
        blockcondition[warpid] = warpcondition;
    }
    __syncthreads();

    // First warp reduces all the votes in shared memory
    if (warpid == 0) {
        int result = __all(blockcondition[threadIdx.x] != 0);

        // first thread stores the block result to global memory
        if (laneid == 0) {
             blockIsNull[blockIdx.x] = (result !=0);
        }
    }
}

[ Huge disclaimer: written in browser, never compiled or tested, use at own risk ]
This code should (I think) work for any number of threads per block up to 1024. You could, if required, adjust the size of blockcondition to a smaller value if you were confident of an upper block size limit less than 1024. Probably the smartest way would be to use C++ templating and make the warp count limit a template parameter.


text:
Q: Closure and lm in R Hi i tried to prepare a little demo code for closures in R when i stumbled into some odd behavior. From using Debug i realize that the failure happens due to the fact that inside of lm this line is being executed
mf <- eval(mf, parent.frame())

however it seems to defeat the functional aspect of programming with closures ?
what am i missing ?  here is my little example
# typical closure use
foo <- function(formula,data,weight=NULL) {
  if(is.null(weight)) w=ones(nrow(data),1) else w=weight
  force(w)
  lm(formula,data,weights=w)
}

setup_something <- function(...) {
   function(formula,data) {
     foo(formula,data,...)
   }
}

# set up our model function
model <- setup_something()

# set up our data
df = data.frame(x=seq(1,10,1),y=c(1:10)^1.5 * 3 + 2)
model(y~x,df)

Error in eval(expr, envir, enclos) : object 'w' not found

A: Instantiating a formula (i.e.x~y) captures both the environment it is created in, which in your cases happens in the parent.frame() of your call to model().
If you want to subjugate the environment, you can do so explicitly by adding this line right before your call to lm(formula,data,weights=w):
# explicitly replace the formula's environment with the current frame
attr(formula,'.Environment')  <-  sys.frame(sys.nframe())

or implicitly by by replacing your call to lm(formula,data,weights=w) with:
#instantiate a new forumla based on the existing formula
lm(stats::formula(unclass(formula)),data,weights=w)

By way of background, if you were to stick the following line into lm() right before the call to mf <- eval(mf, parent.frame()):
print(ls(envir=parent.frame()))

you would get a list of object names that includes "w".  However, the 'mf' object being evaluated is a stats::model.frame thanks to this line:
mf[[1L]] <- quote(stats::model.frame)

and stats::model.frame evaluates the arguments to mf in the context of the .Environment attribute of the formula.


text:
Q: Strange null returned form async function I'm trying to get the URL of an uploaded image file on firebase storage, but I'm facing a very strange behavior.
Please take a look at the code below, problem is explained in the comented lines:
Future<String?> _uploadImage(String fileName, File imageFile) async {
    try {
      // Uploading the selected image with some custom meta data
      await FirebaseStorage.instance
          .ref(fileName)
          .putFile(
              imageFile,
              SettableMetadata(customMetadata: {
                'uploaded_by': 'Some guy',
                'description': 'Some description...'
              }))
          .then((imgUploadTaskSnapshot) async {
        switch (imgUploadTaskSnapshot.state) {
              case TaskState.paused:
                break;
              case TaskState.running:
                break;
              case TaskState.success:
                return await FirebaseStorage.instance.ref(fileName).getDownloadURL().then((fileURL) {
                  print('url : $fileURL'); // here i get a value -> url : https://firebasest.....
                  return fileURL; // but here null is returned
                });
                break;
              case TaskState.canceled:
                break;
              case TaskState.error:
                break;
            }
      });
    } on FirebaseException catch (error) {
      //Todo: handle errors
      print(error);
      throw error;
    }
}

Future<List<String>?> uploadImages(List<Map<String, dynamic>> images) async {
    try {
      List<String> imgsURLs = <String>[];
      for (int i = 0; i < images.length; i++) {
        await _uploadImage(images[i]['filename'], images[i]['imagefile'])
            .then((imgURL) {
          print('imgURL: $imgURL'); // cause here i get -> imgURL: null
          if (imgURL != null) {
            imgsURLs.add(imgURL);
          }
        });
      }
      print('imgsURLs: $imgsURLs');
      return imgsURLs;
    } on FirebaseException catch (error) {
      //Todo: hadle errors
      print(error);
      throw error;
    }
}

A: This is happening because the body in the then callback is another function. So calling return inside it will return the value, but not for _uploadImage but for the anonymous callback.
The returned value will actually apprear as the result of awaiting on the callback. You can add the return to further return it as the result of _uploadImage
return await FirebaseStorage.instance.ref(fileName).getDownloadURL().then(...

What is also worth noting is that you don't have to use then when you are in the async function. This is the main benefit of having those - you don't need to deal with callbacks.
Future<String?> _uploadImage(String fileName, File imageFile) async {
  try {
    // Uploading the selected image with some custom meta data
    final imgUploadTaskSnapshot = await FirebaseStorage.instance
        .ref(fileName)
        .putFile(
            imageFile,
            SettableMetadata(customMetadata: {
              'uploaded_by': 'Some guy',
              'description': 'Some description...'
            }));

    switch (imgUploadTaskSnapshot.state) {
      case TaskState.paused:
        break;
      case TaskState.running:
        break;
      case TaskState.success:
        final fileURL =
            await FirebaseStorage.instance.ref(fileName).getDownloadURL();
        return fileURL;
      case TaskState.canceled:
        break;
      case TaskState.error:
        break;
    }
  } on FirebaseException catch (error) {
    //Todo: handle errors
    print(error);
    throw error;
  }
}


text:
Q: Flutter BottomNavigationBar Border? I'd like to have the shadow of the BottomNavigationBar darker and more visible. I normally do this by adding a border but I somehow can't at this point. Thanks for your help!

A: This is how you add a border to BottomNavigationBar
() => showModalBottomSheet(
            context: context,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30),
              side: BorderSide(color: Colors.black, width: 2.0),
            ),
            builder: (context) => Container(
              decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    color: Colors.black,
                    blurRadius: 20.0, // has the effect of softening the shadow
                    spreadRadius: 5.0, // has the effect of extending the shadow
                    offset: Offset(
                      10.0, // horizontal, move right 10
                      10.0, // vertical, move down 10
                    ),
                  )
                ],
              ),
            ),
          ),

also take a look at box shadow this might have the effect you want


text:
Q: cLisp error in List ( EVAL: variable  has no value ) i have some task that ask me to create a list in LISP , so I'm using clips online and I made this code the create my list and do some operations

(print (setq y '(2 3 4 5 6 7 8)))
(print  (setq y (cons 1 y)))
(print  (setq y (append y '(9))))
(print  (car y))
(print  (second y))
(print  (third y))
(print  (fourth y))
(print  (fifth y))
(print  (last y))
(print (second (reverse y)))
(print  (setq y (reverse y)))
(print  (setq y (cdr y)))
(print  (setq y (reverse (cdr (reverse y)))))
(print  (length y))
(print  (member 9 y))

and this error appears without any other output:
*** - EVAL: variable  has no value

can you please help me understand what's wrong and what to do?
thank you

A: you should ask yourself why your code contains non-printing characters. Just try again to use a program without hidden characters.
> (length "(print (setq y '(2 3 4 5 6 7 8)))")
63

without hidden characters:
> (length "(print (setq y '(2 3 4 5 6 7 8)))")
33

As Bruno Haible mentioned, we can see it more clearly:
[1]> (coerce "(print (setq y '(2 3 4 5 6 7 8)))" 'list)
(#\( #\POP_DIRECTIONAL_FORMATTING #\p #\r #\i #\n #\t #\LEFT-TO-RIGHT_OVERRIDE #\Space #\( #\POP_DIRECTIONAL_FORMATTING #\s #\e #\t #\q #\Space #\y #\LEFT-TO-RIGHT_OVERRIDE #\Space #\' #\( #\POP_DIRECTIONAL_FORMATTING #\2
 #\LEFT-TO-RIGHT_OVERRIDE #\Space #\POP_DIRECTIONAL_FORMATTING #\3 #\LEFT-TO-RIGHT_OVERRIDE #\Space #\POP_DIRECTIONAL_FORMATTING #\4 #\LEFT-TO-RIGHT_OVERRIDE #\Space #\POP_DIRECTIONAL_FORMATTING #\5 #\LEFT-TO-RIGHT_OVERRIDE
 #\Space #\POP_DIRECTIONAL_FORMATTING #\6 #\LEFT-TO-RIGHT_OVERRIDE #\Space #\POP_DIRECTIONAL_FORMATTING #\7 #\LEFT-TO-RIGHT_OVERRIDE #\Space #\POP_DIRECTIONAL_FORMATTING #\8 #\LEFT-TO-RIGHT_OVERRIDE #\) #\) #\)
 #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING
 #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING #\POP_DIRECTIONAL_FORMATTING)


text:
Q: JAX-RS, Spring & ServletConfig: How to access Servlet Config in Configurator I have troubles getting a javax.servlet.ServletConfig into a class annotated with org.springframework.context.annotation.Configuration.
My team decided that we should use spring for dependency injection and I'm trying to use it to migrate one of our simple Rest services.
My constraints are:

*

*JAX-RS: We have several REST Services implemented JAX-RS and we don't really want to change that.

*Not bound to a specific implementation of JAX-RS (Jersey & RESTEasy work fine for us and we can change from one to the other without changing underlying code)

*Import as few dependencies as possible from spring: at the moment I import only org.springframework:spring-context from the spring project.

*No API breakage: Deprecated is fine but the service should keep working during the transition, using our old way of doing things.

*A string parameter is defined in the service's web.xml. I need to get it, instantiate a Bean with it and inject the resulting bean at several place in the code.

*I don't want to mess with Spring Boot/MVC/... as the service already works and I just want the Dependency Injection part.

What I already have:
The code use javax.ws.rs.core.Application, with a class that look like that:
public class MyApplication extends Application {

  @Context
  private ServletConfig cfg;

  public DSApplication() {
  }

  @Override
  public Set<Class<?>> getClasses() {
      return new HashSet<>();
  }

  @Override
  public Set<Object> getSingletons() {
    Set<Object> set = new HashSet<>();
    String injectionStr = cfg.getInitParameter("injection");
    boolean injection = false;
    if (null != injectionStr && !injectionStr.isEmpty()) {
        injection = Boolean.valueOf(injectionStr);
    }

    if (injection) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
                DSServiceProducer.class,
                CContextBeanProvider.class
        );
        IDSService service = context.getBean(IDSService.class);
        set.add(service);
    } else {
        set.add(new DSService()); //Old way
    }
    return set;
  }
}

I need the servlet config in CContextBeanProvider, which look like:
@Configuration
public class CContextBeanProvider {

  private ServletConfig cfg; // How to get this here ?

  @Bean
  public CContextBean cContextBean() {
    String bean = cfg.getInitParameter("cpuContext");
    return new CContextBean(bean);
  }
}

CContextBean is a setting bean initialized from a string found in the web.xml of the service.

*

*Is it possible ?

*Do you have any idea how ?

*Would it be easier with CDI, knowing that we run on base Tomcat ? (I've already find this if I need to use tomcat with CDI)

A: Could you please try to add all jersey CDI related jars to your applications ?


text:
Q: How do I split this string into an array? So I have some data from querying a game server and I need to find a way to extract the information so that it can be used on my site.
# 7 "player1" 1156 STEAM_0:4:00100365   0 09:52   84    3 175.77.234.241:27505
# 8 "player2" 1149 STEAM_0:0:39163243  2 14:05   52    0 109.175.131.239:65423
# 9 "player " 1159 STEAM_0:0:162  31 07:19   45    0 78.1.126.130:27025
#10 "gameer123" 1146 STEAM_0:0:701135   4 16:41   94    0 191.200.0.100:14097

The lines above are in the format:
"id" "name" "userid" "uniqueid" "frag" "time" "ping" "loss" "adr"
How would I extract this information and turn it into an array so I have something like this
[0] => Array
    (
        [Id] => 0
        [Name] => Player0
        [Frags] => 0
        [Time] => 50856
        [Uniqueid] => STEAM_0:4:001534362
    )

[1] => Array
    (
        [Id] => 0
        [Name] => Player1
        [Frags] => 4
        [Time] => 1447
        [Uniqueid] => STEAM_0:4:00100365
    )

BTW I only need the players name, frags, time and uniqueid.

A: $keys = ["id", "name", "userid", "uniqueid", "frag", "time", "ping", "loss", "adr"];
$result = [];

foreach($array as $row){
    $row_array = preg_split('/\s+\"([^\"]+)\"\s+|#\s*|\s+/', $row, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    $result[] = array_combine($keys, $row_array);
    }
    var_export($result);

result
array (
  0 =>
  array (
    'id' => '7',
    'name' => 'player1',
    'userid' => '1156',
    'uniqueid' => 'STEAM_0:4:00100365',
    'frag' => '0',
    'time' => '09:52',
    'ping' => '84',
    'loss' => '3',
    'adr' => '175.77.234.241:27505',
  ),
  1 =>
  array (
    'id' => '8',
    'name' => 'player2',
    'userid' => '1149',
    'uniqueid' => 'STEAM_0:0:39163243',
    'frag' => '2',
    'time' => '14:05',
    'ping' => '52',
    'loss' => '0',
    'adr' => '109.175.131.239:65423',
  ),
  2 =>
  array (
    'id' => '9',
    'name' => 'player ',
    'userid' => '1159',
    'uniqueid' => 'STEAM_0:0:162',
    'frag' => '31',
    'time' => '07:19',
    'ping' => '45',
    'loss' => '0',
    'adr' => '78.1.126.130:27025',
  ),
  3 =>
  array (
    'id' => '10',
    'name' => 'gameer123',
    'userid' => '1146',
    'uniqueid' => 'STEAM_0:0:701135',
    'frag' => '4',
    'time' => '16:41',
    'ping' => '94',
    'loss' => '0',
    'adr' => '191.200.0.100:14097',
  ),
)

A: Here's another RegEx approach, using named patterns that are directly recycled into array keys for your clean, final array. You can use any of the RegEx pattern sets suggested here with the solution below, simply add (?<Keyname>...) at the start of each the patterns' brackets to make them named.
$data = <<<EOL
# 7 "player1" 1156 STEAM_0:4:00100365   0 09:52   84    3 175.77.234.241:27505
# 8 "player2" 1149 STEAM_0:0:39163243  2 14:05   52    0 109.175.131.239:65423
# 9 "player" 1159 STEAM_0:0:162  31 07:19   45    0 78.1.126.130:27025
#10 "gameer123" 1146 STEAM_0:0:701135   4 16:41   94    0 191.200.0.100:14097
EOL;

/* Matching the source data with named patterns */

preg_match_all('#(?<Id>\d+)\s+"(?<Name>[[:alnum:]]+)"\s+\d+\s+(?<Uniqueid>STEAM_[0-9_:]+)\s+(?<Frags>\d+)\s+(?<Time>[\d:]{5})#m', $data, $fields, PREG_SET_ORDER);

/* Cleaning up the numeric keys from RegEx matches */

foreach($fields as $num=>$set) {
    $fields[$num] = array_diff_key($set, array_flip( array_filter( array_keys($set), 'is_int')) );
}

print_r($fields);

Results in:
Array
(
    [0] => Array
        (
            [Id] => 7
            [Name] => player1
            [Uniqueid] => STEAM_0:4:00100365
            [Frags] => 0
            [Time] => 09:52
        )

    [1] => Array
        (
            [Id] => 8
            [Name] => player2
            [Uniqueid] => STEAM_0:0:39163243
            [Frags] => 2
            [Time] => 14:05
        )

    [2] => Array
        (
            [Id] => 9
            [Name] => player
            [Uniqueid] => STEAM_0:0:162
            [Frags] => 31
            [Time] => 07:19
        )

    [3] => Array
        (
            [Id] => 10
            [Name] => gameer123
            [Uniqueid] => STEAM_0:0:701135
            [Frags] => 4
            [Time] => 16:41
        )

)

Note that I've trimmed the third line of your source data from "player " into "player", presume that was a typo. If player names have other characters, add them in: (?<Name>[[:alnum:] _-]+) etc.
========
I recycled the named-pattern int-key-cleaner into a function, in case someone needs to use often.
    /* In place of the foreach-loop above, use: */

$fields = remove_int_keys_pma($fields);

    /* And stick these two functions somewhere. */

/* Remove integer keys from preg_match_all sets. (Must use PREG_SET_ORDER.) */

function remove_int_keys_pma($array) {
    foreach($array as $k=>$set) {
        $array[$k] = remove_int_keys($set);
    }
    return $array;
}

/* Remove integer keys from an array. */

function remove_int_keys($array) {
    return array_diff_key($array, array_flip( array_filter( array_keys($array), 'is_int')) );
}

A: You can use function explode();
$result = [];
$number = 0;
foreach($mysql_result_rows as $row){
    $row_array = explode(' ', $row);
    $result[$number]['Id'] = trim($row_array['0'], ' ');
    $result[$number]['Name'] = trim($row_array['1'], '"');
    $result[$number]['Frags'] = trim($row_array['4'], ' ');
    $result[$number]['Time'] = trim($row_array['5'], ' ');
    $result[$number]['Uniqueid'] = trim($row_array['3'], ' ');
    $number++;
}

A: I made a few assumptions with your data, and there may be a more simplified regex to accomplish this task, but here is a start in any case.
The following code:

$pattern = '/#\s*(\d+)\s+"([a-zA-Z0-9\s]+)"\s+(\d+)\s+(STEAM_\d+:\d+:\d+)\s+(\d+)\s+(\d+:\d+)\s+(\d+)\s+(\d+)\s+(\d+.\d+.\d+.\d+:\d+)/';
$subject = '# 7 "player1" 1156 STEAM_0:4:00100365   0 09:52   84    3 175.77.234.241:27505
# 8 "player2" 1149 STEAM_0:0:39163243  2 14:05   52    0 109.175.131.239:65423
# 9 "player " 1159 STEAM_0:0:162  31 07:19   45    0 78.1.126.130:27025
#10 "gameer123" 1146 STEAM_0:0:701135   4 16:41   94    0 191.200.0.100:14097';

$lines = explode("\n",$subject);

$allMatches = array();
foreach($lines as $line) {
    preg_match($pattern,$line,$matches); // Extract array of fields
    $allMatches[] = array(
        "Id"       => $matches[1],
        "Name"     => $matches[2],
        "Frags"    => $matches[5],
        "Time"     => $matches[6],
        "Uniqueid" => $matches[4]
    );
}

var_export($allMatches);

Got me this result:
array (
  0 =>
  array (
    'Id' => '7',
    'Name' => 'player1',
    'Frags' => '0',
    'Time' => '09:52',
    'Uniqueid' => 'STEAM_0:4:00100365',
  ),
  1 =>
  array (
    'Id' => '8',
    'Name' => 'player2',
    'Frags' => '2',
    'Time' => '14:05',
    'Uniqueid' => 'STEAM_0:0:39163243',
  ),
  2 =>
  array (
    'Id' => '9',
    'Name' => 'player ',
    'Frags' => '31',
    'Time' => '07:19',
    'Uniqueid' => 'STEAM_0:0:162',
  ),
  3 =>
  array (
    'Id' => '10',
    'Name' => 'gameer123',
    'Frags' => '4',
    'Time' => '16:41',
    'Uniqueid' => 'STEAM_0:0:701135',
  ),
)

As Markus-ao has pointed out, the regex pattern I show here is designed to parse out every element from the strings.  To directly solve the problem, the following pattern would be more appropriate:
$pattern = '/#\s*(\d+)\s+"([a-zA-Z0-9\s]+)"\s+(?:\d+)\s+(STEAM_\d+:\d+:\d+)\s+(\d+)\s+(\d+:\d+)/';

Note that this change would also change a match array definition to:
$allMatches[] = array(
    "Id"       => $matches[1],
    "Name"     => $matches[2],
    "Frags"    => $matches[4],
    "Time"     => $matches[5],
    "Uniqueid" => $matches[3]
);

A: Yeap same here :)
I've used the Regex 101 website to fine-tune a pattern as accurate as possible to pickup your required segments.
The rest is basically a mechanism to go through them and assemble and print the result.
<?php
$sampleGmeServerResponse = [
    '# 7 "player1" 1156 STEAM_0:4:00100365   0 09:52   84    3 175.77.234.241:27505',
    '# 8 "player2" 1149 STEAM_0:0:39163243  2 14:05   52    0 109.175.131.239:65423',
    '# 9 "player " 1159 STEAM_0:0:162  31 07:19   45    0 78.1.126.130:27025',
    '#10 "gameer123" 1146 STEAM_0:0:701135   4 16:41   94    0 191.200.0.100:14097',
];

$keys = ['id', 'name', 'userid', 'uniqueid', 'frag', 'time', 'ping', 'loss', 'adr'];
// The regex made here :  https://regex101.com/r/fL9pD7/4 :p
$pattern = '/\s?+(\d+)\s+\"([\w\s]+)\"\s(\d+)\s([\w:"]+)\s+(\d+)\s(\d{2}:\d{2})\s+(\d+)\s+(\d+)\s([\d.:]+)/';
$result = [];

foreach ($sampleGmeServerResponse as $lineOfData) {
    $matches = [];
    preg_match($pattern, $lineOfData, $matches);
    array_shift($matches);

    $result[] = array_combine($keys, $matches);
}

print_r($result);

which results to the following output:
Array
(
    [0] => Array
        (
            [id] => 7
            [name] => player1
            [userid] => 1156
            [uniqueid] => STEAM_0:4:00100365
            [frag] => 0
            [time] => 09:52
            [ping] => 84
            [loss] => 3
            [adr] => 175.77.234.241:27505
        )

    [1] => Array
        (
            [id] => 8
            [name] => player2
            [userid] => 1149
            [uniqueid] => STEAM_0:0:39163243
            [frag] => 2
            [time] => 14:05
            [ping] => 52
            [loss] => 0
            [adr] => 109.175.131.239:65423
        )

    [2] => Array
        (
            [id] => 9
            [name] => player
            [userid] => 1159
            [uniqueid] => STEAM_0:0:162
            [frag] => 31
            [time] => 07:19
            [ping] => 45
            [loss] => 0
            [adr] => 78.1.126.130:27025
        )

    [3] => Array
        (
            [id] => 10
            [name] => gameer123
            [userid] => 1146
            [uniqueid] => STEAM_0:0:701135
            [frag] => 4
            [time] => 16:41
            [ping] => 94
            [loss] => 0
            [adr] => 191.200.0.100:14097
        )

)

A: You can do this, but you have to remove unwanted data from $arr first.
$game_array = array();
$key = array("id", "name", "frags", "time",  "uniqueid");

$str = '7 "player1" 1156    STEAM_0:4:00100365   0 09:52   84    3  175.77.234.241:27505';
$arr = explode(" ", $str);

$arr = array_filter($arr);
$first = array_combine($key, $arr);
$game_array[0] = $first;


text:
Q: Limit items in a API request I would like to ask how can I limit my API request for example to a 5 items only because currently when I access an API it returns 20 items. but I want to display only 5. Mostly that I found is just looping all throughout the array of objects and not limiting it to a number of items.
Note: I have no control on the API because I'm just using the moviedb API
Here's my code:
    const main = document.getElementById('main')

getMovies(URL_API)

async function getMovies(url) {
    const res = await fetch(url)
    const data = await res.json()

    showMovies(data.results)
}

function showMovies(movies){
    main.innerHTML = ''

    movies.forEach((movie) => {
        const {title, poster_path, vote_average, overview, vote_count} = movie

        const movieEl = document.createElement('div')
        movieEl.classList.add('movie')

        movieEl.innerHTML = `

${title}

            ${vote_average}
            ${vote_count}

        `
        main.appendChild(movieEl)
    })
}

A: another way to limit 5, replace
movies.forEach((movie) => {

with
movies.forEach((movie, index) => {
   if(index >= 5) return;

A: You can cut your array into chunks
const main = document.getElementById('main')

getMovies(URL_API)

let chunkIndex = 0; //initialize chunk index

async function getMovies(url) {
    const res = await fetch(url)
    const data = await res.json()

    const chunkSize = 5; //only get 5
    const chunks = []
    for (let i = 0; i < array.length; i += chunkSize) {
       const chunk = data.results.slice(i, i + chunkSize);
       chunks.push(chunk);
    }

    showMovies(chunks[0]); //only use the first chunk for rendering

    //TODO: If you have `get more` button
    //You can use chunks[chunkIndex] to get more data
    //showMovies(chunks[chunkIndex]);
    //chunkIndex++; //increase chunk index
}

function showMovies(movies){
    main.innerHTML = ''

    movies.forEach((movie) => {
        const {title, poster_path, vote_average, overview, vote_count} = movie

        const movieEl = document.createElement('div')
        movieEl.classList.add('movie')

        movieEl.innerHTML = `

${title}

            ${vote_average}
            ${vote_count}

        `
        main.appendChild(movieEl)
    })
}

A: First of all i would check if you can send request to your api to limit te result list. I dont have an account to this api. But i found this request:
https://api.themoviedb.org/5/list/{list_id}?page=1&api_key=<<api_key>>
That must returns 5 items.


text:
Q: Bash history without line numbers The bash history command is very cool. I understand why it shows the line numbers, but is there a way I can invoke the history command and suppress the line numbers?
The point here is to use the history command, so please don't reply cat ~/.bash_history
Current Output:
  529 man history
  530 ls
  531 ll
  532 clear
  533 cd ~
  534 history
Historical graphic source.
Desired Output:
man history
ls
ll
clear
cd ~
history
Historical graphic source.
Thanks to everyone for your great solutions. Paul's is the simplest and will work for me for because my bash history size is set at 2000.
I also wanted to share a cool article I found this morning. It has a couple good options that I am now using, like keeping duplicate entries out of the bash history and making sure multiple bash sessions don't overwrite the history file: http://blog.macromates.com/2008/working-with-history-in-bash/

A: Alternatively, you could use sed:
history | sed 's/^[ ]*[0-9]\+[ ]*//'

Using alias, you can set this as your standard (stick it in your bash_profile):
alias history="history | sed 's/^[ ]*[0-9]\+[ ]*//'"

A: Although cut with the -c option works for most practical purposes, I think that piping history to awk would be a better solution. For example:
history | awk '{ $1=""; print }'

OR
history | awk '{ $1=""; print $0 }'

Both of these solutions do the same thing. The output of history is being fed to awk. Awk then blanks out the first column, which corresponds to the numbers in the history command's output. Here awk is more convenient because you don't have to concern yourself with the number of characters in the number part of the output.
print $0 is equivalent to print, since the default is to print everything that appears on the line. Typing print $0 is more explicit, but which one you choose is up to you. The behavior of print $0 and simply print when used with awk is more evident if you used awk to print a file (cat would be faster to type instead of awk, but this is for illustrating a point).
[Ex] Using awk to display the contents of a file with $0
$ awk '{print $0}' /tmp/hello-world.txt
Hello World!

[Ex] Using awk to display the contents of a file without explicit $0
$ awk '{print}' /tmp/hello-world.txt
Hello World!

[Ex] Using awk when the history line spans multiple lines
$ history
   11  clear
   12  echo "In word processing and desktop publishing, a hard return or paragraph break indicates a new paragraph, to be distinguished from the soft return at the end of a line internal to a paragraph. This distinction allows word wrap to automatically re-flow text as it is edited, without losing paragraph breaks. The software may apply vertical whitespace or indenting at paragraph breaks, depending on the selected style."

$ history | awk ' $1=""; {print}'
 clear
 echo "In word processing and desktop publishing, a hard return or paragraph break indicates a new paragraph, to be distinguished from the soft return at the end of a line internal to a paragraph. This distinction allows word wrap to automatically re-flow text as it is edited, without losing paragraph breaks. The software may apply vertical whitespace or indenting at paragraph breaks, depending on the selected style."

A: history command does not have an option to suppress line numbers. You will have to combine multiple commands as everyone is suggesting:
Example :
history | cut -d' ' -f4- | sed 's/^ \(.*$\)/\1/g'

A: $ hh -n

You may want to try https://github.com/dvorka/hstr which allows for "suggest box style" filtering of Bash history with (optional) metrics based ordering i.e. it is much more efficient and faster in both forward and backward directions:

It can be easily bound to Ctrl-r and/or Ctrl-s

A: awk can help:
history|awk '{$1="";print substr($0,2)}'

This answer can fail if you have a long history.

A: Try this:
$ history | cut -c 8-

A: If you were willing to switch to zsh isntead of bash, then zsh supports this natively (as well as other options for history formatting)
zsh> fc -ln 0

(See https://serverfault.com/questions/114988/removing-history-or-line-numbers-from-zsh-history-file)

A: history -w /dev/stdout

From output of history --help:

-w        write the current history to the history file

It writes current history to specified file - /dev/stdout in this case.

A: I'm late on this one, but the shorter method would be to add the following in your ~/.bashrc or ~/.profile file:
HISTTIMEFORMAT="$(echo -e '\r\e[K')"

From bash manpage:
       HISTTIMEFORMAT
              If this variable is set and not null, its value is used as a
              format string for strftime(3) to print the time stamp associated
              with each history entry displayed by the history builtin.  If
              this variable is set, time stamps are written to the history
              file so they may be preserved across shell sessions.  This uses
              the history comment character to distinguish timestamps from
              other history lines.

Using this capability, a smart hack consist in making the variable "print" a carriage return (\r) and clear the line (ANSI code K) instead of an actual timestamp.

A: You can use command cut to solve it:
Cut out fields from STDIN or files.

*

*Cut out the first sixteen characters of each line of STDIN:
cut -c 1-16

*Cut out the first sixteen characters of each line of the given files:
cut -c 1-16 file

*Cut out everything from the 3rd character to the end of each line:
cut -c3-

*Cut out the fifth field of each line, using a colon as a field delimiter (default delimiter is tab):
cut -d':' -f5

*Cut out the 2nd and 10th fields of each line, using a semicolon as a delimiter:
cut -d';' -f2,10

*Cut out the fields 3 through 7 of each line, using a space as a delimiter:
cut -d' ' -f3-7

A: I know I am late for the party but this is just so much easier to remember:
cat ~/.bash_history

A: If you are trying to send your history without line numbers to a file and want to have the file for later reference please read below:
history | sed 's/^[ ]*[0-9]\+[ ]*//' >>history.txt

The above command will read your history's content into a text file called history.  Which will allow you to have different versions as you progress through your project(s).
I like it, because it helps me simplify automation when executing a bash script (wink)


text:
Q: Apply master theorem work for binary search with linear operation at each level I'm working on the problem from the Introduction to Algorithms book, where there is the following recurrence relation $T(n) = T(\frac{n}{2}) + \Theta(N)$, where $N$ is the size of the array we are searching for.
So the idea here is that on each level of the recursion we're copying each element of the initial array when passing it to solve a subproblem. I understand that the running time here is $\Theta(N\lg{N})$, because on each level we have to copy N elements which is $\Theta(N)$ and there are $\lg{N}$ such levels.
My question is can we apply the master theorem here? I tried to do this and either the theorem can't be applied here or I did something incorrectly. Here is my attempt:
For our recurrence we have $a = 1$, $b = 2$, $f(n) = \Theta(N)$, $N^{\log_b{a}} = N^{log_2{1}} = 1$. So we have that $f(n) = \Omega(1 * N^k)$, where $k = 1$. This is the third case, therefore we check the additional condition that $af(\frac{N}{b}) = \Theta(\frac{N}{2}) \le c \cdot \Theta(N) = \Theta(N)$, so that $c = 1$. So it seems that the solution can be $\Theta(N)$.
I understand that my solution via the master theorem is completely wrong and we probably can't use it to solve this recurrence, but I would like to understand why we can't and what's exactly wrong in my solution?
I'd be very grateful for any help or hints.

A: Notice $\Theta(N)$ is constant, so the inhomogeneous term, $f(n)$ in the theorem, is $O(n^0)$.  The critical exponent is $\log_b a = 0$.  This equals the power of $n$ in the inhomogeneous term, so you are in case 2.
In case 2, we write $f(n) = \Theta(n^0 \log^0 n)$.  The result of the master theorem is $T(n) = \Theta(n^0 \log^1 n)$.  Which is correct, you expect to get $\log_2 n$ copies of $\Theta(N)$.

Here's a potentially more useful way to approach this problem, that highlights more of the theory...
We don't actually have $T(n) = T(n/2) + \Theta(N)$ because that explicitly makes $T$ dependent on $n$ and $N$ (and two constants about which we will have more to say).  So, really, we have
$$  T(n,N) = T(n/2,N) + \Theta(N)  \text{.}  $$
That is, for each choice of $N$, there is a recurrence in $n$.  If $N$ is chosen, we can suppress "$N$" in the recursive function $T$, which is what was done in the problem statement, but it is worth remembering that each choice of $N$ gives a different recursion.  For each choice of $N$, we should think of this as an infinite list of facts: \begin{align*}
T(2,N) &= T(1,N) + c(2,N)  \text{,}  \\
T(4,N) &= T(2,N) + c(4,N)  \text{,}  \\
T(6,N) &= T(3,N) + c(6,N)  \text{,}  \\
    &\vdots
\end{align*}
We have some bounds on the $c$s and there are two forms these bounds can take.

*

*There are (universal) contants, $k_1 > 0$, $k_2 > 0$, and $n_0 > 0$ such that for all $n > n_0, $
$$  k_1 N \leq c(n,N) \leq k_2 N  \text{.}  $$

*For each choice of $N$, there are constants (where we do not suppress the dependence on $N$) $k_1(N) > 0$, $k_2(N) > 0$, and $n_0(N) > 0$ such that for all $n > n_0$
$$  k_1(N) N \leq c(n,N) \leq k_2(N) N  \text{.}  $$
Which of these two is the case, if it is established at all, is established prior to the portion of the problem statement that is recited in the Question.  For our purposes, it doesn't actually matter which is the case, so we assume the latter.  If the former is the case, then each of the functions $k_1$, $k_2$, and $n_0$ become constant functions.
So now we know: for each choice of $N$, we have an infinite list of recursion facts.  Each of these has a $c(n,N)$ and those $c(n,N)$ are bounded below and bounded above by bounds that are independent of $n$.  These bounds only depend on $N$.  Once $N$ has been chose, the bounds on the $c(n,N)$ are fixed and have no dependence on $n$ -- every $c$ on the list has the same bounds.  (It is a useful exercise to show that the $n_0$ in the definition of $\Theta$ used above can be reduced to $0$.  The short version is that the finite beginning of the list with $n \leq n_0$ is automatically bounded by multiples of $N$ and then the infinite rest of the list is bounded by multiples of $N$.  If you choose the looser of the lower bounds and the looser of the upper bounds, you have bounded the entire list by mutiples of $N$, so the whole sequence is $\Theta(N)$.)
Let's look at what happens when we don't choose $N$ but compute $T(8,N)$.
\begin{align*}
T(8,N) &= T(4,N) + c(8,N)  \text{,}  \\
    &= T(2,N) + c(4,N) + c(8,N)  \text{, and}  \\
    &= T(1,N) + c(2,N) + c(4,N) + c(8,N)  \text{.}  \\
\end{align*}
We know that
\begin{align*}
k_1(N) N &\leq c(2,N) \leq k_2(N) N  \text{,}  \\
k_1(N) N &\leq c(4,N) \leq k_2(N) N  \text{, and }  \\
k_1(N) N &\leq c(8,N) \leq k_2(N) N  \text{.}
\end{align*}
From these,
$$  3 k_1(N) N \leq c(2,N) + c(4,N) + c(8,N) \leq 3 k_2(N) N  \text{.}  $$
(This inequality is what we mean when we write "$3\Theta(N)$" -- the sum of three, likely different, bounded numbers.)
Notice that the bounds on $c$ are independent of $n$.  Whether $n$ is big or small, $c$ has the same bounds, so $\Theta(N)$ is both notationally and actually independent of $n$.  That means $\Theta(N) \in O(n^0)$ (relative to $n$).
When we choose an $N$ and apply the master theorem to $T(n)$ (with the dependence on $N$ suppressed because we have already chosen $N$), we treat $n$ as the independent variable.  Consequently, $\Theta$ and $O$ are relative to $n$.  As we have shown $\Theta(N)$ is independent of $n$ -- the upper and lower bounds implicit in "$\Theta(N)$" are independent of $n$.  We may replace $\Theta(N)$ with either the constant $k_1(N)N$ or the constant $k_2(N)N$, whichever leads to the worst case, and apply the master theorem to this recursion with constant inhomogeneous term.  The result is described in the very first part of this Answer.


text:
Q: How can I manipulate the following JSON into the desired Pandas Dataframe? Here is the JSON I am working with:

{
    "2021-05-24": {
        "RSI": "75.1354"
    },
    "2021-05-21": {
        "RSI": "74.5561"
    },
    "2021-05-14": {
        "RSI": "78.1510"
    },
    "2021-05-07": {
        "RSI": "75.3214"
    },
    "2021-04-30": {
        "RSI": "74.1698"
    }
}

I need to transform this JSON into the Following Pandas Dataframe:
         Date         RSI
0        2021-05-24   75.1354
1        2021-05-21   74.5561
2        2021-05-14   78.1510
...

The dataframe that pandas is defaulting to:
       2021-05-24       2021-05-21      2021-05-14
RSI    37.8626          39.4409         40.3654

Basically I want to filter the dataframe to exclude RSI Values that are >25 and < 75. If I have the desired dataframe, I can simply filter by the 'RSI' Index. However, I cannot figure out how to filter the current dataframe. Any help is appreciated, and I am pretty new to Pandas.

A: Try with
out = df.T.reset_index()

A: data={
    "2021-05-24": {
        "RSI": "75.1354"
    },
    "2021-05-21": {
        "RSI": "74.5561"
    },
    "2021-05-14": {
        "RSI": "78.1510"
    },
    "2021-05-07": {
        "RSI": "75.3214"
    },
    "2021-04-30": {
        "RSI": "74.1698"
    }
}

You can use DataFrame.from_dict() method:
df=pd.DataFrame.from_dict(data,orient='index')

OR
Use Transpose attribute:
df=pd.Dataframe(data).T

OR
Use transpose() method:
df=pd.DataFrame(data).transpose()

A: You can use pandas.DataFrame.melt()
df = pd.read_json('<your_file>.json')
df.melt(var_name='Date', value_name='RSI')

        Date      RSI
0 2021-05-24  75.1354
1 2021-05-21  74.5561
2 2021-05-14  78.1510
3 2021-05-07  75.3214
4 2021-04-30  74.1698

Or, because your json orientation is index, you can set the orient parameter of pd.read_json() to "index"
pd.read_json('<your_file>.json', orient='index')

                RSI
2021-04-30  74.1698
2021-05-07  75.3214
2021-05-14  78.1510
2021-05-21  74.5561
2021-05-24  75.1354


text:
Q: activity/task based authorisation Rhino security seems to offer a nice way to perform task/activity based authorization. This is some example code:
bool isAllowed = authorizationService.IsAllowed(userXYZ, "/Messages/Change");

It checks whether userXYZ can perform activity 'Change' on resource 'Messages'. This is all great but I do not like the way the resource and activity is hard coded. Do you reckon there is a way to overcome this? Thanks!

A: Why dont use web.configs? Check this nice article http://weblogs.asp.net/gurusarkar/archive/2008/09/29/setting-authorization-rules-for-a-particular-page-or-folder-in-web-config.aspx


text:
Q: Spark: Difference between: sqlContext.read.load(path= '', format= '') and sqlContext.read.format().load() I was trying to read a unicode delimited txt file on Spark2.2.
Initially was using the previous version of spark.read.load():
df= sqlContext.read.load(path='file:\\C:\Users\zr20684\Downloads\\SPEC_CUST_20190212230550.txt',
                         format= "com.databricks.spark.csv",
                         option= {"delimiter", "←"})

The entire row value was in a single column using above code.
[Row(_c0=u'01\u2190SPEC\u2190ZS\u2190SDN\u2190Insert\u219002/12/2019\u2190\u2190\u2190\u2190HCP\u2190CUST9635663\u2190\u2190\u2190JAMES\u2190\u2190DEANGELO\u2190\u2190\u2190\u2190\u2190\u2190\u2190\u2190JAMES DEANGELO\u2190\u2190\u2190\u2190\u2190\u2190A')]

While using below updated code:
df= sqlContext.read.format("com.databricks.spark.csv").option("delimiter", "←").option("encoding", "UTF-8").load('file:\\C:\Users\zr20684\Downloads\\SPEC_CUST_20190212230550.txt')

It generated the result perfectly.
[Row(_c0=u'01', _c1=u'SPEC', _c2=u'ZS', _c3=u'SDN', _c4=u'Insert', _c5=u'02/12/2019', _c6=None, _c7=None, _c8=None, _c9=u'HCP', _c10=u'CUST9635663', _c11=None, _c12=None, _c13=u'JAMES', _c14=None, _c15=u'DEANGELO', _c16=None, _c17=None, _c18=None, _c19=None, _c20=None, _c21=None, _c22=None, _c23=u'JAMES DEANGELO', _c24=None, _c25=None, _c26=None, _c27=None, _c28=None, _c29=u'A')]

If I updated all my depricated code, will there be any scenario where my entire code will break?
I am assuming the updated one is a superset of the previous version.

A: load method doesn't have option argument so it is simply ignored.
Instead options should be provided as individual keyword arguments, i.e.
sqlContext.read.load(path='...', format = "csv", delimiter = "←")


text:
Q: How to separate my 1 column of time into Data and Time I'm very sorry (I'm brand new), as I understand this has been posted a million times but I want to understand not only the answer, but which methodology I should be using as a best practice. I've clicked 10+ links on how to do this, but I seem to mess it up on my data.
I have 3 columns of data in my heartrate_seconds.csv (ID, Date, Value), my date column is comprised of both the time and date which I'd like to separate (Ex: 4/12/2016 7:22:50 AM)
so far the closest I've been is using
heartrate_timeanddate <- heartrate_seconds %>%
  mutate(Time = as.character(Time)) %>%
  separate(Time, into = c("Date", "Time"), sep = " ") %>%
  mutate(Time = as.Date(Date))

but this results in my newly added Time column as a date, how do I change this?
Other methods I tried that failed very early:
heartrate_seconds_Time <- separate(heartrate_seconds = df, col = Time, into = c('Date, Time'), sep = ' ')

heartrate_time <- data.frame(heartrate_seconds, Time = c('Date','Time'))
heartrate_time$date <- as.Date(heartrate_time$all)
heartrate_time$date <- format(as.Date(heartrate_time$all), format ="%H:%M:%S")

heartrate_seconds %>%
  separate(Time, into = c('Date, Time'), sep = '\\\\') %>%
  select(Date, Time)

I feel I'm using other peoples methods from other posts incorrectly and it's just pushed me into further confusion. So I've come seeking clarity. Thank you so much!
All of this just because I couldn't import the .csv into SQL, which I probably could've fixed in the schema but 1 thing at a time I guess.

A: One simple option is to use separate as you did, but replace the first space with another character, then separate on that.
library(tidyverse)

df %>%
  mutate(col = str_replace(date, "\\s", "|")) %>%
  separate(col, into = c("Date", "Time"), sep = "\\|") %>%
  mutate(Date = as.Date(Date, format="%d/%m/%Y"))

Output
                  date       Date       Time
1 4/12/2016 7:22:50 AM 2016-12-04 7:22:50 AM
2 6/12/2016 7:22:50 PM 2016-12-06 7:22:50 PM

Data
df <-
  structure(list(date = c(
    "4/12/2016 7:22:50 AM", "6/12/2016 7:22:50 PM"
  )),
  class = "data.frame",
  row.names = c(NA,-2L))

Another option is to use as.Date to convert the date into a variable of class Date. Then, for time variable, we can use format to extract the time component as a string.
df$Date <- as.Date(df$date)
df$Time <- format(as.POSIXct(df$date), format = "%H:%M:%S")

Output
                  date       Date     Time
1  2021-05-28 07:16:52 2021-05-28 07:16:52
2  2021-05-30 13:35:00 2021-05-30 13:35:00
3  2021-05-30 14:22:55 2021-05-30 14:22:55
4  2021-05-28 06:51:51 2021-05-28 06:51:51
5  2021-05-30 13:31:55 2021-05-30 13:31:55
6  2021-05-30 13:33:38 2021-05-30 13:33:38
7  2021-05-30 13:35:51 2021-05-30 13:35:51
8  2021-05-30 13:38:44 2021-05-30 13:38:44
9  2021-05-30 13:51:19 2021-05-30 13:51:19
10 2021-05-30 14:04:53 2021-05-30 14:04:53

Data
df <- structure(list(date = structure(c(1622186212, 1622381700, 1622384575,
                                        1622184711, 1622381515, 1622381618, 1622381751, 1622381924, 1622382679,
                                        1622383493),
                                      tzone = "UTC", class = c("POSIXct", "POSIXt"))),
                row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))

A: In your case, I would use either separate or the lubridate package.
tidyr::separate
Use tidyr::separate with parameter extra = "merge". This means that if you include less columns in into, the remaining information will be kept in the last column. Here, this means you can use it to get two columns with the separator " ".
library(dplyr)
library(tidyr)

df %>%
  separate(date, into = c("Date","Time"), extra = "merge", sep = " ")

       Date       Time
1 4/12/2016 7:22:50 AM
2 6/12/2016 7:22:50 PM

lubridate
With the lubridate package, you can convert your column to a datetime object easily with dmy_hms. Then create new variables with date and  format.
library(lubridate)
library(dplyr)

df %>%
  mutate(date = dmy_hms(date),
         Date = date(date),
         Time = format(date, format = "%H:%M:%S"))

                 date       Date     Time
1 2016-12-04 07:22:50 2016-12-04 07:22:50
2 2016-12-06 19:22:50 2016-12-06 19:22:50