text:
Q: Issue with configuring external tool in Visual Studio I have an issue setting up an external tool in Visual Studio.
The tool is for JS Lint, which lints a javascript file.
My setup is as follows:
Title: &JSLint - http://www.jslint.com/
Command: C:\Users\XXXX\Documents\Visual Studio 2008\Tools\JsLint\jslint.cmd
Arguments: $(ItemPath)
Initial Directory: [blank]
When I run the tool, I get the following error in the output window:
Input Error: There is no file extension in "C:\Users\XXXX\Documents\Visual".
The issue I believe is with the space in the folder "Visual Studio 2008". If I change locations the a folder structure with no spaces in the name then all works fine. I would like to keep it in the "C:\Users\XXXX\Documents\Visual Studio 2008\Tools\JsLint\" folders though.
Can anyone help me out with this as to why it does not like the space in the folder names?
Looking at the .cmd windows command script in notepad, it contains the following - maybe I need to alter this to handle the space in the folder path - any ideas?

A: Change arguments to this:
Arguments: "$(ItemPath)"

A: I solved my issue by changing the cmd file from:
@cscript //nologo %~dp0\jslint.wsf %*
to:
@cscript //nologo "C:\Users\XXXX\Documents\Visual Studio 2008\Tools\JsLint\jslint.wsf" %*


text:
Q: DataTables how to use multiple data from json objects so what i'm trying to do is to call some data from a json file to fill my table. But instead of having a lot of json files, i'd like to keep some of the data in a single file. For example, i have 2 types of clients (person and company) and i want to keep them both in the same json, but as different objects, because each one goes in different table.
The problem is: I can't access the data in the JSON file.
I can use it normally if i use the 2 type of clients in different files (person.json and company.json - This works fine).
I did tried these 2 examples, but none of them worked for me.

*

*https://www.datatables.net/examples/ajax/deep.html

*https://www.datatables.net/examples/ajax/objects_subarrays.html
So, how can i do get the data from the file? Here is my json and my datatable code:
{
    "clients": {
        "person": [
            {
                "cd":0,
                "id":"C-0010",
                "nm_cliente":"Name AAA",
                "dt_nasc":"02/11/1990",
                "info":"Some basic info"
            },
            {
                "cd":1,
                "id":"C-0013",
                "nm_cliente":"Name BBB",
                "dt_nasc":"02/11/1990",
                "info":"Some basic info"
            },
            {
                "cd":2,
                "id":"C-0017",
                "nm_cliente":"Name CCC",
                "dt_nasc":"02/11/1990",
                "info":"Some basic info"
            }
        ],
        "company": [
            {
                "cd":0,
                "id":"C-0032",
                "nm_cliente":"Name Client",
                "num_cnpj":"111.222.3333/0001-22",
                "nm_cidade":"City AAA"
            },
            {
                "cd":1,
                "id":"C-0033",
                "nm_cliente":"Client Name",
                "num_cnpj":"111.222.3333/0001-22",
                "nm_cidade":"City BBB"
            },
            {
                "cd":2,
                "id":"C-0035",
                "nm_cliente":"jEmpresa teste",
                "num_cnpj":"111.222.3333/0001-22",
                "nm_cidade":"City CCC"
            }
        ]
    }
}

I already used jsonlint.com to verify, and everything is ok with my JSON. And here is how i'm trying to call this data into my tables.
TableA - Client type Person
//rest of the code goes here...
"aoColumns" : [
    { "mData": "person.id" },
    { "mData": "person.nm_cliente" },
    { "mData": "person.dt_nasc" },
    { "mData": "person.info" }
]

TableB - Client type Company
//rest of the code goes here...
"aoColumns" : [
    { "mData": "company.id" },
    { "mData": "company.nm_cliente" },
    { "mData": "company.nm_cnpj" },
    { "mData": "company.nm_cidade" }
]

I keep getting error like "lenght not defined"
Can anyone help me?

A: You must refer to the person and company arrays themselves, not the items. Updated to demonstrate initialization after load of JSON and how to  reuse and manipulate the options :
//an options object, some example settings
var options = {
    bPaginate: true,
    sPaginationType: "full_numbers",
    aLengthMenu: [25,50,100,500]
    //etc
}

function initialize(json) {
     options.aaData = json.clients.person;
     options.aoColumns = [
           { "mData": "id" },
           { "mData": "nm_cliente" },
           { "mData": "dt_nasc" },
           { "mData": "info" }
        ];

    $("#tableA").dataTable(options);

    options.aaData = json.clients.company;
    options.aoColumns = [
           { "mData": "id" },
           { "mData": "nm_cliente" },
           { "mData": "num_cnpj" },
           { "mData": "nm_cidade" }
        ];

    $("#tableB").dataTable(options);
}

$.getJSON("your.json", function(json) {
   initialize(json);
});

original demo showing how to inject the JSON -> http://jsfiddle.net/3g5wcyet/
reuseable options demo -> http://jsfiddle.net/bpgvfefd/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you produce electricity from a wind mill? How does a spinning windmill produce electricity?What is the principle behind the windmill?

A: First kind of principles is 'How the linear motion is transferred into revolutionary':
There are horizontal- and vertical-axis windmills, horizontal are more common, vertical ones doesn't care about the wind direction.
Second way how to sort windmills is by the principle of transfer energy conserved in axial flow into momentum. Easier way is based on resistance - the blade is usually steel plate - and is used in small and/or old windmills, Sophisticated windmills are based on wing lift - shape is like airplane's wing - and those are made of composites like fiberglass or carbon fiber. Vertical-axis turbines are based different resistance of the profile when the profile is moving against the wind and with it - easiest is S shaped plate.
And revolutionary motion is transferred through braking system (security), gearbox (to obtain exact frequency) into a generator (Alternator, dynamo, 3-phase generator). This part is almost the same as in any other power-plant. Except solar ones.
Nowadays most wind turbines are horizontal and based on wing-lift. They suppose that the velocity of the wind is 1/3 of the velocity in front of the turbine. Theoretical efficiency is about 46%, real one barely reach 29% (Output wattage / Energy flow into the windmill)
If you want some equations to support my numbers and/or describe the relation between profile parameters, wind characteristics and windmill design add comment, I'll find it out in my papers...

A: Generating Electricity from wind uses the same technology that any generator does. BUT unlike steam, water pressure or gas wind is not continuous so its input is not constant.  1st of all the speed governor is critical if not the most important part of the device. 2nd the high wind failure mechanism is critical you ether design for say 60 mile H. or have the blades collapse. 3rd and not to be forgotten you need knowledge of wind patterns to calculate wind shadows. after all this you can calculate blade design and aerodynamics.

A: The short answer, as Karsus Ren says, is that it's electromagnetic induction that generates the electricity: the relative movement of a conductor and a magnetic field.
As Vladimir Kalitvianski points out, strictly speaking, windmills don't generate electricity - wind turbines generate electricity, and windmills mill grain. Still, it's become reasonably common to refer to wind turbines as windmills.
As Crowley says, a wind turbine takes the wind's horizontal motion, turns it into rotary motion, which in some (but not all) turbines then goes through a gearbox. The motion then (depending on the nacelle design) either:
a) rotates either a conducting coil (typically copper) through a magnetic field; or
b) rotates magnets around a coil;
either way, this generates electricity through electromagnetic induction.
The magnets may be permanent magnets (typically a neodymium alloy) or electromagnets.
The theoretical limit on how much of the wind's energy can be captured by the blades is called the Betz limit, and is an efficiency of ~59.3% (16/27).
The Danish wind-turbine manufacturer Vestas has some very accessible stuff on their e-learning site at http://www.vestaselearning.com/ It might seem banal at times, but don't be fooled - there is a lot of decent material in there.


text:
Q: Problema sobre emberJS y polyfills me clone un proyecto de ember y al correrlo me arroja el siguiente error:
loader.js:247 Uncaught Error: Could not find module `@ember/polyfills` imported from `radio/initializers/viewport-config`
    at missingModule (loader.js:247)
    at findModule (loader.js:258)
    at Module.findDeps (loader.js:168)
    at findModule (loader.js:262)
    at requireModule (loader.js:24)
    at index.js:18
    at Array.forEach (<anonymous>)
    at exports.default (index.js:15)
    at Module.callback (app.js:13)
    at Module.exports (loader.js:106)

Previamente habia instalado el cliente de ember, phantomJS e hice tanto un bower install como npm install de los siguientes archivos:
Package.json:
{
  "name": "radio",
  "version": "0.0.0",
  "description": "Small description for radio goes here",
  "private": true,
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "start": "ember server",
    "test": "ember test",
    "deploy": "**",
    "deploy-prod": "**"
  },
  "repository": "",
  "engines": {
    "node": ">= 0.10.0"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "broccoli-asset-rev": "^2.4.2",
    "broccoli-sass": "^0.7.0",
    "ember-ajax": "^2.0.1",
    "ember-cli": "2.7.0",
    "ember-cli-app-version": "^1.0.0",
    "ember-cli-babel": "^5.1.6",
    "ember-cli-bourbon": "1.2.2",
    "ember-cli-dependency-checker": "^1.2.0",
    "ember-cli-google-analytics": "1.5.0",
    "ember-cli-htmlbars": "^1.0.3",
    "ember-cli-htmlbars-inline-precompile": "^0.3.1",
    "ember-cli-inject-live-reload": "^1.4.0",
    "ember-cli-jshint": "^1.0.0",
    "ember-cli-meta-tags": "3.0.1",
    "ember-cli-moment-shim": "2.2.1",
    "ember-cli-pace": "0.1.0",
    "ember-cli-qunit": "^2.0.0",
    "ember-cli-release": "^0.2.9",
    "ember-cli-slick": "1.0.14",
    "ember-cli-sri": "^2.1.0",
    "ember-cli-test-loader": "^1.1.0",
    "ember-cli-uglify": "^1.2.0",
    "ember-data": "^2.7.0",
    "ember-export-application-global": "1.1.1",
    "ember-lazy-image": "0.0.15",
    "ember-load-initializers": "^0.5.1",
    "ember-local-storage": "1.3.1",
    "ember-moment": "6.1.0",
    "ember-resize": "0.0.17",
    "ember-resolver": "^2.0.3",
    "ember-responsive": "1.2.7",
    "ember-social": "0.3.0",
    "ember-youtube": "0.8.2",
    "liquid-fire": "0.24.1",
    "loader.js": "^4.0.1"
  }
}

y el bower.json tiene lo siguiente:
{
  "name": "radio",
  "dependencies": {
    "ember": "~2.7.0",
    "ember-cli-shims": "0.1.1",
    "ember-qunit-notifications": "0.1.0",
    "bourbon": "4.2.6",
    "slick-carousel": "^1.6.0",
    "pace": "^1.0.2",
    "blob-polyfill": "^1.0.20150320"
  }
}

He estado instalando por medio de npm / bower varias librerias para solucionar problemas sobre polyfills pero no encontre una solución, alguien sabe como podria solucionar este problema? saludos.

