text:
Q: Prove by induction that $Fib_{n} \geq (3/2)^{n-1}$ I need help with the last inductive steps, can someone help? I hope my formatting is good enough, first time here.
The case:
"Let the fibonacci sequence be recursivly defined so that
$$F_0 = 0, F_1 = 1$$
Else if n >= 2
$$F_n = F_{n-1}+F_{n-2} $$
Prove that
$$F_n \geq (3/2)^{n-1}$$
For all numbers in the set $\{6,7,8,9...\}$"
Basecase:
$$F_{2} = F_{1} + F_{0} = 1 + 0 $$
$$F_{3} = F_{2} + F_{1} = 1 + 1 $$
$$F_{4} = F_{3} + F_{2} = 2 + 1 $$
$$F_{5} = F_{4} + F_{3} = 3 + 2 $$
$$F_{6} = F_{5} + F_{4} = 5 + 3 $$
$$F_{6} \geq (3/2)^{5} = 8 \geq 7.59 $$
Induction step:
We assume the above is true for $n=k$, so now we prove it is true for $n=k+1$
We remember
$$F_n \geq (3/2)^{n-1}$$
$$F_{k+1} \geq (3/2)^{k}$$
We know that
$$ F_{k} = F_{k-1}+F_{k-2} $$
$$ F_{k+1} = F_{k}+F_{k-1} $$
$$ F_{k}+F_{k-1} \geq (3/2)^{k} $$
I'm not quite sure where to go from here, can anyone help? I've looked at another thread about the same question, but I don't understand the last part of his equation nor the answers.
In my case we are told that "you may need to use $(3/2)+1 > (3/2)^{2}$", but I don't know how to apply it to my case.

A: If $F_k\geqslant\left(\frac32\right)^{k-1}$ and $F_{k+1}\geqslant\left(\frac32\right)^k$, then\begin{align}F_{k+2}&=F_k+F_{k+1}\\&\geqslant\left(\frac32\right)^{k-1}+\left(\frac32\right)^k\\&=\left(\frac32\right)^{k-1}\left(1+\frac32\right)\\&>\left(\frac32\right)^{k-1}\left(\frac32\right)^2\\&=\left(\frac32\right)^{k+1}.\end{align}

A: Write $F_{k+1}\geq (3/2)^k+(3/2)^{k-1}=(3/2)^{k-1}(1+3/2)$ from here you can finish using the hint.


text:
Q: How to get sum of the cubes of its digits First of all I want to know what it is even called; lets take an example a number
153

now let's cube all its digits:
(1 * 1 * 1) + (5 * 5 * 5) + (3 * 3 * 3) == 153

if the output is 153, what exactly is this thing called. I hope you understand what I'm trying to say now. I also want to implement the same thing in code without using any predefined methods in C#
How can I do that?
Please note that the input number can be dynamic and not hard coded like 153 as example

A: First of all, please note that the sequence is finite: if we have 5 digits number, the maximum sum of digits cubed can be
99999 -> 5 * 9**3 == 3645 (max possible sum) < 10000 (min possible number)

Using calculus you can prove that sum of digits cubed grows slower than number itself (let me omit the proof); so if number has 5 or more digits it can't be the number we are looking for.
So far so good, we should check numbers from 1 to 10000 only.
Code: (please, fiddle yourself)
private static IEnumerable<int> A046197() {
  for (int number = 1; number < 10000; ++number) {
    int s = 0;

    for (int n = number; n > 0; n /= 10) {
      int d = n % 10;

      s += d * d * d;
    }

    if (number == s)
      yield return number;
  }
}

Let's have a look:
Console.Write(string.Join(", ", A046197()));

Output:
1, 153, 370, 371, 407

Note, that these numbers are A046197 sequence in oeis where you can find details.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bug with regards to .tar.gz in Chrome when 'Asking where to save downloads' Every time I try to download or save a .tar.gz file, I get something like this:

The popup is simply wrong, I've used the right .tar.gz extension. Clicking on Use .gz saves the file as .tar.gz, and clicking on Use .tar.gz saves the file as .tar.tar.gz.
Is there a way to fix this?

A: This is a documented bug:

*

*https://code.google.com/p/chromium/issues/detail?id=83084
Look for a nightly build or update to potentially address this or perhaps choosing another browser. Hat tip to jaume for the comment alerting us to the specific issue being tracked.


text:
Q: jQuery.prop() does not modify DOM element? I use an input field to submit 2 pieces of data to an event handler: the displayed value and a property value.
When I populate the data, I do this:
      xInput.val('ARC'+opts[0].arc);
      xInput.prop('data-sine',opts[0].sine);
// Now, trigger submit-handler
      xInput.show();
      xInput.trigger('change');

When I stop in the debugger, I can see that the property data-sine exists on the jQuery object and has the correct data.
Now, in the change event, I want to move the data from the "element" onto the event so the astrosearch API invocation can pick it up using a generic event handler, which also handles input from a <SELECT> tag in cases where there is more than one arc to choose from. So, I do this:
    xInput.on('change', function (e) {
      e.sine = $(this).attr('data-sine');
      astrofinder.findAstro(e, true);
      astrofinder.ui.countdown.start(function () { xInput.trigger('find'); });
    });

When I stop at the first line here, this is NOT the xInput jQuery object, it's the raw HTML element - BUT the element DOES NOT HAVE a data-sine property!  Somehow, it didn't make it out of jQuery into the DOM?
Why?  Do I need to use a timer to get into the next event loop?


text:
Q: Describe the open sets of the Cartesian product of metric spaces. I want help with the proof of this theorem

Consider the metric spaces $(\mathbb{X}_j,d_j), j=1,\dotsc,n$.
Let $\mathbb{X}=\mathbb{X_1}\times\cdots\times\mathbb{X_n}$
The map $E:\mathbb{X}\times\mathbb{X} \to \mathbb{R}$ with $$E(x,y)= \left[ \sum_{j=1}^n\big( d_j(x_j,y_j ) \big)^2 \right]^{\frac{1}{2}} $$ is a distance over $\mathbb{X}$, so $(\mathbb{X},E)$ is a new metric space.

Theorem: $\mathbb{X}\supset A \in \tau(E) \iff A = \bigcup\limits_{i \in I}A_i$,
$A_i$ such that $A_i=A_{i1}\times\cdots\times A_{in},\,\, A_{ij}\in \tau(d_j),\,\ \forall i\in I ,j={1,\dotsc,n} $

Proof: ($\Leftarrow$) We have to show that $ \forall i\in I \Rightarrow A_i \in \tau(E)$

That part is easy.

Since $$A_{ij}\in \tau(d_j),\,\ \forall i\in I ,j={1,\dotsc,n}$$
  For every $x=(x_1,\dotsc,x_n)\in A_i$ we can find $\varepsilon$ such that
  \begin{align*}
&B_{d_j}(x_j,\varepsilon)\subset A_{ij}, \,\, j=1,\dotsc,n\\\\
&\Rightarrow \prod_{j=1}^n B_{d_j}(x_j,\varepsilon)\subset \prod_{j=1}^n A_{ij}=A_{i}
\end{align*}
Now in order to finish this part we have to show that $$B_{E}(x,\varepsilon)\subset \prod_{j=1}^n B_{d_j}(x_j,\varepsilon)$$
If we examine the arbitrary $y=(y_1,\dotsc,y_n)\in B_{E}(x,\varepsilon)$, we get
\begin{align*}
&y=(y_1,\dotsc,y_n)\in B_{E}(x,\varepsilon)\Rightarrow \\\\
&\Rightarrow E(x,y) < \varepsilon \\\\
&\Rightarrow \left[ \sum_{j=1}^n\big( d_j(x_j,y_j ) \big)^2 \right]^{\frac{1}{2}} < \varepsilon \\\\
&\Rightarrow d_j(x_j,y_j ) < \varepsilon, \,\, j=1,\dotsc,n\\\\
&\Rightarrow y_j \in B_{d_j}(x_j,\varepsilon), \,\, j=1,\dotsc,n\\\\
&\Rightarrow y\in \prod_{j=1}^n B_{d_j}(x_j,\varepsilon)\\\\
&\Rightarrow B_{E}(x,\varepsilon)\subset \prod \limits_{j=1}^n B_{d_j}(x_j,\varepsilon)
\end{align*}
now I have to show ($\Rightarrow$)

But I have absolutely no idea how to do it.
Could someone write down some steps?
And check the rest of the proof?
Thank you in advance.

A: Hint:  to make things easier first consider $n=2$.  $A$ will be the union of open balls containing each of its points $x\in A$ because it is an open set in a metric space.  Say $x=(x_1, x_2)$.  Given an open ball of radius $r$ around $x$ let $A_1$ be an open ball of radius ${1\over 2}r$ around $x_1$ and let $A_2$ be ditto around $x_2$.  We can easily see that  each element of $A_1\times A_2$ is no more than $({1\over4}r^2 + {1\over4}r^2)^{1/2}=(1/\sqrt{2})r<r$ away from $(x_1, x_2)$ (in the metric $E$ of course).  Given that $x\in A$ was arbitrary, we can see that $A$ is a union of sets of the form $A_1\times A_2$ as desired.  The reasoning generalizes to larger $n$'s.


text:
Q: "ambiguous use" on generic method after migration to swift 4 I am trying to migrate my code from xcode 8.2 swift 3.0.2 to xcode 9 swift 4, and I have problem with this code:
func test<T0, TRet>(_ fn: (T0) -> TRet) -> Void {
    print("foo1")
    print(T0.self)
}

func test<T0, T1, TRet>(_ fn: (T0, T1) -> TRet) -> Void {
    print("foo2")
    print(T0.self)
    print(T1.self)
}

let fn2 : (Int, Int) -> Int = { (x:Int, y:Int)->Int in
    return x+y
}

test(fn2)

xcode 8.0.2, swift 3.0.2 results with:
foo2
Int
Int

xcode 9, swift 4 results with:
Playground execution failed:

error: MyPlayground.playground:12:1: error: ambiguous use of 'test'
test(fn2)
^

