text:
Q: Javascript tag is not apprearing in html on rails I am a beginner in Javascript and html. I have created a javascript tag that adds rows to a html table on rails. It seems to me that the script tag is not getting executed. I am not getting any error as well.
<script type="text/javascript">

  //Make a javascript array from a Ruby array
  //Use the array to create tables in html with proper value
  var myArray = new Array();
  <%@array.each_with_index do |name, index|%>
  myArray[index] = <%= name[:employee]%>
  <%end%>

  var arraylen = myArray.length;

  //Javascript function to add table

  $(function() {
    var table = document.getElementById("table");
    for (var i = 0; i<arraylen; i++){

      var row = table.insertRow(index);
      var name = myArray[i]
      row.insertCell(0).innerHTML = name.value;
    }
  })();

</script>

A: As you found out in your script the index variable you have used is not set to any value. Instead it is intended to use i or you can set any value required.
Also you are assigning a value to javascript array using the erb syntax to so whenever assigning the value to javascript as a String you should put it inside string quotes. Like this:
myArray[index] = "<%= name[:employee]%>"

So the value will be assigned as String in your javascript array.


text:
Q: How to use inner join in the same table I have a table name as tnx_line_transfer. Schema like below

Now i want to generate output like below
Output

I am trying below query but its not showing proper output. what is the issue on this query
SELECT
    main_tbl.operator_id,
    main_tbl.production_line
FROM
    tnx_line_transfer main_tbl
INNER JOIN (
    SELECT
        operator_id,
        max(date) AS max_date
    FROM
        tnx_line_transfer
    GROUP BY
        operator_id
) temp ON main_tbl.operator_id = temp.operator_id

If any other alternative easy solution please let me know.Thanks in advance.

A: You missed to join date column with max_date.
SELECT main_tbl.operator_id,
       main_tbl.production_line
FROM   tnx_line_transfer main_tbl
       INNER JOIN (SELECT operator_id,
                          Max(`date`) AS max_date
                   FROM   tnx_line_transfer
                   GROUP  BY operator_id) temp
               ON main_tbl.operator_id = temp.operator_id
                  AND main_tbl.max_date = temp.`date` --here

Another way would be using Sub-Query
SELECT main_tbl.operator_id,
       main_tbl.production_line
FROM   tnx_line_transfer main_tbl
WHERE  `date` = (SELECT Max(`date`)
               FROM   tnx_line_transfer temp
               WHERE  main_tbl.operator_id = temp.operator_id)

Row_Number concept comes in handy for above scenario but unfortunately Mysql doesnot support Window function's

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delete numerals at the end but keep dates and text I'm a beta tester for a hockey game and sometimes the schedules I get are fouled up. Can anyone help this Notepad-challenged newbie?
Turn this:
19;10;2012;Oklahoma City Barons;San Antonio Rampage323
19;10;2012;Milwaukee Admirals;Charlotte Checkers572
19;10;2012;Manchester Monarchs;Providence Bruins002
19;10;2012;Albany Devils;Syracuse Crunch579

Into this:
19;10;2012;Oklahoma City Barons;San Antonio Rampage
19;10;2012;Milwaukee Admirals;Charlotte Checkers
19;10;2012;Manchester Monarchs;Providence Bruins
19;10;2012;Albany Devils;Syracuse Crunch

Thanks!

A: Assuming Perl:
cat file | perl -ne 's/\d+$//' > newfile

Where file is the file with the numbers and newfile is the corrected entry.

A: To teach you some regex...

*

*First you can match digits with \d

*Secondly, you can "anchor" the match, the $ means "the end of the string"

*Finally, you want to specify 1 or more digits, so you add the + quantifier to the \d token I mentioned earlier to create \d+
3.1. If the numbers are not ALWAYS on the end, make it optional with * ('0 or more') \d*

Full regex: \d+$ or \d*$


text:
Q: How to initialize class with list in? Basic question but I cant find anwser anywhere, I have 2 classes:
public class Book
{
    public int Id { get; set; }
    public string Category { get; set; }
    public string Title { get; set; }
    public IList<Chapter> Chapters{ get; set; }
}

public class Chapter
{
    public int Id { get; set; }
    public string Title { get; set; }
}

How do I add to or initialize this? I have tried:
 var books = new List<Book>();

        books.Add(new Book()
        {
            Id = 1,
            Category = "test",
            Title = "Book1 test",
            Chapters = new Chapter() { Id = 1, Title = "A"},
                       new Chapter() { Id = 2, Title = "B" }
        });

But I'm getting an error: Invalid initializer member declarator?

A: I think you want
Chapters = new List<Chapter>()
               {
                  new Chapter() { Id = 1, Title = "A"},
                  new Chapter() { Id = 2, Title = "B" }
               }

Instead of:
Answers = new Chapter() { Id = 1, Title = "A"},
          new Chapter() { Id = 2, Title = "B" }

*

*Your Book class doesn't have  a property named Answers

*You need to create a new collection and place the initializations (new Chapter() { ... }) inside of the collection initializer.

A: If you give Book a constructor that initializes Chapters:
public Book
{
    public Book()
    {
        Chapters = new List<Chapter>();
    }

    // properties
}

You will be able to use the collection initializer syntax:
var book = new Book()
{
    Id = 1,
    Category = "test",
    Title = "Book1 test",
    Chapters = { new Chapter() { Id = 1, Title = "A" },
                 new Chapter() { Id = 2, Title = "B" } }
};

Note that if you don't initialize Chapters in the constructor this is still legal, however it will throw a NullReferenceException at runtime.

A: Selman22 has one answer. Another might to be initialize the list on instantiation of your object:
public class Book
{
    public int Id { get; set; }
    public string Category { get; set; }
    public string Title { get; set; }
    public IList<Chapter> Chapters{ get; set; }

    public Book()
    {
        Chapters = new List<Chapter>();
    }
}

It's not really an IList anymore, it's just a List. One could always override it though.


text:
Q: How not to modify elements in an Arraylist of Arraylists while doing calculations? I am trying to assign adjused values to the ArrayList adjustedValues, and would need that estimatedValues do not change after the adjustValues() method is called in main.
I have attempted to use inside the adjustValues() method:
ArrayList<ArrayList<Double>> adjustedValues = (ArrayList< ArrayList< Double>>) estimatedValues.clone();

but had no luck since the elements which I needed were still getting modified
import java.util.ArrayList;

public class Test123 {

    public static void main(String[] args) {

        ArrayList<ArrayList<Double>> initialWeight = generateRandomWeights(6,0.1, 1);
        ArrayList<ArrayList<Double>> estimatedValues = generateRandomWeights(6,0.1, 1);

        ArrayList<ArrayList<Double>> adjustedValues = adjustValues(initialWeight, estimatedValues);
    }

    public static ArrayList<ArrayList<Double>> adjustValues (ArrayList<ArrayList<Double>> weights, ArrayList<ArrayList<Double>> estimateValues){

        ArrayList<ArrayList<Double>> adjustedValues = new ArrayList<>(estimateValues);

        for(int i=0; i<estimateValues.size(); i++){
            for(int j=0; j<estimateValues.get(i).size(); j++){
                adjustedValues.get(i).set(j, estimateValues.get(i).get(j) * weights.get(i).get(j));

            }
        }

        return adjustedValues;
    }

    public static ArrayList<Double> getArrayListOfRandom(int c,double min, double max){
        ArrayList randomValues = new ArrayList();

        for(int i=0;i< c; i++){
            double x = ((Math.random() * (max - min)) + min);
            randomValues.add(x);
        }

        return randomValues;
    }

    public static ArrayList<ArrayList<Double>> generateRandomWeights(int c, double min, double max){
        ArrayList<ArrayList<Double>> weights = new ArrayList<>();

        for(int i=0; i<c; i++){
            weights.add(getArrayListOfRandom(c,min,max));
        }

        return weights;
    }

}

A: ArrayList.clone and the copy constructor both create a shallow copy of the initial arraylist.  This would work fine if it were a list of primitives, but your list contains other lists so a shallow copy means they are still mutable(contents can be changed).   A few ways to do a deep copy are discussed on this question.  java: best way to do deep copy of list of lists


text:
Q: Does sharing my Heroku app's name with others present any security risks? If I share the name of a Heroku app with others, does this in any way present any sort of security concern?
Would others be able to then do anything to the app?

A: No, there are no security concerns as long as your app doesn't expose public vulnerabilities. Keep in mind that, in any case, the name is going to be exposed in other ways.
For instance, the standard way to point your custom domain name to an Heroku app is by CNAMing the app endpoint.
example.com CNAME myapp.herokuapp.com

Thus a simple query to the DNS records for your domains will reveal it.


text:
Q: Unable to use some pyautogui functions It looks like really strange, I've correctly installed pyautogui library but, only some functions are working correctly and other ones cause the crash of the program.
I'm just trying to running this simple program:
import pyautogui
import PIL

print(pyautogui.position())
pyautogui.screenshot()