A: El problema es que tu Ember está en la versión 2.7.0, según tu package.json, y @ember/polyfills fue introducido en la versión 2.16.0. La última, por cierto, es la 3.1.
Actualizar Ember.js no es demasiado difícil, particularmente dado que no tienes que tocar el proyecto en sí. Te aconsejo mirar la documentación de Ember.js, pero normalmente basta con npm install --save-dev ember-cli


text:
Q: Rails group validation with just one error message The following validation code in the model:
validates :formatted_address, :zip, :city, :state, :country, :presence => true, :message => "is incomplete. Please enter full address."

is displayed when either of the fields are empty. Let's say now :address and country are empty, 2 errors are displayed:
Formatted Address is incomplete. Please enter full address.
Country is incomplete. Please enter full address.

How can I group the error message in the validation to just show one error message if either of the fields validated does not exist?
Address is incomplete. Please enter full address.

Thanks.

A: You could just write your own validator using the validate macro:
validate :has_complete_address

#...

private
def has_complete_address
    # Check that everything is there and
    # call self.errors.add to store an error
    # message if something is wrong.
end


text:
Q: powershell Parsing for multiple keywords and sending output to a text file I'm trying to write a powershell cmdlet to find multiple words in lines in file. Example. I need to parse "word1", "word2", "word3" are in the same line of a file. I'm doing something wrong because I tried this with no success:
(gci -File -Filter FileName | Select-String -SimpleMatch word1, word2,word3) > outputFileName.txt

where FileName = name of file, outputFileName = generated file from my search of the three words.  Thank you.

A: Select-String doesn't have any combination operator that I can think of. If your words were always in that order, then you could do -Pattern 'word1.*word2.*word3' as your match, but if they could be in any order that would get complex very quickly. Instead, I'd look at
.. | Select-String 'word1' | Select-String 'word2' | Select-String 'Word3'

so, all the lines which match word1. Out of those, the ones which match word2 somewhere. Out of that even smaller result, the ones which also match word3.

A: try this:
$wordlist=@("word1", "word2", "word3")

Get-ChildItem "c:\temp\" -file |  %{$currentfile=$_.FullName; Get-Content $_.FullName |
                    %{
                        $founded=$true
                        foreach ($item in $wordlist)
                        {
                            if (!$_.Contains($item))
                            {
                                $founded=$false
                                break
                            }
                        }

                        if ($founded)
                        {
                            $currentfile
                        }

                    }
}


text:
Q: how do you typically tie the address pins and WP pin of I2C device? Do these lines need a pull-up/down resistor or just tied directly how do you typically tie the address pins and WP pin of I2C device?  Do these lines need a pull-up/down resistor or just tied directly.

A:
Do these lines need a pull-up/down resistor or just tied directly.

Completely dependent on the specific IC you are using, and would be listed in the data sheet. Either outright, or in the recommended/typical application schematic.
That said, I've never personally seen one that couldn't be directly tied to VCC or Gnd. Unless it is one of the fancier ones that can be tied to voltage dividers, or the other address pins, or left floating.

Your specific part, the FM24V02 has both an explicit explanation, and a typical application schematic. Direct Connections shown.

A2-A0, Input, Device Select Address 2-0.
  These pins are used to select one of up to 8 devices of the same type on the same I2C bus. To select the device, the address value on the three pins must match the corresponding bits contained in the slave address. The address pins are pulled down internally.
WP, Input, Write Protect.
When tied to VDD, addresses in the entire memory map will be write-protected. When WP is connected to ground, all addresses are write enabled. This pin is pulled down internally.


text:
Q: Double selection of a uitableviewcell in Custom Cell i have an issue regarding UitableViewCell. the issue is that i have made a custom cell and i have a check box image button in that cell. i check and uncheck it. it works fine but the issue is that when i select Row # 1. it also selects row # 10 same goes with other rows like for 2 it will auto select row # 11. i am showing 10 rows at a time.
here is my code for CellForIndexPath
static NSString *cellIdentifier = @"Cell";
InterestsTableViewCell *cell = (InterestsTableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell==nil) {
    NSArray *arrayNibs = [[NSBundle mainBundle] loadNibNamed:@"InterestsTableViewCell" owner:self options:nil];
    cell = [arrayNibs objectAtIndex:0];
    cell.delegate = self;
    cell.total = [dataArray count];
}

cell.tag = indexPath.row;

cell.lblTitle.text = [dataArray objectAtIndex:indexPath.row];

if (indexPath.row==0) {
    cell.imgBg.image = [UIImage imageNamed:@"tableCell_top_default.png"];
}else if(indexPath.row == [dataArray count]-1){
    cell.imgBg.image = [UIImage imageNamed:@"tableCell_bottom_default.png"];
}else{
    cell.imgBg.image = [UIImage imageNamed:@"tableCell_middle_default.png"];
}

return cell;

Plus i am detecting touch so that i can change the background image (i have an other image as background). Code for Touch Began (in custom cell is below)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//NSLog(@"%i",tag);
isSelected = !isSelected;

btnTickMark.selected = !btnTickMark.selected;
(isSelected ?  (onImage = YES) : (onImage = NO));

Can somebody help me in this issue that why 2 rows are selected when i click a row.
Thanks in advance

A: This is because UITableView dequeues the cell. As you are showing 10 rows per screen it totally fits, that row 11 appears checked as it is dequeued from row 1.
To avoid that behavior you have to add a check to tableView:cellForRowAtIndexPath: to set your checked parameter for each cell – like the text you set for every cell.

A: Try this:
NSArray *arrayNibs = [[NSBundle mainBundle] loadNibNamed:@"InterestsTableViewCell" owner:self options:nil];
for (id currentObject in arrayNibs){
    if ([currentObject isKindOfClass:[UITableViewCell class]]){
        cell =  (InterestsTableViewCell *) currentObject;
        cell.Delegate = self;
        cell.total = [dataArray count];
        break;
    }
}

and let me know if this works for you.

A: Quick Fix - change this line from
InterestsTableViewCell *cell = (InterestsTableViewCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

to
InterestsTableViewCell *cell = nil;

Its not good from a memory/efficiency perspective because you won't be reusing the cells, instead will be reloading one from nib each time - but it will demonstrate whether what Florian Mielke is saying is correct (and his recommended approach will provide a better solution long term).


text:
Q: ChartJS - Update doesn't work when I get data from an API to get new data I have issue where when I update chart with new data, the data just append to a chart.
.ts file
export class InfoComponent implements OnInit {

  public chart: Chart = [];
  id: any;
  date = [];
  price = [];

  constructor(private cryptoAPIService: CryptoAPIService, private route: ActivatedRoute) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.paramMap.get('id');
    console.log(this.id);
    this.getValueById(1);
  }

  getValueById(period) {

    if (typeof this.chart.canvas !== "undefined") {
        console.log(this.date[0]);
        return this.cryptoAPIService.getChartValues(this.id, period).subscribe(res => {
        for(let val of res[0]) {
          var temp = new Date(val[0]).toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric', hour12: false, hour: '2-digit', minute: '2-digit' });
          this.date.push(temp);
          val[1] = Math.round((val[1] + Number.EPSILON) * 100) / 100; // round to 2 decimals
          this.price.push(val[1]);
        }
        console.log("Chart created");
        console.log(this.date);

        this.chart.data.labels = this.date;
        this.chart.data.datasets[0].data = this.price;
        this.chart.update();
      });
    } else {
    return this.cryptoAPIService.getChartValues(this.id, period).subscribe(res => {
      for(let val of res[0]) {
        var temp = new Date(val[0]).toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric', hour12: false, hour: '2-digit', minute: '2-digit' });
        this.date.push(temp);
        val[1] = Math.round((val[1] + Number.EPSILON) * 100) / 100; // round to 2 decimals
        this.price.push(val[1]);
      }
      this.chart = new Chart('canvas', {
        type: 'line',
        data: {
          labels: this.date,
          datasets: [
            {
              data: this.price,
              borderColor: '#45b6fe'
            },
          ]
        },
        options: {
          tooltips: {
            callbacks: {
              label: (tooltipItems, data) => {
                  return '$' + data.datasets[tooltipItems.datasetIndex].data[tooltipItems.index];
              }
          },
        },
          legend: {
            display: false
          },
          scales: {
            xAxes: [{
              display: true
            }],
            yAxes: [{
              ticks: {
                userCallback: function(tick) {
                  return '$' + tick.toString() ;
                }
              },
              display: true
            }],
          }
        }
      });
      console.log("Chart created");
    });
  }
}
}

HTML file
24h
7 Days
Month
Year

  <canvas id="canvas">{{ chart }}</canvas>

So I have tried this while updating just to see where the problem is:
this.chart.data.labels = [10,15,22,14];
this.chart.data.datasets[0].data = [1,111,24,24];

After this the data are displayed normaly, no appends. It is shown like a new Chart what is actually that I need, but with the data from an API.
I am wondering why it doesn't reset chart when I use data from an API, any solutions ?


text:
Q: ¿Como puedo eliminar cualquier elemento de una pila en C++? Me podrían ayudar a como en este código podría eliminar cualquiera de los elementos que se ingresen a la pila.
#include <iostream>
#include <malloc.h>
using namespace std;

struct nodo{
    char placa [6];
    nodo *sig;
};

nodo *cab, *aux;
int ingresar (){
    aux= (struct nodo *) malloc(sizeof(struct nodo));
    cout<<"Ingrese la placa del carro:";
    cin>>aux->placa;

    if (cab==NULL){
        cab = aux;
        cab->sig=NULL;
    }
    else {
        aux->sig = cab;
        cab= aux;
    }
    aux= NULL;
    free(aux);

    return 0;
}

int sacar (){
    if (cab!=NULL){
        aux= cab;
        cab= cab->sig;
        free(aux);
        return 0;
    }

}

int mostrar (){
    aux= cab;
    while(aux!=NULL){
        cout<<"Carro: ";
        cout<<aux->placa<<endl;
        aux= aux->sig;

    }
}

int main(){
    int opc=0;
    do{
        cout<<"1. Ingresar carro"<<endl;
        cout<<"2. Sacar carro"<<endl;
        cout<<"3. Mostrar carros"<<endl;
        cout<<"4. Salir"<<endl;
        cin>>opc;
        switch(opc){
            case 1: ingresar(); break;
            case 2: sacar(); break;
            case 3: mostrar(); break;
        }

    }while(opc!=4);
    return 0;
}

Está la función para sacar, pero solo saca el ultimo agregado, quiero que se pueda sacar cualquiera de los ingresados.

A:
Me podrían ayudar a como en este código podría eliminar cualquiera de los elementos que se ingresen a la pila.

Si pretendes eliminar elementos arbitrarios de la pila, entonces no es una pila, es una lista.

Por lo que veo, estás desarrollando una lista enlazada, en general para eliminar un nodo arbitrario, los pasos a seguir son los siguientes:
Suponiendo que E es el nodo a eliminar y tanto A como P son respectivamente el anterior y el posterior a E:

*

*Enlaza el siguiente de A con P.

