text:
Q: C#: Wrong answer when finding "cool" numbers In my application, a "cool" number is a number that is both a square and a cube, like for example: 64 = 8^2 and 64 = 4^3. My application is supposed to find the number of "cool numbers" between a range given by the user. I wrote my code and the application runs fine, but it is giving me the wrong answer. Can you help me here please? for example:
INPUT
1
100
OUTPUT
1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            double a = Convert.ToDouble(Console.ReadLine()); // first number in the range
            double b = Convert.ToDouble(Console.ReadLine()); // second number in the range
            long x = 0;
            for (double i = a; i <= b; i++)
            {

                   double cube = 1.0 / 3.0;
                   double cuad = 1.0 / 2.0;
                   double crt = Math.Pow(i, cube); // cube root
                   double sqrt = Math.Pow(i, cuad); // square root

                if ((crt * 10) % 10 == 0 || (sqrt * 10) % 10 == 0) // condition to determine if it is a cool number.
                    x++;

            }
            Console.WriteLine(x);
            Console.ReadLine();
        }
    }
}

A: doubles are messy in most languages. They often get stored imprecisely, giving you the wrong answer sometimes. You don't want to use them when you don't have to.
Here's how I would do it. Take two ints from the user. Loop through the integers in the range of those two ints (like you're doing with your floats.) For each one, find the cube root and square root and store them in doubles. Then round the cube root and square roots to the nearest integer (using a library function) and store them as ints. Finally, to see if the current number is a square or cube, multiply the square root int by itself and the cube root int by itself by itself, and see if those two products equal the original number. If they do, you have a cool number.
This way, the rounding function is sure to sift out any precision errors in your doubles, and then all your numbers are nice and sound.
Some code:
int a = int_from_user();
int b = int_from_user();

for (i = a; i <= b; i++) {
  int sqrt = round(sqrt(i));
  int cbrt = round(cbrt(i));

  if (sqrt * sqrt == i && cbrt * cbrt * cbrt == i) {
    cool++;
  }
}

A: "Cool numbers" is a rather roundabout way of describing sixth powers. Clearly every sixth power is a cool number;  x^6 is (x^2)^3 and (x^3)^2. And every number that is not a sixth power is not a cool number. (Proof is left as an exercise. Hint: consider the necessary properties of any prime factorization of a cool number.)
Therefore I would simply write a device which enumerates the sixth powers that are in a range.

A: The || operator is meant to evaluate to true if one of the parts is true, so your condition will evaluate to true whether is exact cube OR exact square
     if ((crt * 10) % 10 == 0 && (sqrt * 10) % 10 == 0)
This is another option, a bit slow but you can test it:
if (((crt == Math.Floor(crt)) && (sqrt == Math.Floor(sqrt))) x++;


text:
Q: Instantiation of generic type to support custom objects While constructing a random graph I am trying to support 2 different edge types

*

*TimestampEdge

*DiffusionEdge
Each of which extend the generic Edge class
public class TimeStampEdge extends Edge<DiffusionVertex,Integer> {

//timestamp edge specific methods

}

public class DiffusionEdge extends Edge<DiffusionVertex,Integer> {

    public DiffusionEdge(String name, DiffusionVertex v, DiffusionVertex v1) {
        super(name, v, v1);
    }
}

V is a self referential variable so that a vertex can maintain a list of its neighbours, and K just some value for an edge to have
public class Edge<V extends Vertex<?,V>,K> implements Edges<V,K> {
    //Generic edge methods and values
}

What I want to do is be able to create a graph of both edge types from the same graph model, here's an example for random K-Trees. Where E should be either TimeStampEdge or a DiffusionEdge, diffusion vertex is the vertices used for all graph models, and GraphClass is the abstract class all graph models inherit from.
public class KTree<E extends Edge<DiffusionVertex, Integer>> extends GraphClass<DiffusionVertex,E>
//ktree methods

   public boolean addEdge(DiffusionVertex v, DiffusionVertex v1){
        if(this.findEdgeSet(v,v1).isEmpty()){

            v.setDegree(v.getDegree()+1);
            v1.setDegree(v1.getDegree()+1);

            E edge = (E) new Edge(v.getLabel() +"-"+v1.getLabel() ,v,v1);

            this.Edges.put(edge.getHashCode(), edge);

            return true;

        }else{

            return false;

        }
    }

//more ktree methods
}

I keep running into the java.lang.ClassCastException where class Edge cannot be cast to TimeStampEdge or DiffusionEdge, I believe the problem comes from my instantiation of edges in the shown addEdge method always being of the Edge class. However I'm not sure how to make it where i create edges of type E. Any help on how to go about doing this would be much appreciated!

A: calling new Edge(...) will not create any subclass of Edge represented as E unless E really does represent Edge. Java does not change the actual type of an object when you cast it from one type to another, let alone when you cast it to a generic type. For a cast to a specific type to work, the object itself must already be that type.
if you want to create a new E, maybe you can pass it a Supplier<E> or use a factory pattern to create a new E properly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get bibtex working I am new with LaTeX and MiKTeX, so the answer may be very simple.
Tried several things, copy pasted some examples, but can't get it.
.Tex file
\documentclass[]{report}
\usepackage{times}
\usepackage[english]{babel}
\usepackage[ibidem]{jurabib}
\usepackage{cite}
\usepackage{comment}

\begin{document}

%First some renames
\renewcommand{\chaptername}{Hoofdstuk}
\renewcommand\bibname{Referenties}
\renewcommand\contentsname{Inhoudsopgave}

\excludecomment{comment} %change exclude to include for showing in pdf too

% Article top matter
\title{Profielwerkstuk}
\author{Remco\\
        Hi}
\date{\today}  %\today is replaced with the current date
\maketitle

\tableofcontents

\chapter{Test}
\section{Introduction}
Some text

\begin{comment}
Text
\end{comment}

%Text

\section {Mathematical Equations}

\chapter{}
\section{Introduction}
This small document is designed to illustrate how easy it is to create a
well structured document within \cite{north}

%Create the environment for the bibliography.  Since there is only one
%reference, set the label width to be one character (I shall follow
%convention as use the number '9'.  This is because it helps to remind
%that it is the maximum number of refs that is now permitted by that
%width).

\end{document}  %End of document.

BibTex file(saved in the same map with same name as .tex)
@string{jpe = "Journal of Political Economy"}
@BOOK{north, % 'north' is de door jou gekozen 'key'
author = {Douglass C. North},
year = 1990,
title = {Institutions, Institutional Change and Economic Performance},
publisher = {Cambridge: Cambridge University Press}
}
@ARTICLE{becker,
author = {Gary S. Becker},
month = feb,
year = 1962,
title = {Irrational Behavior and Economic Theory},
journal = jpe,
volume = 70,
number = 1,
pages = {1--13}
}

A: The jurabib package is rather specialised: it is not designed to work with general bibliography styles. Thus you need to use a style which it comes with (\bibliographystyle{<name>}). The package comes with

*

*jurabib

*jureco

*jurunsrt

*jox


text:
Q: Replacing placeholders in prepared statement OleDbCommand.Parameters I'm trying to perform a simple query on my MS Access DB from a Console Application through prepared statements.
The query tries to look for the desired value either in the "targa" field or in the "auto" field, to simplify the user interface with only one research label.
//grab field from GUI
string ricerca = Ricerca.Text;
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE '%?%'";
command = new OleDbCommand(queryTarga, con);

command.Parameters.Add("@p1", OleDbType.VarChar,ricerca.Length,"targa").Value = ricerca;
command.Parameters.Add("@p2", OleDbType.VarChar, ricerca.Length,"auto").Value = ricerca;

If I insert a known value for the first field "targa", the lookup works out with no issues.
If I insert anything for "auto", the lookup never returns any value!
The problem is that '%?%' gets interpreted in a weird way due to the single quotes and it's not recognising and setting the parameter correctly. By hardcoding the "ricerca" variable in the query string (without using '?') it works just fine:
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE '%" + ricerca + "%'";

Does anyone have a clue of how to set the parameter?

A: try this:
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE @p1";

command = new OleDbCommand(queryTarga, con);
 command.Parameters.AddWithValue("@p1", "%" + Ricerca.Text + "%");


text:
Q: Get data each day if no record display zero Hi i'm trying to create query that will give me the employee double break count each day.
I need to display each day but what i able to display now is the only days that has value.
SELECT   shift, count (COUNT) AS COUNT, TRUNC (date_time) AS date_time
          FROM vw_break_time_doublebreak
         WHERE TRUNC (date_time) IN (
                  SELECT       TRUNC (TO_DATE ('2020-01-01', 'YYYY-MM-DD'),
                                      'MM'
                                     )
                             + LEVEL
                             - 1 AS dateshift
                        FROM DUAL
                  CONNECT BY LEVEL <= 31)

      GROUP BY shift, TRUNC (date_time)
      ORDER BY shift, date_time ASC;

result im getting
SHIFT   COUNT   DATE_TIME

R   11  1/1/2020
R   29  1/2/2020
R   22  1/3/2020
R   3   1/4/2020
R   32  1/6/2020
R   39  1/7/2020
R   41  1/8/2020
R   39  1/9/2020
R   44  1/10/2020
R   9   1/11/2020
R   1   1/12/2020
R   20  1/13/2020
R   29  1/14/2020
R   31  1/15/2020
R   28  1/16/2020
R   34  1/17/2020
R   7   1/18/2020
R   2   1/19/2020
R   33  1/20/2020
R   32  1/21/2020
R   26  1/22/2020
R   37  1/23/2020
R   32  1/24/2020
R   7   1/25/2020
R   41  1/27/2020
R   41  1/28/2020
R   28  1/29/2020
R   41  1/30/2020
R   30  1/31/2020

see result above there's no row for january 5 and january 26.
On the source view there's really no data on that date.
expected result
SHIFT   COUNT   DATE_TIME

    R   11  1/1/2020
    R   29  1/2/2020
    R   22  1/3/2020
    R   3   1/4/2020
    R   0   1/5/2020 <=
    R   32  1/6/2020
    R   39  1/7/2020
    R   41  1/8/2020
    R   39  1/9/2020
    R   44  1/10/2020
    R   9   1/11/2020
    R   1   1/12/2020
    R   20  1/13/2020
    R   29  1/14/2020
    R   31  1/15/2020
    R   28  1/16/2020
    R   34  1/17/2020
    R   7   1/18/2020
    R   2   1/19/2020
    R   33  1/20/2020
    R   32  1/21/2020
    R   26  1/22/2020
    R   37  1/23/2020
    R   32  1/24/2020
    R   7   1/25/2020
    R   0   1/26/2020 <=
    R   41  1/27/2020
    R   41  1/28/2020
    R   28  1/29/2020
    R   41  1/30/2020
    R   30  1/31/2020

Note there is also other shift i only show the data on R shift
data result will be use in graph using chart js
Hope someone help me out with this thank you.


text:
Q: Como saber a quantidade de memória utilizada pela minha aplicação em PHP? Gostaria de saber se existe alguma maneira de saber o quanto a minha aplicação PHP está consumindo de memória.
Por exemplo: Quero saber, no final da execução do script, quanto o PHP gastou no processo de execução de uma determinado script.
Existe alguma função em PHP que eu possa fazer essa verificação?

A: Como já foi citado, memory_get_usage captura o gasto de memória no momento. No entanto, existe outra função, o memory_get_peak_usage, que pega o pico de memória máximo registrado.

Nota: tanto memory_get_usage quanto memory_get_peak_usage só obtém o resultado definido pelo emalloc() é retornado.

Então as diferenças são:

*

*memory_get_usage retorna o gasto de memoria atual aproximado, por exemplo:
<?php

