text:
Q: Nest JSON output (list of children) within its parent (household) JSON using GSON Goal is to avoid using JSONObject() and JSONArray() which requires manually putting each key/value pair, hence GSON or related solutions are appreciated.
I have two objects i.e. 1) Household, 2) Household Members with following properties as JSON (also same in model/pojo class)
Household:
{
    "household": {
        "hh_id": "1",
        "avg_expense": "2",
        "avg_income": "2",
        "beneficiary": "3278963",
        "beneficiary_id": "2342343242342",
        "beneficiary_name": "name"

    }
}

Household Members:
{
    "household_member": [{
        "age": "11",
        "creation_date": "2022-03-20 02:28:44",
        "disability": "1",
        "disability_oth": "",
        "disease": "1",
        "dob": "2011-03-20",
        "education": "1",
        "family_no": "1",
        "gender": "1",
        "hh_id": "1",
        "hh_mem_uuid": "7c828e43-b681-4e09-8cc4-279505244a24"
    }, {
        "age": "11",
        "creation_date": "2022-03-20 02:28:44",
        "disability": "1",
        "disability_oth": "",
        "disease": "1",
        "dob": "2011-03-20",
        "education": "1",
        "family_no": "1",
        "gender": "1",
        "hh_id": "1",
        "hh_mem_uuid": "7c828e43-b681-4e09-8cc4-279505244a24"
    }]
}

Generated using :
gson.toJson(household)
gson.toJson(household_members)

Is there any helper function in GSON library where I could possibly define children (household member) under its parent (household), similar to putting an a JSON array within an object like below:
jHHObject.put("household_member", jHouseholdMemberArray)

Which desire-ably results in below JSON:
{
    "household": {
        "hh_id": "1",
        "avg_expense": "2",
        "avg_income": "2",
        "beneficiary": "3278963",
        "beneficiary_id": "2342343242342",
        "beneficiary_name": "name",

        "household_member": [{
            "age": "11",
            "creation_date": "2022-03-20 02:28:44",
            "disability": "1",
            "disability_oth": "",
            "disease": "1",
            "dob": "2011-03-20",
            "education": "1",
            "family_no": "1",
            "gender": "1",
            "hh_id": "1",
            "hh_mem_uuid": "7c828e43-b681-4e09-8cc4-279505244a24"
        }, {
            "age": "11",
            "creation_date": "2022-03-20 02:28:44",
            "disability": "1",
            "disability_oth": "",
            "disease": "1",
            "dob": "2011-03-20",
            "education": "1",
            "family_no": "1",
            "gender": "1",
            "hh_id": "1",
            "hh_mem_uuid": "7c828e43-b681-4e09-8cc4-279505244a24"
        }]

    }
}

Model: Household:
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey

@Entity(tableName = "household")
open class Household {

    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
    var hh_uuid: String
    var creation_date: String
    var district: String
    var district_name: String
    var tehsil: String
    var tehsil_name: String
    var uc: String
    var uc_name: String
    var rv: String
    var rv_name: String
    var enumerator: String
    var enumerator_name: String
    var household: String
    var household_name: String
    var respondent_name: String
    var beneficiary: String
    var beneficiary_name: String
    var beneficiary_cnic: String
    var cell: String
    var young_couples: String
    var couples: String
    var total_hh_members: String
    var total_hh_male_18: String
    var total_hh_female_18: String
    var total_hh_male_17: String
    var total_hh_female_17: String
    var total_hh_male_5: String
    var total_hh_female_5: String
    var avg_income: String
    var avg_expense: String
    var earning_hand: String
    var family_prefer: String
    var taken_loan: String
    var taken_loan_amount: String
    var own_livestock: String
    var cow: String
    var sheep: String
    var camel: String
    var horse: String
    var comments: String
    var version_code: String
    var version_name: String
    var status_sent: String = "0"

    constructor(

        hh_uuid: String,
        creation_date: String,
        district: String,
        district_name: String,
        tehsil: String,
        tehsil_name: String,
        uc: String,
        uc_name: String,
        rv: String,
        rv_name: String,
        enumerator: String,
        enumerator_name: String,
        household: String,
        household_name: String,
        respondent_name: String,
        beneficiary: String,
        beneficiary_name: String,
        beneficiary_cnic: String,
        cell: String,
        young_couples: String,
        couples: String,
        total_hh_members: String,
        total_hh_male_18: String,
        total_hh_female_18: String,
        total_hh_male_17: String,
        total_hh_female_17: String,
        total_hh_male_5: String,
        total_hh_female_5: String,
        avg_income: String,
        avg_expense: String,
        earning_hand: String,
        family_prefer: String,
        taken_loan: String,
        taken_loan_amount: String,
        own_livestock: String,
        cow: String,
        sheep: String,
        camel: String,
        horse: String,
        comments: String,
        version_code: String,
        version_name: String,
        status_sent: String

    ) {
        this.hh_uuid = hh_uuid
        this.creation_date = creation_date
        this.district = district
        this.district_name = district_name
        this.tehsil = tehsil
        this.tehsil_name = tehsil_name
        this.uc = uc
        this.uc_name = uc_name
        this.rv = rv
        this.rv_name = rv_name
        this.enumerator = enumerator
        this.enumerator_name = enumerator_name
        this.household = household
        this.household_name = household_name
        this.respondent_name = respondent_name
        this.beneficiary = beneficiary
        this.beneficiary_name = beneficiary_name
        this.beneficiary_cnic = beneficiary_cnic
        this.cell = cell
        this.young_couples = young_couples
        this.couples = couples
        this.total_hh_members = total_hh_members
        this.total_hh_male_18 = total_hh_male_18
        this.total_hh_female_18 = total_hh_female_18
        this.total_hh_male_17 = total_hh_male_17
        this.total_hh_female_17 = total_hh_female_17
        this.total_hh_male_5 = total_hh_male_5
        this.total_hh_female_5 = total_hh_female_5
        this.avg_income = avg_income
        this.avg_expense = avg_expense
        this.earning_hand = earning_hand
        this.family_prefer = family_prefer
        this.taken_loan = taken_loan
        this.taken_loan_amount = taken_loan_amount
        this.own_livestock = own_livestock
        this.cow = cow
        this.sheep = sheep
        this.camel = camel
        this.horse = horse
        this.comments = comments
        this.version_code = version_code
        this.version_name = version_name
        this.status_sent = status_sent

    }

}

Model: Household Member
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "household_member")
class HouseholdMember {

    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
    var hh_id: String
    var creation_date: String
    var household_id: String
    var hh_uuid: String
    var hh_mem_uuid: String
    var hh_member_bisp_id: String
    var hh_member_bisp_name: String
    var hh_name_ent: String
    var mem_name: String
    var dob: String
    var age: String
    var family_no: String
    var gender: String
    var marital_status: String
    var has_cnic: String
    var cnic: String
    var disability: String
    var disability_oth: String
    var disease: String
    var education: String
    var work: String
    var income: String
    var skill: String
    var skill_oth: String
    var beneficiary: String

    constructor(
        hh_id: String,
        creation_date: String,
        household_id: String,
        hh_uuid: String,
        hh_mem_uuid: String,
        hh_member_bisp_id: String,
        hh_member_bisp_name: String,
        hh_name_ent: String,
        mem_name: String,
        dob: String,
        age: String,
        family_no: String,
        gender: String,
        marital_status: String,
        has_cnic: String,
        cnic: String,
        disability: String,
        disability_oth: String,
        disease: String,
        education: String,
        work: String,
        income: String,
        skill: String,
        skill_oth: String,
        beneficiary: String

    ) {

        this.hh_id = hh_id
        this.creation_date = creation_date
        this.household_id = household_id
        this.hh_uuid = hh_uuid
        this.hh_mem_uuid = hh_mem_uuid
        this.hh_member_bisp_id = hh_member_bisp_id
        this.hh_member_bisp_name = hh_member_bisp_name
        this.hh_name_ent = hh_name_ent
        this.mem_name = mem_name
        this.dob = dob
        this.age = age
        this.family_no = family_no
        this.gender = gender
        this.marital_status = marital_status
        this.has_cnic = has_cnic
        this.cnic = cnic
        this.disability = disability
        this.disability_oth = disability_oth
        this.disease = disease
        this.education = education
        this.work = work
        this.income = income
        this.skill = skill
        this.skill_oth = skill_oth
        this.beneficiary = beneficiary

    }

}

A: The easiest solution would be to add a household_members field to your household class; maybe this question can be helpful for this as well.
If that is not possible (or the overhead this creates for Room is not desired), you could use Gson to first serialize your household class to an in memory JSON document in the form of Gson's JsonObject, then serialize your household members to JSON as well and add them to the JsonObject. Afterwards you can convert the JsonObject to a JSON document string.
For example:
Gson gson = new Gson();
JsonObject householdJsonObject = gson.toJsonTree(household).getAsJsonObject();
JsonArray householdMembersJsonArray = gson.toJsonTree(householdMembers).getAsJsonArray();
householdJsonObject.add("household_members", householdMembersJsonArray);

// Convert the final JSON object to a JSON document string
// Any other toJson overload works as well, e.g. toJson(..., writer)
String json = gson.toJson(householdJsonObject);


text:
Q: devise-jwt does not check password_confiramtion on sign-up How to add password_confirmation and force "devise-jwt" to check it with given password?
I prepared Back-end and Front-end according to this:
Devise API Authentication With Vue JS | Ruby on Rails 7 Tutorial
here you can get source code:
github: Deanout/devise-vue-api

From postman when I send request:
POST

body:
{
    "user": {
        "email": "admin2@gmail.com",
        "password": "password",
        "password_confirmation": "password_INVALID",
        "nickname": "admin2"
    }
}

result is:
{
    "message": "Signed up sucessfully.",
    "user": {
        "id": "ac6758e1-120e-4c15-b5db-ea52b291f924",
        "email": "admin2@gmail.com",
        "created_at": "2022-03-30T22:02:39.980Z",
        "updated_at": "2022-03-30T22:02:39.980Z",
        "nickname": "admin2",
        "first_name": null,
        "last_name": null
    }
}

Probabbly validation will not be enougth:
validates :password_confirmation, presence: true

What is more this password is not checked, I asked this question here:
devise-jwt does not check password on sign-in

My user.rb file looks like this:
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         #  :recoverable, :rememberable, :validatable
         :jwt_authenticatable,
         jwt_revocation_strategy: JwtDenylist

  scope :only_id_and_nickname, -> { select(:id, :nickname) }

  validates :nickname, presence: true
  validates :nickname, uniqueness: true
end

A: Try to change validates :password_confirmation, presence: true
to
validates :password_confirmation, presence: true, on: :create

redpajama_set_name: RedPajamaStackExchange


text:
Q: Good practice: Constant to non-constant cast When a function doesn't modify an object argument, I always make it ask for a constant reference even if the referenced object isn't really constant. Is this wrong?
For a wrapper class, I'd like to write this:
template<class B>
class Wrapper{
private:
  B* base_;
public:
  Wrapper(const B& b) { base_ = const_cast<B*>(&b); }
  void ModifyBase();
};