*Elimina E.

La función que hace eso podría parecerse a:
void Eliminar(char (&placa)[6])
{
    for (nodo *actual = cab, anterior = nullptr; actual; anterior = actual, actual = actual->sig)
    {
        if (std::equal(placa, placa + 6, actual->placa))
        {
            if (anterior)
            {
                // Enlaza el siguiente de 'A' con 'P'.
                anterior->sig = actual->sig;
            }
            else
            {
                // A no ser que sea el primer nodo, en ese caso cambiamos la cabeza
                cab = actual->sig;
            }

            delete actual;
            return;
        }
    }
}

Una vez respondida la pregunta, vamos a lo serio: Has etiquetado y titulado la pregunta como c++, pero tu código apenas sigue los paradigmas de ese lenguaje, necesitas hacer las siguientes correcciones:

*

*No uses cabeceras de c, <malloc.h> no es una cabecera de C++, no la uses. Lee este hilo para saber más del tema.

*Evita las variables globales. Lee esta respuesta para saber más del tema.

*No uses malloc y free, en C++ la memoria dinámica se gestiona con new y delete.

*Encapsula tus datos.

A: La pila al estar implementada como lista enlazada, cada nodo tiene como referencia un puntero que apunta hacia el siguiente elemento de la lista.
Es decir, al ser una pila solo puedes acceder al ultimo elemento. Sin embargo, como existe esta referencia, puedes recorrer toda la pila como si se tratara de recorrer una lista enlazada al revés.
Para eliminar un enésimo elemento de tiene que

*

*Posicionar una iteración un nodo antes que el elemento a remover.

*Usar estas referencias para conectar el nodo en la iteración actual con un nodo dos espacios adelante

*Asignarle al nodo a remover como siguiente elemento NULL, que queda perfecto por que es un puntero.

Mi ejemplo es general, defino dos structs. Uno como nodo y otro como pila:
typedef struct node {
    int value;
    struct node *next;
} NODE_t;

typedef struct {
    NODE_t *top;
} STACK_t;

Para hacer más abstracta la inicialización de nodos y de la pila, tengo estas dos funciones "constructoras":
NODE_t *Node(int value) {
    NODE_t *node = (NODE_t*)malloc(sizeof(node));
    node -> value = value;
    node -> next = NULL;

    return node;
}

STACK_t *Stack(NODE_t *node) {
    STACK_t *stack = (STACK_t*)malloc(sizeof(stack));
    stack -> top = node;

    return stack;
}

La función que se encarga de añadir elementos a la pila

*

*Crea un nuevo nodo.

*Redifine la referencia inicial hacia NULL, por la cima de la pila.

*Define la cima de la pila como el nuevo nodo.

int push(STACK_t *stack,int value) {
    NODE_t *new_node = Node(value);
    if (new_node == NULL) return -1;

    new_node -> next = (stack -> top);
    stack -> top = new_node;
    return 0;
}

Se produciría algo así:
Cima <= Nuevo Nodo

Existe la referencia de que cuando se elimine el último elemento de la pila, la cima va a ser el elemento anterior a este. Este elemento es un nodo, que tiene como siguiente a la cima.
Al existir este tipo de referencia doble, puedes recorrer la pila en dirección contraria (como lista enlazada), y eliminar el nodo como si fuera una lista enlazada.
                              NULL
                               *
                               |
 Iteración Actual ***> Siguiente Nodo ***> Siguiente Siguiente Nodo
        |                                              *
        |                                              |
        |===============================================

Donde ****> las referencias sin modificar
Ten en cuenta, que si se va a extraer el último elemento de la pila se tiene que usar la función para extraer solo el último.
void remove(STACK_t *stack,int index) {
    int count = 0;
    NODE_t *temp = (stack -> top);

    while(true) {
        if (count == (index - 1)) {
            NODE_t *aux = (temp -> next);
            (temp -> next) = (temp -> next) -> next;
            (aux -> next) = NULL;
            free(aux);

            break;
        }

        temp = temp -> next;
        count++;
    }
}

Al implementar esta función, la pila pierde su concepto. Debido a que estarías extrayendo un elemento que no es el último. Más bien sería una lista enlazada con una cima.
Lo más conveniente para imprimir una pila es usar el método pop() hasta que retorne NULL, pero decidí no implementarlo. Para imprimir la pila como lista enlazada se tiene que recorrer en dirección contraria hasta que un nodo equivalga a NULL:
void print(STACK_t *stack) {
    NODE_t *temp = (stack -> top);

    printf("{ ");
    while (temp != NULL) {
        std::cout << temp -> value << " ";
        temp = temp -> next;
    }
    printf("}\n");
}

Ahora implementando la "pila", se añaden los nodos se remueve x elemento y se imprime por pantalla:
int main(int argc, char const *argv[]) {
    STACK_t *mystack = Stack(Node(25));
    push(mystack,67);
    push(mystack,137);
    push(mystack,26);
    push(mystack,15);
    push(mystack,123);
    print(mystack);

    remove(mystack,3);
    print(mystack);

    return 0;
}

En ejecución muestra:
{ 123 15 26 137 67 25 }
{ 123 15 26 67 25 }

Espero haberte ayudado. :)

A: lo que pides como tal, no se puede. Sin embargo, podemos crear una funcion que:

*

*Crea una pila auxiliar

*Vacie todos los datos de la pila primaria a la auxiliar

*Obtenga la posicion de elemento deseado

*Pasar todos los datos, salvo el elemento a eliminar.

*Completo.

Primer paso, creamos un metodo en el cual obtendremos la posicion del elemento a eliminar:
int Pila::posicion(int x){}
Luego creamos una Pila auxiliar con la que nos apoyaremos, ademas de otras variables, como un contador y una bandera (uno para ir verificando cuantos datos hemos recorrido y, el otro para decir si, es la que deseamos eliminar o no.:
Pila paux;
int band = 0:
int contador = 0;

Muy bien ahora viene la parte donde comprobamos si la pila no esta vacia, ya que, si esta vacia, que nos arroje un mensaje, seguido de un finalizar el metodo, esto lo logramos con un return -1, entonces, esta parte quedaria algo asi:
if(estaVacia()){
    cout<<"Error en posicion()\n";
    return -1;
}

Si este no es el caso, nos dirigimos al else donde viene la parte divertida y es que debemos pensar que sigue:

*

*Recorrer la pila mientras esta no este vacia.

*Contar y llevar nuestro control con la variable contador

*Esperar a que nuestra bandera cambie de valor, si encontramos el dato que deseamos

Comencemos, lo primero que necesitamos es, recorrer la pila mientras esta aun tenga elementos y, durante el recorrido, ir checando el estado de nuestra bandera (para detectar si esta cambia de valor). En codigo se traduce:
while(!estaVacia() && !band)

y dentro de este ciclo while, preguntamos si el dato que tenemos, es igual al que buscamos, la bandera cambia de 0 a 1.
if(getDato()==x)
    band =1;

en caso de que esto no suceda, todos los elementos de tu pila original, se muevan a la pila auxiliar, excepto el dato que deseas sacar.
else
    contador++;
    paux.push(getDato());
    pop();

Espera, que aun no hemos acabado, ya encontramos el dato que buscabamos, tambien lo eliminamos, y usamos la pila auxiliar. Pero, no hemos devuelto los elementos a la pila original, ya que, si no las traemos de vuelta, estas pueden perderse.
Iteramos en la pila auxiliar mientras esta no este vacia, para obtener los datos, sacarlos de esta pila y agregarlos de nueva cuenta a la pila original.
while(!paux.estaVacia())
    push(paux.getDato());
    paux.pop();

Y de esa manera es como puedes sacar un dato "de cualquier lugar"
El codigo completo quedaria algo asi:
    int Pila::posicion(int x){
    Pila paux;

    int contador=0;
    int band = 0;

    if(estaVacia()){
        cout<<"Error en posicion()\n";
        return -1;
    }else{
        while(!estaVacia() && !band){
            if(getDato()==x)
                band =1;

                else
                    contador++;
            paux.push(getDato());
            pop();
        }while(!paux.estaVacia()){
            push(paux.getDato());
            paux.pop();
        }
        if(band)
            return contador;
        else
            return -1;
    }
}

Tambien te agrego el metodo getDato()
int Pila::getDato(){
    if(estaVacia()){
       cout<<"Error en getDato()";
        return -1;
    }
    return tope->getDato();
}

Aclaracion, el codigo que explico es de un ejercicio que resolvi en la universidad, el cual difiere un poco de sintaxis con el tuyo. Aunque la logica es la misma. Si tienes alguna duda aqui estamos :)


text:
Q: PYTHON randomize questions from a list and enumerate I have a list of 25 questions that I'd like to randomly select 7. The list of questions will be in an IRC client (Textual). the following is an example of what I currently have as questions and my proposed process of randomizing 7 from my list.
I'd like to make
questions=[
    'Finish this poem "Roses are red Violets are ..."',
    'What is your favorite food?','Stones or Beatles?',
    'favorite pet?',
    'favorite color?',
    'favorite food?'
]

for q in xrange(3):
    question = ''
    while question not in questions:
        # this is where I'm stuck

I would like something like.

*

*What is your favorite food?

*favorite pet?

*Stones or Beatles?

The end result will be 7 questions from a pool of 25.

A: You can use shuffle():
from random import shuffle

shuffle(questions)

for question in questions[:7]:
    answer = input(question)
    # do something with answer

A: Use random.sample():
import random

for question in random.sample(questions, 7):
    answer = input(question)

You need to have enough questions, however.  Right now you have only six questions in the list, so random.sample() won't be able to come up with seven random questions.  I'm assuming that your real list has 25 questions since you said from a pool of 25, so I merely comment.

A: A good approach could be use random.sample.
>>> from random import sample
>>> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm']
>>> selected = []

>>> for item in sample(items, 7):
...    selected.append(item)
>>> print selected
['h', 'l', 'j', 'm', 'i', 'e', 'c']


text:
Q: Parsing Windows Event Logs stored in syslog-ng system with multi-lines and tabs I am trying to parse through a couple hundred gigs of Windows event logs that have not been formatted using SNARE, NXlog, or Adiscon (I am not sure how they shipped them to the syslog server).
The problem I am running into is determining the best/most efficient way to parse through a multi-line, multi-tabbed Windows event file. I don't have the corresponding EVTX file (it is just a log file).
My goal is to get each event onto one line, with no tabs so that I can parse through it easier using grep and awk.
tr -d "\n\r" < windows.log gets all of the content on one line (removes newlines) and now I would need to strip tabs (tabs less important than new lines) and figure out a way to add a new line every time BEFORE "Jan 14" is seen.
There is probably be a better way to do this with Python, Perl, or Powershell, but I am limited in experience there.
Example log file:
Jan 14 00:00:02 server.host.com MSWinEventLog    5       Security        22159648        Sun Jan 13 23:59:35 2019        4634    Microsoft-Windows-Security-Auditing             N/A     Audit Success   server.host.com  12545   An account was logged off.

