text:
Q: What is the best way to sum arrays using ECMASCRIPT 6 Generator/Functions Is there a better way instead of adding values of arrays up using a generator function as closure?
var sumArrays = function(){
  var sum = 0;
  return function*(){
    while(true){
      var array = yield sum;
      if(array.__proto__.constructor === Array){
        sum += array.reduce(function(val,val2){ return val+val2; });
      }
      else sum=0;
    }
  };
};

var gen = sumArrays();
// is this step required to make a generator or could it be done at least differently to spare yourself from doing this step?
gen = gen();

// sum some values of arrays up
console.log('sum: ',gen.next()); // Object { value=0,  done=false}
console.log('sum: ',gen.next([1,2,3,4])); // Object { value=10,  done=false}
console.log('sum: ',gen.next([6,7])); // Object { value=23,  done=false}

// reset values
console.log('sum: ',gen.next(false)); // Object { value=0,  done=false}
console.log('sum: ',gen.next([5])); // Object { value=5,  done=false}

A: This doesn't seem to be a problem generators are supposed to solve, so I would not use a generator here.
Directly using reduce (ES5) seems to be more appropriate:
let sum = [1,2,3,4].reduce((sum, x) => sum + x);

As a function:
function sum(arr) {
  return arr.reduce((sum, x) => sum + x);
}

If you really want to sum multiple arrays across multiple function calls, then return a normal function:
function getArraySummation() {
  let total = 0;
  let reducer = (sum, x) => sum + x;
  return arr => total + arr.reduce(reducer);
}

let sum = getArraySummation();
console.log('sum:', sum([1,2,3])); // sum: 6
console.log('sum:', sum([4,5,6])); // sum: 15

Keep it simple.

A: Here is use of for/of loop and arrow function,
const sumArray = myArray => {
    let sum = 0;
    for(const value of myArray)
    sum+= value;
    return sum;
}
const myArray = [1, 2, 5];
console.log(sumArray(myArray));


text:
Q: Not receiving Amazon SES Bounce Notifications I have configured postfix on my server to deliver only @gmail.com mails to Amazon SES:
gmail.com          smtp:email-smtp.eu-west-1.amazonaws.com:25
*                  :

Also, I configured in the Amazon SES console to receive Bounces and Complains on mail using Amazon SNS. The problem is that I don't receive a bounce if I send a mail to a non-existent gmail address.
If sending a mail from mail.google.com to the address dsadaerwer.lala-band-sucks.justin-is-a-beaver@gmail.com I receive:
Delivery to the following recipient failed permanently:
 dsadaerwer.lala-band-sucks.justin-is-a-beaver@gmail.com

But If sending from a PHP script to the same address, postfix says:
E4E1A9F9CE: to=<dsadaerwer.lala-band-sucks.justin-is-a-beaver@gmail.com>, relay=email-smtp.eu-west-1.amazonaws.com[54.72.42.170]:25, delay=21, delays=0.02/0.04/11/10, dsn=2.0.0, status=sent (250 Ok 00000146d86bcc13-9fa1ac16-b1cd-476e-8398-31f406d47961-000000)

So Amazon SES accepts the mail but I don't get notified of the failure. What can be wrong?
Note. When sending to valid emails, everything works as expected.
Also, when sending a test mail from AWS SES console to bounce@simulator.amazonses.com, I am immediately notified via email, but sending to the same email from a PHP script via email-smtp.eu-west-1.amazonaws.com does not results in an email notification.

A: I was facing the same problem. In my case, I'm using the PHPMailer library (https://github.com/PHPMailer/PHPMailer/) and I solved it by specifying a Sender of the message.
/**
 * The Sender email (Return-Path) of the message.
 * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
 * @type string
 */
public $Sender = '';

I setted it to the same address as the $From and I now receive the bounces in the expected address.
So this is my working code:
$this->mail = new PHPMailer();
$this->mail->CharSet = 'utf-8';
$this->mail->From = $from_address;
$this->mail->Sender = $from_address;
$this->mail->FromName = $from_name;
$this->mail->Subject = $subject;
$this->mail->Body    = $body;
$this->mail->AltBody = $altBody;
$this->mail->addAddress($to_address, $to_name);
$this->mail->send()

If you use the setFrom method in PHPMailer, it will also set automatically the Sender to the same address.
/**
 * Set the From and FromName properties.
 * @param string $address
 * @param string $name
 * @param boolean $auto Whether to also set the Sender address, defaults to true
 * @throws phpmailerException
 * @return boolean
 */
public function setFrom($address, $name = '', $auto = true)

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP in binary mode? Is it possible to convert PHP to binary mode (compile) and run it in all standard web servers?

A: There are various PHP accelerators that cache the compiled byte code the interpreter produces. Not sure if they will run without the source still on the server though - I've never tried!

A: One Facebook developer is working on a compiled form called "Hyper-PHP", and it's not even clear if that will be an open system once complete, but no solution exists yet.

A: PHP Will never be a compiled Language. It will stay as an Interpreted Language.
@Matchu Facebook is just Promoting their site, so this is just an Promotion action of Facebook

A: There is a number of tools that will convert your php source to bytecode and allow you to protect your source code. Some of the more popular ones are Zend Guard by Zend and Ion Cube encoder. You will still need their respective loaders installed on the target server for them to function.


text:
Q: Sort NSArray according to NSDictionary Let's say if I have an NSArray of NSObjects:
{
  person: {
    'id':'A',
    'firstName':'Bob'
  }
  person: {
    'id':'B',
    'firstName':'Chris'
  }
  person: {
    'id':'C',
    'firstName':'Sarah'
  }
}

and an NSDictionary of key-values (NSDates)
{
  'A':'13:45:12 Tuesday',
  'B':'01:45:12 Monday',
  'C':'05:45:12 Friday'
}

and I want to sort the nsarray according to the the nsdictionary according to date (in this case, the order should be [personB, personA, personC]), what would be a good way to do this?

A: You can use sortedArrayUsingComparator -
 NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    Person *personA=(Person *)a;
    Person *personB=(Person *)b:
    NSDate *first = [keyDictionary objectForKey:personA.id];
    NSDate *second = [keyDictionary objectForKey:personB.id];
    return [first compare:second];
}];


text:
Q: Changing mysql column using Java I have an assignment where I have to update a column from my mysql by using Java. I've already established connection etc...
I have a table with 4 columns : ID, ProductName, Price and Quantity
I want to be able to change the quantity for only ONE product by button click on a Java application. Example:
ID|ProductName|Price|Quantity
_____________________________
1 |  Water    | 20  |30

2 |  Soda     | 25  |30

3 |  Juice    | 25  |30

On a button click I want to ONLY change the quantity of Soda to 29, and if I press the button again it shall go down to 28, while Water and Juice will remain with 30. How do I do this in Java using JButton and selecting this single product (and not all the quantities)..?
EDIT : After the two clicks it should look like this :
ID|ProductName|Price|Quantity
_____________________________
1 |  Water    | 20  |30

2 |  Soda     | 25  |28

3 |  Juice    | 25  |30

** The requested code:
   public void updateMethod(){
    Connection conn = null;
    try {
        String userName = "root";
        String passWord = "";
        String dataBase = "database";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/"+dataBase, userName, passWord);
        if (!conn.isClosed())
        {
            Statement s = conn.createStatement ( );
            s.executeQuery ("SELECT * FROM `database`.Drinks");
            String query = "UPDATE Drinks SET quantity = quantity - 1 WHERE productName = 'Soda' and quantity > 0";
            conn.setAutoCommit(false);
            PreparedStatement pstmt = conn.prepareStatement(query);
   //This one did not work.. pstmt.setString(1, "Soda");
            int result = pstmt.executeUpdate();
            conn.commit();
            ResultSet rs = s.getResultSet ( );
            while (rs.next()) // loop through rows of result set
            {
                int DrinkID = rs.getInt(1);
                String productName = rs.getString(2);
                int price = rs.getInt(3);
                int quantity = rs.getInt(4);

                System.out.println ("ID: " + DrinkID + "\t" + "Product: " + productName + " " + "Price: " + price + " " + "Quantity: " + quantity);
            }
            rs.close(); // close result set
            s.close(); // close statement
        }
    }
    catch (Exception e)
    {
        // If we don't have a error, close the connection!
        System.err.println("Exception: " + e.getMessage());

    }
    finally
    {
        try
        {
            if (conn != null)
            {
                conn.close();
            }
        }
        catch (SQLException e)
        {

        }
    }

A: You would execute your sql based on the product name:
UPDATE product_table
SET Quantity = Quantity - 1
WHERE ProductName = 'Soda'
and Quantity > 0

This will decrement the value of the quantity by 1.
Heres a guide on how to execute sql queries in java - http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
EDIT: Adding code to perform the update query from above:
String query = "UPDATE product_table SET Quantity = Quantity - 1 WHERE ProductName = ? and Quantity > 0";

conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, "Soda");

int result = pstmt.executeUpdate();
conn.commit();

EDIT: Adding full sample code
public Connection getConnection() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    String userName = "root";
    String passWord = "";
    String dataBase = "database";
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    return DriverManager.getConnection("jdbc:mysql://localhost:3306/" + dataBase, userName, passWord);
}

public void print() {

    Connection conn = null;

    try {
        conn = getConnection();

        PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM `database`.Drinks");

        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            int DrinkID = rs.getInt(1);
            String productName = rs.getString(2);
            int price = rs.getInt(3);
            int quantity = rs.getInt(4);

            System.out.println("ID: " + DrinkID + "\t" + "Product: " + productName + " " + "Price: " + price + " " + "Quantity: " + quantity);

        }
        rs.close();
        pstmt.close();

    } catch (Exception e) {
        // If we don't have a error, close the connection!
        System.err.println("Exception: " + e.getMessage());

    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {

        }
    }
}

public void update() {
    Connection conn = null;

    try {
        conn = getConnection();

        String query = "UPDATE Drinks SET quantity = quantity - 1 WHERE productName = ? and quantity > 0";

        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, "Soda");

        pstmt.executeUpdate();

    } catch (Exception e) {
        // If we don't have a error, close the connection!
        System.err.println("Exception: " + e.getMessage());

    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {

        }
    }

}


