text:
Q: Managing dev/staging/production on DynamoDB? We're starting to use DynamoDB, and want separate environments for dev/staging/production. We can't figure out a natural way to do this---do we just create separate AWS accounts? Or do we use the same account, but add silly prefixes to our tables ("dev-products", "staging-products", "prod-products")?

A: Don't forget Amazon's greatly enhanced IAM for access control. It largely gives you the same benefits of separate accounts. (Separate accounts are still an option if you have want to have different levels of paid support.)
Naming wise, my preference is name.environment.whatever.

A: I can't understand why there is'nt a AWS solution for handling DB-versions like production and test in DynamoDB!? Having multiple AWS accounts is a hassle.
It also becomes a big problem to prefix the table names if you get the items by using the c# class attribute [DynamoDBTable("Users")] and fetching the data with DynamoDBContext.Load<User>(userId);
As attributes values can't change during runtime I ended up with this soluting using conditonal compilation symbols and setting constants that can be used as the class attribute value.
public static class DynamoDbTablesConfiguration
{
        #if Debug
            public const string UserTable = "Users_Dev";
        #endif

        #if Release
            public const string UserTable = "Users_Production";
        #endif
}

[DynamoDBTable(DynamoDbTablesConfiguration.UserTable)]
public class User
{
}

Make sure you set the "conditonal compilation symbols" value by right click on project > Properties > Build > "conditonal compilation symbols".
Not a perfect solution but I don't see any other options here if I don't want to create another AWS account.

A: I don't see anything that's "above" the tables that can be created for each instance (dev/staging/prod) you have (like a relational database, which have all tables under one DB).
At the application I'm working on, we're using prefixes to the tables.

A: Amazon now provide a server that you can run locally. You can download it here.

A: The standard way to manage this with any amazon products is to create separate accounts and then use consolidated billing so that it doesn't complicate the billing aspect. The thing i like about this is that you don't risk breaking the production code by accidentally running the wrong command. Obviously it doesn't help you if you're logged into the wrong instance but it still helps quite a bit.
Other uses for multiple accounts could be to manage permissions and better testing. Having the accounts separate helps testing because you can reproduce the production account 100% and turn it on and off when you need to test new features. I've talked with amazon premium support about this issue and they've said that this seems to be standard practice for the larger companies. Some of the larger companies have many accounts. At my work here we just have 3 and I find it more useful every day.


text:
Q: Third Table inner join I retrieve datas with inner join with two tables.This is the sql:
SELECT   mc.user_id, mc.id AS movie_comment_id, mc.add_date,
         mc.movie_id, mc.comment, m.id, m.name
FROM     movie_comment AS mc
         INNER JOIN movie AS m ON m.id = mc.movie_id
WHERE    movie_id = 1500
AND      stat = 'onayli'
ORDER BY mc.add_date DESC
LIMIT 10

What i want is that retriving also usernames from user table.I wrote this sql but does not work
SELECT    u.id, u.username, mc.user_id, mc.id AS movie_comment_id, mc.add_date,
          mc.movie_id, mc.comment, m.id, m.name
FROM      movie_comment AS mc
          INNER JOIN movie AS m ON m.id = mc.movie_id
                                ON mc.user_id = u.id
WHERE     movie_id = 1500
AND       stat = 'onayli'
ORDER BY  mc.add_date DESC
LIMIT 10

How can i also retrieve usernames ?

A: You need to specify INNER JOIN at the start of each inner join.
select  u.ID ,u.USERNAME,mc.USER_ID,mc.ID as Movie_Comment_ID,mc.ADD_DATE,mc.MOVIE_ID,mc.COMMENT,m.ID,m.NAME
from MOVIE_COMMENT as mc
INNER Join MOVIE as m ON  m.ID=mc.MOVIE_ID
INNER JOIN [USER] u ON mc.USER_ID = u.ID
WHERE MOVIE_ID = 1500  and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10

A: select  u.ID ,u.USERNAME,mc.USER_ID,mc.ID as Movie_Comment_ID,mc.ADD_DATE,mc.MOVIE_ID,mc.COMMENT,m.ID,m.NAME
 from MOVIE_COMMENT as mc
INNER Join MOVIE as m ON  m.ID=mc.MOVIE_ID
INNER JOIN usertable as u ON mc.USER_ID = u.ID
WHERE MOVIE_ID = 1500  and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10

A: SELECT  u.ID,
u.USERNAME,
mc.USER_ID,
mc.ID as Movie_Comment_ID,
mc.ADD_DATE,
mc.MOVIE_ID,
mc.COMMENT,
m.ID,
m.NAME
FROM MOVIE_COMMENT as mc
INNER JOIN MOVIE as m ON  m.ID = mc.MOVIE_ID
INNER JOIN [User] u ON u.ID = mc.USER_ID
WHERE MOVIE_ID = 1500  and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing invoice number automatically on workbook close but checking if it has to increase or not I have this code below for my workbook that saves the workbook for me and also increases the invoice number by 1 based on the value in a certain cell:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
     Range("L5").Value = Range("L5").Value + 1
     ThisWorkbook.Save
End Sub

So cell L5 starts with 1 and right now everytime the workbook is closed it will add +1 to it and save the book, so the next time it opens it will be 2,3,4,5 and so on.
The problem I have is that if someone closes it and open and closes it will keep adding numbers even though that invoice doesn't exit.
Is there anyway it can check a list of value from a column in sheet 2 to see if the current invoice number exists, if it does then add 1 and save, if not then leave the same number and save?
UPDATED SUBMIT CODE WITH CLEARING, SAVING, AND UPDAING INVOCE NUMBER. All cells are locked and protected except the cells in the refTable, those are editable by user but L5 is locked and needs to be editable by the VBA code only, not users.
Sub Submit()

Dim refTable As Variant, trans As Variant
refTable = Array("B = L5", "C = C5", "D=G5", "E=C10", "F=C9", "G=I9", "H=I10", "I=C13", "J=C14", "K=C15", "L=C16", "M=C17", "N=C18", "O=I13", "P=I14", "Q=I15", "R=I16", "S=I17", "W=H20")
Dim Row As Long
Row = Worksheets("TravelLog").UsedRange.Rows.Count + 1

For Each trans In refTable
    Dim Dest As String, Field As String
    Dest = Trim(Left(trans, InStr(1, trans, "=") - 1)) & Row
    Field = Trim(Right(trans, Len(trans) - InStr(1, trans, "=")))
    Worksheets("TravelLog").Range(Dest).Value = Worksheets("TravelRequest").Range(Field).Value
Next

If Worksheets("TravelRequest").CheckBox1.Value Then
    Worksheets("TravelLog").Range("T" & Row).Value = "Yes"
Else
    Worksheets("TravelLog").Range("T" & Row).Value = "No"
End If

If Worksheets("TravelRequest").CheckBox2.Value Then
    Worksheets("TravelLog").Range("U" & Row).Value = "Yes"
Else
    Worksheets("TravelLog").Range("U" & Row).Value = "No"
End If

If Worksheets("TravelRequest").CheckBox3.Value Then
    Worksheets("TravelLog").Range("V" & Row).Value = "Yes"
Else
    Worksheets("TravelLog").Range("V" & Row).Value = "No"
End If

Range("L5").Value = Range("L5").Value + 1

Range("I9:I10, I13:I17, H20, C5, C9:C10, C13:C18").Select
Selection.ClearContents

    Dim OleObj As OLEObject

    For Each OleObj In ActiveSheet.OLEObjects
        If OleObj.progID = "Forms.CheckBox.1" Then
            OleObj.Object = False
       End If
    Next OleObj

ThisWorkbook.Save

End Sub

A: Use goto in Workbook_BeforeClose with condition u mentioned like that
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    If 'your_condition' = TRUE Then goto do_save
    Range("L5").Value = Range("L5").Value + 1
    do_save:
    ThisWorkbook.Save
End Sub


text:
Q: Why is the gmpxx conversion from float to integer, producing a result that implies a fraction existed? Backstory:
Learning exercise for large number arithmetic in C++, as I try to create a signalapp library in Qt.
Problem:
I am getting an erroneous result when I try to do division through multiplication.
/* This attempts division through multiplication */
const int dividend(500);
const int divisor (10 );
const int modulo  (17 );

/* Calculate the inverse */
mpq_class rational( 1, divisor );
mpf_class inverse( divisor == 0 ? 0 : rational );

/* Divide through multiplication */
inverse *= dividend;

/* Convert to integer */
mpz_class fromFloat( inverse );

/* Complete the equation with the modulus */
mpz_class result;
mpz_mod( result.get_mpz_t(), fromFloat.get_mpz_t(), mpz_class(modulo).get_mpz_t() );

/* Check Result */
qDebug() << "Expected Result: " << 50 % modulo;   // 16
qDebug() << "Produced Result: " << result.get_d();// 15
qDebug() << "Error:" << fromFloat.get_d() << inverse.get_d(); // 49 & 50

I may have taken an odd route to get to my result:

*

*Create the inverse by simply creating a rational. 1 / 10

*Get precision by converting that rational into a float. 0.1

*Finding the answer by then multiplying the float with the dividend: 0.1 × 500 = 50

*Convert to an integer, that I may use the mpz_mod function, for calculating a modulus. This is where the error seems to be.

Problem is, that the expected result 50 is becoming 49.
My guess?
I am simply ignorant to the nature of float conversions.
For example:
/* Display Float */
mpf_class f(0.1);
mp_exp_t x(-1);
qDebug() << x << QString::fromStdString( f.get_str(x) ) << x;
/* Produces */
// -1 "100000000000000005551" 0
// aka
// 0.100000000000000005551

qDebug() << x << QString::fromStdString( f.get_str(x,10,2) ) << x;
/* Produces */
// -1 "1" 0
// aka
// 0.1

Still: Despite how green I am to math, given that no imprecision should exist with 1 / 10, its hard for me to not consider that some sort of bug. Either way, my guess is that there must be some sort of imprecision lingering that is causing it to floor() down one integer.
Questions:

*

*Should this be regarded as a bug?

*Is it a terrible idea to try to calculate the inverse by simply creating a rational?

*Could I make my existing code work if I set the precision some how?

*Considering this is for cyptography and I will be producing 256 bit sized numbers, what level of precision will I actually need? Is it relatively little considering I will most likely just be rounding up or down?

*Should I try to be calculating this by only using the integer type? Or is appropriate to use its float or rational types?

Thanks.
References:

*

*https://gmplib.org/manual/C_002b_002b-Interface-General

*https://www.signal.org/docs/specifications/xeddsa/


text:
Q: Merging with pandas while keeping NaNs at bottom Let's say I have 3 dataframes, each with a single column. In each df, there are slightly more rows than in the previous one. For example:
and I want to get exactly this:
df1 =       col1
        1   a
        2   b
        3   c

df2 =       col2
        1   x
        2   y
        3   z
        4   w
        5   q

df3 =       col3
        1   A
        2   B
        3   C
        4   D
        5   E
        6   F
        7   G

and I want to get exactly this:
res =       col1    col2    col3
        1   a       x       A
        2   b       y       B
        3   c       z       C
        4   -       w       D
        5   -       q       E
        6   -       -       F
        7   -       -       G

That is, I want the rows to stay in the order in which they are added, so NaNs (-) are kept in the bottom.
I tried this:
import pandas as pd
total = pd.DataFrame()

total = pd.merge(total,df1,how='outer',left_index=True,right_index=True)
total = pd.merge(total,df2,how='outer',left_index=True,right_index=True)
total = pd.merge(total,df3,how='outer',left_index=True,right_index=True)

but I keep getting the table in a seemingly random order. Stuff like:
res =       col1    col2    col3
        1   a       x       A
        4   -       w       D
        3   c       z       C
        5   -       q       E
        2   b       y       B
        7   -       -       G
        6   -       -       F

