text:
Q: How to get First 10 Values of array with PHP i have array and i need to print first 10 values of array
MyArray :
    Array

        [0] => Hello
        [1] => first
        [2] => nice
        [3] => loost
        [4] => emy
        [6] => rood
        [7] => 1599
        [8] => 34345
        [9] => 1313
        [10] => 45667
        [11] => 5678
        [12] => 35546
        [13] => 8877
        [14] => 3434
        [15] => 56767
        [16] => 7778
        [17] => 9987
        [18] => 8842
        [19] => 1223

array_slice not solve my problem !
Thanks for your helps

A: use array_slice
array_slice($array, 0, 10);

Syntax : array_slice(array,start,length,preserve)
Read - PHP: Extract a slice of the array

A: You can apply foreach with counter:-
$counter =0;
foreach($array as $arr){
  if($counter<10){
     echo $arr.PHP_EOL;
  }
  $counter++;
}

Output:- https://eval.in/943912

A: Check to see if array_splice solves your problem.
<?php
    $arr = [1,2,3,4,5];

    $newArr = array_splice($arr, 0, 3);

    echo '<pre>';
    print_r($arr);
    print_r($newArr);

You see here in the above example that I have Spliced out the first three elements from the array - $arr, this would give me a new array - $newArr with those three elements.
The arguments are:

*

*The source array -- $arr

*The starting index -- 0

*The length (ie. number) of elements you need to slice -- 3

array_splice() method is effective in a way where you need to edit the source array. In our case $arr would then only contain the elements [4,5].
See if this is useful to your scenario.

A: <?php
$array = array('Hello','first','nice','loost','emy','rood',1599,34345,1313,45667,5678,35546,8877,3434,56767,7778,9987,8842,1223);
$i =  0 ;
foreach($array as $key=>$value)
{
    if($i <10){
    echo $value.'<br/>';
    }
    $i++;
}
?>

Output
Hello
first
nice
loost
emy
rood
1599
34345
1313
45667

A: I think this is better.
 # $myarray is the array
 # you want to search
 $count = 0;
 foreach ( $myarray as $item ) {
   if ($count < 10)
      echo $item;
   $count++;
 }


text:
Q: How to add an image (jpg) to an existing layout using Python? I have 1500 MXDs with the same template layout, and need to insert other images for the all MXDs, can I do this using Python?
I'm using ArcGIS 10.1

A: If you just want to change the source of an existing picture element there is a code snippet in the ArcGIS help.You would of course have to know the name of your picture element.

The following script will find an image by name and set its data
  source to a new             location.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
for elm in arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT"):
    if elm.name == "Photo":
        elm.sourceImage = r"C:\Project\Data\NewPhoto.bmp"
mxd.save()
del mxd

The following script demonstrates how different pictures can be
  switched out for each page in a Data Driven Pages enabled map
  document. There is a different picture for each page. The pictures are
  named Photo1.png, Photo2.png, Photo3.png, etc to match the
  corresponding page numbers.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
pict = arcpy.mapping.ListLayoutElements(mxd, "PICTURE_ELEMENT", "photo")[0]
for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
    mxd.dataDrivenPages.currentPageID = pageNum
    pict.sourceImage = r"C:\Project\Data\Photo{0}.png".format(pageNum)
    print("Exporting page {0} of {1}"
          .format(mxd.dataDrivenPages.currentPageID,
                  mxd.dataDrivenPages.pageCount))
    arcpy.mapping.ExportToPDF(mxd, r"C:\Project\Page{0}.pdf".format(pageNum))
del mxd

redpajama_set_name: RedPajamaStackExchange


text:
Q: Objective-C in Linux - compiler errors Learning objective c on linux but I don't understand what I am doing wrong.
#import <objc/Object.h>
#import <stdio.h>

@interface Person : Object {
    @private char *name;
}
@property (readwrite, assign, nonatomic) char *name;
+ (Person *)alloc;
- (id)init;
- (id)initWithName;
- (void)sayHello;
@end

@implementation Person
@synthesize name;
+ (Person *)alloc {
    Person *a = [super alloc];
    return a;
}
- (id)init {
    self = [self initWithName:"Gert"];
    return self;
}
- (id)initWithName:(char *)name{
    if (self = [super init]){
        self.name=name;
    }
    return self;
}
- (void)sayHello {
    printf("Hello, my name is %s!\n", self.name);
}
@end

int main() {
    Person *brad = [[Person alloc] init];
    brad.name = "Brad";
    [brad sayHello];
    Person *tom = [[Person alloc] init];
    tom.name = "Tom";
    [tom sayHello];
}

compiler output:
main2.m:18:24: error: class method '+alloc' not found (return type defaults to
      'id') [-Werror,-Wobjc-method-access]
    Person *a = [super alloc];
                       ^~~~~