This is the output on the Shell:
Python 3.9.7 (v3.9.7:1016ef3790, Aug 30 2021, 16:25:35)
[Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>>
==================== RESTART: /Users/luca/Desktop/Bot/bot.py ===================

Warning (from warnings module):
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/rubicon/objc/ctypes_patch.py", line 21
    warnings.warn(
UserWarning: rubicon.objc.ctypes_patch has only been tested with Python 3.4 through 3.8. You are using Python 3.9.7. Most likely things will work properly, but you may experience crashes if Python's internals have changed significantly.
Point(x=793, y=262)
Traceback (most recent call last):
  File "/Users/luca/Desktop/Bot/bot.py", line 5, in <module>
    pyautogui.screenshot()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyscreeze/__init__.py", line 476, in _screenshot_osx
    im = Image.open(tmpFilename)
NameError: name 'Image' is not defined
>>>

As you can read from the output, the pyautogui.position() function work correctly, while the pyautogui.screenshot() function throw an error, even if a screenshot is present inside the directory of the script.
I'm using Python 3.9.7 version, for PyautoGUI the 0.9.52 version and for Pillow the 9.1.0, this is the output on the terminal:
luca@MBP-di-Luca ~ % python3 --version
Python 3.9.7
luca@MBP-di-Luca ~ % python3 -m pip show pyautogui
Name: PyAutoGUI
Version: 0.9.52
Summary: PyAutoGUI lets Python control the mouse and keyboard, and other GUI automation tasks. For Windows, macOS, and Linux, on Python 3 and 2.
Home-page: https://github.com/asweigart/pyautogui
Author: Al Sweigart
Author-email: al@inventwithpython.com
License: BSD
Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Requires: mouseinfo, pygetwindow, pymsgbox, pyobjc, pyobjc-core, pyscreeze, PyTweening
Required-by:
luca@MBP-di-Luca ~ % python3 -m pip show Pillow
Name: Pillow
Version: 9.1.0
Summary: Python Imaging Library (Fork)
Home-page: https://python-pillow.org
Author: Alex Clark (PIL Fork Author)
Author-email: aclark@python-pillow.org
License: HPND
Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages
Requires:
Required-by:

I already tried to unistall and reinstall the interested libraries, but it doesn't work.


text:
Q: Web.config Encryption Error Having problem with encryption. I gave full permissions to all users to RSA folders. I did
C:\>aspnet_regiis -pe "appSettings" -location "web.config" -prov "RsaProtectedCo
nfigurationProvider"
Encrypting configuration section...
An error occurred executing the configuration section handler for appSettings.

Failed to encrypt the section 'appSettings' using provider 'RsaProtectedConfigur
ationProvider'. Error message from the provider: Object already exists.

Failed!

Then I did
C:\>aspnet_regiis -pa "NetFrameworkConfigurationKey" "administrator"
Adding ACL for access to the RSA Key container...
The RSA key container was not found.
Failed!

Followed by
C:\>aspnet_regiis -pc "NetFrameworkConfigurationKey" -exp
Creating RSA Key container...
The RSA key container could not be opened.
Failed!

Nothing is working for me.
Can anyone help?
Thanks

A: I was getting the same issue with this failing:

aspnet_regiis -pa "NetFrameworkConfigurationKey" "{Domain}{Username}"

The above line was returning "The RSA key container was not found."
To fix this issue, I had to run Command Prompt as Administrator (open up Start > Accessories > then right-click Command Prompt and choose Run as administrator...). I had to do this even though my account was an administrator account.

A: C:\>aspnet_regiis -pe "appSettings" -location "web.config"
       -prov "RsaProtectedConfigurationProvider"

In this line your location is incorrect.  When you use the -pd switch location is based on IIS's application paths and web.config is assumed as the point of encryption.
So for example if you have an application named "Website 1" and another named "Website 2" in IIS, and you want the web.config in "Website 1" to be encrypted you would use this line:
C:\>aspnet_regiis -pe "appSettings" -location "Website 1"
        -prov "RsaProtectedConfigurationProvider"

Personally, I found it easier to use the -pef switch as I can point directly to the web app's physical directory.
Follow MSDN's tutorial on Encrypting Configuration Information Using Protected Configuration .  I've used it multiple times and have yet to have an issue doing encyrption.

A: You need to change "administrator" to whatever the account your ASP.NET service is running as. Because, chances are, you aren't running ASP.NET as administrator service account. If you are, then you should reconsider your decision.
For example, here's what I use:
 aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"

or
aspnet_regiis -pa "NetFrameworkConfigurationKey" "ASPNET"

Then for encryption, I use:
  aspnet_regiis -pef "connectionStrings"

or
 aspnet_regiis -pef "appSettings"

A: I had to find the folder where the certs are installed and take ownership/give permissions before the errors with the above commands would go away.  The errors said the key container could not be found, but really it was just that I didn't have permissions to the cert.  In my case I had inherited a development machine from someone else and needed to give myself permissions to the files before I could run the necessary commands.
I had hoped to give a more detailed response with cert folder locations, detailed steps, etc. but haven't had time and just wanted to note what I had to do in my scenario.


text:
Q: The gain of a non-inverting op amp I was attempting the following problem.

In the question it says there is a non inverting amplifier with a feedback resistor of 100k ohms and a source resistor of 5k ohms. If I use the regular non-inverting op amp formula for the gain I get 21 V/V as the answer.
But in the question itself it also says that the gain of the amplifier is 10 V/V. So which is it?
Also do they mean when they say that the gain is 10V/V, that the gain after removing the output voltage consumed by the input bias current and the off set current.

A: The non inverting amplifier setup they are describing looks like this:

simulate this circuit – Schematic created using CircuitLab
You need to calculate the value of R3.
When they talk about "what range of outputs would you expect", they are talking about the output with V1 == 0V. That is not 100% clear in the problem description.
So given that, you should be able to calculate the output offset voltage from the bias and offset currents (assume different signs of the offset to get a range). The rest of the problem should be self-explanatory.

A: The question is not well written.
I think they mean that the amplifier is wired as a non-inverting  amplifier with a feedback resistor of 100k.
Because of the bias current through the feedback network the actual output voltage will not be zero when the input is zero.
For example the 2uA bias current will cause 200mV to be dropped across 100K.
There will also be a voltage across the resistance of the source (5k) due to the input bias current.
It is your task to calculate the effect of the bias current given the input current and offset.
You are then asked how you would compensate for it.
The gain is taken as the slope of the output vs input so it ignores the offset voltages.
EDIT - removed reference to Thevenin equivalent resistance o feedback network.  Although correct it is probably not what was meant.


text:
Q: How to generate a Table of Contents "TOC" with iText? I've created a document with some Chapters.
How to generate a TOC for this document?
It should look like this:
TOC:
Chapter 1                        3
Chapter 2                        4
Chapter 3                        6
Chapter 4                        9
Chapter 5                       10

A: The answer by Christian Schneider seems somewhat complex. I would also use page event, but I would use the onChapter() method to create a list of chapter titles and page numbers. If you also need Section titles, use the onSection() method to keep track of the sections too.
Once you have this list, create the TOC at the end of the document. If you want to move the TOC to the front, read my answer to this question: PDF Page re-ordering using itext

A: This is possible by using PdfTemplates. PdfTemplates are a kind of placeholder that you can fill afterwards.
Update with the hints from Bruno:
To generate at TOC at the beginning, you need to put some Placeholders for all the page numbers in the TOC. Those PdfTemplates you collect in a Map. Then, when you add the Chapters to the document, you can fill those placeholders.
This example shows how:
package com.example.main;

import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.VerticalPositionMark;

public class Main extends PdfPageEventHelper {
    private final Document document;
    private final PdfWriter writer;
    private final BaseFont baseFont = BaseFont.createFont();
    private final Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 24, Font.NORMAL);

    // table to store placeholder for all chapters and sections
    private final Map<String, PdfTemplate> tocPlaceholder = new HashMap<String, PdfTemplate>();

    // store the chapters and sections with their title here.
    private final Map<String, Integer> pageByTitle = new HashMap<>();

    public static void main(final String[] args) throws Exception {
        final Main main = new Main();

        main.document.add(new Paragraph("This is an example to generate a TOC."));
        main.createTOC(10);
        main.createChapters(10);
        main.document.close();
    }

    public Main() throws Exception {
        this.document = new Document(PageSize.A6);
        this.writer = PdfWriter.getInstance(this.document, new FileOutputStream("test.pdf"));
        this.writer.setPageEvent(this);
        this.document.open();
    }

    @Override
    public void onChapter(final PdfWriter writer, final Document document, final float paragraphPosition, final Paragraph title) {
        this.pageByTitle.put(title.getContent(), writer.getPageNumber());
    }

    @Override
    public void onSection(final PdfWriter writer, final Document document, final float paragraphPosition, final int depth, final Paragraph title) {
        this.pageByTitle.put(title.getContent(), writer.getPageNumber());
    }

    private void createTOC(final int count) throws DocumentException {
        // add a small introduction chapter the shouldn't be counted.
        final Chapter intro = new Chapter(new Paragraph("This is TOC ", this.chapterFont), 0);
        intro.setNumberDepth(0);
        this.document.add(intro);

        for (int i = 1; i < count + 1; i++) {
            // Write "Chapter i"
            final String title = "Chapter " + i;
            final Chunk chunk = new Chunk(title).setLocalGoto(title);
            this.document.add(new Paragraph(chunk));

            // Add a placeholder for the page reference
            this.document.add(new VerticalPositionMark() {
                @Override
                public void draw(final PdfContentByte canvas, final float llx, final float lly, final float urx, final float ury, final float y) {
                    final PdfTemplate createTemplate = canvas.createTemplate(50, 50);
                    Main.this.tocPlaceholder.put(title, createTemplate);

                    canvas.addTemplate(createTemplate, urx - 50, y);
                }
            });
        }
    }

    private void createChapters(final int count) throws DocumentException {
        for (int i = 1; i < count + 1; i++) {
            // append the chapter
            final String title = "Chapter " + i;
            final Chunk chunk = new Chunk(title, this.chapterFont).setLocalDestination(title);
            final Chapter chapter = new Chapter(new Paragraph(chunk), i);
            chapter.setNumberDepth(0);

            chapter.addSection("Foobar1");
            chapter.addSection("Foobar2");
            this.document.add(chapter);

            // When we wrote the chapter, we now the pagenumber
            final PdfTemplate template = this.tocPlaceholder.get(title);
            template.beginText();
            template.setFontAndSize(this.baseFont, 12);
            template.setTextMatrix(50 - this.baseFont.getWidthPoint(String.valueOf(this.writer.getPageNumber()), 12), 0);
            template.showText(String.valueOf(this.writer.getPageNumber()));
            template.endText();

        }
    }
}

The generated PDF looks like this:
TableOfContents.pdf


text:
Q: PHPMailer sent but not delivered I have this debug code from my PHPMailer, it says the message was successfully sent, but I don't see any incoming email on my Gmail and other email. I've checked SPAM folder too, but nothing there.
here's the debug message :
2015-02-03 03:44:33 Connection: opening to localhost:26, t=300, opt=array ( )
2015-02-03 03:44:33 Connection: opened
2015-02-03 03:44:33 SERVER -> CLIENT: 220-la03.dewaweb.com ESMTP Exim 4.84 #2 Mon, 02 Feb 2015 19:44:33 -0800 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2015-02-03 03:44:33 CLIENT -> SERVER: EHLO *****.com
2015-02-03 03:44:33 SERVER -> CLIENT: 250-la03.dewaweb.com Hello localhost [127.0.0.1] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250-STARTTLS 250 HELP
2015-02-03 03:44:33 CLIENT -> SERVER: STARTTLS
2015-02-03 03:44:33 SERVER -> CLIENT: 220 TLS go ahead
2015-02-03 03:44:33 CLIENT -> SERVER: EHLO *****.com
2015-02-03 03:44:33 SERVER -> CLIENT: 250-la03.dewaweb.com Hello localhost [127.0.0.1] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP 2015-02-03 03:44:33  CLIENT -> SERVER: AUTH LOGIN
2015-02-03 03:44:33 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2015-02-03 03:44:33 CLIENT -> SERVER: bm8tcmVwbHlAZW1pdm9zb2x1dGlvbnMuY29t
2015-02-03 03:44:33 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2015-02-03 03:44:33 CLIENT -> SERVER: THVhcmJpYXNhSDg4MSE=
2015-02-03 03:44:33 SERVER -> CLIENT: 235 Authentication succeeded
2015-02-03 03:44:33 CLIENT -> SERVER: MAIL FROM:
2015-02-03 03:44:33 SERVER -> CLIENT: 250 OK
2015-02-03 03:44:33 CLIENT -> SERVER: RCPT TO:
2015-02-03 03:44:33 SERVER -> CLIENT: 250 Accepted
2015-02-03 03:44:33 CLIENT -> SERVER: DATA
2015-02-03 03:44:33 SERVER -> CLIENT: 354 Enter message, ending with "." on a line by itself
2015-02-03 03:44:33 CLIENT -> SERVER: Date: Tue, 3 Feb 2015 10:44:33 +0700
2015-02-03 03:44:33 CLIENT -> SERVER: To: no-reply@*****.com
2015-02-03 03:44:33 CLIENT -> SERVER: From: "*****.com"
2015-02-03 03:44:33 CLIENT -> SERVER: Reply-To: *****@gmail.com
2015-02-03 03:44:33 CLIENT -> SERVER: Subject: Segera Aktifkan Account Anda
2015-02-03 03:44:33 CLIENT -> SERVER: Message-ID: <9cd5d51370aedccf9154c8d87f109caf@*****.com>
2015-02-03 03:44:33 CLIENT -> SERVER: X-Priority: 3
2015-02-03 03:44:33 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.9 (https://github.com/PHPMailer/PHPMailer/)
2015-02-03 03:44:33 CLIENT -> SERVER: MIME-Version: 1.0
2015-02-03 03:44:33 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2015-02-03 03:44:33 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2015-02-03 03:44:33 CLIENT -> SERVER:
2015-02-03 03:44:33 CLIENT -> SERVER: Halo, Robert
2015-02-03 03:44:33 CLIENT -> SERVER: .
2015-02-03 03:44:33 SERVER -> CLIENT: 250 OK id=1YIUPh-002egj-8a
2015-02-03 03:44:33 CLIENT -> SERVER: QUIT
2015-02-03 03:44:33 SERVER -> CLIENT: 221 la03.dewaweb.com closing connection
2015-02-03 03:44:33 Connection: closed
2015-02-03 03:44:33 Connection: opening to localhost:26, t=300, opt=array ( )
2015-02-03 03:44:33 Connection: opened
2015-02-03 03:44:33 SERVER -> CLIENT: 220-la03.dewaweb.com ESMTP Exim 4.84 #2 Mon, 02 Feb 2015 19:44:33 -0800 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2015-02-03 03:44:33 CLIENT -> SERVER: EHLO *****.com
2015-02-03 03:44:33 SERVER -> CLIENT: 250-la03.dewaweb.com Hello localhost [127.0.0.1] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250-STARTTLS 250 HELP
2015-02-03 03:44:33 CLIENT -> SERVER: STARTTLS
2015-02-03 03:44:33 SERVER -> CLIENT: 220 TLS go ahead
2015-02-03 03:44:33 CLIENT -> SERVER: EHLO *****.com
2015-02-03 03:44:33 SERVER -> CLIENT: 250-la03.dewaweb.com Hello localhost [127.0.0.1] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250 HELP
2015-02-03 03:44:33 CLIENT -> SERVER: AUTH LOGIN
2015-02-03 03:44:33 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2015-02-03 03:44:33 CLIENT -> SERVER: bm8tcmVwbHlAZW1pdm9zb2x1dGlvbnMuY29t
2015-02-03 03:44:33 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2015-02-03 03:44:33 CLIENT -> SERVER: THVhcmJpYXNhSDg4MSE=
2015-02-03 03:44:33 SERVER -> CLIENT: 235 Authentication succeeded
2015-02-03 03:44:33 CLIENT -> SERVER: MAIL FROM:
2015-02-03 03:44:33 SERVER -> CLIENT: 250 OK
2015-02-03 03:44:33 CLIENT -> SERVER: RCPT TO:
2015-02-03 03:44:33 SERVER -> CLIENT: 250 Accepted
2015-02-03 03:44:33 CLIENT -> SERVER: DATA
2015-02-03 03:44:33 SERVER -> CLIENT: 354 Enter message, ending with "." on a line by itself
2015-02-03 03:44:33 CLIENT -> SERVER: Date: Tue, 3 Feb 2015 10:44:33 +0700
2015-02-03 03:44:33 CLIENT -> SERVER: To: no-reply@*****.com
2015-02-03 03:44:33 CLIENT -> SERVER: From: "*****.com"
2015-02-03 03:44:33 CLIENT -> SERVER: Reply-To: *****@gmail.com
2015-02-03 03:44:33 CLIENT -> SERVER: Subject: Segera Aktifkan Account Anda
2015-02-03 03:44:33 CLIENT -> SERVER: Message-ID:
2015-02-03 03:44:33 CLIENT -> SERVER: X-Priority: 3
2015-02-03 03:44:33 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.9 (https://github.com/PHPMailer/PHPMailer/)
2015-02-03 03:44:33 CLIENT -> SERVER: MIME-Version: 1.0
2015-02-03 03:44:33 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2015-02-03 03:44:33 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2015-02-03 03:44:33 CLIENT -> SERVER:
2015-02-03 03:44:33 CLIENT -> SERVER: Halo, Robert
2015-02-03 03:44:33 CLIENT -> SERVER: .
2015-02-03 03:44:33 SERVER -> CLIENT: 250 OK id=1YIUPh-002egn-EI
2015-02-03 03:44:33 CLIENT -> SERVER: QUIT
2015-02-03 03:44:33 SERVER -> CLIENT: 221 la03.dewaweb.com closing connection
2015-02-03 03:44:33 Connection: closed
Message sent!

A: Your local mail server is accepting the message successfully, but apparently it's not getting anywhere beyond that. It could be bouncing for some reason, or outbound could be broken. You will need to look in your mail server logs to see what has happened to it, or you could try sending directly to your gmail address.


text:
Q: android google maponClick not responsive I have a map in my layout which when clicked should addmarker to it and display it on map.But the onMapClick method is not triggered when clicked.Below is the code":
Details.java:
public class Details extends AppCompatActivity implements OnMapReadyCallback,GoogleMap.OnMapClickListener {
   SupportMapFragment mapFragment;
   private GoogleMap map;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.details);
       mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map1);
       mapFragment.getMapAsync(this);

   }
   @Override
   public void onMapReady(GoogleMap googleMap) {
      map=googleMap; LatLng bolg = new LatLng(9.984616,76.267082);
         map.addMarker(newMarkerOptions().position(bolg).title("Demo")).showInfoWindow(); map.moveCamera(CameraUpdateFactory.newLatLng(bolg));
      map.animateCamera(CameraUpdateFactory.zoomTo(7), 3000, null);
      map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

   }
   @Override
   public void onMapClick(LatLng latLng) {
      Log.e("LongClick","clicked");
      map.addMarker(new MarkerOptions().position(latLng).title("X")).showInfoWindow();
      map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
      map.animateCamera(CameraUpdateFactory.zoomTo(7), 3000, null);
      map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
   }
}