echo round(memory_get_usage() / 1024, 4), 'Kb', PHP_EOL; // 219.2656Kb

$a = str_repeat("Hello", 4242);

echo round(memory_get_usage() / 1024, 4), 'Kb', PHP_EOL; // 240.1797Kb

unset($a);

echo round(memory_get_usage() / 1024, 4), 'Kb', PHP_EOL; // 219.3125Kb

Os valores variam conforme o sistema e versão usada do PHP, também varia se estiver usando extensões como Opcache ou XCache

*memory_get_peak_usage retorna o pico de memória gasto até o momento, então
<?php

echo round(memory_get_peak_usage() / 1024, 4), 'Kb', PHP_EOL; // 222.8906Kb

$a = str_repeat("Hello", 4242);

echo round(memory_get_peak_usage() / 1024, 4), 'Kb', PHP_EOL; // 241.7422Kb

unset($a);

echo round(memory_get_peak_usage() / 1024, 4), 'Kb', PHP_EOL; // 241.8047Kb

Veja que os números permanecem e sempre aumentam.
Testando no final do script
Existe uma função chamada register_shutdown_function que é executado ao final do script, seria como um "__destruct global", neste momento é interessante fazer a checagem do pico de memória, assim:
<?php

register_shutdown_function(function() {
    echo PHP_EOL, round(memory_get_peak_usage() / 1024, 4), 'Kb';
});

$a = str_repeat("Hello", 4242);

unset($a);

Assim sempre que o script maior for terminado (os que são incluídos não disparam esta função a não ser que exista um exit; ou die('foo');) e irá adicionar ao fim do output/saída/corpo do documento o resultado de quanto foi gasto.

Nota: register_shutdown_function pode ser adicionado a qualquer momento antes do shutdown

Aqui sobre extensões

*

*https://pt.stackoverflow.com/a/152472/3635

*https://pt.stackoverflow.com/a/166747/3635

A: A função memory_get_usage retorna o número de bytes alocados para o script.
Um exemplo retirado da documentação do PHP:
// É apenas um exemplo os números serão diferentes dependendo do sistema
echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo memory_get_usage() . "\n"; // 57960

unset($a);

echo memory_get_usage() . "\n"; // 36744

A: memory_get_usage:
memory_get_usage() retorna a quantidade de memória em bytes que está a ser usada pelo teu script php.
DEMONSTRAÇÃO:
echo memory_get_usage(); // 112388 (bytes)

Caso coloques o argumento como true (memory_get_usage(true)), é te retornado o total de memória reservada no sistema para o teu script php:
DEMONSTRAÇÃO, com entrada de argumento como true:
echo memory_get_usage(true); // 262144 (bytes)

Ou seja se quiseres a memória real que o sistema está a usar deves fazer como na ultima demonstração em cima, memory_get_usage(true)
E se quiseres saber a memoria real que o teu script consumiu (dentro da memória reservada, obviamente) usa o primeiro exemplo.


text:
Q: What happened to the Belt of Beloth the Wise? During the siege of Dras-Leona, Eragon loses the belt after the confrontation with the priests of Helgrind. He fails at finding the belt at that time and he still couldn't find the belt when he went to check for it later.
Any idea what happened to it? Was the wards around it so powerful, nobody could ever find if it was lost? Or did someone destroy the belt?

A: We don't know, but it'll probably be in book five (or a different book)

So it's safe to say that any "loose ends" we may come across are intended for future tales? Such as, perhaps, the belt of Beloth the Wise?
Christopher Paolini: Possibly. The problem is, there are always loose ends. If I write another story, it'll probably raise as many questions as it answers. Still, yes, the belt of Beloth the Wise will pop up again somewhere else. Personally, my favorite theory is that Angela swiped it in Dras-Leona. But then again, I can't imagine she would have done anything to harm Eragon's chances of killing Galbatorix.
Shurtagal.com's first post-Inheritance interview with Christopher Paolini, December 2011
So what became of the belt of Beloth the Wise?
Christopher Paolini: Heh. Book V.
Twitter AMA October 2012
Where did the belt of Beloth the Wise go?
Christopher Paolini: Great question. No comment.
Is it potentially important? 'Pay attention to it, readers,' type thing?
Christopher Paolini: Well it's not unimportant. I mean, a big magical artifact suddenly disappearing for a while, that's cause for concern, yes.
Well you say "for a while," so it might reappear at some point.
Christopher Paolini: That's right, it might.
Shurtagal.com's second post-Inheritance interview with Christopher Paolini, January 2013
What happen with the belt of Beloth the Wise?
Christopher Paolini: Good question.
Twitter June 2015
Since Bregan could see Murtagh's eldunari and the belt of Beloth the wise…could he possibly find the belt?
Christopher Paolini: Yup.
Twitter December 2015
Eragon used the Name of Names trying to find [the belt], if I recall correctly, so do we assume that it's been destroyed?
Christopher Paolini: Never assume anything.
Facebook AMA February 2017

A: Angela could have taken it. She has lived for so long and knows so much, maybe she knew a way to hide it where magic, even the name of names, could not find it. If you say that angela would not harm his chances against Galbatorix by taking it, remember, she is wierd. Bregan could have taken it because he can see energy. Spirits could have taken it to another dimention where they live, because even the name of names can't find it, and because spirits eat energy.


text:
Q: Regex how to match a substring that does not contain a fixed string. Regex in TexStudio: I want to a regex expression to replace the following string
{match1}{matchb}{not}{anotb}

with
match1matchb{not}{anotb}}

How to write the regex expression.
Basically I want to find a string inside {} but the string can not contain not.

A: Search for the regex \{(?![^}]*not)([^}]+)\}
And replace with $1 or \1 based on your regex engine(or the function).
In the regex (?![^}]*not) is a negative lookahead that is checking that there is no not inside the {}.
Try it at regex101.

A: You can match this:
\{([^}]*)\}\{([^}]*)\}\{not\}
and replace with:
\1\2{not}
Demo: http://regex101.com/r/uA8rU9


text:
Q: How can I get Control Panel's Add/Remove programs list? Ho can I obtain/export the Windows Control Panel Add/Remove programs list using WMI or VB script?

A: wmic product on the local machine. You can also use wmic /NODE:computername get product on remote machines. It will take a while.


text:
Q: Angular 9 Mat table edit select cell and bind data I'm figuring out a way to edit a table using mat table. I needed to only edit one cell which is a dropdown. I use this link to modify my table but I seem to can't resolve my issue. I'm a bit new to angular 9 and help is much appreciated:
The error: Property 'map' does not exist on type 'MatTableDataSource'.
Here's my html code sample:
<ng-container matColumnDef="bidderstatus">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Status </th>
        <!--<td mat-cell *matCellDef="let element"> {{element.bidderStatus}} </td>-->
        <td mat-cell *matCellDef="let element;">
          <mat-select formControlName="BidderStatus">
            <mat-option [value]="bid.value" *ngFor="let bid of bidderStatus">
              {{ bid.value }}
            </mat-option>
          </mat-select>
        </td>
      </ng-container>

The component.ts as follows
export class BiddersComponent implements OnInit {

  displayedColumns: string[] = ['bidderId', 'title', 'firstName', 'surname', 'email','bidderstatus', 'action'];
  bidders: IBidder[];
  dataSource: MatTableDataSource<IBidder>;
  loading: boolean;
  bidder: FormGroup;
  bidderStatus: BidderStatus[] = [
    { value: "Registered/ not confirmed", description: "Registered/ not confirmed" },
    { value: "Confirmed / can't bid", description: "Confirmed / can't bid" },
    { value: "Can bid", description: "Can bid" },
    { value: "Deactivated / can access but can't bid", description: "Deactivated / can access but can't bid" },
    { value: "Suspended / can't even see", description: "Suspended / can't even see" }
  ]

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  constructor(private bidderService: UserService, private router: Router, private fb: FormBuilder) { }

  ngOnInit() {

    this.LoadBidders();
    this.bidder = this.fb.group({
      BidderStatus:['']
    });
    this.createFormArray();
  }
  LoadBidders() {
    this.LoaderShow();
    this.bidderService.GetBidders(1).subscribe(result => {
      this.bidders = result;
      this.dataSource = new MatTableDataSource(this.bidders);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      this.LoaderHide();
    }, error => { console.error(error); this.LoaderHide(); });
  }

  createFormArray(): FormArray {
    return new FormArray(this.dataSource.map(item => new FormGroup({
      BidderStatus: new FormControl(item.BidderStatus) //This is where the error shows on map
    })));
  }
}

interface BidderStatus {
  value: string;
  description: string;
}

I also tried with forEach() function but same error occurs -> Property 'forEach' does not exist on type 'MatTableDataSource'. So how do I resolve this. And how do I properly bind data here and save. Help is really appreciated.

A: MatTableDataSource is not an array. The data used in your MatTable is stored in the property data of the MatTableDataSource.
If you want to iterate over the displayed data, try: this.dataSource.data.map()