main2.m:26:23: error: 'Object' may not respond to 'init' [-Werror]
    if (self = [super init]){
                ~~~~~ ^
main2.m:27:19: error: local declaration of 'name' hides instance variable
      [-Werror,-Wshadow-ivar]
        self.name=name;
                  ^
main2.m:15:17: error: method definition for 'initWithName' not found
      [-Werror,-Wincomplete-implementation]
@implementation Person
                ^
main2.m:11:1: note: method 'initWithName' declared here
- (id)initWithName;
^


text:
Q: Proving a transformation preserves a property Let $f(x_1,x_2,\ldots,x_n)=(x_1/(\sum_{i=1}^n x_i),x_2/(\sum_{i=1}^n x_i),\ldots,x_n/(\sum_{i=1}^n x_i))$ be in $\mathbb{R}^n_{++}$, and $X$ be a set of points in $\mathbb{R}^n_{++}$.
I was trying to prove if the following holds:
$$
hull(f(X))=f(hull(X))$$
where $hull(X)$ is the convex hull of $X$. $f$ is a projection onto probability simplex in $n$ dimensions, but I was not able to prove the equality.
Another question that I tried to prove is, does this transformation preserve convexity?  Thanks a lot.

A: The answer to the second question is yes, the image under $f$ of a convex set is convex. In general, the image of a segment $AB$ under $f$ is the segment $f(A)f(B)$ (provided $f$ is well-defined throughout the segment $AB$, which is certainly the case if $A, B \in (0,+\infty)^n$).
Let $H$ be the hyperplane $x_1 + \dots + x_n = 1$. Then $f$ is the central projection onto $H$ with respect to the origin $O$. The domain of $f$ is the complement of the hyperplane $H_0 \colon x_1 + \dots + x_n = 0$, that is, the union of the two open half-spaces determined by $H_0$.
Now assume the segment $AB$ is contained in the domain of $f$, i.e., $A$ and $B$ are on the same side of $H_0$. If $O, A, B$ lie on the same line, there is nothing to prove, as $f$ is constant on the segment $AB$. Otherwise, the whole problem is situated within the plane $\alpha$ through $O, A, B$.
Let $l, l_0$ be the lines of intersection of $\alpha$ with $H, H_0$. Then $A, B$ are points in $\alpha$ on the same side of $l_0$, which we can assume without loss of generality to be the same side where $l$ is. The problem is to see that if $C$ is a point between $A$ and $B$, then $f(C)$ is between $f(A)$ and $f(B)$ on line $l$ (and all points of the segment $f(A)f(B)$ are of this form).
Now this is reduced to a well-known fact of plane geometry: given three rays $r_1$, $r_2$ and $r_3$ all in the same plane, if at least one segment drawn from $r_1$ to $r_2$ intersects $r_3$, then all segments drawn from $r_1$ to $r_2$ intersect $r_3$.
It is enough to apply this fact to the rays $r_1 = OA$, $r_2 = OB$, $r_3 = OC$ and the segments $AB$, $f(A)f(B)$.
To answer the first question, it is enough to prove that if $C$ is a convex subset of $H$, then the portion of $f^{-1}(C)$ lying in a chosen half-space with respect to $H_0$ is also convex. This can be given a similar proof by restricting to a plane as above. Then it is enough to see that the region lying between two rays is convex.


text:
Q: Unknown member function inside union I am reading a piece of code. I believe this is in C++:
 union Float_t
 {
    Float_t(float num = 0.0f) : f(num) {}
    // Portable extraction of components.
    bool Negative() const { return (i >> 31) != 0; }
    int32_t RawMantissa() const { return i & ((1 << 23) - 1); }
    int32_t RawExponent() const { return (i >> 23) & 0xFF; }

    int32_t i;
    float f;
    #ifdef _DEBUG
    struct
    {   // Bitfields for exploration. Do not use in production code.
         uint32_t mantissa : 23;
         uint32_t exponent : 8;
         uint32_t sign : 1;
    } parts;
    #endif
};

Can someone explain two things?
1..
 Float_t(float num = 0.0f) : f(num) {}

What is this line saying? What does f(num) mean when f isn't defined?
2.. Why are #ifdef _DEBUG and #endif necessary in the latter part of the code?
Thanks.

A: Float_t(float num = 0.0f) : f(num) {}

This is a constructor that takes a parameter that sets the value of Float_t::f. The constructor has a default parameter that sets Float_t::f to 0.0f
Example of constructor calls:
Float_t f1; // f1.f == 0.0f; is true
Float_t f2 = Float_t(3.f); // f2.f == 3.0f; is true

2.. Why are #ifdef _DEBUG and #endif necessary in the latter part of the code?

The code writer uses the information for debugging purposes and doesn't want the user of the union to access that information.
Note that the added information doesn't affect performance or memory usage if enabled in production code.
Note that all union members are at the same memory address and the following information for f1 and f2 hold
f1.f == 0.0f; // evaluates to true
f1.i == 0; // evaluates to true
f1.parts.mantissa == 0; // evaluates to true
f1.parts.exponent == 0; // evaluates to true
f1.parts.sign == 0; // evaluates to true

f2.f == 3.0f; // evaluates to true
f2.i == 1077936128; // evaluates to true
f2.parts.mantissa == 4194304; // evaluates to true
f2.parts.exponent == 128; // evaluates to true
f2.parts.sign == 0; // evaluates to true

sizeof(f1) == 4; // evaluates to true

reinterpret_cast<float&>(f2.i) == f2.f; // evaluates to true

EDIT
The constant values in the above code are obtained on a little endian configuration with the ordering of data declared as bit fields is from low to high bit


text:
Q: Test AngularJS service initialization I have an AngularJS service that loads data from localStorage while "initializing" (i.e. in the factory function), like this:
module.service('myService', function ($localStorage) {
    var data = $localStorage.data;
    if (!isValid(data)) // isValid omitted on purpose, not relevant.
      data = undefined;

    return {
      getData: function() {
        return data;
      }
      setData: function(value) {
        if (isValid(value))
          data = value;
      }
    };
}

In my tests, I'd like to check that data is actually loaded from localStorage if the value is present there and valid; this is not about testing isValid, but the service initialization that uses it and $localStorage.
I'd like to be able to call the myService factory inside my test. I'm getting an initialized instance of it in the beforeEach hook since I need to test methods of myService as well. I think I need to have a different instance created for my specific initialization test, but since services are singletons in AngularJS, I'm not sure whether this can be done.
describe('myService', function() {
  myService = $localStorage = null;

  beforeEach(module('app'));

  beforeEach(inject(function($injector) {
    myService = $injector.get('myService');
    $localStorage = $injector.get('$localStorage');
  });

  it('should look for stuff in localStorage on creation', function () {
    $localStorage.data = 'my data';
    // I'd like to call service factory here!!
    myService.getData().should.equal('my data');
  });
});

Can this be achieved? Does my code have a difficult-to-test structure, or am I disrespecting the "Angular way" and this should be done differently?

A: Try this:
describe('myService', function() {
  myService = $localStorage = null;

  beforeEach(module('app'));

  beforeEach(inject(function($injector) {
    $localStorage = $injector.get('$localStorage');
    $localStorage.data = 'my data';
    myService = $injector.get('myService');
  });

  it('should look for stuff in localStorage on creation', function () {
    myService.getData().should.equal('my data');
  });
});


text:
Q: View CPU & Memory Usage in Azure AKS Dashboard Hello I upgraded my Azure AKS cluster from 1.12.6 to 1.14.7.
On version 1.12.6 when I connected to Dashboard in a web browser(by az aks browse) I view CPU & Memory Usage
Now on new version I cannot see it
I have to enable something?

A: Unfortunately, your issue is an existing problem and it's still on the way to be fixed. You can take a look at the issue in Github. If it's necessary for you, please use the version 1.12.6 as before.


text:
Q: Angular Routing: Is it possible to use different 'path' strings for different languages? I'm doing an i18n Angular app, so far it works great.
However I have same route strings for different languages, which isn't best for SEO.
Is it possible to have 'path' properties of Routes array be different for each language?
Ex:
const appRoutesEN: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '**', component: PageNotFoundComponent }
];

Is it possible to define also a appRoutesFR: Routes if yes how I can use it?  Shall I inject LOCALE_ID to routing module? If so how?

A: For the moment there seems to be no easy solution for this. I'll update if I find one.
Angular i18n people are working to integrate code level internationalization, maybe then.
Best solution I can come up with is to change routing module(s) in your code and routerLink attributes in templates and all links in other parts of your code for each language, then build your app for each language separately.
Not ideal at all.
UPDATE
As recommended by @estus, I've tried out Greentube/localize-router.
I wasn't happy to install dependencies like @ngx-translate/core and @ngx-translate/http-loader since I'm using Angular i18n implementation/tools and not ngx-translate.
It works till it hits a lazy-loaded module with child routes.
So if you don't have any lazy loaded module with children, localize-router is the way to go.
UPDATE
Lazy loaded modules are now supported in the latest version of localize-router.
Angular i18n will be supported once the programatic translations arrive.

A: If you need different routing per language as you describe in your comment you could have a dedicated routing module for each individual language. Then define in the angular-cli.json for each language a dedicated app with it's own main.ts and it's own AppModule, pulling in only the routing module required for the particular language.
  "apps": [
   {
      "root": "src",
      "name": "yourapp_FR",
...
      "main": "./app/yourapp_FR/main.ts",
...
    },
   {
      "root": "src",
      "name": "yourapp_DE",
...
      "main": "./app/yourapp_DE/main.ts",
...
    }
    ]

You then build for each language the app like this:
ng build --app yourapp_FR --i18n-file src/i18n/messages.fr.xlf --locale fr --i18n-format xlf --aot

This way you set it up once and can build each time without commenting out anything.
I do not have the full context. You say having routes per language is better for SEO. I do not understand this, but if you say so, OK. However I would not like dedicated routing for each language. This means a lot of redundancy and more maintenance.

A: If you are already using something like @ngx-translate/core then you can create your own mapping instead of adding more external libraries.
Example:
function generateI18nRoutes(
    elements: Array<{ i18nPaths: string[]; component: any; data: object; canActivate?:
[] }>
): Routes {
    return elements.reduce(
        (accumulator, currentValue) => [
            ...accumulator,
            ...currentValue.i18nPaths.map((path: string) => ({
                path,
                component: currentValue.component,
                data: currentValue.data,
                canActivate: currentValue.canActivate
            }))
        ],
        []
    );
}

And then use it like:
const routes: Routes = [
    {
        path: "admin",
        component: AdminLayoutComponent,
        canActivate: [AdminAuthGuard],
        children: generateI18nRoutes([{ i18nPaths: [""], component: HomeComponent, data: { title: "ADMIN" } }])
    },
    {
        path: "",
        component: GeneralLayoutComponent,
        children: generateI18nRoutes([
            { i18nPaths: [""], component: HomeComponent, data: { title: "HOME" } },
            {
                i18nPaths: ["sign-in", "iniciar-sesión", "iniciar-sessão"],
                component: SignInComponent,
                data: { title: "SIGN_IN" }
            }
        ])
    },
    {
        path: "**",
        component: PageNotFoundComponent,
        data: { title: "PAGE_NOT_FOUND" }
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}


text:
Q: raw_input alternative for node.js I am creating a server application and I would like to be able to write commands like start server, stop server, broadcast("clients","Hello") in to my application but I can't figure out how to do it in node.
I do know how it would look inside python.
while on == 1:
    cmd = raw_input("user> ")
    if cmd == "start server":
        startserver()
    elif cmd == "stop server":
        stopserver()
        on = 0

I have seen some npm modules for this but they require me to write arguments, I want to make this a console type application.
Thanks

A: Here's a snippet that was recently removed from commander.js. Something along these lines should work.
process.stdout.write("user> ");
process.stdin.setEncoding('utf8');
process.stdin.once('data', function(val){
    //look at val here and execute startserver() et al accordingly
}).resume();

A: This page explains exactly what you need


text:
Q: ¿Cómo actualizar el valor de una clave foránea dependiendo de una acción en otro modelo en django? Soy nuevo en Django y estoy realizando una aplicación con varios modelos, pero para que entiendan mejor usaré un ejemplo de gestionar el préstamo de libros en una biblioteca en los cuales tengo 4 modelos usuarios, libros, prestamos y estados.
Modelo Estado
En este modelo habrán varios estados(libre, prestado) pero para el ejemplo solo esos 2, en este caso sé que se puede poner los estados en un choice pero me dijeron que creara una tabla para evitar tener que editar el código si quieren agregar otros estados.
class estado(models.Model):
id = models.AutoField(primary_key=True, unique=True, null=False,verbose_name="Id")
condicion = models.CharField(max_length=50, verbose_name="Estado")

def __str__(self):
    return self.condicion

Modelo Libro
class libro(models.Model):
id = models.AutoField(primary_key=True, unique=True, null=False,verbose_name="Id")
titulo = models.CharField(max_length=50, verbose_name="titulo")
categoria = models.CharField(max_length=50, verbose_name="categoria")
autor = models.CharField(max_length=20, verbose_name="autor")
estado = models.ForeignKey(estado, on_delete=models.CASCADE, null='False', verbose_name="estado",default=1)
fecha_publicación = models.DateField(verbose_name="Fecha de Publicación")

def __str__(self):
    return self.titulo

Modelo usuarios
class usuarios(models.Model):
id = models.IntegerField(primary_key=True, unique=True,null=False,verbose_name="Identificación")
nombre = models.CharField(max_length=50, verbose_name="Nombre")
dirección = models.CharField(max_length=100, verbose_name="dirección")
telefono = models.CharField(max_length=20, verbose_name="Teléfono")
email = models.EmailField(max_length=50, verbose_name="Correo Electronico")

def __str__(self):
    return self.nombre

Modelo Préstamo
class prestamo(models.Model):
id = models.AutoField(primary_key=True, unique=True,null=False,verbose_name="Id")
libro = models.ForeignKey(libro, on_delete=models.CASCADE, null='False', verbose_name="libro")
usuario = models.ForeignKey(usuario, on_delete=models.CASCADE, null='False', verbose_name="Usuario")
fecha_inicio = models.DateField(auto_now_add=True, verbose_name="Inicio Prestamo")
fecha_final = models.DateField(verbose_name="Fin Préstamo")

def __str__(self):
    return self.libro.titulo

lo que quiero hacer es que el estado del libro se actualice si existe un préstamo relacionado con el id del libro, por defecto es libre pero que cambie a Prestado si existe el préstamo, eh intentado hacerlo desde el modelo y desde la vista pero no eh podido.
de antemano muchas gracias


text:
Q: PHP get characters after # in descriptions How can I make each product identification number mentioned in the below description into variables, excluding the # pulling them from the description in PHP?

Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D.
  (25.2 x 68mm), are supplied as containers. Additional or replacement
  tubes #8909 are available.
As a safety precaution, BioQuip recommends using the #1135Y HEPA
  filter with this aspirator.
Also see #1135X aspirator syringe bulb. It allows users to aspirate
  specimens without inhaling particulate matter.

A: Solution
Use Regex. This regex I wrote (\#.+?) (note the space at end) matches the product id numbers. Try it out here. To use the regex with PHP use preg_match_all:

preg_match_all
(PHP 4, PHP 5, PHP 7) preg_match_all — Perform a global regular
  expression match
Description
int preg_match_all ( string $pattern , string $subject [, array
  &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

Code
<?php
    $pattern = "/(\#.+?) /";
    $string = "Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available. As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator. Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.";
    preg_match_all($pattern, $string, $matches);
    print_r($matches[0]);
?>

Output
Array
(
    [0] => #8909
    [1] => #1135X
    [2] => #1135Y
)

Once, you have the array, you can access the codes, that were found, by grabbing them from $matches[0]. For example to print the first match, just do this:
$matches[0][0]
The second match:
$matches[0][1]
and, if you want to get really fancy you can print it out into a table:
<?php
    $pattern = "/(\#.+?) /";
    $string = "Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available. As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator. Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.";
    preg_match_all($pattern, $string, $matches);

    echo "
";
    echo "
";
    echo "Product Codes	";
    echo "
";

    foreach ($matches[0] as $match)
     {
      echo '' . $match . '	';
      echo '
';
     }
?>

This would output:

Try it out
PHP Sandbox

A: One could use this regular expression (regex):
/#(\w+)/

along with preg_match_all() which performs a global search for data matching a regex, and stores what it finds in an array, as follows:
<?php

$str = "Two 9-dram clear styrene tubes with snap-on caps, 1 x 2-3/4″ I.D. (25.2 x 68mm), are supplied as containers. Additional or replacement tubes #8909 are available.

As a safety precaution, BioQuip recommends using the #1135Y HEPA filter with this aspirator.

Also see #1135X aspirator syringe bulb. It allows users to aspirate specimens without inhaling particulate matter.";

$pat = "/#(\w+)/";
if ( preg_match_all( $pat, $str, $matches )) {
  $popped = array_pop( $matches );
  list( $alpha, $beta, $gamma ) = $popped;
  echo "The IDs are as follows:\n\n$alpha\n$beta\n$gamma\n";
}

See demo
This regex specifies a hashtag followed by parentheses to "remember" one or more word characters, i.e.  numeric or alphabetical data. By  enclosing this expression with parentheses, the hashtag will be excluded and the remaining data stored in $matches[1]. Once $matches contains data, you are done unless you wish to utilize $matches[1] to create three unique variables and optionally display their values.
You could dispense with using a regex and use the following code with the above-indicated value of $str:
<?php
$ids=[];
$a = explode("#",$str);
array_shift( $a );
$ids = array_map( function( $e ) {
                  return explode(" ",$e)[0];
                  },$a);

print_r($ids);

See demo
By avoiding preg_match_all(), the second solution may offer the advantage of better performance. Alternately, you can split the array returned by explode() into a list that only includes relevant information, and then create an array of the list variables for array_map(), as follows:
<?php

$ids=[];
list(,$a,$b,$c) = explode( "#",$str );
$ids = array_map(function( $e ) {
                  return explode(" ",$e )[0];
                  },[ $a,$b,$c ]);

print_r( $ids );

See demo

A: Without regex, you could split the string by space and add a substring of each word beginning with # to an array of results.
foreach (explode(' ', $description) as $word) {
    if ($word[0] == '#') $products[] = substr($word, 1);
}

I think it's safe to assume this will be slower than regex, though.


text:
Q: Ubuntu 22.04 missing Sun RPC (ONC/RPC) libraries Im trying to install Ganglia from source, using (several) Ubuntu 22.04 machines, with all the latest updates installed, and freshly rebooted.
On compile im getting the errors:
configure: error: your system is missing the Sun RPC (ONC/RPC) libraries

I can't see any packages that provide the files either


text:
Q: Local-storage backbone models I am trying to use, https://github.com/jeromegn/Backbone.localStorage, to store models. I ve got a JSON and I am fetch data with backbone and I am trying to local store the fetched data. The first variable of json file is a time key called tstamp. How can I store and retrieve data based on tstamp attribute?? My code:
// Backbone model Creation for highlight
var HighlightModel = Backbone.Model.extend({

    defaults: {
        tstamp: "1234",
        att: "",

    },

    initialize: function () {

    }

});

//Backbone model initialization
highlight = new HighlightModel();

var HighlightList = Backbone.Collection.extend({

    model: HighlightModel,
    localStorage: new Backbone.LocalStorage("highlightList"),
    url: 'data.json'

});

var HighlightView = Backbone.View.extend({

    el: "#highlights",
    template: _.template($('#highlightTemplate').html()),
    render: function (eventName) {

        _.each(this.model.models, function (highlight) {
            var highlightTemplate = this.template(highlight.toJSON());

            //push data to obj for highlight script
            mp = highlight.toJSON();
            // Add data to DOM element
            $(this.el).html(highlightTemplate);
        }, this);

        return this; // .remove(); to stop displaying
    }

});

var highlights = new HighlightList([highlight]);
var highlightsView = new HighlightView({
    model: highlights
});

// Fetching data from server every n seconds
setInterval(function () {

    highlights.fetch({
        reset: true
    });

   highlight.add(sentiments);
highlights.save();
}, htCycle); // Time in milliseconds

highlights.bind('reset', function () {

    highlightsView.render();
    console.log('render');

});

EDIT:
I change my code a little bit, now i have at local storage just store the default model {"tstamp":"1234","att":"","id":"4fb1b437-0e37-8eb7-ed3c-cbd9d0dcff98"}. I want to store the fetched data from server to localstorage.


text:
Q: How to use sed/perl to find only 2d arrays and replace text? Currently I have tons of code that looks like this:
static double    testVar1          [2][8]  = {0.0}    ;  /* This is for testing var 1 */
static double    var_test2         [3][2]  = {0.0}    ;  /* This is for testing var 2 */
static double    var_test3         [4]     = {0.0}    ;  /* This is for testing var 3 */

2d arrays in c++ initialize with double curly brackets, so I need to only find the 2d arrays and change it like this:
static double    testVar1          [2][8]  = {{0.0}}  ;  /* This is for testing var 1 */
static double    var_test2         [3][2]  = {{0.0}}  ;  /* This is for testing var 2 */
static double    var_test3         [4]     = {0.0}    ;  /* This is for testing var 3 */

I have been trying with sed to use groupings, but I can't figure out how to escape the brackets, some posts suggest not escaping at all. I have also tried without extended regular expressions.
Just now, I found out only 9 groupings in sed are possible, so now completely stuck. Any suggestions?
sed -i -r 's/(.*)(\[)([0-9]+)(\])(\[)([0-9]+)(\])(.*)(\{)(0.0)(\})(.*)/echo "\1\2\3"/ge'

A: Use a perl script with the following regex:
\w+\s*(?:\[\d+\]){2}\s*=\s*\K\{([\d.]*)\}

And replace this with \{\{\1\}\}, see a demo on regex101.com.

Broken down, this says:

\w+            # at least one word character
\s*            # Zero or more spaces
(?:\[\d+\]){2} # [0][1] or any other two-dimensional array
\s*=\s*        # spaces = and spaces
\K             # "forget" everything
\{([\d.]*)\}   # match and capture {number}

A: A Perl one-liner, cautious about literals such as 2u and 1e-06l (etc)
perl -pe's/(?:\[ [^]]+ \]){2} \s*=\s* \K (\{ [^}]+ \})/{$1}/x' in > out

The (?:) groups (without capture) and (?:\[[^]]+\]){2} is for [n][m]. The \K is the form of the positive lookbehind, which also drops previous matches so we don't have to put them back.
With an integer inside [] being just digits and with a float in {} being n.m this simplifies
perl -pe's/(?:\[\d+\]){2}\s*=\s*\K( \{[\d.]+\} )/{$1}/x' in > out

Note that [\d.] allows for all kinds of wrong things, like .2..3, but that is a different issue.

However, watch out for use of literals for numbers such as 2u (with the suffix) which are fine as indices as well, along with vec[1.2e+01] or even vec[1.2]. The varied notation for float/double literals is also more likely to show up in data. Altogether I'd go with a more rounded pattern like
perl -pe's/(?:\[ [\d\w+-.]+ \]){2}\s*=\s*\K(\{ [\d\w+-.]+ \})/{$1}/x' in > out

Keep in mind that this allows various wrong formats and so it doesn't check data well.

A: Here is a sed attempt with the regex wrinkles ironed out.
sed -i -r 's/(.*\[[0-9]+\]\[[0-9]+\].*)(\{0.0\})(.*)/\1{\2}\3/'

You had significant amounts of unmotivated additional grouping parentheses so \1\2\3 would only refer to the very beginning of the match.  I simply took them out.  Remember, the captures are ordered from left to right, so the first left parenthesis creates group \1, the second captures into \2, etc.
The GNU sed extension /e allows you to invoke the shell on the replacement string but in this case this added no value and introduced significant additional possible errors, so taking it out was a no-brainer.  The /g option would make sense if you expected multiple matches per line, but your example shows no examples of input lines with multiple matches, and the entire script would need to be rather more complex in order to support that, so I took that out as well.
Depending on the language you are attempting to process and the regularity of the files, you might want to permit whitespace between the closing and opening square brackets, or not; and the "anything" wildcard between the closing square bracket and the opening curly bracket looks somewhat prone to false positives (matching where you don't want it to) -- maybe change it to only permit whitespace and and equals sign, like [ =]* instead of .*

A: Another approach with sed:
sed -i -r 's/((\[[0-9]\]){2} *= )(\{[^}]*\})/\1{\3}/' file

and same in BRE mode :
sed -i 's/\(\(\[[0-9]\]\)\{2\} *= \({[^}]*}\)\)/\1{\2}/' file

A: sed -i '/]\[/s/[{}]/&&/g' file


text:
Q: How to use post method for xml data using php I have a api which sends messages to the people ,and the api in the form of url ,which takes user login details and the phone number as input for the url .At a time a time I am able to send 10 sms ,but I want to implement it for bulk sms .
I am trying this code ,but it's working only for 10sms,if we are providing more than 10 mobile numbers it's not working ,can anyone suggest me what mistake I making in my code
Code:
$numbersarray=explode(",",$numbers);    //stores numbers as array

    /*XML API by Aditya*/
    $numbers_xml_string=""; //stores XML string of numbers and message
    foreach($numbersarray as $num){
        $numbers_xml_string.="<Message><To>".$num."</To><Text>".$text."</Text></Message>";
    }
    //XML string to be encoded
    $xmlstring="<SmsQueue><Account><User>".$user."</User><Password>".$password."</Password></Account><MessageData><SenderId>".$api_id."</SenderId><Gwid>1</Gwid><DataCoding>0</DataCoding></MessageData><Messages>".$numbers_xml_string."</Messages></SmsQueue>";

    $xmlstring=urlencode($xmlstring);//encode the string
    //prepare URL
    $url="http://login.smsgatewayhub.com/xmlapi/pushsms.aspx?data=".$xmlstring;
    echo "url".$url;

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($numbersarray),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

A: There may be two reasons according to your sample code:
First you may only have permissions to send 10 SMS messages.
Second you can only send 10 messages every a certain time. In this case you should know what is the time you should wait and run your script each this time to send sms to the remaining numbers.


text:
Q: Disable/Block a Key with another Key while its pressed and held down So in this game im moving my charachter with the WASD keys, but if i hold down the A and D key at the same time,
the game register that as a forward movement (W key |) so the charachter starts to move forward instead of the strafe actions (Left) \  (right) /.
So i need a code which is prevents the A and D key simultaneous pressing.
CHECK THIS GIF, SO U CAN SEE WHAT I MEAN!
I want A and D override each other (Im not using the W key), because if i hit both A and D at the same time my character moves forward, not like this \  /
and i want to avoid the forward movements.
I want insantly changed fast Left \ and Right / strafing only.
Here is the code what i got so far:
~a::
If (GetKeyState("d", "p"))
{
    Send {d up}
    d = 0
}
Return

~d::
If (GetKeyState("a", "p"))
{
    Send {a up}
    a = 0
}
Return

a up::
If (d)
{
    Send {d down}
    d = 0
}
Return

d up::
If (a)
{
    Send {a down}
    a = 0
}
Return

Basicly this code almost working.
The problem is if i don't change the numbers i can't change directions continuously i need to let go the keys. It stops after 1 direction change. If i change the numbers its working, but after a few direction change its getting toggled either left or right. Even if i let it go its moving left or right....
Any ideas? thx

A: This should work. Try it and let me know.
$*a::
$*d::
    SendInput, {a Up}{d Up}
    StringReplace, hk, A_ThisHotkey, % "$*"
    SendInput, {%hk% Down}
    KeyWait, % hk
    Send, {a Up}{d Up}
return

A: EDIT: You can play around with the code below. Maybe it will help you out
#SingleInstance, force
#Persistent
#NoEnv
#MaxThreadsPerHotkey, 1

~a & d::
~d & a::
Send, {a up}
key := "d"
SetTimer, pressdown, 10
return

~d::key := "d"
~a::key := "a"
~a up::key := "d"
~d up::key := "a"

pressdown:
if GetKeyState(key, "p")
{
    SendInput, {%key% down}
    SetTimer, pressdown, 30
}
else {
    SetTimer, pressdown, Off
    SendInput, {%key% up}
}
return

This script cannot allow A, or D to be simultaneously pressed.


text:
Q: Saving several tab panels with one button I have three seperate tab panels with each being a table in my database. What i'm trying to do is that on a click of a button is save the content of all the three tabs in the database at the same time. I managed to get the PK "Aid" of the current active tab, however when i try to access the second inactive tab B with window.frames["frm_B"] and alerting the result, i'm getting undefined. Any help would be much appreciated.
tabPanel = Ext.create('Ext.tab.Panel', {
        region: 'center',
        activeTab: 0,
        autoScroll: true,
        tbar: [{
            xtype: 'button',
            text: 'Save',
            handler:function(){saveForm("frm_A", save);}
        }],
        items: [
                {
                    id:"panel_A",
                    html: "<iframe src= '"+A_url +"' width='100%' height='100%' id='frm_A' name='frm_A' frameborder=0 />",
                },{
                    id:"panel_B",
                    html: "<iframe src='"+B_url+"'  width='100%' height='100%' id='frm_B' name='frm_B' frameborder=0 />",
                },{
                    id:"panel_C",
                    html: "<iframe src= '"+C_url+"' width='100%' height='100%' id='frm_C' name='frm_C' frameborder=0 />",
                }]
        });

    viewport = new Ext.Viewport({
        layout:'border',
        items:[tabPanel]
    });

    function save(record){

        var Aid = record.getKey();
        var doc =  window.frames["frm_B"];
        alert(doc);
        try {
            doc.RECORD.getField("A_ID").setRealValue(Aid);
            doc.RECORD.update(closeAndRefresh, viewExtError);

        }
        catch(e){
            showError(e);
        }

    }

A: I guess your problem is that your <iframe name='frm_B'> is not rendered (added to DOM) when you try to get it with window.frames["frm_B"].
When you create tab panel with Ext.create('Ext.tab.Panel', {}); you just create JS object, not all of its items: [] added to DOM immediatelly.

A Container's child Components are rendered by that Container's layout
  manager when the Container is first rendered.

For example tabpanel tabs added to DOM when you first time open that tab.
Fiddle to illustrate it
Solution for your question depends on your code actually, but as workaround you can use .render() method of tab panel child panels...


text:
Q: Upsert subscriber data on Triggered Send Background
Subscribers perform on action on a website. The subscriber record is then added into a Triggered Data Extension and an email is sent out as part of the API call / Triggered Email Interaction. Tried, true, tested.
Scenario
I am wondering if when the API call is made inserting the subscriber into the Triggered Send Data Extension, if it could update that subscribe's record if it found a matching Primary Key? So for example, we add an additional attribute into the Data Extension and make it the Primary Key, and when that API call runs it either adds a new record or updates the existing one based on the Primary Key passed through the API call.
I've tested it out and all email sends are stuck in queueing for the triggered email interaction, leading me to believe it wasn't happy with the Primary Key.
Before sinking in more hours on what may be a lost cause I thought to check if anyone has ever attempted this before, and if so what results they found.

A: The above scenario is not possible with Trigger send Data extension template. Trigger send DE is used for the purpose of tracking the email sends, so every time you do a trigger send it will insert a new record in the Trigger send DE. Instead, you create another dataextension an upsert the values in that DE.


text:
Q: Definition of Source Power for RF Transmisison Line Source So I know this is going to seem like a very simple question, but my book provides no definition. If the power P_in is defined as the power the goes from the source into the load in a transmission line, what is the source power in terms of the generator voltage, generator internal resistance, and any other relevant constants.
I've seen elsewhere the book that $$P = \frac{1}{2} Re\{VI^*\}$$. In the case of a generator with some internal impedance (resistance in the simple case) Z_G and some voltage source V_G what is the power it can deliver
$$\frac{V_G^2}{Z_G}$$ or
$$\frac{1}{2} \frac{V_G^2}{Z_G}$$ and why?
I'm just not fundamentally understanding all our different power definitions for these problems, and it would be very helpful if someone could provide a concise summary of what I need to know to tell what's going on. Thanks.

A: While the physics of computing power remains the same for all situations, the context may require that you choose particular values for impedance or voltage, for particular power definitions.
In the context of RF, the 'source power' of a generator will usually be defined as the power it actually delivers into its defined system impedance, which is usually 50 or 75 ohms. This remains the definition whether the generator has an output impedance of nominally the system impedance, or very different from it. If it's different, then this is not the maximum power that can be got from the generator.
If you load a generator with a load other than the system impedance, then it will produce a different power. This new power can be computed in terms of the defined source power, and corrections to it based on source and load matching to the system impedance. This is one of the benefits of referring all measurements to the system impedance, it allows the details of source and load match to be handled systematically, and allows small corrections to be ignored.
When comparing different formulae for power, take care to understand where the voltage is being measured, so whether at the physical port from the generator, or at the theoretical voltage source that drives the theoretical output impedance before the port.


text:
Q: convexity of the product of two entropy-like functions Consider the functions $T_p(q)= \sum_i q_i^p$, where p>1 and q is a finite-dimensional vector satisfying $\sum_i q_i = 1, q_i >0$ (ie, a probability mass function).  In information-theoretic terms, these are equivalent (up to constants) to the Tsallis entropies of q
$T_p$ is a convex function of $q$ for any $p>1$. This is also true of its generalization as a function of (Trace-normalized) Hermitian operators, ie $T_p(A) := Tr(A^p) $
The question is: are products of the form $(T_{p_1})^{r_1}\cdots(T_{p_n})^{r_n}$, where $r_i >1$, also convex?
Note that in general $T_{p_i}, T_{p_j}$ may define different partial orders, so it would appear that simple arguments that give sufficient conditions for the product of two convex functions to be convex, such as this one,  cannot be used. On the other hand, I haven't found any counterexamples yet.


text:
Q: Button click to setOnGenericMotionListener event using mouse scroll work Sir,
    I am work with on button key and it show some value like for Eg:5 if i have move mouse cursor point to button, then on setOnGenericMotionListener event using mouse scroll the Eg: 5 is varied to increase and decrease value depend upon mouse scroll but now i want to move any place of my mouse cursor point have need to set setOnGenericMotionListener event using mouse scroll event to work on that particular button how it possible to perform this event?

Activity

public class MainActivity extends Activity {
Button button;
int x,f;
@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button=(Button)findViewById(R.id.button1);
    button.setOnGenericMotionListener(new OnGenericMotionListener() {
    @Override
        public boolean onGenericMotion(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_SCROLL:
                if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) > 0.0f)
                {
                    x=Integer.parseInt(button.getText().toString());
                    f=x+5;
                    button.setText(""+f);
                }
                else
                {
                    x=Integer.parseInt(button.getText().toString());
                    f=x-5;
                    button.setText(""+f);
                }
            }
            return false;
        }
    });
}}

A: You should not use this method to detect the touch event.
In View.onGenericmotionEvent description:
    /**
     * Implement this method to handle generic motion events.
     *

     * Generic motion events describe joystick movements, mouse hovers, track pad
     * touches, scroll wheel movements and other input events.  The
     * {@link MotionEvent#getSource() source} of the motion event specifies
     * the class of input that was received.  Implementations of this method
     * must examine the bits in the source before processing the event.
     * The following code example shows how this is done.
     *

     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
     * are delivered to the view under the pointer.  All other generic motion events are
     * delivered to the focused view.
     *

     *
 public boolean onGenericMotionEvent(MotionEvent event) {
     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) {
     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
     *             // process the joystick movement...
     *             return true;
     *         }
     *     }
     *     if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) {
     *         switch (event.getAction()) {
     *             case MotionEvent.ACTION_HOVER_MOVE:
     *                 // process the mouse hover movement...
     *                 return true;
     *             case MotionEvent.ACTION_SCROLL:
     *                 // process the scroll wheel movement...
     *                 return true;
     *         }
     *     }
     *     return super.onGenericMotionEvent(event);
     * }

     *
     * @param event The generic motion event being processed.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onGenericMotionEvent(MotionEvent event) {
        return false;
    }

Some cases of usage for this method you can find here
Btw, you should use GestureDetector instead to handle your gesture.


text:
Q: Could not start liferay server I can not start my liferay server due to that error :
The JRE could not be found. Please edit the server to change the configured JRE

But in my preferences JRE is set :
jre1.8.0_131
C:\Program Files\Java\jre1.8.0_131

and path to it is correct.
This problem occured when I deleted JRE to check something( cause I've had a problem with portlet deployment ). But the path and variable which is set now is exactly the same, the server do not want to start though.
Should I clean something or add it somwhere else?
I've got my server configured and I do not want to loose all data.
It's liferay 7


text:
Q: How to create connection in oracle-sqldeveloper without any error? I'm new to Oracle database (I'm using Oracle Database 19C) and sqldeveloper. I have this problems:
When creating new connection I always face with errors when test the connection. First of all, I try to create testing database connection. I set username as 'sys' and set it's role as 'SYSDBA'. Then I set SID as 'orcl' and hit test button, then the errors start to occur like "Status : Failure -Test failed: ORA-00604: error occurred at recursive SQL level 1 ORA-12705: Cannot access NLS data files or invalid environment specified"
I tried multiple solutions on the internet like adding the following two parameters in sqldeveloper.conf but still doesn't work. (AddVMOption -Duser.language=en AddVMOption -Duser.country=US)
Second, I tried to authenticate as personal user(when created while installing oracle19c) but it says "Status : Failure -Test failed: ORA-01017: invalid username/password; logon denied".
Lastly, I tried changing SID as 'xe' but program still shows me "Listener refused the connection with the following error: ORA-12505".
Please help how to create any database connection without error. I tried formatting my laptop 3 times but the program still don't work.


text:
Q: Access fragment's variable outside the fragment I have a single activity, multiple fragments and multiple subview. In some cases I have to access a fragment's variable to which the subview(extends RelativeLayout) is attached. How can I do this?
I can access the views by
getActivity().getFragmentManager.getFragmentByTag("TAG").getView().findViewById()

But can't access the variables in that fragment.

A: getFragmentByTag returns a Fragment, try casting the fragment you get back to your implementation's class and then accessing them like so:
((MyCustomFragment)getActivity().getFragmentManager.getFragmentByTag("TAG"))
    .getMySuperSecretField();

If you post some more details/code, I might be able to diagnose you issue better


text:
Q: How to selectively use multiple libraries compiled with same code but with different compiler flags We're building a C++ library (say libCore) that will be used from another C++ library (say libClient). We're using Android NDK (uses clang) with CMake.
In our case, we have multiple builds of libCore optimized based on cpu features available on target devices. For example, libCore-neon for devices that has ARM NEON fpu and libCore-simd for devices without NEON.
By the way, these libCore-xxxx are built from the same source code. The only difference is that libCore-neon is built with NEON specific compiler flags (-mfpu=neon) which is not used for libCore-simd.
Now libClient shall check if the device has NEON at runtime and use libCore-neon, if not it shall use libCore-simd.
One solution is to load the library at runtime using dlopen. We don't prefer it since we don't think it is safe approach to use in all versions of android.
All these belong to same code base. It doesn't matter if these libraries are static or shared. These need not even be separate libraries. We just want to avoid code duplication since the same code is compiled with different flags.
Is there any other approach we can follow to run the most optimized code work on appropriate devices?


text:
Q: How to display collection data in grid ui admin? I create a controller to get data from the database as code below.
The query in controller:
$orderCollection = $this->_salesOrderCollectionFactory->create()
            ->addFieldToFilter(
                ['status','status','status'],
                [
                    ['eq' => 'delivering'],
                    ['eq' => 'refunded_cancel'],
                    ['eq' => 'refund_kpt_failed']
                ]
            )
            ->addAttributeToSelect('delivery_flightnumber')
            ->addAttributeToSelect('delivery_origin')
            ->addAttributeToSelect('delivery_destination')
            ->addAttributeToSelect('delivery_departure');
        $orderCollection->getSelect()
            ->columns('COUNT(*) AS total_order')
            ->columns('SUM(total_item_count) as total_item')
            ->columns('SUM(base_subtotal) as subtotal')
            ->columns('SUM(base_grand_total) as total')
            ->columns('SUM(base_discount_amount) as discount')
            ->columns('SUM(base_total_refunded) as refunded')
            ->group('delivery_flightnumber')
            ->group('delivery_departure')
            ->order('delivery_departure DESC');

So, I create a model to display the data in the grid.
MyModule\Model\ResourceModel\Report.php
protected function _construct()
    {
        // TODO: Implement _construct() method.
        $this->_init('sales_order', 'entity_id');
    }

I created MyModule\Model\ResourceModel\Report\Collection.php
protected $_idFieldName = 'entity_id';
    protected $_eventPrefix = 'salereports_report_collection';
    protected $_eventObject = 'report_collection';

    public function _construct()
    {
        $this->_init('MyModule\Model\Report', 'MyModule\Model\ResourceModel\Report');
    }

    protected function _initSelect()
    {
        parent::_initSelect(); // TODO: Change the autogenerated stub

        $this->addFieldToFilter(
            ['status','status','status'],
            [
                ['eq' => 'delivering'],
                ['eq' => 'refunded_cancel'],
                ['eq' => 'refund_kpt_failed']
            ]
        )
            ->addAttributeToSelect('delivery_flightnumber')
            ->addAttributeToSelect('delivery_origin')
            ->addAttributeToSelect('delivery_destination')
            ->addAttributeToSelect('delivery_departure');
        $this->getSelect()
            ->columns('COUNT(*) AS total_order')
            ->columns('SUM(total_item_count) as total_item')
            ->columns('SUM(base_subtotal) as subtotal')
            ->columns('SUM(base_grand_total) as total')
            ->columns('SUM(base_discount_amount) as discount')
            ->columns('SUM(base_total_refunded) as refunded')
            ->group('delivery_flightnumber')
            ->group('delivery_departure')
            ->order('delivery_departure DESC');

$saleOrderData = $orderCollection->getData();

        $result = [];

        $result[] = [
            'Date time',
            'Name',
            'Orders',
            'Items',
            'Subtotal',
            'Discount',
            'Total',
            'Refunded',
            'Revenue',
        ];

        foreach ($saleOrderData as $saleOrder) {
            $revenue = $saleOrder['total'] - $saleOrder['refunded'];
            $delivery = $saleOrder['delivery_origin'].'-'.$saleOrder['delivery_destination'];

            $result[] = [
                $saleOrder['delivery_departure'],
                $delivery,
                $saleOrder['total_order'],
                $saleOrder['total_item'],
                $saleOrder['subtotal'],
                $saleOrder['discount'],
                $saleOrder['total'],
                $saleOrder['refunded'],
                $revenue,
            ];
        }

        return $result;
    }

So I create view\adminhtml\ui_component\mymodule_report_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <!-- main part of the grid -->
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">salereports_report_listing.salereports_report_listing_data_source</item>
            <item name="deps" xsi:type="string">salereports_report_listing.salereports_report_listing_data_source</item>
        </item>
        <!-- define where to find the columns -->
        <item name="spinner" xsi:type="string">salereport_report_columns</item>

        <item name="buttons" xsi:type="array">
            <item name="report" xsi:type="array">
                <item name="name" xsi:type="string">report</item>
                <item name="label" xsi:type="string" translate="true">Show report</item>
                <item name="class" xsi:type="string">primary</item>
                <item name="url" xsi:type="string">*/report/*</item>
            </item>
        </item>
    </argument>

    <!-- define the data_source (must be the same than in argument/item/provider and argument/js_config/deps -->
    <dataSource name="salereports_report_listing_data_source">
        <argument name="dataProvider" xsi:type="configurableObject">
            <argument name="class" xsi:type="string">Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider</argument>
            <argument name="name" xsi:type="string">salereports_report_listing_data_source</argument>
            <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
            <argument name="requestFieldName" xsi:type="string">id</argument>
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                    <item name="update_url" xsi:type="url" path="mui/index/render"/>
                    <item name="storageConfig" xsi:type="array">
                        <item name="indexField" xsi:type="string">entity_id</item>
                    </item>
                </item>
            </argument>
        </argument>
    </dataSource>
    <columns name="spinner_columns">
        <column name="delivery_flightnumber">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Flight Number</item>
                </item>
            </argument>
        </column>
        <column name="delivery_departure" class="Magento\Ui\Component\Listing\Columns\Date">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">dateRange</item>
                    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/date</item>
                    <item name="dataType" xsi:type="string">date</item>
                    <item name="label" xsi:type="string" translate="true">Date time</item>
                </item>
            </argument>
        </column>
        <column name="delivery_name">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Name</item>
                </item>
            </argument>
        </column>
        <column name="total_order">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Orders</item>
                </item>
            </argument>
        </column>
        <column name="total_item">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Items</item>
                </item>
            </argument>
        </column>
        <column name="subtotal">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Subtotal</item>
                </item>
            </argument>
        </column>
        <column name="discount">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Discount</item>
                </item>
            </argument>
        </column>
        <column name="total">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Total</item>
                </item>
            </argument>
        </column>
        <column name="refunded">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Refunded</item>
                </item>
            </argument>
        </column>
        <column name="Revenue">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Revenue</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

To display the data from the query. But it can not run to _initselect function and it can't display the column name in query data. It can display the data with the column name in the sales_order table.
it displays the data with the column_name of the sales_order table. it not right.

How to display the data from the query model or controller in grid listing?
Please help me,
Thank you so much.


text:
Q: FR4, 1 oz. copper, PCB trace width for 48V/8A, pulsed (8 ms pulse length, up to 20Hz)? I would like to determine suitable trace width for the pulses shown.
Other details: The application is to pulse a solenoid; board size is 100mm x 100mm. An LM317 charges a 1000uF cap and the cap is discharged into the solenoid using a low side MOSFET. I have it working nicely on perf board. I've used trace width calculators but I am not sure how to address pulses. The average current through the trace is less than 500mA. The solenoid draws about 9W average (limited by the LM317).
*edit: I acknowledge the frequency shown on the plot is 10Hz but I would like to design for up to 20Hz; also the MOSFET and diodes are just stand-ins for simulating; please don't scrutinize them.
.

A: Check the RMS value of your current waveform (rms, not average!). With 10 Hz and above that seems like a reasonable value to design the trace width from.
Then decide what temperature rise of your trace in comparison to ambient you want to allow and choose the trace width accordingly after a table like this one:


text:
Q: React Testing Library jest.fn() toHaveBeenCalled() not working Component:
const MyComp = ({ handler }) => {
  return <button onClick={handler}>Test</button>
};

Test:
it('Calls the handler', async () => {
   const handler = jest.fn();
   render(<MyComp handler={handler} />);

   const button = screen.getByRole('button', { name: /Test/i });
   await fireEvent(button, new MouseEvent('click'));

   expect(handler).toHaveBeenCalled();
});

Expected number of calls: >= 1
Received number of calls: 0

A: Three options:

*

*Make the event bubble, as shown in the example (it doesn't return a promise, no await needed):
fireEvent(button, new MouseEvent("click", { bubbles: true }));

*Use the convenience method, which adds default event properties including bubbling (likewise):
fireEvent.click(button);

*Use userEvent (does return a promise, as of v14):
await userEvent.click(button);

A: Try using userEvent.click, like this
it('Calls the handler', async () => {
   const handler = jest.fn();
   render(<MyComp handler={handler} />);

   const button = screen.getByRole('button', { name: /Test/i });
   await userEvent.click(button);

   expect(handler).toHaveBeenCalled();
});


text:
Q: Rails 4: why is one way of rendering partials so much faster? I'm not sure if this is a Rails specific issue, hence the reason I tagged it ruby as well.
I'm rendering a collection of event records via a partial.  However, I found that rendering the partial differently results in drastic performance differences.
Both version use the exact same data, the only thing changing is the code used to render the partials.
Why the heck is one version consistently 4x faster than the other?  Makes me wonder what other performance hits I'm taking...
Slow version (950ms total request time):
<% events.each do |event| %>
  <%= render partial: "events/event", locals: { event: event } %>
<% end %>

# Log output
Rendered events/_event.html.erb (1.1ms)
Rendered events/_event.html.erb (1.1ms)
...

Faster version (250ms total request time):
<%= render partial: "events/event", collection: events, as: :event %>

# Log output
Rendered events/_event.html.erb (58.7ms)

A: example 1:
you are rendering a partial x times (depending on events).
which means you are compiling html x times(once each time the loop runs). which is slow
example 2:
you are rendering one partial with a collection of events
the html is compiled once(as there is only one partial). which is fast


text:
Q: Two questions on Hilbert's Nullstellensatz. We have this strong version of Hilbert's Nullstellensatz:
If $k$ is any field, every maximal ideal of $k[x_1, \dots, x_n]$ has residue field a finite extension of $k$.
Now I have two questions:

1) Why this is equivalent to say that any field extension of $k$ that is finitely generated as ring is finitely generated as a module?
2) And why this form implies the weak form of Nullstellensatz? (If $k$ is an algebraically closed field, then the maximal ideals of $k[x_1, \dots, x_n]$ are precisely those ideals of the form $(x_1-\alpha_1, \dots, x_n -\alpha_n)$).

A: A lot of this just echoes what Alex Youcis has already said; I thought it would be good to have an answer.
What does it mean for a $B$-algebra $B \to A$ to be finitely generated (or "finite type")? The translation between this statement and "$A$ is a quotient of a polynomial ring $B[x_1, \dots, x_n]$ in finitely many variables by an ideal $I$" must become second nature. Of course, explicitly writing $A$ out in this way gives something slightly more: a choice of generators and a realization of $\operatorname{Spec} A$ inside $\mathbf{A}^n_B$ as a "closed subscheme". Now, $A$ is a field if and only if $I$ is maximal.
If $k$ is algebraically closed then you should be able to show that it has no nontrivial finite field extensions. Maybe it's good to turn things around and see where ideals like $\mathfrak{m} = (x_1 - a_1, \dots, x_n - a_n)$ turn up. What follows applies to any $k$ and describes the "$k$-rational points" of $\mathbf{A}^n_k$. The difference will be that there are closed points not of this form, e.g., the maximal ideal $(x^2 + 1, y - x)$ of $\mathbf{Q}[x, y]$.
Say I have a point $(a_1, \dots, a_n)$ in $k^n$. This induces a morphism of $k$-algebras $\xi\colon k[x_1, \dots, x_n] \to k$, $f \mapsto f(a_1, \dots, a_n)$ and the kernel is $\mathfrak{m}$. Work this out! Now show yourself that you can recover the point of $k^n$ from $\xi$.


text:
Q: It is necessary to load on one domain name pages from different web servers It is necessary to load on one domain name pages from different web servers (apache2). For example, www.somesite.ru/page/ loads from server 12.34.56.78 and www.somesite.ru/another_page/ loads from another server 12.34.56.79.
How to make, what it would work?

A: Solved.
on ip .78 I used mod_rewrite + mod_proxy.
RewriteRule ^/(another_page)/?$ http://www2.somesite.ru/$1 [P]
www2.somesite.ru has ip .79


text:
Q: Bits of the primitive type in C Well, I'm starting my C studies and I was left with the following question, how are the bits of the primitive types filled in, for example, the int type, for example, has 4 bytes, that is 32 bits, which fits up to 4294967296. But if for example , I use a value that takes only 1 byte, how do the other bits stay?
    #include <stdio.h>

    int main(void) {

        int x = 5; // 101 how the rest of the bits are filled
                   // which was not used?
         return 0;
    }

A: All leading bits will be set to 0, otherwise the value wouldn't be 5. A bit, in today computers, has only two states so if it's not 0 then it's 1 which would cause the value stored to be different. So assuming 32 bits you have that
5 == 0b00000000 00000000 00000000 00000101
5 == 0x00000005

A: The remaining bits are stored with 0.
int a = 356;
Now let us convert it to binary.
 1     0    1     1     0   0   1   0   0

Now you get 9 bit number. Since int allocates 32 bits, fill the remaining 23 bits with 0.
So the value stored in memory is
         00000000 00000000 00000001 01100100

A: The type you have picked determines how large the integer is, not the value you store inside the variable.
If we assume that int is 32 bits on your system, then the value 5 will be expressed as a 32 bit number. Which is 0000000000000000000000000101 binary or 0x00000005 hex. If the other bits had any other values, it would no longer be the number 5, 32 bits large.


text:
Q: Google Cross-Origin Request I am trying to use Google JS API from my HTML page and I have to do something like:
<script src="https://www.google.com/jsapi?key=MY_API_KEY"/>

But I am getting the following error:
Firefox:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
  the remote resource at https://www.google.com/jsapi?key=MY_API_KEY.
  (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Chrome:

XMLHttpRequest cannot load
  https://www.google.com/jsapi?key=MY_API_KEY. Response to preflight
  request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8080' is therefore not allowed
  access. The response had HTTP status code 405.

As I have read it is caused by browsers restrictions to crossed request but I have no clue about how to fix it so I can do that request. Can anyone give me a tip?

A: I fixed it changing the way I made the request:
<script>
    $.ajax({
        url: "https://www.google.com/jsapi?key=MY_API_KEY",
        crossDomain: true,
        method: 'GET',
        async: false,
        dataType: 'script',
        headers:{
            "X-Requested-With":"XMLHttpRequest"
        }
    });
</script>


text:
Q: Printing a numbered list one item per line in Python I have a really long list in Python named my_list. I would like to print the contents of this list following these two conditions:

*

*One item per line.

*Each item needs to be numbered using three-digit numbers (e.g., 001, 002...)

This is my desired output:
001  csfiohfewiehns
002  hdifhdigbdgib
003  fdifhihiwhgighigh
004  jfjodopfhaeohgheg

So far, I have tried the following code:
print("\n".join.(my_list))

This worked and now each item appears in a new line. However, I still don't know how to number the lines using the format I want. I have heard of the function enumerate, though I don't know how it could be combined with my current line of code.
Any ideas?

A: You can use enumerate to generate indices:
print("\n".join('%03d %s' % (i, s) for i, s in enumerate(my_list, 1)))

A: Agree with blhsing, but since this case list comprehension's are faster, do:
print("\n".join(['%03d %s' % (i, s) for i, s in enumerate(my_list, 1)]))

Also got Mateen's this way:
print('\n'.join([f'{i + 1:03}  {x}' for i, x in enumerate(xs)]))

Or zfill as bhlsing's way:
print('\n'.join(['  '.join((str(i).zfill(3),v)) for i,v in enumerate(a,1)]))

Or as Mateen's way:
print('\n'.join(['  '.join((str(i+1).zfill(3),v)) for i,v in enumerate(a)]))

A: You could always just use a for loop rather than making a new string:
my_list = ["abc", "def"]

for i, item in enumerate(my_list):
    print(f'{i:03} {item}')

This will output:
000 abc
001 def

If you don't understand some of the above code, leave a comment and I will clarify.

A: This is probably the simplest way:
'\n'.join(f'{i + 1:03}  {x}' for i, x in enumerate(xs))


text:
Q: How to check in apex whether a number is a happy number? I'm new to apex. And it's only been a 3 days since I started learning it. I was going through programming exercises and solving apex programming questions. And I stumbled through this. I get the same debug info for all numbers. Please help with a solution.
Integer I = 19;
Integer k=0;
Integer m=0;
Integer b=I;
for(Integer i=0;i<b;i++) {
    String S = String.valueOf(I);
    System.debug('Value of I '+ I);
    Integer l=s.length();
    for(Integer j=0;j<l;j++){
        String k=S.substring(j,j+1);
        Integer z=Integer.valueOf(k);
        m=m+z*z;
    }
    I = m;
    if(I == 1) {
    system.debug('It is an Happy Number');
        break;
    }
}

A: As mentioned in the comments, Apex is largely case-insensitive. There are some places where case sensitivity matters (things stored in maps or sets, String.contains(), anything involving a hash), but most of the time case does not matter.
So on the line String S = String.valueOf(I);, your loop variable i is shadowing your Integer I inside the loop. S ends up always being '0' as a result. Since you're re-setting the loop variable to 0 each time, I'd expect this to loop infinitely (or rather, until Salesforce stops execution for your code going over the CPU governor limit).
If you'd get past that issue, I suspect that your failure to reset your m variable would cause issues as well.
Apex is based on some version of Java, so (almost) all code must be in a method inside of a class. Anonymous apex allows you to run code without explicitly putting it into a method or class, but it's still a generally good idea to follow the language conventions (especially when you're learning).
Giving variables meaningful names (numberOfDigits, givenInteger, runningSum as opposed to l, i, m) will help make your code easier to read. Perhaps that isn't so important here, but it's important in general.
With all of that in mind, here's how I would write this
public class HappyNumber{
    // From https://mathworld.wolfram.com/HappyNumber.html
    // and http://oeis.org/A039943
    // we know that if we reach any of these numbers (other than 1, which
    //   I've excluded) then the number is not 'happy'
    // The 'new set<type>{ value }' syntax allows us to initialize the collection
    //   with literal values.
    // 'new set<type>()', the typical constructor (with parenthesis) does not
    //   allow us to do that (but if you wanted to copy a set into a new set you
    //   could do Set<type> otherSet = new Set<type>(existingSet); )
    private Set<Integer> nonHappyIntermediates = new Set<Integer>{
        0, 4, 16, 20, 37, 42, 58, 89, 145
    };

    public Boolean isHappy(Integer givenInteger){
        // The strict definition of happy numbers requires the input to be
        //   positive.
        // It's generally accepted practice to perform your checks early.
        // If you're going to guard against null values, the null check must
        //   always be the first check.
        // Comparisons on integers are null-safe, so the null check here isn't
        //   necessary but I'm keeping it to illustrate the point (check null first)
        if(givenInteger == null || givenInteger < 0){
            // Throwing an exception might be better, but I don't feel like
            //   going that far
            return false;
        }

        // I think this is one of the rare times where using a while loop
        //   instead of a for loop makes sense
        // We stop looping if givenInteger is ever one of the non-happy
        //   intermediates (note the negation, '!' at the start of the statement.)
        // Set.contains() is a fast operation
        while(!nonHappyIntermediates.contains(givenInteger)){
            String intAsString = String.valueOf(givenInteger);
            Integer stringLength = intAsString.length();

            // It's important to reset the running sum on each iteration
            // The easiest way to force yourself to do that is to define
            //   this variable inside the scope of the loop
            Integer runningSum = 0;

            for(Integer index = 0; index < stringLength; index++){
                // substring() would work too, but I think mid() is a little
                //   easier to read and a little harder to mess up
                Integer digit = Integer.valueOf(intAsString.mid(index, 1));
                runningSum += digit * digit;
            }

            if(runningSum == 1){
                return true;
            }

            // Primitive types (like Integer, String, Boolean, etc...) are
            //   passed into functions by value.
            // So overwriting it like this (in the method) is safe
            givenInteger = runningSum;
        }

        return false;
    }
}

HappyNumber decider = new HappyNumber();
Integer testInt = 19;

// The 'boolean test ? <value if true> : <value if false>' is a ternary
// It can act as a shortened version of an if/else (both the true and false results
//   must be the same type)
system.debug(testInt + (decider.isHappy(testInt) ? ' is ' : ' is not ') + 'a happy Number');

// Doing string concatenation manually can be messy/error prone.
// An alternative is to use String.format() with placeholders
system.debug(String.format('{0} {1} a happy number', new List<Object>{
    testInt,                                   // gets substituted in place of {0}
    decider.isHappy(testInt) ? 'is' : 'is not' // gets substituted in place of {1}
});


text:
Q: Will we lost the views and clicks in Admob ads while the app is not linked? we have a new app published today in Play Store and we use Admob ads in their activities. However, we could not find the app when we tried to link it in the Admob. After looking here (in Stack Overflow) we saw this is because Admob indexing takes approximately 48 hours. In this interval while the app is not linked, will we receive for the views and clicks?
Do they already count or only after the app is linked?
Thanks in advance!

A: They will count.
The app linking has no impact upon view or clicks.


text:
Q: syntax error, unexpected keyword_ensure, expecting end-of-input I keep getting syntax error, unexpected keyword_ensure, expecting end-of-input.
I made sure the syntax is correct (I think).
I checked with a binding.pry in the controller and @redirect_url is equal to the following: @redirect_url = "http://localhost:3333/articles/medicine/test"
  <%= javascript_tag do %>
    window.location.href = '<%=j @redirect_url %>';
  <% end %>


text:
Q: Google maps API function getlatlong I have this code and problem is that $address_array extract just last position in the array.
How should I fix it?
HMTL

JQUERY

PHP
<?php
function getlatlong($address){
        $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true';
        $json = @file_get_contents($url);
        $data = json_decode($json);
        if ($data->status == "OK")
             return $data;
        else
             return false;
}
$address_array = array('Germany', 'Poland', 'Italy');
foreach ($address_array as $address) {
     $data = getlatlong($address);
     $location = $data->results[0]->geometry->location;
}
?>

JS creat map

A: Fixed

This code wrote one guy and it works great.

The code returns latlng positions.
$address_array = array("Germany", "Poland", "Italy","Italy","Italy");
    $encoded_adress_array = [];

    foreach ($address_array as $address) {
        array_push($encoded_adress_array, getlatlong($address)->results[0]->geometry->location);
    }


text:
Q: PHP Object Access - Video Chat Application, memcache? I am designing a video chat application and as of now, I have built the logic that allows users to register, and access a members area. Now I want to grab groups of users that are logged in and put them in group video chats. So as of now I have created a group video chat object that has an array with the users in the video chat (max of 4), and some more information. However I am having trouble assigning 4 users to the same video chat object. PHP instantiates a new group video chat object for each user. I think that there is something fundamental about PHP that I am not quite understanding. I thought that it had a shared memory and different users could easily access the same object. From looking online it looks like I will have to persist these group video chat objects to the database. But that doesn't feel quite right, because these group video chats are going to have a very short life span. Should I use memcache for this?
Can someone please suggest a way of doing this?
Thanks a lot in advance,
John

A: Every time a user requests a page, a new instance of apache/PHP is called. These do not share variables - think about it, if you have $user as a var in your script, then obviously it is different for each user.
You need to persist the data elsewhere. Using the database for this wouldn't be too bad, but your right in that memcached is a slightly better fit. Still, it should work pretty well no matter what storage you use.


text:
Q: What is INSTALL_DIR useful for in ExternalProject_Add command? I don't understand the usage of INSTALL_DIR in ExternalProject_Add command. I try to use it but it does not seem to work. Here is an example of a CMakeLists.txt, using Eigen library which compiles quickly:
cmake_minimum_required (VERSION 2.6)
project (example CXX)
include(ExternalProject)
include(ProcessorCount)
set(CMAKE_VERBOSE_MAKEFILE ON)
ProcessorCount(N)
if(NOT N EQUAL 0)
   set(CMAKE_BUILD_FLAGS -j${N})
endif()
ExternalProject_Add
(
    mylib
    PREFIX myprefix
    DOWNLOAD_COMMAND wget http://bitbucket.org/eigen/eigen/get/3.2.4.tar.gz && tar xvzf 3.2.4.tar.gz -C mylib --strip-components=1
)

I chose the following project hierarchy:
project
    CMakeLists.txt
    build/

From build repository, I type:
cmake ..
make

The installation process fails with the following message:

file cannot create directory: /usr/local/include/eigen3.
  Maybe need administrative privileges.

As far as I understand, it means that I need to define a "prefix" during the configuration step:
cmake -D CMAKE_INSTALL_PREFIX=$INSTALL_DIR ..

But, the INSTALL_DIR variable is already defined in the ExternalProject_Add command. However, I get the same error when I modify the value of INSTALL_DIR by adding
INSTALL_DIR myprefix/src/install

in the ExternalProject_Add command.
So, what is INSTALL_DIR useful for?
What am I doing wrong?
Of course, I know how to provide my own configuration command to add a prefix and solve the problem. But it is not my question. My question is: if I have to do that, what is the purpose of INSTALL_DIR?

A: From what I found in this discussion https://www.mail-archive.com/cmake@cmake.org/msg51663.html (scroll to the end of the page to navigate through the thread messages) it is indeed pretty common thing to use CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/contrib
Furthermore, lurking through the ExternalProject.cmake module I found out that the only effect setting this directory has is that CMake will create directory specified in INSTALL_DIR before doing anything else.
Also, it will set the property that you can gather through ExternalProject_Get_Property(${project_name} install_dir) command.
And that's pretty much it.
// As of CMake version 3.2.2


text:
Q: Symfony JAVA_HOME not set When trying to run signal-cli via Symfony it errors:

JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation.

Output of echo $JAVA_HOME in the working directory:
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.252.b09-0.fc31.x86_64/jre
Output of java -version in the working directory:
openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252-b09)
OpenJDK 64-bit Server VM (build 25.252-b09, mixed mode)

I'm trying to figure out how to resolve the error. Here is my code:
public function list()
{
  $list = new Process(['.././signal-cli-0.6.8/bin/signal-cli']);
  $list->run();

   if (!$list->isSuccessful()) {
       throw new ProcessFailedException($list);
    }
    echo $list->getOutput();
 }
}

A: From docs (emphasis mine):

In addition to the env vars passed explicitly, processes inherit all the env vars defined in your system. You can prevent this by setting to false the env vars you want to remove [...]
source: https://symfony.com/doc/current/components/process.html#setting-environment-variables-for-processes

I believe that means that your user's/shell's env vars don't matter in that moment and you might have to set those explicitly:

 $process = new Process(['...'], null, ['ENV_VAR_NAME' => 'value']);

anyhow, you could write a small script that just writes the result of env/printenv into a file for further inspection. There's most likely a big difference, due to your shell running lots of additional scripts that impact environment that are not forwarded nor run for your process.
So you might have to explicitly pass JAVA_HOME to the process as implied above (this is a very specific home path, ):
$process = new Process(['...'], null, [
     'JAVA_HOME' => '/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.252.b09-0.fc31.x86_64/jre',
]);

A: it seems that the process that executes your php application is executed as a user that doesn't contain the JAVA_HOME environment variable.
I mean when you execute the following command in your linux CLI :
echo $JAVA_HOME

The result is good because the environment variable is set for your linux user.
But when you call signal-cli via Symfony, it's not your linux user that is used, but the user of the process that executes your web server.
Maybe you use apache as a web server, then the user is something like "apache" or "www-data".
Then still in the case of apache, you'll have to pass the environment variable to the virtual host :
<VirtualHost yourhostname:80>
   ...
   SetEnv VARIABLE_NAME variable_value
   ...
</VirtualHost>

Or you can do as specified here
In case of other web servers, the solution will be a little different but the concept will be the same.


text:
Q: Using REPLACE with CHAR(160) is Returning Hexadecimal as Value I am trying to get rid of &nbsp characters in MYSQL, but am getting weird behavior where using REPLACE is returning a hexadecimal string.
The original value is some HTML stored in a field with the type BLOB:

This was just an appetizer. Are you ready for the full course?

Dive into more business news, check out the latest tech trends, and get a couple quick tips from our health section.

The SQL I am using is this:
UPDATE tbl
SET field = REPLACE(field, CHAR(160), '');

And after executing, this is what is left in the database:
3C68333E5468697320776173206A75737420616E206170706574697A65722E2041726520796F7520726561647920666F72207468652066756C6C20636F757273653F3C2F68333E3C703E4469766520696E746F206D6F726520627573696E657373206E6577732C20636865636B206F757420746865206C61746573742074656368207472656E64732C20616E6420676574206120636F75706C6520717569636B20746970732066726F6D206F7572206865616C74682073656374696F6E2E20C23C2F703E3C2F6469763E

What is going on and how could I avoid this? Do I need to use VARCHAR for the field type?

A: You get (binary) BLOB back, after the replace.
so you have to convert it back to text
UPDATE tbl
SET field = CAST(REPLACE(field, CHAR(160), '')AS CHAR(10000) CHARACTER SET utf8);

Of course you have to check character set and size.

A: I found that CHAR codes didn't work, but a copy pasted whitespace worked. This looks like a normal space, but is in fact CHAR(160) and I don't have an error anymore. ' '


text:
Q: Allocating space to data structure on need basis in C++ I have a data structure of the following form:
class A{
    unsigned t;
    bool isPresent;
    map<unsigned,unsigned> isPresentA;
    map<unsigned,unsigned> isPresentB;
};

int main(int argc, char** argv) {
    A a;
    cout<<"size of map="<<sizeof(a)<<"\n";
    return 0;
}

Now when a.isPresent is true, then only I store values in a.isPresentA and a.isPresentB. And when a.isPresent is false, then my map's a.isPresentA and a.isPresentB are empty. However, I see that although I don't store values in a.isPresentA and a.isPresentB, still its size is 104. Is there some way in C++ so that I may allocate space to a.isPresentA and a.isPresentB only on need basis (i.e. when a.isPresent is true), rather than explicitly allocating storage space to them.
I am storing millions of objects of class A, therefore the size of class A is a concern for me.
I am using gcc version: gcc (Ubuntu/Linaro 4.6.4-6ubuntu2) 4.6.4

A: When you create an instance of class A, the two maps are automatically allocated. To counter this, you can make pointers out of them:
class A{
    unsigned t;
    bool isPresent;
    map<unsigned,unsigned>* isPresentA;
    map<unsigned,unsigned>* isPresentB;
};

However, you need to allocate (and delete!) them yourself now! A safer option is using std::shared_ptr:
class A{
    unsigned t;
    bool isPresent;
    std::shared_ptr<map<unsigned,unsigned>> isPresentA;
    std::shared_ptr<map<unsigned,unsigned>> isPresentB;
};

You still need to initialize them, but at least you won't have to worry about deleting them. You should add a constructor or initializer function to your class to do this:
class A{
    A(bool is_present) {
        isPresent = is_present;
        if (isPresent) {
            isPresentA = std::make_shared<map<unsigned int, unsigned int>>();
            isPresentB = std::make_shared<map<unsigned int, unsigned int>>();
        }
    }
    unsigned t;
    bool isPresent;
    std::shared_ptr<map<unsigned,unsigned>> isPresentA;
    std::shared_ptr<map<unsigned,unsigned>> isPresentB;
};

A: You can achieve what you want without complicating your class by using unique_ptr:
#include <map>
#include <memory>

class A {
    unsigned t;
    unique_ptr<map<unsigned, unsigned>> isPresentA;
    unique_ptr<map<unsigned, unsigned>> isPresentB;
};

you can check for presence by using isPresentA or B directly:
if (a.isPresentA) {
}

or wrap it into some class method alla bool isPresent();
A somewhat more refined version might look like this:
#include <memory>
#include <map>

using namespace std;

class A {
    struct OptinalParts {
        map<unsigned, unsigned> a;
        map<unsigned, unsigned> b;
    };
    unsigned t;
    unique_ptr<OptinalParts> optional;

public:
    A() :t(0),optional(nullptr){};
    A(bool initState):t(0) {
        makePresent(initState);
    }
    bool isPresent() {
        return (bool)optional;
    }
    void makePresent(bool set) {
        if (set && !isPresent())  {
            optional.reset(new OptinalParts);
        }
        else {
            optional.reset(nullptr);
        }
    }
    /*
    * accessors
    */
};

You probably have to replace any occurence of nullptr by NULL


text:
Q: LBP Face Detection I want to implement a face detection algorithm that does not take a lot of training time. I looked at the Viola-Jones method but the training time is too long. I read about LBP and how it is used in face detection. I want to implement in in C on a development board running on linux. It seems LBP is more suitable to use on microprocessors as it uses binary operations as opposed to the floating point operations used by viola-jones.
I want to avoid using openCV as I need to implement it using C on the development board. Are there any useful resources online explaining LBP well other than papers. It would be great if someone can explain LBP in a very simple way.

A: I refer you to my own answer to someone who wanted to do somewhat the same thing. That question covered both training the cascade and its actual running, and I gave a summary of the training process and a detailed explanation for the running of OpenCV's LBP cascade.
Face Detection Algorithms with minimal training time

A: You have image patch. Than according to your mask you compare pairwise pixel intensities and save it in the descriptor.
For example, you compare intensities of the corner pixels and center - it is your mask. Descriptor = array 1x4, result of comparison.
Up-left pixel is lighter than central, desc[0] = 1. Up-right is darker, desc[1] = 0.
Down right is lighter, desc[2] = 1. Down left is lighter, desc[3] = 1.
You have described patch with 4 bit LBP.
Real LBPs have intermediate normalization step, can use not intensity, but gradient, different masks, but basic principle is like this.

A: For information on LBP, you can refer to scholarpedia:
http://www.scholarpedia.org/article/Local_Binary_Patterns


text:
Q: In Multiplayer how do you call in an Artillery or Air Strike? I know that in previous battlefield games you could call in artillery strikes.
Are artillery/air strikes still possible and how do you do it?

A: No artillery or air strike in BFBC2. You'll have to only rely on the guys who are there! :)
But you can also rely on your friends in helicopters and tanks so, pretty much more devastating than an artillery strike sometimes! :)