details.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<fragment
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:id="@+id/map1"
    android:name="com.google.android.gms.maps.SupportMapFragment">
    </fragment>

</LinearLayout>

A:
To detect user click event on GoogleMap, modify the AppCompatActivity
  implements OnMapClickListener, override onMapClick(LatLng point), and
  call map.setOnMapClickListener(this).

map.setOnMapClickListener(this);

A: In your onMapReady set an on click listener map.setOnclicklistener

A: After getting google map from mapfragment you need to do the following for receiving click events.
GoogleMap mGoogleMap = mapFragment.getMap();
mGoogleMap.setOnMapClickListener(this);

you need to implement this listener also GoogleMap.OnMapClickListener


text:
Q: No Outputs section in cloudformation template In cloudformation template, there is an outputs sections which is used for talking to cross-stack.
Is that correct to say that this part should not exist if there is only one stack we are creating in one AWS account?

A: The outputs section can be used for cross-stack references with Export and Fn::ImportValue. It can also be used for general output for the user. A few examples:

*

*Admin URL like https://123.123.123.123/admin

*Credentials for a newly created user

*Identifier for any of the resources for easy access

*An attribute of a resource like EC2 instance IP address


text:
Q: Image of polynomial is $\mathbb{Q}$ I know that the polynomial $f(x)=\frac{1}{2} x^2 + \frac{1}{2}x \in \mathbb{Q}[x] $ has that $f(\mathbb{Z})\subset\mathbb{Z}$.
My question is a bit different: Does there exist a polynomial $f \in \mathbb{R}[x]$ such that $f(\mathbb{Z}) = \mathbb{Q}$? What about a polynomial that $f(\mathbb{Q}) = \mathbb{Z}$?
I suspect that both polynomials do not exist, but I do not know how to prove it.

