text:
Q: JLabel images array I am trying to load the same jlabel stored image twice into a gridlayout panel, however instead of creating two instances of the image, the image is only displayed once then moved.
How can I store the same JLabel position in the pieces array into more than one JLabel in the boardLabels array.
Thanks :)
public static JPanel boardPanel = new JPanel(new GridLayout(4, 0));
public static JLabel pieces[] = new JLabel[2];
private static JLabel[] boardLabels = new JLabel[4];

public MainFrame() {
    pieces[0] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece1.png"));
    pieces[1] = new JLabel(new ImageIcon(System.getProperty("user.dir") + "/images/piece2.png"));

    this.add(boardPanel);
    displayGUIboard();
}

public static void displayGUIboard() {

    //ERROR - the label in pieces[0] is not copied into both boardLabels [0] and [1]
    boardLabels[0] = pieces[0];
    boardLabels[1] = pieces[0];

    boardPanel.add(boardLabels[0]);
    boardPanel.add(boardLabels[1]);
}

public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.setVisible(true);
    frame.setSize(600, 600);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

This works
    boardLabels[0] = new JLabel(pieces[1]);
    boardLabels[1] = new JLabel(pieces[1]);

when using ImageIcons, but I want to avoid this since to update the board I will have to remove then reload the JLabels. I would prefer to just update the already loaded labels.
edit
I tried this before but it throws a null pointer exception...
    boardLabels[0].setIcon(pieces[1]);
    boardLabels[1].setIcon(pieces[1]);

    boardPanel.add(boardLabels[0]);
    boardPanel.add(boardLabels[1]);

A: Don't do this since you can't add the same component more than once to a visualized container. Better to use multiple JLabels but have them use the same ImageIcon. ImageIcons can be used more than once with ease:
public MainFrame() {
    pieceIcon[0] = new ImageIcon(System.getProperty("user.dir") +
        "/images/piece1.png");
    pieceIcon[1] = new ImageIcon(System.getProperty("user.dir") +
        "/images/piece2.png");

    this.add(boardPanel);
    displayGUIboard();
}