MyPlayground.playground:1:6: note: found this candidate
func test<T0, T1, TRet>(_ fn: (T0, T1) -> TRet) -> Void {
^

Am I missing something? Is there any new feature in swift 4 that causes this error?

Update
I filed a bug at bugs.swift.org as suggested in the comments.
https://bugs.swift.org/browse/SR-6108

A: I ran into the same problem, and stumbled across a workaround that is (for my purposes) nicer than disambiguating via naming.  Perhaps it is not even a workaround, just the way things have to be.  It's also possible that this is newly-possible in Swift 4.1 (not sure, since I migrated directly from Swift 3 to 4.1)
Change this:
func test<T0, TRet>( fn: (T0) -> TRet) -> Void
...to this...
func test<T0, TRet>( fn: ((T0)) -> TRet) -> Void
(note the extra pair of parens around the T0 callback parameter, which explicitly makes it into a tuple-of-1)
After this change, test(fn2) compiles and calls the test<T0,T1,TRet> overload.
It seems that the compiler is able to treat a function with N arguments as a function with one N-way-tuple argument.   Hence, both the (T0) -> TRet and (T0,T1) -> TRet overloads are candidates for fn2, and the call is ambiguous.  Adding 2nd pair of parens ((T0)) -> TRet limits that overload to an argument with a single parameter or 1-way tuple.


text:
Q: SQLite in Android How to update a specific row I've been trying to update a specific row for a while now, and it seems that there are two ways to do this. From what I've read and tried, you can just use the:
execSQL(String sql) method
or the:
update(String table, ContentValues values, String whereClause, String[] whereArgs) method.
(Let me know if this is incorrect as I am new to android and very new to SQL.)
So let me get to my actual code.
myDB.update(TableName, "(Field1, Field2, Field3)" + " VALUES ('Bob', 19, 'Male')", "where _id = 1", null);

I am trying to accomplish this:
Update Field1, Field2, and Field3 where the primary key (_id) is equal to 1.
Eclipse gives me a red line right underneath the word "update" and gives me this explanation:

The method update(String, ContentValues, String, String[]) in the type
  SQLiteDatabase is not applicable for the arguments (String, String,
  String, null)

I'm guessing I'm not assigning the ContentValues correctly. Can anyone point me in the right direction?

A: hope this'll help you:
public boolean updatedetails(long rowId, String address)
  {
     SQLiteDatabase mDb= this.getWritableDatabase();
   ContentValues args = new ContentValues();
   args.put(KEY_ROWID, rowId);
   args.put(KEY_ADDRESS, address);
  return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)>0;
 }

A: You try this one update method in SQLite
int id;
ContentValues con = new ContentValues();
con.put(TITLE, title);
con.put(AREA, area);
con.put(DESCR, desc);
con.put(TAG, tag);
myDataBase.update(TABLE, con, KEY_ID + "=" + id,null);

A: Simple way:
String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;

myDataBase.execSQL(strSQL);