A: there is no polynomial $f$ such that $f (\Bbb{Q}) = \Bbb{Z}$:
Suppose $f(X)=a_nX^n+...+a_1X+a_0$ is such a polynomial,  then $f
(0) =a_0= n_0\in \Bbb{Z}$, so the polynomial
$g_1(X)=\frac{(f-n_0)(X)}{X}(\Bbb{Q})\subset  \Bbb{Z} $ and then result
$g_1(O)= a_1 = n_1\in \Bbb{Z}$, by repeating this reasoning $f$ to be
an element of $\Bbb{Z}[X]$, let   $m = lcm(n_i)$ then for suitable m' depending to m , $f (1 / m')\not\in
\Bbb{Z}$.
using the same reasoning if $f$ is such that $f (\Bbb{Z}) =
\Bbb{Q}$, then $f$ is in $\Bbb{Q}[X]$,  and  the fiber $f^{-1}
(x)$ is empty for all $x \in \Bbb{Q}\cap] f (n), f (n + 1)[$ for
suitable $n$.

A: 1st question: non-constant polynomials have infinite limits as $n\to\infty$, so can talk only finitely many values in the interval $(0,1)$, so no polynomial can take all rational values in $(0,1)$. (by @ThomasAndrews)
2nd question: $f(\mathbb{Q})$ is dense in $f(\mathbb{R})$ which is connected, so we cannot have $f(\mathbb{Q})=\mathbb{Z}$. (by @GEdgar)
If you prefer a non-topological argument, the result obviously holds for $f$ constant. So $f'$ has only finitely many roots. Take $a$ such that $f'(a)\ne0$, then for large enough $n$, $f(a+\frac{1}{n})-f(a)$ cannot be an integer - it must converge to 0, but a non-trivial sequence of integers cannot do that. (by @ErickWong and @Hmm.).


text:
Q: Point of reflection on a circle I am trying to find the point on a circle where a light source is reflected to the focal point of a camera...
So I have the coordinates of the light source, the focal point and the centre of a circle. I believe the light will reflect at an angle equal to the incident angle. I have tried forming equations with this information but I always seem to have too many unknowns...
Diagram of problem
Thanks for any help!

A: Define $\tan A={y_1-y_p\over x_1-x_p}\ ;\ \tan B={y_0-y_p\over x_0-x_p}\ \&\ \tan C={y_2-y_p\over x_2-x_p}$
Since incident angle equals reflected angle,at $(x_p,y_p)$, so $$\tan (A-B)=\tan (B-C)\implies {\tan A-\tan B\over 1+\tan A\tan B}={\tan B-\tan C\over 1+\tan B\tan C}$$
Moreover, since $x_p,y_p$ must be on a circle, you must know its radius$(=r)$: there goes another equation $$(x_0-x_p)^2+(y_0-y_p)^2=r^2$$
$2$ equation and $2$ unknowns ,BINGO!

A: To make things easier, I limit all the points to the first quadrant and I also assume that the mirror surface is the horizontal tangent line y = k. Our target is to find k.

Let R be the reflection of Q about the line y = k. Because of the angle of incidence = angle of reflection, we have two sets of equal angles (red and green). Then, $R = (x_2, 2k – y_2)$.
Equation of PR is $L :\dfrac {y – y_1}{x – x_1} = \dfrac {(2k – y_2) – y_1}{x_2 – x_1}$.
Solving L and y = k, we will get the co-ordinates of O which is precisely $(x_0, k)$. Then we have one equation and only one unknown.
Note:- Special treatment will be needed in cases like $x_1 = x_2$ etc.


text:
Q: Return vs. Not Return of functions? Return or not return, it's a question for functions! Or, does it really matter?

Here goes the story:
I used to write code like the following:
Type3 myFunc(Type1 input1, Type2 input2){}

But recently my project colleges told me that I should try, as mush as possible, to avoid writing function like this, and suggest the following way by putting the returned value in the input parameters.
void myFunc(Type1 input1, Type2 input2, Type3 &output){}

They convinced me that this is better and faster because of the extra copying step when returning in the first method.

For me, I start to believe that the second method is better in some situations, especially I have multiple things to return or modify. For example: the second line of following will be better and faster than the first one as avoiding copying the whole vecor<int> when returning.
vector<int> addTwoVectors(vector<int> a, vector<int> b){}
void addTwoVectors(vector<int> a, vector<int> b, vector<int> &result){}:

But, in some other situations, I cannot buy it. For example,
bool checkInArray(int value, vector<int> arr){}

will be definitely better than
void checkInArray(int value, vector<int> arr, bool &inOrNot){}

In this case, I think the first method by directly return the result is better in terms of better readability.

In summary, I am confused about (emphasis on C++):

*

*What should be returned by functions and what should not (or try to avoid)?

*Is there any standard way or good suggestions for me to follow?

*Can we do better in both in readability and in code efficiency?

Edit:
I am aware of that, under some conditions, we have to use one of them. For example, I have to use return-type functions if I need to achieve method chaining. So please focus on the situations where both methods can be applied to achieve the goal.
I know this question may not have a single answer or sure-thing. Also it seems this decision need to be made in many coding languages, like C, C++, etc. Thus any opinion or suggestion is much appreciated (better with examples).

A: As always when someone brings the argument that one thing is faster than the other, did you take timings? In fully optimized code, in every language and every compiler you plan to use? Without that, any argument based on performance is moot.
I'll come back to the performance question in a second, just let me address what I think is more important first: There are good reasons to pass function parameters by reference, of course. The primary one I can think of right now is that the parameter is actually input and output, i.e., the function is supposed to operate on the existing data. To me, that is what a function signature taking a non-const reference indicates. If such a function then ignores what is already in that object (or, even worse, clearly expects to only ever get a default-constructed one), that interface is confusing.
Now, to come back to performance. I cannot speak for C# or Java (though I believe returning an object in Java would not cause a copy in the first place, just passing around a reference), and in C, you do not have references but might need to resort to passing pointers around (and then, I do agree that passing in a pointer to uninitialized memory is ok). But in C++, compilers have for a long time done return value optimization, RVO, which basically just means that in most calls like A a = f(b);, the copy constructor is bypassed and f will create the object directly in the right place. In C++11, we even got move semantics to make this explicit and use it in more places.
Should you just return an A* instead? Only if you really long for the old days of manual memory management. At the very least, return an std::shared_ptr<A> or an std::unique_ptr<A>.
Now, with multiple outputs, you get additional complications, of course. The first thing to do is if your design is actually proper: Each function should have a single responsibility, and usually, that means returning a single value as well. But there are of course exceptions to this; e.g., a partitioning function will have to return two or more containers. In that situation, you may find that the code is easier to read with non-const reference arguments; or, you may find that returning a tuple is the way to go.
I urge you to write your code both ways, and come back the next day or after a weekend and look at the two versions again. Then, decide what is easier to read. In the end, that is the primary criterion for good code. For those few places where you can see a performance difference from an end-user workflow, that is an additional factor to consider, but only in very rare cases should it ever take precedence over readable code – and with a little more effort, you can usually get both to work anyway.

A: Due to Return Value Optimization, the second form (passing a reference and modifying it) is almost certainly slower and less amendable to optimization, as well as less legible.
Let us consider a simple example function:
return_value foo( void );

Here are the possibilities that may occur:

*

*Return Value Optimization (RVO)

*Named Return Value Optimization (NRVO)

*Move semantic return

*Copy semantic return

What is Return Value Optimization? Consider this function:
return_value foo( void ) { return return_value(); }

In this example, an unnamed temporary variable is returned from a single exit point. Because of this, the compiler can easily (and is free to) completely remove any traces of this temporary value, and instead construct it directly in place, in the calling function:
void call_foo( void )
{
    return_value tmp = foo();
}

In this example, tmp is actually directly used in foo as if foo defined it, removing all copies. This is a HUGE optimization if return_value is a non-trivial type.
When can RVO be used? That's up to the compiler, but in general, with a single return code point, it will always be used. Multiple return code points make it more iffy, but if they are all anonymous, your chances increase.
What about Named Return Value Optimization?
This one is a bit trickier; if you name the variable before you return it, it's now an l-value. This means the compiler has to do more work to prove that the in place construction will be possible:
return_type foo( void )
{
    return_type bar;
    // do stuff
    return bar;
}

In general, this optimization is still possible, but less likely with multiple code paths, unless each code path returns the same object; returning multiple different objects from multiple different code paths tends to not difficult to optimize out:
return_type foo( void)
{
    if(some_condition)
    {
        return_type bar = value;
        return bar;
    }
    else
    {
        return_type bar2 = val2;
        return bar2;
    }
}

This is not going to be as well received. It's still possible NRVO could kick in, but it's getting less and less likely. If at all possible, construct a single return_value and tweak it in different code paths, rather than returning wholly different ones.
If NRVO is possible, this will get rid of any overhead; it will be as if it was constructed directly in the calling function.
If neither form of return value optimization is possible, Move return may be possible.
C++11 and C++03 both have the possibility to do move semantics; rather than copying the information out of one object into another, move semantics allow one object to steal the data in another, setting it to some default state. For C++03 move semantics, you need boost.move, but the concept is still sound.
Move return isn't as fast as RVO return, but it's drastically faster than a copy. For a compliant C++11 compiler, of which there are many today, all STL and STD structures should support move semantics. Your own objects may not have a default move constructor/assignment operator (MSVC do not currently have default move semantic operations for user defined types), but adding move semantics is not hard: just use the copy-and-swap idiom to add it!
What is the copy-and-swap idiom?
Finally, if your return_value does not support move and your function is too hard to RVO, you will default to copy semantics, which is what your friend said to avoid.
However, in a large amount of cases, this will not be significantly slower!
For primitive types, such as float or int or bool, copying is a single assignment or move; hardly the sort of thing to complain about; passing such things by reference without a really good reason is sure to make your code slower, as references are internally pointers. For something like your bool example, there's no reason to waste time or energy passing a bool by reference; returning it is the fastest possible way.
When you return something that fits in a register, it's usually returned in a register for exactly that reason; it's fast, and as noted, easiest to maintain.
If your type is a POD type, such as a simple struct, this can often be passed through registers via a fastcall mechanism, or optimized away into direct assignments.
If your type is a large and imposing type, such as std::string or something with a lot of data behind it, requiring lots of deep copies, and your code is sufficiently complex as to make RVO unlikely, then perhaps passing by reference is a better idea.
Summary

*

*Anonymous (rvalue) values of any kind should be returned by value

*Small or primitive types should be returned by value.

*Any type supporting move semantics (the STL, STD, etc) should be returned by value

*Named (lvalue) values that are easy to reason about should be returned by value

*Large data types in complex functions should be profiled or passed by reference

Always return by value when possible, if you are using C++11. It's more legible, and faster.

A: There's no single answer to this question, but as you already stated, the central part is: It depends.
Clearly, for simple types, such as ints or bools, the return value is generally the preferred solution. It is easier to write and also less error-prone (i.e. because you cannot pass something undefined to the function and you don't need to separately define the variable before the call instruction). For complex types, such as a collection, the call-by-reference might be preferred because it avoids, as you say, the extra copy step. But you could also return a vector<int>* instead of just a vector<int>, which archives the same (for the cost of some extra memory-management, though). All this, however, also depends on the language used. The above will mostly hold true for C or C++, but for managed classes such as Java or C#, most complex types are reference-types anyway, so returning a vector does not involve any copying there.
Of course, there are situations where you do want the copy to happen, i.e. if you want to return the (copy of) an internal vector in such a way that the caller cannot modify the internal data structure of the called class.
So again: It depends.

A: This is a distinction between methods and functions.
Methods (a.k.a. subroutine) are called primarily called for their side effect, which is to modify one or more of the objects passed into it as parameter. In languages that supports OOP, the object to be modified is usually implicitly passed as this/self parameter.
Functions, on the other hand, are called primarily for their return value, it calculates something new  and shouldn't modify the parameters at all and should avoid side effects. Functions should be pure in the functional programming sense.
If a function/method is meant to create a new object (i.e. a factory) then the object should be returned. If you pass in a reference to variable, then it isn't clear who will be responsible for cleaning up the object previously contained in the variable, the caller or the factory? With factory function, it's clear that the caller is responsible for ensuring cleanup of the previous object; with factory method, it's not so clear because the factory can do cleanup, although that's often a bad idea for various reasons.
If a function/method is meant to modify an object or objects, then the object (s) should be passed in as argument, the object(s) that have been modified shouldn't be returned (an exception to this is if you're designing for fluent interface/method chaining in a language that supports them).
If your objects are immutable, then you should always use functions because every operations on immutable objects must create new object.
Adding two vectors should be a function (use return value), because the return value is a new vector. If you're adding another vector to an existing vector then that should be a method since you're modifying an existing vector and not allocating a new one.
In a language that doesn't support exception, return value is often used to signal error value; however on languages that supports exception, error conditions should always be signaled with exception, and there should never be a method that return a value, or a function that modified its arguments. In other words, don't do side effects and return a value within the same function/method.

A: What should be returned by functions and what should not (or try to avoid)?
 It depends on what your method is supposed to do.
When your method modifies the list or returns new data you should use the return value. Its much better to understand what your code does than using a ref parameter.
Another benefit of return values is the ability to use method chaining.
You can write code like this which passes the list parameter from one method to another:
method1(list).method2(list)...

A: As as been said, there is no general answer.  But no one has talked about the machine level, so I'll do that and try some examples.
For operands that fit in a register, the answer is obvious.  Every compiler I've seen will use a register for the return value (even if it's a struct).  This is as efficient as you'll get.
So the remaining question is large operands.
At this point it's up to the compiler.  It is true that some (especially older) compilers would emit a copy to implement return of a value larger than a register.  But this is dark ages technology.
Modern compilers - primarily because RAM is much bigger these days, and that makes life much better - are not so stupid. When they see "return foo;" in a function body and foo does not fit in a register, they mark foo as a reference to memory. This is memory allocated by the caller to hold the return value. Consequently, the compiler ends up generating almost exactly the same code as it would if you had passed a reference to return value yourself.
Let's verify this.  Here's a simple program.
struct Big {
  int a[10000];
};