public void displayGUIboard() {
    boardPanel.add(new JLabel(pieceIcon[0]);
    boardPanel.add(new JLabel(pieceIcon[0]);
}

As an aside: note that none of your variables should be static.
Edit: regarding your recent edit:

This works

boardLabels[0] = new JLabel(pieces[1]);
boardLabels[1] = new JLabel(pieces[1]);

when using ImageIcons, but I want to avoid this since to update the board I will have to remove then reload the JLabels. I would prefer to just update the already loaded labels."

Solution
No you don't have to change JLabels at all. Keep your JLabels where they are, but simply swap the icons that they hold using the JLabel setIcon(...) method.
Edit
Also, don't confuse variables with objects. Even if you create a bunch of JLabel variables, if they all refer to the same JLabel object, you still can't add a JLabel object more than once to a container.
Edit  You state:

The code is a part of the display function for a game. An array of integers will represent the board which is interpreted (but not in the above code) and the correct Jlabel images will be placed into a gridlayout panel to display the gui of the board. I have gotten the display code to work fine, but in my current version it removes the jlabels from the board then creates new JLabels(piece...)... but i would prefer it to update itself from the integer array rather than removing the labels, reading the array, then recreating the labels.

So create a JPanel that uses GridLayout and fill it with unchanging JLabels. Then simply change the icons held by the JLabels based on the values held by the int array. You could create a method that simplifies and automates this process.
Edit regarding:

edit I tried this before but it throws a null pointer exception.

Then solve this as you would any NPE. Find out which line throws the NPE, check the variables on the line, at least one is null, and then fix it so that you initialize the variable before trying to use it.
Edit
for example:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;

import javax.swing.*;

@SuppressWarnings("serial")
public class GridExample extends JPanel {
   public static final int[][] MAP = {
      {1, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2},
      {1, 1, 0, 0, 2, 2, 2, 2, 2, 2, 2},
      {1, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2},
      {1, 1, 1, 0, 0, 2, 2, 2, 2, 2, 2},
      {1, 1, 1, 1, 0, 2, 2, 2, 2, 2, 2},
      {1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2},
      {1, 1, 0, 0, 0, 2, 2, 2, 2, 2, 2},
      {1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 2},
      {1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2},
      {1, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2},
      {1, 1, 1, 1, 1, 1, 0, 0, 0, 2, 2}
   };

   public static final Color[] COLORS = {};
   private JLabel[][] labelGrid = new JLabel[MAP.length][MAP[0].length];

   public GridExample() {
      setLayout(new GridLayout(MAP.length, MAP[0].length));
      for (int r = 0; r < labelGrid.length; r++) {
         for (int c = 0; c < labelGrid[r].length; c++) {
            labelGrid[r][c] = new JLabel();
            labelGrid[r][c].setIcon(Ground.getGround(MAP[r][c]).getIcon());
            add(labelGrid[r][c]);
         }
      }
   }

   private static void createAndShowGui() {
      GridExample mainPanel = new GridExample();

      JFrame frame = new JFrame("GridExample");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

enum Ground {
   DIRT(0, new Color(205,133, 63)), GRASS(1, new Color(0, 107, 60)),
   WATER(2, new Color(29, 172, 214));
   private int value;
   private Color color;
   private Icon icon;

   private Ground(int value, Color color) {
      this.value = value;
      this.color = color;

      icon = createIcon(color);
   }

   private Icon createIcon(Color color) {
      int width = 24; // how to use const in enum?
      BufferedImage img = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
      Graphics g = img.getGraphics();
      g.setColor(color);
      g.fillRect(0, 0, width, width);
      g.dispose();
      return new ImageIcon(img);
   }

   public int getValue() {
      return value;
   }

   public Color getColor() {
      return color;
   }

   public Icon getIcon() {
      return icon;
   }

   public static Ground getGround(int value) {
      for (Ground ground : Ground.values()) {
         if (ground.getValue() == value) {
            return ground;
         }
      }
      return null;
   }

}

Which shows a GUI grid:

A: For comparison, I've re-factored @HFOE's example so that Ground implements Icon and indexes the array returned by values(). As value is an implementation detail, int[][] MAP could instead be Ground[][] MAP.
Update: This variation illustrates Ground[][] MAP and adds TexturePaint.

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.*;

/** @see https://stackoverflow.com/a/11556441/230513 */
public class GridExample extends JPanel {

    public static final Ground[][] MAP = {
        {Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.WATER, Ground.WATER},
        {Ground.GRASS, Ground.DIRT, Ground.CITY, Ground.WATER, Ground.WATER},
        {Ground.GRASS, Ground.DIRT, Ground.CITY, Ground.WATER, Ground.WATER},
        {Ground.GRASS, Ground.DIRT, Ground.DIRT, Ground.DIRT, Ground.WATER},
        {Ground.GRASS, Ground.GRASS, Ground.DIRT, Ground.WATER, Ground.WATER},
    };
    private JLabel[][] labelGrid = new JLabel[MAP.length][MAP[0].length];

    public GridExample() {
        setLayout(new GridLayout(MAP.length, MAP[0].length));
        for (int r = 0; r < labelGrid.length; r++) {
            for (int c = 0; c < labelGrid[r].length; c++) {
                labelGrid[r][c] = new JLabel();
                labelGrid[r][c].setIcon(MAP[r][c]);
                add(labelGrid[r][c]);
            }
        }
    }

    private static void createAndShowGui() {
        GridExample mainPanel = new GridExample();
        JFrame frame = new JFrame("GridExample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowGui();
            }
        });
    }
}

enum Ground implements Icon {

    DIRT(new Color(205, 133, 63)), GRASS(new Color(0, 107, 60)),
    WATER(new Color(29, 172, 214)), CITY(Color.lightGray);
    private static final int SIZE = 42;
    private Random random = new Random();
    private TexturePaint paint;

    private Ground(Color color) {
        this.paint = initPaint(color);
    }

    private TexturePaint initPaint(Color color) {
        BufferedImage image = new BufferedImage(
            SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
        Rectangle2D.Double rect = new Rectangle2D.Double(0, 0, SIZE, SIZE);
        for (int row = 0; row < SIZE; row++) {
            for (int col = 0; col < SIZE; col++) {
                if (random.nextBoolean()) {
                    image.setRGB(col, row, color.getRGB());
                } else {
                    if (random.nextBoolean()) {
                        image.setRGB(col, row, color.darker().getRGB());
                    } else {
                        image.setRGB(col, row, color.brighter().getRGB());
                    }
                }
            }
        }
        return new TexturePaint(image, rect);
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(paint);
        g.fillRect(0, 0, SIZE, SIZE);
    }

    @Override
    public int getIconWidth() {
        return SIZE;
    }

    @Override
    public int getIconHeight() {
        return SIZE;
    }
}


text:
Q: How to free memory in the Perl I have daemon with children on perl. For daemonize i use Proc::Daemon. Control daemon and children connected to DB(DBI lib), childs collect mail via imap (Mail::IMAPClient lib) too. I undef all variables in code of children, but over time, a child who works more than anyone, consume a lot of memory. ps output:
user   16521  0.6  1.6 135560 16516 ?        S    10:47   0:54 perl remote_imap.pl
user   16523  0.2 20.0 331976 201764 ?       S    10:47   0:21 perl remote_imapd.pl 16521
user   16525  0.1  3.0 157792 30720 ?        S    10:47   0:09 perl remote_imapd.pl 16521
user   16527  0.1  3.0 157796 30704 ?        S    10:47   0:08 perl remote_imapd.pl 16521
user   16529  0.1  3.0 157796 30572 ?        S    10:47   0:09 perl remote_imapd.pl 16521
user   16531  0.1  3.0 157792 30612 ?        S    10:47   0:08 perl remote_imapd.pl 16521

for sleep i use usleep from Time::HiRes lib. In remote_imap.pl usleep(100000), In remote_imapd.pl - usleep(500000).
Why memory is not released, because I did andef for all variables (except id_connet to DB)? If you want, I'll add code.
Main daemon
remote_imap.pl
Child
remote_imapd.pl

A: Perl uses reference counting to manage it's memory space. When you declare a variable, a small amount is set aside. When you use it, more memory is occupied. Perl may reuse the memory space once a variable is no longer referenced at all.
That's why it's quite important to keep lexical scopes small, and avoid global variables - something global is 'in scope' throughout your code, even if it's only used once.
The gotcha is circular references. A circular reference never becomes unreferenced, so perl can't 'release' it automatically. That's also fairly easy to end up with inside objects - if part of an object has a reference to another part of the object.
That's why you have things like weaken().
I'll note in the examples you give above - the child process (why did you call the files the same thing?) you've lexically scoped:
my (@array, @is_ok, @params, $user_id, $user_remote_id, $is_delete, $error_count, $is_first, $server, $port, $login, $password, $is_ssl, $no_error, $error_text, $pid, $date, $date_up, $exists, $q, $sth, $rv);

Outside your while loop, and tried to 'tidy up' by:
(@array, @is_ok, @params, $user_id, $user_remote_id, $is_delete, $error_count, $is_first, $server, $port, $login, $password, $is_ssl, $no_error, $error_text, $pid, $date, $date_up, $exists, $q, $sth, $rv) = undef;

Out of interest - why are you doing this? Could you not scope them within your while loop, and then you won't need to reuse them? I don't know that's necessarily your problem though - it could quite easily be in one of the libraries you import. The fact that it's happening with the busier child implies that each loop something is getting to an array or object that's persisting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error while writing optimization constraint in cplex python api My goal is to write the following model using docplex.mp.model in python. which ptj takes binary variable {0,1}.
[summation from of Ptj from j=1 to t][t = 1,.....,8]

here is the code I wrote:
N = 8
(period_list = [t for t in range(1, no_of_period+1)])
(j = period_list)
p = Mode.binary_var_dict(period_list, name = 'p')
for t in period_list:
    for j in range(1,t+1):
        Model.add_constraints(Model.sum(p[t,j]) == 1)

but I got an error. Could anyone help me with this problem please?

A: Your code has numerous issues.
First, you need to create one instance of docplex.mp.model.Model to add constraints to: all your calls to Model.<fn> should be rewritten as mdl.<fn> as they are instance methods.
Second, the variable dict you create has periods as keys, that is, 1,2,..P
so querying p[t,j] is sure to crash with KeyError. If you need a square matrix of variables for each couple of periods, use Model.binary_var_matrix.
Third: Model.add_constraints (with a final S) expects an iterable, but you are passing one constraint, this is also sure to crash.
Lastly, using ranges starting at 1 is not the simplest nor the safest choice with Docplex.
Here is a code, freely derived from your sample, which I guess is close to what you need:
pr = range(1, no_of_period+1)
from docplex.mp.model import Model
m = Model()
p = m.binary_var_matrix(pr, pr, name = 'p')
m.add_constraints( (m.sum(p[t,j] for j in pr) == 1) for t in pr)
print(m.lp_string)

and the output is:
Minimize
 obj:
Subject To
 c1: p_1_1 + p_1_2 + p_1_3 = 1
 c2: p_2_1 + p_2_2 + p_2_3 = 1
 c3: p_3_1 + p_3_2 + p_3_3 = 1

[..snip..]


text:
Q: Reference request for discrete subgroups of matrix Lie groups and their representations I studied representation theory of Lie groups and Lie algebras from the book by Brian Hall. I'm now curious about the formulation of the theory for discrete subgroups of Lie groups, mostly matrix Lie groups. Are there any good references on the subject?

A: There is a large literature on discrete subgroups of Lie groups. Here are only a few examples.
Discrete subgroups of Lie groups: M. S. Raghunathan
Discrete Subgroups of Lie Groups | Madabusi S
Discrete Subgroups of Semisimple Lie Groups | G. A. Margulis.


text:
Q: Access dynamically added elements var $singleMember = '

';

$singleMember.attr('href',member.link);
$singleMember.children('.avatar').attr('src',member.avatar);
$singleMember.children('.username').html(member.name);

Why does this throw "undefined is not a function"?

A: var $singleMember is just a string and therefore .attr() and .children() will not work (hence the error you are seeing)
switch it to:
   var singleMember = '

';
   var $singleMember = $(singleMember);

   $singleMember.attr('href',member.link);
   $singleMember.children('.avatar').attr('src',member.avatar);
   $singleMember.children('.username').html(member.name);


text:
Q: Помогите пожалуйста создать базу данных для онлайн кинотеатра В общем у меня 4 таблицы: профили пользователей, каталог фильмов, подписки и история просмотров. Никак не пойму, как правильно связать несколько фильмов к одной определенной подписке.
Подписку к профилю, историю просмотров к каталогу фильмов и к профилям пользователей.

A: Создайте таблицу с полями "ИдФильма" и "ИдПодписки".
Еще одну таблицу с полями "ИдПодписки" и "ИдПрофиля".
И таблицу с полями "ИдФильма" и "ИдПрофиля".

A:
По поводу подписки мне не совсем понятно как должно работать(знать бы структуру таблиц и как должно работать), с ходу вот такое получилось. Будут какие то дополнения по функционалу и наполнению, можно развивать.


text:
Q: Click on element containing text in puppeteer I am having trouble clicking an element from a dropdown list dynamically loaded after another click.
In the console of chrome, I am doing this by
$('.save-to-list-dropdown__trigger').click()

then
$( "div:contains('textcontained')" ).click()

However, I need this to be done by puppeteer.
I have tried
await page.$eval('.save-to-list-dropdown__trigger', form => form.click());

then
const linkHandlers = await page.$x("//div[contains(text(), 'textcontained')]");

but linkHandlers remains lenght 0.
This is the HTML of the dropdown

<svg viewBox="0 0 24 24" width="24px" height="24px" x="0" y="0" preserveAspectRatio="xMinYMin meet" class="artdeco-icon" focusable="false"><path d="M14,9H9v5H7V9H2V7H7V2H9V7h5V9Z" class="small-icon" style="fill-opacity: 1"></path></svg>

      Create  list

      My saved leads

            Your Custom Lists:

Editors

                        (26)

A: Maybe the element's not loaded yet. You could wait for that xpath.
const linkHandlers = await page.waitForXPath("//div[contains(text(), 'My saved leads')]");

waitForXPath will not only wait but return that element.

A: here
 is another way to do it , in this example .item is class of divs you can use other selectors
//wait for elements to appear on the page
await page.waitForSelector('.item' , {  visible: true , timeout: 0 });

// capture all the items
let elements = await page.$$('.item');
// loop trough items
for (let i = 0; i < elements.length; i++) {

    let  text  = await page.evaluate(el => el.innerText, elements[i]);
    if(text.indexOf("My saved leads") > -1 )
    {
         await elements[i].click();
    }
}

A: You have to trigger a double while on the click function

A: With help, I have solved it like this.
const [linkHandler] = await page.$x("//div[contains(., 'textcontained')]");
                if(linkHandler)
                {
                    await linkHandler.click();
    }


text:
Q: natural log of pi to sixty digits, a reference needed I have found a table of the logs of gamma functions at basic fractions, accurate to 60 decimal digits.  It omits $\ln(\Gamma(1/2)) = \ln(\pi)/2$ and I want that number.
Where is a cit-able source that contains this this number to high accuracy?

A: Project Gutenburg has published a compilation of 'Miscellaneous Mathematical Constants' which includes the natural log of pi to 2000 decimal places as:
log(Pi) natural logarithm of Pi to 2000 places.
1.1447298858494001741434273513530587116472948129153115715136230714721377698848
260797836232702754897077020098122286979891590482055279234565872790810788102868
252763939142663459029024847733588699377892031196308247567940119160282172273798
881265631780498236973133106950036000644054872638802232700964335049595118150662
372524683433912698965797514047770385779953998258425660228485014813621791592525
056707638686028076345688975051233436078143991414426429596712897781136526452345
041059007160818570824981188183186897672845928110257656875172422338337189273043
288217348651042761532375161028392221340143696717585616442473718780506046692056
283377310133621627451589875201512996545465739691528252391695852453793594601400
379956519666036538000112659858500129765699060744667455472671045084950668558743
390774251341592412652317771784917799588095767880510296444750901508911403278080
768337337938949488075152890091875363766086707435833345108139232535574067684327
431198049633999761803046221286361595859836404758009861799938264629277646275948
484896414107483132593462053635073046055030768215494444154778884559535228440047
850918217255915179900785243523837112867132342905566964492585582623118824223244
661476739136153339414264534600881979155478967757529878307593230499751706785370
666315222134751026417324918906534257373051835228316776877311442944368108997522
287634554909933469253981028398378467695079971965163008386496663274223886761392
944112379606529081463545502415193643368404005225615575618053680459613160686367
226297126848055518038239624057983138433955882483556816617339018195508924667782
042898879384623081953507082523699065543916029676565349509487102686726405036344
889957813954840804697878603723560031033518890166410542245140400821480026071893
924502077785635698810693233664357379481092927781936265980614204270094398298364
733767922501305495445975380037647617519082652294857728828349379913418698964043
483457091550460629912859614271432256377699794328889523074041463529466113313641
884192574888189320796571991444939402534883228262813
Source: http://www.gutenberg.org/files/634/634.txt

A: Here it is, to 80 digits.
0.57236494292470008707171367567652935582364740645765578575681153573606\
888494241304
Youcan cite me, "personal communication".

A: I know that you are asking for a table or software where you can just look this up, but this number is quickly computable to high accuracy with the right approach. (Assuming that you have an engine that can keep track of high precision in the first place.)
To speed up computations, use that $$\ln(\pi)=\ln\left(\frac{\pi}{22/7}\right)+\ln(2)+\ln(11)-\ln(7)$$ The latter three terms can be looked up to high precision, and now you have to find $\ln(7\pi/22)$, where $7\pi/22$ is very close to $1$. In fact $|1-7\pi/22|<0.00041$. So even the slowly converging Taylor series for $\ln$ can output a result quickly, assuming that you again use a table, this time to look up many digits of $\pi$.
$$\begin{align}
\ln(1+(7\pi/22-1)) & = -\sum_{n=1}^\infty\frac{(-1)^n}{n}(7\pi/22-1)^n
\end{align}$$
Since $(7\pi/22-1)<0$, we do not really have an alternating series, and we'll have to think about Taylor's error bound. The $n+1$st derivative of $\ln(1+x)$ is $(-1)^{n}n!/(1+x)^{n+1}$. On the interval $[-0.00041,0.00041]$, this is bounded in absolute value by $n!/0.99959^{n+1}$. So an error bound for the $n$th partial sum would be $$\frac{n!/0.99959^{n+1}}{(n+1)!}0.00041^{n+1}=\frac{1}{n+1}\left(\frac{0.00041}{0.99959}\right)^{n+1}$$ Using $n=17$ brings this under $10^{-62}$.
At present, I do not have access to an engine that could keep track of enough decimal precision, or else I would conclude my answer with the end result of this process. But here is the formula it yields, with an absolute error bound of less than $10^{-62}$:$$\ln(\pi)\approx-\sum_{n=1}^{17}\frac{(-1)^n}{n}(7\pi/22-1)^n+\ln(2)+\ln(11)-\ln(7)$$

A: (In know this question is old and answered, but...) For $\ln(\pi)$ the Online Encycolpedia of Integer Sequences has a value to 105 decimal places. It is also citable.


text:
Q: Login to website using Google Apps script Login in to a website using Google Apps Script has been discussed here previously and I most probably have seen them all and tried them all. But nothing seems to work. I must oversee something and would appreciate your help.
I am trying to login to this website https://teslaclub.ch/clubdesk/www?action=login&
As it looks like the relevant login information is the following:

<form method="post" action="www" accept-charset="UTF-8">
    <input type="hidden" name="action" value="login">
<input type="hidden" name="redirectUrl" value="HxgrZFvkpAK4n-IGMS4gSQ">

            Benutzername:
            <input id="userId" name="userId" type="text" value="my login name comes here">

            Passwort:
            <input id="password" name="password" type="password">

                    Zugang anfordern

                    Passwort vergessen/
                ändern
                <input style="float: right;" type="submit" value="Anmelden">

</form>

I am trying to login like this (which i took from other examples and modified it):

function loginToSite(){
  var url = "https://teslaclub.ch/clubdesk/www?action=login&"; //change this.
  var payload = {
    "userId":"my login name comes here", //change this.
    "password":"my password comes here" //and change this. done. no need to enter anything elsewhere.
  };
  var opt = {
    "payload":payload,
    "method":"post"
  };
  var response = UrlFetchApp.fetch(url, opt);
  if ( response.getResponseCode() == 200 ) { //could not log in.
    var result = "Couldn't login. Please make sure your username/password is correct.";
  }
  else if ( response.getResponseCode() == 303 ) { //login was successful. you might receive 302 response code as well depending upon the site. So try changing it to 302.
     var result = "Logged in successfully";
     var cookie = response.getAllHeaders()['Set-Cookie'];
     var header = {
       'Cookie':cookie[1] //taking the second cookie because when redirected, a new cookie is set. If the page does not redirect, you might need to use cookie[0] here. Try it out yourself!
     };
  }
Logger.log(result);
}

I always get a 200 response back. Therefore I think I am missing a function to "press" the login (Anmelden) button. But I am not sure how I could do that.
Your help would be highly appreciated.
Heinz


text:
Q: Spring BeanPostProcessor not get called its implemented bean , but invoke for all other beans my bean.xml
hi friends.., i am just learning spring . i implement the interface  BeanPostProcessor in HelloWorld.java . its methods invoked for all other beans , but not itself(Helloworld.java bean)
 <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" >     </bean>
   <!-- Definition for textEditor bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <property name="spellChecker" ref="spellChecker"/>
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

Helloworld.java
public class HelloWorld implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {

        System.out.println();
        System.out.println(bean.getClass().getName() +"---------------"+name+"--->This is after bean initialized ");

        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {

        System.out.println(bean.getClass().getName() +"---------------"+name+"----------->This is before bean initialized ");

        return bean;
    }
}

main program
public class MainApp {
    public static void main(String arg[])throws Exception{
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");

    }
    }

my output is
com.tutorialspoint.SpellChecker---------------spellChecker----------->This is before bean initialized

com.tutorialspoint.SpellChecker---------------spellChecker--->This is after bean initialized

com.tutorialspoint.TextEditor---------------textEditor----------->This is before bean initialized

com.tutorialspoint.TextEditor---------------textEditor--->This is after bean initialized

why BeanPostProcessor interface methods not invoked for  HelloWorld.java  ..,but invoked for  other unrelated beans which is not implementing BeanPostProcessor interface ..?

A: any bean implementing BeanPostprocessor works as bean postprocessor for all beans.Please refer URL for more details.It is clearly mentioned that ApplicationContexts can autodetect BeanPostProcessor beans in their bean definitions and apply them to any beans subsequently created. **Plain bean factories allow for programmatic registration of post-processors, applying to all beans created through this factory**.
Do you want a specific bean having some initializing code then implement InitializingBean as below
package org.studyspring.beanfactory
public class HelloWorld implements InitializingBean {
        private String name;

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println(this.getClass().getName() +"---------------name = "+name+"--->This is after bean initialized ");
        }
    }

add entry for this bean in XML
 <bean id="helloWorld" class="org.studyspring.beanfactory.HelloWorld">
        <property name="name" value="Shirish"/>
    </bean>

or alternatively you can have init and destroy methods for each bean as below
package org.studyspring.beanfactory;

import org.springframework.beans.factory.InitializingBean;

public class HelloWorld1  {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void init() throws Exception {
        System.out.println(this.getClass().getName() +"---------------name = "+name+"--->This is before bean initialized");
    }

    public void destroy() throws Exception {
        System.out.println(this.getClass().getName() +"---------------name = "+name+"--->This is after bean destroyed ");
    }
}

register your bean as below in XML
<bean id="helloWorld1" class="org.studyspring.beanfactory.HelloWorld1" init-method="init" destroy-method="destroy">
    <property name="name" value="Shirish"/>
</bean>

Additionally if you follow common practice for naming init & destroy methods then you can define those methods in <beans> as below
<beans default-init-method="init" default-destroy-method="destroy">

with above the beans which have init and destory methods available they will be called upon initialization and destructions of those beans


text:
Q: The specified blob does not exist - Shows in azure browser - but when I click download does not exist I've uploaded some blobs to azure.
They show in the browser when I log in, but when I attempt to download them I get following message:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
BlobNotFound
<Message>
The specified blob does not exist. RequestId:d3cd1a18-1e48-47bd-9985-4ab7e655eed2 Time:2013-09-19T15:02:16.4158548Z
</Message>
</Error>

Screenshot browsing (showing the blobs)
Screenshot showing what happens after I click download

A: I think I know why you're running into this issue. I believe its an issue with the portal. If you notice, the name of your blob is: Tommy French Toals.North Street.1250251 and it contains spaces. However if you look at the URL the name is coming as: Tommy%2520French%2520Toals.North%2520Street.1250251. Notice the presence of %2520. What portal software is doing is that it is performing URL encoding twice - first, it URL encodes space in the blob name to %20 and then again URL encodes the % sign to %25 and this is messing things up for you.
Just to be double sure, I uploaded a file which contains spaces in its name in my storage account and when I try to download the blob through the portal, it failed with the same error as yours. Then I created a SAS URI for the same blob using storage client library, and it worked perfectly fine. Here's the code I used for creating SAS URI:
        CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("myaccount", "myaccountkey"), true);
        var blobContainer = storageAccount.CreateCloudBlobClient().GetContainerReference("mycontainer");
        var blob = blobContainer.GetBlockBlobReference("this file has spaces in its name.txt");
        var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
        {
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
            Permissions = SharedAccessBlobPermissions.Read,
        });
        var sasUrl = blob.Uri.AbsoluteUri + sas;