Subject:
        Security ID:            S-1-5-21-3015042641-2194367929-112691256-2051
        Account Name:           SVCACCT
        Account Domain:         MYDOMAIN
        Logon ID:               0xD7FC64F5

Logon Type:                     3

This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.

Jan 14 00:00:02 server.host.com  MSWinEventLog    5       Security        22159649        Sun Jan 13 23:59:35 2019        4634    Microsoft-Windows-Security-Auditing             N/A     Audit Success   server.host.com   12545   An account was logged off.

Subject:
        Security ID:            S-1-5-21-3015042641-2194367929-112691256-12106
        Account Name:           SVCACCT2
        Account Domain:         MYDOMAIN
        Logon ID:               0xD7FC600A

Logon Type:                     3

This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.

Example log file condensed:
Jan 14 00:00:02 server.host.com MSWinEventLog    5       Security        22159648        Sun Jan 13 23:59:35 2019        4634    Microsoft-Windows-Security-Auditing             N/A     Audit Success   server.host.com  12545   An account was logged off. Subject: Security ID:            S-1-5-21-3015042641-2194367929-112691256-2051 Account Name:           SVCACCT Account Domain:         MYDOMAIN Logon ID:               0xD7FC64F5 Logon Type:                     3 This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.

Jan 14 00:00:02 server.host.com MSWinEventLog    5       Security        22159648        Sun Jan 13 23:59:35 2019        4634    Microsoft-Windows-Security-Auditing             N/A     Audit Success   server.host.com  12545   An account was logged off. Subject: Security ID:            S-1-5-21-3015042641-2194367929-112691256-2051 Account Name:           SVCACCT2 Account Domain:         MYDOMAIN Logon ID:               0xD7FC64F5 Logon Type:                     3 This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.

A: First, we remove all control characters. Then we search for "Jan 14" and add a newline before it. Finally, we call tr with the -s flag which replaces instances of repeated characters with a single character. I am not quite sure how efficient this is but it might get you started.
tr -d "[:cntrl:]" < windows.log | sed 's/Jan 14/\'$'\n&/g' | tr -s " "

Result
Jan 14 00:00:02 server.host.com MSWinEventLog 5 Security 22159648 Sun Jan 13 23:59:35 2019 4634 Microsoft-Windows-Security-Auditing N/A Audit Success server.host.com 12545 An account was logged off.Subject: Security ID: S-1-5-21-3015042641-2194367929-112691256-2051 Account Name: SVCACCT Account Domain: MYDOMAIN Logon ID: 0xD7FC64F5Logon Type: 3This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.
Jan 14 00:00:02 server.host.com MSWinEventLog 5 Security 22159649 Sun Jan 13 23:59:35 2019 4634 Microsoft-Windows-Security-Auditing N/A Audit Success server.host.com 12545 An account was logged off.Subject: Security ID: S-1-5-21-3015042641-2194367929-112691256-12106 Account Name: SVCACCT2 Account Domain: MYDOMAIN Logon ID: 0xD7FC600ALogon Type: 3This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.

A: Instead of trying to get every record squeezed onto 1 line and then trying to analyze it, just handle each 12-line block as a single record. For example:
$ cat tst.awk
{
    gsub(/\r/,"")
    gsub(/^[[:space:]]+|[[:space:]]+$/,"")
    lineNr = (NR - 1) % 12 + 1
}
lineNr == 1 {
    f["hd"] = $0
}
lineNr ~ /[45679]/ {
    tag = val = $0
    sub(/:.*/,"",tag)
    sub(/[^:]+:[[:space:]]*/,"",val)
    f[tag] = val
}
lineNr == 11 {
    f["tl"] = $0
    for (tag in f) {
        print tag, "=", f[tag]
    }
    print "-------"
}

.
$ awk -f tst.awk file
tl = This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.
Logon ID = 0xD7FC64F5
Logon Type = 3
Account Name = SVCACCT
Security ID = S-1-5-21-3015042641-2194367929-112691256-2051
hd = Jan 14 00:00:02 server.host.com MSWinEventLog    5       Security        22159648        Sun Jan 13 23:59:35 2019        4634    Microsoft-Windows-Security-Auditing             N/A     Audit Success   server.host.com  12545   An account was logged off.
Account Domain = MYDOMAIN
-------
tl = This event is generated when a logon session is destroyed. It may be positively correlated with a logon event using the Logon ID value. Logon IDs are only unique between reboots on the same computer.
Logon ID = 0xD7FC600A
Logon Type = 3
Account Name = SVCACCT2
Security ID = S-1-5-21-3015042641-2194367929-112691256-12106
hd = Jan 14 00:00:02 server.host.com  MSWinEventLog    5       Security        22159649        Sun Jan 13 23:59:35 2019        4634    Microsoft-Windows-Security-Auditing             N/A     Audit Success   server.host.com   12545   An account was logged off.
Account Domain = MYDOMAIN
-------

With that approach you can simply refer to every field by it's name for printing or analysis. You can extend the above to map all of the separate fields on the first line into separate tags/values e.g.
lineNr==1 {
    f["timestamp"] = $1 " " $2 " " $3
    ...
}

or with a regexp match or whatever makes sense. Once you[ve done the above it becomes absolutely trivial to analyze or print whatever you like in the rest of the script.


text:
Q: Changing colour of NavigationBar and Barbutton I have a UINavigationBar, and the colour of it is purple. I have added a uibarbutton of the left of it. It too is purple, But what i want it to look is black.
1.) I only need the navigationbar to remain purple, everything else uibarbutton, navigation back button (when we go from one view to another we get a arrow shaped back button) should be black.
I used the interface builder to change the colour of the uibarbutton (setTint), but when i ran it on my iOS 4.3 device it still appears as purple.
I tried cleaning, building and re-installing the app nothing hapence.

A: You can't set a different tintColor for both objects, but you can set an image as the button background.
I hope it helps you!

A: Just set it up like this
// Loads the view
-(void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem* settings = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsButtonEvent:)]];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor redColor]];
  // some more code for your view

}


text:
Q: How to repeat option with filenames? I have a command which is of the form
#!/bin/bash

command -f hello.txt -f world.txt -f bonjour.txt

hello.txt, world.txt and bonjour.txt are files which are in the directory /directory.
Since in reality there are 50 or 60 such files (and they change), I would like to generate the "-f" parts after command.
This would have been easy if the command was (just one -f)
command -f hello.txt world.txt bonjour.txt

because I would have gone for
command -f $(ls /directory)

Is there a simple way to join -f and elements from ls /directory?
I am looking for the equivalent of the Python
"-f " + " -f ".join(['hello.txt', 'world.txt', 'bonjour.txt'])

where ['hello.txt', 'world.txt', 'bonjour.txt'] is a generated list.

A: Build the variable using a for loop.
Because you're using Bash, you should use an array variable, because command-line arguments are in fact an array and not a single flat string. This would avoid various quoting-related problems:
args=()
for file in /directory/*; do
    args+=(-f "${file##*/}")
done
mycommand "${args[@]}"

For the same reason, avoid $(ls) when you can use built-in wildcards i.e. *.
If you're writing for baseline POSIX shell and not specifically for Bash, you need to use string variables but you can still use * to get the file names, as well as for to join them together:
args=""
for file in ...; do
    args="$args ..."
done
mycommand $args

There are more compact ways of writing this, but they're neither easier to read nor significantly faster.

A: I would use automatic expansion with printf like this:
command $( printf -- '-f %q ' *.txt )
which would result in a command like this, depending on whatever .txt files reside in your directory:
command -f hello.txt -f world.txt -f bonjour.txt


text:
Q: If-statement for 20 years from the Current Date I am trying to:
1) Set 2 variable in date format.
 2) 1 variable cannot be more then twenty years from the current date.
 3) Those variables then set another variable's cell values which are set to a numerical format.
The macro is not functional and I am getting issues trying to code the worksheet as worksheet.
Sub Date_Check()

'Coding Variables

Dim WB As ThisWorkbook
Dim Test_Data As Sheet1
Dim statedate as String
statedate = Format(Date, "mm/dd/yyyy")
Dim enddate as string
enddate = Format(Date, "mm/dd/yyyy")
Dim todaydate as date
'Coverage date is enddate-statedate cell
Dim CvgDate as Range
Set CvgDate(26) = enddate.value - statedate.value
Dim jj as Integer
Dim x as boolean
x = True

'set the ranges as the last cell to contain values

With Worksheet("TestData")
    .Range("V2:V"). Offset(-1,0).xldown.Value2 = startdate
    .Range("W2:W").Offset(-1,0).xldown.Value2 = enddate
    .Range("FutureDate").Format(Date, "yyyy") = True

    ' Error!

    ' I am getting an argument not option error when trying to set futureyear.
    'Create function that will check if range is 20 years within today's date.
    FutureYear = 20  < DateSerial(Year, 1)
    .Range("enddate").Offset(-1, 0).Select =x
    .Cell.Number = "mm/dd/yyyy"

    'Create an if statement using fuction
    If Range("enddate").Cell <> = FutureYear Then
        MsgBox "Please check that the end reporting date is within 20 years from today's date!"
    End If

    'Ensure that enddate meets criteria before being put in numerical format
    .Range("Cvgdate").Offset(-1,0).Select
    .Selection.NumberFormat = "jj"

End With

Any suggestions are helpful but I am focused on ensuring that the enddate variable is within 20 years of the current date.

A: I'm really struggling to understand what you are trying to do given the code that is posted. I can't imagine it making it all the way to the line that is throwing the error without erroring well before that.
Just the same, here is a brief rewrite that I think is close to what you are trying to do. Namely, Get two dates from the worksheet in columns V and W and set those dates to a variable. Then compare the enddate from column W to current date and throw a message box up if it's more than 20 years from now.
Sub Date_Check()
    Dim startdate as date
    Dim enddate as date

    With Worksheet("TestData")
        'Set startdate and end date getting it form the last populated row in each column
        startdate = .Range("V2").End(xlDown).Value
        enddate = .Range("W2").End(xlDown).Value

        'Check to see if enddate is more than 20 years from now (ignoring leap years)
        If enddate - Date > 365*20 Then
            MsgBox "Please check that the end reporting date is within 20 years from today's date!"
        End If

    End With
End Sub

This doesn't take into account your cvgdate range, but that is set incorrectly and you never really do anything with it besides change the number format.
A couple of pointers:

*

*If you are dealing with a date in a variable, then declare the variable as a date. String dates are of the devil. You can't subtract strings, and you can't compare string dates with other string dates without substringing yourself into a corner.

*Above all of your code in your module put Option Explicit this will cause your VBE to throw an error if you try to use a variable that is not declared catching spelling mistakes as they happen.

*Don't .Select or .Activate. That's for humans, not code. The only exception is if, at the end of your code, you want to set a particular worksheet or cell as selected. Then a nice little Sheet1.Range("A1").Select so your user is set up at the top of the worksheet is totally cool.