How can I force the final df to take the desired form?
Thanks!

A: concat and pass axis=1 to do so column-wise:
In [203]:
pd.concat([df1,df2,df3], axis=1)

Out[203]:
  col1 col2 col3
1    a    x    A
2    b    y    B
3    c    z    C
4  NaN    w    D
5  NaN    q    E
6  NaN  NaN    F
7  NaN  NaN    G


text:
Q: How to write parent item in Fluent UI groupedList component? I am using Fluent UI. I need groupedList component, but there is something I couldn't fix. Parents are always group, but I want to aadd few items as parents just like the picture below.
I saw a github issue below, but seems it wasn't fixed. Is there any way to achive what I want?
https://github.com/microsoft/fluentui/issues/10971


text:
Q: Is it possible to use WinMerge inside Visual Studio 2008 and Visual Source Safe 6.0? I would like to use WinMerge as the default diff tool inside VS2008 from the solutions explorer in place of the "Compare..." context menu item. Is this possible? I'm looking for a quick replacement of the current bland diff tool an I just like WinMerge better. I'm not interested in going to the folder explorer and doing the comparison there.
I'm using Visual Source Safe 6.0 not TFS

A: I think I have this working at a serviceable level if not optimal.
in visual studio go to tools > options > source control > plug-in settings
click the "advanced" button
in the sourcesafe options dialog, switch to the "custom editors" tab
for operation, select file difference
for file extension enter .*
for command line enter
"C:\Program Files\WinMerge\WinMergeU.exe" /x /e /ub /wl /dl %6 /dr %7 %1 %2

click the "add" button then the "ok" button.
using "compare" from a file's context menu or viewing history and selecting "diff" should bring up winmerge with the file comparison. the original is on the left and the modified file is on the right (is that the right placement? should they be swapped?). if you selected a highlighted difference, you can actually sync that area at this time as well. visual studio will just recognize the file has changed and ask you to reload. I haven't gotten to the situation where I'm in an actual "merge" situation so I'm not sure what happens there. I'll update this post if I ever have more info to add.
I'm using VS2008, sourcesafe 2005, and winmerge 2.12.4 installed to the default directory. I copied the settings from this post: http://weblogs.asp.net/garrypilkington/archive/2009/12/16/winmerge-as-a-comparison-tool-in-visual-studio-2008.aspx

A: Yep, it's possible!
See this link: http://whyiamright.wordpress.com/2008/01/18/changing-the-diffmerge-program-used-by-visual-studio/
Tools-> Options.  In the tree, choose Source Control, then the plugin of your choice (VS team Foundation, Source Safe, etc).
Click the "Configure User Tools" button, click add, then specify the appropriate extension, operation, EXE, and arguments list.
This site: has the settings for many, including winmerge: http://blogs.msdn.com/jmanning/articles/535573.aspx
EDIT:
You mentioned VSS:  Check out the Winmerge manual here: http://winmerge.org/docs/manual/VersionControl.html.  It says how to do it about 1/5th the way down the page.

A: I have been wondering about this as well and have not found anything to make it possible in VSS 6.0.
For now, it looks like the answer to our question is "No".

A: As I stated previously, I don't think we can integrate WinMerge with Visual Studio 2008 and VSS 6.0.
However, I did find that VSS 2005 is backward compatible with VSS 6.0 databases. So, if your server can't change from VSS 6.0, at least perhaps you can change your client to VSS 2005, and then follow the other instructions from the answers here.


text:
Q: Time Range restriction on OWL We have a class CBSTV, which has some subclasses like News, Documentary, and etc. The data property time will specify the time of each program. For example, the news is every day between 16:00:00-17:00:00. I tried to represent this restriction this way:
dateTime [>= T16:00:00Z, <=T17:00:00Z ]
but, it is wrong, anyone know the correct way to represent this
also, we have another data property duration. For instance the duration of the news is between 45 minutes to one hour. I don't know how I should represent this one too?

A: The datatype for recurring times (e.g., 17:00 every day) is not xsd:dateTime but xsd:time


text:
Q: Работа с canvas через функцию Как можно работать с canvas через функцию? Внизу один и тот же код, но через обработчик событий работает, а через функцию выдаёт ошибку.Что нужно исправить?
procedure TForm1.Button1Click(Sender: TObject);
begin
  Image1.Canvas.Brush.Color:=clBlack;
  Image1.Canvas.Rectangle(1,1,50,50);
end;

function f():byte;
begin
  Image1.Canvas.Brush.Color:=clBlack;
  Image1.Canvas.Rectangle(1,1,50,50);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
   f;
end;

Ошибка:

Undeclared identifier: 'Image1'

A: Данная ошибка возникает из-за того, что Image1 это не глобальный объект, а поле класса TForm1. Обработчик - метод этого класса и видит это поле, а для сторонней функции оно недоступно.
Можно сделать так
function f():byte;
begin
  Form1.Image1.Canvas.Brush.Color:=clBlack;
  Form1.Image1.Canvas.Rectangle(1, 1, 50, 50);
end;

Но это ОЧЕНЬ неправильно. Т.к. идет ненужное обращение к глобальной переменной.
Можно в функцию передать указатель на объект класса TForm1
function f(AForm: TForm1):byte;
begin
  AForm.Image1.Canvas.Brush.Color:=clBlack;
  AForm.Image1.Canvas.Rectangle(1, 1, 50, 50);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
   f(Self);
end;

но это глупо. С тем же успехом можно сделать f методом класса TForm. Вы же, как я понимаю, хотите написать функцию для рисования прямоугольника на произвольной канве. Тогда все, что нужно, это передать в функцию указатель на нужную канву
procedure f(ACanvas: TCanvas)
begin
  ACanvas.Brush.Color:=clBlack;
  ACanvas.Rectangle(1, 1, 50, 50);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
   f(Image1.Canvas);
end;

Начиная с Delphi 2006 можно написать хелпер для класса TCanvas и сделать f псевдометодом этого класса
type
  TCanvasHelper = class helper for TCanvas
  public
    procedure f;
  end;

procedure TCanvasHelper.f
begin
  Brush.Color:=clBlack;
  Rectangle(1, 1, 50, 50);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
   Image1.Canvas.f;
end;


text:
Q: When I click on Captcha then click on Login it not working I have an application, on the login page of an application I have a username, password captcha, and log in. When I fill in username, password and click on captcha it's working fine but when I click on login it not working. Please check the screenshot: https://prnt.sc/1qhua85
Page Link: https://sell360d.allomate.solutions/login
My code:
WebDriverWait wait = new WebDriverWait (driver, 10);
  WebElement username = wait.until(ExpectedConditions.elementToBeClickable(By.id("exampleInputEmail_2")));
  username.sendKeys("username");

  WebElement password = wait.until(ExpectedConditions.elementToBeClickable(By.id("exampleInputpwd_2")));
  password.sendKeys("password");

  WebElement captcha = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/app-root/div/div/div[1]/app-login-component/div/div/div/div/div/div/div/form/div[3]/div/re-captcha/div/div/iframe")));
  captcha.click();

  WebElement login = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/app-root/div/div/div[1]/app-login-component/div/div/div/div/div/div/div/form/div[4]/button")));
  login.click();

A: The thing is captcha is in iframe, and login button is not.
also try to put some hardcoded sleep, cause explicit wait does not seems to be working:
  WebDriverWait wait = new WebDriverWait (driver, 10);
  WebElement username = wait.until(ExpectedConditions.elementToBeClickable(By.id("exampleInputEmail_2")));
  username.sendKeys("username");

  WebElement password = wait.until(ExpectedConditions.elementToBeClickable(By.id("exampleInputpwd_2")));
  password.sendKeys("password");

  WebElement captcha = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/app-root/div/div/div[1]/app-login-component/div/div/div/div/div/div/div/form/div[3]/div/re-captcha/div/div/iframe")));
  captcha.click();

  Thread.sleep(5000);

  WebElement login = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class,'btn-login')]")));
  login.click();


text:
Q: Radio button state not getting updated on mouseup or click I am using a custom image for a radio button so my radio button is hidden and i am using a label for that radio button like this :-
Click here for JS fiddle link

$('body').on('mouseup', 'label.q1odiv', function() {
  if ($('input:radio[name="radio1"]').is(':checked')) {
    // My code here
    // I want to access currently checked radio button's value here
  }
});
input[type=radio],
input[type=checkbox] {
  display: none;
}
input[type=radio] + label {
  display: block;
  cursor: pointer;
  background-image: url("http://www.clker.com/cliparts/8/V/0/V/G/Z/radiobutton-unchecked-th.png");
  background-repeat: no-repeat;
  background-size: contain;
  margin-bottom: 2vw;
}
input[type=radio]:checked + label {
  background-image: url("http://www.clker.com/cliparts/M/2/V/6/F/u/radiobutton-checked-sm-th.png");
}
.radio-btn {
  width: 2vw;
  height: 2vw;
}
.options-text-div {
  margin: 0 3vw;
  font-size: 2vw;
  line-height: 2.2vw;
  width: 25vw;
}

  <input type="radio" id="q1o0" name="radio1" checked="checked">

Kicks

  <input type="radio" id="q1o1" name="radio1">

Flip Flops

  <input type="radio" id="q1o2" name="radio1">

Stilletos

  <input type="radio" id="q1o3" name="radio1">

Boots

  <input type="radio" id="q1o4" name="radio1">

Wedges

The problem is whenever i check a radio button, the radio button state which i checked is not updated while i am inside the function.Hence, I get the previously checked radio button as the value instead of the currently checked one.

A: a) your solution is not accessible for people with keyboards
b) It should work if you listen for the change of inputs:
https://jsfiddle.net/x31epgot/6/
$('body').on('change', 'input', function(){
});

A:

//By changing the specific radio you will get the id of that radio button
$('body').on('change', 'input:radio[name="radio1"]', function() {
 console.log($('input:radio[name="radio1"]:checked').attr('id'));

});
input[type=radio],
input[type=checkbox] {
  display: none;
}
input[type=radio] + label {
  display: block;
  cursor: pointer;
  background-image: url("http://www.clker.com/cliparts/8/V/0/V/G/Z/radiobutton-unchecked-th.png");
  background-repeat: no-repeat;
  background-size: contain;
  margin-bottom: 2vw;
}
input[type=radio]:checked + label {
  background-image: url("http://www.clker.com/cliparts/M/2/V/6/F/u/radiobutton-checked-sm-th.png");
}
.radio-btn {
  width: 2vw;
  height: 2vw;
}
.options-text-div {
  margin: 0 3vw;
  font-size: 2vw;
  line-height: 2.2vw;
  width: 25vw;
}

  <input type="radio" id="q1o0" name="radio1" checked="checked">

Kicks

  <input type="radio" id="q1o1" name="radio1">

Flip Flops

  <input type="radio" id="q1o2" name="radio1">

Stilletos

  <input type="radio" id="q1o3" name="radio1">

Boots

  <input type="radio" id="q1o4" name="radio1">

Wedges


text:
Q: How to send ASYNC 8,N,1 serial data over an SPI interface using two Arduino Uno boards Need help with sending ASYNC data between two Arduino UNO R3 micro-controllers.
System design follows:
RS232 modem 19,200,8,N,1 --> UNO-1 D0=(rx), D1=(tx). RS232 parameters cannot be changed because the device is hardcoded. UNO-1 runs sketch sending AT commands and parsing data received. Parsed data must be sent to another RS232 modem but unfortunately this device is hardcoded for 9,600, 7,E,2. There is only one USART o the UNO.
My idea is to take advantage of a 2nd UNO R3 to convert the data to 9,600, 7,E,2.
So..  19,200,8,N,1 modem --> UNO-1 -->SPI INTERFACE (mstr) --> UNO-2 --> software serial port --> Device 9600, 7, E, 2.
I've tried reconfiguring the USART on the UNO before sending data to each ASYNC device. Problem showed up that unsolicited and important data is received form the 19,200 modem while the UNO is sending data to the other ASYNC device at 9600,7 ,E, 2.
The SPI interface seems to be my only option. Can any one help?