text:
Q: Add a row to a matrix I have a matrix A like
1 2 3 4 5
6 7 8 9 0

and I want to expand it with a row of ones to get
1 1 1 1 1
1 2 3 4 5
6 7 8 9 0

I create the row of ones with
col_size = size(A, 2);
ones_row = ones(1, col_size);

How can I add my ones_row to the matrix?

A: Once you have A and ones_row you do:
[ones_row; A]

This returns the following.
1 1 1 1 1
1 2 3 4 5
6 7 8 9 0

A: I would probably do it as suggested in the previous answer, however in some cases (when the matrix sizes get very big), a more memory friendly solution would be to preallocate a matrix of the correct size and use indexing to put the existing values in the correct place:
A = [ 1 2 3 4 5; 6 7 8 9 0 ];
B = ones(size(A) + [1,0]); % Create an array of ones that is one row longer
B(2:end,:) = A;            % Replace the elements of B with elements from A

The reason why I say this is more memory friendly is because when we create a row of ones we need to allocate memory for a vector, and then when we concatenate we need to allocate memory again for the result of the concatenation. When we use indexing, there's no need to allocate an intermediate vector. It isn't really important in this example, but can be quite significant for larger matrices or operations performed thousands of times.

There's also a useful function in the Image Processing Toolbox - padarray:
A = [ 1 2 3 4 5; 6 7 8 9 0 ];
B = padarray(A,[1 0],1,'pre');

A: I can give a solution that can worked for any matrix.
suppose your matrix is A, A is m*n
n = size(A,2)

out = [ones(1,n);A]

This solution works for any matrix.


text:
Q: Same response being triggered for Different events I get the same response from the MessageBox when I click either on Help->Help... or File->Exit. I don't understand, where I am going wrong. (I am very new to wxPython)
I have this code snippet from wxPython:
class NewSheet(wx.Frame):
'''Anatomy of Sheet Frame'''
def __init__(self, parent, id, title,Nrows,Ncols,SheetName):
    wx.Frame.__init__(self, parent, -1, title, size = (550, 500))

    box = wx.BoxSizer(wx.VERTICAL)
    menuBar = wx.MenuBar()
    menu1 = wx.Menu()
    menuBar.Append(menu1, '&File')
    menu1.Append(1,"&Exit")
    self.Bind(wx.EVT_MENU, self.OnExit,id = 2)

    menuBar.Append(menu8, '&Help')
    menu8.Append(1, "&Help...")
    self.Bind(wx.EVT_MENU, self.OnHelp, id=1)
    self.SetMenuBar(menuBar)
    self.SetSizer(box)

    notebook = wx.Notebook(self, -1, style=wx.RIGHT)
    sheet1 = MySheet(notebook,Nrows,Ncols)
    notebook.AddPage(sheet1, str(SheetName))
    sheet1.SetFocus()
    box.Add(notebook, 1, wx.EXPAND)

    self.Centre()
    self.Show(True)

def OnExit(self,event):
    self.Close(True)  #NOT WORKING!

    self.Exit() #NOT WORKING EITHER!

def OnHelp(self,event):
    wx.MessageBox("HTML Based Help System coming soon","Help System",wx.OK | wx.ICON_INFORMATION, self)

I get the same response from the MessageBox when I click either on Help->Help... or File->Exit. I don't understand, where I am going wrong. Can you please advise?

A: You need to specify different id values in menu?.Append and use the same ids in the Binds.  Try:
    em = menu1.Append(-1, "&Exit")
    self.Bind(wx.EVT_MENU, self.OnExit, id=em)

    menuBar.Append(menu8, '&Help')
    hm = menu8.Append(-1, "&Help...")
    self.Bind(wx.EVT_MENU, self.OnHelp, id=hm)

This tells wx to pick and return new ids and then uses them.  Actually after a little bit you should find that for these two have predefined IDs wx.ID_EXIT & wx.ID_HELP see here for more so it is better to use:
    menu1.Append(wx.ID_EXIT, "&Exit")
    self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)

    menuBar.Append(menu8, '&Help')
    menu8.Append(wx.ID_HELP, "&Help...")
    self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)

As you will find that on some platforms it helps by doing tricks like standard translations.


text:
Q: Prettier.js confic how to convert any js file in any subfolder I'm trying to run prettier for any js file inside the following folder:
prettier --config .prettierrc --write ./resources/assets/js/**

But it only converts the js files located into js folder. I would like to convert any js file in any subfolder inside /assets/js/...
Can someone help me?

A: prettier --config .prettierrc --write ./resources/assets/**/*.js

May be it helps you.

A: I ended up using the following:
prettier --write "./resources/assets/js/**{.js,}"
And then I created an ignore file, that specifies any folders or file types that need to be ignored.
.prettierignore
resources/assets/js/vendor/
*.min.js
*.DS_Store


text:
Q: DateFormatter returning nil for valid Date in format "dd/MM/yyyy" I'm using a DateFormatter to convert a String to Date, but when the String is "25/10/1986" or "25/10/1987" the result is nil.
Already removed the locale and timeZone, but the result is still nil.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "pt_BR")
formatter.timeZone = TimeZone(abbreviation: "BRT")
formatter.dateFormat = "dd/MM/yyyy"

print(formatter.date(from: "25/10/1986"))


text:
Q: How to find SQL Server queries that took a lot of time? I have application that is up more than 3 days.
I can see in logs that there was a moment when application executed some SQL query and this took a lot of time, probably because of some db locks.
I heard that there is a query for such situations. So I need to be able to ask all queries that took, for example, more than 30 minutes. Is it possible?

A: give this a try:
SELECT TOP 10
    total_worker_time/execution_count AS Avg_CPU_Time
        ,execution_count
        ,total_elapsed_time/execution_count as AVG_Run_Time
        ,(SELECT
              SUBSTRING(text,statement_start_offset/2,(CASE
                                                           WHEN statement_end_offset = -1 THEN LEN(CONVERT(nvarchar(max), text)) * 2
                                                           ELSE statement_end_offset
                                                       END -statement_start_offset)/2
                       ) FROM sys.dm_exec_sql_text(sql_handle)
         ) AS query_text
FROM sys.dm_exec_query_stats
ORDER BY AVG_Run_Time DESC

A: use SQL Server Profiler.

A: You can use the SQL Server Profiler (a separate tool which you can choose to install together with SQL Server itself).
It has a wizard you can use to set up a trace for long-running queries.

A: You can achieve it by querying Dynamic Management Views. SQL Server 2005 Performance Dashboard Reports will also reveal (actually they are based on dmv) lots of useful performance related information.
Keep in mind that when you restart sql server the above information is lost.
In sql server 2008 you can use Data Collector

A: In SQL Server Management Studio, connect to your server. Then, right-click the server name in the Object Explorer, and click "Activity Monitor". "Recent Expensive Queries" will tell you much of what you'd like to know. Try double-clicking on one of the queries while you're there.


text:
Q: Nivo Slider having problem in Chrome & Safari I'm using Nivo slider on this page. The problem is that the slider collapses in chrome and safari. What I need to change?
Secondly, I want to change the title and links on each new images. How will I accomplish this? Will I use "afterChange" method? I've to load images dynamically using some server-side language (PHP). Please help!

A: #nivo-slider is supposed to have a height and width specified, you're applying dimentions to its parent container, #nivo-slider-wrapper.
If you have more than one question the best practice is to post them separatedly.

A: Hey. I can't help with the afterChange method, but I can help with the collapsing issues you are having.
Try putting the following in your styles.css:
#slider {
     min-height: 400px; //or whatever height you require.
}

And then alter your html for displaying the nivoSlider to:
<div id="slider" class="nivoSlider">
     //other nivo stuff here.
</div>

Should solve the collapsing problem. Good luck :)


text:
Q: data.table. Fast way to count number of changes within every column I would like to know how many times each variable changes within each group and later add the result for all groups.
I've found this way:
mi[,lapply(.SD, function(x) sum(x != shift(x),
  na.rm=T) ), by = ID][,-1][,lapply(.SD,sum, na.rm=T)]

It works, it produces the proper result but it's really slow in my large datatable.
I would like to do both operations inside the same lapply (or something faster and more compact), but the first one is done by group, the second isn't.
It could be written in an easier way (maybe not always)
mi[,lapply(.SD, function(x) sum(x != shift(x),
    na.rm=T) )] [,-1]-mi[,length(unique(ID))]+1

But it's still slow and needs a lot of memory.
Any other idea?
I've also tried with diffs instead of shift, but it becomes more difficult.
Here you have a dummy example:
mi <- data.table(ID=rep(1:3,each=4) , year=rep(1:4, times=3),
   VREP=rep(1:3,each=4) , VDI=rep(1:4, times=3), RAN=sample(12))
mi <- rbind(mi, data.table(4,1,1,1,0), use.names=F)

Big example for benchmark
mi <- as.data.table(matrix(sample(0:100,10000000,
 replace=T), nrow=100000, ncol=100))
mi[,ID := rep(1:1000,each=100)]

My problem is that the true dataset is much bigger, it's in the limit of memory size, then I've configured R to be able to use more memory using the pagefile, and it makes many operations slow.
I know I could do it splitting the file and joining it again, but sometimes that makes things more difficult or some operations are not splittable.

A: Your second method produces incorrect results, so is not a fair comparison point. Here's an optimized version of alexis_laz's suggestion instead:
setorder(mi, ID)
setDT(Map(`!=`, mi, shift(mi)))[,
  lapply(lapply(.SD, `&`, !ID), sum, na.rm = T), .SDcols = -"ID"]
#   year VREP VDI RAN
#1:    9    0   9   9

On your bigger sample:
setorder(mi, ID)
microbenchmark(method1(), alexis_laz(), eddi(), times = 5)
#Unit: milliseconds
#         expr       min        lq      mean    median        uq      max neval
#    method1() 7336.1830 7510.9543 7932.0476 8150.3197 8207.2181 8455.563     5
# alexis_laz() 1350.0338 1492.3793 1509.0790 1492.5426 1577.3318 1633.107     5
#       eddi()  400.3999  475.6908  494.5805  504.6163  524.2077  567.988     5