Big process(int n, int c)
{
  Big big;
  for (int i = 0; i < 10000; i++)
    big.a[i] = n + i;
  return big;
}

void process(int n, int c, Big& big)
{
  for (int i = 0; i < 10000; i++)
    big.a[i] = n + i;
}

Now I'll compile it with the XCode compiler on my MacBook.  Here's the relevant output for the return version:
    xorl    %eax, %eax
    .align  4, 0x90
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
    leal    (%rsi,%rax), %ecx
    movl    %ecx, (%rdi,%rax,4)
    incq    %rax
    cmpl    $10000, %eax            ## imm = 0x2710
    jne     LBB0_1
## BB#2:
    movq    %rdi, %rax
    popq    %rbp
    ret

and for the reference version:
    xorl    %eax, %eax
    .align  4, 0x90
LBB1_1:                                 ## =>This Inner Loop Header: Depth=1
    leal    (%rdi,%rax), %ecx
    movl    %ecx, (%rdx,%rax,4)
    incq    %rax
    cmpl    $10000, %eax            ## imm = 0x2710
    jne     LBB1_1
## BB#2:
    popq    %rbp
    ret

Even if you don't read assembly language code, you can see the similarity.  There is perhaps one instruction's difference.  This is with -O1.  With optimization off, the code is longer, but still almost identical.  With gcc version 4.2, the results are very similar.
So you should tell your friends "no".  Using a return value with a modern compiler has no penalty.

A: To me, the passing of a non-const pointer means two things:

*

*The parameter may be changed in-place (you can pass a pointer to a struct member and obviate assignment);

*The parameter needs not be returned if null is passed.

The latter may allow to avoid a whole possibly expensive branch of code that calculates its output value because it is not desired anyway.
I see this as an optimization, that is, something which is done when performance impact is measured or at least estimated. Otherwise I prefer as immutable data as possible, and as pure functions as possible, to simplify correct reasoning about the program's flow.
Usually correctness beats performance, so I'd stay with clear separation of (const) input parameters and a return struct, unless it's obviously or provably hampers performance or code readability.
(Disclaimer: I don't usually write in C.)


text:
Q: NameNotFoundException Java Enterprise Application I am working on a Java Enterprise application which have an EJB layer and a WEB layer bundled together with an EAR. The problem I am facing is that I have some entities in my EJB layer and when I try to get their EAOs by JNDI in my WEB layer, I get NameNotFoundException.
My Ear name is : StudentManagement
My EJB layer is : StudentManagementEJB
My Web layer is : StudentManagementWEB
Application Server : JBOSS-4.2
My Entity Class :
@Entity
@Table(name="student")
public class Student implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="student_id")
private int studentId;

@Column(name="sudent_name")
private String studentName;

@Column(name="student_class")
private String studentClass;

public int getStudentId() {
    return studentId;
}

public void setStudentId(int studentId) {
    this.studentId = studentId;
}

public String getStudentName() {
    return studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

public String getStudentClass() {
    return studentClass;
}

public void setStudentClass(String studentClass) {
    this.studentClass = studentClass;
}
}

My Remote Inteface :
@Remote
public interface StudentEAO {

public void save(Student student);

}

My Interface Implementation:
@Stateless
public class StudentEAOImpl implements StudentEAO {

@PersistenceContext
private EntityManager entityManager;
/* (non-Javadoc)
 * @see com.learn.interfce.StudentEAO#save(com.learn.entity.Student)
 */
@Override
public void save(Student student) {
    // TODO Auto-generated method stub
    try{
        entityManager.persist(student);
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

}

And In my servlet, I am trying to get StudentEAOImpl  Object as
   try {
        StudentEAO studentEao = (StudentEAO) new InitialContext().lookup("StudentManagement/StudentEAOImpl/remote");
        studentEao.save(student);
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

StackTrace of ERROR :
01:15:45,539 INFO  [STDOUT] Hello World from StudentActionServlet.
01:15:45,543 ERROR [STDERR] javax.naming.NameNotFoundException: StudentManagement not bound
01:15:45,543 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:529)
01:15:45,543 ERROR [STDERR] at org.jnp.server.NamingServer.getBinding(NamingServer.java:537)
01:15:45,543 ERROR [STDERR] at org.jnp.server.NamingServer.getObject(NamingServer.java:543)
01:15:45,543 ERROR [STDERR] at org.jnp.server.NamingServer.lookup(NamingServer.java:267)
01:15:45,543 ERROR [STDERR] at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:628)
01:15:45,543 ERROR [STDERR] at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:590)
01:15:45,543 ERROR [STDERR] at javax.naming.InitialContext.lookup(InitialContext.java:392)
01:15:45,543 ERROR [STDERR] at com.learn.servlets.StudentActionServlet.doGet(StudentActionServlet.java:46)

I am not getting what I am missing here. Please help me in this regard.
Thanks!

A: Atlast! Issue resolved and here are my findings about that:
1- You have to check your EJB, WEB and EAR layer compiler level, It all should be same.
2- Check your EAR name while giving JNDI name , means if your JNDI name is : MyEar/MYEJB/remote, then MyEar should be your EA-Project name.
3- You server log must be clean. It should not produce any critical exception which may be show-stopper.
After doing all these checks and fixes, my issue is resolved.
Hopefully it will help someone.

A: Try to bind your EAOImpl class manually as follows:
@RemoteBinding(jndiBinding="StudentManagement/StudentEAOImpl/remote")


text:
Q: Thymeleaf does not resolve fragment in my app when I call it in brackets. Why is that? I am new to spring and thymeleaf.
I have a spring-boot web application with thymeleaf, and I encountered a problem.
This line works perfectly:
Footer

But when I write brackets around it, as in the documentation, I get an error.
Footer

Error:

There was an unexpected error (type=Internal Server Error, status=500).
  Error resolving template "~{fragments/footer", template might not exist or might not be accessible by any of the configured Template Resolvers (index:11)

So what can be the problem, I use the default spring boot configuration.
pom.xml :
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Log:

2017-03-01 22:47:51.585 ERROR 4014 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "index": Error resolving template "~{fragments/footer", template might not exist or might not be accessible by any of the configured Template Resolvers (index:11)
  2017-03-01 22:47:51.591 ERROR 4014 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template "~{fragments/footer", template might not exist or might not be accessible by any of the configured Template Resolvers (index:11)] with root cause
  org.thymeleaf.exceptions.TemplateInputException: Error resolving template "~{fragments/footer", template might not exist or might not be accessible by any of the configured Template Resolvers (index:11)
      at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
      at org.thymeleaf.standard.fragment.StandardFragment.extractFragment(StandardFragment.java:202) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
      at org.thymeleaf.standard.processor.attr.AbstractStandardFragmentHandlingAttrProcessor.computeFragment(AbstractStandardFragmentHandlingAttrProcessor.java:72) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
      at org.thymeleaf.processor.attr.AbstractFragmentHandlingAttrProcessor.processAttribute(AbstractFragmentHandlingAttrProcessor.java:63) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]

A: Looks like you are using thymeleaf 2.  Fragment expressions are new to thymeleaf 3.
http://www.thymeleaf.org/doc/articles/thymeleaf3migration.html#fragment-expressions


text:
Q: In NASM labels next to each other in memory are printing both strings instead of first one I am having an issue while programming in NASM. I am learning how to develop an OS purely in assembly and have started by creating a boot loader.
My goal currently is to print "Hello, World!" and "Goodbye!" using the the BIOS interrupt 0x10.
The issue I seem to be having occurs while printing values on the screen. Two labels appear to be next to each other in memory causing printing one string to print the contents of the other string.
Why isn't hlen stopping the loop at the end of the first string?
    [org 0x7c00]

    mov ah, 0x0e

    mov bx, HELLO_MSG
    mov cx, hlen
    call print_string

    mov bx, GOODBYE_MSG
    mov cx, glen
    call print_string

    jmp $

    %include "print_string.asm"

    HELLO_MSG db 'Hello, World!',0
    GOODBYE_MSG db 'Goodbye!',0

    hlen equ $ - HELLO_MSG
    glen equ $ - GOODBYE_MSG

    times 510-($-$$) db 0
    dw 0xaa55

BUGS:

*

*Prints goodbye message twice
This is due to the HELLO_MSG printing Hello, World! and Goodbye!.
I believe this occurs because the Hello_MSG label is right next to the GOODBYE_MSG label in memory

;;;print_string.asm
print_string:                   ;cx = string length
                                ;bX = string label - memory offset
                                ; -- if you want the data at a memory adress use [bx]
        mov al, [bx]
        int 0x10

        inc bx

        loop print_string

        ret

A: Your computation of hlen includes the string Goodbye! because it comes after the defintion of GOODBYE_MSG. The expression $ - HELLO_MSG is the number of bytes between the label HELLO_MSG and the line where hlen is defined. That is why your first call to print_string prints both messages.
Try this order instead:
HELLO_MSG db 'Hello, World!',0
hlen equ $ - HELLO_MSG

GOODBYE_MSG db 'Goodbye!',0
glen equ $ - GOODBYE_MSG

See How does $ work in NASM, exactly? for more details, including this as an example.


text:
Q: how to give an array as option values in select using select2 This is my html
<select class="compare-tag1">
 </select>

this is the array i want to be there as option values in the above select class:
optionVal = ["1","2","3"];