A: You can use Bill Porter's Easy Transfer Library to transfer packets back and forth between two Arduino's, over the I2C or VirtualWire.
Note the SPI has a master/slave relationship, so the master side is always polling when idle to recieve. The above ET is async.
I agree @Chris Stratton. I believe a single UNO with one Hard UART at 19200 and one Soft UART at 9600 would do the job.
Regardless, You may find the 19200 side will require the ability to Flow Off the Modem(or Host), likely using either output pin as CTS or XON/XOFF commands. Note that when you assert the CTS the host will not send the next buffer, but will finish its current buffer. Hence the Arduino's rx buffer needs to be large enough, to get one packet and send the next packet. The ATmega328 only has 2K. So your maximum packet would need to be 512 (aka 1/4) or less, minus operating room. etc...
That all said, most modem's (that are less than 15 years old) should support AT&Q5 turning on auto reliable mode with speed buffering. Allowing it to auto detect the baud rate of the DTE.


text:
Q: Careers 2.0 impressed by non-existent answers Careers recently sent me an email inviting me to join. Great! Except their email congratulated me on my excellent work in answering backbone.js questions, and as it happens, I've never answered a single Backbone.js related question. What's going on?

A: Yeah, we mixed up some ids and effectively sent a batch of invites with random tags.  Rest assured, however:

*

*We did mean to invite you, and

*We also meant to invite some other person with exemplary backbone.js activity

So, at least there's that...


text:
Q: MFC multiple radio buttons groups on dialog I have 2 groups of radio boxes on a dialog. How can I specify which button is in which group? Because right now when I select one, all the others get unselected, even the ones from the other group.

A: The tab order of the dialog, and the Group property completely dictates which radio buttons belong to which groups.
Each radio button belongs to the group of the previous main radio button in the tab order.  The main radio button has the Group property set to True.
You can set the tab order by going to the dialog editor and pressing Ctrl+D.  You then click on each control from 1 to N in the order you want the tabbing to go.


text:
Q: How to run an RScript from local to remote server I have an rscript that is on my local desktop but I want to run this in a directory that is on a remote password protected sever. R is already installed in this computing cluster but what do I use in my terminal to execute the R script?
Thanks!


text:
Q: My own Arch Linux based distribution Well, i'm looking for some book, or wiki, to create my own based distribution, I really don't know where to start, only thing that I know is: I want to make a Arch Linux distribution, not just a Live CD, or something, but my OWN distribution, I know that I'll have to study so much to get there, but I really want it.

A: Arch Linux is a distribution. What you want is to make your own distribution, possibly based on Arch Linux. If you're interested in creating your own distro, then I'd suggest starting with Linux From Scratch . From there you can then add things such as a package manager (e.g., pacman), and other features you like. LFS is not only a great way to get started in making your own distro, it's also an excellent way to learn the inner-workings of Linux. Have fun!


text:
Q: Get differences between two excel files Problem Summary
Given 2 excel files, each with 200 columns approx, and have a common index column - ie each row in both files would have a name property say, what would be the best to generate an output excel file which just has the differences from excel file 2 to excel file 1.
The differences would be defined as any new rows in file 2 not in file1, and rows in file2 that have the same index (name), but one or more of the other columns are different.
There is a good example here using pandas that could be useful : Compare 2 Excel files and output an Excel file with differences
Difficult to apply that solution to an excel file with 200 columns though.
Sample Files
Below is a sample of 2 simplified (columns reduced from 200 to 4) excel files in csv format, index column is Name.
Name,value,location,Name Copy
Bob,400,Sydney,Bob
Tim,500,Perth,Tim

Name,value,location,Name Copy
Bob,400,Sydney,Bob
Tim,500,Adelaide,Tim
Melanie,600,Brisbane,Melanie

So given the above 2 input files, the output file should be :
Name,value,location,Name Copy
Tim,500,Adelaide,Tim
Melanie,600,Brisbane,Melanie

So the output file would have 2 rows (not including column title row), rows 2 is a new row not in file1, and row 1 contains changes from file1 to file2.
The following works, but the index column is lost (it's [1, 2] instead of ['Tim', 'Melanie'] :
import pandas as pd
df1 = pd.read_excel('simple1.xlsx', index_col=0)
df2 = pd.read_excel('simple2.xlsx', index_col=0)

df3 = pd.merge(df1, df2, how='right', sort='False', indicator='Indicator')
df4 = df3.loc[df3['Indicator'] == 'right_only']
df5 = df4.drop('Indicator', axis=1)

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df5.to_excel(writer, sheet_name='Sheet1')
writer.save()

A: The solution was to use numpy.array_equal to determine if rows were equal or not :
import sys
import pandas as pd
import numpy as np

# Check for correct number of input arguments
if len(sys.argv) != 4:
    print('Usage :\n\tpython {} old_excel_file new_excel_file  output_excel_file\n'.format(sys.argv[0]))
quit()

# Import input files into dataframes
old_file = sys.argv[1]
new_file = sys.argv[2]
out_file = sys.argv[3]
df1 = pd.read_excel(old_file, index_col=0)
df2 = pd.read_excel(new_file, index_col=0)

# Merge dataframes, maintaining index
df_merged = pd.merge(df1, df2, left_index=True, right_index=True, how='outer', sort=False, indicator='Indicator')

# Add right-only rows to output dataframe
right_only_index = df_merged.index[df_merged['Indicator'] == 'right_only']
df_out = df2.loc[right_only_index]

# Iterate through "both" rows, and append ones that are not equal to the output dataframe
both_index = df_merged.index[df_merged['Indicator'] == 'both']
df_both = df2.loc[both_index]

for i, values in df_both.iterrows():
    if not np.array_equal(df1.loc[i].values, df2.loc[i].values):
        df_out = df_out.append(df2.loc[i])

# Write output dataframe to an Excel file (first the two header rows, and then the data rows)
writer = pd.ExcelWriter(out_file, engine='xlsxwriter')
df_out.to_excel(writer, sheet_name='Sheet1')
writer.save()


text:
Q: Detect when at the end of a stringstream I am trying to write a function which will detect when I'm almost at the end of a stringstream, but it doesn't seem to work.
Here's some code:
std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
    if (ss.peek() != '.') {
        ss >> number;
        if (ss.tellg() == path.length()) {
            std::cout << "Last one: " << number;
        } else {
            std::cout << number;
        }
    } else { ss.get(); }
}

I tried using ss.tellg() == path.length(), but that doesn't work. Does somebody have an alternative?

A: I figured it out..
std::string path(1.2.3);
int number;
std::stringstream ss(path);
while (!ss.eof()) {
    if (ss.peek() != '.') {
        ss >> number;
        if (ss.tellg() == -1) {
            std::cout << "Last one: " << number;
        } else {
            std::cout << number;
        }
    } else { ss.get(); }
}


text:
Q: SQL Server Management Studio commands latency I noticed, while trying to run an UPDATE script on a remote DB server geographically dislocated in another country, that the command executes successfully in about 1 hour if I run it from Management Studio on my local machine. If, instead, i run it directly on Management Studio that is installed on the server, it takes about 10 minutes to execute.
So, my question is: is latency important even if there is no "data traffic" generated by my command? I would expect latency when i execute an INSERT or SELECT command because there is effectively data that has to be sent from one machine to the other. That's not my case because the UPDATE commands i'm executing don't produce any output and don't have input data inside them.


text:
Q: LOAD DATA INFILE not working inside BASH SCRIPT I am new to ssh ,trying to laod csv files through bash script using LOAD DATA INFILE syntax using bash script
Here is my script:
mysql -u $MYSQL_USERNAME -p$MYSQL_PASSWORD -D $MYSQL_DATABASE \
  load data local infile '$FILE_TR_HI' into table trans_hist_test \
  fields terminated by ',' lines terminated by '\r\n';

This script runs fine individually. I mean outside the script.
But when I include this in script, it throws an error

Load command not found

How can I fix this?

A: Try to provide a full path to mysql
/usr/local/mysql/bin/mysql -u ...

A: You can use the --execute option of mysql using -e.

mysql -u $MYSQL_USERNAME -p$MYSQL_PASSWORD -D $MYSQL_DATABASE -e "load data local infile '$FILE_TR_HI' into table trans_hist_test fields terminated by ',' lines terminated by '\r\n'"


text:
Q: Smooth scrolling animation to sections of page in IE on Windows Phone I have a page with various sections and links to those sections. I have implemented scrolling animation with the following:
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') &&      location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
});
});

This works perfectly in Chrome, Safari, Firefox and on iOS 7 and Android, but on Windows Phone (8 with IE) the scrolling is jerky and the top of the section is out.
Any ideas how to make it work?

A: IE has a bug with the smooth scroll feature and animations not firing until after the scroll.
It is on by default for all win8 users of IE11.
Here is what I use to fix the jerkeyness on fixed header.
if(navigator.userAgent.match(/Trident\/7\./)) {
    $('body').on("mousewheel", function () {
        event.preventDefault();
        var wd = event.wheelDelta;
        var csp = window.pageYOffset;
        window.scrollTo(0, csp - wd);
    });
}


text:
Q: Server Timeout on Http GET on certain network I am trying to make a get request in Java using HttpURLConnection.  The response is 200 when I am on my home network but on the company nework i am getting a connect timed out error (SocketTimeoutException) I changed the timeout to be 20 seconds and I am still getting this error after a few seconds.  The link is available when I view it in the browser on the same network that I am getting the timeout from the Java code, so I could it still be a firewall issue? Or something else? Here is my code:
    String USER_AGENT = "Mozilla/5.0";
    URL obj = new URL("http://jsonplaceholder.typicode.com/posts/1");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setConnectTimeout(20000);
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);
    int responseCode = con.getResponseCode();
    System.out.println("GET Response Code :: " + responseCode);

A: This is typically an error produced by a firewall in your company's network. But if your browser is able to get to the internet, then your browser is using some proxy (likely the system proxy). So, you have to parametrize the JVM through the standard Java network properties to make it use the system proxy:
java -Djava.net.useSystemProxies=true ...

Or, alternatively, find out which are the system proxy parameters (host, port, user and password) and pass them to the JVM:
java -Dhttp.proxyHost=... -Dhttp.proxyPort=...


text:
Q: Android back to main activity from MusicService notification I'm working on a music player for android and i'm stuck at this problem.
By now i can play a song with musicservice and send it to background, i also display a notification with current playing song.
What i need is to re-open the main activity from the song notification and continue playing the song, it actually starts the desired activity but the music service is re-created and it stops the current playing song.
Here is my code.
MusicService.java
public class MusicService extends Service implements
    MediaPlayer.OnPreparedListener,
    MediaPlayer.OnErrorListener,
    MediaPlayer.OnCompletionListener {

private final IBinder musicBind = new MusicBinder();

//media player
private MediaPlayer player;

//song list
private ArrayList<SongModel> songs;

//current position
private int songPosition;

public MusicService() {
}

public void onCreate() {
    //create the service
    super.onCreate();

    //initialize position
    songPosition = 0;

    //create player
    player = new MediaPlayer();

    initMusicPlayer();
}

public void initMusicPlayer() {
    //set player properties
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);

}

public void setList(ArrayList<SongModel> theSongs) {
    songs = theSongs;
}