The constructor doesn't modify the base so it asks for a constant reference.
The wrapper have some methods who will need to modify the base so it needs to store a non-constant pointer (thus the conversion).
I feel my solution is not the best.
Is there a better way to do this?
Is there any accepted convention?

A: When you choose your parameter to be a const reference, you're telling the user "You can trust that if you pass me an object, it will not get modified [through this reference]†." You should do that as often as possible, because the user can understand more about what your function will and won't do just from looking at the types. Also, passing around mutable references can lead to code that is difficult to reason about.
However, in your question, your const is not telling the truth. It is casting away the constness and storing a non-const pointer - this means the object may very well get modified. You lied to the user! It doesn't matter that the constructor itself does nothing to do the object. It allows it to be modified by other member functions. This is bad behaviour. Your constructor should not take a const reference.
Not only that, but your current implementation allows undefined behaviour. Even if an object that is originally declared as const is given to your Wrapper, it doesn't care. It casts away it's constness and allows the other member functions to modify it. Modifying an object that was originally const is undefined behaviour.
† See 6502's comment

A: It doesn't really matter that the ctor won't alter the object in the ctor, what happens after the ctor is done is why you need a non-const object pointer to B.  So it has to do with ownership and lifetime of the B object passed in:  if you want to take ownership (via the & reference, then the object must be non-const because it can be altered.  If you want to simply copy the B object passed in, then don't use a refernce, pass by value and store a pointer to the copy.


text:
Q: Error converting data type varchar to int This is my stored procedure code
ALTER procedure [Proc_Add_User]
    (@UserId varchar(20),
     @UserName varchar(100),
     @Page_Name varchar(20),
     @AccessIndicator int,
     @CreatedBy varchar(50),
     @returnStatus varchar(50) output)
as
   DECLARE @intErrorCode INT
DECLARE @Page_Indicator INT
begin
BEGIN TRAN
Set @Page_Indicator = (select Page_Indicator from Pages where Page_Name=@Page_Name);
if (select count(*) from Users where UserId=@UserId and UserName=@UserName) > 0 begin
    if (select count(*) from User_Credentials where Page_Indicator=@Page_Indicator and
    UserId=@UserId  ) > 0
    set @returnStatus='User already has access'
    else
    insert into User_Credentials(UserId,Page_Indicator,Access_Indicator,CreatedBy)
        values (@UserId,@Page_Indicator,@AccessIndicator,@CreatedBy)
    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM
end
else begin
    insert into Users(UserId,UserName,CreatedBy)
    values(@UserId,@UserName,@CreatedBy)
    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM
    insert into User_Credentials(UserId,Page_Indicator,Access_Indicator,CreatedBy)
        values (@UserId,@Page_Indicator,@AccessIndicator,@CreatedBy)
    SELECT @intErrorCode = @@ERROR
    IF (@intErrorCode <> 0) GOTO PROBLEM
end
COMMIT TRAN
if(@returnStatus is null)
    set @returnStatus='Success';
PROBLEM:
IF (@intErrorCode <> 0) BEGIN
set @returnStatus= 'Unexpected error occurred!'
ROLLBACK TRAN
end
end

And I am calling this from the code pasted below:
Con.Open();
cmd = new OleDbCommand();
cmd.Connection = Con;

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Proc_Add_User";

cmd.Parameters.Clear();
cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = userLanId;
cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("@Page_Name", SqlDbType.VarChar).Value = pageName;
cmd.Parameters.Add("@AccessIndicator", SqlDbType.Int).Value = accessIndicator;
cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = createdBy;

OleDbParameter output = new OleDbParameter("@returnStatus", SqlDbType.VarChar);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);

int result = cmd.ExecuteNonQuery();

I am getting the error mentioned at the ExecuteNonQuery statement. What's confusing to me is I am able to execute the stored procedure in SSMS but not from my application (front-end). I provided the same values too yet it fails from my app.
I double checked to make sure the order of parameters passed match and are of same data type but still it throws this error. I can paste my stored proc code here if wanted so let me know..Thanks in advance!
EDIT
OOPS! I just realized that all the inserts are all happening and getting committed fine in the database. It's just this error is getting caught inside catch block in my app. Any ideas?
I can not ignore it because based on the return value of ExecuteNonQuery(), I have some statements and also it's not going through the code present after ExecuteNonQuery().

A: This is most likely because you are using SqlDbType with OleDbParameters:
OleDbParameter output = new OleDbParameter("@returnStatus", SqlDbType.VarChar);

This causes .NET to use the OleDbParameter(String, Object) constructor, setting the value of the parameter to SqlDbType.VarChar which it assumes is an int.
You should use this instead:
OleDbParameter output = new OleDbParameter("@returnStatus", OleDbType.VarChar);

And change your calls to cmd.Parameters.Add to use OleDbType as well.
Alternatively, you could use System.Data.SqlClient instead of OleDb


text:
Q: Finding nth degree polynomial functions I need to find an nth degree polynomial function that has real coefficients using the following conditions:
n=3; 3 and 4i are zeros; f(2)=40
I have no idea what I'm doing on this one. It's been too long. Also, there's no homework tag because this isn't something I have to do. I'm just brushing up in preparation for an upcoming math course.

A: We want $3$ and $4i$ to be roots. If a real polynomial has a complex root, the conjugate also is a root. So we can just write down a polynomial that has exactly these roots:
\begin{align*}
f(x)=(x-3)(x-4i)(x+4i)=(x-3)(x^2+16)
\end{align*}
which indeed has only real coefficients and is of degree $3$. But the value at $2$ is not $40$ but $-20$ so the polynomial you are looking for is $g(x)=-2f(x)$.


text:
Q: Bind click event to a collection of svg paths at runtime in angular 5 In my Angular 5 project I am trying to bind a click event to each of the paths of an svg object that gets dynamically loaded. I have successfully bound a click event to one path element using the following code:
constructor(private elemRef: ElementRef) { }

mapEventInit() {
        this.elemRef.nativeElement.querySelector('.country')
        .addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
        console.log(event.target.id);
}

The problem is that querySelector only lets me bind to the first element in the collection of elements with the .country class. Is there a proper 'angular' way to do this or should I just use regular typescript, as follows?
const pathCollection = document.querySelectorAll('.country');
for (let i = 0; i < pathCollection.length; i++) {
  pathCollection[i].addEventListener('click', function(event) {
    console.log(this.id);
  });
}


text:
Q: how to set the path of live sass compiler to be the current path in VsCode I have below folder structure:
-src
  -component
    -button
      -button.js
      -button.scss
    -dropdown
      -dropdown.js
      -dropdown.scss

When I use live sass compiler to watch the scss file, it generates 2 files like button.css and button.css.map, but it does not generate in the same path.
I want these generated files to be generated in the same path like below:
-src
  -component
    -button
      -button.js
      -button.scss
      -button.css
      -button.css.map
    -dropdown
      -dropdown.js
      -dropdown.scss
      -dropdown.css
      -dropdown.css.map

In setting.json
{
    "editor.wordWrap": "on",
    "workbench.iconTheme": "eq-material-theme-icons",
    "liveSassCompile.settings.formats": [

        {
            "format": "expanded",
            "extensionName": ".css",
            "savePath": "/dist/css"
        }
    ]
}

How should I do it?

A: In setting.json
{
    "editor.wordWrap": "on",
    "workbench.iconTheme": "eq-material-theme-icons",
    "liveSassCompile.settings.formats": [

        {
            "format": "expanded",
            "extensionName": ".css",
            "savePath": null
        }
    ]
}


text:
Q: Git merge not showing merge commit but showing all commits Given I have two branches master and BranchA. BranchA came off master.
I was on BranchA and did a git pull and it was successful.
I then did a git fetch followed by git merge origin/master.
It then stated that the Merge made by the 'recursive' strategy and was successful.
When I tried to do git push I got a warning and stated the remote contains work I did not have locally. After doing a git pull again I can see git apply commits that look to be part of my merge of master.
My query is that my merge did not show as a merge commit but seems to show each of the commits that were in master but not in BranchA at the time of merging. Why would this occur?