and this is how I am trying to do it with select2
$(".compare-tag1").select2({
    val: tagValuesArray
    });

Im getting no-error,but no values are shown in the dropdown. How can I get the values of the array as option values using select2?

A: It sounds like you might be looking for the data option, which will convert a an array of data objects (or single strings) into <option> tags.
$(".compare-tag1").select2({
  data: tagValuesArray
});


text:
Q: How can I update app content frequently? I'm new to app development and I am soon going to be developing an app for a local charity.
The charity is a dog rescue charity and the app will display information about dogs available for adoption.
The content will obviously need to be updated frequently, even daily, which will obviously not work constantly updating the app via the relevant app stores. What is the most common way to deliver content to an app?
My thoughts on previous experience would be to create a REST API and deliver the content remotely. Would an app allow this? Is there a method more generally used?
Thanks in advance.

A: I see you don't have clear specification on how often to update the app content and technical capability.
Use JobScheduler
Syncing to the backend (via REST API)to fetch the data is a battery drainer & there is no use in syncing data on device which is about to die, I would prefer Jobscheduler which will intelligently act as per various environment criteria met like charging/idle.
There are several facilities available to help your app schedule work. These include:

*

*AlarmManager

*JobScheduler

*SyncAdapter

Caution: Exponential backoff is enabled on job dispactchers/schedulers
For 24-hour logic check here

A: You can save all the information to show of each dog available to adoption in a database, then make the app retrieve all the data from it every n time.
I recommend you to use Firebase, it is cross-platform (includes Android and iOS), and I consider it really good when starting using databases.
Here you can find documentation for every supported platform, and easy examples on how to work with it.
Good luck with your project! :)


text:
Q: I need regular expression for allow only letters,numbers and white space but not allow special characters I need regular expression for allow only letters,numbers and white space but not allow special characters This is my code
<input type="text" name="station_name" class="form-control" data-validation="required" data-validation-regexp="/^[a-zA-Z ]*$/"  data-validation-error-msg="Please enter the valid Station Name" maxlength="50" value="<?php  echo $shop_name;?>">

A: Try this:
<input type="text" name="station_name" class="form-control" data-validation="required" data-validation-regexp="/^[\s0-9A-Za-z]+$/"  data-validation-error-msg="Please enter the valid Station Name" maxlength="50" value="<?php  echo $shop_name;?>">

A: Please correct your regexp from:
/^[a-zA-Z ]*$/

To:
/^[\s0-9A-Za-z]+$/

So finally code like:
<input type="text" name="station_name" class="form-control" data-validation="required" data-validation-regexp="/^[\s0-9A-Za-z]+$/"  data-validation-error-msg="Please enter the valid Station Name" maxlength="50" value="<?php  echo $shop_name;?>">


text:
Q: Fastest method of searching and removing elements from a sorted vector of integers in C++ I have a large vector of sorted integers. I need to quickly find and remove eight values from the array.
For example, vector a includes the elements
{1, 4, 7, 15, 16, 19, 24, 26, 31, 53, 67, 68, 73, 75, 77, 82}

vector b includes the eight values
{4, 15, 19, 24, 67, 68, 73, 75}

After completing the operation, vector a should now have
{1, 7, 16, 26, 31, 53, 77, 82}

My old solution was pretty slow:
for (vector<int>::iterator val = b.begin(); val != b.end(); val++)
        a.erase(remove(a.begin(), a.end(), *val), a.end());

Is there a faster method?
EDIT:
Actually, my "A" vector is a lot larger than my "B" vector. Maybe it's better to just search for the individual elements via a binary search and delete them?
EDIT2:
Perhaps a vector isn't a good container for this kind of operation. I don't think I can use forward_list because I cannot compile with C++11. Maybe I can use a different container and then copy the results into a vector afterwards?

A: I would probably do something like:
std::vector<int> temp;

std::set_difference(a.begin(), a.end(),
                    b.begin(), b.end(),
                    std::back_inserter(temp));
std::swap(a, temp);