public class MusicBinder extends Binder {
    public MusicService getService() {
        return MusicService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return musicBind;
}

@Override
public boolean onUnbind(Intent intent) {
    player.stop();
    player.release();
    return false;
}

public int getPosition() {
    return player.getCurrentPosition();
}

public int getCurrenListPosition() {
    return songPosition;
}

public int getDuration() {
    return player.getDuration();
}

public boolean isPlaying() {
    return player.isPlaying();
}

public void pausePlayer() {
    player.pause();
}

public void stopPlayer() {
    player.stop();
}

public void seekToPosition(int posn) {
    player.seekTo(posn);
}

public void start() {
    player.start();
}

public void playSong() {
    try {
        //play a song
        player.reset();

        SongModel playSong = songs.get(songPosition);
        String trackUrl = playSong.getFileUrl();

        player.setDataSource(trackUrl);
        player.prepareAsync();

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

@Override
public void onCompletion(MediaPlayer mp) {
    if (mp.getCurrentPosition() == 0) {
        mp.reset();
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    mp.reset();
    return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
    //start playback
    mp.start();

    SongModel playingSong = songs.get(songPosition);

    Intent intent = new Intent(this, NavDrawerMainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(this);

    builder.setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_action_playing)
            .setTicker(playingSong.getTitle())
            .setOngoing(true)
            .setContentTitle(playingSong.getTitle())
            .setContentText(playingSong.getArtistName());

    Notification notification = builder.build();
    startForeground((int) playingSong.getSongId(), notification);
}

@Override
public void onDestroy() {
    stopForeground(true);
}

public void setSong(int songIndex) {
    songPosition = songIndex;
}

}
DiscoverSongsFragment.java
public class DiscoverSongsFragment extends Fragment
    implements MediaController.MediaPlayerControl {

JazzyGridView songsContainer;
SongsHelper songsHelper;
SongsAdapter songsAdapter;
ArrayList<SongModel> songsArrayList;
ConnectionState connectionState;

Context mContext;
private static View rootView;

SongModel currentSong;
SeekBar nowPlayingSeekBar;
final Handler handler = new Handler();

// this value contains the song duration in milliseconds.
// Look at getDuration() method in MediaPlayer class
int mediaFileLengthInMilliseconds;

View nowPlayingLayout;
boolean nowPlayingLayoutVisible;

TextView nowPlayingTitle;
TextView nowPlayingArtist;
ImageButton nowPlayingCover;
ImageButton nowPlayingStop;

private MusicService musicService;
private Intent playIntent;
private boolean musicBound = false;
private boolean playbackPaused = false;

private int mCurrentTransitionEffect = JazzyHelper.SLIDE_IN;

public static DiscoverSongsFragment newInstance() {
    return new DiscoverSongsFragment();
}

public DiscoverSongsFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_discover_songs, container, false);
    mContext = rootView.getContext();
    setupViews(rootView);

    return rootView;
}

@Override
public void onStart() {
    super.onStart();

    if (playIntent == null) {
        playIntent = new Intent(mContext, MusicService.class);
        mContext.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        mContext.startService(playIntent);
    }
}

@Override
public void onResume() {
    super.onResume();

    if (isPlaying()) {
        showNowPlayingLayout();
        primarySeekBarProgressUpdater();
    }
}

@Override
public void onDestroy() {
    mContext.stopService(playIntent);
    musicService = null;
    super.onDestroy();
}

private void hideNowPlayingLayout() {
    nowPlayingLayoutVisible = false;
    nowPlayingLayout.setVisibility(View.GONE);

    Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_out);
    nowPlayingLayout.startAnimation(animationFadeIn);
}

private void showNowPlayingLayout() {
    nowPlayingLayoutVisible = true;
    nowPlayingLayout.setVisibility(View.VISIBLE);

    Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
    nowPlayingLayout.startAnimation(animationFadeIn);
}

private void setupViews(View rootView) {
    songsHelper = new SongsHelper();
    songsArrayList = new ArrayList<SongModel>();
    connectionState = new ConnectionState(mContext);
    songsAdapter = new SongsAdapter(mContext, songsArrayList);

    nowPlayingLayout = rootView.findViewById(R.id.nowPlayingLayout);
    nowPlayingLayout.setVisibility(View.GONE);
    nowPlayingLayoutVisible = false;

    songsContainer = (JazzyGridView) rootView.findViewById(R.id.songsContainerView);
    songsContainer.setTransitionEffect(mCurrentTransitionEffect);
    songsContainer.setAdapter(songsAdapter);
    songsContainer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            musicService.setSong(position);
            musicService.playSong();

            if (playbackPaused) {
                playbackPaused = false;
            }

            currentSong = songsArrayList.get(position);

            // gets the song length in milliseconds from URL
            mediaFileLengthInMilliseconds = getDuration();

            if (currentSong != null) {
                nowPlayingTitle.setText(currentSong.getTitle());
                nowPlayingArtist.setText(currentSong.getArtistName());
                nowPlayingCover.setImageBitmap(currentSong.getCoverArt());
            }

            primarySeekBarProgressUpdater();

            if (!nowPlayingLayoutVisible) {
                showNowPlayingLayout();
            }
        }
    });

    nowPlayingSeekBar = (SeekBar) rootView.findViewById(R.id.nowPlayingSeekbar);
    nowPlayingSeekBar.setMax(99);

    nowPlayingTitle = (TextView) rootView.findViewById(R.id.nowPlayingTitle);
    nowPlayingArtist = (TextView) rootView.findViewById(R.id.nowPlayingArtist);
    nowPlayingStop = (ImageButton) rootView.findViewById(R.id.nowPlayingStop);
    nowPlayingStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isPlaying()) {

                currentSong = null;
                playbackPaused = false;
                musicService.stopPlayer();
                mediaFileLengthInMilliseconds = 0;
                nowPlayingSeekBar.setProgress(0);
                hideNowPlayingLayout();

            }
        }
    });

    nowPlayingCover = (ImageButton) rootView.findViewById(R.id.nowPlayingCover);
    nowPlayingCover.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Intent intent = new Intent(mContext, SongDetailsActivity.class);
                intent.putExtra("Title", currentSong.getTitle());
                intent.putExtra("Artist", currentSong.getArtistName());
                intent.putExtra("Album", currentSong.getAlbumName());
                intent.putExtra("Genre", currentSong.getGenre());
                intent.putExtra("CoverUrl", currentSong.getCoverArtUrl());

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

    getSongs();
    hideNowPlayingLayout();
}

private void getSongs() {

    if (!connectionState.isConnectedToInternet()) {

    }

    songsAdapter.clear();

    String songsUrl = Constants.getAPI_SONGS_URL();
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(songsUrl, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {

            if (jsonArray != null) {

                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        SongModel song = songsHelper.getSongFromJson(jsonObject);
                        songsAdapter.add(song);

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

                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    });

    AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

@Override
public void onDetach() {
    super.onDetach();
}

/**
 * Method which updates the SeekBar primary progress by current song playing position
 */
private void primarySeekBarProgressUpdater() {
    nowPlayingSeekBar.setProgress((int) (((float) getCurrentPosition() / getDuration()) * 100));

    //if (isPlaying()) {
    Runnable runnable = new Runnable() {
        public void run() {
            primarySeekBarProgressUpdater();
        }
    };
    handler.postDelayed(runnable, 1000);
    //}
}

@Override
public void start() {
    musicService.start();
}

@Override
public void pause() {
    playbackPaused = true;
    musicService.pausePlayer();
}

@Override
public int getDuration() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.getDuration();
    }
    return 0;
}

@Override
public int getCurrentPosition() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.getPosition();
    }
    return 0;
}

public int getCurrentListPosition() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.getCurrenListPosition();
    }
    return 0;
}

@Override
public void seekTo(int pos) {
    musicService.seekToPosition(pos);
}

@Override
public boolean isPlaying() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.isPlaying();
    }
    return false;
}

@Override
public int getBufferPercentage() {
    return 0;
}

@Override
public boolean canPause() {
    return true;
}

@Override
public boolean canSeekBackward() {
    return true;
}

@Override
public boolean canSeekForward() {
    return true;
}

@Override
public int getAudioSessionId() {
    return 0;
}

//connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
        //get service
        musicService = binder.getService();
        //pass list
        musicService.setList(songsArrayList);
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        musicBound = false;
    }
};

}
(The fragment also re-creates itself when navigating through drawer menu items)
I hope somebody can help me achieve this. I dont know how to maintane the state when re-starting the MainActivity (by the way, im using navdrawer to hold fragments)