text:
Q: WebClient - get response body on error status code I'm looking essentially for the same thing asked here:
Any way to access response body using WebClient when the server returns an error?
But no answers have been provided so far.
The server returns a "400 bad request" status, but with a detailed error explanation as response body.
Any ideas on accessing that data with .NET WebClient? It just throws an exception when server returns an error status code.

A: You cant get it from the webclient however on your WebException you can access the Response Object cast that into a HttpWebResponse object and you will be able to access the entire response object.
Please see the WebException class definition for more information.
Below is an example from MSDN (added reading the content of the web response for clarity)
using System;
using System.IO;
using System.Net;

public class Program
{
    public static void Main()
    {
        try {
            // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
            HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL");

            // Get the associated response for the above request.
            HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
            myHttpWebResponse.Close();
        }
        catch(WebException e) {
            Console.WriteLine("This program is expected to throw WebException on successful run."+
                              "\n\nException Message :" + e.Message);
            if(e.Status == WebExceptionStatus.ProtocolError) {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream()))
                {
                    Console.WriteLine("Content: {0}", r.ReadToEnd());
                }
            }
        }
        catch(Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}

A: You can retrieve the response content like this:
using (WebClient client = new WebClient())
{
    try
    {
        string data = client.DownloadString(
            "http://your-url.com");
        // successful...
    }
    catch (WebException ex)
    {
        // failed...
        using (StreamReader r = new StreamReader(
            ex.Response.GetResponseStream()))
        {
            string responseContent = r.ReadToEnd();
            // ... do whatever ...
        }
    }
}

Tested: on .Net 4.5.2


text:
Q: SQL Order Results Count by specific Query I have a table with the following data:
Snack ID   |   Child    |  Fruit

1              Child A     Apple
2              Child B     Orange
3              Child A     Banana
4              Child A     Orange
5              Child C     Banana
6              Child A     Banana
7              Child C     Banana
8              Child A     Banana

And another table listing out the fruits available in each Child's hometown grocery:
Child ID   |   Child Name   |  Local Fruit 1  | Local Fruit 2 |  Local Fruit 3

1              Child A         Apple            Mango            Orange
2              Child B         Orange           Banana           Cherry
3              Child C         Banana           Mango            Apple

I need to order the results, from highest to lowest, for the number of a specific fruit eaten for each child, but only if said fruit is one of their hometown fruits;
If the query is "Orange", I need the results to display as below:
Hometown Orange Eaters (Highest to Lowest)

Child   |   Number of Fruits eaten

Child A     1
Child B     1

if the query is "Mango":
Hometown Mango Eaters

Child   |   Number of Fruits eaten

Child A     0
Child C     0

For Bananas (Child A is not displayed, despite eating the most bananas, as this is not one of their hometown fruits):
Hometown Banana Eaters

Child   |   Number of Fruits eaten

Child C     1
Child B     0

The SQL command I am currently using is as follows:
select child, sum(fruit = '$fruit') `Number of fruits eaten`
from meals
group by child
order by `Number of fruits eaten` desc

However, this only displays results for those that have already eaten the fruit; e.g. for the banana example, only the below is displayed:
Hometown Banana Eaters

Child   |   Number of Fruits eaten

Child C     1

How can I adjust the current command so that all "hometown fruit" children are displayed, regardless of if they have eaten said fruit or not?

A: Here is one option:
select child,
    (select count(*) from meals m where m.child = l.child and m.fruit = ?)  cnt
from listing l
where ? in (local_fruit_1, local_fruit_2, local_fruit_3)
order by cnt

The logic is to filter the listing table for rows where the concerned fruit can be found. Then, we use a correlated subquery to bring the count of fruits that were eaten.
The question marks represent the fruit whose analysis you want to bring.

A: I think this is a join and aggregation with filtering:
select s.child, sum(c.fruit = $fruit) as num_fruit
from snacks s join
     child c
     on c.child_id = s.child
where $fruit in (c.local1, c.local2, . . . )
group by s.child
order by num_fruit desc;


text:
Q: Edit Existing PDF multiple page File using FPDF & FPDI I am usinf FPDI to edit my existing pdf file and its work perfect for single page.
As ou can see i am editing my $tplIdx = $pdf->importPage(1); first page.
I have six page pdf file and need to add 2 variable in different page.
Is is possible ? How?
<?php
require_once('fpdf.php');
require_once('fpdi.php');

// initiate FPDI
$pdf = new FPDI();
// add a page
$pdf->AddPage();
// set the sourcefile
$pdf->setSourceFile('ex.pdf');

// import page 1
$tplIdx = $pdf->importPage(1);

// use the imported page and place it at point 10,10 with a width of 100 mm
$pdf->useTemplate($tplIdx, 10, 10, 200);

// now write some text above the imported page
$pdf->SetFont('Arial');
$pdf->SetTextColor(255,0,0);
$pdf->SetXY(50, 50);
$pdf->Write(0, "Ajay Patel");

$pdf->Output('newpdf1.pdf', 'D');
?>

Thanks In Advance !

A: Thanks @J A Your idea works for me
I just posted answer for other to help them
<?php
require_once('fpdf.php');
require_once('fpdi.php');

// initiate FPDI
$pdf = new FPDI();
// add a page
$pdf->AddPage();
// set the sourcefile
$pdf->setSourceFile('newpdf.pdf');

// import page 1
$tplidx = $pdf->importPage(1);
for ($i = 1; $i < 6; $i++) {
              $tplidx = $pdf->ImportPage($i);

                     $pdf->useTemplate($tplidx, 10, 10, 200);
                     $pdf->AddPage();

                     $pdf->SetFont('Arial');
                     $pdf->SetTextColor(0,0,0);
                     $pdf->SetFontSize(8);

                     if ($i==3) {
                        $pdf->SetXY(50, 124);
                        $pdf->Write(1, "Ajay Patel");

                        $pdf->SetXY(50, 133);
                        $pdf->Write(1, date("d/m/Y"));
                     }

                     if ($i==4) {
                        $pdf->SetXY(50, 171);
                        $pdf->Write(1, "Ajay Patel");

                        $pdf->SetXY(50, 185);
                        $pdf->Write(1, date("d/m/Y"));
                     }

                }

$pdf->Output('newpdf1.pdf', 'D');
?>

A: It's hard to try without FPDI installed. But the core idea would be following I believe:
<?php

  require_once('fpdf.php');
  require_once('fpdi.php');

  // initiate FPDI
  $pdf = new FPDI();

  /* <Virtual loop> */
  $pdf->AddPage();
  $pdf->setSourceFile('ex.pdf');
  $tplIdx = $pdf->importPage(1);

  $pdf->useTemplate($tplIdx, 10, 10, 200);

  // now write some text above the imported page
  $pdf->SetFont('Arial');
  $pdf->SetTextColor(255,0,0);
  $pdf->SetXY(50, 50);
  $pdf->Write(0, "Ajay Patel");

  /* </Virtual loop/> */

  $pdf->AddPage();
  //$pdf->setSourceFile('ex.pdf');
  $tplIdx = $pdf->importPage(2);

  $pdf->useTemplate($tplIdx, 10, 10, 200); // dynamic parameter based on your page

  $pdf->SetFont('Arial');
  $pdf->SetTextColor(255,0,0);
  $pdf->SetXY(50, 50);
  $pdf->Write(0, "Ajay Patel2");

  $pdf->Output('newpdf1.pdf', 'D');
?>

If this works you can get rid of the second block of the code and out this on a loop (and dynamic positioning as well).

A: You should really make use of the return value of setSourceFile to iterate over all pages:
Description
public int FPDI::setSourceFile ( string $filename )
Depending on the PDF version of the used document the PDF version of the resulting document will be adjusted to the higher version.
Parameters
$filename : string // A valid path to the PDF document from which pages should be imported from

Return Values
The number of pages in the document


text:
Q: nameError name is not defined Hello I am trying to create a program where you input how many hours you worked and the rate per hour. Every hour over 40 is counted as over time (x1.5).
I am getting a nameError on line 11. (  ganancias = (horas * tarifa)
NameError: name 'horas' is not defined)
I dont understand why since I defined "horas" in the second line. Thanks for your time!
def calculo_salario() :
  horas = float(input("input salario: "))
  tarifa = float(input("input tarifa: "))

def sums(a,b):
  sum = a + b
  return sum

calculo_salario()

ganancias = (horas * tarifa)
preOt = (40 * tarifa)

if horas > 40 :
    overtimeHr = horas - 40
    overtimeAm = (overtimeHr * tarifa) * 1.5
    gananciasOt = sums(overtimeAm, preOt)
    print(gananciasOt)

else :
    print(ganancias)

A: Your issue is on the scope of horas. You're defining horas as a local variable in the method calculo_salario. This means that the variable will only be available inside the method definition and not outside.
I'd suggest starting out your program without any methods and then figure out how it would work by encapsulating logic within these methods.
horas = float(input("input salario: "))
tarifa = float(input("input tarifa: "))

ganancias = (horas * tarifa)
preOt = (40 * tarifa)

if horas > 40 :
    overtimeHr = horas - 40
    overtimeAm = (overtimeHr * tarifa) * 1.5
    gananciasOt = overtimeAm + preOt
    print(gananciasOt)

else :
    print(ganancias)

The code above should run without any issues notice that now all the variables are in the global scope of the script.

A: Check out variable scope. Right now, horas and tarifa are being dropped as soon as calculo_salario() is finished.
To fix this, one option is to return the values. Of course, in this specific instance you don't need a method at all, but that's not the point.
def calculo_salario() :
  horas = float(input("input salario: "))
  tarifa = float(input("input tarifa: "))
  return (horas, tarifa)

...

(horas, tarifa) = calculo_salario()

...

A: I used jhpratt's suggestion in using the return to assign those values to "calculo_salario()"
here is my final working code
def calculo_salario() :
  horas = float(input("input salario: "))
  tarifa = float(input("input tarifa: "))
  return (horas, tarifa)

(horas, tarifa) = calculo_salario()
ganancias = (horas * tarifa)
preOt = (40 * tarifa)

if horas > 40 :
    overtimeHr = horas - 40
    overtimeAm = (overtimeHr * tarifa) * 1.5
    gananciasOt = (overtimeAm + preOt)
    print("salario: " , gananciasOt)

else :
    print("salario:" , ganancias)


text:
Q: jsReport xlsx Recipe beforeRender When Rendering a XLSX recipe with data from mssql I get this error