text:
Q: Some accepted answers appear to have been unaccepted but still have the checkmark Some accepted answers do not have a valid accept-vote in Votes table, even though the question owner still exists. Stack Overflow alone has over 2000 such answers. A recent example is Sub query for column name:

*

*The timeline says that the answer was unaccepted on July 3, 2014.

*However, it still has the green checkmark

*However, the checkmark does not show acceptance time on hover.

Is the answer accepted or not? Is it some kind of Schrödinger's acceptance?

A: Looks like the serial voting reversal process got too greedy and removed the raw accept vote along with "real" upvotes:

Most likely a bug when there are invalid upvotes on an accepted answer.
This gets more serious for this user:


text:
Q: SQL Server 2005 - writing an insert and update trigger for validation I'm pretty bad at SQL, so I need someone to check my trigger query and tell me if it solves the problem and how acceptable it is. The requirements are a bit convoluted, so please bear with me.
Suppose I have a table declared like this:
CREATE TABLE Documents
(
    id int identity primary key,
    number1 nvarchar(32),
    date1 datetime,
    number2 nvarchar(32),
    date2 datetime
);

For this table, the following constraints must be observed:

*

*At least one of the number-date pairs should be filled (both the number and the date field not null).

*If both number1 and date1 are not null, a record is uniquely identified by this pair. There cannot be two records with the same number1 and date1 if both fields are not null.

*If either number1 or date1 is null, a record is uniquely identified by the number2-date2 pair.

Yes, there is a problem of poor normalization, but I cannot do anything about that.
As far as I know, I cannot write unique indexes on the number-date pairs that check whether some of the values are null in SQL Server 2005. Thus, I tried validating the constraints with a trigger.
One last requirement - the trigger should have no inserts of its own, only validation checks. Here's what I came up with:
CREATE TRIGGER validate_requisite_uniqueness
ON [Documents]
FOR INSERT, UPDATE
AS
BEGIN
    DECLARE @NUMBER1 NVARCHAR (32)
    DECLARE @DATE1 DATETIME
    DECLARE @NUMBER2 NVARCHAR (32)
    DECLARE @DATE2 DATETIME
    DECLARE @DATETEXT VARCHAR(10)
    DECLARE inserted_cursor CURSOR FAST_FORWARD FOR SELECT number1, date1, number2, date2 FROM Inserted

    IF NOT EXISTS (SELECT * FROM INSERTED)
        RETURN

    OPEN inserted_cursor
    FETCH NEXT FROM inserted_cursor into @NUMBER1, @DATE1, @NUMBER2, @DATE2

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@NUMBER1 IS NULL OR @DATE1 IS NULL)
        BEGIN
            IF (@NUMBER2 IS NULL OR @DATE2 IS NULL)
            BEGIN
                ROLLBACK TRANSACTION
                RAISERROR ('Either the first or the second number-date pair should be filled.', 10, 1)## Heading ##
            END
        END

        IF (@NUMBER1 IS NOT NULL AND @DATE1 IS NOT NULL)
        BEGIN
            IF ((SELECT COUNT(*) FROM Documents WHERE number1 = @NUMBER1 AND date1 = @DATE1) > 1)
            BEGIN
                ROLLBACK TRANSACTION

                SET @DATETEXT = CONVERT(VARCHAR(10), @DATE1, 104)
                RAISERROR ('A document with the number1 ''%s'' and date1 ''%s'' already exists.', 10, 1, @NUMBER1, @DATETEXT)
            END
        END
        ELSE IF (@NUMBER2 IS NOT NULL AND @DATE2 IS NOT NULL) /*the DATE2 check is redundant*/
        BEGIN
            IF ((SELECT COUNT(*) FROM Documents WHERE number2 = @NUMBER2 AND date2 = @DATE2) > 1)
            BEGIN
                ROLLBACK TRANSACTION

                SET @DATETEXT = CONVERT(VARCHAR(10), @DATE2, 104)
                RAISERROR ('A document with the number2 ''%s'' and date2 ''%s'' already exists.', 10, 1, @NUMBER2, @DATETEXT)
            END
        END

        FETCH NEXT FROM inserted_cursor
    END

    CLOSE inserted_cursor
    DEALLOCATE inserted_cursor
END

Please tell me how well-written and efficient this solution is.
A couple of questions I can come up with:

*

*Will this trigger validate correctly against existing rows and newly inserted/updated rows in case of bulk modifications? It should, because the modifications are already applied to the table in the scope of this transaction, right?

*Are the constraint violations handled correctly? Meaning, was I right to use the rollback transaction and raiserror pair?

*Is the "IF NOT EXISTS (SELECT * FROM INSERTED) RETURN" statement used correctly?

*Is the use of COUNT to check the constraints acceptable, or should I use some other way of checking the uniqueness of number-date pairs?

*Can this solution be optimized in terms of execution speed? Should I add non-unique indexes on both number-date pairs?

Thanks.
EDIT:
A solution using a check constraint and an indexed view, based on Damien_The_Unbeliever's answer:
CREATE TABLE dbo.Documents
(
    id int identity primary key,
    number1 nvarchar(32),
    date1 datetime,
    number2 nvarchar(32),
    date2 datetime,
    constraint CK_Documents_AtLestOneNotNull CHECK (
        (number1 is not null and date1 is not null) or
        (number2 is not null and date2 is not null)
    )
);
go
create view dbo.UniqueDocuments
with schemabinding
as
    select
        CASE WHEN (number1 is not null and date1 is not null)
            THEN CAST(1 AS BIT)
            ELSE CAST(0 AS BIT)
        END as first_pair_filled,
        CASE WHEN (number1 is not null and date1 is not null)
            THEN number1
            ELSE number2
        END as number,
        CASE WHEN (number1 is not null and date1 is not null)
            THEN date1
            ELSE date2
        END as [date]
    from
        dbo.Documents
go
create unique clustered index IX_UniqueDocuments on dbo.UniqueDocuments(first_pair_filled,number,[date])
go

A: I would avoid the trigger, and use a check constraint and an indexed view:
CREATE TABLE dbo.Documents
(
    id int identity primary key,
    number1 nvarchar(32),
    date1 datetime,
    number2 nvarchar(32),
    date2 datetime,
    constraint CK_Documents_AtLestOneNotNull CHECK (
        (number1 is not null and date1 is not null) or
        (number2 is not null and date2 is not null)
    )
);
go
create view dbo.UniqueDocuments
with schemabinding
as
    select
        COALESCE(number1,number2) as number,
        COALESCE(date1,date2) as [date]
    from
        dbo.Documents
go
create unique clustered index IX_UniqueDocuments on dbo.UniqueDocuments(number,[date])
go

Which has the advantage that, although there is some "trigger-like" behaviour because of the indexed view, it's well-tested code that's already been deeply integrated into SQL Server.