text:
Q: (1) no such table from database, downloaded from URL I have a database on server as in-app purshase.
Downloading:
private static boolean downloadDatabase(Context context) {
    try {
           // Log.d(TAG, "downloading database");
            URL url = new URL("http://url/");
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();
            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = null;
            // Select storage location
            fos = context.openFileOutput(Global.getName(), Context.MODE_PRIVATE);

            fos.write(baf.toByteArray());
            fos.close();
           // Log.d(TAG, "downloaded");
    } catch (IOException e) {
            Log.e(TAG, "downloadDatabase Error: " , e);
            return false;
    }  catch (NullPointerException e) {
            Log.e(TAG, "downloadDatabase Error: " , e);
            return false;
    } catch (Exception e){
            Log.e(TAG, "downloadDatabase Error: " , e);
            return false;
    }
    return true;

This is DBHelper, where database is copying into data/data/... dir.
public class DBHelper extends SQLiteOpenHelper {

private static String DB_PATH = "/data/data/mypackage/databases";
public static String DB_NAME = Global.getName();
private static final int DB_VERSION = 1;
private static final String SP_KEY_DB_VER = "db_ver";

private SQLiteDatabase db;
private  Context context;

 public DBHelper(Context context) {

        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
        initialize();
    }

    private void initialize() {
        if (databaseExists()) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(context);
            int dbVersion = prefs.getInt(SP_KEY_DB_VER, 1);
            if (DB_VERSION != dbVersion) {
                File dbFile = context.getDatabasePath(DB_NAME);
                if (!dbFile.delete()) {
                    Log.w("MY APP", "Unable to update database");
                }
            }
        }
        if (!databaseExists()) {
            createDatabase();
        }
    }

    private boolean databaseExists() {
        File dbFile = context.getDatabasePath(DB_NAME);
        Log.e("TAG","database exist?"+dbFile.exists());
        return dbFile.exists();
    }

    /**
     * Creates database by copying it from assets directory.
     */
    private void createDatabase() {
        String parentPath = context.getDatabasePath(DB_NAME).getParent();
        String path = context.getDatabasePath(DB_NAME).getPath();
        File file = new File(parentPath);
        if (!file.exists()) {
            if (!file.mkdir()) {
                Log.w("MY APP", "Unable to create database directory");
                return;
            }
        }

        InputStream is = null;
        OutputStream os = null;
        try {
            is = context.openFileInput(Global.getDictionary());
            os = new FileOutputStream(path);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void openDataBase() throws SQLException{

        String myPath = DB_PATH + DB_NAME;
        db= SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }

    @Override
    public synchronized void close() {

            if(db != null)
                db.close();

            super.close();

    }

public String getStr() {
    databaseExists();
    SQLiteDatabase db = this.getReadableDatabase();
    String s=null;
    Cursor c = db.rawQuery("SELECT indexStr from tablename where id=2 ",null);
    while (c.moveToNext()) {
          s = c.getString(0);
    }
    c.close();
    db.close();
    return s;
}

@Override
public void onCreate(SQLiteDatabase arg0) {}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}

I see, that my app аfter downloading the database takes up more space of memory, but when I run any SELECT returns "(1) no such table", but database exists. May be database empty, but why?
P.S. all permissions as WRITE_EXTERNAL_STORAGE/READ_EXTERNAL_STORAGE written.

A: I think your table name is incorrect
  Cursor c = db.rawQuery("SELECT indexStr from tablename where id=2 ",null);

the name of the table is really "tablename" ???
Check the value of
public static String DB_NAME = Global.getName();

probably you are reading a different Database!.

A: Try adding this code to the onCreate() method and see if the error goes off.
SQLiteDatabase db2 = openOrCreateDatabase("dbname", Context.MODE_PRIVATE, null);
    db2.execSQL("CREATE TABLE IF NOT EXISTS table_name(row1 INT PRIMARY KEY, row2 VARCHAR, row3 VARCHAR, row4 VARCHAR, );");

If it does, that means your table was not created according to the way you tried before.
The best way for you to check if the database is populated, is by clicking on DDMS and checking if the database file is created under your project. If it is created, pull the file from the device, and viewing it through a SQLite DB browser like SQLiteBrowser


text:
Q: Is it appropriate to divide a rate evenly among individual units? I am working with a rate of effort on a project. Since I think my question would apply to any type of rate, let's use something like miles per hour (mph) for simplicity's sake. Let's say I have a group of four cars with an average speed of 80 mph; I don't know what each car's distance or time is so I must distribute evenly among all four cars. Therefore, I say each car traveled 20 miles in 0.25 hours. I don't know the right words, but to me, distance and time are like single units, so they can be divided in this way. This results in EACH car going an average speed of 80 mph, as well as the whole group going an average speed of 80 mph. Again, this makes sense to me because a rate shouldn't be divided among parts to add up to a whole (at least, I think).
Here's the question: someone told me that the way I should be attributing the rate to each car is to divide distance as I have done, but leave the denominator (time) the same, resulting in each car traveling 20 miles in one hour, such that each car has traveled at an average speed of 20 mph. Then to get the total speed of the group, you add the rate of speed of each car. According to this person, if you want the rate PER CAR, you have to leave per car in the denominator -- in other words, if you divide the distance per car and the time per car, then your average speed does not end up being the speed per car because you're canceling this out (which is what I have above).
I'm not sure if we are actually trying to answer two different questions here? I feel like I almost understand what the other person is trying to say, but I just don't quite get it. I am hoping someone here who understands this more intuitively than I do might be able to break it down for me. Thanks for any help!

A: Let total distance travelled = $d$. Then the individual distances travelled are $d_1,d_2,d_3,d_4$ such that $d=d_1+d_2+d_3+d_4$. Let $t$ be the total time taken, and $t_1,t_2,t_3,t_4$ be the individual times. Finally, let the rates (velocities in this case) be $v_1,v_2,v_3,v_4$, with the group rate (or in this case average velocity) being $v$.
Now we have
\begin{array}{|r|r|r|r|}
\hline
v_1 = \frac{d_1}{t_1} &v_2 = \frac{d_2}{t_2}&v_3 = \frac{d_3}{t_3} &v_4= \frac{d_4}{t_4}\\
d_1 = v_1t_1 &d_2 = v_2t_2 &d_3 = v_3t_3 &d_4= v_4t_4\\
\hline
\end{array}
Then
\begin{align*}
v&=\frac{d}{t}\\&= \frac{d_1+d_2+d_3+d_4}{t_1+t_2+t_3+t_4}\\&= \frac{v_1t_1+v_2t_2 +v_3t_3 +v_4t_4}{t_1+t_2+t_3+t_4}
\end{align*}
Assumption 1: all units are weighted equally. Say $t_1=t_2=t_3=t_4 = k$. Then we have
\begin{align*}
v&= \frac{v_1k+v_2k +v_3k +v_4k}{4k}\\
&= \frac{v_1+v_2 +v_3 +v_4}{4}\\
\end{align*}
Assumption 2: all rates are the same. Say $v_1=v_2=v_3=v_4 = u$. Then we have
\begin{align*}
v&= \frac{v_1+v_2 +v_3 +v_4}{4}\\
&= \frac{u+u +u +u}{4}\\
&=u
\end{align*}
Conclusion: So group rate $v$ is equal to individual rate $u$ under the given assumptions.


text:
Q: Fluent NHibernate Mapping help I am getting the following error:
Invalid index 3 for this OracleParameterCollection with Count=3
when i am attempting to insert a new column into a table.
my entity class is:
public class Operator
{
    public Operator()
    {
        this.OperatorMemberships = new List<OperatorMembership>();
    }
    public virtual int Id { get; set; }
    public virtual int OperatorMembershipId { get; set; }
    public virtual int SchemeId { get; set; }
    public virtual string Description { get; set; }
    public virtual IList<OperatorMembership> OperatorMemberships { get; set; }
}

public class OperatorMembership
{
    public virtual int Id { get; set; }
    public virtual int OperatorId { get; set; } // delete
    public virtual int UserRoleId { get; set; } // delete
    public virtual UserRole UserRole { get; set; }
    public virtual Operator Operator { get; set; }
}

My mappings are:
public OperatorMap()
    {
        Table("OPERATOR");
        Id(x => x.Id, "OPERATOR_ID").GeneratedBy.Identity();
        Map(x => x.SchemeId, "SCHEME_ID");
        Map(x => x.Description, "DESCRIPTION");
        //HasMany(x => x.OperatorMemberships).Inverse().AsBag().Cascade.AllDeleteOrphan();
        HasMany(x => x.OperatorMemberships).Inverse().AsBag();
        //References(x => x.SchemeServices, "OPERATOR_ID");
    }
}

public class OperatorMembershipMap : ClassMap<OperatorMembership>
{
    public OperatorMembershipMap()
    {
        Table("USER_OPERATOR_MEMBERSHIP");
        Id(x => x.Id, "USER_OPERATOR_MEMBERSHIP_ID").GeneratedBy.Identity();
        Map(x => x.OperatorId, "OPERATOR_ID");
        Map(x => x.UserRoleId, "USER_ROLE_ID");

        References(x => x.Operator).Column("OPERATOR_ID"); ;
        References(x => x.UserRole).Column("USER_ROLE_ID");
    }
}

the code to insert the new row is:
public int AddOperatorMembership(int operatorId, int userRoleId)
    {
        OperatorMembership op = new OperatorMembership();
        op.OperatorId = operatorId;
        op.UserRoleId = userRoleId;
        _provider.AddEntity(op);

        return op.Id;
    }

and my database table is:
USER_OPERATOR_MEMBERSHIP_ID -- OPERATOR_ID -- USER_ROLE_ID

any help would be good, i am sure there are some very clever fluent nhibernate developers out there who can spot the error straight away.
many thanks.
Randolf.

A: You're mapping the referenced entities AND the foreign key :
public OperatorMembershipMap()
{
    Table("USER_OPERATOR_MEMBERSHIP");
    Id(x => x.Id, "USER_OPERATOR_MEMBERSHIP_ID").GeneratedBy.Identity();
    // Map(x => x.OperatorId, "OPERATOR_ID");
    // Map(x => x.UserRoleId, "USER_ROLE_ID");

    References(x => x.Operator).Column("OPERATOR_ID"); ;
    References(x => x.UserRole).Column("USER_ROLE_ID");
}

You can also remove the foreign keys from your entity :
public class OperatorMembership
{
    public virtual int Id { get; set; }
    // public virtual int OperatorId { get; set; } // delete
    // public virtual int UserRoleId { get; set; } // delete
    public virtual UserRole UserRole { get; set; }
    public virtual Operator Operator { get; set; }
}

A: I too came across the same issue and ended up googling for half a day but no success. The above answer given by Mathieu seemd relevant and i tried the same but did not work for me. Then i tried with removing references and keeping the properties intact, it worked for me and hope will work for you as well.
    Table("USER_OPERATOR_MEMBERSHIP");
    Id(x => x.Id, "USER_OPERATOR_MEMBERSHIP_ID").GeneratedBy.Identity();
    Map(x => x.OperatorId, "OPERATOR_ID");
    Map(x => x.UserRoleId, "USER_ROLE_ID");

    //References(x => x.Operator).Column("OPERATOR_ID"); ;
    //References(x => x.UserRole).Column("USER_ROLE_ID");

Remove the same from class as well
public class OperatorMembership
{
     public virtual int Id { get; set; }
     public virtual int OperatorId { get; set; } // delete
     public virtual int UserRoleId { get; set; } // delete
     //public virtual UserRole UserRole { get; set; }
     //public virtual Operator Operator { get; set; }
}


text:
Q: Function is trying to convert to boolean somewhere I have a function in Winforms VB.Net and when I call this function I keep getting an exception saying I can't convert a String to Boolean. However, I can't see where it is trying to convert anything to a Boolean. Code is below
Public Async Function UploadArrayToDropbox(client As DropboxClient, folder As String, fileName As String, fileArray As ArrayList) As Task
    Dim stream As New MemoryStream

    Using r As StreamWriter = New StreamWriter(stream)
        For i As Integer = 0 To fileArray.Count - 1
            r.WriteLine(fileArray(i).ToString)
        Next
        r.Flush()
        stream.Position = 0

        Using rd As StreamReader = New StreamReader(stream)

            Dim response = Await client.Files.UploadAsync(Convert.ToString(folder & Convert.ToString("/")) & fileName, WriteMode.Overwrite.Instance, rd.ReadToEnd)
            rd.Close()
        End Using
        r.Close()
    End Using

End Function

A: Dim response = Await client.Files.UploadAsync(Convert.ToString(folder & Convert.ToString("/")) & fileName, WriteMode.Overwrite.Instance, rd.ReadToEnd)

Should be
Dim response = Await client.Files.UploadAsync(Convert.ToString(folder & Convert.ToString("/")) & fileName, WriteMode.Overwrite.Instance, body:=rd)

From Maurice ;)


text:
Q: how to design a database model to record client's history activity? In my App,a question answering application.I seleced MySql as its database.Once user A answer user B's question Q in time X,I should push a message to B that A had answered Q.Reasonablly,I should also record these two things,one is for A that you answer B's question Q in time X,another one is for B that you question Q is answered by A in time X.Correspondingly,these records should be able to be reviewed by users in the future.
  How I should to design a db system to save these user historys?
I have three tables:

*

*one is for question items

It include a field question_item_xmltree_path saving answer_item_id answerig this question by json just like ["120","121","122"],I know it's a very bad way.
one

*one is for key items

including some fields descripting keys like raiser_name raising_time

A: You are going about this the wrong way.
Think of the way you described your entities in text - there are users, questions and answers. Those are the main entities of the system and should be the main tables in your database. Since a user can post many questions, while each question may be posted by a single user, you have a 1:m relationship between these tables. Same goes for questions and answers, and for users and answers.
Long story short - start with this basic design:
TblUsers (user details)
TblQuestions (question details, and an fk to tblusers, for the user that asked the question)
TblAnswers (answer details, an fk to tblusers for the user that posted the answer, and an fk to tblquestions for the question that it belongs to).

From this structure you can get all the information you need for a basic q&a application.