Edit based on edited question:
Given that your a vector is substantially larger than your b vector, there's a second question I'd consider: do you need a to remain sorted after this is complete?
If rearranging elements in a is allowed, then you can improve speed substantially: instead of doing a remove/erase to remove the items from the middle of a, you can swap the item to be removed with the last element of a, then erase it from the end (which has constant complexity). This makes the removals constant, so the overall complexity is O(N log M) (where N = b.size() and M = a.size()).
If you do have to maintain order, you can still improve speed somewhat: instead of removing elements from a, then immediately erasing the removed element, do an std::remove_if to find all the elements of a that need to be removed, then once (when that's done) do one erase to remove all those elements.
As it stands right now, you're using a separate call to remove for each element of a that you remove. All the elements of a after each removal point are copied (or moved, if applicable) for each remove. That means if you remove 10 elements from a, you're copying (on average) half of a 10 times over. By using a single remove_if instead, you're copying each element of a only once.
Unfortunately, remove_if doesn't give you a good way to take advantage of the ordering in b. You can use a binary search, which helps some, but not as much as you'd like.
If you don't mind writing your own loop, you can take full advantage of the fact that both a and b are sorted, something like this:
#include <vector>
#include <iostream>

// Compute the difference between two "set"s in-place. Each 'set' must be a
// sorted sequence.
//
template <class FwdIt, class InIt>
FwdIt
inplace_set_difference(FwdIt b1, FwdIt e1, InIt b2, InIt e2) {
    FwdIt pos = b1;
    while (pos != e1 && b2 != e2) {
        if (*pos < *b2)
            *b1++ = *pos++;
        else if (*b2 < *pos)
            ++b2;
        else
            ++pos;
    }
    while (pos != e1)
        *b1++ = *pos++;
    return b1;
}

int main() {
    std::vector<int> a{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    std::vector<int> b{ 2, 5, 9 };

    auto it = inplace_set_difference(a.begin(), a.end(), b.begin(), b.end());
    a.erase(it, a.end());

    for (auto i : a)
        std::cout << i << '\t';
}

If you wanted to make this maximally generic, you'd probably want to change it to only use post-increment on the iterators, allow the user to pass a comparison operator instead of using < directly, etc. These are left as the dreaded "exercise for the reader".
It's probably worth noting that this is basically the same algorithm as set_difference normally uses, just with minor adjustment to operate in-place. This does cause a substantial change in the interface though: since it can (and does) create duplicate elements in the collection, it can be applied to a sorted sequence (vector, deque, hash, etc.) but not to an associative container ([unordered_][multi_](set|map)).
Since this traverses a and b exactly once each, it's clearly O(N + M), but since we're starting with the idea that M(=b.size()) is small, it's effectively O(N)
Note: the test code uses C++11 features heavily (e.g., to initialize the two vectors) but I believe the algorithm implementation itself should be fine in C++98/03.

A: Rather than removing elements, just add items to a new vector. Assuming your inputs are 'original' (A) and 'toRemove' (B), just create iterators for both original and toRemove:
If the next item in original matches the next item in toRemove, drop it. Otherwise, copy it to the result.
If it's greater than the next item in toRemove, go to the next item in toRemove and run the comparison again.
This way, you're only iterating over each list once, and not constantly copying array values around during a 'remove' operation.
This solution will run in O(A+B), which is faster than your current (and proposed) solution.
For comparison purposes:
Your existing solution which is roughly O(A*A*B) (A for remove, A for non-optimized search, B for iterating over B).
Your edit suggests doing a binary search to remove the elements; this will only improve your original solution to O(logA*A*B) (A for remove, logA for optimized search, B for iterating over B).

A: Built in functions in the vector header are faster. For example,

vector  vect;

and after adding all the elements, you could use

sort(vect.begin(),vect.end());

That would sort the list in ascending order. For descending, you might have to perform

reverse(vect.begin,vect.end());

on the Sorted List.


text:
Q: Field Security: how to make it possible to edit a field when creating a record, then make it read only for editing? We'd like to make it possible for our users to fill out the lead source field when creating a record, but after it has been created, lock the field so only an admin can edit it. How can I do this?

A: You don't really need a code solution if your purpose is just what you described. You should go for a validation rule on the object. Here is one that will work for your purpose:
AND(
NOT(ISNEW()),
ISCHANGED(LeadSource),
$Profile.Name  <> "System administrator"
)


text:
Q: When to start the MySQLi connection (2 scenarios) I'm doing my first PHP project with mysqli (I've been using mysql until today). As it's quite simple I'm not using classes, just functions, and I'm wondering when and how should I instantiate the connection. I.e., I'm thinking of these two scenarios:
Scenario I:
$DBLink = new mysqli(...);

function foo($DBLink, $params, ...) {
    //Stuff.
}

foo($DBLink, ...);

Scenario II:
function getConnection() {
    $DBLink = new mysqli(...);
    return $DBLink;
}

function foo($params,...) {
    $DBLink = getConnection();
    //Stuff
}

foo(...);

There will be more than one function using the DBLink (quite a few, actually).
Which of the two scenarios is better and why? I prefer the second one, it seems cleaner, but maybe it's a better idea instantiating it just once.

A: The answer is the second method, although there is a better way of doing it.
The best option is to use a singleton class that you can get from any method you want. An incomplete example would be (this won't actually work on its own, but it gives you an idea of what happens inside a singleton like this);
class Database {
    private static $conn = NULL;

    public function __construct(...) {
        self::$conn = new mysqli(...);
    }

    public static function getInstance() {
        return self::$conn;
    }
}

which you can use to get the current connection like this;
// initailise connection
$conn = new Database(...);

function foo() {
    $db = Database::getInstance();
    // do stuff
}

You can get complete wrapper classes for your MySQLi connection, for example this PHP-MySQLi-Database-Class which also have helper methods for your queries. This means you don't have to worry about maintaining a wrapper class yourself.

A: You can use the first example which is quite similar to Singleton design pattern.To avoid creating a new database connection each time.
Example below shows using class , which though not what you are asking but probably you should take into considerations.
singleton.php
<?php
        class Database
        {
            // Store the single instance of Database
            private static $m_pInstance;

            private $db_host='localhost';
            private $db_user = 'root';
            private $db_pass = '';
            private $db_name = 'databasename';

            // Private constructor to limit object instantiation to within the class
            private function __construct()
            {
                mysql_connect($this->db_host,$this->db_user,$this->db_pass);
                mysql_select_db($this->db_name);
            }

            // Getter method for creating/returning the single instance of this class
            public static function getInstance()
            {
                if (!self::$m_pInstance)
                {
                    self::$m_pInstance = new Database();
                }
                return self::$m_pInstance;
            }

            public function query($query)
            {
               return mysql_query($query);
            }

         }
?>

& we can call it from other files or functions :
<?php
       include 'singleton.php';
       $pDatabase = Database::getInstance();

       $result = $pDatabase->query('...');
?>


text:
Q: javascript conditional operator issue Hello sorry if this is a duplicate question but I was wondering if someone could help me out with my code I don't know what i'm missing i'm supposed to create a page that the user enters a age and it returns the result of the ticket prices.
Under age 5 entry is free
Between ages 5 and 12 (inclusive) a child's ticket costs $5.00
Older than 12 an adult ticket costs $9.00
Here's my code:

function myFunction() {
    var age;
    var older;
    var young;

    age = document.getElementById("age").value;

    older = (age >= 13) ? "$9":"$5";

    document.getElementById("demo").innerHTML = older + " movie";
}

Input your age and click the button:

<input id="age" />

<button onclick="myFunction()">Try it</button>

 Under age 5 entry is free

Between ages 5 and 12 (inclusive) a childís ticket costs $5.00

Older than 12 an adult ticket costs $9.00

A: You can add check for age < 5 at beginning of conditional operator

function myFunction() {
    var age;
    var older;
    var young;

    age = document.getElementById("age").value;

    older = age < 5 ? "free" : (age >= 13) ? "$9" : "$5";

    document.getElementById("demo").innerHTML = older + " movie";
}

Input your age and click the button:

<input id="age" />

<button onclick="myFunction()">Try it</button>

 Under age 5 entry is free

Between ages 5 and 12 (inclusive) a childís ticket costs $5.00

Older than 12 an adult ticket costs $9.00

A: You can very easily achieve what you want by chaining ifs:
function myFunction() {
    var age = document.getElementById("age").value;
    var price;

    if (age >= 13) {
        price = "$9";
    }
    else if (age >= 5) {
        price = "$5";
    }
    else {
        price = "Free";
    }

    document.getElementById("demo").innerHTML = price + " movie";
}

Or, if you really, really want to use shorthand:
function myFunction() {
    var age = document.getElementById("age").value;
    var price = (age >= 13) ? "$9" : ((age < 5) ? "Free" : "$5");

    document.getElementById("demo").innerHTML = price + " movie";
}

The parentheses are optional. I've only included them to make it clear what is going on.


text:
Q: How to launch app by Automator from mounted disk in MacOS? I have a .dmg package that mounts a disk. I would like to create launch program by Automator to execute sh-script from this disk. Is there any way to do this?
Disk and script are highlighted:

A: In Automator needs the following:

/Volumes/iRule/start-irule-client.sh


text:
Q: The FFT result is keep diverging..(Fortran/ MKL) I tried to conduct 2-Dimensional FFT with visual Fortran and Intel MKL.
But the result keeps blowing up. How can I fix it?
I would appreciate it if you could answer my question.
Here is my code:
\\\\\
First, I created a sinusoidal wave,
real(8), allocatable::  Wave_ini_2D(:,:)  ! [nx, nt] dimensional
with duration x:[-40,40], t:[0:10] with resolution nx and nt, respectively.
And the wave is passed to a subroutine as follows,
    subroutine FFTF2_R2C(nx, nt, L1, Wave_ini_2D,  Wave_fft_2D)
        integer, intent(in)::       L1(2), nx, nt
        real(8), intent(in)::       Wave_ini_2D(nx, nt)
        complex(8), intent(out)::    Wave_fft_2D(L1(1), L1(2))

        type(DFTI_DESCRIPTOR), POINTER :: My_Desc2_Handle       !   FFT handler
        real(8):: Win(nx*nt)
        integer:: status, i

        Win = reshape(Wave_ini_2D, shape(Win))

        Status = DftiCreateDescriptor( My_Desc2_Handle, DFTI_SINGLE, DFTI_REAL, 2, L1)
        Status = DftiCommitDescriptor( My_Desc2_Handle)
        Status = DftiComputeForward( My_Desc2_Handle, Win)
        Status = DftiFreeDescriptor(My_Desc2_Handle)

        Wave_fft_2D = reshape(Win, shape(Wave_fft_2D))

    end subroutine


text:
Q: Strom must declare exactly one stream form last bolt in LinearDRPCTopology? I want to my data output to a kafka queue, so I write the topology as follow:
LinearDRPCTopologyBuilder builder = new LinearDRPCTopologyBuilder("xx");
builder.addBolt(new JdEntryParseBolt(config), 2);
builder.addBolt(new JdCrawlerBolt(config), 2).shuffleGrouping();
builder.addBolt(new JdParseBolt(config), 2).shuffleGrouping();
builder.addBolt(new KafkaBolt<String, Integer>(), 2).shuffleGrouping();

Config conf = new Config();
Map<String, String> map = new HashMap<>();
map.put("metadata.broker.list", "127.0.0.1:9092");
map.put("serializer.class", "kafka.serializer.StringEncoder");
conf.put("topic", "jdQueryCrawler");
conf.setMaxTaskParallelism(10);

LocalDRPC drpc = new LocalDRPC();
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("xx-drpc", conf, builder.createLocalTopology(drpc));

when I submit the topology, it returns:
java.lang.RuntimeException: Must declare exactly one stream from last bolt in LinearDRPCTopology
            at backtype.storm.drpc.LinearDRPCTopologyBuilder.createTopology(LinearDRPCTopologyBuilder.java:152) ~[storm-core-0.9.3.jar:0.9.3]
            at backtype.storm.drpc.LinearDRPCTopologyBuilder.createLocalTopology(LinearDRPCTopologyBuilder.java:87) ~[storm-core-0.9.3.jar:0.9.3]
            at com.ipin.jd.process.topology.TestCrawlerDrpc.main(TestCrawlerDrpc.java:58) ~[test-classes/:na]

What does "exactly one stream from last bolt in LinearDRPC" mean? I do not add more than one stream.


text:
Q: Javascript: `new a()` vs `a()` - new operator vs functioncall() function a() {
    this.a = function () {
        console.log("In A");
    }
    this.b = function () {
        console.log("In B");
    }
    this.c = function (cb) {
        console.log("In C ");
    }
    this.d = function (cb) {
        cb();
        console.log("In D");
    }

    this.d(function () {
        this.a();
        this.b();
        this.c();
    });
}

*

*var A = a();
IN A
IN B
IN C
IN D

*var A = new a();
IN A
IN B
IN C
IN D
IN B
IN C
IN D
Could anyone explain me how this works?
Also, any suggestions on links where I can find such interesting problems/questions?
Thanks, in advance :)


text:
Q: Files on jump drive suddenly unavailable-- error "The file "scan-2005-5-19-07.jpg" couldn't be opened because you don't have permission to view it I am using MacOS 10.12.6 on a 2009 Mac with 12 gigs of memory. I have 34 folders of old scans on a jump drive. They are important legal documents so I must solve this problem.
The scans are jpg files, not pdfs. This morning I opened a few of them as normal in Preview. This afternoon - nothing changed - Preview gives me "The file "scan-2005-5-19-07.jpg" couldn't be opened because you don't have permission to view it."
All the files, in every folder, show the same error. What happened? I used sudo chown -R admin to recursively change the permissions on every file and folder. No effect.
Here's what I don't understand: 1) although I can't open the files in Preview, they open just fine in Finder Quick Look (which is ok, except that I can't print them), and Get Info shows the following permissions: admin(Me) Read & Write, staff Read only and everyone Read only. Also, VLC  and GIMP will open the files.
The problem seems to be Preview-specific.


text:
Q: Как подождать полной загрузки скрипта гугл аналитики? На страницу с помощью js скрипта ставится 2 счетчика:
яндекс метрика
гугл аналитика.
В дальнейшем производятся манипуляции с их куками и данымми.
Возникают ситуации когда счетчики (скрипты подгружаемые от яндекса и гугла) не успевают поставиться на страницу, а манипуляции в скрипте уже происходят, которые становятся из-за этого некорректыными.
У яндекса в АПИ есть возможность отследить завершение установки счетчика асинхронно и затем уже манипулировать им :