text:
Q: jQuery Autocomplete, different source depending on what character was entered I have textbox to which I added autocomplete. But this is the issue, I want to be able to use a different value from the object depending if parenthesis is entered or not.The issue is that I need to create something like State(County). I pick the State (this part works OK), but then I need to pick the County after a ( is entered, it doesn't do anything, no error or nothing.

This is my code:
  $(function() {
     $("document").ready(function() {

    var states = [
        { 'state': "New York", 'county': '1' },
        { 'state': "New York", 'county': '1a' },
        { 'state': "New York", 'county': '1b' },
        { 'state': "Florida", 'county': '2' },
        { 'state': "Florida", 'county': '2a' },
        { 'state': "Florida", 'county': '2b' },
        { 'state': "Florida", 'county': '3' },
        { 'state': "Alaska", 'county': '4' },
        { 'state': "Alaska", 'county': '5' },
        { 'state': "Hawaii", 'county': '6' },
        { 'state': "Hawaii", 'county': '7' },
        { 'state': "Maine", 'county': '8' },
        { 'state': "Maine", 'county': '9' },
        { 'state': "Maine", 'county': '10' }
    ];
function split(val) {
  return val.split(/,\s*/);
}

function extractLast(term) {
  return split(term).pop();
}

$('#text').on('keypress', function(e) {
  theKeyCode = e.which;

  // if (e.which !== 40) { // I tried this too ------------
  if (String.fromCharCode(e.which) !== '(') { // Just trying something different

    $(e.target)
      .autocomplete({
        minLength: 0,
        autoFocus: true,
        source: function(request, response) {
          var lastEntry = extractLast(request.term);
          var filteredArray = $.map(states, function(item) {
            if (item.state.indexOf(lastEntry) === 0) {
              return item.state;

            } else {
              return null;
            }
          });
          response($.ui.autocomplete.filter(filteredArray, lastEntry));
        },
        focus: function() {
          return false;
        },
        select: function(event, ui) {
          var terms = split(this.value);
          terms.pop();
          terms.push(ui.item.value);
          terms.push("");
          this.value = terms.join("");

          return false;
        }
      }).on("keydown", function(event) {
        if (event.keyCode === $.ui.keyCode.TAB /** && $(this).data("ui-autocomplete").menu.active **/ ) {
          event.preventDefault();
          return;
        }
        var newY = $(this).textareaHelper('caretPos').top + (parseInt($(this).css('font-size'), 10) * 1.5);
        var newX = $(this).textareaHelper('caretPos').left;
        var posString = "left+" + newX + "px top+" + newY + "px";
        $(this).autocomplete("option", "position", {
          my: "left top",
          at: posString
        });
      });
  } else {

    console.log(e.which); //This shows the right e.which
    $('#text').autocomplete("destroy"); // Just experimenting. It doesn't work with or without it
    $(e.target)
      .autocomplete({
        minLength: 0,
        autoFocus: true,
        source: function(request, response) {
          var lastEntry = extractLast(request.term);
          var filteredArray = $.map(states, function(item) {
            if (item.county.indexOf(lastEntry) === 0) {
              return item.county;
            } else {
              return null;
            }
          });
          response($.ui.autocomplete.filter(filteredArray, lastEntry));
        },
        focus: function() {
          return false;
        },
        select: function(event, ui) {
          var terms = split(this.value);
          terms.pop();
          terms.push(ui.item.value);
          terms.push("");
          this.value = terms.join("), ");
          return false;
        }
      }).on("keydown", function(event) {
        if (event.keyCode === $.ui.keyCode.TAB) {
          event.preventDefault();
          return;
        }
        var newY = $(this).textareaHelper('caretPos').top + (parseInt($(this).css('font-size'), 10) * 1.5);
        var newX = $(this).textareaHelper('caretPos').left;
        var posString = "left+" + newX + "px top+" + newY + "px";
        $(this).autocomplete("option", "position", {
          my: "left top",
          at: posString
        });
      });
  } //e.preventDefault();
});

 });
});

I know there are some issues here, like when I enter the state name, the same entry shows several times, but I'll deal with that later, I just want to be sure that what I'm trying to do is possible. Thanks in advance.


text:
Q: GAE search API - how to geoSearch a field Hello I am having a difficult time geoSearching a field.  What I am trying to do is query the geofield to find the closest store to me based on the zipcode I provide.
First i get the lat & lng from google maps api (components:postal_code:). Then I input the lat & lng coordinates into the query string.
EX.  query = "distance(store_location, geopoint(lat, lng)) < 4500"
My index is populated with plenty of documents...store_location is my geoField
EX. store_location | search.GeoPoint(latitude=34.0324...)
The PROBLEM is... when ever I search the index i get back zero
EX. search.SearchResults(number_found=0)
Why am I not getting back a result? Thank you for the help.
class FindStore(BaseHandler):
    def post(self):
        data = zipcheck.get_lat_lng_from_google_map(self.request.body)
        obj = json.loads(data)
        ziplat = obj['lat']
        ziplng = obj['lng']
        index = INDEX_STORE
        query = "distance(store_location, geopoint(%s, %s)) < 4500" %(ziplat, ziplng)
        results = index.search(query)
        return results


text:
Q: How could I check if a value in an array begins with a certain letter? I have a program in which a user picks a letter. The program should then search through a list and count how many names start with the letter the user chose.
This is what I've got so far:
nameslist = ["bob", "phil", "james"]

letter = input("Pick a letter.")
letter = letter.lower()

wordcount = 0

for I in range(len(nameslist)-1):
   if list[I].startswith(letter):
      wordcount = wordcount+1
      print(list[I])

I was led to believe that startswith would help me but it doesn't work.

A: You could use the following:
names = ["bob","phil","james"]

letter = input("Pick a letter.")
letter = letter.lower()
count = 0

for name in names:
    if name.startswith(letter):
        print(name)
        count += 1

This iterates over each name in names and uses the startswith() method to check whether name begins with letter. If name begins with letter, it prints name. It also counts the number of name in names that begin with letter using the count variable.

A: If you want to keep your current code all you need to do is fix some typos. Here is the correct code with comments showing what I changed:
nameslist=["bob","phil","james"]

letter=input("Pick a letter.")
letter=letter.lower()

wordcount=0

for I in range(len(nameslist)):  # you dont need the -1 at the end of this
   if nameslist[I].startswith(letter): # you need to change list to nameslist
      wordcount=wordcount+1
      print(nameslist[I])  # you need to change list to nameslist


text:
Q: get_relationship method call returns a single record when two are expected I have a defined one to many relationship between accounts and analysis, sugar link name is accounts_analysis_1. Using API V4.1 I want to retrieve all analysis ids where accounts id is equal for example to this fixed id 31381e50-2eff-bc0f-0636-5b9a71e60551
In order to achieve, I have tried the following logic but I only get one result and I expect two
$relationshipParameters = (object)[
    'moduleName' => 'Accounts',
    'moduleId' => '31381e50-2eff-bc0f-0636-5b9a71e60551',
    'linkFieldName' => 'accounts_analysis_1',
    'relatedModuleQuery' => '',
    'relatedFields' => ['id'],
    'relatedModuleLinkNameToFieldsArray' => []
];

$results = $this->restClient->getRelationships(
    $relationshipParameters->moduleName,
    $relationshipParameters->moduleId,
    $relationshipParameters->linkFieldName,
    $relationshipParameters->relatedModuleQuery,
    $relationshipParameters->relatedFields
);

the call to $this->restClient->getRelationships is just a wrapper to the API Method get_relationships
This is the result I get in JSON format, here I expect two results but I am getting one. Even when the wrapper call to get_relationships api method set limit to 200 by default
{
    "entry_list": [
        {
            "id": "45e93fff-63d0-e6e5-a55d-5d5a8c73f7fe",
            "module_name": "analysis",
            "name_value_list": { "id": { "name": "id", "value": "45e93fff-63d0-e6e5-a55d-5d5a8c73f7fe" } }
        }
    ],
    "relationship_list": []
}

In summary, I try to reproduce the following SQL query, which returns me two ids
select accounts_analysis_1_c.accounts_analysis_1analysis_idb from accounts_analysis_1_c where accounts_analysis_1accounts_ida = '31381e50-2eff-bc0f-0636-5b9a71e60551';

A: Can you try to verify it by using the below query:
select accounts_analysis_1_c.accounts_analysis_1analysis_idb from accounts_analysis_1_c where accounts_analysis_1accounts_ida = '31381e50-2eff-bc0f-0636-5b9a71e60551' and deleted = 0;

A: I have worked in the past with getting related contacts to an account and following code worked fine for me:
$get_relationships_parameters = array(
    'session' => $session_id,
    'module_name' => 'Accounts',
    'module_id' => '2a2ecece-ac87-55c7-2f42-5d5a6ce70fe4',
    'link_field_name' => 'contacts',
    'related_module_query' => "",
    'related_fields' => array(
        'id',
        'first_name',
        'last_name'
    ),
    'related_module_link_name_to_fields_array' => array(
        array(
        ),
    ),
    'deleted'=> 0,
    'order_by' => '',
    'offset' => 0,
    'limit' => 200,
);

Modify it according to your need and for further help, you can read details from here


text:
Q: I am trying to bind a text area to an angularjs variable and have it reflect changes I make to the text area with jquery, in the angular js variable I want to bind a text box to an angularjs variable and have it output rendered html in a separate div.  I also want to manage the data in that div with jquery.  When I update using jquery the bound angularjs does not update.
I have:
$('#sections, #phases').change(
...
$('textarea#displayData').val(html);

This works.  When sections or phases change, displayData gets updated.

<form:textarea ng-model="ddata" id="displayData" path="displayData"/>

{{ddata}}

This also works.  When I modify displayData in the text area, the bound ddata variable shows my change.
What doesn't happen is when the sections or phases change, and the displayData gets updated, the ddata doesn't reflect that change.

A: If you want the angular world to know about changes made outside the angular world, you must do the changes using scope.$apply()
//jQuery world
$(function() {
    var scope = angular.element("textarea#displayData").scope();
    scope.$apply(function(){
        // angular world
        scope.ddata = html;
    });
});

See a working example here: http://plnkr.co/edit/YnXZQm78M9nMqd9uOURz?p=preview


text:
Q: How to get data in a column in order by using SQL in operator There is a data set as shown below;

When input for event_type is 4, 1, 2, 3 for example, I would like to get 3, 999, 3, 9 from cnt_stamp in this order. I created a SQL code as shown below, but it seems like it always returns 999, 3, 9, 3 regardless the order of the input.
How can I fix the SQL to achieve this? Thank you for taking your time, and please let me know if you have any question.
SELECT `cnt_stamp` FROM `stm_events` WHERE `event_type` in (4,1,2,3)

A: Add ORDER BY FIELD(event_type, 4, 1, 2, 3) in your query. It should look like:
SELECT cnt_stamp FROM stm_events WHERE event_type in (4,1,2,3) ORDER BY FIELD(event_type, 4, 1, 2, 3);

A: its cannot because as default the data sort by ascending, if u want result like u want,, better u create 1 column for indexing


text:
Q: Почему background-image не работает в option Хочу чтобы фон у option был в виде градиента , но background-image: linear-gradient() не показывает фон.

option {
  background-image: linear-gradient(to bottom, rgb(0, 255, 238), rgba(38, 255, 0, 0.319));
}

  What is your goal?
  <select name="goal" id="goal">
    <option class="option" value="">Wanna change my profession</option>
    <option class="option" value="">Improve my skill/abilities</option>
    <option class="option" value="">Hobby</option>
    <option class="option" value="">Wanna be freelancer</option>
  </select>


text:
Q: Getting the next textbox using the next() function in jquery I am trying to write some Jquery code that will get the value of the next textbox that is of a class "in". The code I have here isn't working, the value is always undefined. I think I am using the next() function incorrectly but I am not sure, does anybody have any input?
<!DOCTYPE html>
<html>

<body>
<input type="text" class="mm" />
<br>
<input type="text" class="in" />

$(document).ready(function() {
    $("input").focus(function() {

        var value = $(this).next(".in").val();
        if (value) {
            alert(value);
        }

    });
});

  </script>
 </body>
</html>

A: You would need to post your html. The Next gets the next sibling, so it very much depends on the html structure - it might just need you to add a parent in to get to the point which is a parent of all the text boxes.

A: $(this).next(".in") will only return a value if the next element has a class of "in", rather than looking at all siblings for the first textbox with a class of "in".
Try $(this).nextAll(".in:eq(0)").

A: Your example as you've given the HTML actually works.  You can see it here: http://jsfiddle.net/jfriend00/RGsDq/.  Based on your comments, it sounds like you want the first sibling that has the class "in" whether it's the next sibling or not.  .next() only examines the very next sibling.  If you want the first sibling that has the class "in" even if it's not the very next sibling, you can do either of these:
$(this).nextAll(".in").first().val();           // next sibling with class ".in"
$(this).parent().find(".in").first().val();     // next child of parent with class ".in"

You can see the first of these two options working here: http://jsfiddle.net/jfriend00/4VwAN/


text:
Q: Sums of even Divisor problem How to find sum of all even divisor of a number using formula.Or more efficiently. Please any suggestions.

A: Hints:

*

*The sum of divisors function $\sigma$ is a multiplicative function.  In other words, if $n$ and $m$ are relatively prime, then $\sigma(nm)=\sigma(n)\sigma(m)$.  Moreover, if $p$ is prime, then $\sigma(p)=p+1$.  Moreover $\sigma(p^k)=1+p+p^2+\cdots+p^k$, which is a geometric sum equal to $\frac{p^{k+1}-1}{p-1}$.

*The sum of the even divisors of $n$ is $\sigma(n)$ minus the sum of the odd divisors.

*If $2^k$ is the largest power of $2$ dividing $n$, then $\sigma\left(\frac{n}{2^k}\right)$ is the sum of the odd divisors of $n$.

*Putting this together,
\begin{align*}
\sigma(n)-\sigma\left(\frac{n}{2^k}\right)&=\sigma(2^k)\sigma\left(\frac{n}{2^k}\right)-\sigma\left(\frac{n}{2^k}\right)\\
&=\left(\sigma(2^k)-1\right)\sigma\left(\frac{n}{2^k}\right)\\
&=(2^{k+1}-2)\sigma\left(\frac{n}{2^k}\right).
\end{align*}
For example, let $n=180=2^2\cdot 3^2\cdot 5$.  Then, the divisors of $180$ are:
$$
\{1,2,3,4,5,6,9,10,12,15,18,20,30,36,45,60,90,180\}.
$$
The sum of the divisors is
$$
1+2+3+4+5+6+9+10+12+15+18+20+30+36+45+60+90+180=546.
$$
The sum of the odd divisors is
$$
1+3+5+9+15+45=78.
$$
The sum of the even divisors is
$$
2+4+6+10+12+18+20+30+36+60+90+180=468.
$$
Observe that $468+78=546$ (as expected).
Alternately, we can use our formula to check all of this: The largest power of $2$ dividing $180$ is $2^2$, and $\frac{180}{4}=45$.  Therefore, the sum we're looking for can be computed as:
\begin{align*}
(2^3-2)\sigma(45)&=(2^3-2)\sigma(3^2)\sigma(5)\\
&=6\cdot\frac{3^3-1}{3-1}\cdot(5+1)\\
&=6\cdot 13\cdot 6=468.
\end{align*}
Observe additionally that $\sigma(45)=13\cdot 6=78$, i.e., the sum of the odd divisors.

A: Here is some code, the idea is to use the multiplicative formula but pre-sieving the primes first. Perhaps the only interesting idea is that the even divisors of $x$ are exactly the divisors of $x$ that are not divisors of the odd part of $x$.
This code should work within the time limits of most contest problems:
#include <bits/stdc++.h>
using namespace std;
typedef long long lli;

const int MAX=1000010; // this will let us factorize number up to slightly less than MAX*MAX
int C[MAX];// the cribe
vector <int> P; //here we store the primes

lli sumd(lli x){
    lli res=1;
    for(int i=0;P[i]*P[i]<= x; i++){// by the prime number theorem this takes at most 2sqrt(n)/log(n) (approximately)
        lli m=1,f=1;// m is what we need to multiply the answer by at the end, f lets us build m
        while(x%P[i]==0){
            f*=P[i];
            m+=f;
            x/=P[i];
        }
        res=res*m;
    }
    if(x>1) res=res*(x+1);
    return(res);
}

int odd(int x){
    while(x%2){
        x/=2;
    }
    return(x);
}

int main(){
    for(int i=2;i<MAX;i++){// this sets up the cribe.
        if(!C[i]){
            P.push_back(i);
            for(int j=2*i;j<MAX;j+=i){
                C[j]=1;
            }
        }
    }
    int cases;
    cin >> cases;
    while(cases --){
        int x;
        cin >> x;
        cout << sumd(x)- sumd(odd (x) ) << endl;
    }
}


text:
Q: Queryset in django admin breaks migrations and py.test I am getting FATAL: database "xxxxxxxxx" does not exist during the loading of py.test.  This is coming from the loading of the admin forms, where by I have a queryset being passed to a ModelChoiceField
class CustomChoiceField(forms.ModelChoiceField):
    def __init__(self, queryset=None, *args, **kwargs):
        return super().__init__(SomeModel.objects.limited_qs(), *args, **kwargs)

class SomeModelForm(forms.ModelForm):
    some_model = CustomChoiceField()

    class Meta:
        model = SomeModel

class SomeModelAdmin(admin.ModelAdmin):
    form = SomeModelForm

I've tried this with
formfield_overrides = { models.ForiegnKey : {'queryset': ... } }

all result in the same problem with py.test
EDIT
Having the queryset either in the __init__ method or in formfield_overrides also breaks the migrations.
Note: these all work exactly how I want them to on the server - they just prevent me for running any tests.
How do I get this to pass (w/o conditionally registering my admin stuff ;_; I like tdd)

A: I had a similar problem, in my case, the problem was that in my SomeModel.objects.limited_qs(), I was calling another queryset like:
self.filter(another_model=AnotherModel.objects.get(xxx=1))

So, to build the queryset a call to database was executed before the test database creation, causing the "FATAL database does not exist"


text:
Q: How to stop finally block from execute in C# I have created a try block.Inside that try block again try block and it's finally block.I closed that outside try block.followed by finally block.Suppose I don't want to execute the finally block,for that I wrote Environment.Exit(0).Does there is any other method that stop finally block from execution.return 0;(that is in java).Please let me know.
public static int Main()
        {
            try
            {
                Console.WriteLine("First try block");

                try
                {
                    Console.WriteLine("Second try block");
                    //exit(0);
                    Environment.Exit(0);
                    //return 0;
                }

                finally
                {
                    Console.WriteLine("Finally block of inner try");
                }
            }

            finally
            {
                Console.WriteLine("Finally block of second try");
            }

A: From the MSDN -

The statements of a finally block are executed when control leaves a try statement, whether the transfer of control occurs as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.

A: You can use Environment.FailFast() to exit the application immediately, while skipping finally and finalizers.
http://msdn.microsoft.com/en-us/library/ms131100.aspx

A: It is possible to use one try block and few catch blocks. If one type of exception require some action you can enter them into that block and leave finally block empty.

A: You can't - the finally block is always executed, unless for some reason the JVM exits before it gets to it.    Link from MSDN
I'm not quite sure why you would want to do this, anyway. Sounds like you may need to change your design somewhat.

A: Alternative:
Use a boolean to determine which code in your finally block is called.
    public static int Main()
    {
        bool complete = false;
        try
        {
            Console.WriteLine("First try block");

            try
            {
                Console.WriteLine("Second try block");
                //exit(0);
                //Environment.Exit(0);
                return 0;
            }

            finally
            {
                Console.WriteLine("Finally block of inner try");
            }
        }

        finally
        {
            if (complete)
            {
                Console.WriteLine("Finally block of second try");
            }
        }
    }

Make sure to set your complete variable somewhere.

A:     static void Main(string[] args)
    {
        try
        {
            int a = 10/0;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {

            while (true)
            {
                Console.WriteLine("Statement 1");
                break;
                Console.WriteLine("Statement 2");
            }
        }
        Console.ReadLine();
    }


text:
Q: How do I view surface in ParaView? I created a collection of particles that are held together by a bond. The file is in .vtu format. I don't get to see the particles when I tried to view the surface: only the collections of the bonds were shown.
This is what I am getting:


text:
Q: can't install mariadb because of Cannot link cmake I'm sorry if my question is a little newbie, i just get Mac in my job and I'm usually a Linux user...
I'm trying to install mariadb to use it after with python, i tried with brew. I know it's old version of macOS (and i can't do anything about it)
brew install mariadb
Running `brew update --auto-update`...
Warning: You are using macOS 10.14.
We (and Apple) do not provide support for this old version.
It is expected behaviour that some formulae will fail to build in this old version.
It is expected behaviour that Homebrew will be buggy and slow.
Do not create any issues about this on Homebrew's GitHub repositories.
Do not create any issues even if you think this message is unrelated.
Any opened issues will be immediately closed without response.
Do not ask for help from MacHomebrew on Twitter.
You may ask for help in Homebrew's discussions but are unlikely to receive a response.
Try to figure out the problem yourself and submit a fix as a pull request.
We will review it but may or may not accept it.

==> Fetching dependencies for mariadb: cmake, fmt, mecab, mecab-ipadic, msgpack, ca-certificates, openssl@1.1, pcre, groonga, pcre2, xz and zstd
==> Fetching cmake
==> Downloading https://github.com/Kitware/CMake/releases/download/v3.25.2/cmake-3.25.2.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/b19b531ca705f5d1736fb10a83767e06ac2e8801a3f9f34ac8b4bd6e1697dda2--cmake-3.25.2.tar.gz
==> Fetching fmt
==> Downloading https://github.com/fmtlib/fmt/archive/9.1.0.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/d39fe7ae376a7198a34490e5acb665b0112ea585720eb917c496bb050bc76c62--fmt-9.1.0.tar.gz
==> Fetching mecab
==> Downloading https://ghcr.io/v2/homebrew/core/mecab/manifests/0.996-3
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/21431e68751945bd7900be15e222a38b4402841088e6d5669b4f48c56dc614b3--mecab-0.996-3.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/mecab/blobs/sha256:ef261d203140305ca8c9e4b7311c61176a17325df9454610d3eb33a312c4d3c5
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/45441007488c38750c14c63895eccd562a5af40519f48eed3e35ce6eb10fbb13--mecab--0.996.mojave.bottle.3.tar.gz
==> Fetching mecab-ipadic
==> Downloading https://ghcr.io/v2/homebrew/core/mecab-ipadic/manifests/2.7.0-20070801
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/011316e018929eb52aa0a17e2d6634fe3804c07bf44859f3cc7a0b4baf0e3cea--mecab-ipadic-2.7.0-20070801.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/mecab-ipadic/blobs/sha256:30967b4167d34f05c79f185d71a40198fff4067d0cce82aed59383548c898681
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/f5097a021ff29918177e2d4279101124910e2f287932a3619641988e92f66a76--mecab-ipadic--2.7.0-20070801.mojave.bottle.tar.gz
==> Fetching msgpack
==> Downloading https://github.com/msgpack/msgpack-c/releases/download/c-5.0.0/msgpack-c-5.0.0.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/c58619083eaba272e9c477c3c0deb886dc539140f009dd42dc2634e8db0378a3--msgpack-c-5.0.0.tar.gz
==> Fetching ca-certificates
==> Downloading https://ghcr.io/v2/homebrew/core/ca-certificates/manifests/2023-01-10
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/927414ed081d996b84d938be6af4d2639403b4d2bee3cc29268d0844999da180--ca-certificates-2023-01-10.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/ca-certificates/blobs/sha256:11fe9d0a98a2ac454fa1db95762a697c3340f46560ff27e5e9db8fdeb003f17e
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/ca2448928ab98c455b5e46d4a6604247a151ab0f4e60553dbb5c6aecd2e1df3c--ca-certificates--2023-01-10.all.bottle.tar.gz
==> Fetching openssl@1.1
==> Downloading https://www.openssl.org/source/openssl-1.1.1t.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/ec3feb171aa63b32c30a6e7423e78f743f92d1ef984b66b0ea548d08220c0ce6--openssl-1.1.1t.tar.gz
==> Fetching pcre
==> Downloading https://ghcr.io/v2/homebrew/core/pcre/manifests/8.45
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/4a3bba0e8d1899c13ac3442d2c49df6c1999948bdc0943f2f179693257d82545--pcre-8.45.bottle_manifest.json
==> Downloading https://ghcr.io/v2/homebrew/core/pcre/blobs/sha256:a42b79956773d18c4ac337868cfc15fadadf5e779d65c12ffd6f8fd379b5514c
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/456b31dd91116840800d9cc2f35c6f2ebde8cfe8513e6d08dd6974f3309dc4f9--pcre--8.45.mojave.bottle.tar.gz
==> Fetching groonga
==> Downloading https://packages.groonga.org/source/groonga-normalizer-mysql/groonga-normalizer-mysql-1.2.1.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/8bc84be3a691a3cf950cf2576dac8b64884fd7f4f91026475399827c9d96fd6b--groonga-normalizer-mysql-1.2.1.tar.gz
==> Downloading https://packages.groonga.org/source/groonga/groonga-13.0.0.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/31a0c28bde3252bed7d10bba33dec5ef45e6a5379da383e40c28f668bb03878d--groonga-13.0.0.tar.gz
==> Fetching pcre2
==> Downloading https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.42/pcre2-10.42.tar.bz2
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/7f4d74ac3e447b9fed53bce4202af3921ffc5ae1469894e7e1b10bda2145a15b--pcre2-10.42.tar.bz2
==> Fetching xz
==> Downloading https://downloads.sourceforge.net/project/lzmautils/xz-5.4.1.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/ca0c062e8ecb14160415874ad277c80d73d9a9d00aa926ff11a32e877f6651fe--xz-5.4.1.tar.gz
==> Fetching zstd
==> Downloading https://github.com/facebook/zstd/archive/v1.5.4.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/a7632ef95a5b612da27d37abb163299230d9f9394c53a8385de8c57a366c2ebe--zstd-1.5.4.tar.gz
==> Fetching mariadb
==> Downloading https://downloads.mariadb.com/MariaDB/mariadb-10.10.3/source/mariadb-10.10.3.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/182c68feeae25618d12662bea09676695697b3545a81c63d59850e574372c312--mariadb-10.10.3.tar.gz
==> Installing dependencies for mariadb: cmake, fmt, mecab, mecab-ipadic, msgpack, ca-certificates, openssl@1.1, pcre, groonga, pcre2, xz and zstd
Error: Cannot link cmake
Another version is already linked: /usr/local/Cellar/cmake/3.24.2

i tried to upgrade cmake in case of but i wasn't a better try:
==> Upgrading 1 outdated package:
cmake 3.24.2 -> 3.25.2
==> Fetching cmake
==> Downloading https://github.com/Kitware/CMake/releases/download/v3.25.2/cmake-3.25.2.tar.gz
Already downloaded: /Users/cea/Library/Caches/Homebrew/downloads/b19b531ca705f5d1736fb10a83767e06ac2e8801a3f9f34ac8b4bd6e1697dda2--cmake-3.25.2.tar.gz
==> Upgrading cmake
  3.24.2 -> 3.25.2

Error: Permission denied @ apply2files - /usr/local/share/emacs/site-lisp/cmake

if someone has any solutions for me thanks!


text:
Q: Crop screenshot in android programmatically for taking screen shot i have am using below code
  public void takeScreenShot(){
    File wallpaperDirectory = new File("/sdcard/Hello Kitty/");
    if(!wallpaperDirectory.isDirectory()) {
    // have the object build the directory structure, if needed.
    wallpaperDirectory.mkdirs();
    // create a File object for the output file
    }
    File outputFile = new File(wallpaperDirectory, "Hello_Kitty.png");
    // now attach the OutputStream to the file object, instead of a String representation
    // create bitmap screen capture
    Bitmap bitmap;
    View v1 = mDragLayer.getRootView();
    v1.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v1.getDrawingCache(),0,0,v1.getWidth(),v1.getHeight());
    v1.setDrawingCacheEnabled(false);

    OutputStream fout = null;

    try {
        fout = new FileOutputStream(outputFile);
      //  Bitmap bitMap = Bitmap.createBitmap(src)
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
        fout.flush();
        fout.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

and now i want a cropped bitmap in that i want to crop some portion from left and some portion from bottom so i have used code like this
      Bitmap.createBitmap(v1.getDrawingCache(),v1.getWidth()/10,v1.getHeight()/10,v1.getWidth(),v1.getHeight());

but i got an error
   08-29 23:41:49.819: E/AndroidRuntime(3486): java.lang.IllegalArgumentException: x +    width must be <= bitmap.width()
   08-29 23:41:49.819: E/AndroidRuntime(3486):  at android.graphics.Bitmap.createBitmap(Bitmap.java:410)
    08-29 23:41:49.819: E/AndroidRuntime(3486):     at android.graphics.Bitmap.createBitmap(Bitmap.java:383)

can anybody tell me how to crop portion of an bitmap from left and bottom thanks...

A: It appears you misunderstood the usage of that specific Bitmap.create(...) function. Rather than supplying the source's width and height as the last two parameters, you should specificy the width and height the cropped result should end up with.
The error explains that since you specified an offset from the left and top, but passed in the source's dimensions, the cropped result would exceed the bounds of the original image.
If all you want to do is crop a tenth off the left and top, simply subtract the offsets from the original width/height:
Bitmap source = v1.getDrawingCache();
int x = v1.getWidth()/10;
int y = v1.getHeight()/10
int width = source.getWidth() - x;
int height = source.getHeight() - y;
Bitmap.createBitmap(source, x, y, width, height);

A: Instead of using
Bitmap.createBitmap(v1.getDrawingCache(),v1.getWidth()/10,v1.getHeight()/10,v1.getWidth(),v1.getHeight());

You can use  bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Refer here for some more methods Bitmap


text:
Q: How to build a tree from a set of path fragments for leaf nodes I am looking for an algorithm to construct a possible top down tree structure when the only input data is path decisions (in random order) for the leaf nodes.
The path decisions is notaded with [nodeID]+ if the leaf node has passed through that node and [nodeID]- if the leaf node has not passed through that node. Example input:

One possible tree structure from the example input above would be:

The output should be a list of nodes and the node respective parent, like this:

As you can see the possible positions for each leaf node is not limited to one, since the input data is not complete paths. Leaf1 in the example can be a child of node D or node I.
There can be any number of leafs you get path data from, but only one single line of path data per leaf. There can be leafs you get no data from at all and you are not aware of how many total leafs there is in the tree. All nodes mentioned in path data should be present in the output table and only the calculated root shouldn't have any parent assigned.
I guess one must somehow combine the facts from each Leaf paths, like from Leaf1 you know: A and E must not be in parallell lines, and from Leaf2 you know that A and I must not be in parallell lines, and so on ...
Preferable javascript but other language or pseudo code is also welcomed!

A: Since nobody answered, I'll give some partial thoughts.
You start with:
1: [A+, E+, H-]
2: [B-, A+, I+, D-]
3: [K+, G+, E+, C-]
4: [H+, A-, G-]

First, search for nodes that only appear with a +.  Make those roots.  Scanning this, we can do that for nodes E, I, and K.  So our answer starts with:
E
E I
I K

And our path data is simplified to:
1: [A+, H-]
2: [B-, A+, D-]
3: [G+, C-]
4: [H+, A-, G-]

And now we have a partition operation.  For this we make a graph where 2 nodes are connected iff they appear together with a +.  We then separate nodes by connected components, and separate leaves into partitions where there is a + (any leaf without a partition can be made a leaf right there in the tree and then dropped).  Deleting any - that is taken care of by this separation.  In our case this is a totally disconnected graph which puts each node into its own partition and divides the path data into 3 groups (note, we lose all - rules which are explained by the partitioning):
1: [A+]
2: [A+]

3: [G+]

4: [H+]

And now we solve each problem, coming to a final solution of:
E
E I
I K
K A
K B
K C
K D
K G
K H

I believe that this approach will only fail to make progress in the case where no tree is possible.  If there is a tree to be found, it will find one.


text:
Q: Restrict many - many results in SQL join The SQL below contains some DDL and a simple query.
The result I am getting is
a1|b1|c1
a1|b2|c3
a3|b3|c2
a3|b3|c3
a3|b3|c4
a3|b3|c5
a3|b5|c6
a3|b5|c7

The result I want is
a1   |b1   |c1
a1   |b2   |c3
a3   |b3   |c2
null |null |c4
null |null |c5
a3   |b5   |c6
null |null |c7

I tried using MAX, MIN, rownums and what not. I am at my wit's end. I am including only the base query I started with and not all the options I tried because they don't work at all. Any help is appreciated!

BEGIN TRANSACTION;

drop table if exists table_A;
drop table if exists table_B;
drop table if exists table_C;

/* Create a table called NAMES */
CREATE TABLE table_A(a_Id text PRIMARY KEY, val_a text);
CREATE TABLE table_B(a_Id text, b_Id text, val_b text);
CREATE TABLE table_C(b_Id text, c_Id text, val_c text);

/* Create few records in this table */
INSERT INTO table_A VALUES('a1','va1');
INSERT INTO table_A VALUES('a2','va2');
INSERT INTO table_A VALUES('a3','va3');

INSERT INTO table_B VALUES('a1', 'b1','vb1');
INSERT INTO table_B VALUES('a1', 'b2','vb2');
INSERT INTO table_B VALUES('a3', 'b3','vb31');
INSERT INTO table_B VALUES('a2', 'b4','vb4');
INSERT INTO table_B VALUES('a3', 'b5','vb31');

INSERT INTO table_C VALUES('b1', 'c1','vc1');
INSERT INTO table_C VALUES('b3', 'c2','vc2');
INSERT INTO table_C VALUES('b3', 'c3','vc3');
INSERT INTO table_C VALUES('b2', 'c3','vc3');
INSERT INTO table_C VALUES('b3', 'c4','vc2');
INSERT INTO table_C VALUES('b3', 'c5','vc3');
INSERT INTO table_C VALUES('b5', 'c6','vc3');
INSERT INTO table_C VALUES('b5', 'c7','vc3');

COMMIT;

select
a.a_Id, b.b_Id, c.c_Id
from
table_A as a
join
table_B as b
on a.a_Id = b.a_Id
join
table_C as c
on b.b_Id = c.b_Id;

A: I'd first recommend that this sounds better to handle in your presentation logic.  However, it is possible to accomplish with SQL alone.
You can take advantage of Oracle's LAG() function along with CASE to check if the previous row had the same a and b id values.
Here's an example using a common table expression:
with cte as (
  select
    a.a_Id, b.b_Id, c.c_Id,
    lag (a.a_Id,1) over (order by a.a_Id, b.b_Id) prev_a_Id,
    lag (b.b_Id,1) over (order by a.a_Id, b.b_Id) prev_b_Id
  from table_A a
    join table_B b
      on a.a_Id = b.a_Id
    join table_C c
      on b.b_Id = c.b_Id
  order by
    a.a_id, b.b_id
  )
select
  case
      when prev_a_Id is null or
            prev_a_Id <> a_Id or
            prev_b_Id <> b_Id
      then a_id
    end new_a_Id,
  case
      when prev_a_Id is null or
            prev_a_Id = a_Id or
            prev_b_Id = b_Id
      then b_id
    end new_b_Id, c_Id
from cte;

*

*SQL Fiddle Demo

A: something like this should work (I have tested it on PostgreSql, should work on Oracle too)
SELECT
  case when row_number = 1 then a_id end as a_id,
  case when row_number = 1 then b_id end as b_id,
  c_id
FROM (
  SELECT
    a.a_Id,
    b.b_Id,
    c.c_Id,
    row_number() OVER (partition by a.a_id, b.b_id order by c.c_id) as row_number, --for a_id, b_id
    row_number() OVER (partition by c.c_id order by c.c_id) as row_number2         --to avoid c_id duplicates
  FROM
    table_A  a
    join
    table_B  b on a.a_Id = b.a_Id
    join table_C  c on b.b_Id = c.b_Id
  )  innerquery
WHERE
  row_number2 = 1 --this is to avoid c_id duplicates

SQLFIDDLE

A: select  t1.a_id, t1.b_id, table_c.c_id
from table_c
left join
(
  select a_Id, b_Id, c_Id
  from
  (
    select a.a_Id as a_id, b.b_Id as b_id, c.c_Id as c_id,
           ROW_NUMBER() OVER (PARTITION BY  a.a_ID, b.b_id ORDER BY C_ID) as aNum
    from table_A as a
    join table_B as b on a.a_Id = b.a_Id
    join table_C as c on b.b_Id = c.b_Id
  ) t2
  where aNum = 1
) t1 on  table_c.c_id = t1.c_id
order by table_c.c_id

fiddle:
http://sqlfiddle.com/#!3/6049b/1

A: I don't think i fully understood that you are trying to achieve, but correct me please if i'm wrong.
First, you use inner join to join tables (at least it will be if you use sql server, but should be the same in oracle). That means that for example you will get row from first table only if it has a correspondent row in the second table, And if now rows in first table for corresponding rows in second table, that rows from second table never appear in results.
According to description of result that you want to achieve you need is a outer join . Which one exactly left/right/full outer join depends on that you are trying to achieve (looks like you need left outer join or full outer join). I'm not quite sure that you exact aim because you explain how your data in this concrete example should looks like not general case.
So please have a look at description of different join types and choose sql join types
And also one importation remark: text type is probably last type from the list that i would consider as primary key.


text:
Q: Wrong charset when scraping with Scraperjs I'm currently scraping a website with charset ISO-8859-1 using Scraperjs. My problem is that characters such as æ, ø, å and é are not properly encoded (they are displayed/saved as a question mark).
Any ideas?
Scraperjs:
https://github.com/ruipgil/scraperjs

A: Found the solution myself. You need to specify the encoding to binary in order to read the characters as displayed. See code below:
        scraperjs.StaticScraper.create()
        .request({ url:"http://vg.no", encoding: "binary"})
        .scrape(function($) {
            return $("p").map(function() {
                return $(this);
            });
        })
        .then(function(domElements).........

A: const scraperjs = require('scraperjs');
const urlToScrape = 'http://www.somesite.com';
const selectorToScrape = "div#someId";
scraperjs.StaticScraper.create({
    url: urlToScrape,
    encoding: "binary"
}).scrape(function ($) {
    return $(selectorToScrape).map(function () {
        return $(this).text();
    }).get();
}).then(function (result) {
 console.log(result);
});


text:
Q: Date function format in elegant way? How write this is more elegant way? This function makes column sorting work. Is another way to do this? If not this fucntion sorting will not work properly :(

 getTime1(element: Tsk) {
    const reg = /[\s\.]/

    const [day, month, year, hour, minutes] = element.time.split(reg)

    return new Date(parseInt(year)
      , parseInt(month) - 1,
      parseInt(day),
      parseInt(hour),
      parseInt(minutes)

    ).getTime();

  }
  announceSortChange(sortState: Sort) {

    this.dataSource.sortingDataAccessor = (item, property) => {

      switch (property) {
        case 'title':
          return item[property].toLocaleLowerCase();
          break;
        case 'time':
          return this.getTime1(item);
          break;

        default:
          return item[property];
      }
    };

    console.log("============")
    this.dataSource.sort = this.sort;
  }

If I will do this =>
getTime1(element: Task) {
emphasized text const reg = /[\s\.]/
const [day, month, year, hour, minutes] = element.time.split(reg)
return new Date(element.time);
 }

case 'time':
 return item.time;

soritng doesn't work properly :(
If I will do such thing:
 case 'time':
return new Date(element.time)
 break;

arrow sorting is not working

A: Here is a example what I mean:
 getTime1(element: Tsk) {
    return new Date(element.time).getTime();
  }

  announceSortChange(sortState: Sort) {

    this.dataSource.sortingDataAccessor = (item, property) => {

      switch (property) {
        case 'title':
          return item[property].toLocaleLowerCase();
        case 'time':
          return this.getTime1(item);
        default:
          return item[property];
      }
    };

    console.log("============")
    this.dataSource.sort = this.sort;
  }

the getTime() method will be called inside your getTime1 function.
Greetings, Florian


text:
Q: Field is not writeable: ESR_Assignment__c.Customer_Address1__c at line 95 column 18 when I add formula field then showing like error
   /////////control class///////////

public with sharing class importDataFromCSVController {

 public Blob csvFileBody {get;set;}
 public String csvAsString {get;set;}
 public String[] CsvFileLines {get;set;}
 public List < ESR_Assignment__c > camtlist {get;set;}
 public Boolean exprots {get;set;}
 public Map < String, ESR_Assignment__c > esrNoByESR;
 public decimal trno {get;set;}

 public importDataFromCSVController() {
  exprots = False;
  CsvFileLines = new string[] {};
  camtlist = new list < ESR_Assignment__c > ();
  esrNoByESR = new Map < String, ESR_Assignment__c > ();

  for (ESR_Assignment__c objesrs: [select id, Name, ESR_Status__c, Payment__c, Payment_Date__c, Company_Name__c, Difference__c, Customer_Address1__c,CAMT_Payment_Date__c,CAMT_IDNUMBER__c,
                                    CAMT_ESRNumber__c, Total_Amount__c, CAMT_TotalAmount__c, Customer_Name__c,
                                    CAMT_Customer_Name__c, CAMT_CustomerAddress__c,
                                    CAMT_Upload_Date_File__c from ESR_Assignment__c
                                   ]) {

        esrNoByESR.put(objesrs.Name, objesrs);
        esrNoByESR.put(objesrs.CAMT_ESRNumber__c, objesrs);
  }
    system.debug('==33==' + esrNoByESR);
 }

 public void importCSVFile() {
  csvAsString = csvFileBody.toString();
  CsvFileLines = csvAsString.split('\n');
  system.debug('====' + esrNoByESR);
  List < ESR_Assignment__c > upertToList = new List < ESR_Assignment__c > ();

  for (Integer i = 1; i < CsvFileLines.size(); i++) {

   String[] CsvRecordData = CsvFileLines[i].split(',');
   ESR_Assignment__c objesrs = new ESR_Assignment__c();

    String esrnum = (CsvRecordData[1]).trim();

   system.debug('==='+(CsvRecordData[1]).trim());

   Decimal camttotalAmount =0.00;
   if(!String.isEmpty((CsvRecordData[2]).trim())){
       camttotalAmount = decimal.valueof((CsvRecordData[2]).trim());
   }

   ///////////////////////scenario3/////////////

  if (esrNoByESR.keySet() !=Null && esrNoByESR.containsKey(esrnum)){
     objesrs.id = esrNoByESR.get(esrnum).id;
     objesrs.Name = (CsvRecordData[1]);
   //  objesrs.Payment__c=(CsvRecordData[1]);
     //String de = String.valueof(CsvRecordData[0]);
     //system.debug('dedded=' + de);
   // objesrs.CAMT_ESRNumber__c = Decimal.valueof(de.trim());

   /*  objesrs.CAMT_ESRNumber__c =(CsvRecordData[0]);
     objesrs.CAMT_IDNUMBER__c=(CsvRecordData[4]);
     objesrs.CAMT_Payment_Date__c=mydate; */

     //objesrs.Name=objesrs.CAMT_ESRNumber__c;
       // if( objesrs.Status__c == ''){
    // objesrs.Status__c = 'Match';
    // upertToList.add(objesrs);
    // }
         }

    /*if there is ESR Number is not matched to csv file number this else part will create new esr recordaccordingly */
     else{
        // objesrs.Name = (CsvRecordData[0]);
        // String de = String.valueof(CsvRecordData[0]);
         //system.debug('dedded=' + de);
        // objesrs.CAMT_ESRNumber_optional__c = Decimal.valueof(de.trim());
       // objesrs.CAMT_ESR_Numberformula_del__c=(CsvRecordData[0]);
          objesrs.CAMT_IDNUMBER__c=(CsvRecordData[0]);
         objesrs.CAMT_ESRNumber__c =(CsvRecordData[1]);
         objesrs.CAMT_TotalAmount__c = camttotalAmount ;
         objesrs.CAMT_Customer_Name__c=(CsvRecordData[3]);
         objesrs.CAMT_CustomerAddress__c=(CsvRecordData[4]);
         objesrs.CAMT_Payment_Date__c=Date.valueof((CsvRecordData[5]));

         objesrs.ESR_Status__c= 'No Match';
         objesrs.Name='0';
         objesrs.Total_Amount__c=0;
         objesrs.Company_Name__c='Null';
         objesrs.Customer_Name__c='Null';
         objesrs.Customer_Address1__c='Null';
         objesrs.Payment__c=Null;
         objesrs.Difference__c=0;
       //  upertToList.add(objesrs);
         }

   ////////////////////////secanrio4///////////////////
   if (esrNoByESR.keySet() != Null && esrNoByESR.containsKey(esrnum) && esrNoByESR.get(esrnum).Payment__c == 'Not Paid' && esrNoByESR.get(esrnum).Total_Amount__c == camttotalAmount ) {
    objesrs.id = esrNoByESR.get(esrnum).id;
    objesrs.Name = (CsvRecordData[1]);
    //objesrs.CAMT_ESR_Numberformula__c= camtesrnumber;
    objesrs.CAMT_IDNUMBER__c=(CsvRecordData[0]);
    objesrs.CAMT_ESRNumber__c =(CsvRecordData[1]);
    objesrs.CAMT_TotalAmount__c = camttotalAmount ;
    objesrs.CAMT_Customer_Name__c=(CsvRecordData[3]);
    objesrs.CAMT_CustomerAddress__c=(CsvRecordData[4]);
    objesrs.CAMT_Payment_Date__c=Date.valueof((CsvRecordData[5]));

    system.debug('esrNoByESR.get(esrnum).Total_Amount__c=' + esrNoByESR.get(esrnum).Total_Amount__c);
    objesrs.Total_Amount__c = esrNoByESR.get(esrnum).Total_Amount__c;
    objesrs.Customer_Name__c = esrNoByESR.get(esrnum).Customer_Name__c;
    objesrs.Difference__c = esrNoByESR.get(esrnum).Difference__c;
    objesrs.Payment__c = esrNoByESR.get(esrnum).Payment__c;
    objesrs.Payment_Date__c = esrNoByESR.get(esrnum).Payment_Date__c;
    objesrs.Company_Name__c = esrNoByESR.get(esrnum).Company_Name__c;
    // objesrs.Customer_Address1__c=esrNoByESR.get(esrnum).Customer_Address1__c;
 //   objesrs.Test__c = Integer.valueof((CsvRecordData[0]).trim());

    objesrs.Payment__c ='Paid';
    objesrs.ESR_Status__c= 'Match';
    objesrs.Difference__c=0;
    upertToList.add(objesrs);
   }

   //////////////////////////secanrio 5/////////////
   else if (esrNoByESR.keySet() != Null && esrNoByESR.containsKey(esrnum) && esrNoByESR.get(esrnum).Payment__c == 'Not Paid' && esrNoByESR.get(esrnum).Total_Amount__c != camttotalAmount ) {

     objesrs.id = esrNoByESR.get(esrnum).id;
     objesrs.Name = (CsvRecordData[1]);
   //  objesrs.Test__c = Integer.valueof((CsvRecordData[0]).trim());

    //objesrs.CAMT_ESR_Numberformula__c= camtesrnumber;
    objesrs.CAMT_IDNUMBER__c=(CsvRecordData[0]);
    objesrs.CAMT_ESRNumber__c =(CsvRecordData[1]);
    objesrs.CAMT_TotalAmount__c = camttotalAmount ;
    objesrs.CAMT_Customer_Name__c=(CsvRecordData[3]);
    objesrs.CAMT_CustomerAddress__c=(CsvRecordData[4]);
    objesrs.CAMT_Payment_Date__c=Date.valueof((CsvRecordData[5]));

    system.debug('esrNoByESR.get(esrnum).Total_Amount__c=' + esrNoByESR.get(esrnum).Total_Amount__c);
    objesrs.Total_Amount__c = esrNoByESR.get(esrnum).Total_Amount__c;
    objesrs.Customer_Name__c = esrNoByESR.get(esrnum).Customer_Name__c;
    objesrs.Difference__c = esrNoByESR.get(esrnum).Difference__c;
    objesrs.Payment__c = esrNoByESR.get(esrnum).Payment__c;
    objesrs.Payment_Date__c = esrNoByESR.get(esrnum).Payment_Date__c;
    objesrs.Company_Name__c = esrNoByESR.get(esrnum).Company_Name__c;
    system.debug(camttotalAmount+'==='+esrNoByESR.get(esrnum).Total_Amount__c+'===='+(camttotalAmount-esrNoByESR.get(esrnum).Total_Amount__c).toPlainString());
    objesrs.Difference__c=camttotalAmount-esrNoByESR.get(esrnum).Total_Amount__c;
    objesrs.ESR_Status__c= 'Difference';
  //  objesrs.Test__c = Integer.valueof((CsvRecordData[0]).trim());

    upertToList.add(objesrs);

   }

   //////////////////////secanrio 6////////////////////
   /*if there is ESR Number is not matched to csv file number this else part will create new esr recordaccordingly */
   else if (esrNoByESR.keySet() != Null && esrNoByESR.containsKey(esrnum) && esrNoByESR.get(esrnum).Payment__c == 'Paid') {
    objesrs.id = esrNoByESR.get(esrnum).id;
    objesrs.Name = (CsvRecordData[1]);
    //objesrs.CAMT_ESR_Numberformula__c= camtesrnumber;//objesrs.Test__c = Integer.valueof((CsvRecordData[0]).trim());
    objesrs.CAMT_IDNUMBER__c=(CsvRecordData[0]);
    objesrs.CAMT_ESRNumber__c =(CsvRecordData[1]);
    objesrs.CAMT_TotalAmount__c = camttotalAmount;
    objesrs.CAMT_Customer_Name__c=(CsvRecordData[3]);
    objesrs.CAMT_CustomerAddress__c=(CsvRecordData[4]);
    objesrs.CAMT_Payment_Date__c=Date.valueof((CsvRecordData[5]));

    system.debug('esrNoByESR.get(esrnum).Total_Amount__c=' + esrNoByESR.get(esrnum).Total_Amount__c);
    objesrs.Total_Amount__c = esrNoByESR.get(esrnum).Total_Amount__c;
    objesrs.Customer_Name__c = esrNoByESR.get(esrnum).Customer_Name__c;
    objesrs.Difference__c = esrNoByESR.get(esrnum).Difference__c;
    objesrs.Payment__c = esrNoByESR.get(esrnum).Payment__c;
    objesrs.Payment_Date__c = esrNoByESR.get(esrnum).Payment_Date__c;
    objesrs.Company_Name__c = esrNoByESR.get(esrnum).Company_Name__c;

    objesrs.ESR_Status__c= 'Already Match';
    objesrs.Difference__c=0;
    upertToList.add(objesrs);
   }

   camtlist.add(objesrs);
  }

  system.debug('list==' + camtlist);
 // try{
  system.debug('coming' + upertToList);
  if (camtlist.size() > 0)
   update upertToList;
  system.debug('going out ' + upertToList);
 //  }
  /* Catch(Exception e){

    Apexpages.Message errorMessage =new Apexpages.Message(Apexpages.severity.ERROR,'An error is occured when importing data Please make sure input csv file is correct');

   Apexpages.AddMessage(errorMessage );
   }
   */
  // return null;
 }

 public PageReference  ExcelFileDownload() {

  exprots = true;
  return null;
 }

}

//////////////////visualforce page////////////

<script>
    function refersh(){
        var url = window.location.href;
        window.location = url;
    }
</script>

<apex:form >
    <apex:pagemessages />
    <apex:pageBlock >
        <apex:pageBlockSection columns="4" >
              <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
              <apex:commandButton value="Import CAMT File" action="{!importCSVFile}" rendered="{!camtlist.size!=Null}" disabled="{!IF((camtlist.size>0 ), true, false)}"/>
            <!--<apex:commandButton value="Download Excel" action="{!ExcelFileDownload}" /> -->
      </apex:pageBlockSection>
       <apex:outputText value="{!trno}"></apex:outputText>
    </apex:pageBlock>
    <apex:pageBlock rendered="{!camtlist.size>0}">
       <apex:pageblocktable value="{!camtlist}" var="cam">

            <!--- CAMT File Uploaded --->
         <!---  <apex:column value="{!cam.Name}" headerValue="ESR Number"/>
           <apex:column value="{!cam.CAMT_ESRNumber_optional__c}" headerValue="CAMT ESR Number"/>
           <apex:column value="{!cam.Status__c}" headerValue="CAMT Status"/>  --->

         <apex:column value="{!cam.CAMT_IDNUMBER__c  }" headerValue="CAMT ESR ID"/>
       <!--- <apex:column value="{!cam.CAMT_ESR_Numberformula_del__c}" headerValue="CAMT ESR ID"/> --->
         <apex:column value="{!cam.CAMT_ESRNumber__c}" headerValue="CAMT ESRNUmber"/>
          <apex:column value="{!cam.CAMT_TotalAmount__c}" headerValue="CAMT Total Amount"/>
          <apex:column value="{!cam.CAMT_Customer_Name__c}" headerValue="CAMT Customer Name"/>
          <apex:column value="{!cam.CAMT_CustomerAddress__c}" headerValue="CAMT Customer Address" />
           <apex:column value="{!cam.CAMT_Payment_Date__c}" headerValue="CAMT Payment Date"/>

         <!--- <apex:column value="{!cam.CAMT_Upload_Date_File__c}" headerValue="CAMT:Upload Date File" />--------->
         <!---<apex:column value="{!cam.CAMT_Payment__c}" headerValue="CAMT:CAMT Payment" />--->
         <!--- <apex:column value="{!cam.CAMT_CustomerAddress__c}" headerValue="CAMT Customer Address" /> --->

          <!---- Fetch Data From Data Base --->

         <apex:column value="{!cam.ESR_Status__c}" headerValue="Process Match" />
          <apex:column value="{!cam.Name}"  headerValue="ESRNumber"/>
          <apex:column value="{!cam.Total_Amount__c}" headerValue="Total Amount"/>
          <apex:column value="{!cam.Customer_Name__c}" headerValue="Customer Name"/>
          <apex:column value="{!cam.Customer_Address1__c}" headerValue="Customer Address" />
        <apex:column value="{!cam.Company_Name__c}" headerValue="Company Name" />
         <apex:column value="{!cam.Payment__c}" headerValue="Payment" />
          <apex:column value="{!cam.Payment_Date__c}" headerValue="Payment Date" />
          <apex:column value="{!cam.Difference__c}" headerValue="Difference" />

         <!--- <apex:column headerValue="Adress">

          <apex:outputText value="{!cam.Customer_Address1__c}">
          </apex:outputText>
          </apex:column>  --->

    </apex:pageblocktable>

        <apex:pageBlockButtons >
            <apex:actionregion >
                <apex:commandButton value="Download Excel" action="{!ExcelFileDownload}" rendered="{!camtlist.size>0}" />
                <input type="button" class="btn" value="Clear" onclick="refersh();" style="{!IF((camtlist.size>0 ), '', 'display:none')}"/>
            </apex:actionregion>
        </apex:pageBlockButtons>
 </apex:pageBlock>


text:
Q: Android Studio fails building project in task mergeDebugResources I'm trying to move my project from Eclipse to Android Studio.
After creating all the modules (the app has a few library project), Gradle fails with this error all the time:
Error:Execution failed for task ':AppLib:mergeDebugResources'.
> Unsupported type 'database' in file C:\Android\Code\AS_workspace\SuperApp\Infra\src\main\res\values\database.xml

This XML file is defined in a library project and is overridden with the same name in the app module.
Needles to say this works perfectly well in Eclipse for ages...
Any idea?
Thanks.
Adding the build.gradle files:
This is the app file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"

    defaultConfig {
        applicationId "com.app.superapp"
        minSdkVersion 10
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':library1')
}

This is the file for module :library1 which is an android library:
apply plugin: 'com.android.library'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"
    defaultConfig {
        minSdkVersion 10
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':library2')
}

This is the file for module :library2 which is also a library:
apply plugin: 'com.android.library'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"
    defaultConfig {
        minSdkVersion 10
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':AppLib')
}

And now for the library for AppLib:
apply plugin: 'com.android.library'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.1"
    defaultConfig {
        minSdkVersion 10
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':GooglePlayServices')
    compile project(':facebook')
}

I have a lot of libraries but once I'll fully understand Gradle's flavor I'll be able to decrease them to two modules.
Database.xml in the AppLib is:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="NAME" format="string" type="database"/>
    <item name="TABLE_NAME" format="string" type="database"/>
    <item name="DATABASE_VERSION" format="integer" type="database">101</item>
    <item name="MIN_APPLICATION_DATABASE_VERSION" format="integer" type="database">10</item>

</resources>

Database.xml in the SuperApp just adds the strings.

A: https://code.google.com/p/android/issues/detail?id=52962
above deals with transitive library dependencies. Its long , not quite exactly to your point  over the collision on a name value, but you may want to check it out .
I would try using the project import dialog in AS 0.8.14+ which is pretty good with transitive dependencies among Libraries... Dont worry about coding the 'build.gradles' and their details. Rather let the importer give it a whack and then, if it will not build sucessful, go back to the details on the issue link above and try something like:
 releaseCompile project(path: '..:$Path-to-Library1', configuration: 'release')
 debugCompile project(path: '..:$Path-to-Library1', configuration: 'debug')

and same for your 'Library2'
Assumes:  that your eclipse.project.properties like below to guide AS importer...
android.library.reference.1=../Library1

A: I think you need to specify using a newer gradle version in your app build.gradle.
Ex:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4.3'

    }
}

Older gradle versions give the mergeDebugResources error a lot more often.

A: This apparently happens because android studio doesn't go well with "custom" type like I put "database".
After making it to strings and integers I worked.
Don't know why in Eclipse it's OK but AS complains.


text:
Q: Reading and Writing XML file I have an Application in which first I want to create a backup of message from inbox and store it into backup.xml file which is stored at SDCARD/MYBACKUP/mybackup.xml
Now I want to retrieve data, stored on SDCARD/MYBACKUP/mybackup.xml  and display all messages in listview.

A: For Writing XML file to sdcard see this answeer Qberticus's Answer
android Reading file is just simple you have to use Xml parsing See This for XML parsing
To R/W Sdcard You have to give Permission
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


text:
Q: How to add new option in Discount type woo commerce Coupon module
If I choose Fixed product price and enter a Coupon amount each product should have its price set to that price.
Example : suppose we have a product that costs $100 each. Then I add the OFFER-20 coupon and use the Fixed product price discount type. Then I change the coupon amount to $20. If an user adds 3 products to the shopping cart, each product will cost $100 and the total will be $300. When the user applies the OFFER-20 coupon, each product should change to $20 and the total amount should be $60

A: You can use woocommerce_coupon_discount_types action hook for new discount type. check the below code. code will go in your active theme functions.php file.
function custom_discount_type( $discount_types ) {
    $discount_types['fixed_product_price'] = __( 'Fixed product price', 'woocommerce' );
    return $discount_types;
}
add_filter( 'woocommerce_coupon_discount_types', 'custom_discount_type', 10, 1 );

Tested and works.


text:
Q: Creating database connection in module.php file zf2 I have a onBootstrap method in module.php file. I want to use this function to also store user log details into the mysql db. Not able to use persist and flush methods. Any thoughts, how to create a db connection?
Thanks in advance
public function onBootstrap(MvcEvent $e)
{
    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
    $eventManager->attach('finish', array($this, 'outputCompress'), 100);

    $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
    $controller = $e->getTarget();
    $app = $e->getApplication();
    $sm  = $app->getServiceManager();
    $auth = $sm->get('zfcuser_auth_service');
    $routeMatch = $e->getRouteMatch();
   // $name = $auth->getresolvedIdentity('id');
    //echo "<pre>"; var_dump($auth); var_dump($routeMatch);
   if($routeMatch && $auth){
        $Userlog = new Userlog();
        $Userlog->setUserid(10);
        $Userlog->setUsername('abc');
        $Userlog->setUrl_loaded('xyz');
        $this->getObjectManager()->persist($Userlog);
        $this->getObjectManager()->flush();
    }


text:
Q: is it ever allowed (or trappable) to pass an undefined variable into a python function? I'm looking for the behavior where a function can accept an arbitrary and possibly undefined variable as an argument.  If the variable passed in actually exists, do something.  If that variable does not exist (i.e. is undefined), do something else.
I can implement this by wrapping the function call that uses the possibly undefined variable in a try/except block to catch a NameError, but what I really want is to do this INSIDE the function itself, rather than having to wrap every time I call the function.
Is this even a thing in Python?
def func(foo, bar):
    print(f"I like {foo} and {bar}")

def func2(foo, bar):
    try:
        print(f"I like {foo} and {bar}")
    except NameError:
        print(f"I like {foo} and I just made up a value for -- {whatever was passed} --")

a = 'Mike'

Ideally, if a user called the function like this:   func2(a, purple['people'].eaters) the output would be:
I like mike and I just made up a value for  -- self.purple['people'].eaters --

A: This is not possible in python because the arguments are evaluated by the caller not the function being called, so the exception can't be caught inside the function.
One way of doing this would be to pass in a string, which would then be evaluated by the function, like this:
def func2(foo, bar):
    try:
        print(f"I like {foo} and {eval(bar)}")
    except NameError:
        print(f"I like {foo} and I just made up a value for -- {bar} --")

func2(a, "purple['people'].eaters")


text:
Q: NetworkX: Approximate/Inexact Subgraph Isomorphism For Undirected Weighted Graphs Given two graphs (A and B), I am trying to determine if there exists a subgraph of B that matches A given some threshold based on the difference in edge weights. That is, if I take the sum of the difference between each pair of associated edges, it will be below a specified threshold. The vertex labels are not consistent between A and B, so I am just relying on the edge weights.
A will be somewhat small (e.g. max 10) and B will be larger (e.g. max 200).

A: I believe one of these two packages may help:
The Graph Matching Toolbox in MATLAB "implements spectral graph matching with affine constraint (SMAC), optionally with kronecker bistochastic normalization". It states on the webpage that it "handles graphs of different sizes (subgraph matching)"
http://www.timotheecour.com/software/graph_matching/graph_matching.html
The algorithm used in the Graph Matching Toolbox in MATLAB is based on the algorithm described in the paper by Timothee Cour, Praveen Srinivasan, and Jianbo Shi titled Balanced Graph Matching. The paper was published in NIPS 2006.
In addition, there is a second toolkit called Graph Matching Toolkit (GMT) that seems like it might have support for error-tolerant subgraph matching, as it does support error-tolerant graph matching. Rather than using a spectral method, it has various methods of computing edit distance, and then it is my impression that it finds the best matching by giving the argmax of the minimum edit distance. If it doesn't explicitly support subgraph matching and you don't care about efficiency, you might just search all subgraphs of B and use GMT to try to find matches of those subgraphs in A. Or maybe you could just search a subset of the subgraphs of B.
http://www.fhnw.ch/wirtschaft/iwi/gmt
Unfortunately neither of these appear to be in Python, and they don't seem to support networkx's graph format either. But I believe you may be able to find a converter that will change the representation of the networkx graph's to something usable by these toolkits. Then you can run the toolkits and output your desired subgraph matchings.


text:
Q: Java interface & I can't understand what is it??
interface A{
    void foo();
}
interface B{
    void foo();
}

then what is the result of (A & B)
        System.out.println((A & B) () -> {
            System.out.println("1");
            System.out.println("2");
        });

Could someone help me?

A: A & B is an intersection type. An object of this type can act as both an A and as a B.
This particular intersection type also happens to be a "functional interface" type, which means that it only has 1 abstract method. This lets you instantiate an object of this type using a lambda-expression. A & B is a "functional interface" type because both A and B have the foo-method with the exact same type signature.
So that is what this code means. You are instantiating an object of type A & B, implementing the foo-method with the lambda-function.
(A & B) () -> {
  System.out.println("1");
  System.out.println("2");
}

The System.out.println will just print out this lambda object using it's toString-method. Note that it will not call the actual foo-method. Your code will therefore just print out something similar to this: Main$$Lambda$1/1642360923@1376c05c


text:
Q: How to chain checks in java Consider a class like the following
public class MyClass {

    private Integer myField;
    private Result result;
    // more global variables

    public MyResult check(Integer myParameter) {
        init(myParameter);

        if (myField < 0) {
            result.setErrorMessage("My error message");
            return result;
        }

        // a lot more 'checks' like above where something may be written
        // to the error message and the result gets returned.
    }

    private void init(Integer myParameter) {
        result = new Result();
        result.setExistsAnnouncement(/*search a certain object via crudService with myParameter*/);
        // initialize other global variables including myField
    }

}

The problem is that the check method above is way too long and has many  return statements. I thought of some refactorings but am still unsure what to do. I was thinking about something like a chain-pattern. I would then implement several checker-classes who either call the next checker in the chain or return result with a corresponding errorMessage.
But then I had an even better idea (at least I think so): Why not behave like java 8? I thought of using something like Try-Success-Failure-Pattern. But I have no clue how to realize this. I am thinking of something like:
entrancePoint.check(firstChecker)
    .check(secondChecker)
    .check // and so on

The idea would be: When check fails, it would behave like Optional.map() and return something like an Optional.EMPTY (or in this context something like a Failure). When check is successful it should go on and do the next check (return a Success).
Do you have any experience in doing something like this?

A: When we think about validation, it is generally a Composite pattern. It broadly is depicted as:
If THIS is valid, then do SOMETHING.
And as you are imposing, you want to chain up multiple checkers in a chain to perform validation in their area, you can implement a Chain of Responsibility pattern.
Consider this:
You can have a Result Object, that can contain a message about failure as well as simple true/false.
You can have a Validator Object, that does whatever validation is required and returns an instance of Result.
public interface Result {
    public boolean isOk();
    public String getMessage();
}

// We make it genric so that we can use it to validate
// any type of Object that we want.
public interface Validator<T> {
    public Result validate(T value);
}

Now when you say that you want to validate 'X' using multiple checkers, you're imposing a Validation Rule that is nothing but a collection of Validator objects while being an instance of Validator itself. That being said, you can no more use the Result object to check the validation result of your rule. You will need a composite Result object that can keep the results as {Validator=Result}. Doesn't it look like an implementation of HashMap<Validator, Result>? Yes, because it is.
Now you can implement your Rule and CompositeResult as:
public class Rule extends ArrayList<Validator> implements Validator {

    public Rule(Validator<?> ... chain) {
        addAll(Arrays.asList(chain));
    }

    public Object validate(Object target) {
        CompositeResult result = new CompositeResult(size());
        for (Validator rule : this) {
            Result tempResult = rule.validate(value);
            if (!tempResult.isOk())
                result.put(rule, tempResult);
        }
        return result;
    }
}

public class CompositeResult extends HashMap<Validator, Result> implements
        Result {

    private Integer appliedCount;

    public CompositeResult(Integer appliedCount) {
        this.appliedCount = appliedCount;
    }

    @Override
    public boolean isOk() {
        boolean isOk = true;
        for (Result r : values()) {
            isOk = r.isOk();
            if (!isOk)
                break;
        }
        return isOk;
    }

    @Override
    public String getMessage() {
        return toString();
    }

    public Integer failCount() {
        return size();
    }

    public Integer passCount() {
        return appliedCount - size();
    }

}

And that's it! Now, to implement your checkers:
public class Checker1 implements Validator<Integer> {
    /* Implementation */
}

public class CheckerN implements Validator<Integer> {
    /* Implementation */
}

And it's time to do the validation:
Validator<Integer> checkingRule = new Rule(new Checker1(), new CheckerN());
CompositeResult result = checkingRule.validate(yourParameter);
if (result.isOk())
    System.out.println("All validations passed");
else
    System.out.println(result.getFailedCount() + " validations failed");

Easy and neat.
I have uploaded an example in my public repo for you to play around.

A: You could use Hibernate Validator (or another implementation of the JSR 303/349/380 Bean Validation standards).
Example user class that throws an exception when being instantiated with invalid arguments. You can check all the built in constraints in the docs
    public final class User {

      @NotNull
      private final String username;

      @NotNull
      private final String firstName;

      @NotNull
      private final String lastName;

      public User(String username, String firstName, String lastName) {
        this.username = username;
        this.firstName = firstName;
        this.lastName = lastName;

        MyValidator.validate(this);
      }
      // public getters omitted
    }

And the validator class:
import java.security.InvalidParameterException;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public final class MyValidator {

    public static void validate(Object object) {

      ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
      Validator validator = factory.getValidator();

      Set<ConstraintViolation<Object>> constraintViolations = validator.validate( object );

      if (!constraintViolations.isEmpty()) {
          ConstraintViolation<Object> firstViolation = constraintViolations.iterator().next();

          throw new InvalidParameterException("not valid "
          + object.getClass()
          + " failed property ' " + firstViolation.getPropertyPath() + " ' "
          + " failure message ' " + firstViolation.getMessage() + " ' ");
      }
    }
}

And message:

java.security.InvalidParameterException: not valid class
  com.foo.bar.User failed property ' firstName '  failure message ' may not be null '

Don't forget to include the dependency in your pom.xml (if you use Maven)
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.1.Final</version>
</dependency>


text:
Q: how to implemet database logic in tableview to controll rows information? My meaning is i want to implement the table from where i will get data from the database.I store all the data into database now the problem is i am not able to show this data in tableView as describe below.Also you can see the example that i want to develop table like chipottle Chipottle app. There is a  bag for created order list information.If you do not get my question then please see the chipottle app just create order it will store into bag in main view click on bag button you will see one table with all your created order information and in last subtitle.Please See the app it's totally free i really stuck into this problem so please try to help me.
I stored 10 fields in database
Ordername ={Order1,Order2}
category = {category1,category2}
submenu1 = {{sub00,sub01,sub02},{sub11,sub12}}
price1 = {{$2,$3.1,$4.2},{$7.85,$2.3}}
submenu2 = {{sub21,sub22,sub23,sub24},{sub31,sub32}}
price2 = {{$2.2,$4.5,$7.7,$3.2},{$4.4,$1.3}}
drinkmenu = {pepsi,pepsi1,soda,lemon,pinaplesoda}
dirnkprice = {$4.4,$8.5,$3.7,$2.8,$3.4}
I count the no. of section like =  [Ordername count] .also able to display the section title as per the Ordername.
Now i want to display category ,submenu1,price1,submenu2,price2 all at Zero(0) index means (at   indexpath.row = 0) all value as per the Ordername.
and for drinkmenu it is display on different different indexpath.row but after at zero index.
Thank You.
Please it is very urgent.

A: go through following link you will have your work done.
http://blog.webscale.co.in/?p=284
It is customization of UITableViewCell.
Hope it helps.

A: All you've got to do, is create a special order tableViewCell and put in your data, show it for indexPath.row == 0 only. Here is some example code:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)anIndexPath
{
    // sectioning logic here...

    if(anIndexPath.row == 0) {
        // Helper to create a fresh cell, implements dequeueing
        OrderTableViewCell *cell = [TableViewCellFactory orderTableViewCell:aTableView];

        // pass on the cell to do fill in data
        [self configureOrderCellWithCell:cell andIndexPath:anIndexPath];

        return cell;
    } else {
        // process other cells
    }
}

- (void)configureVideoClipCellWithCell:(VideoClipTableViewCell *)aCell andIndexPath:(NSIndexPath *)anIndexPath
{
    // get model at current indexPath
    Order *order = [orders objectAtIndex:anIndexPath.row];

    // publish data in cell
    aCell.category.text = order.category;
    aCell.submenu1.text = order.submenu1;
    aCell.price1.text = order.seprice1rie;
    aCell.submenu2.text = order.submenu2;
    aCell.price2.text = order.price2;
}