text:
Q: Showing that if an equation has a unique solution for one variable, then it has unique solutions for all. I have a problem and a proposed solution. Please tell me if I'm correct.
Problem: Let $A$ be a square matrix. Show that if the system $AX=B$ has a unique solution for some particular column vector B, then it has a unique solution for all $B$.
Solution: If $AX=B$ has a unique solution for some column vector $B$, then $A$ in reduced row echelon form has a pivot in each column and $A$ can be reduced to $I_n$, for $A$,$\\ n \times n$. Since the number of equations = the number of unknowns, we will have column vector $(n \times 1)$ of $x_i$'s  = column vector $n \times 1$ of $b_i$'s. Hence, varying $B$ is equivalent to varying $X$ and will create a new solution for every change made to $B$.
Thanks!

A: Hence, varying B is equivalent to varying X and will create a new solution for every change made to B.
This statement is not precise.  There are several ways to fix it, depending on how much you know.  Do you know what non-singular matrices are?  Do you know that they are invertible and that if $A$ can be reduced to $I_n$ then it is nonsingular?  If you know that $A$ is invertible then from $AX = B$ you can write $X = A^{-1}B$ so there is only one choice for $X$ no matter what $B$ is.
Another way of seeing that the solution is unique (that doesn't use non-singularity explicitly) is the following.  As $A$ reduces to $I_n$, when you reduce the augmented matrix $[A \ | \ B]$ do any of the choices you make depend on $B$?  Try arguing that no matter what that last column is, reducing the augmented matrix will always yield something with a pivot in each of the first $n$ columns.  Thus there will be no independent variables in your solution.  I suspect that this is what you had in mind with what you wrote, but you should explain it a little further.

A: Your argument is essentially correct, but the end of it is a bit vague. What you've shown is that if $AX=B$ has a unique solution for some $B$, then $A$ can be row-reduced to $I_n$. This row-reduction is independent of the augmentation column in the augmented matrix, so for any $n\times 1$ column vector $C$ we can row-reduce the augmented matrix $[A\mid C]$ to some $[I_n\mid Y]$, and $Y$ will be the unique solution to $AX=C$. Thus, $AX=C$ has a unique solution for each $C$.
There are many ways to see why this shows that $A$ is invertible (non-singular). If you know that when $[A\mid I_n]$ can be row-reduced to something of the form $[I_n\mid D]$, then $D=A^{-1}$, the result is clear. If you know that row-reduction can be accomplished by premultiplying by elementary matrices, then you can argue that row-reducibility of $A$ to $I_n$ means that there are elementary matrices $E_1,\dots,E_m$ such that $E_mE_{m-1}\dots E_2E_1A=I_n$ and hence $E_mE_{m-1}\dots E_2E_1=A^{-1}$.


text:
Q: get file input values from array - PHP I have a block of PHP which sits onto a form I have where I have multiple file input form elements allowing the form user to upload files. This works well, but I want to be able to return the filename / path of the server for where the file has been uploaded - but cant seem to work out how to do this - currently the value of the field comes back as "array".
Any ideas on how to get the actual uploaded path and filename for each input?
// initialize output;
$output = true;

// valid extensions
$ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg', 'jpeg', 'png', 'eps', 'svg', 'gif', 'ai');

// create unique path for this form submission
//$uploadpath = 'assets/uploads/';

// you can create some logic to automatically
// generate some type of folder structure here.
// the path that you specify will automatically
// be created by the script if it doesn't already
// exist.

// UPLOAD TO FOLDER IN /ASSETS/UPLOADS/ WITH ID OF THE PARENT PROJECT FOLDER RESOURCE

// Get page ID
// $pageid = $modx->resource->get('id');
// $uploadpath = 'assets/uploads/'.$pageid.'/';

// Get parent page title
$parentObj = $modx->resource->getOne('Parent');
$parentpageid = $parentObj->get('pagetitle');
$uploadpath = 'assets/uploads/'.$parentpageid.'/';

// get full path to unique folder
$target_path = $modx->config['base_path'] . $uploadpath;

// get uploaded file names:
$submittedfiles = array_keys($_FILES);

// loop through files
foreach ($submittedfiles as $sf) {

// Get Filename and make sure its good.
$filename = basename( $_FILES[$sf]['name'] );

// Get file's extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$ext = mb_strtolower($ext); // case insensitive

// is the file name empty (no file uploaded)
if($filename != '') {

    // is this the right type of file?
    if(in_array($ext, $ext_array)) {

        // clean up file name and make unique
        $filename = mb_strtolower($filename); // to lowercase
        $filename = str_replace(' ', '_', $filename); // spaces to underscores
        $filename = date("Y-m-d_G-i-s_") . $filename; // add date & time

        // full path to new file
        $myTarget = $target_path . $filename;

        // create directory to move file into if it doesn't exist
        mkdir($target_path, 0755, true);

        // is the file moved to the proper folder successfully?
        if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
            // set a new placeholder with the new full path (if you need it in subsequent hooks)
            $modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
            // set the permissions on the file
            if (!chmod($myTarget, 0644)) { /*some debug function*/ }

        } else {
            // File not uploaded
            $errorMsg = 'There was a problem uploading the file.';
            $hook->addError($sf, $errorMsg);
            $output = false; // generate submission error
        }

    } else {
        // File type not allowed
        $errorMsg = 'Type of file not allowed.';
        $hook->addError($sf, $errorMsg);
        $output = false; // generate submission error
    }

// if no file, don't error, but return blank
} else {
    $hook->setValue($sf, '');
}

}

return $output;


text:
Q: Angular dropdown with autocomplete I am using bootstrap with Angularjs.I have many drop down menus in my page and want to implement the functionality as there should be a textbox which on focus shows data in array and on typing shows autocomplete functionality.
I have tried 2 approaches with autocomplete but they just show data on typing.when we type nothing data in drop down isn't showing. like This Directive
<angucomplete id="ex1" placeholder="Select Nationality" selectedobject="std.NATIONALITY_ID" localdata="nationalities"    searchfields="description" titlefield="description" minlength="1"   inputclass="form-control form-control-small"/>
    </div>

This is showing data on typing only i want a
 list on focus and autocomplete on typing.Kindly suggest an approach or angular or bootstrap for this.

A: First of all, you should have read what they said about their module on their github:

NOTE: I no longer actively mantain this repository. I've started using ReactJS now and its a breath of fresh air compared to AngularJS. If you're still using Angular and need a autocomplete component I'd encourage you to look at this fork of my original Angucomplete: angucomplete-alt

To use the new module you just have to do some modifications that I've already made and it seems to work as you expected.
Snippet:

var app = angular.module('app', ['angucomplete-alt']);