document.addEventListener('yacounter123456789inited', function() {
// выполнить этот код если счетчик загружен
}

    разработка на дев сервере ведется,
    вот пример

addMetric ('GA', 'UA-102241230-1');
showCookie('_ga');
function addMetric(type, counterID){
        switch (type) {
            case 'GA':
                if (counterID !== null) {
                    var scriptGA = '(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,\'script\',\'https://www.google-analytics.com/analytics.js\',\'ga\');ga(\'create\', \'' + counterID + '\', \'auto\');ga(\'send\', \'pageview\');';
                    var createGA = document.createElement('script');
                    createGA.innerHTML = scriptGA;
                    document.body.appendChild(createGA);
                }break;
        }
    }

Если analytics.js не успеет загрузиться, то showCookie('_ga') покажет - undefined
Есть такой же функционал у гугл? как правильно его использовать?

A: Нашел решение.
В Google Analytics для выполнения функций после полной загрузки счетчика необходимо воспользоваться встроенной функцией ga(callback).
https://developers.google.com/analytics/devguides/collection/analyticsjs/command-queue-reference?hl=ru
т.е.
функция

ga(function(){
  alert('hello');
});

будет выполнена только после полной загрузки счетчика гугл


text:
Q: About saturated set in topology and set theory I am currently listening to my online lectures on quotient topology, and my professor first builds up the term saturated using set theory. He defines as

For $X$ and an equivalence class $P$ induced by a partition $p$ of $X$, subset $A \subset X$ is a saturated set if $A$ is a union of elements in $P$.

So for example just to clear up the definition, suppose we have $X=[0, 1]$ and an equivalence relation $\sim$ such that $0\sim1$ and $x\sim x$, the equivalence classes are $P=\{\{0, 1\}, A_t\}$ where $A_t=\{t\}$ for $^\forall t \in (0, 1)$. Then, we can say that the set $\{0, 0.5, 1\}$ is a saturated set in $X$ since it is a union of elements of $P$, but $\{0, 0.5\}$ is not a saturated set.
In Munkres, though, the author defines saturated set somewhat differently:

A subset $A$ of $X$ is saturated(with respect to surjective map $p:X \to Y$ if $A$ contains every set $p^{-1}(\{y\})$ it intersects. This, $C$ is saturated if it equals the complete inverse image of a subset of $Y$.

I don't think these definitions are different, they obviously have the same name, so there must be a reason. In my opinion, the first definition of saturated set is a specific case of the second definition, in particular when the map is defined as $p:X \to X/P$ such that $p(x)=Q$ where $Q\in X/P$ and $x \in Q$; so the map where the element is mapped to its partition belonging to. Is my understanding correct?

A: An equivalent (and simpler, in my opinion) definition is that $A$ is saturated by a surjective map $p:X \to Y$ when $A = p^{-1}(p(A))$. This is equivalent to Munkres definition, which states that $A$ is saturated if there exists a subset $S$ of $Y$ such that $A = p^{-1}(S)$. The trick is that, since $p$ is surjective, $p(A) = p(p^{-1}(S)) = S$.
It is easy to pass from the Munkres definition to the partition definition, as explained by Alessandro Codenotti.
In the opposite direction, just define $p$ to be the quotient map from $X$ onto $X/{\sim}$, where $\sim$ is the equivalence relation defined by the partition.


text:
Q: Non-monotonic depth buffer; cyclical overlapping in OpenGL Is it possible to implement custom depth buffer values so that I can implement a non-transitive ordering? E.g.
Red > Green
Green > Blue
Blue > Red

Which I imagine would be implemented in the fragment shader or something, only writing the pixel if it's on top of the existing one as per the schema above. Note that since it's non-transitive it's impossible to assign a single numeric value to each of the colors and retain the ordering.
Put another way, I would like a custom z-buffer where each element is of a non-transitive type. So the z-buffer would be a large sheet full of Red, Green or Blue values. Assign a number to each and then compare as per the schema above to determine which one is on top. If all three colors are on the same fragment then I don't care which one is on top.
Image below illustrates what I mean (this is what I want it to be able to do):

(image from Wikipedia)
Is what I want here possible in OpenGL or am I going too much against the grain? If it is possible, how severe would the reduction in performance be?

A: What you want to do is not only possible, it's relatively fast and simple. I've implemented something like this in my game in order to render the penrose triangle.
The trick is to use a stencil buffer instead of the depth buffer. There are actually several different ways you can use the stencil buffer to achieve a circular ordering effect, depending on your exact needs. I'll describe one possible algorithm here:

*

*Draw the red layer with no stencil test, while writing 1s to the stencil buffer.

*Draw the green layer with stencil test not equal to 1, while writing 2s to the stencil buffer. This will prevent it from being drawn where red has already been drawn, effectively putting green "behind" red.

*Draw the blue layer with stencil test not equal to 2. This will allow it to be drawn on top of red, but not green, effectively placing it between them.

The same technique generalizes to N layers like so:
- for each layer X going front-to-back, from `N - 1` down to `0`
    - draw layer X with stencil test `not equal to X + 1`, while writing `X` to the stencil buffer

Code for this might look something like:
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
for (int X = N - 1; X >= 0; --X) {
    glStencilFunc(GL_NOTEQUAL, X + 1, 0xFF);
    // drawLayer(X);
}

This algorithm only guarantees that layer X will correctly interact with layers (X - 1) % N and (X + 1) % N. If you want more sophisticated rules, you will need a more sophisticated algorithm.
Note that with an 8-bit stencil buffer, you will be limited to 255 layers.
Also note that because this algorithm doesn't use the depth buffer, it works for 3D scenes as well - just enable the depth test like normal, and you're off to the races. That's how I'm able to render the penrose triangle example in 3D.


text:
Q: strange behaviour with glossaries and setacronymstyle I have several cross-refences of acronyms within my thesis, where I would like to include both abbreviations.
The following MWE however produces strange output. Note, that the abbreviation is (PCI) instead of (PXI):
PCI eXtensions for Instrumentation (PCI) is a specific communication bus.

MWE:
\documentclass{scrreprt}

\usepackage{glossaries}

%   on first use, display the long form with the short form in parentheses
%   (this is also the default behavior)
\setacronymstyle{long-short}

\makeglossaries
\newacronym{PCI}{PCI}{Peripheral Component Interconnect}
\newacronym{PXI}{PXI}{\acrshort{PCI} eXtensions for Instrumentation}

\begin{document}

\gls{PXI} is a specific communication bus.

\printglossaries

\end{document}

When I leave out the \setacronymstyle, the text is rendered with the correct abbreviation:
PCI eXtensions for Instrumentation (PXI) is a specific communication bus.

Since those are acronyms, I prefer not to use the see tag that are possible for glossaries.
Can I somehow use setacronymstyle with the text correctly rendered?
Just in case, I'm using:
pdfTeX, Version 3.14159265-2.6-1.40.16 (TeX Live 2015/W32TeX)
scrreprt 2015/10/03 v3.19a
glossaries 4.18

A: There's some strange interaction between the acronym rendering; it seems to be solved if you put the \acrshort instruction in braces.
\documentclass{scrreprt}

\usepackage{glossaries}

%   on first use, display the long form with the short form in parentheses
%   (this is also the default behavior)
\setacronymstyle{long-short}

\makeglossaries
\newacronym{PCI}{PCI}{Peripheral Component Interconnect}
\newacronym{PXI}{PXI}{{\acrshort{PCI}} eXtensions for Instrumentation}

\begin{document}

\gls{PCI} is the original. Again \gls{PCI}.

\gls{PXI} is a specific communication bus. Again \gls{PXI}.

\printglossaries

\end{document}


text:
Q: Webhooks: GCP and Github Since Github changed their authentication methods to only accept Personal Access Tokens I've had some trouble with getting my GCP Build Trigger to run when I push to the main branch of my repo.
Does anyone know how I can re-authenticate, or change the password that's being used to connect GCP to Github?
On GCP I have tried reconnecting to the repo, 'forgetting' the repo and then reconnecting, I'm not incredibly clued up on this platform, I've only been using it for a few weeks.

A: "token" would be used for HTTPS URL.
The official GCP documentation uses SSH URLs, which does not need tokens (but SSH keys): that would be one alternative.


text:
Q: JSONDecoder fails to parse a list of maps I have prepared a simple test Playground at Github to demo my problem:

My Swift code:
struct TopResponse: Codable {
    let results: [Top]
}
struct Top: Codable {
    let uid: Int
    let elo: Int
    let given: String
    let photo: String?
    let motto: String?
    let avg_score: String?
    let avg_time: String?
}

let url = URL(string: "https://slova.de/ws/top")!
let task = URLSession.shared.dataTask(with: url) {
    data, response, error in

    let decoder = JSONDecoder()
    guard let data2 = data,
          let tops = try? decoder.decode(TopResponse.self, from:
                                            data2) else { return }
    print(tops.results[4].given)
}
task.resume()

fails to parse the fetched JSON string and does not print anything.
What could be the problem here please?

A: What's wrong with your code?
try?

That's the main culprit.
Why? You are ignoring the error thrown by the decode(_:from:). You are ignoring the error that could give you the exact reason or at least a hint on why it failed. Instead, write a proper do { try ... } catch { ... }.
So:
guard let data2 = data,
      let tops = try? decoder.decode(TopResponse.self, from:
                                        data2) else { return }
print(tops.results[4].given)

=>
guard let data2 = data else { return }
do {
let tops = try decoder.decode(TopResponse.self, from: data2)
print(tops.results[4].given)
} catch {
    print("Got error while parsing: \(error)")
    print("With response: \(String(data: data2, encoding: .utf8))") //Just in case because I've seen plenty of code where expected JSON wasn't the one received: it was an error, doc changed, etc...
}

Output for the first print:
$>Got error while parsing: keyNotFound(CodingKeys(stringValue: "results", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"results\", intValue: nil) (\"results\").", underlyingError: nil))

Fix:
struct TopResponse: Codable {
    let results: [Top]

    enum CodingKeys: String, CodingKey {
        case results = "data"
    }
}

Or rename results with data.
Then, next error:
$>Got error while parsing: typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "avg_score", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))

Extract from JSON:
    "avg_score": 20.4

It's not a String (the value it's not between double quotes), that's a Double.
Fix:
let avg_score: String?

=>
let avg_score: Double?


text:
Q: djangocms: move data from deprecated cmsplugin-filer-*-plugins to djangocms-*-plugins Since the cmsplugin-filer-*-plugins are deprecated with django-cms 3.5, I need a way to keep my plugins with moving them to the newer djangocms-*-plugins.
I am using the cmsplugin-filer plugins FilerFile, FilerFolder and FilerImage. Also I got a custom plugin which inherits from FilerImage.
I need to move those to the newer djangocms-file-file, djangocms-file-folder and djangocms-picture without losing my plugins / data.

A: After some time working on a migration I came to this solution:
https://gist.github.com/wfehr/86ac31e8e263b872b746cc721662251e
The gist provides a migration to move the data between the said third-party-apps and keep alls the plugins/data and change them to the supported ones.
I hope this will help someone facing the same problems:)
(The migration code itself may not be the perfect solution, but it gets the job done)
EDIT:
The linked migration can be used in any application of yours. Just put it in there as the next following migration, for example you have already "0011_added_new_model.py", then put in the file as "0012_filer_deprecation_move.py".
Then you have to add the migration 0011 in the dependencies, as seen in other (default) migrations.
TLDR: The above migration is a single, standalone migration. It is called as any other migration with python manage.py migrate [app] [migration] and you can put it in "any" app you want (where it makes the most sense to you).


text:
Q: Mac OS X Server Xcode Bot Issue I've successfully integrated CI on my Mac OS X server, but my bot actually build wrong.
I guess, that it should build archive with selected 'Release' Configuration, but it uses Debug configuration instead. Did someone faced with this?

A: The bot runs using configurations set the scheme it starts off of.  If the scheme sets the archive configuration to Release, the bot should build in Release.  Edit the scheme to archive in debug build configuration, and you should see your bot build an archive in debug build configuration.
The following shows the edit scheme window.  This scheme's archive  phase uses the release build config.

A: Hm, need to checkmark 'Perform Archive action' when creating/editing bot. This will cause performing Debug->Release Build configuration. If also check 'Perform Analyze/Test action' it will be: Debug->Analyze->Test->Archive.


text:
Q: Подключение qss файла к PyQt5 приложению Подключаю qss файл по инструкции - стили не подключаются. Хотя print исправно выводит правильное содержимое stream.readAll().
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QWidget, QPushButton, QVBoxLayout
import sys

class Main(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()

        self.btn_box = QVBoxLayout(self)

        self.exit_button = QPushButton("х")

        self.btn_box.addWidget(self.exit_button)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    file = QtCore.QFile(r"data/data_pink.qss")
    file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text)
    stream = QtCore.QTextStream(file)
    app.setStyleSheet(stream.readAll())
    w = Main()
    w.show()
    sys.exit(app.exec_())

data_pink.qss:
QPushButton#exit_button {
font: 12pt "Montserrat Alternates";
background-color: #292f32;
color: #efe2cd;
padding: 5;
border: 1px solid #f4726e;
border-radius: 10px;
}
QPushButton#exit_button:pressed {
font: 11pt "Montserrat Alternates";
background-color: #323335;
color: #efe2cd;
padding: 5;
border: 1px solid #f4726e;
border-radius: 10px;
}

A: Имя, указанное после "#" в qss - не имя переменной. Его необходимо отдельно указать:
self.exit_button.setObjectName('exit_button')