A: I would use this logic instead (I didn't type it all as it takes ages), and definitely use SELECT 1 FROM ... in the IF EXISTS() statement as it helps performance. Also remove the cursors like marc_s said.
CREATE TRIGGER trg_validate_requisite_uniqueness
ON dbo.[Documents]
AFTER INSERT, UPDATE
AS

 DECLARE @Number1 NVARCHAR(100) = (SELECT TOP 1 number1 FROM dbo.Documents ORDER BY Id DESC)
 DECLARE @Date1 DATETIME        = (SELECT TOP 1 date1 FROM dbo.Documents ORDER BY Id DESC)
 DECLARE @Number2 NVARCHAR(100) = (SELECT TOP 1 number2 FROM dbo.Documents ORDER BY Id DESC)
 DECLARE @Date2 DATETIME        = (SELECT TOP 1 date2 FROM dbo.Documents ORDER BY Id DESC)
 DECLARE @DateText NVARCHAR(100)

IF EXISTS (SELECT 1 FROM dbo.Documents AS D
INNER JOIN INSERTED AS I ON D.id = I.id WHERE I.Number1 IS NULL AND I.number2 IS  NULL)
BEGIN
ROLLBACK TRANSACTION
RAISERROR ('Either the first or the second number pair should be filled.', 10, 1)
END

ELSE IF EXISTS (SELECT 1 FROM dbo.Documents AS D
       INNER JOIN INSERTED AS I ON D.id = I.id WHERE I.Date1 IS NULL AND I.Date2 IS NULL)
BEGIN
  ROLLBACK TRANSACTION
  RAISERROR ('Either the first or the second date pair should be filled.', 10, 1)
END

ELSE IF EXISTS (SELECT 1 FROM dbo.Documents AS D
           GROUP BY D.number1, D.date1 HAVING COUNT(*) >1
          )

BEGIN
  ROLLBACK TRANSACTION
  SET @DateText = (SELECT CONVERT(VARCHAR(10), @Date1, 104))
  RAISERROR ('Cannot have duplicate values', 10, 1, @Number1, @DateText )
END


text:
Q: Alamofire Swift HTTPPost login and JSON response Can someone help me with a brief tutorial about the logging in to the web service by passing about 4 parameters and receiving response in JSON using Alamofire and Swift?
Thanks.

A: Your question is very general. Alomofire has great docs on how to do this. I don't think I can write a better tutorial here. Nevertheless here is some example code.
I'm getting a filtered selection of companies from a REST-API :
    let connection = DefaultConnection.connection
    let companySelection = "/companies"

    // configure parameters for our query
    var parameters = ["columns":"id,name,short_name,active,language_code,remarks,created_at,updated_at"]

    // filter(s)

    parameters["filter"] = "[\"deleted_at\", \"filters/null\"]"

    // limit (used for debugging purposes)
    //parameters["limit"] = "25"

    //sort
    parameters["sort"] = "name"

    // load the whole shebang
    connection.loadData(companySelection,  parameters:parameters, importHandler: handleImportedData)

where DefaultConnection is a singleton (so I can reuse that code for all my queries) :
 func loadData (dataPath : String, parameters:Dictionary <String,String>, importHandler: ((data:JSON) -> Void)?)  {

        let urlPath = baseURL +  dataPath

        let start = NSDate()
        Alamofire.request(.GET, urlPath, parameters: parameters, headers: ["X-API-KEY": apiKey, "Content-type application":"json", "Accept application" : "json"]).responseJSON() {
            (req,res, data, error) in

            if error != nil {
   ....


text:
Q: Netty: Event Loop Group and custom events Can i use netty event group to execute custom task? I require same functionality as of socket channel, that is i want to register my object with event-loop and  execute it on a particular thread again and again?

A: Sure you can do this. It's as easy as obtaining the EventLoop of the Channel and then use any of the provided ScheduledExecutorService methods that it implements. That said you need to ensure you not do any blocking calls in these scheduled tasks as otherwise you will block the EventLoop and no I/O can happen on the EventLoop until the task completes (which will affect all Channels that use this EventLoop).
For example this is how you would execute a task on the EventLoop:
EventLoop loop = channel.eventLoop();
loop.execute(() -> {
    // Do something.
});


text:
Q: NodeJS create CSV write directly to Google Storage I've tried to tackle this a few different ways but am coming up dry.  There are many csv converters, but they all seem to write to a local file (which is not allowed on the app engine).  I would like to write the file directly to google storage bucket.
Very simply...
app.get('/', (req, res) => {
  var writer = csvWriter()
  writer.pipe(fs.createWriteStream('out.csv')); // bucket.upload('out.csv);
  writer.write({hello: "world", foo: "bar", baz: "taco"})
  writer.end();
});`

A: Nailed it...
const blob = bucket.file('file.csv');
const blobStream = blob.createWriteStream({
  resumable: false,
});

app.get('/', (req, res) => {
  var writer = csvWriter();
  writer.pipe(blobStream);
  writer.write({hello: "world", foo: "bar", baz: "taco"})
  writer.end();
  res.end();
});


text:
Q: How to loop over JSON array in a JSON object I've been trying to learn R and I have a JSON file full of single line JSON objects, and each object has an array of account data. What I'm trying to do is parse each row, then get the JSON array out of the parsed JSON object, pull the account type and the amount. But my problem is that I don't know how best to pull just those two attributes out.
I've tried using the dplyr package to pull "accountHistory" out of each of my JSON lines, but I get a console error. When I try:
select(JsonAcctData, "accountHistory.type", "accountHistory.amount")

What happens is, my code only returns the last account for each row's type and amount.
Right now my code is writing to a csv file and I can see all the data I need, but I just want to remove the ext
library("rjson")
library("dplyr")

parseJsonData <- function (sourceFile, outputFile)
{
  #Get all total lines in the source file provided
  totalLines <- readLines(sourceFile)

  #Clean up old output file
  if(file.exists(outputFile)){
    file.remove(outputFile)
  }

  #Loop over each line in the sourceFile,
  #parse the JSON and append to DataFrame
  JsonAcctData <- NULL
  for(i in 1:length(totalLines)){
    jsonValue <- fromJSON(totalLines[[i]])
    frame <- data.frame(jsonValue)
    JsonAcctData <- rbind(JsonAcctData, frame)
  }

  #Try to get filtered data
  filteredColumns <-
    select(JsonAcctData, "accountHistory.type", "accountHistory.amount")
  print(filteredColumns)

  #Write the DataFrame to the output file in CSV format
  write.csv(JsonAcctData, file = outputFile)

}
Test JSON File Data:
{"name":"Test1", "accountHistory":[{"amount":"107.62","date":"2012-02-
  02T06:00:00.000Z","business":"CompanyA","name":"Home Loan Account
  6220","type":"payment","account":"11111111"},
  {"amount":"650.88","date":"2012-02-
  02T06:00:00.000Z","business":"CompanyF","name":"Checking Account
  9001","type":"payment","account":"123123123"},
  {"amount":"878.63","date":"2012-02-
  02T06:00:00.000Z","business":"CompanyG","name":"Money Market Account
  8743","type":"deposit","account":"123123123"}]}
  {"name":"Test2", "accountHistory":[{"amount":"199.29","date":"2012-02-
  02T06:00:00.000Z","business":"CompanyB","name":"Savings Account
  3580","type":"invoice","account":"12312312"},
  {"amount":"841.48","date":"2012-02-
  02T06:00:00.000Z","business":"Company","name":"Home Loan Account
  5988","type":"payment","account":"123123123"},
  {"amount":"116.55","date":"2012-02-
  02T06:00:00.000Z","business":"Company","name":"Auto Loan Account
  1794","type":"withdrawal","account":"12312313"}]}

what I would expect is to get a csv that has just the account types and the amounts held in each account.

A: Here is a way using regex (in base R)
# read json
json <- readLines('test.json', warn = FALSE)
# extract with regex
amount <- grep('\"amount\":\"\\d+\\.\\d+\"', json, value = TRUE)
amount <- as.numeric(gsub('.*amount\":\"(\\d+\\.+\\d+)\".*', '\\1', amount, perl = TRUE))
type   <- grep('\"type\":\"\\w+\"', json, value = TRUE)
type   <- gsub('.*type\":\"(\\w+)\".*', '\\1', type, perl = TRUE)
# output
data.frame(type, amount)
#         type amount
# 1    payment 107.62
# 2    payment 650.88
# 3    deposit 878.63
# 4    invoice 199.29
# 5    payment 841.48
# 6 withdrawal 116.55


text:
Q: How does CHAR(n) represent its data in binary? I am currently reading Robin Nixon's Learning PHP, MySQL, & JavaScript book. In particular the chapters on databases using MySQL. Here is the topic that I am struggling to thoroughly understand.
"The year field, however, has more-predictable values, so instead of VARCHAR we use the more efficient CHAR(4) data type. The parameter of 4 allows for 4 bytes of data, supporting all years from –999 to 9999; a byte comprises 8 bits and can have the values 00000000 through 11111111, which are 0 to 255 in decimal."
In the example above, CHAR(4) is set to store 4 characters that will represent a four digit year entry. Why is it that -999 to 9999 are the only options. How is it represented in binary that it is limited to just those values? My original thought process was that since 4 bytes is 32 bits and if all 32 bits are set to 1, 2^32 is about 4 Billion unsigned and about 2 Billion signed, that would be the amount that could be stored.
I appreciate any explanations.

A: The book you quoted seems to be suggesting using CHAR to store year values, even though this does not store in binary, it stores digit characters. You are correct that four bytes could store a much greater range if you use the bytes to store a binary value of the number.
It's surprising that the book is concerned about the single extra byte needed to encode the length for a VARCHAR, then it uses CHAR to store numeric year values in such an inefficient way.
It's an example of "penny wise, pound foolish."
Take this book (or any book) with a grain of salt. Remember that tech books are written by people, and they can make mistakes.

A: First all, for limited year values use YEAR (yyyy, 1901 to 2155, or 0000): 1 byte.

*

*INT(4) can be stored in 2 bytes and would be best (as it has no year 2156 problem). Actually 4 bytes; SMALL INT takes 2 bytes, as @BillKarwin mentions.

*CHAR(4) in general (single byte charset) is limited to 4 bytes, and but CHAR is padded with spaces, like '712 ' and cannot immediatedly be used with arithmetic.

*VARCHAR(4) needs more than CHAR(4) and allows also smaller strings '712'.


text:
Q: C# {String was not recognized as a valid Datetime} Well I"m trying to read a csv file in my directory but it has a DateTime value. The thing is I'm trying to read the value but shows me this error:

String was not recognized as a valid Datetime

this is the library from where im calling the value DateTime:
public class Main
{
    string names;
    string addresses;
    string phones;
    DateTime birthdates;

    string resultado = string.Empty;
    RegisterSalesTableAdapter myRegisterSales = new RegisterSalesTableAdapter();

    public string InsertSalesTable(string Name, string Address, string Phone, DateTime Birthdate)
    {

        names = Name;
        addresses = Address;
        phones = Phone;
        birthdates = Birthdate;

        myRegisterSales.Insert(Name, Address, Phone, Birthdate);
        return resultado;
    }

    public string Nombres { get => names; set => names = value; }
    public string Direcciones { get => addresses; set => addresses = value; }
    public string Telefonos { get => phones; set => phones = value; }
    public DateTime Cumpleanos { get => birthdates; set => birthdates = value; }

    public DataTable GetSalesTable()
    {
        return myRegisterSales.GetData();
    }
}

And this is where it gives me the error:
static List<Main> list;
static void Main(string[] args)
{
    list = new List<Main>();

    // Get the data from path.
    string sampleCSV = @"C:\Borrado\PRUEBA.csv";

    string[,] values = LoadCSV(sampleCSV);
    int num_rows = values.GetUpperBound(0) + 1;

    //Read the data and add to List
    for (int r = 1; r < num_rows; r++)
    {

        //name age mail company
        Main main = new Main();

        main.InsertSalesTable(values[r, 0], values[r, 1], values[r, 2], DateTime.Parse(values[r, 3]));
    }

    //read data from list
    foreach (var item in list)
    {
        Console.WriteLine(item.Nombres + "\t" + item.Direcciones + "\t" + item.Telefonos + "\t" + item.Cumpleanos + "\t");
    }
    Console.ReadLine();

}

A: Try to do this
string dateString = values[r, 3];
string format = "dd/MM/yyyy HH:mm:ss.ffffff"; /*use the correct format*/
date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

main.InsertSalesTable(values[r, 0], values[r, 1], values[r, 2],
DateTime.Parse(date));


text:
Q: update mysql table based on checked checkboxes I have a table with a column called extension_list which has comma separated values in
200,201,202,203,204 etc
If i have a loop that selects these from the database:
$stmt = $pbx01_pdoconn->prepare("SELECT * from client where parent_client_id = :parent_client_id ");
$stmt->execute(array(':parent_client_id' => $customerid));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $result) {
    $stmt = $pbx01_pdoconn->prepare("SELECT * from extension where client_id = :client_id ");
    $stmt->execute(array(':client_id' => $result["id"]));
    $extension = $stmt->fetch();
    if($extension["type"] == 'term') {
        echo '

    '.$result["name"].' ('.$extension["number"].')

';
    }
}

how can i show checkboxes next to each value and if the $extension["number"] value is in the extension_list column make the check box ticked.
also, when the checkbox is ticked and submit button is pressed, it will update the extension_list column and add that value into the comma separated list

A: You should normalize your table.
Then you can have HTML input checkboxes such as this:
<input type="checkbox" name="extensions[]" value="<?php echo $extension['id'] ?>">
Then, in your script, you can handle them such as this:
$extensions = isset($_POST['extensions'])  && is_array($_POST['extensions']) ? $_POST['extensions'] : array();
foreach($extensions as $extension) {
  // use $extension here
}

This should help point you in the right direction.

A: <input name="extenstionbox[]" id="extenstionbox" type="checkbox" value="<? echo $extension['id']; ?>" <?php if(in_array($extension['id'], $extensions)) echo 'checked="checked"';?>>


text:
Q: Scroll view issue iphone I need to scroll the views horizontally using page controller. Using scroll view i am trying to scroll the views. The issue is the views does not fit to scroll view, while scrolling horizontally it moves up and down. I have already disabled shows vertical indicator, bounces vertically etc. Still it bounces up and down. The code which i use follows:
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++)
{
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIView *subview = [[UIView alloc] initWithFrame:frame];
    subview.backgroundColor = [colors objectAtIndex:i];
    [subview sizeToFit];
    [self.scrollView addSubview:subview];
}

self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = colors.count;

A: Try this:
float subviewWidth = 320;
float subviewHeight = 200;

NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
    float x = subviewWidth * i;  //width of your one view

    UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(x, 0, subviewWidth, subviewHeight)];//last two parameters is for your view's width and height
    subview.backgroundColor = [colors objectAtIndex:i];
    [self.scrollView addSubview:subview];
}

self.scrollView.frame = CGRectMake (0,50,subviewWidth,subviewHeight);
self.scrollView.contentSize = CGSizeMake(subviewWidth * colors.count, subviewHeight);
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = colors.count;


text:
Q: How to get XmlSerializer to ignore all members of a certain type? I want to deserialize XML into the following class:
public partial class Delivery
{
    public System.Nullable<System.DateTime> sentDate { get; set; }
    public System.Nullable<System.DateTime> receivedDate { get; set; }
    public System.Nullable<System.DateTime> responseDueDate { get; set; }
}

However, the dates in the XML are not in an XmlSerializer friendly format. Based on answers to mulitple questions, I added this class:
public partial class DateSafeDelivery : Delivery
{
    [XmlElement("sentDate")]
    public string sentDateString
    {
        internal get { return sentDate.HasValue ? XmlConvert.ToString(sentDate.Value) : null; }
        set { sentDate = DateTime.Parse(value); }
    }
    [XmlElement("receivedDate")]
    public string receivedDateString
    {
        internal get { return receivedDate.HasValue ? XmlConvert.ToString(receivedDate.Value) : null; }
        set { receivedDate = DateTime.Parse(value); }
    }
    [XmlElement("responseDueDate")]
    public string responseDueDateString
    {
        internal get { return responseDueDate.HasValue ? XmlConvert.ToString(responseDueDate.Value) : null; }
        set { responseDueDate = DateTime.Parse(value); }
    }
}

I then configure my overrides:
private static XmlAttributeOverrides GetOverrides()
{
    var overrides = new XmlAttributeOverrides();
    var attributes = new XmlAttributes();
    attributes.XmlElements.Add(new XmlElementAttribute(typeof(DateSafeDelivery)));
    overrides.Add(typeof(MyParent), "Delivery", attributes);
    var ignore = new XmlAttributes { XmlIgnore = true };
    overrides.Add(typeof(DateTime?), ignore);
    return overrides;
}

This results in the following expection:
Message=The string '2010-06-12T00:00:00 -05:00' is not a valid AllXsd value.
Source=System.Xml.ReaderWriter
StackTrace:
    at System.Xml.Schema.XsdDateTime..ctor(String text, XsdDateTimeFlags kinds)
    at System.Xml.XmlConvert.ToDateTime(String s, XmlDateTimeSerializationMode dateTimeOption)
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDeserializedAudit.Read1_NullableOfDateTime(Boolean checkType)
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDeserializedAudit.Read15_DateSafeDelivery(Boolean isNullable, Boolean checkType)
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDeserializedAudit.Read16_MyParent(Boolean isNullable, Boolean checkType)

So DateSafeDelivery is being used, but the XmlIgnore for the dates is being, well, ignored.
It will work, if I switch:
    overrides.Add(typeof(DateTime?), ignore);

with:
    new Dictionary<string, Type>()
    {
        { "sentDate", typeof(Delivery) },
        { "receivedDate", typeof(Delivery) },
        { "responseDueDate", typeof(Delivery) },
    }
        .ToList()
        .ForEach(t1 => overrides.Add(t1.Value, t1.Key, ignore));

And that's fine for one class and three properties. But I have 14 classes with a total of three dozen date properties. I know I have to add overrides for the 14 classes, but is there a way to get the serializer to ignore all DateTime properties?
I thought XmlAttributeOverrides.Add Method (Type, XmlAttributes) would do it. But it isn't working. Why? What is this method for? What does it do?

A: XmlAttributeOverrides.Add(Type, XmlAttributes) is designed to add an XML override attribute to the type itself, rather than to all properties returning values of that type.  E.g. if you wanted to add an [XmlRoot("OverrideName")] attribute to DateSafeDelivery, you could do something like:
overrides.Add(typeof(DateSafeDelivery),
    new XmlAttributes { XmlRoot = new XmlRootAttribute("OverrideName") });

There is no dynamic override attribute to ignore all properties returning a given type because there is no static XML serialization attribute that can suppress serialization of all properties of a given type.   The following does not even compile, because [XmlIgnore] can only be applied to a property or field:
[XmlIgnore] public class IgnoreAllInstancesOfMe { } // Fails to compile.

(As to why Microsoft did not implement support for [XmlIgnore] applied to a type - you would need to ask them.)
Thus you will need to introduce an extension method like the following:
public static partial class XmlAttributeOverridesExtensions
{
    public static XmlAttributeOverrides IgnorePropertiesOfType(this XmlAttributeOverrides overrides, Type declaringType, Type propertyType)
    {
        return overrides.IgnorePropertiesOfType(declaringType, propertyType, new HashSet<Type>());
    }

    public static XmlAttributeOverrides IgnorePropertiesOfType(this XmlAttributeOverrides overrides, Type declaringType, Type propertyType, HashSet<Type> completedTypes)
    {
        if (overrides == null || declaringType == null || propertyType == null || completedTypes == null)
            throw new ArgumentNullException();
        XmlAttributes attributes = null;
        for (; declaringType != null && declaringType != typeof(object); declaringType = declaringType.BaseType)
        {
            // Avoid duplicate overrides.
            if (!completedTypes.Add(declaringType))
                break;
            foreach (var property in declaringType.GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
            {
                if (property.PropertyType == propertyType || Nullable.GetUnderlyingType(property.PropertyType) == propertyType)
                {
                    attributes = attributes ?? new XmlAttributes { XmlIgnore = true };
                    overrides.Add(declaringType, property.Name, attributes);
                }
            }
        }
        return overrides;
    }
}

And do:
    private static XmlAttributeOverrides GetOverrides()
    {
        var overrides = new XmlAttributeOverrides();

        var attributes = new XmlAttributes();
        attributes.XmlElements.Add(new XmlElementAttribute(typeof(DateSafeDelivery)));
        overrides.Add(typeof(MyParent), "Delivery", attributes);

        // Ignore all DateTime properties in DateSafeDelivery
        var completed = new HashSet<Type>();
        overrides.IgnorePropertiesOfType(typeof(DateSafeDelivery), typeof(DateTime), completed);
        // Add the other 14 types as required

        return overrides;
    }

Please also note that the DateString properties on DateSafeDelivery must have public get and set methods, e.g.:
public partial class DateSafeDelivery : Delivery
{
    [XmlElement("sentDate")]
    public string sentDateString
    {
        get { return sentDate.HasValue ? XmlConvert.ToString(sentDate.Value, XmlDateTimeSerializationMode.Utc) : null; }
        set { sentDate = DateTime.Parse(value); }
    }

XmlSerializer cannot serialize a property that is not fully public.
Incidentally, please note you must statically cache any XmlSerializer constructed with overrides to avoid a severe memory leak, as explained in this answer.


text:
Q: Django Queryset with filtering on reverse foreign key with Django-Filter I have a model that is related by foreign key with another model.
How i filter that foreign model in template with django filter...
Example.
class Author(Model):
name = CharField(max_lenght=100)

class Book(Model):
title = CharField(max_lenght=200)
author = ForeignKey(Author, SET_DEFAULT, related_name='books')

how in template django.
i filter that books in authorView.
Example:
AuthorView.html
{% extends 'base.html'}
{% block main %}
    My name is {{ object.name }}
    My books is:
{# how do i put book filter here or something? #}
    {% for book in object.books.all %}
        {{ book.name }}
    {% endfor %}
{% endblock %}

in my project i use django-filter and django-tables2 to list and filter a some model like author. But i need filter a sub model related.
Ty for support.


text:
Q: How to apply color palette to point shapefile in GEE, based on value of a property In google earth engine, I have a point shapefile as an asset. Lat / Lon, and a property (say elevation). I'd like to find a way to control the edge color, the fill color, and the size. Easy to do with the code below. However, I am really struggling to find a way to color the fill based on the elevation value. I'm familiar with how to do this for an 'image' (using palette and vis params), but I have run into a wall in terms of how to do with this with a featurecollection made up of a point shapefile.
Code is below. The csodata is a shapefile with lat, lon, month, day, year, and elevation. The simple code just plots blue symbols with black outlines
var table2 = ee.FeatureCollection("users/dfh/ms_shapefiles/csodata");

var vis=table2.style({
  color: '000000',
  width: 10,
  fillColor: '0000FF',
  pointSize: 30,
  pointShape: 'circle'
})

Map.addLayer(vis,null,'test')

A: Map over the collection and assign a 'style' dictionary to each feature, individually, with the styles you want to override.
var colors = ee.List(["red", "green", "blue"])
table3 = table2.map(function(f) {
    var index = f.getNumber('elevation').divide(100).clamp(0, 2)
    var color = colors.get(index)
    return f.set('style', {fillColor: color})
})
Map.addLayer(table2.style({..., styleProperty: 'style'}))


text:
Q: Proper usage of user_likes permission of Facebook App Here I have an app, with logic as follow:

*

*Check user whether he liked the page or not (login via user_likes permission and with Graph API call /me/likes/{facebook_page_id}/

*If yes, proceed to obtain a coupon

*If no, ask the user to like the page

Facebook App Review team said the 1st step violates Facebook App's rules:

Gate access to your app, or some content within your app based on whether or not someone has liked a page.

But with FBSDKLikeButton or FBSDKLikeControl, there is no callback / delegate to know whether I can proceed to Step 2.
My question is: Is there any workarounds?

I'm working on iOS and Android App. Here are the codes of iOS related part:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                            initWithGraphPath:@"/me/likes/19292868552/"
                            parameters:@{@"fields": @"id"}
                            HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                    id result,
                                    NSError *error) {
  if(error) {
    // notify there is error
  } else {
    NSArray *likedID = [[result valueForKey:@"data"] valueForKey:@"id"];
    if(likedID != nil && likedID.count > 0) {
      // Liked, get coupon
    } else {
      // Not liked yet, show like button
      likeButton = [[FBSDKLikeButton alloc] init];
      likeButton.objectID = [NSString stringWithFormat:@"https://www.facebook.com/FacebookDevelopers?rand=%d", rand()];
      likeButton.objectType = FBSDKLikeObjectTypePage;
      [likeButton addTarget:self action:@selector(likeFBclick:) forControlEvents:UIControlEventTouchUpInside];
      [self.view addSubview:likeButton];
    }
  }
}];

where likeFBclick: is just forwarding users to obtain coupon.


text:
Q: Rails 4 - config.ssl_options is not working I have enabled the config.force_ssl=true, but i am trying to do a redirect to some domain with the help of config.ssl_options = {redirect: { host: "www.google.com", port: 8080 }}.
But, config.ssl_options is not working.
Ref:

*

*Rails SSL
Any help would be appreciated.
Thanks

A: The code you referenced is from a commit that doesn't belong to Rails 4.x, here's the version of the same file in Rails 4.2.5.1
You'll have to use this syntax:
config.ssl_options = { host: "www.google.com", port: 8080 }


text:
Q: How to make selenium to scrape pages after the page gets loaded I'm using scrapy to crawl all the links and selenium to scrape all the pages. Selenium scraped most of the pages but left a few pages as the page took time to load.
I tried with timeout() , but didn't seem to work, then I tried with execute_script

driver.execute_script("return document.readyState=="complete";")

this also didn't seem to work, then I tried with expected_conditions

WebDriverWait.until(expected_conditions.execute_script("return
document.readyState=="complete";"))

but didn't seem to work
I m using firefox browser, phantomJs for Headless
Tried using Chrome driver so installed using brew cask install chromedriver but I'm facing this error

raise WebDriverException("Can not connect to the Service %s" %
self.path) selenium.common.exceptions.WebDriverException: Message: Can
not connect to the Service chromedriver

so back to phantomjs.
Thank you!

A: Make use of sleep function which will help you in delaying the running of code in that time webpage will be loaded

A: I had this problem before. I used a while loop with try and except in it. Loop will keep trying to finish the work you have completed. If the page is not loaded then it will go into except which will just pass. But when it enters the try block and executes successful then at the end of the try block you can use a break to cone out of the loop. This worked 100% of the time for me.

A: raise WebDriverException("Can not connect to the Service %s" % self.path) selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver

This is raised because your program is unable to connect to the service through given chromedriver.exe, this can happen due to version mismatch or non availability of executable file.
You can resolve it as follows:

*

*Check the version of chrome browser you're using on your system, you
can check it in chrome settings > About chrome. Then download the
chromedriver accordingly here :
https://chromedriver.chromium.org/downloads

*You can store it anywhere, but it's better if you keep it in the same
directory as your code. Unzip it and copy it to the respective directory and you're good to go with chromedriver.

*Uncomment this driver = webdriver.Chrome() or use driver = webdriver.Chrome(executable_path=r'your path here') if it is not in same directory as your program.


text:
Q: Cascading dropdowns using MVC Razor Entity Framework and stored procedures I am new to MVC and Razor and have looked at so many examples and tutorials of this but have not been able to get it working. It seems so simple but I think the fact that I am trying to use stored procedures complicates everything.
I am trying to create a few simple cascading dropdowns in MVC using stored procedures and entity framework.
My entity consists of the following stored procedures:

exec prcGetMakes
exec prcGetModels 'BMW'
exec prcGetVariants '1 SERIES 5-DOOR'

I created a view model class called VehicleViewModel:
public class VehicleViewModel
{
    [Display(Name = "Manufacturer")]
    public string BrandName { get; set; }
    public string BrandID { get; set; }

    [Display(Name = "Model")]
    public string ModelName { get; set; }
    public string ModelID { get; set; }

    [Display(Name = "Variant")]
    public string VariantName { get; set; }

    public IEnumerable<SelectListItem> Manufacturer { get; set; }
    public IEnumerable<SelectListItem> Model { get; set; }
    public IEnumerable<SelectListItem> Variant { get; set; }
}

I'm using the default controller class called HomeController.cs:
public class HomeController : Controller
{
    VehicleInfoEntities db = new VehicleInfoEntities();

    public ActionResult Index()
    {
        var app = new VehicleViewModel
        {
            Manufacturer = GetMakes()
        };

        return View(app);
    }

    private IEnumerable<SelectListItem> GetMakes()
    {
        var list = new VehicleViewModel();
        IEnumerable<SelectListItem> manufacturer = from s in db.prcGetMakes(null)
                                            select new SelectListItem
                                            {
                                                Selected = s.ToString() == "Active",
                                                Text = s.BrandName,
                                                Value = s.BrandID
                                            };
        return manufacturer;

    }

    private IEnumerable<SelectListItem> GetModels(string brandName)
    {
        var list = new VehicleViewModel();
        IEnumerable<SelectListItem> models = from s in db.prcGetModels(brandName)
                                            select new SelectListItem
                                            {
                                                Selected = s.ToString() == "Active",
                                                Text = s.ModelName,
                                                Value = s.ModelID
                                            };
        return models;

    }

    private IEnumerable<SelectListItem> GetVariants(string modelName)
    {
        var list = new VehicleViewModel();
        IEnumerable<SelectListItem> variants = from s in db.prcGetVariants(modelName)
                                             select new SelectListItem
                                             {
                                                 Selected = s.ToString() == "Active",
                                                 Text = s.VariantName,
                                                 Value = s.VariantName
                                             };
        return variants;

    }
}

This is my view
@model WebApplication12.Models.VehicleViewModel

@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("Index", "Sample", FormMethod.Post))
{
@Html.AntiForgeryToken()

@Html.ValidationSummary()

    @Html.Label("Manufacturer:", new { @class = "col-md-2 control-label" })

        @Html.DropDownList("Manufacturer", ViewData["Manufacturer"] as SelectList, new { @class = "form-control" })

}

The desired outcome is

I would just like to know now how to use JQuery to make the cascading DropDowns work and filter on selection of each DropDown.

A: Compared to thick client apps, web cascading drop down lists are convoluted and complex, but that's web programming! Keep in mind that javascript doesn't care about your MVC stuff at all. You just need a web method (something that responds to web URL) that takes a parameter and returns the correct list in the correct format. Whatever method it uses internally (EF stored procedure, hard coded list, PHP reading a text file) doesn't make any difference
To do what you want, you need to add an "event handler" to your drop down which calls some javascript which calls your method to look up the correct list, then populates the target drop down with that list.
I'll put some sample code here but

*

*there is a degree of 'wiring up' required (using the correct names of things)

*I'm going to make some assumptions

*I learnt this from the web and some syntax may be incorrect
So first add an onchange event handler to your drop down so that when somehing is changed it fires some javascript code
@Html.DropDownList("Manufacturer",
                   ViewData["Manufacturer"] as SelectList,
                   htmlAttributes:
                         new { @class = "form-control" ,
                               @onchange = "refreshModelFromManufacturer()"
                             }
                   )

When the drop down value is changed it will call javascript function refreshModelFromManufacturer()
Here is the javascript function. Hopefully you know how to add this. It requires you to also have a drop down with name "Model" (which you don't have in your view yet so add it):
function refreshModelFromManufacturer()() {
    // get references to the source and target drop downs html controls
    // These are jquery searches to find the drop down controls

    // find a control with id=Manufacturer
    src = $("#Manufacturer");

    // find a control with id=Model (you need to add this to your view)
    tgt = $("#Model");

    // clear drop down
    tgt.empty();

    // Get new model dataset via ajax
    // based on manufacturer
    // The url parameter points at your web method
    $.ajax({
        type: 'GET',
        url: 'Home/GetModels',
        dataType: 'json',
        data: { brandName: src.val() },
        // success is called when dataset returns
        success: function (p) {
                // Populate with each returned member
                $.each(p, function (i, pr) {
                    tgt.append(
                        '<option value="' + pr.Value + '">' +
                        pr.Text + '</option>'
                        );
                })
            }
        });
    }

This is the most likely place that things will go wrong. Javascript is unforgiving, case sensitive, and has waaaaay too many brackets that are easily messed up. Make sure you are using source control so you can roll back because it can be impossible to work out a misplaced bracket sometimes because the code fails somewhere deep inside the jquery library, giving you no clue
The last thing is that your web method needs to be of type Json so that the ajax call works
public JsonResult GetModels(string brandName)
{
    var list = db.prcGetModels(brandName)

    return Json(new SelectList(list, "your id column","your label column"));
}

The only other difference in my code is that actually define a drop down just like this:
@Html.DropDownList("Customer_ID", null, htmlAttributes: new { @class = "form-
control", @onchange = "refreshProjectFromClient()" })

I think that if your ViewBag name is the same as your drop down, then you don't need to explicitly define the viewbag (my second parameter is null)
For debugging (because this won't work first time), make sure you know how to use the F12 debugger to debug javascript as well as observe internal web calls (the network tab). For example when you run this, you should see calls to the Home/GetModels method in the network tab


text:
Q: Convert String to Clickable Link I am creating a webpage that displays user history. Written in Java, I have pojo that contains properties that my jsf retrieves via bean injection. The problem: one of the values is a url. Currently, the String is a long url but isn't clickable. Also to note, these values (Strings) are in an ArrayList. How can I assign a String value that contains a url and output a clickable url?
userHistoryDetails.completeData bean may look like this (sudo):
[{status=complete,userid=123,reportUrl=http://www.reporturl.com}]

example of table created in my jsf file. Where  #{cRow[cColModel.value]} creates a row in the table with its respective header value.
<ace:dataTable id="completedTable"
    value="#{userHistoryDetails.completeData}" var="cRow"
    paginator="true" rows="50" paginatorPosition="both"
    emptyMessage="NO RECORDS TO DISPLAY">
    <c:forEach items="#{userHistoryDetails.userHistoryHeaders}"
        var="cColModel">
        <ace:column headerText="#{cColModel.headerText}">
                #{cRow[cColModel.value]}
        </ace:column>
                </c:forEach>
</ace:dataTable>

Please let me know if this does not make sense. It is kind of hard to explain. Thanks in advance!
EDIT I have tried changing String to:
    [{status=complete,userid=123,reportUrl=View report}]

but still no luck. I feel like I am on the right track, just missing something.

A:
How can I assign a String value that contains a url and output a clickable url?

Two ways:
#{bean.url}

<h:outputLink value="#{bean.url}">#{bean.url}</h:outputLink>

userHistoryDetails.completeData bean may look like this (sudo):
[{status=complete,userid=123,reportUrl=http://www.reporturl.com}]

example of table created in my jsf file. Where #{cRow[cColModel.value]} creates a row in the table with its respective header value.

So .. If #{cColModel.value} equals to reportUrl you want to generate a link? That'll have to look something like this:
<ui:fragment rendered="#{cColModel.value eq 'reportUrl'}">
    #{cRow[cColModel.value]}
</ui:fragment>
<ui:fragment rendered="#{cColModel.value ne 'reportUrl'}">
    #{cRow[cColModel.value]}
</ui:fragment>


text:
Q: Objective function in proximal policy optimization In PPO's objective function second term introduces squared error loss of the value function neural network. Is that term is essentially the squared advantage values, right?

A: No, that's the TD error for training V. You can separate the two losses and nothing changes, because the networks do not share parameters. In practice, the policy is trained on the first term of the equation, while V is trained on the second.


text:
Q: Add a contact to a linked exchange table I am trying to build an access process to add contacts to an outlook folder.  I have linked the folder and can add, update and delete records.  But not all of the fields are showing up correctly in outlook.  Namely the address field.
I have added a test contact and added an address, went back into access and mimicked the data perfectly, but no address shows up in outlook.
Is there something that needs to be done in order for addresses to show up in outlook?
Here is my data:
First   Last    Title   Company Department  Office  Post Office Box Address City    State   Zip/Postal Code Country/Region  Phone
John    Test        superduper              500 west T  Test City   MI  99999   United States of America    1 800 555 5555
Bill    Test        Awesomedawesome             600 East G  Test City   MI  99999   United States of America    1 800 666 6666

The first record is outlook added, the lower one is access added.
Here is the view I get in outlook:

A: I ended up going the code route:
Dim olCI As Outlook.ContactItem
Set olCI = mf.Items.Add(olContactItem)
    With olCI
        .FullName = Trim(rs!Name)
        .Title = Trim(rs!Salutation)
        .JobTitle = Trim(rs!Title)
        .Email1Address = Trim(rs!Email)
        .CompanyName = Trim(rs!AccountName)
        .BusinessAddressStreet = Trim(rs!MailingStreet)
        .BusinessAddressCity = Trim(rs!MailingCity)
        .BusinessAddressPostalCode = Trim(rs!MailingZipCode)
        .BusinessAddressCountry = Trim(rs!MailingCountry)
        .BusinessFaxNumber = Trim(rs!Fax)
        .BusinessTelephoneNumber = Trim(rs!Phone)
        .OtherTelephoneNumber = Trim(rs!OtherPhone)
        .BusinessHomePage = ""
        .MobileTelephoneNumber = Trim(rs!MobilePhone)
        .Birthday = IIf(IsNull(rs!Birthdate), 0, rs!Birthdate)
        .Department = rs!Department
        .Save
    End With


text:
Q: Order of execution of function calls within a line - undefined? p.77 K&R C says the output of the following program is undefined, but current version of Xcode gives no warning. Is it still undefined in current standard? What about in C++? Bonus points for similar program in Java and C#.
#include <stdio.h>

int my_m()
{
    static int n = 0;
    static int m[] = { 42, 57 };
    return n++ % 2 == 0 ? m[0] : m[1];
}
int main()
{
    printf("%d" , my_m() - my_m());

    return 0;
}

A: The result isn't actually undefined, just unspecified.
The difference is that undefined behavior means anything can happen, including behavior that seems to be entirely unrelated to anything in the program at all. The classic line is that it "makes demons fly out of your nose."
Unspecified means that you have no way of knowing which call of my_m will be evaluated first and which will be evaluated second, but it will be1 one invocation and then the other. One call will start and run to completion then the other call will start and run to completion--the two won't be interleaved or anything like that. The only thing that's unpredictable is the order in which the two calls are made (and yes, under current C and C++ standards, the order is still 100% unpredictable).
In both C# and Java the order of evaluation is specified as left to right.

1. Or at least it'll act as if it did. Both C and C++ follow what's usually called the "as if rule" that allows a compiler to do things differently as long as it does so in a way that maintains the specified externally visible behavior.

A: A compiler won't warn you about all undefined programs. In the following line:
printf("%d" , my_m() - my_m());

the order of the calls my_m() is unspecified. The compiler might decide to call either the first one or the second one first. Since the function returns 42 on the first call and 57 on the second call the result is either 42 - 57 or 57 - 42.
Edit: I missed the difference between undefined and unspecified, see Jerry Coffins answer for details about that.


text:
Q: What will be the movement of the block?
Assume that there is no friction occurring.
In case (A)-:
*If the pulley is moved by X units in forward direction(which is shown through dotted lines) then clearly we can say that string L1 and L2 will also moves X units to keep them attached to it.Now,if the pulley moves in forward direction as shown then we can analyse that the string will move from L2 to L1 i.e the block will move in forward direction.
So from the above paragraph we can say that 2x units of string will move from L2 to L1 to keep the string around the pulley tight,or in other words we can say that due to X units of displacement of the pulley the block displaced 2X units,right.
In case (B)-:
Now,in case (B) if the pulley displaces is in the direction shown,then it is clear that the block will move along the inclined in upward direction.So my question here is,what is the relation between the block's movement and the pulley's movement,if the pulley is displaced by X units in the forward direction.


text:
Q: Do objects only exist in the dispatch queue that created them? Consider this code:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

 dispatch_async(queue, ^{

UIGraphicsBeginImageContext(self.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();

//perform some drawing into this context

UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

dispatch_sync(dispatch_get_main_queue(), ^{
    self.imageView.image=viewImage;
    });
});

Why is it necessary to get the main queue at the end before updating an object with the results of the routine? Why not just update within the queue queue ?

A: Anything that touches the GUI has to be on the main thread. (The main dispatch queue is guaranteed to be running on the main thread.) That part of Cocoa/Cocoa Touch is not thread-safe.
See "Threads and Your User Interface" in the Threading programming guide:

...it is recommended that you receive user-related events and initiate interface updates from your application's main thread. [...] Some frameworks, such as Cocoa, generally require this behavior...

The image view is part of the GUI, so you need to set its properties only on the main thread.
If you were updating an array, for example, it would not be required that you do it on the main thread (you'd just have to watch out for reads or other writes happening simulataneously).


text:
Q: java.lang.NoClassDefFoundError: roboguice.activity.SherlockAccountAuthenticatorActivity with ActiveAndroid in android 5.0 I am getting this error -
java.lang.NoClassDefFoundError: roboguice.activity.SherlockAccountAuthenticatorActivity
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:308)
at com.activeandroid.ModelInfo.scanForModelClasses(ModelInfo.java:187)
at com.activeandroid.ModelInfo.scanForModel(ModelInfo.java:152)
at com.activeandroid.ModelInfo.<init>(ModelInfo.java:63)
at com.activeandroid.Cache.initialize(Cache.java:66)
at com.activeandroid.ActiveAndroid.initialize(ActiveAndroid.java:44)
at com.activeandroid.ActiveAndroid.initialize(ActiveAndroid.java:34)
at com.activeandroid.ActiveAndroid.initialize(ActiveAndroid.java:30)
at com.activeandroid.app.Application.onCreate(Application.java:25)
at com.dvor.androidapp.Application.TabletApplication.onCreate(TabletApplication.java:22)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1011)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4518)
at android.app.ActivityThread.access$1500(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1339)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

In Android version 5.0, I am using RoboGuice and ActiveAndroid and the application class is extending com.activeandroid.app.Application, is there any other way how to fix this issue except extending the normal Application class and adding the model classes manually(this way it each model class needs to be added), as explained(https://github.com/pardom/ActiveAndroid/issues/291) :
  Configuration.Builder configurationBuilder = new Configuration.Builder(this);
    configurationBuilder.addModelClass(Test.class);
    configurationBuilder.addModelClass(Test2.class);
    ActiveAndroid.initialize(configurationBuilder.create());

A: The workaround for this problem, was adding the Roboguice jar files, and ActiveAndroid jar files to lib folder, and replacing Gradle "compile" command with -
compile files('libs/ActiveAndroid.jar')
compile files('libs/simple.facebook-2.2.jar')
compile files('libs/guice-3.0-no_aop.jar')
compile files('libs/javax.inject-1.jar')
compile files('libs/roboguice-3.0b-experimental.jar')


text:
Q: Ember.js routing, can't access controller I have started small ember application, I have view:
Cellar.SearchTextField = Ember.TextField.extend({
    insertNewline: function(){
      Cellar.SearchController.loadResults();
    }
});

and controller:
Cellar.SearchController = Ember.ArrayController.create({
  content: [],
  searchQuery: "",
  loadResults: function() {
    var me = this;
    SC.get('/tracks', { q: me.get('searchQuery') }, function(tracks) {
      me.set('content', []);
      $(tracks).each(function(index, value){
        var track = Cellar.Track.create({
          id: value.id,
          artwork: value.artwork_url,
          download_url: value.download_url,
          duration: value.duration,
          stream_url: value.stream_url
        })
        me.pushObject(track);
      });
    });
  }
});

and an application template:

{{#linkTo "index"}}Cellar{{/linkTo}}

      <form class="navbar-search">
        {{view Cellar.SearchTextField placeholder="search" valueBinding="Cellar.SearchController.searchQuery"}}
      </form>

{{outlet}}

my problem is when I am on the route http://localhost:3000/ my searchController doesn't work, but it's all okay when URL is http://localhost:3000/#/, why?

A: The Ember default is to use the hash based routes. You can change that by reopening the Router and switching to HTML5 location api.
App.Router.reopen({
  location: 'history'
});

Edit: I think there is a version mismatch here. This appears to be an older version of ember.
In the current version, you do not create a controller instead manually. You provide a controller and extend either ArrayController or ObjectController.
You won't have a reference to an App.SearchController anymore. You can either send events or call a method on the controller via the {{action}} helper.
There are quite a few differences, I'd suggest giving the Ember Getting Started Guide a quick read to refresh up on the changes.


text:
Q: Copy Merged Cells and the whole row in excel-macro Good Morning Programming Gurus! I am beginner at excel-macro's or vba.
I have a problem in copying the excel merged cells also in getting its whole row.
So this is my Code in Getting the First Column of the first sheet and transfer it to another sheet.
Sub cmdCopy()

Dim lastrow As Long, erow As Long, xNumber As Integer

lastrow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row
For i = 5 To lastrow

Sheet2.Cells(i, 1).Copy
erow = Sheet4.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Sheet2.Paste Destination:=Sheet4.Cells(erow, 1)

Next i

Application.CutCopyMode = False
Range("A1").Select

End Sub

Also I wanted to Sort it by the Column Date but i dont know how to perform it. this is the actual photo of excel file.
[This is where the rows will get]

[And this one is the destination of the rows]

I know someone out there has a capability to do this. Please Guys, Help me!

A: Try this: This should copy a cell you have in the first range (sheet2) and paste it at the end of your column in the next sheet (sheet4), then go back to the next cell in Sheet2 and put it after the cell that you just pasted into in Sheet4, so the loop will go though every cell you want in Sheet2 and paste it into Sheet4.
Sub cmdCopy()
    Dim lastrow As Long, erow As Long, xNumber As Integer
    lastrow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row
    For i = 5 To lastrow
        erow = Sheet4.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
        Sheet2.Cells(i, 1).Copy Sheet4.Cells(erow, 1)
        'the copy method can have a destination typed right after it, so Excel
        'takes Sheet4.Cells(row, 1) as the implied destination range.
    Next i
    Application.CutCopyMode = False
    Range("A1").Select
End Sub


text:
Q: Attempt to present MPMoviePlayerViewController while a presentation is in progress I get warning described in title and I've found that this is as a result of calling viewDidLayoutSubviews multiple times.
- (void) viewDidLayoutSubviews
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"wq" ofType:@"mp4"]];
self.playerController = [[MPMoviePlayerViewController alloc]initWithContentURL:url];

[self presentMoviePlayerViewControllerAnimated:self.playerController];
[self.playerController.moviePlayer prepareToPlay];

self.playerController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
self.playerController.moviePlayer.controlStyle = MPMovieControlStyleNone;
self.playerController.moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
self.playerController.moviePlayer.repeatMode = MPMovieRepeatModeOne;

[self.playerController.view setFrame:self.movieView.bounds];
[self.movieView addSubview:self.playerController.view];

[self.playerController.moviePlayer play];
}

I have also tried using above code in (void) loadView but the result was the same.
I also have some buttons in the storyboard which I don't want to miss them.
Could anyone help me to have only one MPMoviePlayerViewController?
Thanks in advance!


text:
Q: How do I redirect a Django form submit to a new tab after form validation?
*

*I have a Django form with two dropdown integer fields and a submit button.

*A user selects values from these dropdown fields and click on submit button.

*The Django template performs a form 'post' and sends these two dropdown values to my Django views.

*Django views performs the form validation by validating these two dropdown fields values.

*If the form is not valid, it will send the error message to the Django template and I can display the error message on the same form page above the form.

*If the form is valid, then it will redirect to a new URL.

Issue: How do I tell my Django view to redirect the URL to a new tab only after the form is valid?

A: I'm assuming that you're already familiar with Djangos Form View. Within the form_valid(self, form) method of your class based view simply replace return super().form_valid(form) with redirect(reverse('YOUR_TARGET_VIEW')). If you have other mixins within your view that rely on form_valid you may also call super().form_valid(form) prior to returning the redirect reponse but without returning its returned data further.
As of displaying error messages you may refer to the django message framework.
EDIT: A cleaner way to do this, may be to overwrite success_url within your processing but this may not be appropriate to all use cases as you need to provide usefull defaults within each request path.


text:
Q: Does decreasing transmit power of wireless router decrease the bandwidth? I have a very simple wireless router (without a lot of settings to change). I want to limit the speed for the devices that connect directly to my router via WiFi -- so that my PC which is connected to the router directly via network cable can get the best speed.
I have a setting transmit power that was 100%. If I decrease that, can I get the effect I am after?

A: The transmit power just adjusts the output amplitude of the signal, it does not change the frequency.
This adjusts how far the signal will travel, not the amount of data in the signal.

A: wrong
I stick our router which is downstairs, down to just 2mhz, power output this limits the transmission speed from 80-100% to just 13mbps which is enough for the kids
no more work conference calls interrupted because a nintendo switch is downloading games
IF its "dad the wifi is slow" then i question what they have done, so they pause downloads for another time or heaven forbid go outside


text:
Q: How can I upload a file to a SharePoint Document Library using Silverlight and client web-services? I'm using C# in Visual Studio with a Silverlight app. I want to upload a file to a document library, but none of the web-services here http://msdn.microsoft.com/en-us/library/ms479390.aspx seem to have a way to do this.
I'm not using object model, only service references to the .asmx's in that link.

A: After searching for a solution to this all week I finally found a web-service call that works with it. Here is how I solved this problem: (SharepointCopy is my service reference to copy.asmx)
   public void UploadFile(String fileName, byte[] file)
   {

        string[] destinationUrls = {"http://[server]/sites/[listName]/"+fileName};

        // load the file into a file stream

        byte[] fileBytes = file;

        // fill out the metadata
        // remark: don't set the Name field, because this is the name of the document

        SharepointCopy.FieldInformation titleInformation = new SharepointCopy.FieldInformation
            {DisplayName ="Title",
             InternalName ="Title",
             Type = SharepointCopy.FieldType.Text,
             Value ="Test1Title"};

        // to specify the content type

        SharepointCopy.FieldInformation ctInformation = new   SharepointCopy.FieldInformation
            {DisplayName ="Content Type",
             InternalName ="ContentType",
             Type = SharepointCopy.
             FieldType.Choice,
             Value ="Your content type"};

        SharepointCopy.FieldInformation[] metadata = { titleInformation };

        // initialize the web service

        SharepointCopy.CopySoapClient copyws = new SharepointCopy.CopySoapClient();

        // execute the CopyIntoItems method
        copyws.CopyIntoItemsCompleted += copyws_CopyIntoItemsCompleted;
        copyws.CopyIntoItemsAsync("http://null", destinationUrls, metadata, fileBytes);

     }

Many Thanks to Karine Bosch for the solution here: http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/f135aaa2-3345-483f-ade4-e4fd597d50d4

A: Uploading a document can be done using a HTTP PUT command, for example using WebClient and the UploadData method.


text:
Q: dns_get_record using post from form I am trying to create a simple DNS query based on dns_get_record. I have scoured the internet for support on this but to no avail! Most likely because it is an old and outdated method. Nevertheless, I am having a hard time getting a form to work with the php. Any help would be appreciated.
index.html
<html>
<body>

<form action="dns.php" method="post">
Name: <input type="text" name="search"><br>
<input type="submit">
</form>

</body>
</html>

dns.php
<?php
$search = test_input($_POST["search"]);
$result = dns_get_record($search, DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?>

A: Have you tried without test_input function?
$search = $_POST["search"];


text:
Q: Is it possible to detect if a web page is shown inside an Infragistics igDialog? My web page is shown sometimes without container and sometimes inside an igDialog of another container page, depending on the navigation of the user inside our web application.
Is it possible (in pure javascript or jQuery) to detect from my page if I am inside an igDialog?

A: This answer may not meet your "pure JavaScript" requirement, but here is how I would do it.
Add a parameter to query string when accessing the page, such as "mywebpage?igdialog=true"
Then you could use JavaScript to check if that parameter is set.


text:
Q: continuous slider in matlab I am very frustrated about this, because every method I found online does not work for me. Some can only display str rather then pass on variable. E.g.
h = uicontrol('style','slider','callback',@(src,evt)disp(get(src,'value')));
addlistener(h,'Value','PreSet',@(~,~)disp('hi'));

If I replace the disp function with my Callback, I get error saying there is no 'Value' property. Here is my code
zeta = .5;                           % Damping Ratio
wn = 2;                              % Natural Frequency
sys = tf(wn^2,[1,2*zeta*wn,wn^2]);
f = figure;
ax = axes('Parent',f,'position',[0.13 0.39  0.77 0.54]);
h = stepplot(ax,sys);
setoptions(h,'XLim',[0,10],'YLim',[0,2]);
b = uicontrol('Parent',f,'Style','slider','Position',[81,54,419,23],...
              'value',zeta, 'min',0, 'max',1,'callback',@(s,e)updateSystem(h,tf(wn^2,[1,2*s.Value*wn,wn^2])));
addlistener(b,'Value','PostSet',@(s,e)updateSystem(h,tf(wn^2,[1,2*s.Value*wn,wn^2])))

"No appropriate method, property, or field 'Value' for class 'matlab.graphics.internal.GraphicsMetaProperty'."
In other example, there is 'ContinuousValueChange', 'ActionEvents', which simply does not work.
Can anyone give me a simple example where slider give continuous output on its value?
Thanks

A: in your listener line the variable s is the listener object not the uicontrol variable (b).
Updating your simple example it would be:
figure;
h = uicontrol('style','slider','callback',@(src,evt)disp(get(src,'value')));
addlistener(h,'Value','PreSet',@(~,~)disp(h.Value));