A: Include the currently playing song in your notification intent.  Update the intent as the song changes.  Include the flag to clear top and the flag to update current in the notification intent. :( sorry IDK if I have the flags right for your situation but you'll have a place to do more research.
In your service where you create the notification intent.
        // link the notifications to the recorder activity
        Intent resultIntent = new Intent(context, KmlReader.class);
        resultIntent
                .setAction(ServiceLocationRecorder.INTENT_COM_GOSYLVESTER_BESTRIDES_LOCATION_RECORDER);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent resultPendingIntent = PendingIntent
                .getActivity(context, 0, resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        return mBuilder.build();
    }

Then in main onCreate check the bundle for the name of the currently playing song and display it.  Notice how I check for the existence of a bundle key before using it.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();

    String intentaction = intent.getAction();

    // First Run checks
    if (savedInstanceState == null) {
        // first run init

...
    } else {
        // get the saved_Instance state
        // always get the default when key doesn't exist
        // default is null for this example
        currentCameraPosition = savedInstanceState
                .containsKey(SAVED_INSTANCE_CAMERA_POSITION) ? (CameraPosition) savedInstanceState
                .getParcelable(SAVED_INSTANCE_CAMERA_POSITION) : null;

...


text:
Q: stream and functional Interface: throw exception inside stream and aggregate them I am new to stream and functional interface and just wonder if this requirement could be done via them. Given an array of integers, if any of them is negative, then do not process but instead throw exception containing all negative integers.
Example: INPUT = [0, -1, -2]
EXPECTED Exception: invalid integers: (-1, -2).

I do know how to do that with a for loop but really curious if this can be achieved via stream and functional interfaces. So any help is appreciated.
int [] input = {0, -1, -2};
List<Integer> negatives = new LinkedList<>();

for (int i : input) {
    if (i < 0) {
        negatives.add(i);
    }
}

if (negatives.isEmpty() == false) {
    throw new IllegalArgumentException("Invalid integers: " + negatives);
}

A: I'd write it with a simple filter:
final List<Integer> invalid = Arrays.asList(0, -1, -2).stream()
    .filter(i -> i < 0)
    .collect(Collectors.toList());

if (!invalid.isEmpty()) throw new RuntimeException("Invalid integers " + invalid);

A: You can do as follow
public static void main(String[] args)  {
    List<Integer> list = Arrays.asList(1, 2, 3, -3, -2);
    checkList(list);
}

private static void checkList(List<Integer> list) {
    list.stream().filter(i -> i < 0).findFirst()
            .ifPresent(integer -> {
                throw new IllegalArgumentException("Invalid are" +
                             Arrays.toString(list.stream().filter(i -> i < 0).toArray()));
            });
}

Which will give
Exception in thread "main" java.lang.RuntimeException: Invalid are[-3, -2]


text:
Q: webpack + react + config file I'm pretty new using this technologies and there is a thing I need to achieve and I can't do it.
When I build my react project, webpack chunks all the files in a couple of javascripts.
I have many URL's defined (for example endpoint URL's to access some services).
My idea is to copy this build to different environments (qa, prod) and modify the values of the URL.
The IMPORTANT thing here is that I'll not have the URL's from prod, so I'll need a configuration file outside all the chunked javascripts where I can reference from my project.
Basically what I want is to have a json file outside all the js chunked file and use it from a react component for example.
Is this possible?
Thanks


text:
Q: Input characters not reading correctly This should be a simple error. My code is basically reading a user input value and if the value is greater than 0 it will return the value. If not it will print an error and ask for the value again. The only problem is when a new value is input it uses the old false value without error.
int menuSize(int s) {
printf(" Please Enter size: ");
scanf("%i", &s);
if (s>0) {
}
else {
    printf(" Invalid Input\n");
    getchar();
    menuSize(s);
}
return s;
}

A: If the input is invalid, the function makes a recursive call to itself but doesn't do anything with the return value of the recursive call.  That means the invalid value that was read in the current invocation is what will be returned.
Change the function to return the value of the recursive call.  Also, get rid of the parameter to the function since it isn't used and make s local.  You should also initialize s to some known value and check the return value of scanf in case nothing gets read.
int menuSize(void)
{
    int s = -1;
    printf(" Please Enter size: ");
    int rval = scanf("%i", &s);
    if (rval == 1 && s>0) {
        return s;
    } else {
        printf(" Invalid Input\n");
        getchar();
        return menuSize();
    }
}


text:
Q: How to remove the namespace name without removing the namespace declaration I'm still pretty new to XSLT and I have the following XML which I need to remove the namespace.  I also found the following XSLT which almost gets the job done with the exception that it will not retain the xmlns declaration.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<etd_ms:thesis xmlns:etd_ms="http://www.ndltd.org/standards/metadata/etdms/1.0/"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.ndltd.org/standards/metadata/etdms/1.0/ http://www.ndltd.org/standards/metadata/etdms/1.0/etdms.xsd">
   <etd_ms:title>Aspects of negritude in the works of two Harlem renaissance authors : Claude McKay and Langston Hughes</etd_ms:title>
   <etd_ms:creator>Charles, Asselin</etd_ms:creator>
   <etd_ms:subject/>
   <etd_ms:publisher>Concordia University</etd_ms:publisher>
   <etd_ms:contributor role="advisor">Butovsky, M</etd_ms:contributor>
   <etd_ms:date>1980</etd_ms:date>
   <etd_ms:type>Electronic Thesis or Dissertation</etd_ms:type>
   <etd_ms:identifier>TC-QMG-1</etd_ms:identifier>
   <etd_ms:format>text</etd_ms:format>
   <etd_ms:identifier>https://spectrum.library.concordia.ca/1/1/MK49585.pdf</etd_ms:identifier>
   <etd_ms:language>en</etd_ms:language>
   <etd_ms:degree>
      <etd_ms:name>M.A.</etd_ms:name>
      <etd_ms:level>masters</etd_ms:level>
      <etd_ms:discipline>Dept. of English</etd_ms:discipline>
      <etd_ms:grantor>Concordia University</etd_ms:grantor>
   </etd_ms:degree>
</etd_ms:thesis>

and here's the XSLT:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output indent="yes" method="xml" encoding="utf-8" omit-xml-declaration="no"/>

    <!-- Stylesheet to remove all namespaces from a document -->
    <!-- NOTE: this will lead to attribute name clash, if an element contains
        two attributes with same local name but different namespace prefix -->
    <!-- Nodes that cannot have a namespace are copied as such -->

    <!-- template to copy elements -->
    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template>

    <!-- template to copy attributes -->
    <xsl:template match="@*">
        <xsl:attribute name="{local-name()}">
            <xsl:value-of select="."/>
        </xsl:attribute>
    </xsl:template>

    <!-- template to copy the rest of the nodes -->
    <xsl:template match="comment() | text() | processing-instruction()">
        <xsl:copy/>
    </xsl:template>

</xsl:stylesheet>

The results is the following:
<?xml version="1.0" encoding="UTF-8"?>
<thesis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.ndltd.org/standards/metadata/etdms/1.0/ http://www.ndltd.org/standards/metadata/etdms/1.0/etdms.xsd">
   <title>Aspects of negritude in the works of two Harlem renaissance authors : Claude McKay and Langston Hughes</title>
   <creator>Charles, Asselin</creator>
   <subject/>
   <publisher>Concordia University</publisher>
   <contributor role="advisor">Butovsky, M</contributor>
   <date>1980</date>
   <type>Electronic Thesis or Dissertation</type>
   <identifier>TC-QMG-1</identifier>
   <format>text</format>
   <identifier>https://spectrum.library.concordia.ca/1/1/MK49585.pdf</identifier>
   <language>en</language>
   <degree>
      <name>M.A.</name>
      <level>masters</level>
      <discipline>Dept. of English</discipline>
      <grantor>Concordia University</grantor>
   </degree>
</thesis>

It's almost there, with the exception that I need to keep the xmlns declaration, so ultimatly the root element should be something like:
<thesis xmlns="http://www.ndltd.org/standards/metadata/etdms/1.0/"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.ndltd.org/standards/metadata/etdms/1.0/ http://www.ndltd.org/standards/metadata/etdms/1.0/etdms.xsd">

Can someone help me resolving this issue?  Thanks.

A: Change
<xsl:element name="{local-name()}">

to
<xsl:element name="{local-name()}" namespace="http://www.ndltd.org/standards/metadata/etdms/1.0/">


text:
Q: Touch on Android Secondary Display I would like to enable mouse and\or touch input on a secondary display on Android.
Is it possible? It seems like secondary display is only targeted for presentations on HDMI or WiFi Displays where touchscreen doesn't normally exist.
However I don't see why I shouldn't be allowed to plug in mouse and allow it to move from primary display to secondary one. Or have the mouse exclusively on a secondary monitor.


text:
Q: How do apps like Mapbox, AllTrails and Maps.me use and display ALL of OSM data? When all the resources say that's a huge amount of data I started exploring Overpass Turbo and Mapbox with hopes of building my travel app. I can query some data in OT and get towns or islands, no problem, I understand the whole process of querying and exporting as Geojson.
But for learning purposes, I always do queries within a small area so I don't get too much data back.
Also, various resources mention that OSM data for the whole planet is huge, like here: https://wiki.openstreetmap.org/wiki/Downloading_data it says: The entire planet is a huge amount of data. Start with a regional extract to make sure your setup works properly. Common tools like Osmosis or various import tools for database imports and converters take hours or days to import data, depending largely on disk speed.
But when I go to apps like AllTrails, Maps.me or Mapbox, they seem to be showing a huge amount of data, definitely the main POIs.
here's an example screenshot from All Trails
Can someone briefly explain how is this done then? Do they actually download all of data? Or little by little depending on the current bounding box. Any info I can research further, I'd appreciate it!
Thanks
P.S. I am hoping to build my app with Node.js, if that makes a difference.

A: Several reasons:

*

*They don't always display everything. You will always only see a limited region, never the whole world in full detail. If you zoom in, you will see a smaller region but with more details. If you zoom out, you will see a larger region but with reduced details (less or no POIs, smaller roads and waterways disappear etc.).

*They don't contain all the available data. OSM data is very diverse. OSM contains roads, buildings, landuse, addresses, POI information and much more. For each of the mentioned elements, there is additional information available. Roads for instance have maxspeed information, lane count, surface information, whether they are lit and if they have sidewalks or cycleways etc. Buildings may have information about the number of building levels, the building color, roof shape and color and so on. Not all of these information are required for the apps you listed and thus can be removed from the data.

*They perform simplifications. It isn't always necessary to show roads, buildings, waterways and landuse in full detail. Instead, special algorithms reduce the polygon count so that the data becomes smaller while keeping sufficient details. This is often coupled with the zoom level, i.e. roads and lakes will become less detailed if zoomed out.

*They never ship the whole world offline. Depending on the app, the map is either online or offline available, or both. If online, the server has to store the huge amount of data, not the client device. If offline, the map is split into smaller regions that can be handled by the client. This usually means that a certain map only covers a state, a certain region or sometimes a city but rarely a whole country except for smaller countries. If you want to store whole countries offline you will need a significant amount of data storage.

*They never access OSM directly. All apps and websites that display OSM maps don't obtain this information live from OSM. Instead, they either already have a local database containing the required data. This database is periodically updated from the main OSM database via planet dumps. Or they use a third-party map provider (such as MapBox from your screenshot) to display a base map with layers on top. In this case they don't have to store much information on their server, just the things they want to show on top of OSM.
None of the above is specifically for OSM. You will find similar mechanisms in other map apps and for other map sources.


text:
Q: ElasticSearch - creating JDBC river I working on a PHP project, Using MYSQL for storing data. I want to use ElasticSearch search engine for searching I installed the ES on my Mac OS. I know after that I should create JDBC river but I don't know how. Any body can help me? thanks.

A: Steps to install Elasticsearch JDBC River Plugin
1) Download and install Elasticsearch
2) Start Elasticsearchby running bin/elasticsearch from the installation directory
3) Install the river-jdbc plugin for Elasticsearch version. You can get jdbc river plugin for your version from here
If you are using elaticssearch version 1.0.0 then your installation command will be
./bin/plugin --install river-jdbc --url http://bit.ly/1gIk4jW

4) Now download the MySQL JDBC driver. The current version is 5.1.30. You can get latest version information from here
5) Copy jar in elasticsearch/plugins/river-jdbc direcory
6) Now Restart elasticsearch from your installation directory bin/elsaticsearch -f
7) Run below command configure jbdc river with your elasticsearch index.
curl -XPUT 'localhost:9200/_river/my_jdbc_river/_meta' -d '{
    "type" : "jdbc",
    "jdbc" : {
        "url" : "jdbc:mysql://localhost:3306/test",
        "user" : "",
        "password" : "",
        "sql" : "select * from yourDBTable",
        "index" : "write_index_name_here",
        "type" : "write_index_type_here"
    }
}'

You can use more parameter as per your need more details about elasticsearch-river-jdbc parameters
8) Now test your plugin is up or not using below command
curl -XGET 'localhost:9200/jdbc/_search?pretty&q=*'


text:
Q: Converting ASP.Net GridView HTML into a string We are trying to take the HTML from a GridView and store it into a String so that string can be used a a body of an email.
So far we have used this coding in the code-behind:
Protected Sub EmailStudentList()

    ' Get the rendered HTML.
    '-----------------------
    Dim SB As New StringBuilder()
    Dim SW As New StringWriter(SB)
    Dim htmlTW As New HtmlTextWriter(SW)

    GridViewSummary.RenderControl(htmlTW)

    ' Get the HTML into a string.
    ' This will be used in the body of the email report.
    '---------------------------------------------------
    Dim dataGridHTML As String = SB.ToString()

    MsgBox(Server.HtmlEncode(dataGridHTML))
End Sub

When the application is running this error is displayed:
Control 'BodyPlaceholder_GridViewSummary' of type 'GridView' must be placed
inside a form tag with runat=server.

so I placed a form tag at this location in the markup:
<asp:Content
    ID="ContentBody"
    ContentPlaceHolderID="BodyPlaceholder"
    runat="server">

<form runat="server">

Now we get this error:
A page can have only one server-side Form tag.

There are no other form tags in anywhere else in the markup.
This is the markup for the GridView:
<asp:GridView
    ID="GridViewSummary"
    runat="server"
    AllowPaging="True"
    AllowSorting="True"
    AutoGenerateColumns="False">

    <Columns>
        <asp:BoundField DataField="Surname" HeaderText="Last Name" SortExpression="Surname" />
        <asp:BoundField DataField="Forename" HeaderText="First Name" SortExpression="Forename" />
        <asp:BoundField DataField="ParentName" HeaderText="Parents" SortExpression="ParentName" />
    </Columns>

</asp:GridView>

A: Add following sub in your page and try again:
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    Return
End Sub

Edit:
To turn off event validation, just add EnableEventValidation="False" into your aspx page's directive. For example
<%@ Page EnableEventValidation="False" %>