Try downloading a file which does not contain spaces or any special characters in its name and it should work just fine.

A: Go and Edit container meta data on azure bolb storage. change access private to public.
Azure blob storage container edit page

A: I was able to make it work by:

*

*Opening the Azure Storage App and navigating to the container / blob

*Right-click the blob and selecting "Properties..."

*Copy/paste the text after the server path from the URL

For example, if the URL shows as: https://<storageaccount>.windows.net/somecontainer/someblob
The text to copy/paste would be: somecontainer/someblob

A: check file name, its case sensitive. after correcting case it started working for me.


text:
Q: How to detect system information like os or device type The most important things I want to know are the device type, the OS version, if it has a hardware keyboard and maybe the screen resolution. but if you know other useful debug information please add them :)
I found this for the OS version:
string += "OS Version: " + System.getProperty("os.version");

How do I get the other properties?

A: you can try this >
import android.os.Build;
import android.os.StrictMode;
import android.provider.Settings;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utilies {

    public static String android_id = Settings.Secure.getString(App.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);

    public static void getInternet() {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    public static String readKernelVersion() {
        try {
            Process p = Runtime.getRuntime().exec("uname -a");
            InputStream is = null;
            if (p.waitFor() == 0) {
                is = p.getInputStream();
            } else {
                is = p.getErrorStream();
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(is), 1024);
            String line = br.readLine();
            br.close();
            return line;
        } catch (Exception ex) {
            return "ERROR: " + ex.getMessage();
        }
    }

    public static String getDeviceModelNumber() {
        String manufacturer = Build.VERSION.CODENAME;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    private static  String capitalize(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }
    // get System info.
    public static String OSNAME = System.getProperty("os.name");
    public static String OSVERSION = System.getProperty("os.version");
    public static String RELEASE = android.os.Build.VERSION.RELEASE;
    public static String DEVICE = android.os.Build.DEVICE;
    public static String MODEL = android.os.Build.MODEL;
    public static String PRODUCT = android.os.Build.PRODUCT;
    public static String BRAND = android.os.Build.BRAND;
    public static String DISPLAY = android.os.Build.DISPLAY;
    public static String CPU_ABI = android.os.Build.CPU_ABI;
    public static String CPU_ABI2 = android.os.Build.CPU_ABI2;
    public static String UNKNOWN = android.os.Build.UNKNOWN;
    public static String HARDWARE = android.os.Build.HARDWARE;
    public static String ID = android.os.Build.ID;
    public static String MANUFACTURER = android.os.Build.MANUFACTURER;
    public static String SERIAL = android.os.Build.SERIAL;
    public static String USER = android.os.Build.USER;
    public static String HOST = android.os.Build.HOST;

}

A: Here is all device informations that is possible in android using below enum and utility class
public enum Device {
        DEVICE_TYPE, DEVICE_SYSTEM_NAME, DEVICE_VERSION, DEVICE_SYSTEM_VERSION, DEVICE_TOKEN,
        /**
         *
         */
        DEVICE_NAME, DEVICE_UUID, DEVICE_MANUFACTURE, IPHONE_TYPE,
        /**
         *
         */
        CONTACT_ID, DEVICE_LANGUAGE, DEVICE_TIME_ZONE, DEVICE_LOCAL_COUNTRY_CODE,
        /**
         *
         */
        DEVICE_CURRENT_YEAR, DEVICE_CURRENT_DATE_TIME, DEVICE_CURRENT_DATE_TIME_ZERO_GMT,
        /**
         *
         */
        DEVICE_HARDWARE_MODEL, DEVICE_NUMBER_OF_PROCESSORS, DEVICE_LOCALE, DEVICE_NETWORK, DEVICE_NETWORK_TYPE,
        /**
         *
         */
        DEVICE_IP_ADDRESS_IPV4, DEVICE_IP_ADDRESS_IPV6, DEVICE_MAC_ADDRESS, DEVICE_TOTAL_CPU_USAGE,
        /**
         *
         */
        DEVICE_TOTAL_MEMORY, DEVICE_FREE_MEMORY, DEVICE_USED_MEMORY,
        /**
         *
         */
        DEVICE_TOTAL_CPU_USAGE_USER, DEVICE_TOTAL_CPU_USAGE_SYSTEM,
        /**
         *
         */
        DEVICE_TOTAL_CPU_IDLE, DEVICE_IN_INCH;
    }

--> Utility class :
 public class DeviceInfo {

        public static String getDeviceInfo(Context activity, Device device) {
            try {
                switch (device) {
                    case DEVICE_LANGUAGE:
                        return Locale.getDefault().getDisplayLanguage();
                    case DEVICE_TIME_ZONE:
                        return TimeZone.getDefault().getID();//(false, TimeZone.SHORT);
                    case DEVICE_LOCAL_COUNTRY_CODE:
                        return activity.getResources().getConfiguration().locale.getCountry();
                    case DEVICE_CURRENT_YEAR:
                        return "" + (Calendar.getInstance().get(Calendar.YEAR));
                    case DEVICE_CURRENT_DATE_TIME:
                        Calendar calendarTime = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
                        long time = (calendarTime.getTimeInMillis() / 1000);
                        return String.valueOf(time);
    //                    return DateFormat.getDateTimeInstance().format(new Date());
                    case DEVICE_CURRENT_DATE_TIME_ZERO_GMT:
                        Calendar calendarTime_zero = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"), Locale.getDefault());
                        return String.valueOf((calendarTime_zero.getTimeInMillis() / 1000));
    //                    DateFormat df = DateFormat.getDateTimeInstance();
    //                    df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
    //                    return df.format(new Date());
                    case DEVICE_HARDWARE_MODEL:
                        return getDeviceName();
                    case DEVICE_NUMBER_OF_PROCESSORS:
                        return Runtime.getRuntime().availableProcessors() + "";
                    case DEVICE_LOCALE:
                        return Locale.getDefault().getISO3Country();
                    case DEVICE_IP_ADDRESS_IPV4:
                        return getIPAddress(true);
                    case DEVICE_IP_ADDRESS_IPV6:
                        return getIPAddress(false);
                    case DEVICE_MAC_ADDRESS:
                        String mac = getMACAddress("wlan0");
                        if (TextUtils.isEmpty(mac)) {
                            mac = getMACAddress("eth0");
                        }
                        if (TextUtils.isEmpty(mac)) {
                            mac = "DU:MM:YA:DD:RE:SS";
                        }
                        return mac;

                    case DEVICE_TOTAL_MEMORY:
                        if (Build.VERSION.SDK_INT >= 16)
                            return String.valueOf(getTotalMemory(activity));
                    case DEVICE_FREE_MEMORY:
                        return String.valueOf(getFreeMemory(activity));
                    case DEVICE_USED_MEMORY:
                        if (Build.VERSION.SDK_INT >= 16) {
                            long freeMem = getTotalMemory(activity) - getFreeMemory(activity);
                            return String.valueOf(freeMem);
                        }
                        return "";
                    case DEVICE_TOTAL_CPU_USAGE:
                        int[] cpu = getCpuUsageStatistic();
                        if (cpu != null) {
                            int total = cpu[0] + cpu[1] + cpu[2] + cpu[3];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_TOTAL_CPU_USAGE_SYSTEM:
                        int[] cpu_sys = getCpuUsageStatistic();
                        if (cpu_sys != null) {
                            int total = cpu_sys[1];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_TOTAL_CPU_USAGE_USER:
                        int[] cpu_usage = getCpuUsageStatistic();
                        if (cpu_usage != null) {
                            int total = cpu_usage[0];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_MANUFACTURE:
                        return android.os.Build.MANUFACTURER;
                    case DEVICE_SYSTEM_VERSION:
                        return String.valueOf(getDeviceName());
                    case DEVICE_VERSION:
                        return String.valueOf(android.os.Build.VERSION.SDK_INT);
                    case DEVICE_IN_INCH:
                        return getDeviceInch(activity);
                    case DEVICE_TOTAL_CPU_IDLE:
                        int[] cpu_idle = getCpuUsageStatistic();
                        if (cpu_idle != null) {
                            int total = cpu_idle[2];
                            return String.valueOf(total);
                        }
                        return "";
                    case DEVICE_NETWORK_TYPE:
                        return getNetworkType(activity);
                    case DEVICE_NETWORK:
                        return checkNetworkStatus(activity);
                    case DEVICE_TYPE:
                        if (isTablet(activity)) {
                            if (getDeviceMoreThan5Inch(activity)) {
                                return "Tablet";
                            } else
                                return "Mobile";
                        } else {
                            return "Mobile";
                        }
                    case DEVICE_SYSTEM_NAME:
                        return "Android OS";
                    default:
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return "";
        }

        public static String getDeviceId(Context context) {
            String device_uuid = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
            if (device_uuid == null) {
                device_uuid = "12356789"; // for emulator testing
            } else {
                try {
                    byte[] _data = device_uuid.getBytes();
                    MessageDigest _digest = java.security.MessageDigest.getInstance("MD5");
                    _digest.update(_data);
                    _data = _digest.digest();
                    BigInteger _bi = new BigInteger(_data).abs();
                    device_uuid = _bi.toString(36);
                } catch (Exception e) {
                    if (e != null) {
                        e.printStackTrace();
                    }
                }
            }
            return device_uuid;
        }

        @SuppressLint("NewApi")
        private static long getTotalMemory(Context activity) {
            try {
                MemoryInfo mi = new MemoryInfo();
                ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
                activityManager.getMemoryInfo(mi);
                long availableMegs = mi.totalMem / 1048576L; // in megabyte (mb)

                return availableMegs;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }

        private static long getFreeMemory(Context activity) {
            try {
                MemoryInfo mi = new MemoryInfo();
                ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
                activityManager.getMemoryInfo(mi);
                long availableMegs = mi.availMem / 1048576L; // in megabyte (mb)

                return availableMegs;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }

        private static String getDeviceName() {
            String manufacturer = Build.MANUFACTURER;
            String model = Build.MODEL;
            if (model.startsWith(manufacturer)) {
                return capitalize(model);
            } else {
                return capitalize(manufacturer) + " " + model;
            }
        }

        private static String capitalize(String s) {
            if (s == null || s.length() == 0) {
                return "";
            }
            char first = s.charAt(0);
            if (Character.isUpperCase(first)) {
                return s;
            } else {
                return Character.toUpperCase(first) + s.substring(1);
            }
        }

        /**
         * Convert byte array to hex string
         *
         * @param bytes
         * @return
         */
        private static String bytesToHex(byte[] bytes) {
            StringBuilder sbuf = new StringBuilder();
            for (int idx = 0; idx < bytes.length; idx++) {
                int intVal = bytes[idx] & 0xff;
                if (intVal < 0x10)
                    sbuf.append("0");
                sbuf.append(Integer.toHexString(intVal).toUpperCase());
            }
            return sbuf.toString();
        }

        /**
         * Returns MAC address of the given interface name.
         *
         * @param interfaceName eth0, wlan0 or NULL=use first interface
         * @return mac address or empty string
         */
        @SuppressLint("NewApi")
        private static String getMACAddress(String interfaceName) {
            try {

                List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    if (interfaceName != null) {
                        if (!intf.getName().equalsIgnoreCase(interfaceName))
                            continue;
                    }
                    byte[] mac = intf.getHardwareAddress();
                    if (mac == null)
                        return "";
                    StringBuilder buf = new StringBuilder();
                    for (int idx = 0; idx < mac.length; idx++)
                        buf.append(String.format("%02X:", mac[idx]));
                    if (buf.length() > 0)
                        buf.deleteCharAt(buf.length() - 1);
                    return buf.toString();
                }
            } catch (Exception ex) {
                return "";
            } // for now eat exceptions
            return "";
            /*
             * try { // this is so Linux hack return
             * loadFileAsString("/sys/class/net/" +interfaceName +
             * "/address").toUpperCase().trim(); } catch (IOException ex) { return
             * null; }
             */
        }

        /**
         * Get IP address from first non-localhost interface
         *
         * @return address or empty string
         */
        private static String getIPAddress(boolean useIPv4) {
            try {
                List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
                for (NetworkInterface intf : interfaces) {
                    List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                    for (InetAddress addr : addrs) {
                        if (!addr.isLoopbackAddress()) {
                            String sAddr = addr.getHostAddress().toUpperCase();
                            boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                            if (useIPv4) {
                                if (isIPv4)
                                    return sAddr;
                            } else {
                                if (!isIPv4) {
                                    int delim = sAddr.indexOf('%'); // drop ip6 port
                                    // suffix
                                    return delim < 0 ? sAddr : sAddr.substring(0, delim);
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
            } // for now eat exceptions
            return "";
        }

        /*
         *
         * @return integer Array with 4 elements: user, system, idle and other cpu
         * usage in percentage.
         */
        private static int[] getCpuUsageStatistic() {
            try {
                String tempString = executeTop();

                tempString = tempString.replaceAll(",", "");
                tempString = tempString.replaceAll("User", "");
                tempString = tempString.replaceAll("System", "");
                tempString = tempString.replaceAll("IOW", "");
                tempString = tempString.replaceAll("IRQ", "");
                tempString = tempString.replaceAll("%", "");
                for (int i = 0; i < 10; i++) {
                    tempString = tempString.replaceAll("  ", " ");
                }
                tempString = tempString.trim();
                String[] myString = tempString.split(" ");
                int[] cpuUsageAsInt = new int[myString.length];
                for (int i = 0; i < myString.length; i++) {
                    myString[i] = myString[i].trim();
                    cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
                }
                return cpuUsageAsInt;

            } catch (Exception e) {
                e.printStackTrace();
                Log.e("executeTop", "error in getting cpu statics");
                return null;
            }
        }

        private static String executeTop() {
            java.lang.Process p = null;
            BufferedReader in = null;
            String returnString = null;
            try {
                p = Runtime.getRuntime().exec("top -n 1");
                in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while (returnString == null || returnString.contentEquals("")) {
                    returnString = in.readLine();
                }
            } catch (IOException e) {
                Log.e("executeTop", "error in getting first line of top");
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                    p.destroy();
                } catch (IOException e) {
                    Log.e("executeTop", "error in closing and destroying top process");
                    e.printStackTrace();
                }
            }
            return returnString;
        }

        public static String getNetworkType(final Context activity) {
            String networkStatus = "";

            final ConnectivityManager connMgr = (ConnectivityManager)
                    activity.getSystemService(Context.CONNECTIVITY_SERVICE);
            // check for wifi
            final android.net.NetworkInfo wifi =
                    connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            // check for mobile data
            final android.net.NetworkInfo mobile =
                    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (wifi.isAvailable()) {
                networkStatus = "Wifi";
            } else if (mobile.isAvailable()) {
                networkStatus = getDataType(activity);
            } else {
                networkStatus = "noNetwork";
            }
            return networkStatus;
        }

        public static String checkNetworkStatus(final Context activity) {
            String networkStatus = "";
            try {
                // Get connect mangaer
                final ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
                // // check for wifi
                final android.net.NetworkInfo wifi =
                connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                // // check for mobile data
                final android.net.NetworkInfo mobile =
                connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                if (wifi.isAvailable()) {
                networkStatus = "Wifi";
                } else if (mobile.isAvailable()) {
                networkStatus = getDataType(activity);
                } else {
                networkStatus = "noNetwork";
                networkStatus = "0";
               }

            } catch (Exception e) {
                e.printStackTrace();
                networkStatus = "0";
            }
            return networkStatus;

        }

 public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    public static boolean getDeviceMoreThan5Inch(Context activity) {
        try {
            DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
            // int width = displayMetrics.widthPixels;
            // int height = displayMetrics.heightPixels;

            float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
            float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
            double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
            if (diagonalInches >= 7) {
                // 5inch device or bigger
                return true;
            } else {
                // smaller device
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static String getDeviceInch(Context activity) {
        try {
            DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();

            float yInches = displayMetrics.heightPixels / displayMetrics.ydpi;
            float xInches = displayMetrics.widthPixels / displayMetrics.xdpi;
            double diagonalInches = Math.sqrt(xInches * xInches + yInches * yInches);
            return String.valueOf(diagonalInches);
        } catch (Exception e) {
            return "-1";
        }
    }

    public static String getDataType(Context activity) {
        String type = "Mobile Data";
        TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        switch (tm.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                type = "Mobile Data 3G";
                Log.d("Type", "3g");
                // for 3g HSDPA networktype will be return as
                // per testing(real) in device with 3g enable
                // data
                // and speed will also matters to decide 3g network type
                break;
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                type = "Mobile Data 4G";
                Log.d("Type", "4g");
                // No specification for the 4g but from wiki
                // i found(HSPAP used in 4g)
                break;
            case TelephonyManager.NETWORK_TYPE_GPRS:
                type = "Mobile Data GPRS";
                Log.d("Type", "GPRS");
                break;
            case TelephonyManager.NETWORK_TYPE_EDGE:
                type = "Mobile Data EDGE 2G";
                Log.d("Type", "EDGE 2g");
                break;

        }

        return type;
        }
}

-- Get IP Address without using InetAddressUtils class
    private static final String IPV4_BASIC_PATTERN_STRING =
                "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + // initial 3 fields, 0-255 followed by .
                        "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; // final field, 0-255
    private static final Pattern IPV4_PATTERN =
                Pattern.compile("^" + IPV4_BASIC_PATTERN_STRING + "$");
    public static boolean isIPv4Address(final String input) {
            return IPV4_PATTERN.matcher(input).matches();
   }

   /**
     * Get IP address from first non-localhost interface
     *
     * @return address or empty string
     */
    private static String getIPAddress(boolean useIPv4) {
        try {
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
                for (InetAddress addr : addrs) {
                    if (!addr.isLoopbackAddress()) {
                        String sAddr = addr.getHostAddress().toUpperCase();
                        //TODO 3.0.0
                        boolean isIPv4 = isIPv4Address(sAddr);
                        if (useIPv4) {
                            if (isIPv4)
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); // drop ip6 port
                                // suffix
                                return delim < 0 ? sAddr : sAddr.substring(0, delim);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
    }

A: edit: to get a complete overview of useful attributes, I combined them all together in my ErrorHandler activity (start to read at line 56): https://github.com/simon-heinen/SimpleUi/blob/master/SimpleUI/srcAndroid/simpleui/util/DeviceInformation.java#L56
Windowsize and keyboard presence were a good idea, i added some more infos for debug purpose:
String s="Debug-infos:";
s += "\n OS Version: " + System.getProperty("os.version") + "(" + android.os.Build.VERSION.INCREMENTAL + ")";
s += "\n OS API Level: " + android.os.Build.VERSION.SDK_INT;
s += "\n Device: " + android.os.Build.DEVICE;
s += "\n Model (and Product): " + android.os.Build.MODEL + " ("+ android.os.Build.PRODUCT + ")";

A: For screen resolution:
getWindow().getWindowManager().getDefaultDisplay().getWidth();
getWindow().getWindowManager().getDefaultDisplay().getHeight();

For hardware keyboard presence:
boolean keyboardPresent = (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS);

A: Update on screen resolution:
getHeight() and getWidth deprecated in API level 13 - HONEYCOMB_MR2; use getSize(Point) instead.
More info at:
http://developer.android.com/reference/android/view/Display.html

A: Try this to get Device Information.
String serviceType = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getActivity().getSystemService(serviceType);
String DeviceId, SubscriberId, NetworkOperator, OsVersion,SimOperatorName;
DeviceId = m_telephonyManager.getDeviceId();
SubscriberId = m_telephonyManager.getSubscriberId();
NetworkOperator = m_telephonyManager.getNetworkOperator();
OsVersion = m_telephonyManager.getDeviceSoftwareVersion();
SimOperatorName = m_telephonyManager.getSimOperatorName();

Show Output
Log.d("Device Information :", "\n DeviceId : " + DeviceId +
                            "\n SubscriberId : " + SubscriberId
                            + "\n NetworkOperator : " + NetworkOperator +
                            "\n SoftwareVersion : " + OsVersion+
                            "\n SimOperatorName : " + SimOperatorName);

A: Try this
Log.i(TAG, "Device Info: " + System.getProperty("http.agent"));


text:
Q: Get first value in a CSV field from SQL Server I am working on a database in SQL Server 2018. Unfortunately there is a multiselect column that stores values as a CSV string in a column.
The following values can be seen:
Value1
Value1,Value2
Value1,Value2,Value3
....

I have tried the following approach
select SUBSTRING(t.FIELD, 0,charindex(',',t.FIELD)) as first_value
from TABLE t

However this returns the first value only when there is  comma, and not when there is only a single value
Currently the query returns
NULL
Value1
Value1

I want the query to return
Value1
Value1
Value1

Any help would be greatly appreciated

A: You can easily fix your logic by adding a comma to the field for the call to charindex():
select left(t.FIELD, charindex(',', t.FIELD + ',') - 1) as first_value

Note that I also replaced substr() with left() because that is more concise.

A: You can also leverage JSON_VALUE to get the first value from comma separated list of values, like given below:
DECLARE @t table(cval VARCHAR(100))
INSERT INTO @t values
('Value1'),
('Value1,Value2'),
('Value1,Value2,Value3');

--Convert the comma separated list into JSON Array and pick the first value
SELECT JSON_VALUE(
        CONCAT('["',replace(cval,',','","'),'"]'),'$[0]') as firstValue
        FROM @T

One more approach of using xml.
SELECT
CAST(concat('<root><v>',replace(cval,',','</v><v>'),'</v></root>') AS xml).value('(/root/v)[1]', 'nvarchar(50)')
FROM @T

+------------+
| firstValue |
+------------+
| Value1     |
| Value1     |
| Value1     |
+------------+


text:
Q: Meu case 3 não exclui da lista e o case 4 não compara e retorna a quantidade de gênero escrito Cadastro alguns livros, após isso tento excluir algum com meu case 3, mas digitando o case 2 para mostrar todos ele continua mostrando o livro que deveria ter sido excluído.
Meu case 4 deveria comparar a String  genero digitada com a String genero da classe Livro de cada lista, mas ele sempre retorna o valor ZERO no meu count como se não tivesse nenhuma String igual ... Segue meu código principal e o objeto abaixo.
package application;

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

    import entities.Livro;

    public class Program {

        public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);
            Livro livroLivraria;
            List<Livro> livros = new ArrayList<>();

            int count = 0;

            System.out.println("1 - Cadastrar Livro\n2 - Listar \n3 - Excluir Livro\n4 - Pesquisar Livro pelo gênero\n"
                    + "5 - Pesquisar Livro por faixa de preço\n6 - Calcular Total do Acervo\n7 - Sair\n");

            int opcao = sc.nextInt();

            do {
                switch(opcao) {
                    case 1 :    System.out.print("Quantos livros quer cadastrar ? ");
                                int j = sc.nextInt();
                                sc.nextLine();
                                for(int i=1; i <= j; i++) {
                                    System.out.println("LIVRO " + i);
                                    System.out.print("Nome: ");
                                    String nome = sc.nextLine();
                                    System.out.print("Autor: ");
                                    String autor = sc.nextLine();
                                    System.out.print("Gênero: ");
                                    String genero = sc.nextLine();
                                    System.out.print("Preço: ");
                                    Double preco = sc.nextDouble();
                                    sc.nextLine();
                                    livroLivraria = new Livro(nome, autor, genero, preco);
                                    livros.add(livroLivraria);
                                }
                                break;

                    case 2 :    for (Livro l : livros) {
                                    System.out.println(l);
                                }
                                break;

                    case 3 :    System.out.print("Qual nome do livro que deseja excluir ? ");
                                String nome = sc.nextLine();
                                sc.nextLine();

                                for (Livro l : livros) {
                                    if (l.getNome().equals(nome)) {
                                        livros.remove(l);
                                    }
                                }

                                System.out.println("Livro excluído...");
                                break;

                    case 4 :    System.out.print("Qual gênero procura ? ");
                                String genero = sc.nextLine();
                                sc.nextLine();

                                count = 0;
                                for(Livro l : livros) {
                                    if (l.getGenero().equals(genero)) {
                                        count++;
                                    }
                                }
                                System.out.println(count + " livros do gênero " + genero);

                                break;

                    case 5 :    System.out.print("Digite o valor inicial: ");
                                double p1 = sc.nextDouble();
                                System.out.print("Digite o valor final: ");
                                double p2 = sc.nextDouble();

                                count = 0;
                                if (p1 < p2) {
                                    for(Livro l : livros) {
                                        if (l.getPreco() >= p1 && l.getPreco() <= p2) {
                                            count++;
                                        }
                                    }
                                    System.out.println(count + " livros entre os valores R$" + p1 + " e R$" + p2);
                                }else {
                                    System.out.println("ERRO: valor inicial maior que valor final...");
                                }

                                break;

                    case 6 :    double t=0;
                                for (Livro l : livros) {
                                    t += l.getPreco();
                                }
                                System.out.println("Valor total dos livros R$" + t);

                                break;

                    case 7 : break;

                    default :   System.out.println("Esta opção não existe...");
                                break;
                }

                System.out.println("\n1 - Cadastrar Livro\n2 - Listar \n3 - Excluir Livro\n4 - Pesquisar Livro pelo gênero\n"
                        + "5 - Pesquisar Livro por faixa de preço\n6 - Calcular Total do Acervo\n7 - Sair\n");

                opcao = sc.nextInt();

            }while(opcao != 7);

            sc.close();
        }
    }

Classe objeto Livro:
package entities;

public class Livro {

    private String nome;
    private String autor;
    private String genero;
    private Double preco;

    public Livro(String nome, String autor, String genero, Double preco) {
        this.nome = nome;
        this.autor = autor;
        this.genero = genero;
        this.preco = preco;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getAutor() {
        return autor;
    }

    public void setAutor(String autor) {
        this.autor = autor;
    }

    public String getGenero() {
        return genero;
    }

    public void setGenero(String genero) {
        this.genero = genero;
    }

    public Double getPreco() {
        return preco;
    }

    public void setPreco(Double preco) {
        this.preco = preco;
    }

    @Override
    public String toString() {
        return "Livro [ Nome = " + nome + ", Autor = " + autor + ", Genero = " + genero + ", Preço = " + preco + " ]";
    }

}

Como eu resolveria isso ?

A: O que ocorre é que no seu Case 3, no trecho:
System.out.print("Qual nome do livro que deseja excluir ? ");
                                String nome = sc.nextLine();
                                sc.nextLine();

Você chama o sc.nextLine() para a String nome,  depois você anula chamando novamente o sc.nextLine(). Apenas invertendo as chamadas, o problema já não ocorre mais. É o mesmo caso para os outros cases.
System.out.print("Qual nome do livro que deseja excluir ? ");
                sc.nextLine();
                String nome = sc.nextLine();

Dê uma estudada sobre a classe Scanner e sobre imutabilidade.
Espero ter ajudado.


text:
Q: ¿Cómo calcular la distancia más cercana en un array de coordenadas? un placer saludarles, me preguntaba si alguien me podría explicar como hacer para calcular la distancia entre un grupo de coordenadas.
Es decir yo tengo un array de objetos en donde me viene distintos lugares, aquí viene sus coordenadas:
[
    {
        "_id": "lugar1",
        "lat": 15.4997741,
        "lng": -88.03860120000002
    },
    {
        "_id": "lugar2",
        "lat": 15.5085874,
        "lng": -88.0264096
    },
   .
   .
   .
    N
]

Entonces entre este grupo de coordenada quiero poder calcular cual es la coordenada más cercana al P1:
P1: { lat: 15.5158049, lng: -88.0416823 }

Y como resultado quiero obtener por ejemplo algo como:
"El lugar más cercano al P1 es la coordenada del lugar1: lat: "xxx" - long: "xxx" (es un ejemplo de lo que se quiere obtener)
Estuve investigando, pensé que computeDistance de google api me ayudaría, pero no logre aplicarlo, luego mire link pero no me ayudo mucho, ya que ellos se basan en una distancia especifica y realmente no me quedo muy clara la explicación de su función. En mi caso estoy usando angular
De antemano muchas gracias por sus respuestas siempre.


text:
Q: How to make XCode bundle C++ project as an .app? A few months ago, I inherited a C++ command-line XCode project that I've since turned into an app with a GUI, but XCode won't build it as an .app bundle:

Instead, XCode builds a Debug folder, which, interestingly enough, works as an app if I copy it and rename it to "[Bundle Display Name].app".

There are two problems with this though:
(1) I have to manually do this for each build
(2) It doesn't link to my Assets.xcassets file containing my app icons or my Info.plist file or any of the other resources I need.
I've scoured Apple's XCode documentation and come up with nothing. Are there any XCode veterans who know the solution?
EDIT: It seems like the only solution is to add a script to the Build Rules to manually change the Debug directory to an .app and structure it properly. The problem I'm now having is that my app doesn't see my .icns file unless the absolute path is hardcoded into the Info.plist file. For example:
<key>CFBundleIconFile</key>
    <string>AppIcon.icns</string>

^This doesn't work
<key>CFBundleIconFile</key>
    <string>/Users/.../build/Control Cam.app/Contents/Resources/AppIcon.icns</string>

^This works. But of course it can't find the icon anymore if I move the app to a different folder. Any ideas how to get it to use relative path names?


text:
Q: Determining Under Which Conditions A Mapping is a Well-defined Homorphism This is a continuation of this problem. I have part of a solution, but am unsure it is correct. Allow me to write the problem again:

Determine the integers $z$ for which $f : \mathbb{Z}/48 \mathbb{Z} \rightarrow Z_{36}$ with $f_z(\overline{1})= x^z$, where $x$ is the generator of $Z_{36}$, extends to a well-defined homomorphism.

First of all, it seems that proving this problem requires I prove that

$f_z$ is a well-defined homomorphism iff $f_z(\overline{b}) = x^{bz}$ and $z$ is such that $36$ divides $48z$.

Being the overly cautious person that I am, I searched the internet for a solution. I found this. This is somewhat embarrassing, but how does $36 | 48z$ imply $3|z$? I can only get $3|4z$.
My second question pertains to proving the above conjecture. I was able to show that $f_z(\overline{b}) = x^{bz}$ and $z$ is such that $36$ divides $48z$ implies $f_z$ is a well-defined homomorphism easily enough. However, I am having trouble with the second direction. Here is my attempt:
Suppose $f_z$ is a well-defined homomorphism with $f_z(\overline{1}) = x^z$. Let $\overline{b} \in \mathbb{Z}/46\mathbb{Z}$ be arbitrary. Then by the homomorphism property, we have
$f_z(\overline{b}) = f_z(\overline{1} + \dots + \overline{1}) = f_z(\overline{1}) \dots f_z(\overline{1}) = x^z \dots x^z = x^{bz}$.
Now, we want to show $z$ satisfies $36|48z$. Suppose the contrary, and let $\overline{b} = \overline{b'}$, which implies $b' = b +48k$, for some $k \in \mathbb{Z}$. Because $f_z$ is well-defined, we have
$f_z(\overline{b}) = f_z(\overline{b'})$
$x^{bz} = x^{b'z}$
$x^{bz} = x^{(b+48k)z}$
$x^{bz} = x^{bz} (x^{48z})^k$
$e = (x^{48z})^k$,
where we have assumed $x^{48z} \neq e$.
I feel that there is some contradiction lurking in this equations, but I cannot see it.


text:
Q: Set selected item in Dropdown List simple question ,
how to set the selected item in dropdown list !!
in plain Html is easy https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_option_selected
but when Angular came in every thing begin to be messy !!
here is a live Demo of my question
https://stackblitz.com/edit/angular-jrvpus?embed=1&file=src/app/app.component.html

A: <select class="form-control" [(ngModel)]="ItemId" (change)="DoSomeThingMethods()"
                    name="itemsfromServer" required>
                <option *ngFor="let item of itemsfromServer" value="{{ item.ItemId }}" [selected]="item.ItemId == 0 ">{{ item.type }} {{ item.ItemId }}</option>
            </select>

now set your [(ngModel)] value in component.
If you set ItemId to 0.
{ItemId : 0 ,selected : true ,type:"Type default"} will be selected in dropdown.

A: You can set it via ngModel.
Consider your template HTML;
<select [(ngModel)]="id" (change)="change()" name="item" required>
    <option *ngFor="let item of items" value="{{ item.id }}">
        {{ item.type }}
    </option>
</select>

And in you component.ts;
this.id = 5; //or whatever

Now if the items collection is like;
[
    {type:"t1", id:"1"},
    {type:"t2", id:"2"},
    {type:"t3", id:"3"},
    {type:"t4", id:"4"},
    {type:"t5", id:"5"},
    {type:"t6", id:"6"},
    {type:"t7", id:"7"},
]

Now the type : t5 should be selected by default.


text:
Q: show the textField in the alertController in swift Just now I wrote the code which is provided below. I would like to produce the output for the following code but it crashes when I run it, and it shows nil.
class ViewController: UIViewController ,UITableViewDataSource{
var names = [String]()

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    title = "\"The List\""
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    // Do any additional setup after loading the view, typically from a nib.
}

@IBAction func addName(sender: AnyObject) {
    let alert = UIAlertController(title: "New name", message: "Add one new name here", preferredStyle: .Alert)
    let saveAction = UIAlertAction(title: "Save", style: .Default, handler: {(action:UIAlertAction) ->Void in
        alert.addTextFieldWithConfigurationHandler{(textField:UITextField)->Void in
            alert.view.endEditing(true)
            let textField = alert.textFields?.last
            self.names.append(textField!.text!)
            self.tableView.reloadData()
        }

    })
    let cancleAction = UIAlertAction(title: "Cancel", style: .Default, handler: {(action:UIAlertAction) ->Void in
        alert.addTextFieldWithConfigurationHandler {(textFiled:UITextField) ->Void in
        }
                })
    alert.addAction(saveAction)
    alert.addAction(cancleAction)
    self.presentViewController(alert,animated:true,completion:nil)

}

    //MARK:-TableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return names.count

}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
    cell?.textLabel?.text = names[indexPath.row]
    return cell!

}
}

How to fix it???

A: Code for Adding textField in UIALertController :
let alertController = UIAlertController(title: "PlainTextStyle", message: "PlainTextStyle AlertView.", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField) -> Void in
            textField.placeholder = "Login"
        }
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (result : UIAlertAction) -> Void in
            print("Cancel")
        }
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in
           print(alertController.textFields?.first?.text)
        }
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)

Update Swift 3.0
 let alertController = UIAlertController(title: "PlainTextStyle", message: "PlainTextStyle AlertView.", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addTextField { (textField : UITextField) -> Void in
            textField.placeholder = "Login"
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (result : UIAlertAction) -> Void in
        }
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
        }
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)

TextField in UIALertController :

A: The error is I forget to add textfield into the AlertController...So simple


text:
Q: How can I change the color of a toolbar in MFC? I've been trying to change the color of one toolbar for 2 days and I can't find the correct way... Is really frustrating...
Can anybody tells me how I can change this color??

Is it possible??
What I've tried:

*

*Generate an object and overriding the methods:

· OnEraseBkgnd()
· OnCtlColor()
· PreparePaint()

*

*Getting one method where to insert the color directly

*Search for the rectangle of the control and change de color there

*Using SetBckgndColor() method from the GetToolBarCtld() object.

thanks


text:
Q: A pair of MOLS of order 15? Is there any place where I can find a pair of MOLS(mutually orthogonal latin squares) of order 15? I can't seem to find a place where it's spelled out explicitly.

A: For any odd $n$, a diagonally cyclic Latin square construction works.  Here's GAP code that implements it:
n:=15;

# Diagonally cyclic Latin square
L:=List([1..n],i->List([1..n],j->0));
for j in [1..n] do L[1][j]:=((2*(j-1)) mod n)+1; od;
for i in [2..n] do for j in [1..n] do L[i][j]:=(L[i-1][((j-2) mod n)+1] mod n)+1; od; od;
L;

# Fixed diagonal Latin square
M:=List([1..n],i->List([1..n],j->((j-i) mod n)+1));
M;

and this is what the output looks like:
gap> L;
[ [ 1, 3, 5, 7, 9, 11, 13, 15, 2, 4, 6, 8, 10, 12, 14 ],
  [ 15, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13 ],
  [ 14, 1, 3, 5, 7, 9, 11, 13, 15, 2, 4, 6, 8, 10, 12 ],
  [ 13, 15, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11 ],
  [ 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, 2, 4, 6, 8, 10 ],
  [ 11, 13, 15, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9 ],
  [ 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, 2, 4, 6, 8 ],
  [ 9, 11, 13, 15, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7 ],
  [ 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, 2, 4, 6 ],
  [ 7, 9, 11, 13, 15, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5 ],
  [ 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, 2, 4 ],
  [ 5, 7, 9, 11, 13, 15, 2, 4, 6, 8, 10, 12, 14, 1, 3 ],
  [ 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, 2 ],
  [ 3, 5, 7, 9, 11, 13, 15, 2, 4, 6, 8, 10, 12, 14, 1 ],
  [ 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15 ] ]

and
gap> M;
[ [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ],
  [ 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ],
  [ 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ],
  [ 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ],
  [ 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ],
  [ 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ],
  [ 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
  [ 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8 ],
  [ 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7 ],
  [ 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6 ],
  [ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5 ],
  [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4 ],
  [ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3 ],
  [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2 ],
  [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1 ] ]

We can readily see that they're orthogonal (the forwards broken diagonals of the first square are $1,2,\ldots,n$ cyclically permuted, whereas the forwards broken diagonals of the second are $x,x,\ldots,x$, for some $x$).  The only thing we should check is that the first square is always a Latin square, which comes from its first row being an orthomorphism.

A: The Wikipedia page on Greco-Latin squares shows squares of order 3 and 5.  Gerry Myerson gave an answer to your question /mutually-orthogonal-latin-squares-of-order-mn-from-order-m-and-order-n which shows how to make one.  What don't you understand?

A: Natalia Makarova has built a MOLS group of order 15, consisting of four Latin squares. The topic is discussed in detail on her webpage, and I will also quote the squares below. They also built a MODLS of order 15 on page dedicated to MODLS.
Whether a group of MODLS of order 15 containing more than 4 squares is still an open question.
1 7 12 10 9 3 15 6 5 13 4 11 14 2 8
3 2 8 13 11 10 4 15 7 6 14 5 12 1 9
2 4 3 9 14 12 11 5 15 8 7 1 6 13 10
14 3 5 4 10 1 13 12 6 15 9 8 2 7 11
8 1 4 6 5 11 2 14 13 7 15 10 9 3 12
4 9 2 5 7 6 12 3 1 14 8 15 11 10 13
11 5 10 3 6 8 7 13 4 2 1 9 15 12 14
13 12 6 11 4 7 9 8 14 5 3 2 10 15 1
15 14 13 7 12 5 8 10 9 1 6 4 3 11 2
12 15 1 14 8 13 6 9 11 10 2 7 5 4 3
5 13 15 2 1 9 14 7 10 12 11 3 8 6 4
7 6 14 15 3 2 10 1 8 11 13 12 4 9 5
10 8 7 1 15 4 3 11 2 9 12 14 13 5 6
6 11 9 8 2 15 5 4 12 3 10 13 1 14 7
9 10 11 12 13 14 1 2 3 4 5 6 7 8 15

1 11 8 3 6 12 9 4 13 15 5 10 2 7 14
8 2 12 9 4 7 13 10 5 14 15 6 11 3 1
4 9 3 13 10 5 8 14 11 6 1 15 7 12 2
13 5 10 4 14 11 6 9 1 12 7 2 15 8 3
9 14 6 11 5 1 12 7 10 2 13 8 3 15 4
15 10 1 7 12 6 2 13 8 11 3 14 9 4 5
5 15 11 2 8 13 7 3 14 9 12 4 1 10 6
11 6 15 12 3 9 14 8 4 1 10 13 5 2 7
3 12 7 15 13 4 10 1 9 5 2 11 14 6 8
7 4 13 8 15 14 5 11 2 10 6 3 12 1 9
2 8 5 14 9 15 1 6 12 3 11 7 4 13 10
14 3 9 6 1 10 15 2 7 13 4 12 8 5 11
6 1 4 10 7 2 11 15 3 8 14 5 13 9 12
10 7 2 5 11 8 3 12 15 4 9 1 6 14 13
12 13 14 1 2 3 4 5 6 7 8 9 10 11 15

1 9 7 13 3 2 12 10 6 11 14 4 15 8 5
9 2 10 8 14 4 3 13 11 7 12 1 5 15 6
15 10 3 11 9 1 5 4 14 12 8 13 2 6 7
7 15 11 4 12 10 2 6 5 1 13 9 14 3 8
4 8 15 12 5 13 11 3 7 6 2 14 10 1 9
2 5 9 15 13 6 14 12 4 8 7 3 1 11 10
12 3 6 10 15 14 7 1 13 5 9 8 4 2 11
3 13 4 7 11 15 1 8 2 14 6 10 9 5 12
6 4 14 5 8 12 15 2 9 3 1 7 11 10 13
11 7 5 1 6 9 13 15 3 10 4 2 8 12 14
13 12 8 6 2 7 10 14 15 4 11 5 3 9 1
10 14 13 9 7 3 8 11 1 15 5 12 6 4 2
5 11 1 14 10 8 4 9 12 2 15 6 13 7 3
8 6 12 2 1 11 9 5 10 13 3 15 7 14 4
14 1 2 3 4 5 6 7 8 9 10 11 12 13 15

1 6 13 7 12 5 8 14 11 4 2 15 10 9 3
10 2 7 14 8 13 6 9 1 12 5 3 15 11 4
12 11 3 8 1 9 14 7 10 2 13 6 4 15 5
15 13 12 4 9 2 10 1 8 11 3 14 7 5 6
6 15 14 13 5 10 3 11 2 9 12 4 1 8 7
9 7 15 1 14 6 11 4 12 3 10 13 5 2 8
3 10 8 15 2 1 7 12 5 13 4 11 14 6 9
7 4 11 9 15 3 2 8 13 6 14 5 12 1 10
2 8 5 12 10 15 4 3 9 14 7 1 6 13 11
14 3 9 6 13 11 15 5 4 10 1 8 2 7 12
8 1 4 10 7 14 12 15 6 5 11 2 9 3 13
4 9 2 5 11 8 1 13 15 7 6 12 3 10 14
11 5 10 3 6 12 9 2 14 15 8 7 13 4 1
5 12 6 11 4 7 13 10 3 1 15 9 8 14 2
13 14 1 2 3 4 5 6 7 8 9 10 11 12 15

A: If n, m1 and m2 are such that 1=(n,m1)=(n,m2)=(n, m1-m2) then the LS
given by x+m1y, x+m2y on Z_n are MOLS.
For n=15 you can take m1=1, m2=2 or m1=2, m2=4, etc


text:
Q: Calling a variable without a space before it in powershell? I am trying to use variables from a imported CSV file to substitute variables in a string.
Here's the code.
param( [string] $CSV)
$VMs = Import-Csv $CSV
Foreach ($VM in $VMs) {
psexec \\$VM.VM_Name -h netsh interface ip set address name='"Local Area Connection"' static $VM.IP_Address 255.255.255.0 $VM.Gateway 1
}
this is what it returns:
psexec \@{VM_Name=TESTCSVVM; IP_Address=10.12.81.82; Gateway=10.12.81.1; VLAN=H
Q_VM_81}.VM_Name -h netsh interface ip set address name="Local Area Connection"
static 10.12.81.82 255.255.255.0 10.12.81.1 1
Here's what I want it to look like:
psexec \TESTCSVVM -h netsh interface ip set address name="Local Area Connection"
static 10.12.81.82 255.255.255.0 10.12.81.1 1
Here's the CSV file:
"VM_Name","IP_Address","Gateway","VLAN"
"TESTCSVVM","10.12.81.82","10.12.81.1","HQ_VM_81"
How do I make sure theres no space between the \ and the 1st variable $VM.VM_Name?
Thanks

A: Try this :
Foreach ($VM in $VMs) {
    psexec \\\\$($VM.VM_Name) -h netsh interface ip set address `
        name='"Local Area Connection"' `
        static $VM.IP_Address 255.255.255.0 $VM.Gateway 1
}

A: Also, generally wrapping variables in quotes will work too.
So if:
$path = C:\Windows\
$File = MyFile.ext
write-host "$path$File

Would look like:
C:\Windows\myFile.ext


text:
Q: Multiple checkout locations from Perforce with CruiseControl [.Net] I'm employing a production-test server, that is, a test server in the production environment, which is only accessible from my company's network. This is for doing smoke tests and regression tests (for example making sure that our 3rd party web services are accessible), before we actually deploy the project to production (the project is a web site).
We use a Perforce Source Control Server and CruiseControl.Net, and I'd like to configure the CruiseControl to check out our production code to two different file system locations (on our build server) so it can build it twice with different build configurations, i.e. one build configuration for production, one for production-test. Then I'm gonna robocopy the production-test build to the production-test server.
How do I specify multiple checkout directories for "production-test" and "production", without having to create two different branches for it?

A: Create two separate projects. Use Configuration Preprocessor to extract all common parts into a template and include it twice, changing only the project name, working/artifacts directories and the configuration. That's the simplest and most bulletproof solution.


text:
Q: HTML - multiple  tags I am writing a website for a school project in PHP+HTML+CSS.
It is a website about a School-Orchestra.
I tried to use multiple audio-tags.
But it only displays the first  and .
Here is my Code:

        <meta charset="utf-8">

        <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Con Fuoco</title>
  <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="style.css">

  <?php
   include("nav.html");
  ?>

Die 9. Sinfonie von Antonín Dvořák

Allgemeines

Die 9. Sinfonie von Antonin Dvorak entstand während Dvorak's dreijährigem Amerika-Aufenthaltes und wurde auch von diesem inspiriert.

Original-Besetzung

2 Flöten (2. auch Piccoloflöte), 2 Oboen (2. auch Englischhorn), 2 Klarinetten, 2 Fagotte, 4 Hörner, 2 Trompeten, 3 Posaunen, Tuba, Pauke, Triangel, Becken, Streicher

Hörprobe? Ja!

1. Satz: Adagio - Allegro molto

        <audio src="./files/9-ad-1.ogg" controls /a>

2. Satz: Largo

        <audio src="./files/9-ad-2.ogg" controls /a>

3. Satz: Scherzo, Molto vivace

        <audio src="./files/9-ad-3.ogg" controls /a>

4. Satz: Allegro con fuoco

        <audio src="./files/9-ad-4.ogg" controls /a>

  <?php
   include("besucher.php");
  ?>

A: Thanks to FirstOne!
Removing the /a> at the and and closing the tag normally works.

1. Satz: Adagio - Allegro molto

        <audio src="./files/9-ad-1.ogg" controls></audio>

2. Satz: Largo

        <audio src="./files/9-ad-2.ogg" controls></audio>

3. Satz: Scherzo, Molto vivace

        <audio src="./files/9-ad-3.ogg" controls></audio>

4. Satz: Allegro con fuoco

        <audio src="./files/9-ad-4.ogg" controls></audio>


text:
Q: When Java 9 module system integrate into Maven, how to handle automatic module I have already practiced java 9 module system integration with Maven project. and it seems to work well but I was anxious about backward compatibility of maven module compiled before java 9.
For backward compatibility, JPMS(Java Platform Module System) has Automatic Module Concept. In JPMS, Jar file without module-info.java is regarded as Automatic Module and other java module can use this jar file by using its file name as module name.
In case of integration with maven project, I think additional support for JPMS backward compatibility needed.
first, basic jar file and maven jar file is not same structure.
second, maven jar file naming is incompatible with rule can be compatibility with JPMS module naming rule. see the below example.
<artifactId>previous-version-module</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

In above cases, We already uses previous-version-module-0.0.1-SNAPSHOT and want to use this module in new java 9 maven project.
module new.module{
  requires previous-version-module-0.0.1-SNAPSHOT
}

but it occur compile error or IDEA tool throw error.
I'm wondering how to use maven jar file which compiled before java 9 in java 9 and maven integration project.
I searched some additional module definition rule or maven plugin, I can't find any solution.
Thanks.

A: If the module name isn't obvious then you can use jar --file=<jarfile> --describe-module to see the derived name. Alternatively, use the --list-modules option, i.e. java -p <jarfile> --list-modules.
Once you know the module name then you use requires <module> and it should work. The maven-compiler-plugin puts all dependences on the module path when building a project that has a module-info.java in the source tree.


text:
Q: APE + CUE in Rhythmbox I can open ape file in my Rhythmbox and it plays ok. But it doesn't fetch cue file, so I can't see songs list, only one line in the player with huge duration. What should I do to configure Rhythmbox?
Files: cd1.ape and cd1.cue
Cue text:
... FILE "cd1.ape" WAVE  ...

A: It seems rhythmbox does not support cue lists )=
Hope it will in future.
Now you can use Clementine player for such files. It does support them!
After googling it seems only Clementine and audacious have .cue support in linux world...
But those two work for sure (checked).

A: I know command line music players might not be that popular, but cmus has support for cue files and many others. Is super lightweight also.
You can install it in Ubuntu with:
sudo apt install cmus


text:
Q: How do I convert '\x80' hex to decimal I am communicating with a servo using python's serial module. When I perform a serial.read(1) I get the value '\x80'. I need to convert this to decimal (128). Any suggestions?

A: Oh, never mind. I should have thought a bit. Googling opposite of chr() found me this page in the python docs. And ord() does the trick.


text:
Q: Trying to update the state using setstate inside the return in react component and getting "Maximum update depth exceeded error"? I'm trying to update the state directly inside the return without using any of the life cycle method and am getting error like this:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

I referred to this link for the above error, but I didn't get an appropriate solution. Is it always necessary to use a function or life cycle method to update the state?
import React, { Component } from "react";

import "./App.css";

class App extends Component {
  state = {
    name: "john"
  };

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <header className="App-header">
          {this.state.name}
          {this.setState({ name: "abc" })}
        </header>
      </div>
    );
  }
}

export default App;

I wrote the above code and am getting the error but in console the state value is getting update and printing it in many times.

A: *

*You have this error because setState triggers re-render of the component each time when your component renders. This causes an endless loop of updates.

setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

*Yes, it is necessary to use a function or life cycle method to update the state. You must not update a state directly in a render function. You should prepare your data for rendering before render and you should update a state in lifecycle methods or in callbacks.

A: This is because you are using setState inside the render method. You cannot use setState inside the render method because it will cause the Component to re-render again and again. Because in react application a Component get re-rendered only if Props pass to that component or when setState is called.

So you can use componentDidMount life-cycle to set the state.


text:
Q: Why not open viewController when clicking a table cell in moreViewControllers of UITabBarController? Why not open viewController when clicking a table cell in moreViewControllers of UITabBarController?
When I click cell, cell is highlighted (or selected). But viewController was not shown.

Oh, must I type some code to open viewController? Does not tabBarController open viewController automatically?


text:
Q: determine if a particular pixel is within a shape processing I'm creating an image filter that will create a honeycomb effect by finding the averages of groups of hexagons.
This code will generate a grid of hexagons for any given size, and will eventually be limited to the size of the canvas:
float unitSize = 20;
float eqTriH = 0.8660254;
int cellsX;
int cellsY;
void setup() {
  size(700, 700);
  cellsX = int(width/(unitSize*3));
  cellsY = int(height/(unitSize*eqTriH*2+eqTriH));
  smooth();
}

void draw() {
  for (int i = 0; i < cellsX; i++) {
    for (int j = 0; j < cellsY; j++) {
      beginShape();
      for (int k = 0; k < 6; k++) vertex(unitSize+i*unitSize*3+cos(TWO_PI/6*k)*unitSize, unitSize*eqTriH+j*unitSize*2*eqTriH+sin(TWO_PI/6*k)*unitSize);
      endShape(CLOSE);
      beginShape();
      for (int k = 0; k < 6; k++) vertex(unitSize*2.5+i*unitSize*3+cos(TWO_PI/6*k)*unitSize, unitSize*eqTriH*2+j*unitSize*2*eqTriH+sin(TWO_PI/6*k)*unitSize);
      endShape(CLOSE);
    }
  }
}

This works fine, however, I can't figure out how to, for every hexagon that is drawn, get an array of pixel locations inside each hexagon.
If this question is too vague, please let me know so I can get more specific.
EDIT: when I say I want to determine if a pixel is in the shape, I mean, once I can do this, I'm going to loop through, THEN create an array.

A: There are two approaches:

*

*walk through all image pixels, determine what hexagon every pixel belongs to, and write its coordinate in corresponding list/array

*rasterize every hexagon, getting scan lines  - ready-to-use continuous pixels arrays.
I think that the second approach is better for your case. You have coordinates of vertices. It seems that your hexagons are flat-topped (horizontal), so scan upper trapezoid then bottom one.
pseudocode for bottom trapezoid:
for y = (centery; y <= centery + ysize; y++)
    left_x = (int) themostleftx + (y - centery) * eqTriH
    right_x = (int) themostright - (y - centery) * eqTriH
    get horizontal segment of pixels (left_x,y)-(right_x,y)


text:
Q: How to use pyodbc, cursor, execute to extract data from SQL when there is no parameters for query.format? Usually, I use the following way to extract data from SQL using Python:
myConnect=pyodbc.connect('DSN=B1P HANA;UID=****;PWD=****')
myCursor=myConnect.cursor()

Start1=20150101
End=20200101
query = """
        SELECT "Operator",
               "Position"
        FROM ******
        """
myRow = myCursor.execute(query.format(Start1=Start1,
                                      End=End)
Result = myRow.fetchall()
OperatorTMs = pd.DataFrame(columns=["Operator", "Position"])
for i in Result:
    OperatorTMs=OperatorTMs.append({"Operator":i.Operator,"Position":i.Position},ignore_index=True)

But now, I do not need any parameters in query.format(). And I tried the way in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html. And it does not work
So, how can I do this without any parameters in query.format?

A: You really shouldn't be using .format to insert column values into your SQL command. Search for "SQL Injection" or "Little Bobby Tables" for more information.
Instead, you should be using ? parameter placeholders and supplying the column values as additional arguments to .execute as in
query = "SELECT col1, col2 FROM tablename WHERE col1 BETWEEN ? AND ?"
myRow = myCursor.execute(query, Start1, End)

For queries with no parameter values you simply pass the query string by itself
query = "SELECT col1, col2 FROM tablename"
myRow = myCursor.execute(query)