Error occured - Error during rendering report: Cannot read property
  'xl/worksheets/sheet1.xml' of undefined Stak - TypeError: Cannot read
  property 'xl/worksheets/sheet1.xml' of undefined
      at Object.add (evalmachine.:176:42)
      at Object. (evalmachine.:406:17)
      at Object.eval (eval at createFunctionContext

I have my linked script set up to load data. example:
var sql = require('mssql');
var config = {
    "user": "jsreport",
    "password": "password",
    "server": "janblaha-PC\\SQLEXPRESS",
    "database": "northwind"
}

function beforeRender(done) {
    sql.connect(config).then(function() {
        var req = new sql.Request();
        return req.query('select count(*) as Count, ShipCountry  from Orders group by ShipCountry').then(function(recordset) {
            request.data = { countries: recordset };
            done();
        });
    }).catch(done);
}

I can load data into pdf, html, and even html-xlsx with no error.  I tried to use just a basic sheet that I can get to load without the script, shown below. I have also tried using the data in {{#each }} statement.  I always get the same error.  Wondering if anyone has tried to do this and/or if I need to load my data a different way.
{{#xlsxAdd "xl/worksheets/sheet1.xml" "worksheet.sheetData[0].row"}}
    <row>
        <c t="inlineStr"><is><t>Hello world</t></is></c>
        <c><v>11</v></c>
    </row>
{{/xlsxAdd}}

{{{xlsxPrint}}}

A: Received an answer on Github:
//old
request.data = { countries: recordset };
//new
Object.assign(request.data, { countries: recordset })

The recipe is passing some additional data to the templating engines
  processing and you are overwriting them.


text:
Q: How to attach outer function to $routeProvider resolve? This code works fine:
$routeProvider.when('/clients',
        {
            templateUrl:'/views/clients.html',
            controller:'clientsController',
            resolve: {
                rights: function ($rootScope, apiService) {
                    var userInfo = localStorage.getItem("connectionInfo");
                    if (userInfo) {
                        userInfo = JSON.parse(userInfo);
                        var promiseObj= apiService.getUsersRights(userInfo.auth_token);
                        promiseObj.then(function(value) {
                            console.log(value);
                            $rootScope.user.rights = value.values.rights;
                            return value.values.rights;
                        });
                    } else {
                        return null;
                    }
                }
            }
        });

I want to use this function many times, but when I try this, it doesn't work. It throws Injection error.
function userRightsResolver ($rootScope, apiService) {
    var userInfo = localStorage.getItem("connectionInfo");
    if (userInfo) {
        userInfo = JSON.parse(userInfo);
        var promiseObj= apiService.getUsersRights(userInfo.auth_token);
        promiseObj.then(function(value) {
            console.log(value);
            $rootScope.user.rights = value.values.rights;
            return value.values.rights;
        });
    } else {
       return null;
    }
}

$routeProvider.when('/clients',
        {
            templateUrl:'/views/clients.html',
            controller:'clientsController',
            resolve: {
                rights: userRightsResolver($rootScope, apiService)
            }
        });

I am new to angularJS. How to make it right?

A: You might try the following approach, which I've used in my apps.
Create a routeResolve object above your routes, and give it methods representing the resolve functions you'll reuse:
var routeResolve = {
  rights: ['$rootScope', 'apiService', function($rootScope, apiService) {
    var userInfo = localStorage.getItem("connectionInfo");
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
      var promiseObj= apiService.getUsersRights(userInfo.auth_token);
      promiseObj.then(function(value) {
        console.log(value);
        $rootScope.user.rights = value.values.rights;
        return value.values.rights;
      });
    } else {
       return null;
    }
  }],
  anotherMethod: [function() {...}]
};

Then in your route, you can do:
$routeProvider
  .when('/clients', {
     templateUrl:'/views/clients.html',
     controller:'clientsController',
     resolve: {
       rights: routeResolve.rights
     }
  });


text:
Q: After upgrade to Ember v11, {{input}} value binding doesn't work I wanted to update my Ember CLI version from 0.1.15 to 0.2.3 today. Part of this, of course, came with upgrading to the new HTMLBars rendering engine. However now, I'm seeing some very odd behavior in that my {{input}} helpers are no longer binding to computed properties correctly when passing them to value. Instead, they are being evaluated as strings, even though they don't contain quotes. For example:
{{input type="text" value=deviceId}}
Literally gets displayed as a text box with a value equal to the string deviceId, not of the actual computed property. The weird thing is, when I use the deprecated valueBinding instead of value like this:
{{input type="text" valueBinding=deviceId}}
It works fine, but throws a deprecation message. I wasn't able to find anyone else experiencing a similar issue. Would anyone have ideas on what could be the issue?
Many thanks!

A: Try this:
{{input type="text" value=model.deviceId}}

I recently updated one of my projects and prefixing with the model did the trick.

A: I figured out what was going on. I was using ember-easyForm, which overwrites the input helper explicitly. EasyForm does not yet support Ember 1.11, and is known to break {{input}} across the application outside of a {{#form-for}} as described here


text:
Q: Set PropertyName using variable value I want to create a property of a class, and set the name of that property using a variable value.
E.g.
string resultValue = "stack";
MyClass myclass = new MyClass();
myclass.resultValue = "overflow";

Now here in this case, stack is the property name and "overflow" is the value of the stack property.
Please tell how is it possible.
Thanks in advance.

A: You could use Reflection. For example:
string name = "stack";
string value = "overflow";
PropertyInfo pi = typeof(MyClass).GetProperty(name);
MyClass instance = new MyClass();
pi.SetValue(instance, value, null);
// at this stage instance.stack equals to "overflow"

This obviously assumes that MyClass has a public property stack with a public setter:
public class MyClass
{
    public string stack { get; set; }
}

A: You should use Reflection for this
MyClass myclass = new MyClass();
Type type = typeof(MyClass);
PropertyInfo property = type.GetProperty("stack");
property.SetValue(myclass, "overflow", null);

A: I think that the Dynamic Source Code Generation and Compilation section on MSDN should contain the information you need.

The .NET Framework includes a mechanism called the Code Document
  Object Model (CodeDOM) that enables developers of programs that emit
  source code to generate source code in multiple programming languages
  at run time, based on a single model that represents the code to
  render.

I think that you could also get this done using Reflection.

A: I can't imagine why you want to generate property on your class, but consider other ways. E.g. using Dictionary:
class MyClass
{
    Dictionary<string, object> _values = new Dictionary<string, object>();

    public object this[string name]
    {
        get
        {
            if (!_values.ContainsKey(name))
                throw new ArgumentException(name);

            return _values[name];
        }

        set
        {
            if (!_values.ContainsKey(name))
            {
                _values.Add(name, value);
                return;
            }

            _values[name] = value;
        }
    }
}

Usage:
MyClass myClass = new MyClass();
myClass["stack"] = "overflow";
Console.WriteLine(myClass["stack"]);

A: Maybe you should take a look at DynamicObject. With this you can create properties at runtime by simply assigning a value. An example can also be found at the MSDN article.

A: Have at look at Mark Gravell's FastMember
It allows you to set properties in a dynamic manner.
// obj could be static or DLR
var wrapped = ObjectAccessor.Create(obj);
string propName = // something known only at runtime

FastMember Blog Post

A: As far as I know, is this not possible. You can try using a dictionary.


text:
Q: Installing phpunit via Ansible I'm attempting to install phpunit via ansible with a view to running it on a vagrant vm, however I keep receiving an error in the build process:

Channel "pear.phpunit.de" is not initialized, use "pear channel-discover pear.phpunit.de" to initializeor pear config-set auto_discover 1
  unknown channel "pear.phpunit.de" in "pear.phpunit.de/PHPUnit"
  invalid package name/package file "pear.phpunit.de/PHPUnit"
  install failed

The ansbile config looks something like:
- name: Install phpunit
  command: pear channel-discover pear.phpunit.de
  command: pear channel-discover pear.symfony-project.com
  command: pear channel-discover components.ez.no
  command: pear channel-discover pear.symfony.com
  command: pear update-channels
  command: pear upgrade-all
  command: pear install pear.symfony.com/Yaml
  command: pear install --alldeps pear.phpunit.de/PHPUnit
  command: pear install --force --alldeps pear.phpunit.de/PHPUnit

Has anyone managed to successfully get phpunit to install via ansible?

A: Since the pear installer for PHPUnit is no longer supported. If you want to install PHPUnit with ansible you could do:
 get_url: url=https://phar.phpunit.de/phpunit.phar dest=/usr/local/bin/phpunit mode=555

A: The playlist snippet you pasted is incorrect–it will only run the first command because you can't specify multiple commands in a single task. Try this list of tasks, instead:
 - command: pear channel-discover pear.phpunit.de
 - command: pear channel-discover pear.symfony-project.com
 - command: pear channel-discover components.ez.no
 - command: pear channel-discover pear.symfony.com
 - command: pear update-channels
 - command: pear upgrade-all
 - command: pear install pear.symfony.com/Yaml
 - command: pear install --alldeps pear.phpunit.de/PHPUnit
 - command: pear install --force --alldeps pear.phpunit.de/PHPUnit

You don't need to specify a - name for every task, but you do have to use the hyphen before each command to signal to Ansible that this is a new task.

A: More infor about no longer supported PEAR installation method:
https://github.com/sebastianbergmann/phpunit/wiki/End-of-Life-for-PEAR-Installation-Method
Russell's method works fine.


text:
Q: C# How to fit my window dimensions to my string text So i have small Form with 2 Labels: Caption and Message and Ok button:
Suppose I have a string with the text:

"Cable News Network is an American basic cable and satellite
  television news channel owned by the Turner Broadcasting System, a
  division of Time Warner. CNN was founded in 1980 by American media
  proprietor Ted Turner as a 24-hour cable news channe"

Now this string should put inside Label in order to see in in a small window just like Message Box window.
This is my `Form':
<Border Background="Red" BorderBrush="#FF103766" BorderThickness="0" CornerRadius="20,20,20,20">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition Height="110"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <Border BorderBrush="IndianRed" BorderThickness="0,0,0,1" Grid.Row="0">
            <Label Name="lblCaption"
                   FontSize="20"
                   FontWeight="Bold"
                   Foreground="Yellow"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   Margin="0,0,0,0"/>
        </Border>
        <Grid Grid.Row="1">
            <Label Name="lblMessage"
                   FontSize="15"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"/>
        </Grid>
            <Border BorderThickness="0,1,0,0" BorderBrush="IndianRed" Grid.Row="2">
            <Grid VerticalAlignment="Center">
                <Button Name="btnOk"
                        Content="OK"
                        FontSize="16"
                        VerticalAlignment="Stretch"
                        HorizontalAlignment="Stretch"
                        Click="btnOk_Click""/>
            </Grid>
        </Border>
    </Grid>
</Border>

How can i automatically fit this Grid dimensions to my Label that contains my Text ?
EDIT
I also want to break the message line to fit the with

A: Just set SizeToContent to proper value in the window that shows your user control:
<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test"
        SizeToContent="WidthAndHeight"
        mc:Ignorable="d">
    <Grid>
        <local:MyUserControl/>
    </Grid>
</Window>

In this case MyUserControl is your Form


text:
Q: invalid JWT error with timeframe using google-cloud-vision api on virtual windows I installed windows7 on the virtualbox to use google-cloud-vision api on the activeX web page on my CentOS server.
Using google-cloud-vision API for authentication, following error during authentication:
google.api_core.exceptions.ServiceUnavailable: 503 Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.')

Windows Internet Time Sync, time is synchronized, but an error occurs.
but same code on normal Windows, no error occurs.
client = vision.ImageAnnotatorClient()

imgByteArr = io.BytesIO()
textImage.save(imgByteArr, format='PNG')
content = imgByteArr.getvalue()

image = types.Image(content=content)

response = client.text_detection(image=image)
labels = response.text_annotations
print(labels[0].description)

A: Troubleshooting: Reset host os time (set NTP)
problem was the time difference between host os and guest os.
ln -sf / usr / share / zoneinfo / Asia / Seoul / etc / localtime
rdate -s time.bora.net
hwclock --systohc
date
hwclock

At time.bora.net, find and configure the appropriate ntp(network time protocol) server. Fit your area


text:
Q: I push two half spheres of enriched uranium together after which the resultant sphere has a mass above the critical value. Will it explode? Suppose I hold in both my hands a piece of enriched uranium, in the form of a half-sphere and both having equal mass as well as radius. The mass of one piece lies below the critical value. Now I push the smooth surfaces of both half spheres with all the force I possess against each other, resulting in one spherical piece (which isn't true, obviously, but I don't know how to put it in words otherwise) of enriched uranium with a mass above the critical value. Will the last thing I see be a killing flash? By which I mean an atomic bomb explosion. Of course, I'll try not doing this at home! ;)

A: It won't explode in the sense of 'be a nuclear bomb': what you are describing is reasonably close to one of the accidents that befell the 'demon core', and in particular the Slotin criticality incident (it's not actually the same: the Slotin incident was due to a reflector being allowed to fall over the core, but it's close).
What you would get would be prompt criticality followed, I assume, by either you dropping the thing or it explosively disassembling itself.  In either case you would get a really large burst of neutrons from the thing, which would kill you.  If it explosively disassembled itself then you'd presumably die in the explosion, which would be the better (quicker) outcome for you.
What it won't do is to be a nuclear weapon: in order to construct such a thing you need to assemble the thing really quickly and keep it assembled for as long as you can.  This generally involves some kind of explosive to assemble the thing and various other tricks.  The worst case is something like a 'fizzle', which would be a fairly small explosion.  Such a thing would still not be good since it would scatter bits of the device everywhere, requiring a lot of cleanup.  As far as I know the Slotin incident didn't result in any kind of explosion at all, although I think they had the presence of mind to disassemble the thing rather quickly.
As far as I am aware criticality incidents exactly as you describe haven't happened (list on Wikipedia), although almost exactly what you are describing has been shown in the 1980s BBC serial Edge of Darkness, which I think was relatively well-researched.
In any case: don't do this, obviously.


text:
Q: NSInvocation & NSError - __autoreleasing & memory crasher In learning about NSInvocations it seems like I've got a gap in my understanding about memory management.
Here is a sample project:
@interface DoNothing : NSObject
@property (nonatomic, strong) NSInvocation *invocation;
@end

@implementation DoNothing
@synthesize invocation = _invocation;

NSString *path = @"/Volumes/Macintosh HD/Users/developer/Desktop/string.txt";

- (id)init
{
    self = [super init];
    if (self) {

        SEL selector = @selector(stringWithContentsOfFile:encoding:error:);
        NSInvocation *i = [NSInvocation invocationWithMethodSignature:[NSString methodSignatureForSelector:selector]];

        Class target = [NSString class];
        [i setTarget:target];
        [i setSelector:@selector(stringWithContentsOfFile:encoding:error:)];

        [i setArgument:&path atIndex:2];

        NSStringEncoding enc = NSASCIIStringEncoding;
        [i setArgument:&enc atIndex:3];

        __autoreleasing NSError *error;
        __autoreleasing NSError **errorPointer = &error;
        [i setArgument:&errorPointer atIndex:4];

        // I understand that I need to declare an *error in order to make sure
        // that **errorPointer points to valid memory. But, I am fuzzy on the
        // __autoreleasing aspect. Using __strong doesn't prevent a crasher.

        [self setInvocation:i];
    }

    return self;
}

@end

Of course, all I'm doing here is building up an invocation object as a property for the NSString class method
+[NSString stringWithContentsOfFile:(NSString \*)path encoding:(NSStringEncoding)enc error:(NSError \**)error]

It makes sense, especially after reading this blog post, as to why I need to handle the NSError object by declaring and assigning the address to **errorPointer. What is a little difficult to grasp is the __autoreleasing and memory management what is happening here.
The **errorPointer variable isn't an object, so it does not have a retain count. It simply is memory that stores a memory address which points to an NSError object. I understand that the stringWith... method will alloc, init, and autorelease an NSError object, and set the *errorPointer = the allocated memory. As you'll see later, the NSError object becomes inaccessible. Is this...

*

*...because an autorelease pool has drained?

*...because ARC filled in the "release" call to stringWith...'s alloc + init?

So let's take a look at how the invocation "works"
int main(int argc, const char * argv[])
{
    @autoreleasepool {

        NSError *regularError = nil;
        NSString *aReturn = [NSString stringWithContentsOfFile:path
                                                      encoding:NSASCIIStringEncoding
                                                         error:&regularError];

        NSLog(@"%@", aReturn);

        DoNothing *thing = [[DoNothing alloc] init];
        NSInvocation *invocation = [thing invocation];

        [invocation invoke];

        __strong NSError **getErrorPointer;
        [invocation getArgument:&getErrorPointer atIndex:4];
        __strong NSError *getError = *getErrorPointer;  // CRASH! EXC_BAD_ACCESS

        // It doesn't really matter what kind of attribute I set on the NSError
        // variables; it crashes. This leads me to believe that the NSError
        // object that is pointed to is being deallocated (and inspecting with
        // NSZombies on, confirms this).

        NSString *bReturn;
        [invocation getReturnValue:&bReturn];
    }
    return 0;
}

This has been eye opening (a bit disconcerting) for me, as I thought I knew what the hell I was doing when it came to memory management!
The best I could do to resolve my crasher, is to pull the NSError *error variable out from the init method, and make it global. This required me to change the attribute from __autoreleasing to __strong on **errorPointer. But, clearly that fix is less than ideal, especially given that one is likely to reuse NSInvocations many times in an operation queue. It also only kinda confirms my suspicion that *error is being dealloc'd.
As a final WTF, I tried played around a bit with the __bridge casts, but 1. I'm not sure if that's what I need here and 2. after permuting I couldn't find one that worked.
I'd love some insight that might help me better understand why this all isn't clicking.

A: This is actually a very simple error that has nothing to do with Automatic Reference Counting.
In -[DoNothing init], you're initializing the error parameter of the invocation with a pointer to a stack variable:
__autoreleasing NSError *error;
__autoreleasing NSError **errorPointer = &error;
[i setArgument:&errorPointer atIndex:4];

And in main, you're grabbing that same pointer and dereferencing it:
__strong NSError **getErrorPointer;
[invocation getArgument:&getErrorPointer atIndex:4];
__strong NSError *getError = *getErrorPointer;

But of course by this point all the local variables that live in -[DoNothing init] no longer exist, and attempting to read from one produces a crash.


text:
Q: MySQL | Sum Column If Different ID I'm trying to Sum column only if id is different.
I tried like this, but it is not working:
SUM(CASE WHEN
             DISTINCT empLeaves.ApprovedLeaveID
         THEN empLeaves.TotalLeavesTaken END) AS Total

What Would be the proper way to SUM it?
Here is the total query, I am working on:
SELECT
      E.employee_id AS EmployeeID,
      E.employee_code AS EmployeeCode,
      E.full_name AS EmployeeName,
      empLeaves.LeavesFromDate,
      empLeaves.LeavesToDate,
      -- COUNT(empLeaves.ApprovedLeaveID) AS TotalApprovedApplications,
      ATT.`in_date` AS InDate,
      ATT.`out_date` AS OutDate,
      SUM(CASE WHEN DISTINCT empLeaves.ApprovedLeaveID THEN empLeaves.TotalLeavesTaken END) AS Total
FROM employee E
LEFT JOIN `attendence` ATT ON ATT.`employee_id` = E.`employee_id`
LEFT JOIN (
           SELECT
                 LA.`leave_approval_id` AS ApprovedLeaveID,
                 E.`employee_id` AS EmployeeID,
                 LA.`approved_from` AS LeavesFromDate,
                 LA.`approved_to` AS LeavesToDate,
                 DATEDIFF(LA.approved_to,approved_from) AS TotalLeavesTaken
            FROM leave_application APP
            INNER JOIN leave_approval LA
                 ON LA.`leave_application_id` = APP.`application_id` AND LA.`trashed` = 0 AND LA.`status` = 2
            INNER JOIN employee E
                 ON E.`employee_id` = APP.`employee_id` AND E.`trashed` = 0 AND E.`enrolled` = 1
            INNER JOIN ml_leave_type MLLT
                 ON MLLT.`ml_leave_type_id` = APP.`ml_leave_type_id` AND MLLT.`trashed` = 0
) empLeaves ON E.`employee_id` = empLeaves.EmployeeID
WHERE
     E.`enrolled` = 1 AND E.`trashed` = 0
GROUP BY
     E.`employee_id`,empLeaves.EmployeeID

A: When which ID is different from what?
In general, when you have a value in a field and you want to add them together except for those in a particular set of rows, you simply set the unwanted values to 0:
sum( case otherfield when somevalue then row.field else 0 end ) as SumOfValues

So when otherfield shows that this is the row you want included in the total, you expose the field you want to add (row.field in this example). Otherwise, you expose a zero. Of course, if the value you're testing is to find the rows you don't want in the total, just put the zero after the then and the field after the else.


text:
Q: Invalid argument supplied for foreach() in View. Laravel I want to make searching on table users but have got error in view on http://127.0.0.1:8000/:

Invalid argument supplied for foreach() (View:
/opt/lampp/htdocs/abonamenty/resources/views/users/index.blade.php)

And on the localhost error 404 after click search button.

"Object not found! The requested URL was not found on this server. The
link on the referring page appears to be incorrect or outdated. Tell
the author of this page about the problem. If you think this is a
server error, contact your administrator."

This is part of my controller
public function index(Request $request)
{
    $data = User::sortable()->paginate(5);
    return view('users.index', compact('data'))->with('i', ($request->input('page', 1) - 1) * 5);
}

public function search(Request $request)
{
    $search = $request->get('search');
    $data = DB::table('users')->where('surname', "%$search%")->paginate(5);
    return view('users.index', ['users' => $data]);
}

My routes:
Route::get('/home', 'HomeController@index')->name('home');

Route::group(['middleware' => ['auth']], function () {
    Route::resource('roles', 'RoleController');
    Route::resource('users', 'UserController');
    Route::resource('permissions', 'PermissionController');
    Route::resource('products', 'ProductController');
    Route::get('/search', 'UserController@search');
    Route::get('data', 'UserController@index');
    Route::get('posts', 'PostController@index');
});

My view:
@extends('layouts.app')

@section('content')

Zarządzanie kontami użytkowników

                <form action="/search" method="get">

                        <input type="search" name="search" class="form-control">

                            <button type="submit" class="btn btn-primary">Wyszukaj</button>

                </form>

                 Utwórz nowego użytkownika

    @if ($message = Session::get('success'))

{{ $message }}

    @endif

            @sortablelink('id', 'Numer')
            @sortablelink('name', 'Imię')
            @sortablelink('surname', 'Nazwisko')
            @sortablelink('showname', 'Nazwa wyświetlania')
            @sortablelink('email', 'Email')
            Rola
            Akcja

        @foreach ($data ?? '' as $key => $user)

                {{ ++$i ?? '' ?? '' }}
                {{ $user->name }}
                {{ $user->surname }}
                {{ $user->showname }}
                {{ $user->email }}

                    @if(!empty($user->getRoleNames()))
                        @foreach($user->getRoleNames() as $v)
                            {{ $v }}
                        @endforeach
                    @endif

                    id) }}">Wiecej informacji
                    id) }}">Edytuj użytkownika
                    {!! Form::open(['method' => 'DELETE','route' => ['users.destroy', $user->id],'style'=>'display:inline']) !!}
                    {!! Form::submit('Usuń', ['class' => 'btn btn-danger']) !!}
                    {!! Form::close() !!}

        @endforeach

    {!! $data ?? ''->appends(request()->except('page'))->render() !!}

ARTplus 2020

@endsection

A: I think you need to change the search method
use Illuminate\Support\Facades\Input;

public function search()
{
    $search =Input::get('search');
    $data = DB::table('users')->where('surname', "%$search%")->paginate(5);
    // Also we can check using print_r($data); die();
    return view('users.index', ['users' => $data]);
}


text:
Q: Ionic ion-datetime element validation and property change I want to add some validation to Ionic ion-datetime element, I have this code.
<ion-item>
        <ion-label>Birth of Date</ion-label>
        <ion-datetime displayFormat="MM/YYYY" pickerFormat="MMMM YYYY" min="1940" max="{{lastYear | date:'yyyy'}}">
        </ion-datetime>
    </ion-item>

And i want set this field inside a form has to be required field. And i want this max year should be 16 years lower than current year (-16)
I have been trying this so far but it is not worked
lastYear = null;
this.lastYear = new Date('yyyy');

i tried to deduct -16 from this but give me error like

Cannot read property 'year' of null

Some one can give me proper way to do this 2 validation.
Thank you

A: *

*i want set this field inside a form has to be required field.

Add a formgroup to that component and in that formgroup declare the form control name for date and time and declare that as a required one like the below example
public holidayForm: FormGroup;

constructor public fb: FormBuilder){

this.holidayForm = fb.group({
  'holiday_date': [null, Validators.compose([Validators.required])],
});
}

when u submit the form check weather the form is valid or not if it is valid then submit if not then show required message in your app.
2.i want this max year should be 16 years lower than current year (-16)
 this.currentTime = new Date();
 this.year = this.currentTime.getFullYear();
 this.year = this.year - 16;

try using this hope this will be helpful for you


text:
Q: Applying arithmetic operators to lists of values Let's say I have list(s) of values and I want to apply an arithmetic operator to each value. For a binary operator like addition, this would mean something like this:
add_lists([],[],[]).
add_lists([A|TA],[B|TB],[R|TR]) :- R is A+B,
                                   add_lists(TA,TB,TR).

Now I wanted to write something like:
?- arithop_lists(+,[1,2,3],[0.2,-2,100],R).

This works:
arithop_lists(_Op,[],[],[]).
arithop_lists(Op,[A|TA],[B|TB],[R|TR]) :- E =.. [A,Op,B], R is E,
                                          arithop_lists(Op,TA,TB,TR).

But I am extremely frustrated that I couldn't find an easier way to do this. I couldn't come up with a findall solution that doesn't use member. What is more, I couldn't figure out how to do it without a =.. call for every pair of operands.
My initial feeling was that it can be done with maplist, and I know it can be done, but I don't know if using maplist and lambda is any less of a hack.

A: I think the better way, efficiency wise, should be
add(A, B, C) :- C is A + B.
mul(A, B, C) :- C is A * B.

yields
?- X = add, maplist(X, [1,2,3], [0.2,-2,100], R).
X = add,
R = [1.2, 0, 103].

?- X = mul, maplist(X, [1,2,3], [0.2,-2,100], R).
X = mul,
R = [0.2, -4, 300].

edit library(apply_macros) could be the blueprint for efficient evaluation (via rewriting). A library of numerical algorithms could use it to get the maximal efficiency. Of course, such optimizations should be postponed after correctness.


text:
Q: How to Dynamically create table from JSON data using Hibernate I am creating a application in which I am receiving the data in JSON format from Jersey RESTServices.I need to dynamically generate the table using the JSON  data and also want to store the values in this table. Let us suppose that I get the data as:
     { "fieldLists":
                     {"fields":[

                                {"name":"field_a","type":"any Java Type"},

                                {"name":"field_b","type":"any Java Type"}
                               ]
                     }
      }

Now I need to create table using this data.I am stuck how to create class and its mapping at run time?
Please suggest which approach will be better?

A: An ORM framework is really not an ideal choice for your requirement primarily because they were never designed to support dynamic domain models.  While you may use the native sql features of your ORM framework of choice, it's effectively just a wrapper around JDBC.
Using JDBC, you would simply construct the CREATE TABLE DDL statements based on the JSON provided data when a table should be created and then construct the appropriate statements when you need to add, alter, or remove rows.

A: First you need to create class.
Save it to some location. Compile it and load to memory.
Add class to hibernate config.
programmatically-compile-and-instantiate-a-java-class
create database in Hibernate at runtime


text:
Q: jQuery Event Bubbling on wrong object I'm still a little new to jQuery events.
I'm trying to write jQuery a wrapper/framework of the Asp.NET UpdatePanel that automatically tracks UpdatePanel async updates.
I want to be able to do something like
$("#myUpdatePanel").on("update", myFunc);

and have it run some handler with this as the updated UpdatePanel.  I actually have this bit working.
I also want to be able run a function exactly once any time one or many UpdatePanels update.
$.updatePanel.on("update", myRunOnceFunc);

This is where I'm having issues.
I've defined my wrapper:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
    var prm;

    var UpdatePanel = function () { };
    UpdatePanel.prototype = { };

    // initialize on $(document).ready()
    $(function () {
        prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm) {
            prm.add_pageLoaded(function (s, e) {
                $.each(e.get_panelsUpdated(), function () {
                    // call panel-specific update event handlers
                    $(this).trigger($.Event("update"));
                });

                // triggered once no matter how many panels were updated
                $(UpdatePanel).trigger($.Event("update"));
            });
        }
    });

    return $(UpdatePanel);
})();

Then in my code that uses $.updatePanel:
$(function() { $.updatePanel.on("update", myRunOnceFunc); });

What I'm finding is that myRunOnceFunc is being run during both $(this).trigger($.Event("update")); and $(UpdatePanel).trigger($.Event("update"));.
Any ideas why and how to fix it?

A: I figured out what was wrong.
Rather than return $(UpdatePanel);, I needed to call return $(new UpdatePanel());.  Then I needed to replace $(UpdatePanel).trigger(...) with $.updatePanel.trigger(...).  Code below:
// wrap updatePanel reload functionality
$.updatePanel = (function () {
    var prm;

    var UpdatePanel = function () { }
    UpdatePanel.prototype = { };

    $(function () {
        prm = Sys.WebForms.PageRequestManager.getInstance();
        if (prm) {
            prm.add_pageLoaded(function (s, e) {
                $.each(e.get_panelsUpdated(), function () {
                    $(this).trigger($.Event("update"));
                });

                // triggered once no matter how many panels were updated
                $.updatePanel.trigger($.Event("update"));
            });
        }
    });

    return $(new UpdatePanel());
})();


text:
Q: Stuck using Microsoft.Web.WebPages.OAuth.OAuthWebSecurity in an MVC application I don't understand some code in the Microsoft.Web.WebPages.OAuth namespace, specifically the OAuthWebSecurity class.
It's this method here:
internal static void RequestAuthenticationCore(HttpContextBase context,
    string provider, string returnUrl)
{
    IAuthenticationClient client = GetOAuthClient(provider);
    var securityManager = new OpenAuthSecurityManager(context,
        client, OAuthDataProvider);
    securityManager.RequestAuthentication(returnUrl);
}

The first line is fine => grab the provider data, for this authentication request. Let's pretend this is a TwitterClient(..).
Now, we need to create a SecurityManager class .. which accepts three args. What is that 3rd arg? An OAuthDataProvider? That's defined as a static, here:
internal static IOpenAuthDataProvider OAuthDataProvider =
    new WebPagesOAuthDataProvider();

And this creates a WebPagesOAuthDataProvider. This is my problem. What is this? And why does it have to be tightly coupled to an ExtendedMembershipProvider? What is an ExtendedMembershipProvider? Why is this needed?
In my web application I'm trying to use a RavenDb database and my own custom principal and custom identity. Nothing to do with Membership or SimpleMembership that comes with ASP.NET.
What is that class and why is it used, etc? What's it's purpose? Is this something that DNOA requires? and why?

A: I didn't write the code you mention, so I could be wrong here, but I believe the ASP.NET code you refer to is indeed bound to their Membership provider.
If you aren't using the ASP.NET membership provider, I would suggest you simply use DotNetOpenAuth directly (as opposed to through the facade that Microsoft added), which has no such tight coupling.

A: If you don't need the ASP.NET Membership system to provide local login accounts (accounts stored in your local membership database) on your system I wouldn't go down the Route of using any WebMatrix based bits (WebSecurity / OAuthWebSecurity).
They actually make it harder to interact with DNOA and more or less hide all the interesting bits at the same time anyway ...
As I needed local acounts I ended up pulling all the source code for this into my source code and then editing it from there (I had other reasons for doing this as well, not just to enrich the interaction with DNOA).
If you need local accounts - use WebMatrix
If you don't need local accounts - use DNOA directly.


text:
Q: gcloud cli command shows error INVALID_ARGUMENT when listing assets for project ID for some accounts gcloud cli throws an error INVALID_ARGUMENT ehen I try to run this command for some accounts.
gcloud scc assets list projects/project-id

Ths is the exact error that I get,
ERROR: (gcloud.scc.assets.list) INVALID_ARGUMENT: Request contains an invalid argument.

There is no specific way to troubleshoot what exactly is the issue in any documnetations..

A: What SDK version are you on? I just tested the same gcloud command as you mentioned and had no issues.
gcloud version:
Google Cloud SDK 349.0.0
alpha 2021.07.19
beta 2021.07.19
bq 2.0.70
core 2021.07.19
gsutil 4.65

Command:
gcloud scc assets list projects/my-project-id

A: It looks like you are using Security Command Center Legacy, which is disabled according to the official documentation.

Security Command Center Legacy, previously known as Cloud Security Command Center, and Event Threat Detection Legacy have been permanently disabled. For information on upgrading to Security Command Center Standard or Premium, see Migrate from legacy Security Command Center products. To inquire about flexible pricing options for the Premium tier, complete our inquiry form. You should receive a response within two US business days.

I suggest you to migrate your account to Security Command Center Standard or Premium.