A: There is no official artillery strike in Bad Company 2, but the mortar strike is a weaker version of the same thing.  The mortar strike which as LudoMC says is a gadget that unlocks for the Recon class after you've gained enough points.


text:
Q: Using R: Multiplying a matrix by its transpose while ignoring missing values The following example may explain what I want to do and you may know a trick that would efficiently do it. Using R, preferably without looping, I would like to multiply, for instance, this matrix:
1  2
NA 3
4  5

By its transpose:
1 NA 4
2 3  5

And get (where NA was ignored):
(1x1)+(2x2)  (2x3)   (1x4)+(2x5)
   (3x2)     (3x3)      (3x5)
(4x1)+(5x2)  (5x3)   (4x4)+(5x5)

Which is:
05  06  12
06  09  15
14  15  41

A: You can replace NAs by 0s, so that their product don't contribute to the result:
m1 = matrix(c(1,NA,4,2,3,5),ncol=2)
m1[is.na(m1)] = 0
m2 = t(m1)
m1%*%m2
     [,1] [,2] [,3]
[1,]    5    6   14
[2,]    6    9   15
[3,]   14   15   41


text:
Q: Deriving the Poincare patch from global coordinates in AdS$_{3}$ I have been reading Thomas Hartman's lecture notes on Quantum Gravity and Black Holes.