A: use this code in your DB
      `
public boolean updatedetails(long rowId,String name, String address)
      {
       ContentValues args = new ContentValues();
       args.put(KEY_ROWID, rowId);
       args.put(KEY_NAME, name);
       args.put(KEY_ADDRESS, address);
       int i =  mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
    return i > 0;
     }

for updating in your sample.java use this code
  //DB.open();

        try{
              //capture the data from UI
              String name = ((EditText)findViewById(R.id.name)).getText().toString().trim();
              String address =(EditText)findViewById(R.id.address)).getText().toString().trim();

              //open Db
              pdb.open();

              //Save into DBS
              pdb.updatedetails(RowId, name, address);
              Toast.makeText(this, "Modified Successfully", Toast.LENGTH_SHORT).show();
              pdb.close();
              startActivity(new Intent(this, sample.class));
              finish();
        }catch (Exception e) {
            Log.e(TAG_AVV, "errorrrrr !!");
            e.printStackTrace();
        }
    pdb.close();

A: At first create a ContentValues object :
ContentValues cv = new ContentValues();
cv.put("Field1","Bob");
cv.put("Field2","19");

Then use the update method. Note, the third argument is the where clause. The "?" is a placeholder. It will be replaced with the fourth argument (id)
myDB.update(MY_TABLE_NAME, cv, "_id = ?", new String[]{id});

This is the cleanest solution to update a specific row.

A: First make a ContentValues object :
ContentValues cv = new ContentValues();
cv.put("Field1","Bob"); //These Fields should be your String values of actual column names
cv.put("Field2","19");
cv.put("Field2","Male");

Then use the update method, it should work now:
myDB.update(TableName, cv, "_id = ?", new String[]{id});

A: Can try like this:
ContentValues values=new ContentValues();
values.put("name","aaa");
values.put("publisher","ppp");
values.put("price","111");

int id=sqdb.update("table_name",values,"bookid='5' and booktype='comic'",null);

A: *

*I personally prefere .update for its convenience. But execsql will work same.

*You are right with your guess that the problem is your content values. You should create a ContentValue Object and put the values for your database row there.

This code should fix your example:
 ContentValues data=new ContentValues();
 data.put("Field1","bob");
 data.put("Field2",19);
 data.put("Field3","male");
 DB.update(Tablename, data, "_id=" + id, null);

A: if your sqlite row has a unique id or other equivatent, you can use where clause, like this
update .... where id = {here is your unique row id}

A: For updates, need to call setTransactionSuccessfull for changes to get committed like so:
db.beginTransaction();
try {
    db.update(...)
    db.setTransactionSuccessfull(); // changes get rolled back if this not called
} finally {
   db.endTransaction(); // commit or rollback
}

A: //Here is some simple sample code for update
//First declare this
private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;

//initialize the following
dbhelper=new DatabaseAppHelper(this);
        db=dbhelper.getWritableDatabase();

//updation code
 ContentValues values= new ContentValues();
                values.put(DatabaseAppHelper.KEY_PEDNAME, ped_name);
                values.put(DatabaseAppHelper.KEY_PEDPHONE, ped_phone);
                values.put(DatabaseAppHelper.KEY_PEDLOCATION, ped_location);
                values.put(DatabaseAppHelper.KEY_PEDEMAIL, ped_emailid);
                db.update(DatabaseAppHelper.TABLE_NAME, values,  DatabaseAppHelper.KEY_ID + "=" + ?, null);

//put ur id instead of the 'question mark' is a function in my shared preference.

A:  public void updateRecord(ContactModel contact) {
    database = this.getReadableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_FIRST_NAME, contact.getFirstName());
    contentValues.put(COLUMN_LAST_NAME, contact.getLastName());
    contentValues.put(COLUMN_NUMBER,contact.getNumber());
    contentValues.put(COLUMN_BALANCE,contact.getBalance());
    database.update(TABLE_NAME, contentValues, COLUMN_ID + " = ?", new String[]{contact.getID()});
    database.close();
}

A: you can try this...
db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 ");

A: just try this way
  String strFilter = "_id=" + Id;
  ContentValues args = new ContentValues();
  args.put(KEY_TITLE, title);
  myDB.update("titles", args, strFilter, null);**

A: Method for updation in SQLite:
public void updateMethod(String name, String updatename){
    String query="update students set email = ? where name = ?";
    String[] selections={updatename, name};
    Cursor cursor=db.rawQuery(query, selections);
}

A: I will demonstrate with a complete example
Create your database this way
    import android.content.Context
    import android.database.sqlite.SQLiteDatabase
    import android.database.sqlite.SQLiteOpenHelper

    class DBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
        override fun onCreate(db: SQLiteDatabase) {
            val createProductsTable = ("CREATE TABLE " + Business.TABLE + "("
                    + Business.idKey + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                    + Business.KEY_a + " TEXT, "
                    + Business.KEY_b + " TEXT, "
                    + Business.KEY_c + " TEXT, "
                    + Business.KEY_d + " TEXT, "
                    + Business.KEY_e + " TEXT )")
            db.execSQL(createProductsTable)
        }
        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
            // Drop older table if existed, all data will be gone!!!
            db.execSQL("DROP TABLE IF EXISTS " + Business.TABLE)
            // Create tables again
            onCreate(db)

        }
        companion object {
            //version number to upgrade database version
            //each time if you Add, Edit table, you need to change the
            //version number.
            private val DATABASE_VERSION = 1

            // Database Name
            private val DATABASE_NAME = "business.db"
        }
    }

Then create a class to facilitate CRUD -> Create|Read|Update|Delete
class Business {
    var a: String? = null
    var b: String? = null
    var c: String? = null
    var d: String? = null
    var e: String? = null

    companion object {
        // Labels table name
        const val TABLE = "Business"
        // Labels Table Columns names
        const val rowIdKey = "_id"
        const val idKey = "id"
        const val KEY_a = "a"
        const val KEY_b = "b"
        const val KEY_c = "c"
        const val KEY_d = "d"
        const val KEY_e = "e"
    }
}

Now comes the magic
import android.content.ContentValues
import android.content.Context

    class SQLiteDatabaseCrud(context: Context) {
        private val dbHelper: DBHelper = DBHelper(context)

        fun updateCart(id: Int, mBusiness: Business) {
            val db = dbHelper.writableDatabase
            val valueToChange = mBusiness.e
            val values = ContentValues().apply {
                put(Business.KEY_e, valueToChange)
            }
            db.update(Business.TABLE, values, "id=$id", null)
            db.close() // Closing database connection
        }
    }

you must create your ProductsAdapter which must return a CursorAdapter
So in an activity just call the function like this
internal var cursor: Cursor? = null
internal lateinit var mProductsAdapter: ProductsAdapter

 mSQLiteDatabaseCrud = SQLiteDatabaseCrud(this)
    try {
        val mBusiness = Business()
        mProductsAdapter = ProductsAdapter(this, c = todoCursor, flags = 0)
        lstProducts.adapter = mProductsAdapter

        lstProducts.onItemClickListener = OnItemClickListener { parent, view, position, arg3 ->
                val cur = mProductsAdapter.getItem(position) as Cursor
                cur.moveToPosition(position)
                val id = cur.getInt(cur.getColumnIndexOrThrow(Business.idKey))

                mBusiness.e = "this will replace the 0 in a specific position"
                mSQLiteDatabaseCrud?.updateCart(id ,mBusiness)

            }

        cursor = dataBaseMCRUD!!.productsList
        mProductsAdapter.swapCursor(cursor)
    } catch (e: Exception) {
        Log.d("ExceptionAdapter :",""+e)
    }

A: SQLiteDatabase myDB = this.getWritableDatabase();

ContentValues cv = new ContentValues();
cv.put(key1,value1);
cv.put(key2,value2); /*All values are your updated values, here you are
                       putting these values in a ContentValues object */
..................
..................

int val=myDB.update(TableName, cv, key_name +"=?", new String[]{value});

if(val>0)
 //Successfully Updated
else
 //Updation failed

A: Here I have completed this kind of code for update the row of a database, this is the code of Database handler class
public Boolean updateData(String id,String name,String age,String gender){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(ID,id);
    contentValues.put(NAME,name);
    contentValues.put(AGE,age);
    contentValues.put(GENDER,gender);

    sqLiteDatabase.update(TABLE_NAME,contentValues,ID+"= ?",new String[]{id});
    return true;           //Boolean value return korbe
}

A: public long fillDataTempo(String table){
    String[] table = new String[1];
    tabela[0] = table;
    ContentValues args = new ContentValues();
    args.put(DBOpenHelper.DATA_HORA, new Date().toString());
    args.put(DBOpenHelper.NOME_TABELA, nome_tabela);
    return db.update(DATABASE_TABLE, args, STRING + " LIKE ?" ,tabela);
}

A: just give rowId and type of data that is going to be update in ContentValues.
public void updateStatus(String id , int status){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("status", status);
db.update(TableName, data, "columnName"  + " = "+id , null);
}


text:
Q: Ionic $http request get not working with error data null status -1 I use Ionic and Cordova framework for developing a mobile app, I've got the issue that can not use http get to request some url. For $http.get to some url that works fine, but some others not work and it response error like as
I/Web Console( 9179): {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[n ull],"url":"http://someexmaple.com/","headers":{"Accept":"application/json, text/plain, */*"},"withCredentials":true}," statusText":""}

This issue only happens when I test on real mobile device and using adb debugging tool. But I tested on Browser and Genymotion virtual devices, both of them worked well for all url request.
So I've know idea with this response error. I think may be my device got problem.

A: Finally I've resolved my problem. I use inspect tool in Chrome, and move to network tab for watching the network packet, I see when I access to the url of site, it redirect me to another server port (instead of 80, it redirect to 443), I've noticed this because the 'Remote Address field' is the same address of url server, but port was changed. So I changed my $http.get request url from port 80 into port 443. And then it works, so I guess that when $http.get to the url but it didn't redirect to another port to get data, so it just response the null.


text:
Q: local JMX connection Using the reference to link .
I am trying to Make an Explicit local JMX Connection.
After executing
 java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=3333 - Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -jar   test.jar command

I am  trying  to make make JMX connection. But when I tried to connect with localhost and port 3333,
I got error saying cannot connect to localhost:3333 using service:jmx:rmi:///jndi/rmi/://localhost:3333/jmxrmi.
I tried according to document but i can not figure out what is the problem.
Thanks in advance!


text:
Q: Get value of asp.net CheckBox via jquery(true/false) got the answer syntax error
i want to get value of asp.net check box via jquery , if its selected return true otherwise false. i'm doing this: -
  var ApprovalRequired = $('<%= chkRequired.ClientID %>').is(':checked');
  // also
   var ApprovalRequired = $('<%= chkRequired.ClientID %>').val();

and the checkbox return in html as
  <input id="ctl00_ContentPlaceHolder1_chkRequired" type="checkbox" name="ctl00$ContentPlaceHolder1$chkRequired" checked="checked">

in either way its returning 'false'. Any idea to get true when checked and false on unchecked

A: You forgot the # in your selector:
$('#<%= chkRequired.ClientID %>').is(':checked');

That should work


text:
Q: Return undefined value outside the loop I'm using a for loop for checking the queries I've read before, and after I adding the wrong queries to a map and return the map I received 'undefined'.
I'm using async functions but it didn't help.
This is the function:
async function validateQueryResult(connection, queries) {
var result;
var alertsList = new Map();

return new Promise((resolve, reject) => {
    for (query in queries) {
        connection.execute({
            sqlText: queries[query]["query"],
            complete: function (err, stmt, rows) {
                if (err) {
                    console.error('Failed to execute query ' + queries[query]["query"] + ' due to the following error: ' + err.message);
                }
                else {
                    rows[0].toString();
                    result = Object.values(rows[0]);
                    if (result[0] > 0) {
                        alertsList.set(queries[query], result[0]);
                    }
                }
            }
        });
    }
   resolve(alertsList);
})

}
Thanks for help!

A: Your problem is, that connection.execute() is another async call. And your for-loop is done before any of the expected answers returns. Try it this way:
async function validateQueryResult(connection, queries) {
  var result;
  var alertsList = new Map();

  return new Promise((resolve, reject) => {
     for (query in queries) {
           const result = await this.execute(query);

           if (result && result[0] > 0) {
               alertsList.set(queries[query], result[0]);
           }
     }
    resolve(alertsList);
  })
}

async function execute(query) {
   connection.execute({
      sqlText: queries[query]["query"],
      complete: function (err, stmt, rows) {

      if (err) {
         console.error('Failed to execute query ' + queries[query]["query"] + ' due to the following error: ' + err.message);
       }
       else {
           rows[0].toString();
           return Object.values(rows[0]);
       }
      }

   });
}


text:
Q: css apply color to div id and class When i apply color to div  id and class it does not works. Please provide solution for this .I am trying to add color for div   in the following code:
html:
body {
    background-color:#666
}
.header{
  padding: 10px;
  /*float:left; */
  margin-left:auto;
  width:100%;
  background-color:#C60;
  height:60px;
  /*position:fixed; width:100%; */
  overflow:hidden
}

.logo1 {
  /**width:14%;
  /height: 70px;
  /*margin-left: 20px;
  /float: left; */
  color : #0F0;
  overflow : auto
}

Here  tag color is not working properly.
HTML :

A: Please note that the color property will only change the text color, to change the color of the div, use background-color instead. You will not see your color if your div does not have any content unless you give it a width/height
here is an example:(I used exaclty your code)

.header{
  padding: 10px;
  margin-left:auto;
  width:100%;
  background-color:#C60;
  height:60px;
  overflow:hidden
}

.logo1 {
  color : #0F0; /**this will only change the text color**/
  overflow : auto
}

Logo

Simply click "Run code snippet"


text:
Q: System.Net.WebClient() DownloadUsingWebClientAsync working in .netcore 3.1 but not with .netcore 2.2 (behind proxy) I did POC on my office machine to download a zip file, extract and do some process. I showcased this using a console app however, this needs to go to azure functions app. So I made sure I am using the matching framework (.netcore 2.2) which is running in production. This is working perfectly as intended.
Below is the code snippet to download the file:
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace DownloadFile
{
    class Program
    {

        private static string url = @"http://somesite.com/somefile.dat";

        static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Downloading...");

                await DownloadUsingWebClientAsync(url, Path.Combine(Path.GetTempPath(), "avvdat.ini"));

                Console.WriteLine("Download complete");

            }
            catch(Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message.ToString());
            }
            Console.Write("Press ENTER key to end");
            Console.ReadLine();
        }

        private static async Task DownloadUsingWebClientAsync(string url, string filePath)
        {
            using (var client = new WebClient())
            {
                await client.DownloadFileTaskAsync(url, Path.Combine(filePath));
            }
        }

    }
}

When I ran the same code (console app) in my client's vm this is failing with below error (SS of error log)

Soon I realized our client's VMs are behind a proxy and uses .pac (proxy script file in IE) to auto-detect settings.

I made slight changes to code to use proxy settings
client.Proxy = new WebProxy("http://proxy.clientsite.com/internet_proxy.pac");
await client.DownloadFileTaskAsync(url, Path.Combine(filePath));

This is now giving me error

I am sure 404 is not related the download url because its unchanged/correct.
Now, when I changed the framework to .netcore 3.1, the code without proxy setting is working.
I am not sure why is this but it must be 3.0 is taking care of proxy settings internally. Is there a way I can do it using 2.2? because I am not yet authorized to upgrade to 3.1


text:
Q: Why is delta used to describe difference between two entities I hear a lot about extracting "delta" between two properties in my current job. I come from a User Interface programming background and I do not really have much math background. I looked up delta online but did not find any definition of it meaning "difference"
Can anyone help me understand?


text:
Q: Join row with MAX row in another table? How do I join a row from one table to a row with the MAX value for a given column on another table?
For example, I have a auctions table and an auction_bids table. I want to join the auctions table with the highest bid for that auction (i.e. highest value for column bid_amount AND where auction_id = x) in the auction_bids table.

A: It's annoyingly complicated. You'd be better off with a "winner" flag in each winning auction_bid.
SELECT * FROM auctions a
INNER JOIN
(
    /* now get just the winning rows */
    SELECT * FROM auction_bids x
    INNER JOIN
    (
        /* how to tell the winners */
        SELECT auction_id, MAX(bid_amount) as winner
        FROM auction_bids
        GROUP BY auction_id
    ) y
    ON x.auction_id = y.auction_id
    AND x.bid_amount = y.winner
) b
ON a.auction_id = b.auction_id

Note that auctions with zero bids will not be listed at all, and auctions with ties (can that happen?) will appear once for each tied bid.

A: Try this:
SELECT a.*, bid_amount
  FROM auction a INNER JOIN
    (
     SELECT auction_id, MAX(bid_amount)  AS bid_amount
       FROM auction_bids
         WHERE acution_id = x
         GROUP BY auction_id
    ) b
    ON a.auction_id = b.auction_id

A: Try this:
SELECT a.id, MAX(ab.bid_amount)
FROM auctions AS a
INNER JOIN action_bids AS ab
   ON a.id = ab.auction_id
GROUP BY a.id;

Add more columns to your SELECT and GROUP BY clauses as needed.

A: Try this
 Select A.ID,max(AB.bit_amount)
 From  auctions A Inner Join Auction_bids AB on A.ID = AB.auction_ID
 Where A.ID = x
 Group By A.ID

A: Basically you have to use a sub query to do this in the actual join.
Select bid as highest_bid
  from auctions
    left outer join auctions_bids on action_bids.ref_no = auctions.ref_no
     and (select max(bid) from auctions_bids as ab
           where auctions_bid.ref_no = a2.ref_no)


text:
Q: Prove Borel Sets Proof $[a,b], (a,b], [a,b)$ are borel sets.
I read from book, the definition of Borel sets :

Borel sets is smallest $\sigma$-algebra that contains all open sets.

But I cannot understand it.
Please help me.

A: *

*$ \{a\}$ and $ \{b\}$ are closed, hence Borel.

*$[a,b]= (a,b) \cup  \{a\} \cup \{b\}$.

*$[a,b)= (a,b) \cup  \{a\} .$

*$(a,b]$ is your turn !

A: $[a,b]=\cap_n (a-\frac 1 n, b+\frac 1 n)$, $(a,b]=\cap_n (a, b+\frac 1 n)$ and $[a,b)=\cap_n (a-\frac 1 n, b)$.


text:
Q: Uncaught ReferenceError: monaco is not defined I am trying to run Monaco Editor but it gives an error. Uncaught ReferenceError: monaco is not defined.
I'm running a local web server and I can see the loader.js is being loaded in the Firefox Developer Tools. Also when I type monaco into the Firefox's console it says that it is not defined.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>


text:
Q: Position a node a certain distance away from another node at a certain angle in TikZ? Like the title says, is it possible to position a node a certain distance away from another node at a certain angle from that node?

A: You can shift node position B regarding to another node A from an angle and a radius in the following way:
\usepackage{tikz}
\begin{document}
 \begin{tikzpicture}
   \node (A) {A};
   \node (B) at ([shift=({240:1 cm})]A) {B};
 \end{tikzpicture}
\end{document}

A: Yes, TikZ can use polar coordinates. Not sure exactly what is the best way of defining the second node, here is one way.
\documentclass{scrartcl}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \node (A) {A};
  \path (A) ++(30:2) node (B) [draw,fill=blue!20] {B};
\end{tikzpicture}
\end{document}

In (30:2) 30 is the angle, 2 the distance. 0° is to the right, positive direction is counterclockwise, so node B will be above and to the right of A.

A: There is another way to define a node using node coordinate system:
\usetikzlibrary{calc}
\begin{tikzpicture}
\node[draw] (A) {A};
\node[draw,circle]
    (node cs:name=B) at ($(node cs:name=A)+(30:2)$) {B};
\end{tikzpicture}

A: TikZ allows you to specify positions and vectors in polar coordinates. Here's an example:
\begin{tikzpicture}
\node at (0,0) (a) {A node};
\node at (120:1cm) (b) {B node};
\path (a) ++(-45:2cm) node (c) {C node};
\end{tikzpicture}


text:
Q: Tangent complex to a cotangent stack Given a smooth Artin cotangent stack $X = T^{*}Y$ can one describe the two-term tangent complex $T_X$ in terms of $T_Y$?
The example I am interested in here is the stack of Higgs bundles over a curve $C$, so we have $X = Higgs_G(C)=T^{*}Bun_G(C)$ and $T_{Bun_G(C)} = R\pi_{*}(ad(\mathcal{P})[1])$, where $\mathcal{P}$ denotes the universal G-bundle and $\pi: C \times Bun_G(C) \to Bun_G(C)$ is the canonical projection.


text:
Q: Can I programmatically generate a list of local pure ESM node_modules for Webpack/babel-loader? Is there an easy way to get a list of your local node_modules that are pure ESM (i.e. only support ES6 import/export syntax)?
While trying to create a CommonJS bundle for a Serverless Framework project I needed to use npm packages that had recently gone pure ESM. This meant manually listing them in my Webpack config.
The solution to using pure ESM modules (details in this blog post) that I came up with was to first tweak the babel-loader exclude definition so that any modules I know to be pure ESM (and its pure ESM dependencies) are still transpiled then also make sure that webpack-node-externals passed these transpiled versions into the bundle by defining them in the allowlist.
Now I'd like to automate getting that list of third-party pure ESM modules in my project (along with their dependencies), so I don't have to keep maintaining it by hand.
Maybe loop through everything in package-lock.json as a starting point?
Here's what that currently looks like (sample repo). pureESMModules is the list I'd like to programmatically generate:
const path = require('path');

const babelLoaderExcludeNodeModulesExcept = require('babel-loader-exclude-node-modules-except');
const nodeExternals = require('webpack-node-externals');
const slsw = require('serverless-webpack');

const { isLocal } = slsw.lib.webpack;

const pureESMModules = ['pretty-ms', 'parse-ms'];

module.exports = {
  target: 'node',
  stats: 'normal',
  entry: slsw.lib.entries,
  externals: [nodeExternals({ allowlist: pureESMModules })],
  mode: isLocal ? 'development' : 'production',
  optimization: { concatenateModules: false },
  resolve: { extensions: ['.js'] },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: babelLoaderExcludeNodeModulesExcept(pureESMModules),
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
          },
        },
      },
    ],
  },
  output: {
    libraryTarget: 'commonjs2',
    filename: '[name].js',
    path: path.resolve(__dirname, '.webpack'),
  },
};

I use serverless-webpack and set includeModules to true to specifically tell it to bundle modules, which then applies to the transpiled versions that babel-loader generated:
custom:
  webpack:
    includeModules: true

Have I actually over-engineered this? It does feel like something Webpack should have already been doing for me. Or are there valid reasons it (or webpack-node-externals) can't programmatically identify which pure ESM modules to handle differently?
I know that excluding most modules in babel-loader is just there for performance reasons. If I skip that exclude option entirely, it would transpile everything and just run a little slower. I still need pureESMModules for my allowlist definition though.
Edit: Turns out webpack-node-module-types does get you a list of ESM modules, so in my example above, I use this now:
const { determineModuleTypes } =
  require('webpack-node-module-types/sync');

// ...

const pureESMModules = determineModuleTypes()?.esm || [];

You might need to do something about filtering out the ESM modules that are only used by devDependencies, in case Webpack can't tree-kshake those, or you will end up with unnecessary code in your bundle.

A: I ended up using webpack-node-module-types to get a list of ESM modules, and then also matching those up against just my dependencies, so I don't needlessly bundle up devDependencies:
const path = require('path');

const babelLoaderExcludeNodeModulesExcept = require('babel-loader-exclude-node-modules-except');
const nodeExternals = require('webpack-node-externals');
const slsw = require('serverless-webpack');
const getPureESMDependencies = require('./util/pureESMDependencies.js');

const pureESMDependencies = getPureESMDependencies();

module.exports = {
  target: 'node',
  stats: 'normal',
  entry: slsw.lib.entries,
  externals: [nodeExternals({ allowlist: pureESMDependencies.map((dep) => RegExp(`^${dep}(/.*)?$`)) })],
  mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
  optimization: { concatenateModules: false },
  resolve: { extensions: ['.js'] },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: babelLoaderExcludeNodeModulesExcept(pureESMDependencies),
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
          },
        },
      },
    ],
  },
  output: {
    libraryTarget: 'commonjs2',
    filename: '[name].js',
    path: path.resolve(__dirname, '.webpack'),
  },
};

Note how for the allowlist, I also use an array of regexps, which also catches some packages that imported stuff like formdata-polyfill/esm.min.js.
pureESMDependencies.js then looks like this:
const jsonfile = require('jsonfile');
const { determineModuleTypes } = require('webpack-node-module-types/sync');

// Recursively get all dependencies (not dev, peer) for the current project
function getDependencies(packageJsonLock, packages, knownDependencies = new Set()) {
  if (!packages?.length) return [];

  packages.forEach((packageName) => {
    const dependencies = Object.keys(packageJsonLock.packages[`node_modules/${packageName}`].dependencies || {});

    knownDependencies.add(packageName);
    if (dependencies.length) {
      dependencies.forEach((dependency) => knownDependencies.add(dependency));

      getDependencies(packageJsonLock, dependencies, knownDependencies);
    }
  });

  return [...knownDependencies];
}

// Get a list of packages that are pure ESM and in the 'dependencies' list in package.json
module.exports = function getPureESMDependencies() {
  const packageJsonLock = jsonfile.readFileSync('./package-lock.json');
  const packageJson = jsonfile.readFileSync('./package.json');

  const esmModules = determineModuleTypes()?.esm;
  if (!esmModules?.length) return [];

  const allDependencies = getDependencies(packageJsonLock, Object.keys(packageJson.dependencies));
  console.log({ allDependencies });

  return esmModules.filter((packageName) => allDependencies.includes(packageName));
};


text:
Q: How to make an array of objects an object grouped by day? So I have an array of items, each with a date (from the moment library) and some text.
I am able to successfully turn this into an object of objects however if two or more objects have the same day, as it is mapped over it rewrites the previous item with the new one.
I must organize the object of objects based on YYYY-MM-DD format.
For example, the items array might look like this when it is console logged-
Array [
  Object {
    "date": 2019-08-06T19:10:00.000Z,
    "id": 0,
    "text": "Item1",
  },
  Object {
    "date": 2019-08-06T22:10:00.000Z,
    "id": 1,
    "text": "Item2",
  },
]

this is the code I am using to turn it into an object of objects
const calItemsArray = Object.assign({},
      ...this.props.items.map(item =>
        ({ [moment(item.date).format('YYYY-MM-DD')]: [{
          text: item.text, time: moment(item.date).format('h:mm a') }]
        }))
      );
      console.log(calItemsArray);

This is what would be console logged from calItemsArray based on the given data (two items with the same date)
Object {
  "2019-08-06": Array [
    Object {
      "text": "Item2", //item one seems to be overwritten
      "time": "6:10 pm",
    },
  ],
}

I would like each date to contain all of the texts and the time of items that have that date. However if one already exists, instead of adding it to the dates array of objects it just rewrites the date's object itself.

A: Answer:
Use a reduce function instead of Object.assign
const callItemsObject = this.props.items.reduce( ( acc, item ) => {
  let key = moment( item.date ).format( 'YYYY-MM-DD' ),
    payload = {
      text: item.text,
      time: moment( item.date ).format( 'h:mm a' )
    };

  ( acc[ key ] ) ? acc[ key ].push( payload ): ( acc[ key ] = [ payload ] );

  return acc;
}, {} );

      console.dir(calItemsObject);

Example Explanation:
Now that you've provided your data model I've created some dummy data and an example. We have three dates and 5 records.

*

*Today: two records (items 1 and 2)

*5 days from now: two records (items 3 and 5)

*7 days from now: one record (item 4)

These will be pushed into an object using the date as a key in YYYY-MM-DD format. Because there are multiple records for each day you need to store them into an Array if you are going to use the date as the key, otherwise ( as in your attempt using Object.assign ) the key's value will be overridden by the newest data.
{
  items: [ {
    "date": moment(),
    "id": 0,
    "text": "Item1"
  }, {
    "date": moment(),
    "id": 1,
    "text": "Item2"
  }, {
    "date": moment().add( 7, 'days' ),
    "id": 2,
    "text": "Item3"
  }, {
    "date": moment().add( 5, 'days' ),
    "id": 3,
    "text": "Item4"
  }, {
    "date": moment().add( 7, 'days' ),
    "id": 4,
    "text": "Item5"
  } ]
}

Example:
Note: To your comment that says this doesn't work, by running this code ( which isn't changed ) I can show you that it does, in fact, work. If you're having issues feel free to comment, but you'll have to provide more information about your environment.

let data = {items:[{"date": moment(),"id":0,"text":"Item1"},{"date": moment(),"id":1,"text":"Item2"},{"date": moment().add(7, 'days'),"id":2,"text":"Item3"}, {"date": moment().add(5, 'days'),"id":3,"text":"Item4"}, {"date": moment().add(7, 'days'),"id":4,"text":"Item5"}]};

function component(props) {
let component_proto = {};
component_proto.props = Object.assign({}, props);

component_proto.getTimes = function() {
      const callItemsObject = this.props.items.reduce( ( acc, item ) => {
      let key = moment( item.date ).format( 'YYYY-MM-DD' ),
        payload = {
          text: item.text,
          time: moment( item.date ).format( 'h:mm a' )
        };

      ( acc[ key ] ) ? acc[ key ].push( payload ): ( acc[ key ] = [ payload ] );

      return acc;
    }, {} );
   return callItemsObject;
}

return component_proto;
}

let result = component(data).getTimes();

  console.dir(result);
<script src="https://momentjs.com/downloads/moment.js"></script>


text:
Q: OpenCV segmentation fault after comparing descriptor.type and descriptor.cols In my program whenever I cover the camera with something that causes no ORB features to be detected the program crashes with the error:
OpenCV Error: Assertion failed (type == src2.type() && src1.cols == src2.cols && (type == CV_32F || type == CV_8U)) in batchDistance, file /bin/opencv-2.4.7/modules/core/src/stat.cpp, line 2473
terminate called after throwing an instance of 'cv::Exception'
  what():  /bin/opencv-2.4.7/modules/core/src/stat.cpp:2473: error: (-215) type == src2.type() && src1.cols == src2.cols && (type == CV_32F || type == CV_8U) in function batchDistance

Aborted

In order to try and fix this error I followed the advice in this post here which involved adding the following if around the line matcher->match(descriptorsObject, descriptors, matches);
 if(descriptorsObject.type() == descriptors.type() && descriptorsObject.cols == descriptors.cols) {
      matcher->match(descriptorsObject, descriptors, matches);
  }

However when the camera cannot detect any feature points the program still crashes but I just get the error:
Segmentation fault
I am not sure why this is now happening, do I need to have an else condition to get the next frame if the condition of the if is not met?
EDIT:
When the code is run in debug mode I get the following error:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000402d9e in main (argc=2, argv=0x7fffffffe428) at ORB.cpp:57
57        double dist = matches[i].distance;

When enabling all warnings when compiling I get the following:
ORB.cpp:87:42: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]

Extra code:
    if(descriptorsObject.type() == descriptors.type() && descriptorsObject.cols == descriptors.cols) {
      matcher->match(descriptorsObject, descriptors, matches);
    }

    double max_dist = 0;
    double min_dist = 100;
    for( int i = 0; i < descriptorsObject.rows; i++ ) {
      double dist = matches[i].distance;  //LINE 57
      if( dist < min_dist )
        min_dist = dist;
      if( dist > max_dist )
       max_dist = dist;
    }
    std::vector<DMatch> goodMatches;

    for( int i = 0; i < descriptorsObject.rows; i++ ) {
      if( matches[i].distance < 3*min_dist ) {
       goodMatches.push_back( matches[i]);
      }
    }
if(goodMatches.size() >= 4) {
    Mat outputImage;
    Scalar keypointColor = Scalar(255, 0, 0);
    drawMatches( img_object, keypointsObject, gray, keypoints, goodMatches, imgMatches, Scalar::all(-1), Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
    std::vector<Point2f> obj;
    std::vector<Point2f> scene;

    for( int i = 0; i < goodMatches.size(); i++ ) {  //LINE 87
      //-- Get the keypoints from the good matches
      obj.push_back( keypointsObject[ goodMatches[i].queryIdx ].pt );
      scene.push_back( keypoints[ goodMatches[i].trainIdx ].pt );
    }
    std::vector<uchar> mask;
    Mat H = findHomography( obj, scene, CV_RANSAC, 3, mask );
    std::vector<Point2f> obj_corners(4);
    obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( img_object.cols, 0 );
    obj_corners[2] = cvPoint( img_object.cols, img_object.rows ); obj_corners[3] = cvPoint( 0, img_object.rows );
    std::vector<Point2f> scene_corners(4);
    perspectiveTransform( obj_corners, scene_corners, H);
    line( imgMatches, scene_corners[0] + Point2f( img_object.cols, 0), scene_corners[1] + Point2f( img_object.cols, 0), Scalar(0, 255, 0), 4 );
    line( imgMatches, scene_corners[1] + Point2f( img_object.cols, 0), scene_corners[2] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
    line( imgMatches, scene_corners[2] + Point2f( img_object.cols, 0), scene_corners[3] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
    line( imgMatches, scene_corners[3] + Point2f( img_object.cols, 0), scene_corners[0] + Point2f( img_object.cols, 0), Scalar( 0, 255, 0), 4 );
    if (mask.size() < 100) {
      std::cout << fileNamePostCut << std::endl;
    }
}
    namedWindow("Output");
    imshow("Output", imgMatches);

A: Did you try debugging?
As modifying the code with the if statement led to a different error, the most possible reason could be that you might be trying to pick some value from matches or descriptors after the if condition. And as there are no matches or features present in the image, this can lead to segmentation fault.
Try debugging the code and give us more details including code snippet so that the possibilities could be narrowed down further.

A: I extended the scope of the if statement so instead of closing after the line matcher->match(descriptorsObject, descriptors, matches); it now closes at the end above the line namedWindow("Output");


text:
Q: Calculate moving weather stats in PostgreSQL I'm trying to calculate the days since last rain and the amount of rain in that event for each day in my PostgreSQL table of weather data. I've been trying to achieve this with window functions but the limitation of ranges having to be unbounded has left me a bit stuck on how to proceed.
Here's the query I have so far:
SELECT
        station_num,
        ob_date,
        rain,
        max(rain) OVER (PARTITION BY station_num ORDER BY ob_date ASC RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as prev_rain_mm,
        '' as days_since_rain --haven't attempted this calculation yet
FROM
        obs_daily_ground_moisture

This results in the following:

but I'm trying to achieve something more like this:

I feel like all the pieces are there in regards to window functions range & filter and nested queries but I'm not sure how to pull it all together. Also the above data is just a subset of the actual dataset, the entire dataset is just over half a million rows.

A: The key here is to group the observations starting from the first occurrence of rain>0 value to the next occurrence of rain>0 value. Thereafter you can use window functions to calculate the needed columns.
select
x.station_num,
x.ob_date,
max(rain) over(partition by station_num,col) prev_rain,
case when rain > 0 then 0
else row_number() over(partition by station_num, col order by ob_date)-1 end days_since_rain
from (select t.*,
      sum(case when rain > 0 then 1 else 0 end) over(partition by station_num order by ob_date) col
      from t) x

Sample Demo

A: try this.
        DECLARE @Rain  AS FLOAT

        UPDATE A
        SET
        @Rain = CASE WHEN A.Rain = 0 THEN @Rain ELSE A.Rain END,
        A.Rain = CASE WHEN @Rain IS NULL OR A.Rain <> 0 THEN A.Rain ELSE @Rain END
        FROM obs_daily_ground_moisture A

        SELECT ob_date, Rain,
        max(rain) OVER (PARTITION BY station_num ORDER BY ob_date ASC RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as prev_rain_mm,
        ROW_NUMBER() OVER(PARTITION BY Rain ORDER BY ob_date) - 1  as days_since_rain
        FROM obs_daily_ground_moisture ORDER BY ob_date


text:
Q: DQL to query type fragments in documentum I have an object in docmentum, this object has attributes and type fragments, I want to query by a type fragment attribute value. My object name is CIC and it has a type fragment called Emision which has an attrribute called receptor, so when I do :
select * from dfl_cic c where c.emision.receptor = "XXXXX"

I get an error, so how I can query by this value ??


text:
Q: fuzzy searching an array in php after i searched i found how to do a fuzzy searching on a string
but i have an array of strings
$search = {"a" => "laptop","b" => "screen" ....}
that i retrieved from the DB MySQL
IS there any php class or function that does fuzzy searching on an array of words
or at least a link with maybe some useful info's
i saw a comment that recommend using PostgreSQL
and it's fuzzy searching capability but
the company had already a MySQL DB
Is there any recommendation ??

A: You could do this in MySQL since you already have a MySQL database - How do I do a fuzzy match of company names in MYSQL with PHP for auto-complete? which mentions the MySQL Double Metaphone implementation and has an implementation in SQL for MySQL 5.0+
Edit: Sorry answering here as there is more than could fit in a comment…
Since you've already accepted an answer using PHP Levenshtein function then I suggest you try that approach first. Software is iterative; the PHP array search may be exactly what you want but you have to test and implement it first against your requirements. As I said in your other question a find as you type solution might be the simplest solution here, which simply narrows the product as the user types. There might not be a need to implement any fuzzy searching since you are using the User to do the fuzzy search themselves :-)
For example a user starts typing S, a, m which allows you to narrow the products to those beginning with Sam. So you are always only letting the user select a product you already know is valid.

A: Look at the Levenshtein function
Basically it gives you the difference (in terms of cost) between to strings. I.e. what is the cost to transform string A into string B.
Set yourself a threshold levenshein distance and anything under that for two words mean they're similar.
Also the Bitap algorithm is faster since it can be implemented via bitwise operators, but I believe you will have to implement it yourself, unless there is a PHP lib for it somewhere.
EDIT
To use levenshtein method:
The search string is "maptop", and you set your "cost threshold" to say 2. That means you want any words that are two string transform operations away from your search string.
so you loop through your array "A" of strings until
levenshtein ( A[i] , searchString ) <= 2
That will be your match. However you may get more than one word that matches, so it is up to you how you want to handle the extra results.


text:
Q: Is the "very low quality" flag necessary? I'm having a hard time finding a use case for the "very low quality" flag that isn't already covered by some other flag. The descriptive text for VLQ basically says that it's for cases where no amount of editing can salvage a post, no matter how intrepid the editors are.
In 99.9% of cases, that translates to "we can't tell what this person was trying to say. Even if we squint and tilt our heads."

*

*Incomprehensible questions can also be described as "not a real question" or "not constructive." Users can already flag or vote to close as one of those two, depending on rep.

*Incomprehensible answers can also be described as "not an answer." We already have that as a flag option, too.
In the other 0.1% of cases, a question might be just coherent enough to be understood, but show a complete and utter lack of effort. NARQ would apply there, too.
So do we really need VLQ as a distinct flagging option?
Related posts:
Is the Very Low Quality flag too ambiguous?
Add a warning to the "low quality" flag option

A: "Not constructive" does not mean "unreadable". Its goal is to cover questions that are polls or invite extensive discussion. Please don't use that close/flag reason for other purposes.
You could potentially use NARQ for questions that are hard to understand, but usually I see it pop up on questions that are blog posts in disguise or where the question tries to cover too much ground. All the "what ifs" fall into this category as well. I don't think "this question has major formatting/content problems" is quite the same.
Far as answers go, I agree with this. "Not an answer" is for things that don't answer the question. As in, someone goes off on an unrelated tangent. A bad/incorrect answer or an answer that's difficult to understand can still answer the question, albeit badly. I don't think "not an answer" the same as "very low quality" at all.
Mind you, most "very low quality" flags I see (on Programmers) are things that can be fixed with a simple edit, but that's a topic for another time.

A:
So do we really need VLQ as a distinct flagging option?

In my eyes yes. An answer can answer a question, and still be very low quality. I find it helpful to have as a separate flag.

A: In my opinion they are usefull for questions/answers that are written is something that looks like english (e.g. uses latin alphabet) but actually it's hard to say if they are in english or not ;) In other words, when the message can not be understood, in order to be categorized in another category. Understanding what the user is asking would require a lot of effort and a long dialogue with the OP. But since it's rarely used, and 'doesn't belong here' is the most used one, I would suggest reworking the dialog so the default one is doesn't belong here, and 'very low quality' falls to 'other' category


text:
Q: Understanding bootstrapping in analog active filters "Bootstrapping" is a common technique in (analog) active filters, where the output of the filter is fed back to a node that would otherwise be connected to ground.
For example, the Sallen Key topology begins with two RC L-sections followed by a unity-gain buffer.  Then the output of the buffer is also connected to the base of the first L-section (C3 in the following schematic).  This is said to "bootstrap" that node.

Here is another example, from an old National Semiconductor / Texas Instruments app note (LB-5 / snoa690), in which the ground node of a Twin-T notch filter is 'bootstrapped' in order to greatly increase the Q of the filter:

How can I understand the operation of the 'bootstrap' intuitively?

A: A sine signal going through a T notch filter is phase shifted.
So bootstrapping means connecting the point normally connected to GND to the  buffered phase shifted signal.
So the signal at notch frequency (or near it) not only has to work against GND but against its own opposite (negative signal).
This improves the  filter (higher Q) as described in the app note.

A: A simpler example would be a transistor voltage follower in which bootstrapping is used to increase the input impedance. Normally, the input impedance is significantly affected (reduced) by the bias resistors R1 & R2.
By applying some of the output back to a series resistor R3 the input impedance is increased since the same voltage (or nearly) appears on either side of R3 so little current flows through it and the effect of the bias resistors is reduced.
With active filters, the situation is more complicated due to phase shift. Curd gives an explanation which could also be applied to bandpass filters but I'm not sure that there is any reasonable way of intuitively understanding how this works in the case of the S&K LPF. Perhaps others know different!

A: I wonder if you have found the term "bootstrapping" in connection with this filter circuit.
As shown in the previous post (MikeJ-UK) this method is used for the purpose of increasing the input impedance of an amplifier circuit.
However, for filtering purposes the method of feedback is used exclusively for the purpose of increasing the quality factor (pole-Q) of the transfer function (thus allowing Butterworth  and Chebyshev responses).
Without such feedback, any RC-filter circuit would be passive with a maximum of Q=0.5.
As can be shown, the input impedance of the shown S&K filter is not drastically influenced by the feedback path.
For DC the input current is (nearly) zero and for very high frequencies the input current is determined by the resistors only (with and without feedback)


text:
Q: Matching formal argument does not work if its default is an external variable Suppose I'm writing a new R package called myvals.
I write this in file zzz.r:
.__COMMONS__. <- new.env(parent = emptyenv())
.__COMMONS__.$vals <- c('val1', 'val2', 'val3')

Then, if I wrote this function in file vals.r:
whatvals <- function() {
  return(.__COMMONS__.$vals)
}

When I install my package (e.g., through devtools package) and load it (i.e., library(myvals)), whatvals() works:
[1] "val1" "val2" "val3"

But, if then I write another function:
isval <- function(val = .__COMMONS__.$vals) {
  match.arg(val)
}

When I call it it doesn't work because R cannot find .__COMMONS__. object.
I think this depends on the lazy evaluation of the formal parameter val by match.arg function.
Inspecting match.arg source code I found that first lines are interesting:
if (missing(choices)) {
  formal.args <- formals(sys.function(sys.parent()))
  choices <- eval(formal.args[[deparse(substitute(arg))]])
}

So I have two questions for you:

*

*how to make .__COMMONS__. environment correctly evaluated when passed to val formal parameter of isval function?

*there is a more elegant way to create global variables for a R package?

Thanks in advance.


text:
Q: asp.net core / openiddict & client spa Authorization with custom permissions I need some help in understanding a basic thing or two with Token-based authentication.
My setup is a backend asp.net core app with openiddict for token auth. It's all working well so far - I now need to add user-permissions. I will have a lot of them (e.g. User can view xy, user can edit xy, user can delete xy, with many different xy-components). Backend is working well so far, my problem is now: How to get these permissions via token to my client side app..

*

*As far as I understood these are not classical "claims" as a claim would describe "who" you are rather "what you are allowed to do" . Right?

*But how can I pack them into my id_token/ How can I add them to my payload?

*Second thing: Do I need to validate the token (signature) in my case? Every Api-request ist validated at server side, so basically I don't need to care if my client side permissions are tempered with, right? (As they are only for UI-Display purposes)
Thanks for your help!

A:
As far as I understood these are not classical "claims" as a claim would describe "who" you are rather "what you are allowed to do" . Right?

In theory, nothing prevents you from representing permissions as claims, just like you'd do with roles or any other claim. In practice tho', it's rarely the best approach, because the number of actions a user can do is usually important (and often unlimited: can the user A update the product 124? And this other product?).
A possible alternative is to catch the 403 responses returned by your API when a user is not allowed to execute a specific action so you can display an adequate error message. Another one is to create an API endpoint that dynamically determines whether a user is allowed to execute the action, according to your own policy.

Second thing: Do I need to validate the token (signature) in my case? Every Api-request ist validated at server side, so basically I don't need to care if my client side permissions are tempered with, right? (As they are only for UI-Display purposes)

Both access tokens and identity tokens are digitally signed, so they can't be tempered with (at least, not easily). You don't need to validate signatures yourself, as it's already done by the validation/JWT middleware.


text:
Q: aligning the bottom bar elements Hi I am trying to align the bottombar elements so that they are in 2 columns on the side of 102. I was wondering if there is a way to fix it as they are all floating on the right at the moment. I am a beginner html css programmer and I am not very experienced yet. Ill appreciate any help you can give me!
CSS
/*bottom navbar*/
.bottomnav{
  width: 100%;
  background-color: rgb(248, 138, 180);
  display: flex;
  flex-direction: row;
}

.navbarlogo2{
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 10%;
  text-decoration: none;
}

/*bottombar*/
.nav {
    display: flex;
    flex-direction: row;
  }

  .left, .right {
    flex: 1;
  }

HTML

About Us

Affiliates

TOS

END RESULT

WANTED RESULT

A: I made things like that. CSS Grid is one of the new HTML5 standard you should take a look. In your case, use a grid is better choice against flex because you're looking for a table-like structure.
I choosed to split your needs in 2 parts:

*

*Center your logo

*Make a 2 columns grid for your links

Centering your logo
We need to center an element and prevent it to interfere with our incoming links grid. So we'll set our container with a position: relative and place the img tag in position: absolute. Note the image's top right bottom left properties are now relative to the first parent positioned as relative.
And so we only need to make some simple maths. Note the calc() function, we don't want to center the top left corner of your logo but the center. So we need to remove the half of the defined logo's width.
navbarlogo2 {
  left: calc(50% - 60px);
}

Make a 2 columns grid for your links
In order make a grid, you have to display your container as grid and set its grid-template-columns to 1fr 1fr. You can translate fr with the word fraction. So here, we're asking for a row split in 2 fractions.
Because we want a place for our logo, we're adding a gap (grid-cap) in out container to make some space between our 2 columns.
Learn more about the fr unit here.

body {
  margin:0
}

.bottomnav {
  width: 100%;
  background-color: rgb(248, 138, 180);
  position: relative;
}

.navbarlogo2 {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 120px;
  text-decoration: none;
  position: absolute;
  filter: brightness(10);
  top: 15px;
  left: calc(50% - 60px) /*center top left corner then remove half logo width (120px)*/
}

/*bottombar*/
.nav {
  display: grid;
  grid-gap: 120px;
  grid-template-columns: 1fr 1fr;
}
.nav ul {
  padding-left: 0;
}
.nav ul li {
  list-style: none;
  text-align: center;
  padding-left: 0;
}

.left,
.right {
  flex: 1;
}

About Us

Affiliates

TOS

Fourth


text:
Q: Method definition for 'initWithName...' not found. Error I have a NSObject class in Xcode and the @implementation line is giving me an error; Method definition for 'initWithName:tutorID:tutorPhone:tutorEmail:' not found.
My .h file:
#import <Foundation/Foundation.h>

@interface TutorsItem : NSObject

@property (nonatomic, strong) NSString *tutorName;
@property (nonatomic) int tutorID;
@property (nonatomic, strong) NSString *tutorPhone;
@property (nonatomic, strong) NSString *tutorEmail;

- (id)initWithName:(NSString *)tutorName tutorID:(int)tutorID tutorPhone:(NSString *)tutorPhone tutorEmail:(NSString *)tutorEmail;

@end

My .m file:
#import "TutorsItem.h"

@implementation TutorsItem

@synthesize tutorName = tutorName;
@synthesize tutorID = tutorID;
@synthesize tutorPhone = tutorPhone;
@synthesize tutorEmail = tutorEmail;

- (id)initWithName:(NSString *)title subtitle:(NSString *)subtitle {
    self = [super init];
    if (self) {
        self.tutorName = tutorName;
        self.tutorID = tutorID;
        self.tutorPhone = tutorPhone;
        self.tutorEmail = tutorEmail;

    }

    return self;
}

@end

A: You want to change your .m file to:
- (id)initWithName:(NSString *)tutorName tutorID:(int)tutorID tutorPhone:(NSString *)tutorPhone tutorEmail:(NSString *)tutorEmail{
    self = [super init];
    if (self) {
        self.tutorName = tutorName;
        self.tutorID = tutorID;
        self.tutorPhone = tutorPhone;
        self.tutorEmail = tutorEmail;

    }

    return self;
}

The header of the function in .m file only included the subtitle, and not tutorName , tutorId and so on.
I hope this helps :)

A: Method defenition not found is not an ERROR, it's a WARNING. And you get it cause you did not provide the definition for your method inside @implementation section. You can still compile and run your code, but if you try to call this method your app will crash. Simply provide the definition and this warning will vanish
And btw get rid of this:
    self.tutorName = tutorName;
    self.tutorID = tutorID;
    self.tutorPhone = tutorPhone;
    self.tutorEmail = tutorEmail;

inside - (id)initWithName:(NSString *)title subtitle:(NSString *)subtitle because what you do there makes no sense. What you do there is assign variable values to themselves

A: The report is not an error it's a warning (unless you've enabled "warnings are errors"). It's a common warning when your @interface declares a method that your @implementation doesn't provide.
At @Wain comments, you have an init method with a very different signature in your implementation; did you intend for it to match the signature that you defined, or did you plan to provide two initializers? It's fine to have a method that doesn't appear in your @interface, but it's expected that everything presented in your @interface is intended to have an implementation as well.

A: Just so you are clear what people are try to tell you in your .h you have the following line of code
- (id)initWithName:(NSString *)tutorName tutorID:(int)tutorID tutorPhone:(NSString *)tutorPhone tutorEmail:(NSString *)tutorEmail;

but in your .m file you have this...
- (id)initWithName:(NSString *)title subtitle:(NSString *)subtitle

As you can see the 2 lines of code don't match, the compiler expects you to have a method in the .m file with the same name as you've defined in the .h. So to get rid of the error your .m file would need to have the following
- (id)initWithName:(NSString *)tutorName tutorID:(int)tutorID tutorPhone:(NSString *)tutorPhone tutorEmail:(NSString *)tutorEmail
{
    self = [super init];
    if (self) {
        self.tutorName = tutorName;
        self.tutorID = tutorID;
        self.tutorPhone = tutorPhone;
        self.tutorEmail = tutorEmail;

    }

    return self;
}

As others have also pointed out its not a good idea to have your parameter names to be the same as your properties, it just adds to confusion. The same goes for your @synthesize
This...
@synthesize tutorName = tutorName;

Might as well be this...
@synthesize tutorName;


text:
Q: How to fit a list of paths inside a border in WPF am writing a C# WPF program to view and edit SVGs.
So i have a List of pathes (PathList) and i diplay them inside a border on a canvas here's my XAML:
            <ItemsControl ItemsSource="{Binding PathList}" >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas>
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="MouseDown" >
                                    <cmd:EventToCommand Command="{Binding Path= OnMouseDownCommand}" PassEventArgsToCommand="True" />
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </Canvas>

                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>

                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Viewbox Stretch="Uniform"  Height="500" Width="500">
                        <Path Stroke="{Binding Stroke}"
                              StrokeThickness="{Binding StrokeThickness}"
                              Fill="{Binding Fill}"
                              Data="{Binding Data}"
                              Tag="{Binding Tag}"
                        </Viewbox>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>

as i said in the title my goal is to fit those paths inside a border and as you can see in my code i used Viewbox to stretch the paths but the problem is it stretches each and every path inside the list to fill the size (500*500) distorting the form of the vector graphics.. i want the scaling to happen to all the list at once as an entity leaving the relative scale and locations of those paths intact.

A: The following simplified example shows how to put a list of Geometry items in a scalable ItemsControl. It is necessary that you set the Width and Height of the ItemsControl.
<Viewbox>
    <ItemsControl Width="500" Height="500">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Path Stroke="Black" StrokeThickness="3" Data="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.Items>
            <EllipseGeometry Center="150,150" RadiusX="100" RadiusY="100"/>
            <EllipseGeometry Center="350,350" RadiusX="100" RadiusY="100"/>
        </ItemsControl.Items>
    </ItemsControl>
</Viewbox>


text:
Q: Capture SQL before ExecuteNonQuery, ExecuteReader statement without modifying current logic In my current project, they have built huge application which is not using any ORM but does all CRUD operations using dynamic SQL and then using ExecuteNonQuery, ExecuteReader or ExecuteScalar.
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Connection.Open();
    command.ExecuteNonQuery();   // want to capture queryString before execution
}

There is no logging to capture SQL text so I am thinking if I can handle and "PreExecute" event for above 3 methods, I can put this logging right there and does have to modify their tons of DAO files.
I did not find anything related to such PreExecute event so how can we do that? I read about wrapper class but did not exactly get how it would help me?


text:
Q: ¿Cómo detectar el cambio de valor en una celda de un DataGridView? Cómo podría controlar los cambios que se hagan dentro de una celda de un DataGridView?
Quiero decir, necesito que cuando el valor de una celda se modifique, entonces yo pueda hacer algo.
Intenté utilizar el "CellValueChanged" pero no me funcionó. Alguien tiene alguna idea de alguna otra forma de controlar eso?
Gracias desde ya.


text:
Q: What jquery dialog box is your preferred one? I have been googling for a while looking for good, flexible and easy to use dialog box, but still can't find the right one, maybe you guys can tell me what's your preferred one?
I found some of them:
nyrodev
this list has 10 examples
And jquery.Dialog() of course
Please, only one plugin for each answer so we can select the best one.

A: I would suggest this one:
Facebox
http://www.electrictoolbox.com/jquery-facebox-opaque-background/

A: jQuery UI dialog() is very flexible and it's built in, why use anything else.


text:
Q: Numbering cells in a grid using opencv python I have created grids on an image with open cv, and I am trying to number the cells created from 1,2,3,4,5,... This image shows what the result of this code is. Does anyone have an idea of how to get all the cells numbered in python ?
x = 0
y = 0
k = 0
while x < self.img.shape[1]:
    cv2.line(self.img, (x, 0), (x, self.img.shape[0]), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1)

    while y < self.img.shape[0]:
          cv2.line(self.img, (0, y), (self.img.shape[1], y), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1)
           y += 100
           k += 1
           cv2.putText(self.img, str(k),
                    (x,y), font,
                    1, (0, 255, 255),
                    1, cv2.LINE_AA)

    x += 100


text:
Q: how to get N records from a model per parent ? In laravel eloquent How can i get n records from a model per parent in laravel eloquent.
For example lets say i have products table and categories table. And i want a list of all the products who's name starting with A  but not more then 10  products per category.
My table structure is something like this.
products table
---------------------------------
id  | title | slug | category_id
----------------------------------

Category table
--------------
id  | title |
--------------

I tried to follow this example which is exactly what i want
https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/
But when i tried to query just like the example in the link after adding the scope in my  product model . It throwing and sql error saying.

SQLSTATE[HY000]: General error: 1267 Illegal mix of collations
  (utf8mb4_unicode_ci,IMPLICIT) and (utf8mb4_0900_ai_ci,IMPLICIT) for
  operation '=' (SQL: select count(*) as aggregate from...

Can anyone please tell how i can get n results per related model or how can i fix this error.

A: There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class Category extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Product extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then you can apply limit()/take() to your relationship:
Category::with(['products' => function($query) {
    $query->where('name', 'LIKE', 'A%')->limit(10);
}])->get();

A: Pass a query when you call relation:
Category::with(['products' => function($query){
    $query->take(10)->skip(0);
}])->get();

Assuming you have a relation in your Category model.
public function products()...

A: First lets create your models:
class Category extends Model
{
    public $timestamps = false;

    protected $fillable = [

       'title'];

    public function products(){
    return $this->hasMany(\App\Products::class)->limit(10);
}
}

and the second one:
class Products extends Model
{
    public $timestamps = false;

    protected $casts = [
        'category_id' => 'int',
    ];

    protected $fillable = [

       'title',
        'slug'
    ];

    public function category()
    {
        return $this->belongsTo(\App\Category::class);
    }
}

Using eloquent the following would be:
$Category = Category::get();

You can also use starts_with() to define the column, word

A: From how I see it, for each categoryID you need an array of 10 products to be listed. Using Eloquent, this is what I came up with
$categories = Category::all()
productsArray = array();
foreach($categories as $category) {
        $products = Product::where('category_id', $category->id)->where('title', 'LIKE', 'A%')->get();
        if(sizeof($products)) {
            $products = $products->take(10);
            $productsArray[$category->id] = $products;
        }
    }
return $productsArray;

The only down side I see in this is the looping for each category ID, which might take more time if you have thousands of records. You can have any other key, other than $category->id if you wish to show it in your blade file.


text:
Q: Why doesn't $\sum_{n=1}^\infty \frac{1}{n^{1+\frac{1}{n}}}$ converge? $\sum_{n=1}^\infty \frac{1}{n^{1+\frac{1}{n}}} = \infty$. Is there a comparison that works well to prove this?

A: Alternatively, you can use the limit comparison test. Since
$$\lim_{n\to \infty} n\cdot \frac{1}{n^{1 + 1/n}} = \lim_{n\to \infty} \frac{1}{n^{1/n}} = 1$$
and $\sum_{n = 1}^\infty \frac{1}{n}$ diverges, your series diverges by limit comparison.

A: Hint: Show that $n^{1/n}$ is bounded above, so that $\frac{1}{n^{1+1/n}}>\frac{C}{n}$ for some constant $C$.


text:
Q: Is $\mathbb{Q} \times \mathbb{Q} \cup \mathbb{I} \times \mathbb{I}$ disconnected?
Let $\mathbb{I}$ be the set of all irrational real numbers and $\mathbb{Q}$ be the set of all rational numbers as usual. As a subspace of the Euclidean plane $\mathbb{R}^2$, is the set  $\mathbb{Q} \times \mathbb{Q} \cup \mathbb{I} \times \mathbb{I}$ disconnected?

The story is the following.
I was making a typical undergraduate level topology problem which concerns connectedness. The question which I concerned is the following.
As a subspace of the Euclidean plane $\mathbb{R}^2$, is the set $\mathbb{Q} \times \mathbb{I} \cup \mathbb{I} \times \mathbb{Q}$ connected? What about the set  $\mathbb{Q} \times \mathbb{Q} \cup \mathbb{I} \times \mathbb{I}$ ?
The former is relatively well known. For second, the solution which I had in mind turned out to be wrong. I guess lines of the form $y=qx$ where $q$ is some positive rationals will connect the set which is apparently wrong. Now I have no solution.
Please give some help to resolve this problem.

A: The set is connected.
Suppose that the set is disconnected by disjoint open sets $U$ and $V$. So, we assume that $\mathbb{Q}\times\mathbb{Q} \cup \mathbb{I}\times\mathbb{I}\subseteq U\cup V$ and $U\cap V=\phi$.
Find open balls $B_U \subseteq U$ and $B_V\subseteq V$. Then we can find a line of the form $y=q_1x + q_2$ with $q_1\in \mathbb{Q}-\{0\}$, $q_2\in\mathbb{Q}$ such that the line goes through both balls. Note that this line takes rational to rational, irrational to irrational. Thus, $\{(x,y)|y=q_1x+q_2\}\subseteq\mathbb{Q}\times\mathbb{Q} \cup \mathbb{I}\times\mathbb{I}$.
However, since $U$ and $V$ disconnects the set $\mathbb{Q}\times\mathbb{Q} \cup \mathbb{I}\times\mathbb{I}$, so we can find a point on the line that does not belong to any of $U$ or $V$. This is a contradiction.

A: Here's a slightly different way to think about it in terms of components:
Suppose $(a,b), (c,d) \in \mathbb{Q}^2.$  Then the lines
$$x+y = a+b \\ x-y = c-d$$
are continuous paths in $\mathbb{Q}^2 \cup \mathbb{I}^2 \subset \mathbb{R}^2$ containing $(a,b), (c,d)$ respectively and intersecting at $\left(\frac{1}{2}(a+b+c-d), \frac{1}{2}(a+b-c+d)\right).$  In particular, this shows that $\mathbb{Q}^2$ lies in a single path-component of $\mathbb{Q}^2 \cup \mathbb{I}^2.$  Therefore (since path components refine connected components) there is a connected component $C \subseteq \mathbb{Q}^2 \cup \mathbb{I}^2$ such that $\mathbb{Q}^2 \subseteq C.$
Finally, since $\mathbb{Q}^2$ is dense in $\mathbb{R}^2,$ it is also dense in any subspace containing it, showing that
$$C \subseteq \mathbb{Q}^2 \cup \mathbb{I}^2 = \text{cl}(\mathbb{Q}^2) \subseteq \text{cl}(C) = C$$
so $\mathbb{Q}^2 \cup \mathbb{I}^2 = C$ is connected.

A: Let $S = \mathbb{Q}^2 \cup \mathbb{I}^2$. For each nonzero rationals $q$, let $L_q$ be the line through the origin with slope $q$. Then $L_q \subseteq S$. Let $T=\bigcup_{q \in \mathbb{Q}\setminus \left\{0 \right\}} L_q$. Then $T$ is connected in $S$. Moreover $\overline{T}$ relative to $S$ itself is equal to $S$. Therefore $S$ is connected.


text:
Q: Add value (n+1) in last empty row I have a problem, I don't know how create button in a Google spreadsheet which will find the last empty row and add in first column next number (n+1) and in second column actual date.

function selectFirstEmptyRow() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  sheet.setActiveSelection(sheet.getRange("A" + getFirstEmptyRowWholeRow()))
  // copy value from row
  var ss = SpreadsheetApp.getActiveSheet();

  ss.insertRowAfter(ss.getLastRow());
  ss.getRange(1, 1).copyTo(ss.getRange(ss.getLastRow() + 1, 1));

  // add 1
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeRange = ss.getActiveRange();
  var cell, cellValue, cellFormula;

  // iterate through all cells in the active range
  for (var cellRow = 1; cellRow <= activeRange.getHeight(); cellRow++) {
    for (var cellColumn = 1; cellColumn <= activeRange.getWidth(); cellColumn++) {
      cell = activeRange.getCell(cellRow, cellColumn);
      cellFormula = cell.getFormula();

      if (cellFormula[0] != "=") {
        cellValue = cell.getValue();
        cell.setValue(cellValue + 1);
      }
    }
  }
}

function getFirstEmptyRowWholeRow() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var values = range.getValues();
  var row = 3;
  for (var row = 3; row < values.length; row++) {
    if (!values[row].join("")) break;
  }
  return (row + 1);
}

A: You can add a custom menu to a Google spreadsheet:
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My menu')
      .addItem('Add new date row', 'insertAtNextEmptyRow')
      .addToUi();
}

function insertAtNextEmptyRow() {
  var firstRow = 3;

  var sheet = SpreadsheetApp.getActiveSheet();
  var row = getNextEmptyRow(firstRow);
  var previousNum = SpreadsheetApp.getActiveSheet().getRange('A' + (row - 1)).getValue()
  if (previousNum !== parseInt(previousNum, 10))
    previousNum = row - firstRow - 1;
  SpreadsheetApp.getActiveSheet().getRange('A' + row).setValue(previousNum + 1);
  var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
  SpreadsheetApp.getActiveSheet().getRange('B' + row).setValue(date);
}

function getNextEmptyRow(firstRow) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  var values = range.getValues();

  for (var row = firstRow; row < values.length; row++) {
    if (!values[row].join(""))
      return (row + 1);
  }
  return null;
}

Here is what it'll look like:


text:
Q: Merging two data.tables with many to one realtionship in R? I have two data.table(s) where table 'DT1' is a master, and I want to merge data from a second table 'DT2' that has rows that match one or more of the rows in 'DT1'. I want to preserve all columns of DT1 and add additional columns from DT2(which are going to repeat eventually).
DT1:
ID          DEP CAT BCC value
ZCC81899ZZ  31,HH2  2,039   BCC1    0
ZZ02362D    2FF2,2F 02,06   BCC1    0
ZZ42716D    384,338 2   BCC1    0
ZZ64457TZZ  389,391 01,02   BCC1    1
ZCC81899ZZ  31,HH2  20,390  BCC2    1
ZZ02362D    2FF2,2  2   BCC2    1
ZZ42716D    384,338 2   BCC2    1
ZZ64457TZZ  389,391 01,02   BCC2    1
ZZ66595ZZ   14,191  11,072  BCC2    0
ZCC81899ZZ  31,HH2  203 BCC6    0
ZZ02362D    2FF2    2   BCC6    1
ZZ42716D    384,338 2   BCC6    0
ZZ64457TZZ  389,391 01,02   BCC6    0
ZZ66595ZZ   141,914 11,072  BCC6    0

DT2:
BCC    LABEL     CO     IN
BCC1   Dim1      0.47   1.904
BCC2   Dim2      0.535  0.575
BCC6   Dim3      0.44   0.344

So I want to merge these two data.table(s) with key BCC and result should be :
DT1:
ID          DEP CAT BCC value    LABEL    CO    IN
ZCC81899ZZ  31,HH2  2,039   BCC1    0        Dim1     0.47  1.904
ZZ02362D    2FF2,2F 02,06   BCC1    0        Dim1     0.47  1.904
ZZ42716D    384,338 2   BCC1    0        Dim1     0.47  1.904
ZZ64457TZZ  389,391 01,02   BCC1    1        Dim1     0.47  1.904
ZCC81899ZZ  31,HH2  20,390  BCC2    1        Dim2     0.535 0.575
ZZ02362D    2FF2,2  2   BCC2    1        Dim2     0.535 0.575
ZZ42716D    384,338 2   BCC2    1        Dim2     0.535 0.575
ZZ64457TZZ  389,391 01,02   BCC2    1        Dim2     0.535 0.575
ZZ66595ZZ   14,191  11,072  BCC2    0        Dim2     0.535 0.575
ZCC81899ZZ  31,HH2  203 BCC6    0        Dim3     0.44  0.34
ZZ02362D    2FF2    2   BCC6    1        Dim3     0.44  0.34
ZZ42716D    384,338 2   BCC6    0        Dim3     0.44  0.34
ZZ64457TZZ  389,391 01,02   BCC6    0        Dim3     0.44  0.34
ZZ66595ZZ   141,914 11,072  BCC6    0        Dim3     0.44  0.34

I am doing the following:
> setkey(DT1, BCC)
> setkey(DT2, BCC)
> DT1[DT2, `:=`(LABEL= i.LABEL, CO = i.CO), IN = i.IN)]

It is giving the results same as DT1 and I tried DT1[DT2] that also gave the same result. I have no idea where I am missing this. This should work I guess. Any help is appreciated.
* The issue is that I am generating DT1 after using "melt" operation and when I am calling    BCC value (factor : datatype) and all coming as . When I passing both tables as command it is working fine. So I figured that this is the issue with the results after melt operation. Is there any other way of reshaping data in data.table?

A: the merge command allows for one to many merges, by default it only keeps the inner join (when the 2 tables match), but using the commands all= ; all.x and all.y allow you to do any other option you want
the help page for merge makes this clear


text:
Q: C++ high precision time measurement in Windows I'm interested in measuring a specific point in time down to the nanosecond using C++ in Windows. Is this possible? If it isn't, is it possible to get the specific time in microseconds at least?. Any library should do, unless I suppose it's possible with managed code.
thanks

A: For future reference, with Windows Vista, 2008 and higher, Windows requires the hardware support "HPET". This operates independently of the CPU and its clock and frequency. It is possible to obtain times with accuracies to the sub-microsecond.
In order to implement this, you DO need to use QPC/QPF. The problem is that QPF (frequency) is a NOMINAL value, so using the raw calls will cause time drifts that can exceed minutes per day. In order to accound for this, you have to measure the actual frequency and check for its drift over time as heat and other physical operating conditions will affect it.
An article that describes this can be found on MSDN (circa 2004!) at this link.
http://msdn.microsoft.com/en-us/magazine/cc163996.aspx
I did implement something similar to this myself (and just found the above link today!) but prefer not to use "microsecond time" because the QPC call itself is rather lengthy compared to other Windows calls such as GetSystemTimeAsFileTime, and synchronization adds more overhead. So I prefer to use millisecond timestamps (approx 70% less call time than using QPC) especially when I'm trying to get the time hundreds of thousands of times per second.

A: The best choice are the functions QueryPerformanceCounter and QueryPerformanceFrequency.
Microsoft has just recently (2014) released more detailed information about QueryPerformanceCounter:
See Acquiring high-resolution time stamps (MSDN 2014) for the details.
This is a comprehensive article with lots of examples and detailed description. A must read for users of QPC.

A: I think microseconds is a bit unreasonable (without hardware assistance).  Milliseconds is doable, but even then not that accurate due to various nefarious counter resolution issues.  Regardless, I include my own timer class (based on std::chrono) for your consideration:
#include <type_traits>
#include <chrono>

class Stopwatch final
{
public:

    using elapsed_resolution = std::chrono::milliseconds;

    Stopwatch()
    {
        Reset();
    }

    void Reset()
    {
        reset_time = clock.now();
    }

    elapsed_resolution Elapsed()
    {
        return std::chrono::duration_cast<elapsed_resolution>(clock.now() - reset_time);
    }

private:

    std::chrono::high_resolution_clock clock;
    std::chrono::high_resolution_clock::time_point reset_time;
};

Note that under the hood on Windows std::chrono::high_resolution_clock is using QueryPerformanceCounter, so it's just the same but portable.

A: If you have a threaded application running on a multicore computer QueryPerformanceCounter can (and will) return different values depending on which core the code is executing on. See  this MSDN article. (rdtsc has the same problem)
This is not just a theoretical problem; we ran into it with our application and had to conclude that the only reliable time source is timeGetTime which only has ms precision (which fortunately was sufficient in our case). We also tried fixating the thread affinity for our threads to guarantee that each thread always got a consistent value from QueryPerformanceCounter, this worked but it absolutely killed the performance in the application.
To sum things up there isn't a reliable timer on windows that can be used to time thing with micro second precision (at least not when running on a multicore computer).

A: MSDN claims that -

A Scenario object is a highly-accurate timer that logs ETW events
  (Event Tracing for Windows) when you start and stop it. It's designed
  to be used for performance instrumentation and benchmarking, and comes
  in both C# and C++ versions. ... As a rule of thumb on modern
  hardware, a call to Begin() or End() takes on the order of a
  microsecond, and the resulting timestamps are accurate to 100ns (i.e.
  0.1 microseconds). ... Versions are available for both .NET 3.5 (written in C#), and native C++, and run on both x86 and x64
  platforms. The Scenario class was originally developed using Visual
  Studio 2008, but is now targeted at developers using Visual Studio
  2010.]

From Scenario Home Page. As far as i know, it was provided by the same people as PPL.
Addionaly you can read this High Resolution Clocks and Timers for Performance Measurement in Windows.

A: In newer Windows versions you probably want GetSystemTimePreciseAsFileTime. See Acquiring high resolution timestamps.
Lots of this varies a rather unfortunate amount based on hardware and OS version.

A: If you can use the Visual Studio compiler 2012 or higher, you can well use the std::chrono standard library.
#include <chrono>

::std::chrono::steady_clock::time_point time = std::chrono::steady_clock::now();

Note that the MSVC 2012 version may be only 1ms accurate. Newer versions should be accurate up to a microsecond.

A: Windows has a high-performance counter API.
You need to get the ticks form QueryPerformanceCounter and divide by the frequency of the processor, provided by QueryPerformanceFrequency.
LARGE_INTEGER frequency;
if (::QueryPerformanceFrequency(&frequency) == FALSE)
    throw "foo";

LARGE_INTEGER start;
if (::QueryPerformanceCounter(&start) == FALSE)
    throw "foo";

// Calculation.

LARGE_INTEGER end;
if (::QueryPerformanceCounter(&end) == FALSE)
    throw "foo";

double interval = static_cast<double>(end.QuadPart - start.QuadPart) / frequency.QuadPart;

This interval should be in seconds.

A: You can use the Performance Counter API as Konrad Rudolf proposed, but should be warned that it is based on the CPU frequency.  This frequency is not stable when e.g. a power save mode is enabled.  If you want to use this API, make sure the CPU is at a constant frequency.
Otherwise, you can create some kind of 'statistical' system, correlating the CPU ticks to the PC BIOS clock.  The latter is way less precise, but constant.

A: using QueryPerformanceCounter (for windows)

A: With respect to Konrad Rudolph's answer, note that in my experience the frequency of the performance counter is around 3.7MHz, so sub-microsecond, but certainly not nanosecond precision.  The actual frequency is hardware (and power-save mode) dependent.  Nanosecond precision is somewhat unreasonable in any case since interrupt latencies and process/thread context switching times are far longer than that, and that is also the order of magnitude of individual machine instructions.

A: rdtsc instruction is  the most  accurate.

A: Here is a Timer class that will work both for Windows and Linux :
#ifndef INCLUDE_CTIMER_HPP_
#define INCLUDE_CTIMER_HPP_

#if defined(_MSC_VER)
#  define NOMINMAX // workaround a bug in windows.h
#  include <windows.h>
#else
#  include <sys/time.h>
#endif

namespace Utils
{
   class CTimer
   {
   private:
#     if defined(_MSC_VER)
         LARGE_INTEGER m_depart;
#     else
         timeval m_depart;
#     endif

   public:
      inline void start()
      {
#        if defined(_MSC_VER)
            QueryPerformanceCounter(&m_depart);
#        else
            gettimeofday(&m_depart, 0);
#        endif
      };

      inline float GetSecondes() const
      {
#        if defined(_MSC_VER)
            LARGE_INTEGER now;
            LARGE_INTEGER freq;

            QueryPerformanceCounter(&now);
            QueryPerformanceFrequency(&freq);

            return (now.QuadPart - m_depart.QuadPart) / static_cast<float>(freq.QuadPart);
#        else
            timeval now;
            gettimeofday(&now, 0);

            return now.tv_sec - m_depart.tv_sec + (now.tv_usec - m_depart.tv_usec) / 1000000.0f;
#        endif
      };
   };
}
#endif // INCLUDE_CTIMER_HPP_

A: Thanks for the input...though I couldn't get nano, or microsecond resolution which would have been nice, I was however able to come up with this...maybe someone else will find it usefull.
    class N_Script_Timer
{
    public:
        N_Script_Timer()
        {
            running = false;
            milliseconds = 0;
            seconds = 0;
            start_t = 0;
            end_t = 0;
        }
        void Start()
        {
            if(running)return;
            running = true;
            start_t = timeGetTime();
        }
        void End()
        {
            if(!running)return;
            running = false;
            end_t = timeGetTime();
            milliseconds = end_t - start_t;
            seconds = milliseconds / (float)1000;
        }
        float milliseconds;
        float seconds;

    private:
        unsigned long start_t;
        unsigned long end_t;
        bool running;
};