text:
Q: How to set the dictionary for text analysis using neural networks I want to use a neural network to do text analysis.
If I use a large dictionary, then it will contain all the words in training and test set, but the size of the dictionary is too large which will make the neural network training hard and time consuming. Another option is using the words in training set only, and make it a dictionary, for test set, all the words that are not in dictionary will be disregarded. Which option is better?
In general, I think for a bag of words model, the second option doesn't harm too much, and we may use it. But for other models, for example, if we treat the text as a series (time series), and we use a recurrent neural network, disregarding some words may break the relationship in this series or create a wrong relationship.  So how to set the dictionary for the above situations?

A: The standard method for handling unseen words is to use word embeddings, and in your
particular case/question, neural embeddings, like the word2vec model by Mikolov. The principal, underlying approach is to add "unseen words" to your training set, so it does not depend on the machine learning method being used.
One way is to randomly pepper your training set with "unseen" words, replacing a random selection of your low-frequency words with "unseen" ones by replacing those words with the special token UNSEEN, which you add to your vocabulary ("dictionary") for this purpose. Another, even simpler approach is to replace all your words in the training set with a frequency below some cutoff (2 or 3, normally - i.e., words that only appear once or twice and as such are often quite "useless") with that special token UNSEEN.
Just in case this is not obvious: Do not use the actual string "UNSEEN", as it is likely to occur in your training or test data, or at least in production. Use some symbol that you are absolutely sure will remain a unique sentinel in your system, e.g., by padding it with special characters that would have been separated by your tokenizer.
Then, when you actually do find missing words during the test phase or in production, your system already has learned how to handle the situation gracefully and will still produce the best possible result, because you feed it this special UNSEEN token instead (of the actual, never-before-seen word).
Overall, the vocabulary for your system is the entire space of training words plus this "unseen word" UNSEEN (plus the padding tokens for the word vectors, naturally, but this is unrelated to the question). Thus, the ("feature extracted") WV you then get from your inputs can mitigate the strong effect unseen words normally have in your downstream processing, because all the "seen" words (during training) in the surrounding of the unseen word (during testing/production) will aid in figuring out the semantic space of this unseen word. Overall, this is probably half of the explanation why word embeddings are so popular (the other half being the semantic aspect).
An example of this, using RNNs and Theano, can be found in this deep learning tutorial, mostly based on the paper linked to earlier.
It should be noted that this approach of handling unseen words is not restricted to neural networks/embeddings, and computationally far more efficient methods like Hellinger PCA or low-rank multi-view learning (LR-MVL) can achieve the same effect with equal performance.
To make this discussion complete, it is necessary to mention two more advanced techniques for this issue. One is to include the orthographic properties in the learning process, which can be helpful (yet expensive, because you have to match words based on similarity) when words are just misspelled and can help detect words that are proper nouns or symbols ("1a"), because they have rather particular orthography. This approach was, for example, suggested in an ArXiv paper (Note that they wrongly use the word morphological here, which is actually something very different to the orthographic properties they are measuring; well, this is ArXiv, not JMLR...) Finally, the most advanced technique maybe is to forgo words entirely and train you neural network right off the character stream.
EDIT 26/06/2017: As this answer is still getting votes, an update might be a good idea. My latest favorite way of handling unseen words is by also learning embeddings for character n-grams ("subword information"), as implemented by FastText and described in an (warning: not peer reviewed) arXiv document entitled "Enriching Word Vectors with Subword Information".


text:
Q: How to find lost horse? I'm in a HUMONGOUS RPG map, and I fenced in a horse near the edge of a forest. I have two problems:

*

*I want my horse back

*I want to find the area where that was

I can't find the area, and I want to get there. I know commands to tp the horse to me, but I want to find that whole area, not just the horse. So is there a command to locate the horse? A command that will just give me the coordinates?

A: No, there is no command to locate an entity.
There is however a way, but be aware that this will always require the horse to be loaded first of all, so you need to be inside render distance from it or it has to be in the spawn chunks.
You do /tp @p @e[type=horse,c=1] to teleport yourself to the nearest horse.
You can also try to do /tp @e[type=horse] ~ ~ ~. This should print the coordinates of every loaded horse in chat, because it will teleport them to the coordinates where they already are and return the success message containing the coordinates (be aware this this will be different in version 1.13).

A: With the new 1.13 update, that command does not work but you can use:
/tp @e[type=minecraft:horse,limit=1,sort=nearest]

to teleport you to the nearest horse.

A: You can use @e[type=horse,name=whateveryounamedyourhorse] in the teleport, then, if there are no spaces or commas in the name, you get teleported to the horse directly (if it's loaded).
I did this and I found my horse Maximus.


text:
Q: MultiBoost vs Gradient Boosted Decision Trees Why isn't there an implementation of GBDT in Weka? (Java ML library)
Instead the recommendation is to use the MultiBoost algorithm with J48 (Java implementation of Decision Trees - C4.5 algorithm). Refer - MultiBoost
Do you know if MultiBoost is a superior version of GBDT or if there are more intricacies and differences to be aware of?

A: I posted this question to the weka mailing list and got the following answer:
For squared error as the loss function, WEKA has AdditiveRegression. You can run it with depth-limited and otherwise unpruned REPTree models to implement gradient-boosted regression trees. You can also combine it with Bagging, and use RandomTree as an alternative to REPTree to inject randomness into the learning process.
For minimising negative loglikelihod in classification problems, you can take a look at LogitBoost as an alternative. Again, use it with depth-limited and otherwise unpruned REPTree models (or RandomTree).
To automatically determine an appropriate number of iterations for these methods, use IterativeClassifierOptimizer.
Google
weka iterativeclassifieroptimizer
etc.
If you install the RPlugin package for WEKA, you can also access xgboost and well-known gradient boosting implementations in R through WEKA's MLRClassifier (which uses the mlr package in R to access learning algorithms in R).


text:
Q: Relations between fractional ideals of an order of a quadratic number field and binary quadratic forms Let $\mathfrak{F}$ be the set of binary quadratic forms over $\mathbb{Z}$.
Let $F = ax^2 + bxy + cy^2 \in \mathfrak{F}$.
We say $D = b^2 - 4ac$ is the discriminant of $F$.
It is easy to see that $D \equiv 0$ (mod $4$) or $D \equiv 1$ (mod $4$).
Let $\Gamma =SL_2(\mathbb{Z})$.
Let $\alpha = \left( \begin{array}{ccc}
p & q \\
r & s \end{array} \right)$ be an element of $\Gamma$.
We write $f^\alpha(x, y) = f(px + qy, rx + sy)$.
Since $(f^\alpha)^\beta$ = $f^{\alpha\beta}$, $\Gamma$ acts on $\mathfrak{F}$ from right.
Let $D$ be a non-square integer such that $D \equiv 0$ (mod $4$) or $D \equiv 1$ (mod $4$).
We denote the set of binary quadratic forms of discriminant $D$ by $\mathfrak{F}(D)$.
It is easy to see that $\Gamma$ acts on $\mathfrak{F}(D)$ from right.
Let $\sigma = \left( \begin{array}{ccc}
1 & 1 \\
0 & 1 \end{array} \right) \in \Gamma$.
Let $\Gamma_{\infty} = \{\sigma^n; n \in \mathbb{Z}\}$.
$\Gamma_{\infty}$ also acts on $\mathfrak{F}(D)$ from right.
We denote the set of $\Gamma_{\infty}$-orbits on $\mathfrak{F}(D)$ by $\mathfrak{F}(D)/\Gamma_{\infty}$.
Let $K$ be a quadratic number field.
Let $R$ be an order of $K$.
Let $D$ be its discriminant.
It is easy to see that $D$ is not not a square integer and $D \equiv 0$ (mod $4$) or $D \equiv 1$ (mod $4$).
We denote the group of invertible elements of the ring $\mathbb{Z}$ by $\mathbb{Z}^\times$.
Namely $\mathbb{Z}^\times = \{-1, 1\}$.
Let $F = ax^2 + bxy + cy^2 \in \mathfrak{F}(D)$.
By this question, $I = \mathbb{Z}a + \mathbb{Z}\frac{(-b + \sqrt{D})}{2}$ is an ideal of $R$.
Hence we get a map $\psi_0\colon \mathfrak{F}(D) \rightarrow \mathfrak{i}(R)$, where $\mathfrak{i}(R)$ is the set of fractional ideals of $R$.
We define a map $\psi_1\colon \mathfrak{F}(D) \rightarrow \mathfrak{i}(R)\times\mathbb{Z}^\times$
by $\psi_1(F) = (\psi_0(F), sgn(a))$, where  $sgn(a)$ is the sign of $a$.
It is easy to see that $\psi_1$ induces a map $\mathfrak{F}(D)/\Gamma_{\infty} \rightarrow \mathfrak{i}(R)\times\mathbb{Z}^\times$.
Hence this map induces a map $$\psi\colon\mathfrak{F}(D)/\Gamma_{\infty} \rightarrow (\mathfrak{i}(R)/\mathbb{Q}^\times)\times\mathbb{Z}^\times$$
Next we would like to define a map $(\mathfrak{i}(R)/\mathbb{Q}^\times)\times\mathbb{Z}^\times \rightarrow \mathfrak{F}(D)/\Gamma_{\infty}$
Let $I \in \mathfrak{i}(R)$.
$I$ can be written as $I = J/\lambda$, where $J$ is an ideal of $R$ and $\lambda \in R$.
We define the norm of $I$ as $N(I) = N(J)/N(\lambda R)$.
It is easy to see that this is well defined.
Let $\alpha, \beta \in K$.
We denote $\alpha\beta' - \alpha'\beta$ by $\Delta(\alpha, \beta)$, where $\alpha'$(resp. $\beta'$) is the conjugate of $\alpha$(resp. $\beta$).
$\Delta(\alpha, \beta) \neq 0$ if and only if $\alpha, \beta$ are linearly independent over $\mathbb{Q}$.
If $D < 0$, we define $\sqrt{D}$ as i$\sqrt{|D|}$.
Let $\{\alpha, \beta\}$ be $\mathbb{Z}$-basis of $I \in \mathfrak{i}(R)$.
If $\Delta(-\alpha, \beta)/\sqrt{D} > 0$, we say the basis $\{\alpha, \beta\}$ is positively oriented.
If $\Delta(-\alpha, \beta)/\sqrt{D} < 0$, we say the basis $\{\alpha, \beta\}$ is negatively oriented.
Let $\{\alpha, \beta\}$ be positively oriented basis of $I \in \mathfrak{i}(R)$.
We can assume that $\alpha \in \mathbb{Q}$.
Let $x, y$ be indeterminates.
Let $s \in \mathbb{Z}^\times$.
We write $f(\alpha, \beta, s; x, y) = sN_{K/\mathbb{Q}}(x\alpha - sy\beta)/N(I)$.
Namely $f(\alpha, \beta, s; x, y) = s(x\alpha - sy\beta)(x\alpha' - sy\beta')/N(I)$.
It is easy to see that $f(\alpha, \beta, s; x, y)$ is a binary quadratic form of discriminant $D$.
My question
Are the following propositions true?
If yes, how do we prove them?
Proposition 1
The class of $\mathfrak{F}(D)/\Gamma_{\infty}$ represented by $f(\alpha, \beta, s; x, y)$ is determined only by the class of $(\mathfrak{i}(R)/\mathbb{Q}^\times)$ represented by $I$ and $s$.
Proposition 2
By proposition 1, we can define a map $$\phi\colon (\mathfrak{i}(R)/\mathbb{Q}^\times)\times\mathbb{Z}^\times \rightarrow \mathfrak{F}(D)/\Gamma_{\infty}$$ by $\phi(([I], s)) = [f(\alpha, \beta, s; x, y)]$, where $[I]$(resp. $[f(\alpha, \beta, s; x, y)]$) denotes the class represented by $I$(resp. $f(\alpha, \beta, s; x, y)$).
Then $\psi$ and $\phi$ are inverses of each other.
Corollary
Let $\mathfrak{F}_0(D)$ be the set of primitive binary quadratic forms of discriminant $D$.
Let $\mathfrak{I}(R)$ be the group of invertible fractional ideals of $R$.
Then the map $\psi$ induces a bijection:
$$\mathfrak{F}_0(D)/\Gamma_{\infty} \rightarrow (\mathfrak{I}(R)/\mathbb{Q}^\times)\times\mathbb{Z}^\times$$
Proof:
This follows immediately from proposition 2 and the proposition of this question.