In page 97, he derives (9.4), which is the metric of AdS$_{3}$ in global
coordinates:
$$ds^{2} = \ell^{2}(-\cosh^{2}\rho\ dt^{2} + d\rho^{2} + \sinh^{2}\rho\ d\phi^{2}).$$

In page 100, he states that, expanding the metric at large $r$ under the coordinate change
    \begin{align}
    t^{\pm} = t \pm \phi, \qquad \rho = \log(2r),
\end{align}
we can show that, to leading order, the induced metric on the hyperboloid AdS$_{3}$ becomes
\begin{align}
    ds^{2} = \ell^{2} \left(\frac{dr^{2}}{r^{2}}-r^{2}dt^{+}dt^{-}\right).
\end{align}

I find, under the coordinate change, that
    \begin{align}
    ds^{2} = \ell^{2} \left(\frac{dr^{2}}{r^{2}} - \frac{1}{4}dt^{+2} - \left(r^{2} + \frac{1}{16r^{2}} \right) dt^{+}dt^{-} - \frac{1}{4}dt^{-2} \right).
\end{align}
Of course, the term in $1/r^{2}$ drops off at large $r$, but I am not able to get rid of the components in $dt^{+2}$ and $dt^{-2}$. Am I missing something here?

He then goes on to mention that these are Poincare coordinates, but does not make contact with the usual way in which the metric of AdS$_{3}$ is written in Poincare coordinates:
$$ds^{2} = \frac{\ell^{2}}{z^{2}}(dz^{2}-dt^{2}+d\vec{x}^{2}).$$
What am I missing here?

A: It is likely that he cut the terms lower than $O(r)$ (except the $dr^2$ term), making your $dt^\pm$ terms, $O(1)$, vanish. I have derived a slightly different result but with a common result. I used the transformation
\begin{equation}
dt^2=(dt^+-d\phi)(dt^--\phi)=dt^+dt^-+d\phi^2
\end{equation}
which brings me to the metric
\begin{equation}
ds^2=l^2\left(\frac{dr^2}{r^2}-\left(r^2+\frac{1}{16r^2}+\frac{1}{2}\right)dt^+dt^--d\phi^2\right).
\end{equation}
Cutting the small terms below $O(r)$ will lead you to the right answer. This is indeed in the form of Poincaré coordinate:
\begin{equation}
ds^2=\alpha^2\left(\frac{du^2}{u^2}+u^2(dx^\mu dx_\mu)\right).
\end{equation}