app.controller('mainCtrl', function($scope) {
  $scope.selectedObj = {};
  $scope.nationalities = [
     {
        "NATIONALITY_ID": 1,
        "description":"Afghan"
     },
     {
        "NATIONALITY_ID": 2,
        "description":"Andorran"
     },
     {
        "NATIONALITY_ID": 3,
        "description":"Botswanan"
     },
     {
        "NATIONALITY_ID": 4,
        "description":"Brazilian"
     },
     {
        "NATIONALITY_ID": 5,
        "description":"Canadian"
     },
     {
        "NATIONALITY_ID": 6,
        "description":"Cypriot"
     }
  ];
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angucomplete-alt/2.4.1/angucomplete-alt.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <angucomplete-alt id="ex1"
    placeholder="Select Nationality"
    selected-object="selectedObj"
    local-data="nationalities"
    search-fields="description"
    title-field="description"
    minlength="1"
    inputclass="form-control form-control-small"
    match-class="highlight" />
</body>

</html>

You can check more examples here.

A: I hope this link help you for Autocomplete dropdown : http://embed.plnkr.co/jBJkDb But it's using ui-select please note that.


text:
Q: Get step function values from matplotlib I have 2 numpy arrays with data, say x,y, and I apply plt.step() and get a continues (step) curve of it.
I would like to be able to create this function by my own, meaning I want to have an (zero order hold) step approximation to the value of y for x that does not actually exist in the original x array.
For example, in the following link I want to have the 'new' actual rectangle sine values, and not only plotted:
https://matplotlib.org/gallery/lines_bars_and_markers/step_demo.html#sphx-glr-gallery-lines-bars-and-markers-step-demo-py

A: You can use scipy's interp1d to create a step function. Default the interpolation is 'linear', but you can change it to 'next', 'previous' or 'nearest' for a step function.
A standard step function is obtained from step_fun = interp1d(x, y, kind='previous') and then calling it as step_fun(new_x).
The following code compares different types of "interpolation":
from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import interp1d

x = np.random.uniform(0.1, 0.7, 20).cumsum()
y = np.sin(x)

kinds = ['linear', 'previous', 'next', 'nearest', 'cubic']
for i, kind in enumerate(kinds):
    function_from_points = interp1d(x, y + i, kind=kind)
    x_detailed = np.linspace(x[0], x[-1], 1000)
    plt.plot(x_detailed, function_from_points(x_detailed), color='dodgerblue')
    plt.scatter(x, y + i, color='crimson')
plt.yticks(range(len(kinds)), kinds)
plt.show()

A: You can choose tick values and corresponding function values whichever you want. This is an example not equally spaced arguments and their values:
x = np.arange(20) + np.random.random(20)/2
y = np.sin(x / 2)**2 + np.random.random(20)/5

Remark: these two arrays must have equal size. If you want your own custom function, you can use np.vectorise:
x = np.arange(20) + np.random.random(20)/2
func = np.vectorize(lambda x: np.sin(x) + np.random.random()/5)
y = func(x)


text:
Q: Colorbox IFrame opens a URL in the browser instead of a box I used Colorbox in my aspx project and I used the Iframe from example 1. I copied the css and js files mentioned in the html page but when clicking on the link, it opens up the page in the browser itself whereas I want it to show up in the box like in the examples.
Here's the code -
Click here

A: You need to render the colorbox in an element on the page:
Click here

A: You must instead do this -
 Click me


text:
Q: Which module is related to "Manage orders" (path : admin/commerce/orders)? I've a commerce kickstart (D7.15) up, everything work well, but the part of orders managing doesn't ...
That's located at this path : http://website/en/admin/commerce/orders (http://website/en#overlay=en/admin/commerce/orders & http://website/en?q=admin/commerce/orders don't work either)
I get this error :
"EntityMetadataWrapperException: Missing data values. in EntityMetadataWrapper->value() (line 83 of /Applications/MAMP/htdocs/website/profiles/commerce_kickstart/modules/contrib/entity/includes/entity.wrapper.inc)."
and this message :
"The website encountered an unexpected error. Please try again later."
The biggest problem is that I've no idea about which module is related to this interface, I need to know, then I could update it and/or try fix it by myself ...
Here the "Commerce" modules enabled :
Cart (commerce_cart) 7.x-1.4
Checkout (commerce_checkout) 7.x-1.4
Commerce (commerce) 7.x-1.4
Commerce Atos Payment method (commerce_atos) 7.x-1.0-beta3+1-dev
Commerce Discount (commerce_discount) 7.x-1.0-alpha1
Commerce Discount Date (commerce_discount_date) 7.x-1.0-alpha1
Commerce UI (commerce_ui) 7.x-1.4
Customer (commerce_customer) 7.x-1.4
Customer UI (commerce_customer_ui) 7.x-1.4
Line Item (commerce_line_item) 7.x-1.4
Line Item UI (commerce_line_item_ui) 7.x-1.4
Order (commerce_order) 7.x-1.4
Order UI (commerce_order_ui)  7.x-1.4
Payment (commerce_payment) 7.x-1.4
Payment UI (commerce_payment_ui) 7.x-1.4
Price (commerce_price)  7.x-1.4
Product (commerce_product) 7.x-1.4
Product Pricing (commerce_product_pricing) 7.x-1.4
Product Pricing UI (commerce_product_pricing_ui) 7.x-1.4
Product Reference (commerce_product_reference) 7.x-1.4
Product UI (commerce_product_ui)  7.x-1.4
Tax (commerce_tax) 7.x-1.4
Tax UI (commerce_tax_ui)  7.x-1.4
Checkout Redirect (commerce_checkout_redirect) 7.x-1.x-dev
Commerce (Product Display Manager) (commerce_pdm) 7.x-1.0-alpha3
Commerce Addressbook (commerce_addressbook) 7.x-2.0-rc3
Commerce Backoffice (commerce_backoffice) 7.x-2.0-rc1
Commerce Backoffice Order (commerce_backoffice_order) 7.x-2.0-rc1
Commerce Backoffice Product (commerce_backoffice_product) 7.x-2.0-rc1
Commerce Checkout Progress (commerce_checkout_progress) 7.x-1.2
Commerce Extra Price Formatters (commerce_extra_price_formatters) 7.x-1.1
Commerce File (commerce_file) 7.x-1.0-beta4+4-dev
Commerce Migrate (commerce_migrate)  7.x-1.0
Commerce Price Savings Formatter (commerce_price_savings_formatter) 7.x-1.3
Commerce Stock (commerce_stock) 7.x-1.1
Flat Rate (commerce_flat_rate) 7.x-1.x-dev
Shipping (commerce_shipping) 7.x-2.0
Shipping UI (commerce_shipping_ui) 7.x-2.0
Commerce Extra (commerce_extra) 7.x-1.0-alpha1+8-dev
Commerce Extra Address Populate (commerce_extra_address_populate)  7.x-1.0-alpha1+8-dev
Commerce Extra Login Page (commerce_extra_login_page) 7.x-1.0-alpha1+8-dev
Commerce Extra Quantity (commerce_extra_quantity)  7.x-1.0-alpha1+8-dev
Commerce Kickstart Block (commerce_kickstart_block) 7.x-2.0-rc1
Commerce Kickstart Blog (commerce_kickstart_blog) 7.x-2.0-rc1
Commerce Kickstart Checkout Redirect (commerce_kickstart_checkout_redirect) 7.x-2.0-rc1
Commerce Kickstart Comment (commerce_kickstart_comment) 7.x-2.0-rc1
Commerce Kickstart Content UI (commerce_kickstart_content_ui)  7.x-2.0-rc1
Commerce Kickstart Menus (commerce_kickstart_menus) 7.x-2.0-rc1
Commerce Kickstart Migrate (commerce_kickstart_migrate) 7.x-2.0-rc1
Commerce Kickstart Order (commerce_kickstart_order)  7.x-2.0-rc1
Commerce Kickstart Payment Example (commerce_kickstart_payment) 7.x-2.0-rc1
Commerce Kickstart Reset (commerce_kickstart_reset) 7.x-2.0-rc1
Commerce Kickstart Search (commerce_kickstart_search) 7.x-2.0-rc1
Commerce Kickstart service provider (commerce_kickstart_service_provider) 7.x-2.0-rc1
Commerce Kickstart User (commerce_kickstart_user) 7.x-2.0-rc1
Commerce Features (commerce_features) 7.x-1.0-rc1
Commerce Kickstart help (commerce_kickstart_help) 7.x-2.0-rc1
Here the "Order" modules enabled :
Order (commerce_order) 7.x-1.3+40-dev
Order UI (commerce_order_ui) 7.x-1.3+40-dev
(There are some "Order" modules already in the list above.)
Please halp me :(
Thank you .
Regards

A: I don't think your problem is with an order module. The problem will lie with one of the other modules that hook into the order process. You have quite a large number of commerce modules and finding the offending module may be difficult.
I do not use commerce kickstart though and am only really taking a guess. I would try posting this on the drupal commerce website http://www.drupalcommerce.org/


text:
Q: Syncfusion GridDataControl and DataContext Issue i needed to add a simple button in a GridDataControl. note complicated so far.
<syncfusion:GridDataVisibleColumn HeaderText="Open Unit" MappingName="JobNumber">
    <syncfusion:GridDataVisibleColumn.HeaderStyle>
        <syncfusion:GridDataColumnStyle HorizontalAlignment="Center" />
    </syncfusion:GridDataVisibleColumn.HeaderStyle>
    <syncfusion:GridDataVisibleColumn.CellItemTemplate>
        <DataTemplate>
            <Button HorizontalContentAlignment="Stretch"
                    VerticalContentAlignment="Stretch"
                    Name="cmdOpenUnit"
                    Click="cmdOpenUnit_Click"
                    Content="Open Unit" />
        </DataTemplate>
    </syncfusion:GridDataVisibleColumn.CellItemTemplate>
</syncfusion:GridDataVisibleColumn>

Now i tried the GridDataUnboundVisibleColumn but by using it i cannot use a mapping name therefore when i look for DataContext, there isn't any. So i used GridDataUnboundVisibleColumn and set MappingName="JobNumber" to a random data in the source just to make sure i have DataContext
The click event :
private void cmdOpenUnit_Click(object sender, RoutedEventArgs e)
{
    try
    {
        CUnit obj = ((Button)sender).DataContext as CUnit ;
    }
    catch { }
}

I have a grid with ObservableCollection<CProject> as Datasource then when you choose one the CProject.UnitList // <-- ObservableCollection<CUnit> become the Datasource of the currect grid i am working with. Therefore each row in the grid is a specific CUnit.
The problem is that the DataContext on ((Button)sender).DataContext is the JobNumber data in the Cunit object but i cannot get the parent property. i tried different casting but couldn't get anything yet. I have used this method a couple time with sucess but it's my first time doing this with syncfusion and they help files contains nothing about that.
the DataContext of the Sender i received is of type Syncfusion.Windows.Controls.Grid.GridDataCellBoundWrapper if that might help.

A: After couple message back and forth with Syncfusion, turns out the data context do not actually contain the data context per say. you need couple cast and mouse pointer location to find it out.


text:
Q: StimulSoft Report For ASP.NET MVC3 I'm new to ASP.NET MVC Razor. I want to use stimulsoft reporter to get report from my data. I have added two dlls to my project's reference, but none of the online solutions works for me. I want a resource to learn stimulsoft for MVC Razor. Can you help me?

A: Read Stimulsoft User Manual, Stimulsoft Programming Manual.
Look at the sample projects in Stimulsoft.Web distributive.


text:
Q: Laravel Adding Bulk data in Polymorphic Relationship Suppose we have this schema:
Set
    id
    name

Question
    questionable_type
    questionable_id
    content

And I have 100 question in array(see code below)
I initially thought of adding like this:
DB::('transactions',function() use..{
    $set = Set::create(['name'=>'hello']);

    $questions = [
        [
            'content' => 'A',
            'questionable_type'='App\Set',
            'questionable_id'=>$set->id,
            ...
        ]
        [
            'questionable_type'='App\Set',
            'questionable_id'=>$set->id,
            'content'=>'B'
            ...
        ]
        ...
    ]

    Question::insert($questions);
});

But the main problem is inside transaction i don't like to use App\Set And Questionable id ?
And do you have any good way for handling such polymorphic mass assignment relationship.
And you can imagine I am giving user to type 100 questions at first so I guess I should go on this way isn't it?
Thank you so much


text:
Q: If I enter the letters TL in cell A8, is there a way to turn that cell and multiple others in that row blue? If I enter the letters TL in cell A8, is there a way to turn that cell and multiple others in that row blue? Is there a way to have multiple letter/color variations?
I have 8 two letter combinations that correspond to 8 colors. For example:
TS=light blue  TC=medium blue  TL=dark blue     DD=black
RS=light green  RC=medium green  RL=dark green  LT=brown
I'd like to enter one of these these letter combinations into M8 & have columns, B,C,E,F,K-AM in row 8 turn the corresponding color. Is there a way to do that?

A:
If I enter the letters TL in cell A8 ... enter one of these these letter combinations into M8 & have columns, B,C,E,F,K-AM in row 8 ...

Your narrative is confusing. This code is for M8.
Adjust the worksheet name and the RGB parameters for the colours you want then run this code.
Option Explicit

Sub addCFRs()

    Dim i As Long, rng As Range, arr1 As Variant, arr2 As Variant

    arr1 = Array("TS", "TC", "TL", "DD", "RS", "RC", "RL", "LT")
    arr2 = Array(RGB(0, 0, 255), RGB(0, 0, 128), RGB(0, 0, 64), RGB(0, 0, 0), _
                 RGB(0, 255, 0), RGB(0, 128, 0), RGB(0, 64, 0), RGB(0, 0, 0))

    With Worksheets("sheet6")

        Set rng = Intersect(.Range("B:C, E:F, K:AM"), .Range("8:8"))

        With rng

            .FormatConditions.Delete

            For i = LBound(arr1) To UBound(arr1)

                .FormatConditions.Add Type:=xlExpression, Formula1:="=$M8=" & Chr(34) & arr1(i) & Chr(34)
                .FormatConditions(.FormatConditions.Count).Interior.Color = arr2(i)

            Next i

        End With

    End With

End Sub

Most of the RGBs are somewhat close to what you want except for brown; I have no idea what RGB makes up brown.

A: This can be done using conditional formatting.
You will need a separate formula for each colour.

*

*Highlight the cells you wish to change colour in row 8 (you can use Ctrl+click to select separate cells)

*Go to "Conditional Formatting" and select "New rule"

*Select "Use a formula to determine which cells to format"

*In the rule description type =$M8="TL"

*Click on "Format" and choose the "Fill" tab at the top

*Select the correct colour for the code

*Click OK and then OK again.
All done for row 8.

If you want it to do more rows, go to "Conditional Formatting" and select "Manage rules".
Select the icon to the right of the "Applies to" box and then highlight all the areas that you want to change colour. Again, you can use Ctrl to select separate areas. You can select entire columns if you want but this can slow the sheet down.
Once you have this set up you can repeat the process for the other colour codes, just replace TL in the formula with the code you wish to use.


text:
Q: Changing the window.scroll placement based on a media query? The site I'm working on has a "mandatory" Header at the top they won't let me remove. My workaround for this was to start the window scroll below that header with a body onLoad event, like such:
    <body <?php body_class(); ?> onLoad="window.scroll(0, 100)">

The issue comes up as I'm working on the sites responsive elements. When the screen hits the 400px media query, I hide that div entirely. Which means my site is still scrolling 100px down needlessly.
Is there a way to Change that window.scroll event to NOT scroll down, (or to scroll down less if they make me put the header back on mobile, albeit smaller) based on that media query?

A: You can play around with this fiddle
JAVASCRIPT:
$(window).load(function () {
    $('html, body').animate({
        scrollTop: $("#content").offset().top
    }, 1000);
});

Basically it scrolls to the element you want to show so if the header is not present the #content top will be 0 so it won't scroll.
Alternatively, you could use the code below which will scroll the site accordingly to the header's height. No header = no height = problem solved.
$(window).load(function () {
    $('html, body').animate({
        scrollTop: $("#header").height()
    }, 1000);
});


text:
Q: Break out of while loop that has an array inside Want to let the user make an array until they press cancel on the prompt
But the nested if statement won't trigger and break the while loop.
The goal of the program is to show the first ten items in the array with the message
'Only the first ten guests will be recorded'
This is part of my course which is why I am letting the user input as much as they like
and then reducing it to 10 after.
let guests = []
i = 1
j = 1

while (j = 1) {
    input = guests.push(prompt('Enter Guest' + i + '(press cancel to stop)'))
    i++

    if(input === null) {
        j++
        //break;
    }
}

if (guests.length > 10) {
    console.log('Only the first ten guests will be recorded')

    while (guests.length > 10) {
        guests.pop()
    }
}

console.log(guests)

If I remove the if() brackets the program stops after the user inputs one array item
And if I try break;
it stops after the user types in 1 array item.
I have also tried adding
    else {
        continue;
    }

but to no avail

A: Store the result of prompt to test for null (instead of comparing the return value of Array#push).
while (true) {
    input = prompt('Enter Guest' + i + '(press cancel to stop)');
    if(input === null) break;
    guests.push(input);
    i++;
}


text:
Q: Can not add iframe into page with contentscript chrome extension I'm writing a chrome extension and in contentscript, I try to append an iframe into page. Src of iframe is my html file. But it couldn't load the iframe, it showed 'page not found' instead.
 $('<iframe />');
  $('<iframe />', {
    name: 'frame1',
       id: 'frame1',
      src: 'iframe.html'
  }).appendTo('body');

A: You have to use this function to recieve the correct path
chrome.extension.getURL("iframe.html");


text:
Q: how MD5 signature affects the app security? I am planning to integrate a paid 3rd party SDK to my app. For that, 3rd party team asked to share my app package name and MD5 signature of app (Which is generated using another app provided by 3rd party company). I just want to know whether sharing the MD5 signature of my app affects the security of my app/code? Can somebody help me to get an idea on this?

A: MD5 was intended to provide integrity, not security. MD5 is a checksum, so It is supposed to be a short representation of potentionally infinite data. If you have a 1GB file, create an MD5 hash of it and flip a single bit within the 1GB file, the MD5 completly changes.
You will need the 1GB file, to calculate the MD5, you cannot get the 1GB file from the MD5.
I write intended since MD5 is concidered broken, an attacker could potentionally create content that is aimed to produce the same MD5.

A: No. MD5 is just hash (one way) function. It won't expose anything but the hashing result. Sharing it or making public poses any threat to your app/code.


text:
Q: MySQL updates getting stuck I have a Mediacore-based website that is getting stuck due to an update query. Those update queries are running all the time, but sometimes (I believe, during high traffic hours), one of those updates just becomes stuck, locking all other queries:
245     mediacore_user  localhost   mediacore   Query   36  Locked      UPDATE media SET modified_on='2011-12-21 09:42:58', views=(media.views + 1) WHERE media.id = 1048
246     mediacore_user  localhost   mediacore   Query   36  Locked      UPDATE media SET modified_on='2011-12-21 09:42:58', views=(media.views + 1) WHERE media.id = 1048
248     mediacore_user  localhost   mediacore   Query   36  Updating    UPDATE media SET modified_on='2011-12-21 09:42:58', views=(media.views + 1) WHERE media.id = 1048
249     mediacore_user  localhost   mediacore   Query   36  Locked      UPDATE media SET modified_on='2011-12-21 09:42:58', views=(media.views + 1) WHERE media.id = 1048
253     mediacore_user  localhost   mediacore   Query   36  Locked      UPDATE media SET modified_on='2011-12-21 09:42:58', views=(media.views + 1) WHERE media.id = 1048
258     mediacore_user  localhost   mediacore   Query   30  Locked      UPDATE media SET modified_on='2011-12-21 09:43:04', views=(media.views + 1) WHERE media.id = 416
268     mediacore_user  localhost   mediacore   Query   3   Locked      UPDATE media SET modified_on='2011-12-21 09:43:31', views=(media.views + 1) WHERE media.id = 1048
269     mediacore_user  localhost   mediacore   Query   3   Locked      UPDATE media SET modified_on='2011-12-21 09:43:31', views=(media.views + 1) WHERE media.id = 1048
270     mediacore_user  localhost   mediacore   Query   3   Locked      UPDATE media SET modified_on='2011-12-21 09:43:31', views=(media.views + 1) WHERE media.id = 1048
271     mediacore_user  localhost   mediacore   Query   3   Locked      UPDATE media SET modified_on='2011-12-21 09:43:31', views=(media.views + 1) WHERE media.id = 1048
272     mediacore_user  localhost   mediacore   Query   1   Locked      UPDATE media SET modified_on='2011-12-21 09:43:33', views=(media.views + 1) WHERE media.id = 1048

If I kill the "Updating" connection, another one gets stuck, and so on, until there are only about 3 queries left locked.
Any ideas?
Media table:
CREATE TABLE `media` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(8) DEFAULT NULL,
  `slug` varchar(50) NOT NULL,
  `podcast_id` int(11) DEFAULT NULL,
  `reviewed` tinyint(1) NOT NULL,
  `encoded` tinyint(1) NOT NULL,
  `publishable` tinyint(1) NOT NULL,
  `created_on` datetime NOT NULL,
  `modified_on` datetime NOT NULL,
  `publish_on` datetime DEFAULT NULL,
  `publish_until` datetime DEFAULT NULL,
  `title` varchar(255) NOT NULL,
  `subtitle` varchar(255) DEFAULT NULL,
  `description` text,
  `description_plain` text,
  `notes` text,
  `duration` int(11) NOT NULL,
  `views` int(11) NOT NULL,
  `likes` int(11) NOT NULL,
  `popularity_points` int(11) NOT NULL,
  `author_name` varchar(50) NOT NULL,
  `author_email` varchar(255) NOT NULL,
  `dislikes` int(11) NOT NULL,
  `popularity_likes` int(11) NOT NULL,
  `popularity_dislikes` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `slug` (`slug`),
  KEY `podcast_id` (`podcast_id`),
  CONSTRAINT `media_ibfk_1` FOREIGN KEY (`podcast_id`) REFERENCES `podcasts` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1049 DEFAULT CHARSET=utf8

INNODB Status after the problem happened:
=====================================
111221 12:12:09 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 6 seconds
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 78, signal count 78
Mutex spin waits 0, rounds 453, OS waits 17
RW-shared spins 122, OS waits 61; RW-excl spins 0, OS waits 0
------------
TRANSACTIONS
------------
Trx id counter 0 1115749
Purge done for trx's n:o < 0 1115735 undo n:o < 0 0
History list length 13
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 1115747, not started, process no 15360, OS thread id 140486827099904
MySQL thread id 111, query id 11647 localhost mediacore_user
---TRANSACTION 0 0, not started, process no 15360, OS thread id 140486827898624
MySQL thread id 106, query id 11651 localhost root
show innodb status
---TRANSACTION 0 1115709, not started, process no 15360, OS thread id 140486826567424
MySQL thread id 103, query id 10874 localhost mediacore_user
---TRANSACTION 0 1115731, not started, process no 15360, OS thread id 140486792349440
MySQL thread id 102, query id 11517 localhost mediacore_user
---TRANSACTION 0 1115668, not started, process no 15360, OS thread id 140486792881920
MySQL thread id 101, query id 10067 localhost 127.0.0.1 a7user
---TRANSACTION 0 1115737, not started, process no 15360, OS thread id 140486791816960
MySQL thread id 95, query id 11578 localhost mediacore_user
---TRANSACTION 0 1115738, not started, process no 15360, OS thread id 140486827366144
MySQL thread id 87, query id 11577 localhost mediacore_user
---TRANSACTION 0 1115744, not started, process no 15360, OS thread id 140486827632384
MySQL thread id 61, query id 11606 localhost mediacore_user
---TRANSACTION 0 1115746, not started, process no 15360, OS thread id 140486826301184
MySQL thread id 22, query id 11633 localhost mediacore_user
---TRANSACTION 0 1115748, ACTIVE 1 sec, process no 15360, OS thread id 140486826833664
mysql tables in use 1, locked 1
MySQL thread id 55, query id 11650 localhost mediacore_user Table lock
UPDATE media SET modified_on='2011-12-21 12:12:08', dislikes=10 WHERE media.id = 572
Trx read view will not see trx with id >= 0 1115749, sees < 0 1115740
---TRANSACTION 0 1115743, ACTIVE 14 sec, process no 15360, OS thread id 140486826034944
mysql tables in use 1, locked 1
MySQL thread id 23, query id 11601 localhost mediacore_user Table lock
UPDATE media SET modified_on='2011-12-21 12:11:55', views=(media.views + 1) WHERE media.id = 1048
Trx read view will not see trx with id >= 0 1115744, sees < 0 1115740
---TRANSACTION 0 1115742, ACTIVE 14 sec, process no 15360, OS thread id 140486825502464
mysql tables in use 1, locked 1
MySQL thread id 90, query id 11599 localhost mediacore_user Table lock
UPDATE media SET modified_on='2011-12-21 12:11:55', views=(media.views + 1) WHERE media.id = 1048
Trx read view will not see trx with id >= 0 1115743, sees < 0 1115740
---TRANSACTION 0 1115741, ACTIVE 14 sec, process no 15360, OS thread id 140486825768704 starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 368, 1 row lock(s)
MySQL thread id 73, query id 11596 localhost mediacore_user Updating
UPDATE media SET modified_on='2011-12-21 12:11:55', views=(media.views + 1) WHERE media.id = 1048
Trx read view will not see trx with id >= 0 1115742, sees < 0 1115740
------- TRX HAS BEEN WAITING 14 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 0 page no 1025 n bits 88 index `PRIMARY` of table `mediacore`.`media` trx id 0 1115741 lock_mode X locks rec but not gap waiting
Record lock, heap no 20 PHYSICAL RECORD: n_fields 27; compact format; info bits 0
 0: len 4; hex 80000418; asc     ;; 1: len 6; hex 00000011065c; asc      \;; 2: len 7; hex 00000003c20d5b; asc       [;; 3: len 5; hex 766964656f; asc video;; 4: len 30; hex 617273656c696f2d7061746f2d64652d63617276616c686f2d686f6d656e; asc arselio-pato-de-carvalho-homen;...(truncated); 5: len 4; hex 80000013; asc     ;; 6: len 1; hex 81; asc  ;; 7: len 1; hex 81; asc  ;; 8: len 1; hex 81; asc  ;; 9: len 8; hex 8000124a82217b0b; asc    J !{ ;; 10: len 8; hex 8000124a8230e083; asc    J 0  ;; 11: len 8; hex 8000124a82220ef0; asc    J "  ;; 12: SQL NULL; 13: len 30; hex 417273c3a96c696f205061746f2064652043617276616c686f20686f6d65; asc Ars  lio Pato de Carvalho home;...(truncated); 14: SQL NULL; 15: len 30; hex 3c703e43656e74726f206465204e6575726f6369c3aa6e63696173206520; asc <p>Centro de Neuroci  ncias e ;...(truncated); 16: len 30; hex 43656e74726f206465204e6575726f6369c3aa6e6369617320652042696f; asc Centro de Neuroci  ncias e Bio;...(truncated); 17: SQL NULL; 18: len 4; hex 80000000; asc     ;; 19: len 4; hex 80000099; asc     ;; 20: len 4; hex 80000000; asc     ;; 21: len 4; hex 80000000; asc     ;; 22: len 3; hex 554356; asc UCV;; 23: len 9; hex 7563764075632e7074; asc ucv@uc.pt;; 24: len 4; hex 80000000; asc     ;; 25: len 4; hex 80000000; asc     ;; 26: len 4; hex 80000000; asc     ;;

------------------
---TRANSACTION 0 1115740, ACTIVE 14 sec, process no 15360, OS thread id 140486792083200
2 lock struct(s), heap size 368, 1 row lock(s), undo log entries 1
MySQL thread id 97, query id 11597 localhost mediacore_user Table lock
SELECT 1
FROM media_fulltext
 LIMIT 1
Trx read view will not see trx with id >= 0 1115741, sees < 0 1115741
--------
FILE I/O
--------
I/O thread 0 state: waiting for i/o request (insert buffer thread)
I/O thread 1 state: waiting for i/o request (log thread)
I/O thread 2 state: waiting for i/o request (read thread)
I/O thread 3 state: waiting for i/o request (write thread)
Pending normal aio reads: 0, aio writes: 0,
 ibuf aio reads: 0, log i/o's: 0, sync i/o's: 0
Pending flushes (fsync) log: 0; buffer pool: 0
187 OS file reads, 469 OS file writes, 298 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 0.00 writes/s, 0.00 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 0, seg size 2,
0 inserts, 0 merged recs, 0 merges
Hash table size 2212699, node heap has 9 buffer(s)
0.17 hash searches/s, 0.17 non-hash searches/s
---
LOG
---
Log sequence number 0 148655397
Log flushed up to   0 148655397
Last checkpoint at  0 148655397
0 pending log writes, 0 pending chkp writes
177 log i/o's done, 0.00 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 1225697720; in additional pool allocated 11846912
Dictionary memory allocated 203840
Buffer pool size   65536
Free buffers       65299
Database pages     228
Modified db pages  0
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages read 225, created 3, written 259
0.00 reads/s, 0.00 creates/s, 0.00 writes/s
Buffer pool hit rate 1000 / 1000
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
6 read views open inside InnoDB
Main thread process no. 15360, id 140486801540864, state: sleeping
Number of rows inserted 13, updated 85, deleted 2, read 281971
0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.17 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

EDIT: Somehow, some of the updates are not unlocking the table after they commit. I watched the queries for quite some time and saw that after 50 seconds, the lock is freed and one update is executed. I've changed the innodb_lock_wait_timeout to 5 and I saw the same thing, only with intervals of 5 seconds instead of 50. But once it gets only a few updates left locked, they're all executed instantaneously... it's a very strange behavior...

A: A bit late but I'd like to add some more information: From my observation this happens if you have the full-text index enabled. In that case there seems to be a bad interaction in MySQL involving InnoDB (media table) and MyISAM (full-text index) locking.
I never saw the issue if MediaCore's full-text triggers were not installed.

A: I think it is because of the large number of queries at a time. Try using mysql index with your fields. It will speed up the performance.


text:
Q: Javascript toggle enabled/disabled What's the best way to toggle a "Please have Javascript enabled" warning?
Currently I've got something like this:

ONLY SQUARES DON'T USE JAVASCRIPT

to which I then apply .style.display = "none".
This shows the warning on every page for a little while until it loads.  There must be a more graceful way. Can I do it with PHP?
(BTW, get_browser() is not the solution I'm looking for.)
//EDIT
Thanks everyone, that does the trick.  Incidentally, to get the page to validate (XHTML 1.0 Strict), I needed to place the child node(s) in a block container.

A:
Please enable Javascript.

http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3.1

A: I think you're after the noscript tag:
ONLY SQUARES DON'T USE JAVASCRIPT

It's a browser convention, so you don't need to hide it when js is disabled (the browser does this automatically).

A: use the noscript tag

    You need to enable javascript to view this page!

A: Does you apply this rule when DomContentLoaded is fired?
There is  too but it seems to me chrome ignores it.

A: The best way is to … not. Build on things that work.
JavaScript support is not a binary state. People can turn it on. People can turn it off. JS files can fail to load (because a server is down, or blocked). JS can be selectively enabled (e.g. with the Firefox NoScript extension).
Better to use progressive enhancement.


text:
Q: Neo4J Admin visualization as a part of Rails Application I am working on a small internally deployed Rails Application in my organisation with Neo4J as persistence layer.
I want to allow users to be able to visually see the Data stored in the Database Browser provided by Neo4J and interact with it. ( Security is not a concern )
However I want to keep the experience seamless and provide the visualisation tool as a part of my web application.
Is there a work around for it?


text:
Q: REST API for a PHP Web application I am working on a API for my web application written in CodeIgniter. This is my first time writing a API.
What is the best way of imposing a API limit on the API?
Thanks for your time

A: Log the user's credentials (if he has to provide them) or his IP address, the request (optional) and a timestamp in a database.
Now, for every request, you delete records where the timestamp is more than an hour ago, check how many requests for that user are still in the table, and if that is more than your limit, deny the request.
Simple solution, keep in mind, though, there might be more performant solutions out there.
Pretty straight forward. If that doesn't answer your question, please provide more details.
I don't see how this is codeigniter related, for example.

A: You can use my REST_Controller to do basically all of this for you:
http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
I recently added in some key logging, request limiting features in so this can all be done through config.

A: One thing you can do is consider using an external service to impose API limits and provide API management functionality in general.
For example, my company, WebServius ( http://www.webservius.com ) provides a layer that sits in front of your API and can provide per-user throttling (e.g. requests per API key per hour), API-wide throttling (e.g. total requests per hour), adaptive throttling (where throttling limits decrease as API response time increases), etc, with other features coming soon (e.g. IP-address-based throttling). It also provides a page for user registration / issuing API keys, and many other useful features.
Of course, you may also want to look at our competitors, such as Mashery or Apigee.


text:
Q: Using Foreign Key on Django model to populate select input im having problems finding out on the documentation how to solve my problem so im posting here:
I have 3 Models one for a class room with its attributes, one for students and the last one a relation of the room and the student.
So on the template i want it to show a select button with a option value being the student id and the label being the student name
on my models.py i have this:
student_id = models.ForeignKey('Student', verbose_name=u"Student")

on my template.html i just call the field:
  {{ field }}

and the result that i get is:
<select name='student_id'>
  <option value='1'>Student object</option>
</select>

is there a way that i can preset the value and label like its done using choices for static data? to something like this:
STUDENT_CHOICES =(
    (model.student.id , model.student.name),
)
student_id = models.ForeignKey('Student', verbose_name=u"Student",, choices=STUDENT_CHOICES)

let me know if im not clear enough on the question since im fairly new to python and django

A: Turned out all i had to do was to set the default value to be returned by adding a unicode function to each model:
def __unicode__(self):
    return self.student_name

And the full model code below:
Class StudentRoom(models.Model):
    student_id  = models.ForeignKey('Student')
    room_id  = models.ForeignKey('Room')

Class Student(models.Model):
    student_name = models.CharField(max_length=100)
    student_email = models.CharField(max_length=100)

  def __unicode__(self):
    return self.student_name

Class Room(models.Model):
    room_name = models.CharField(max_length=100)
    room_faction = models.CharField(max_length=100)

  def __unicode__(self):
    return self.room_name


text:
Q: jQuery dataTables add multiple collapsible rows using the fnOpen() API function I am using the jQuery dataTables plugin to build advanced tables for our application. One of the requirements is to have "collapsible" rows (not groups!): e.g. rows represent campaigns, and they might have child campaigns. The structure of child rows is (in basic case) the same as in the parent table - same cells, same data types.
But, the child rows shouldn't affect the parent table itself: I mean, the number of rows per page should remain the same, child rows shouldn't be sorted separately from the parent row, they should always remain binded. Therefore I can't use fnAddData() API func for that.
And the other tricky requirement is the possibility to have multi-level collapsible rows (e. g. child campaigns for child campaigns, etc.)
I was using the fnOpen() API function for that, it allows to "open" any row, appends a child  block to it, and you can generally insert there whatever you want. It was working just fine in dataTables 1.8.2, i used code like this to generate child rows:
$(childRowData).each(function(){
    row = $(oTable.fnOpen(row.get(0), $(this), "child_row"));
    $(row).addClass('child_row');
});

Generally, it "opened" the current row (defined above), inserted data in the child row, then in the cycle "opened" the child row, added a child to it, etc.
But as of dataTables 1.9.0 looks like it is allowed only to "open" the parent rows, and only do it once.
Of course, I can create a sub-table, apply $.dataTable() to it and insert it to the child row, but it seems like a somewhat lame and expensive solution, especially when we might have 3-4 levels of depth.
Is there any other way to implement collapsible rows in dataTables?

A: Datatables has been updated somehow and it's very straight forward now for adding children rows to parent rows: http://datatables.net/reference/api/row().child()
One of the thing not really obvious, is in case you want to use the same layouts for your children rows like for the parent rows, you need to use the jquery selector, for passing a node instead of a string (written in the documentation but I missed it the first time).
Doint that is correct:
.child(
    $(
        '
'+
            ''+rowIdx+'.1	'+
            ''+rowIdx+'.2	'+
            ''+rowIdx+'.3	'+
            ''+rowIdx+'.4	'
        '
'
    )
)

But doing that is wrong: (it will insert your "tr" into a "td" with a colspan of the size of your table and it will obviously break the columns alignment)
.child(
    '
'+
        ''+rowIdx+'.1	'+
        ''+rowIdx+'.2	'+
        ''+rowIdx+'.3	'+
        ''+rowIdx+'.4	'
    '
'
)

A: When you create the child row that has subchildren, you're probally best off rolling your own solution.. I was doing some stuff similar to this a few weeks ago with datatables and that was the best I could come up with.


text:
Q: Email template HTML remove bullet points from ul I am currently  trying to make some email templates to be send via an Email client (SendGrid in this case). After doing some research on how to create these templates I came to the conclusion that using regular HTML & CSS is not the way to go since Mail client preprocessors (Mainly Gmail & Outlook) strip almost all styles which have been applied that are not inline. However I still am having one Issue.
I can't seem to get rid of the bullet points using List-style-type: none even inline on the UL and on each LI tag. Anybody has experience on how to remove bullet points from UL or an LI when it comes to Email templates?

A: You need to combine list-style: none; with a solution for Outlook, which is to conditionally push them away from sight, like so:
Put this in your  section:

With list:

content

content

Note that Outlook does not respect margins in
, and others have defaults, so it is best to always reset margins and paddings and then apply margins (not padding) in

A: You need to set list-style-type: none; to li element to remove bullet points.
To remove bullet from UL you can simply use list-style: none; or list-style-type: none; If still not works then i guess there is an issue of priority css. May be globally UL already defined. So best way add a class to that particular UL and add your css there. Hope it will works.

A: You may add list-style-type: none; to ol, ul tags
and to apply it forcefully you may add '!important'
e.g: list-style-type: none !important;

A: If the normal CSS isn't working, then you can try to set an blank 1x1 transparent image as the list markers.
ul.a {
    list-style-image: url('data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=');
}


text:
Q: Having different image url paths depending on stage to preface: Im running a vue / spring webapp. My application on localhost runs under
"localhost:8080/application/"
while on DEV and TEST it runs under http://application-dev/ and http://application-test/   - so the /application prefix is missing.
In my sass I have the following image url paths: url("/application/image.png")
And on the DEV and TEST webservers I made redirects from /application to / to have it find the images.
Now I want to remove the "/application" part from my images and still get it to work on localhost.
Is there any way I can have a variable in my sass like "{contextpath}/image.png" and let the Spring webapp fill in the contextpath depending on where its deployed? So if I deploy at localhost the path would be ="/application" and if I deploy on test it would need to be equal to an empty string.
Is this even possible? tyvm


text:
Q: What kind of virtual machine is BEAM (the Erlang VM)? From what I understand a virtual machine falls into two categories either "system virtual machine" or a "process virtual machine". It's kind of fuzzy to me where BEAM lies. Is there another kind of virtual machine I am not aware of?

A: Virtual machine is a computing system. The ultimate goal of a computing system is to execute programmed logic. From this perspective, virtual machines can be categorized into 4 types according to the level of abstraction and scope of emulation:
Type 1: Full Instruction Set Architecture (ISA) virtual machine provides a full computer system's ISA emulation or virtualization. Guest operating systems and applications can run on the top of the virtual machine as an actual computer (e.g.,VirtualBox,QEMU,XEN).
Type 2: Application Binary Interface (ABI) virtual machine provides a guest process ABI emulation. Applications against that ABI can run in the process side by side with other processes of native ABI applications (e.g.,Intel's IA-32 Execution Layer on Itanium, Transmeta's Code Morphing for X86 emulation, Apple's Rosetta translation layer for PowerPC emulation).
Type 3: Virtual ISA virtual machine provides a runtime engine so that applications coded in the virtual ISA can execute on it. Virtual ISA usually defines a high level and limited scope of ISA semantics, so it does not require the virtual machine to emulate a full computer system (e.g.,Sun Microsystem's JVM, Microsoft's Common Language Runtime, Parrot Foundation's Parrot virtual machine).
Type 4: Language Virtual Machine provides a runtime engine that executes programs expressed in a guest language. The programs are usually presented to the virtual machine in source form of the guest language, without being fully compiled into machine code beforehand. The runtime engine needs to interpret or translate the program and also fulfill certain functionalities that are abstracted by the language such as memory management (e.g., the runtime engines for Basic, Lisp, Tcl, Ruby).
The boundaries between virtual machine types are not clear-cut. For example, a language virtual machine can also employ the technique of a virtual ISA virtual machine by compiling the program into a kind of virtual ISA and then executing the code on a virtual machine of that virtual ISA.
Many VM designs, such as BEAM, crossing the boundaries. They could be fit into both 3rd and 4th categories.
source:

*

*Wikipedia

*Advanced Design and Implementation of Virtual Machines; Xlao-Feng LI

A: The Erlang VM runs as one OS process. By default it runs one OS thread per core to achieve maximum utilisation of the machine. The number of threads and on which cores they run can be set when the VM is started.
Erlang processes are implemented entirely by the Erlang VM and have no connection to either OS processes or OS threads. So even if you are running an Erlang system of over one million processes it is still only one OS process and one thread per core. So in this sense the Erlang VM is a "process virtual machine" while the Erlang system itself very much behaves like an OS and Erlang processes have very similar properties to OS processes, for example isolation. There is actually an Erlang VM, based on the BEAM, which runs on bare metal and is in fact an OS in its own right, see
Erlang on Xen.
By the way, it is perfectly possible to have systems running millions of Erlang processes and it is actually done in some products, for example WhatsApp.
We were definitely thinking very much about OSes when we designed the basic Erlang environment.

A: I assume that you've been reading http://en.wikipedia.org/wiki/Virtual_machine - under that terminology, BEAM is a "process virtual machine", just like the JVM.


text:
Q: Null Variable in Javascript Code It keeps saying my variable is null even though it is assigned to a button in HTML. It doesn't allow the button press to work. The variable is "clickMe"
var yourName;   //global variable accessible to all functions

function showAnotherMessage() {
    alert("Hi " + yourName + ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
}

function init() {
    yourName = prompt("Hi. Enter your name.\nWhen the browser window is first loaded\nthe function containing this prompt window is called.", "Your name");
    var clickMe = document.getElementById("buttonclick");
  clickMe.onclick = showAnotherMessage;
    }

window.onload = init();

A: Avoid window.onload because it's fired too late in the page lifecycle - it's only fired after everything is loaded, including all images - which can be up to several seconds after the page has loaded.
Instead, use the DOM events API, and use the DOMContentLoaded event:
window.addEventListener('DOMContentLoaded', function(e) {

    // page startup code goes here
} );

Another reason to avoid window.onload = ... is that it will overwrite any previous event-handler for the onload event, whereas addEventListener does not remove any previous event handler.


text:
Q: Issues generating an OpenAPI spec using Micronaut-openapi for sealed Kotlin classes I'm having trouble with sealed classes. I get a specification from Micronaut-openapi, but the code generator I am using (orval) experiences a cyclic reference and fails.
Given this data class:
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type",
    visible = true
)
@JsonSubTypes(
    JsonSubTypes.Type(name = "lounge", value = AnonymousResponse.Lounge::class),
    JsonSubTypes.Type(name = "diningRoom", value = AnonymousResponse.DiningRoom::class)
)
sealed class AnonymousResponse {
    abstract val id: Int

    @JsonTypeName("lounge")
    data class Lounge(
        override val id: Int,
        val hasTv: Boolean,
    ) : AnonymousResponse()

    @JsonTypeName("diningRoom")
    data class DiningRoom(
        override val id: Int,
        val hasTable: Boolean,
    ) : AnonymousResponse()
}

Micronaut-openapi generates the following components:
components:
  schemas:
    AnonymousResponse:
      type: object
      properties:
        id:
          type: integer
          format: int32
      discriminator:
        propertyName: type
        mapping:
          lounge: '#/components/schemas/AnonymousResponse.Lounge'
          diningRoom: '#/components/schemas/AnonymousResponse.DiningRoom'
      oneOf:
      - $ref: '#/components/schemas/AnonymousResponse.Lounge'
      - $ref: '#/components/schemas/AnonymousResponse.DiningRoom'
    AnonymousResponse.DiningRoom:
      allOf:
      - $ref: '#/components/schemas/AnonymousResponse'
      - required:
        - hasTable
        - id
        type: object
        properties:
          id:
            type: integer
            format: int32
          hasTable:
            type: boolean
    AnonymousResponse.Lounge:
      allOf:
      - $ref: '#/components/schemas/AnonymousResponse'
      - required:
        - hasTv
        - id
        type: object
        properties:
          id:
            type: integer
            format: int32
          hasTv:
            type: boolean

Which leads to the following error in orval:
src/models/anonymousResponseDiningRoom.ts:10:13 - error TS2456: Type alias 'AnonymousResponseDiningRoom' circularly references itself.

10 export type AnonymousResponseDiningRoom = AnonymousResponse & AnonymousResponseDiningRoomAllOf;
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/models/anonymousResponse.ts:11:13 - error TS2456: Type alias 'AnonymousResponse' circularly references itself.

11 export type AnonymousResponse = AnonymousResponseLounge | AnonymousResponseDiningRoom | AnonymousResponseOneOf;
               ~~~~~~~~~~~~~~~~~

src/models/anonymousResponseLounge.ts:10:13 - error TS2456: Type alias 'AnonymousResponseLounge' circularly references itself.

10 export type AnonymousResponseLounge = AnonymousResponse & AnonymousResponseLoungeAllOf;
               ~~~~~~~~~~~~~~~~~~~~~~~

I am not entirely sure whether it's the specification generator or the code generator doing something wrong, but the "allOf" - AnonymousResponse references looks iffy to me, as (at least from how I read it) it would lead to e.g. Lounge also containing information from DiningRoom?

A: After trying placing a @Schema annotation on the sealed class, and looking into how to customise the automatic Schema generation, I realised this worked:
// No Schema here
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type",
    visible = true
)
@JsonSubTypes(
    JsonSubTypes.Type(name = "lounge", value = AnonymousResponse.Lounge::class),
    JsonSubTypes.Type(name = "diningRoom", value = AnonymousResponse.DiningRoom::class)
)
sealed class AnonymousResponse {
    abstract val id: Int

    @Schema // Schema here
    data class Lounge(
        override val id: Int,
        val hasTv: Boolean,
    ) : AnonymousResponse()

    @Schema // Schema here
    data class DiningRoom(
        override val id: Int,
        val hasTable: Boolean,
    ) : AnonymousResponse()
}

which ultimately resulted in the following orval code:
anonymousResponse.ts
import type { AnonymousResponseLounge } from './anonymousResponseLounge';
import type { AnonymousResponseDiningRoom } from './anonymousResponseDiningRoom';
import type { AnonymousResponseOneOf } from './anonymousResponseOneOf';

export type AnonymousResponse = AnonymousResponseLounge | AnonymousResponseDiningRoom | AnonymousResponseOneOf;

anonymousResponseLounge.ts
export interface AnonymousResponseLounge {
  id: number;
  hasTv: boolean;
  type?: string;
}

anonymousResponseDiningRoom.ts
export interface AnonymousResponseLounge {
  id: number;
  hasTv: boolean;
  type?: string;
}

anonymousResponseOneOf.ts
export type AnonymousResponseOneOf = {
  id?: number;
};

And while it doesn't have constant values for the discriminator types, I don't think this is the fault of the spec.


text:
Q: iCal share multiple calendars with one person I'd like to share all my calendars with my boss. She shares her calendars with me using Google Calendar and I was hoping doing the same with my calendars.
How can I share multiple calendars to be visible as one? I can only find calendars to be shared one-by-one.


text:
Q: Why is present tense uses rather than past tense in this essay?
Grandpa liked chewing tobacco, and he carried a Styrofoam cup with him wherever he went. I remember him spitting in that cup with great regularity when I used to spend the night with him and grandmother.

This is one of the sentences that I took from an essay called "Unheeded Advice".
Why is "remember" used as present tense and not past tense as the verb used in the essay is in the past tense?

A: Do you remember the cup now, or was it something you remembered when you passed some Styrofoam cups at the market?  In this case the author is saying he remembers it as he is writing. It doesn't matter when his Grandpa did it; the memory in this case is current, so the tense is present.

A: Extra note: 'Why is present tense uses rather than past tense in this essay?'
is grammatically incorrect, you should change the 'uses' to 'used'.
It should be, 'Why is present tense used rather than past tense in this essay?'
Why? This is because your question is in the passive voice of present simple.