A: Notations
We denote a binary quadrtic form $ax^2 + bxy + cy^2$ also by $(a, b, c)$.
Let $x_1,\cdots,x_n$ be elements of $K$.
We denote by $[x_1,\cdots,x_n]$ the subgroup of $K$ generated by the set $\{x_1,\cdots,x_n\}$.
First we prove that the map $\psi\colon\mathfrak{F}(D)/\Gamma_{\infty} \rightarrow (\mathfrak{i}(R)/\mathbb{Q}^\times)\times\mathbb{Z}^\times$ is well-defined.
It suffices to prove the following lemma.
Lemma 1
Let $\psi_0\colon \mathfrak{F}(D) \rightarrow \mathfrak{i}(R)$ be the map defined in the question.
Let $(a, b, c) \in \mathfrak{F}(D)$.
Then $\psi_0((a,b,c)^{\sigma^n}) = \psi_0((a, b, c))$, where $\sigma = \left( \begin{array}{ccc}
1 & 1 \\
0 & 1 \end{array} \right) \in \Gamma$ and $n \in \mathbb{Z}$.
Proof:
Note that $\sigma^n = \left( \begin{array}{ccc}
1 & n \\
0 & 1 \end{array} \right) \in \Gamma$.
$a(x + ny)^2 + b(x + ny)y + cy^2 = ax^2 + (2an + b)xy + an^2 + bn + c$.
Hence $(a,b,c)^{\sigma^n} = (a, 2an + b, an^2 + bn + c)$.
Hence $\psi_0((a,b,c)^{\sigma^n}) = [a, (-2an - b + \sqrt D)/2] = [a, -an + (-b + \sqrt D)/2] = [a, (-b + \sqrt D)/2] = \psi_0((a, b, c)).$
QED
Definition 1
Let $I$ be a fractional ideal of $R$.
Let $\alpha, \beta$ be $\mathbb{Z}$-basis of $I$.
It is easy to see that $\Delta(\alpha, \beta)^2$ is a non-zero rational number and independent of the choice of the $\mathbb{Z}$-basis(see Lemma 7 of my answer to this question).
We denote it by $d(I)$.
Lemma 2
Let $I$ be a fractional ideal of $R$.
Let $\gamma \in I$.
Then $N(\gamma)/N(I)$ is a rational integer.
Proof:
We may suppose $\gamma \ne 0$.
By Proposition 13 of my answer to this question, $N(\gamma R)/N(I)$ is a rational integer. On the other hand, by Proposition 11 of the same answer, $N(\gamma R) = |N(\gamma)|$.
QED
Definition 2
Let $I = [\alpha, \beta]$ be a fractional ideal of $R$.
Let $x, y$ be indeterminates.
Let $s \in \mathbb{Z}^\times$.
We write $f(\alpha, \beta, s; x, y) = sN_{K/\mathbb{Q}}(x\alpha - sy\beta)/N(I)$.
Namely $f(\alpha, \beta, s; x, y) = s(x\alpha - sy\beta)(x\alpha' - sy\beta')/N(I)$.
Lemma 3
Let $I = [\alpha, \beta]$ be a fractional ideal of $R$.
Then $f(\alpha, \beta, s; x, y)$ is an integral binary quadratic form of discriminant $D$,
i.e. $f(\alpha, \beta, s; x, y) \in \mathfrak{F}(D)$.
Proof:
We first prove that $f(\alpha, \beta, s; x, y)$ has integral coefficients.
$N(x\alpha - sy\beta) = (x\alpha - sy\beta)(x\alpha' - sy\beta')
= (\alpha \alpha')x^2 - s(\alpha\beta' + \beta\alpha')xy + (\beta\beta')y^2$.
Hence $f(\alpha, \beta, s; x, y) = ax^2 + bxy + cy^2$,
where
$a = s(\alpha \alpha')/N(I)$
$b = -(\alpha\beta' + \beta\alpha')/N(I)$
$c = s(\beta\beta')/N(I).$
By Lemma 2, $a, c \in \mathbb{Z}$.
$N(\alpha + \beta) = (\alpha + \beta)(\alpha' + \beta')
= \alpha \alpha' + (\alpha\beta' + \beta\alpha') + \beta\beta'$.
Hence $(\alpha\beta' + \beta\alpha')/N(I) = N(\alpha + \beta)/N(I) - N(\alpha) /N(I) - N(\beta)/N(I)$.
Hence, by Lemma 2, $b \in \mathbb{Z}$.
It remains to prove that the discriminant of $f(\alpha, \beta, s; x, y)$ is $D$.
Since $(\alpha\beta' + \beta\alpha')^2 - 4\alpha \alpha'\beta\alpha' = (\alpha\beta' - \beta\alpha')^2 = \Delta(\alpha, \beta)^2 = d(I), b^2 - 4ac = d(I)/N(I)^2$.
Hence, by the corollary of Proposition 12 of my answer to this question, $b^2 - 4ac = D$.
QED
Lemma 4
Let $I = [\alpha, \beta]$ be a fractional ideal of $R$.
Let $r \ne 0$ be a rational number.
Then $f(r\alpha, r\beta, s; x, y) = f(\alpha, \beta, s; x, y)$.
Proof:
$f(r\alpha, r\beta, s; x, y) = sN(xr\alpha - syr\beta)/N(rI) = sN(r)N(x\alpha - sy\beta)/|N(r)|N(I) = sr^2N(x\alpha - sy\beta)/r^2N(I) = f(\alpha, \beta, s; x, y).$
QED
Lemma 5
Let $I$ be a fractional ideal of $R$.
Then there exists $r \in \mathbb{Q}$ and a primitive ideal(see here) $I_0$ such that $I = rI_0$.
Proof:
There exists $\gamma \ne 0 \in K$ such that $\gamma I \subset R$.
We may suppose $\gamma \in R$.
Let $c = N(\gamma)$.
Then $cI = \gamma'\gamma I \subset \gamma'R \subset R$.
There exist $d \in \mathbb{Z}$ and a primitive ideal $I_0$ such that $cI = dI_0$.
Hence $I = rI_0$, where $r = d/c$.
QED
Lemma 6
Let $I$ be a primitive ideal of $R$.
Suppose $I = [c, \beta]$, where $c$ is a rational integer.
Then $\beta$ can be written as $\beta = d \pm \omega$, where $d \in \mathbb{Z}, \omega = (D + \sqrt D)/2$.
Proof:
Let $a, b + \omega$ be the canonical basis of $I$(see here).
Since $I \cap \mathbb{Z} = a\mathbb{Z} = c\mathbb{Z}$, $c = \pm a$.
Since $R = [1, \omega]$, $\beta$ can be written as $\beta = d + e\omega, d, e \in \mathbb{Z}$.
Then $N(I) = a = |ce| = a|e|$.
Hence $e = \pm 1$.
QED
Lemma 7
Let $I$ be a primitive ideal of $R$.
Suppose $I = [a, \beta] = [a, \gamma]$, where $a \gt 0$ is a rational integer and both $\{a, \beta\}$ and $\{a, \gamma\}$ are positively oriented.
Then $\beta - \gamma \in a\mathbb{Z}$.
Proof:
By Lemma 6, there exists $d \in \mathbb{Z}$ such that $\beta = d \pm \omega$.
If $\beta = d + \omega, \Delta(-a, \beta) = -a(d + \omega') + a(d + \omega) = a(\omega - \omega') = a\sqrt D$.
If $\beta = d - \omega, \Delta(-a, \beta) = -a(d - \omega') + a(d - \omega) = a(\omega' - \omega) = -a\sqrt D$.
Since $\{a, \beta\}$ is positively oriented, $\beta$ must be $d + \omega$.
Similarly $\gamma = c + \omega$.
Hence $\beta - \gamma = d - c \in I \cap \mathbb{Z} = a\mathbb{Z}$.
QED
Lemma 8
Let $I$ be a fractional ideal of $R$.
Suppose $\{\alpha, \beta\}$ is a positively oriented $\mathbb{Z}$-basis of $I$.
Then $\{\alpha, \beta+n\alpha\}$ is also a positively oriented $\mathbb{Z}$-basis of $I$ for any $n \in \mathbb{Z}$
and $f(\alpha, \beta+n\alpha, s; x, y) = f(\alpha, \beta, s; x, y)^{\sigma^{-sn}}$.
Proof:
Clearly $I = [\alpha, \beta+n\alpha]$.
$\Delta(-\alpha, \beta + n\alpha) = -\alpha(\beta' + n\alpha') + \alpha'(\beta + n\alpha)
= \Delta(\alpha, \beta)$.
Hence $\{\alpha, \beta+n\alpha\}$ is positively oriented.
Suppose $f(\alpha, \beta, s; x, y) = (a, b, c)$.
$a = s(\alpha \alpha')/N(I)$
$b = -(\alpha\beta' + \beta\alpha')/N(I)$
$c = s(\beta\beta')/N(I).$
Suppose $f(\alpha, \beta+n\alpha, s; x, y) = (k, l, m)$.
$k = s(\alpha \alpha')/N(I) = a$
$l = -(\alpha(\beta+ n\alpha)' + (\beta + n\alpha)\alpha')/N(I) = b - 2sna$
$m = s(\beta+n\alpha)(\beta'+n\alpha')/N(I)
= s(\beta\beta' + n(\beta\alpha' + \alpha\beta') + n^2\alpha\alpha')/N(I)
= c - snb + an^2$
Hence $(k, l, m) = (a, b, c)^{\sigma^{-sn}}$.
QED
Proof of Proposition 1
Let $I, J$ be fractional ideals of $R$.
Suppose $I = [\alpha, \beta], J = [\gamma, \delta]$,
where $\alpha, \gamma \in \mathbb{Q}$ and
$\{\alpha, \beta\}$ and$\{\gamma, \delta\}$ are positively oriented bases of $I$ and $J$ respectively.
Suppose $J = rI$ for some $r \in \mathbb{Q}$.
We need to prove that $f(\gamma, \delta, s; x, y) = f(\alpha, \beta, s; x, y)^{\sigma^n}$
for some $n \in \mathbb{Z}$.
By Lemma 5, there exists $q \in \mathbb{Q}$ and a primitive ideal $I_0$ such that $I = qI_0$.
Then $J = rqI_0$.
Hence $I_0 = [(1/q)\alpha, (1/q)\beta] = [(1/rq)\gamma, (1/rq)\delta]$.
Hence, by Lemma 4, we may suppose that $I$ is a primitive ideal and $I = J$.
Since $I = [-\alpha, -\beta]$, we may suppose $\alpha \gt 0$ by Lemma 4.
Similarly we may suppose $\gamma \gt 0$.
Since $I \cap \mathbb{Z} = \alpha \mathbb{Z} = \gamma \mathbb{Z}$, $\alpha = \gamma$.
Hence, by Lemma 7 and Lemma 8, we are done.
QED
Proof of Proposition 2
We first prove that $\phi\circ \psi = 1$.
Let $(a, b, c) \in \mathfrak{F}(D)$.
Let $I = [a, (-b + \sqrt D)/2] = [a, - (D + b)/2 + \omega]$, where $\omega = (D + \sqrt D)/2$.
Note that $I$ is a primitive ideal.
Suppose $a \gt 0$.
Note that $N(I) = a$.
Let $\alpha = a, \beta = (-b + \sqrt D)/2$.
$\{\alpha, \beta\}$ is positively oriented.
Suppose $f(\alpha, \beta, 1; x, y) = (k, l, m)$.
$k = (\alpha \alpha')/N(I) = a^2/a = a$
$l = -(\alpha\beta' + \beta\alpha')/N(I) = ab/a = b$
$m = (\beta\beta')/N(I) = (b^2 - D)/4a = 4ac/4a = c$
Suppose $a \lt 0$.
Note that $I = [-a, (-b + \sqrt D)/2$ and $N(I) = -a$.
Let $\alpha = -a, \beta = (-b + \sqrt D)/2$.
$\{\alpha, \beta\}$ is positively oriented.
Suppose $f(\alpha, \beta, -1; x, y) = (k, l, m)$.
$k = -(\alpha \alpha')/N(I) = a^2/a = a$
$l = -(\alpha\beta' + \beta\alpha')/N(I) = ab/a = b$
$m = -(\beta\beta')/N(I) = (b^2 - D)/4a = 4ac/4a = c$
Hence $\phi\circ \psi = 1$ in either case.
It remains to prove that $\psi\circ \phi = 1$.
Let $I = [a, b + \omega]$ be a primitive ideal of $R$, where $a \gt 0, b \in \mathbb{Z}, \omega = (D + \sqrt D)/2$.
Let $\alpha = a, \beta = b + \omega$.
Let $s \in \mathbb{Z}^\times$.
Let us compute $f(\alpha, \beta, s; x, y)$.
Let $f(\alpha, \beta, s; x, y) = (k, l, m)$.
$k = s(\alpha \alpha')/N(I) = sa$
$l = -(\alpha\beta' + \beta\alpha')/N(I) = -(2b + D)$
$m = s(\beta\beta')/N(I) = s(b^2 + bD + (d^2 - d)/4)/a.$
Hence $\psi\circ\phi([I], s) = ([[sa, b + (D + \sqrt D)/2]], s) = ([I], s)$.
QED


text:
Q: Question regarding the $\min(.,.)$ of an $(\varepsilon, \delta)$ proof.
Show that $f(x) = x^2$ is continuous.

My question is not regarding the continuity of this function nor is it regarding how to show it. It's regarding the way of finding $\delta$ in an $(\varepsilon, \delta)$ proof.
So the so called "scratchwork" goes like this $$|x -y|< \delta \implies |f(x)-f(y)| < \varepsilon$$ for all $\varepsilon, \delta > 0$.
Now $$|x^2-y^2| = |x-y||x+y|$$ and we have control over $|x-y|$ since $|x-y| < \delta$.
So the problematic term is $|x+y|$. This is where my question is centered, now if I assume that $|x-y|<\delta \le 1$ which seems reasonable since I'm interested when $x$ and $y$ are close (I could probably also assume $|x-y| < \pi$, but $1$ seems convinient).
Then $|x-y| < 1 \iff -1<x-y<1 \iff -1+2y<x+y<2y+1$.
So now I have bounded $|x+y| < 2y+1$ IF $|x-y|< 1$.
Continuing the "scratchwork" $$|x^2-y^2| = |x-y||x+y| \\ < \delta (2y+1)$$
which would mean that the natural choice for $\delta =\frac{\varepsilon}{2y+1}$, however I also assumed that $\delta \le 1$ so I need that $\delta = \min(1, \frac{\varepsilon}{2y+1})$.
Now the thing that confuses me is that it seems that $\frac{\varepsilon}{2y+1}$ seems to be fully dependent of the assumption that I made for $\delta \le 1$?
Also what would happen if someone would to choose $\varepsilon = 10$ and say $y = 1$?
Then $$|x^2-1^2| = |x-1||x+1| < \delta(2+1) = 2\delta + \delta =2+1 =3 \ne \varepsilon?$$
This part of taking $\min(.,.)$ confuses me. It seems that it's required since we made the assumption earlier, but I don't quite understand it.


text:
Q: C++ returning MyClass* vs MyClass I have a template class I am creating and I need a method that returns an object of that class and assigns it.  I have a method that takes in 2 objects, creates a new one, and returns it, as well as an overload of the assignment operator to copy members correctly.
I have tried to do this 2 ways (both methods are static).
Method 1:  Works, but isn't this bad practice?
template <class T>
MyClass<T>* MyClass<T>::MyFunction(const MyClass& a, const MyClass& b)
{
    MyClass<T> *newObject= new MyClass<T>(a.member, b.member2);

    //...do stuff to the object

    return newObject;
}

Method 2: Doesn't work, but isn't this a better line of thought?
template <class T>
MyClass<T> MyClass<T>::MyFunction(const MyClass& a, const MyClass& b)
{
    MyClass<T> newObject(a.member, b.member2);

    //...do stuff to the object

    return newObject;
}

My fear with method 1 is that I am creating a new object in the heap and not ever destroying it.  I am assigning all of its members to another instance of MyClass, but what happens to the first instance if I perform the operation a second time?  Does the first "new" object I created on the stack just sit there?
The problem I have with method 2 is that the object is going out of scope before my assignment operation overload is called.  I looked into copy constructors and move constructors.  Unfortunately, I do not see those being called in this situation (probably a major lack of experience here).
For completion, here is the remaining portions of relevant code.
template <class T>
void MyClass<T>::operator = (const MyClass& b)
{
    if (this == &b) { return; }

    DeleteData();
    //just calls the same member removal operation as the destructor
    //to clear everything out to receive new data

    //...simple member copying stuff
}

template<class T>
inline void MyClass<T>::DeleteData()
{
    //call delete on members which need to be deleted manually
}

template <class T>
MyClass<T>::~MyClass()
{
    DeleteData();
}

template <class T>
MyClass<T>::MyClass(const T member, const T member2)
{
    //member initialization operations
}

EXAMPLE USAGE:
MyClass<T> myObj1(member1, member 2);

MyClass<T> myObj2(member1, member 2);

MyClass<T> myObj3 = *(MyClass<T>::MyFunction(myObj1, myObj2));

TL;DR Question:
When using new inside a function to return a class* instead of a class is the created object destroyed when it no longer has any references?
If not, what is the best practice to return an object that is created in a method?
If so, is this method a bad practice?
I apologize if this has been answered before, I am new enough to C++ that my previous researched has not yielded me a satisfactory answer, likely due to me not knowing what I don't know.
IMPLEMENTED SOLUTION:
(I also added a copy constructor.  Without it, this solution still worked for the scope of the question, but there were some items beyond this question's scope that were fixed by one.  Hopefully someone in the future might find this info useful)
//this is a static function of MyClass
template <class T>
std::unique_ptr<MyClass<T>> MyClass<T>::MyFunction(const MyClass& a, const MyClass& b)
{
    std::unique_ptr<MyClass<T>> newObj = std::make_unique<MyClass<T>>(a.member, b.member2);

    //...Be the factory...

    return newObj ;
}

int main()
{
    MyClass<T> myObj1(member1, member 2);

    MyClass<T> myObj2(member1, member 2);

    MyClass<T> myObj3 = *(MyClass<T>::MyFunction(myObj1, myObj2));
}

A:
When using new inside a function to return a class* instead of a class is the created object destroyed when it no longer has any references?

It is not. Anything passed to new must be explicitly deleted, or passed to a container that assumes ownership of it (e.g. unique_ptr).

If so, is this method a bad practice?

It depends, but typically, yes, returning and dealing with raw pointers in general is discouraged as it is prone to memory leaks. The code you have above indeed leaks (as you described).

If not, what is the best practice to return an object that is created in a method?

It depends. If you don't mind copying, or if your object has move semantics defined, you can return a concrete object like in method 2 and hope the compiler performs return value optimization.
If you do mind copying, then consider returning a smart pointer of some sort:
template <class T>
std::unique_ptr<MyClass<T>> MyClass<T>::MyFunction(const MyClass& a, const MyClass& b)
{
  auto newObject = std::unique_ptr<MyClass<T> {new MyClass<T>(a.member, b.member2)};
  //...do stuff to the object
  return newObject;
}

A: How about this:
template <class T>
std::shared_ptr<MyClass<T>> MyClass<T>::MyFunction(const MyClass& a, const MyClass& b)
{
    auto newObject = std::make_shared<MyClass<T>>(MyClass<T>(a.member, b.member2));

    //...do stuff to the object

    return newObject;
}

This is the right way to do it in modern C++, if you ever think about returning pointers. The shared pointer will clean everything for you, and you'll not be passing copies. Assuming you don't want to use a move constructor.
EDIT:
Since people criticized shared_ptr a lot in the comments, because it's killing a fly with a bazooka (and I agree), I offer also the same with unique_ptr. Just be aware that unique_ptr is a unique object that must be moved, not copied.
template <class T>
std::unique_ptr<MyClass<T>> MyClass<T>::MyFunction(const MyClass& a, const MyClass& b)
{
    auto newObject = std::unique_ptr<MyClass<T>>(new MyClass<T>(a.member, b.member2));

    //...do stuff to the object

    return newObject;
}

PS: Notice that I didn't use make_unique (as opposed to make_shared). This is because make_unique is C++14, not C++11.

A: It is quite common, in C++ code, to pass pointers around everywhere. Generally speaking, it is best practice to have the creator of a pointer also destroy it. But it is also acceptable to pass ownership of the pointer to someone else have them take responsibility of maintaining and destroying the pointer.
This is especially true in your case where it appears your method is nothing more than a factory method. It is perfectly okay to think of a factory method as being the same as the constructor. And the one who took responsibility for creating - and has responsibility for destroying - the pointer.
If you are less concerned about best practices and just want it to be memory safe, you can use a std::shared_pointer in #include <memory>. These act kinda like garbage collectors. You use them exactly as you would a normal pointer. But as soon as the last reference to it goes out of scope, it deletes the underlying pointer for you.


text:
Q: TypeError: Cannot read property 'find' of undefined in React-redux while running a test I know there has been a lot of "cannot read property ".find" fo undefined" questions, but I have been looking at them and have not found an answer that I am looking for.
I am running a test of my components.. and this one does not pass.. I was able to make the other tests pass.. but the ".find" returns an undefined error.. been looking at it the whole morning, but cannot find the solution.. can anybody help me?
Here is the commentList.test.js file:
import React from 'react';
import { mount } from 'enzyme';

import { CommentList } from 'components/commentList';
import Root from 'Root';

let wrapped;
beforeEach(() => {
  const initialState = {
    comments: ['Comment 1', 'Comment 2']
  };

  wrapped = mount(
    <Root initialState={initialState}>
      <CommentList />
    </Root>
  );
});

it('creates one LI per comment', () => {
  expect(wrapped.find('li').length).toEqual(2);
});

Here is the commentList.js file
import { connect } from 'react-redux';
import React, { Component } from 'react';

class CommentList extends Component {
  renderComments() {
    return this.props.comments.map(comment  => {
      return
{comment}

    })
  }

  render() {
      return (

            {this.renderComments()}

    )
}
}

const mapStateToProps = (state) => {
  return {
    comments: state.comments
  };
}

export default connect(mapStateToProps)(CommentList);

and finally the Root.js file:
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from 'reducers';

export default ({ children, initialState = {} }) => {
  return (
    <Provider store={createStore(reducers, initialState)}>
      {children}
    </Provider>
  )
}

Here is what can bee seen in my terminal
enter image description here

A: This may have come a little bit late.. I was not able to give my answer at that time because I have not the required reputation to give an answer.. lol.. but for those who have been following this question and wondering where i did the fix.. here it is:
replace this line of code
import { CommentList } from 'components/commentList';

with this:
import CommentList from 'components/commentList';

Hope this will be helpful for someone out there.

A: try looking for hostnodes:
it('creates one LI per comment', () => {
  expect(wrapped.hostNodes().find('li').length).toEqual(2);
});

https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/hostNodes.md