text:
Q: Getting Error Data should be a "String", "Array of arrays" OR "Array of objects" when trying to export data to CSV in reactJS I want to download some data that I have from my firebase firestore DB that I have listed in a table.
I am adding the data that is coming from my firestore in order to export to CSV and have a complete viewable file in my admin dashboard
But every time I try to follow the steps to download the data and export them to CSV format I get this error: "Data should be a "String", "Array of arrays" OR "Array of objects"
here is my code:
 import { CSVLink } from 'react-csv';

const [data, setData] = useState([]);
  const [csvData, setcsvData] = useState([]);
  const list = []
  const csvList = []

 useEffect(() => {
    firebase.firestore().collection("Users").get().then((userSnapshot) => {

      userSnapshot.forEach((doc) => {

        const {powerAccount,first_name,registerDate,email,company,country,phone} = doc.data();
        setID(doc.data().usersID)
        list.push({
          usersID:doc.id,
          powerAccount:powerAccount,
          first_name:first_name,
          registerDate:registerDate,
          email:email,
          company:company,
          country:country,
          phone:phone,
        });

        const userData = {
          usersID: doc.id,
          powerAccount: powerAccount,
          first_name: first_name,
          registerDate: registerDate,
          email: email,
          company: company,
          country: country,
          phone: phone,
        };

        const headers = [
          { label: 'Account', key: powerAccount },
          { label: 'Name', key: first_name },
          { label: 'RegistrationDate', key: registerDate },
          { label: 'Email', key: email },
          { label: 'Company', key: company },
          { label: 'Country', key: country },
          { label: 'Phone', key: phone },
        ];
        const csvReport = {
          filename: "userReport.csv",
          headers: headers,
          data: userData
        }
        csvList.push(csvReport)
      });
      setData(list);
      setcsvData(csvList)
    });
  },[]);

 return (

    <CSVLink  {...csvData} >
    Export
  </CSVLink>

)

A: I fixed this error by adding a conditional wrapper around my CSVLink component so that it didn't try to create that component before the data was loaded.
So, for your example, something like this could do the trick:
{csvData && (
    <CSVLink  {...csvData} >
    Export
  </CSVLink>
)}


text:
Q: *** glibc detected *** ./test: free(): invalid pointer: I am trying to fetch and store ID and Status from Database using statements ID = r->getInt(1) and stat = r->getString(10) where I have declared ID as int and stat as string.
Where first field is an ID containing value 1 and 10th field is status containing value 'A'.
If I try to fetch only ID, my code works fine. Else, when I try to fetch status as well, then while running the code, I am getting below mentioned error:
*** glibc detected *** ./test: free(): invalid pointer: 0x000000001c3f5a60 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3d23e71684]
/lib64/libc.so.6(cfree+0x8c)[0x3d23e74ccc]
/usr/lib64/libstdc++.so.6(_ZNSsD1Ev+0x3a)[0x3d28a9dc1a]
./test[0x401837]
./test(__gxx_personality_v0+0x310)[0x401120]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x3d23e1d8b4]
./test(__gxx_personality_v0+0x89)[0x400e99]

Please help.
Adding just the basics of what I am trying to achieve:
char loader_session[10];
char sql_query[500];
int ID;
string STATUS;
string CURRENT_CNT_FILE

env = Environment::createEnvironment (Environment::DEFAULT);
conn = env->createConnection( user, passwd, db);
strcpy(loader_session,"TEST");
sprintf(sql_query,"SELECT ID, SESSION_NAME, SRC_SUCCESS_PATH, SRC_CDR_PATH, LOG_FILE, CURRENT_CNT_FILE, LOG_MAX_FILE_CNT, LOG_MAX_FILE_SIZE, PROCEDURE_NAME, STATUS, ERROR_CDR_PATH, LOCK_FILE_PATH FROM TEST_DB WHERE SESSION_NAME = '%s'",loader_session);
Statement* const s = conn->createStatement(sql_query);
s->setPrefetchRowCount(10);
ResultSet* const r = s->executeQuery();
while (r->next())
  {

    ID      =  r->getInt(1);
    STATUS  =  r->getString(10);
    CURRENT_CNT_FILE = r->getString(6);
  }

A: Ok I got a temporary solution for my question. Just by setting MALLOC_CHECK_ to 0, I am not getting the error and my code is running fine. Don't know the side effects of this, but as of now, it's working fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To Parsing JSON data from Yii Framework ? first of all, i'm a newbie and i already follow tutorial to create website using Yii framework as server. a simple website with CRUD function is already build. now i want to connect it with my android application.
my platform : Win 7 64, Eclipse IDE, Android ADT, GenyMotion.
/* Yii Side */
this is my EmployeeController on (protected\controllers\EmployeeController.php)
public function actionGetEmployee($id)
{
    header('Content-type: application/json');
    $employee = Employee::model()->findAll();
    echo CJSON::encode($employee);
    Yii::app()->end();
}

the result from above code is this :
[
{
    "id": "1",
    "departmentId": "1",
    "firstName": "Hendy",
    "lastName": "Nugraha",
    "gender": "female",
    "birth_date": "1987-03-16",
    "marital_status": "Single",
    "phone": "856439112",
    "address": "Tiban Mutiara View ",
    "email": "hendy.nugraha87@yahoo.co.id",
    "ext": "1",
    "hireDate": "2012-06-30 00:00:00",
    "leaveDate": "0000-00-00 00:00:00"
},
{
    "id": "2",
    "departmentId": "2",
    "firstName": "Jay",
    "lastName": "Branham",
    "gender": "male",
    "birth_date": "0000-00-00",
    "marital_status": "Single",
    "phone": "0",
    "address": "",
    "email": "jaymbrnhm@labtech.org",
    "ext": "2",
    "hireDate": "0000-00-00 00:00:00",
    "leaveDate": "0000-00-00 00:00:00"
}
]

/* Now on Android side */
this is the main.xml :
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Daftar Biodata Karyawan Online" />

        <TableLayout
            android:id="@+id/tableLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" >

                <Button
                    android:id="@+id/btnrefresh"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Refresh" />

                <Button
                    android:id="@+id/btnedit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Edit" />

                <Button
                    android:id="@+id/btnhapus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Hapus" />
            </TableRow>
        </TableLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TableLayout
            android:id="@+id/tableLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1" >
        </TableLayout>
    </LinearLayout>
</LinearLayout>
 </ScrollView>

and this is my Akses_Server_Activity :
    public class Akses_Server_Activity extends Activity{

static String url = "http://10.0.2.2/restayii/index.php/department/getdepartment?id";
static final String Employee_ID = "id";
static final String Employee_Dept_ID = "departmentId";
static final String Employee_First_Name = "firstName";
static final String Employee_Last_Name = "lastName";
static final String Employee_Gender = "gender";
static final String Employee_Birth_Date = "birth_date";
static final String Employee_Marital_Status = "marital_status";
static final String Employee_Phone_Number = "phone";
static final String Employee_Address = "address";
static final String Employee_Email = "email";
static final String Employee_Ext = "ext";
static final String Employee_Hire_Date = "hireDate";
static final String Employee_Leave_Date = "leaveDate";
JSONArray employee = null;
JSONObject json_object;
Button btnrefresh;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.daftar_employee_online);

    btnrefresh = (Button) findViewById(R.id.btnrefresh);
    btnrefresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Toast.makeText(getApplicationContext(), "Hendy", Toast.LENGTH_LONG).show();
                new MyAsynTask().execute();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    public JSONObject GetJson(String url) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;

    }
}

public class MyAsynTask extends AsyncTask<String, Void, JSONObject>{

    @Override
    protected JSONObject doInBackground(String... arg0) {

        JSONParser json_parse = new JSONParser();
        json_object = json_parse.GetJson(url);
        return null;
    }

    protected void onPostExecute(String Result){
        // com
        try {
            employee = json_object.getJSONArray("employee");
            TableLayout table_layout =(TableLayout) findViewById(R.id.tableLayout);
            table_layout.removeAllViews();
            int jml_baris = employee.length();
            String [][] data_employee = new String [jml_baris][13];
            for(int i=0;i<jml_baris;i++){
                JSONObject jobj = employee.getJSONObject(i);
                data_employee[i][0] = jobj.getString(Employee_ID);
                data_employee[i][1] = jobj.getString(Employee_Dept_ID);
                data_employee[i][2] = jobj.getString(Employee_First_Name);
                data_employee[i][3] = jobj.getString(Employee_Last_Name);
                data_employee[i][4] = jobj.getString(Employee_Gender);
                data_employee[i][5] = jobj.getString(Employee_Birth_Date);
                data_employee[i][6] = jobj.getString(Employee_Marital_Status);
                data_employee[i][7] = jobj.getString(Employee_Phone_Number);
                data_employee[i][8] = jobj.getString(Employee_Address);
                data_employee[i][9] = jobj.getString(Employee_Email);
                data_employee[i][10] = jobj.getString(Employee_Ext);
                data_employee[i][11] = jobj.getString(Employee_Hire_Date);
                data_employee[i][12] = jobj.getString(Employee_Leave_Date);
            }

            TableLayout.LayoutParams ParameterTableLayout = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
            for(int j=0; j<jml_baris; j++){
                TableRow  table_row = new TableRow(null);
                table_row.setBackgroundColor(Color.BLACK);
                table_row.setLayoutParams(ParameterTableLayout);
                TableRow.LayoutParams ParameterTableRow = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
                ParameterTableRow.setMargins(1,1,1,1);
                for(int kolom = 0; kolom < 13; kolom++){
                    TextView TV= new TextView(null);
                    TV.setText(data_employee[j][kolom]);
                    TV.setTextColor(Color.BLACK);
                    TV.setPadding(1, 4, 1, 4);
                    TV.setGravity(Gravity.LEFT);
                    TV.setBackgroundColor(Color.BLUE);
                    table_row.addView(TV,ParameterTableRow);
                }
                table_layout.addView(table_row);
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
    }

this is the logcat :
11-04 16:23:47.273: E/JSON Parser(1867): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

my problem is : when android app running, i click the refresh button, it not showing the Table Layout that contain employee json data. any help would be very apreciated. thanks.

A: I think you have error when making request from Android app, because <!DOCTYPE is start of webpage. Try to look at the result of request from Android app.


text:
Q: Looping through Magento attribute values skips the first item This is an ajax file running the following code:
$model = Mage::getModel('catalog/product'); //getting product model
    foreach ($violins as $k => $v)
       {
           $_product = $model->load($v); //getting product object for particular product id
           $violinmodel = $_product->getAttributeText('Violinmodel'); //grabbing the violinmodel attribute value
           echo $violinmodel;
       }

$violin contains an array with three product ID's. My output is echoing the attribute value for the second and third ID's fine, but is NOT echoing the first ID!
I don't get this at all! Why would it completely skip the first ID in the loop and not echo anything, while echoing the following ID's without a problem?
The attributes are set up properly and no matter how I rearrange the ID's in the $violins array, the first attribute value is always skipped. What am I missing?

A: When you iterate over a product collection in Magento, the items it contains are actually product object instances. What you are doing here (hitting the database multiple times, loading all attribute) is unnecessary given what you are trying to accomplish (getting one attribute). Try adding the attribute to the collection to begin with and iterate over it:
$coll = Mage::getModel('catalog/product')->getCollection()
                                           ->addAttributeToSelect('Violinmodel');
                                           //be certain that the attribute code is capitalized...

foreach ($coll as $product) {
    //var_dump($product->debug()); //for example
    var_dump($product->getAttributeText('Violinmodel));
}

A: Initializing $model outside of your loop is unsafe. You might think that you are being more efficient with memory and/or function calls but you're asking for trouble. The Mage_Catalog_Model_Product object is being loaded at that time, and calling ->load() isn't giving you a new object, it's just setting the data of your existing one. Except, you'll get strange behavior when not all of the data gets overwritten (for example if ProductA has a Violinmodel attribute and ProductB doesn't... it will look like ProductA.Violinmodel == ProductB.Violinmodel). For that reason, you should always put your model inside your loop.
foreach ($violins as $k => $v) {
    $_product = Mage::getModel('catalog/product')->load($v); //getting product
    if ($_product->getId() == $v) { // sanity check
        $violinmodel = $_product->getAttributeText('Violinmodel'); //grabbing the violinmodel attribute value
        echo $violinmodel;
    }
}

Or, as benmarks suggested, load this data via a collection:
$_products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('Violinmodel')
    ->addIdFilter($violins);
foreach ($_products as $_product) {
    echo $_product->getAttributeText('Violinmodel'));
}


text:
Q: How do I add line break in FPDF cell using multicell I'm trying to give this particular table column a new line, so it doesn't exceed to other part of column
$pdf->SetFont('Arial','B',10);
$pdf->SetFillColor(208,208,208);
$pdf->Cell(10,8,'No.',1,0,'C',true);
$pdf->Cell(30,8,'Barcode',1,0,'C',true);
$pdf->Cell(80,8,'Product Name',1,0,'C',true);   //190
$pdf->Cell(25,8,'Stock',1,0,'C',true);
$pdf->Cell(45,8,'Image',1,1,'C',true);

    $select = $pdo->prepare("SELECT * FROM tbl_product");
    $select->execute();
    $index = 0;

while($item = $select->fetch(PDO::FETCH_OBJ)){
    $index++;
    $productimage = $item->pimage;
    $pdf->SetFont('Arial','',10);
    $pdf->Cell(10,18,$index,1,0,'C');
    $pdf->Cell(30,18,'8309128312',1,0,'C');
    $pdf->Cell(80,18,'Long product name that needs a line break - and more',1,1,'L');
    $pdf->Cell(25,18,'123',1,0,'C');
    if($productimage == ""){
    $pdf->Cell(45,18,'-',1,1,'C');
    } else {
    $pdf->Cell(45,18,$pdf->Image('productimages/'.$productimage, $pdf->GetX() + 15, $pdf->GetY() + 1, 11.5),1,1,'L');
    }
}

I have tried using MultiCell() for this line of code.
$pdf->Cell(80,18,'Long product name that needs a line break - and more',1,0,'L');
Overflow text in cell table
into
$pdf->MultiCell(80,18,'Long product name that needs a line break - and more',1,0,'L');
I'm also aware that MultiCell() goes by this
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
but I'm not sure which parameter I should fiddle around to make sure everything is in place.
After applying MultiCell
Any help would be appreciated. Thank you.


text:
Q: Greenplum Single Node fails on distributed files Running a Greenplum single node edition db, and I'm having errors with gpfdist.  Exact error message is:
ERROR:  connection with gpfdist failed for gpfdist://localhost:8080/facts_days1-3_out.csv. effective url: http://127.0.0.1:8080/facts_days1-3_out.csv. error code = 111 (Connection refused) (url.c:258)  (seg0 slice1 localhost:50001 pid=26618)
Does anyone have a recommendation for debugging this?
thanks,
mcpeterson

A: Ah, I ended up figuring this out.  I had two problems not displayed in the code unfortunately. I apologize for not showing them.
One:  I called the file with
'gpfdist//localhost...
as opposed to
'gpfdist://localhost...
Which didn't register the file.  Secondly, I think my gpfdist process had died without me knowing it.  rerunning with:
./gpfdist -p 8081 -d mydirectory
and calling the external table from 8081 remedied the problem.
Best,
mcpeterson


text:
Q: Efficient solution for my task needed I just solve this but want know more efficient way to do matrix multiplication
 M = | 1 0 3 |
     | 1 0 2 |
     | 0 5 0 |

f[n] = M^n
I have implemented using Exponentiation_by_squaring
Is there more efficient then this ?

A: I guess, this is actually more suitable for math as there's a closed form solution. It's system of Linear homogeneous recurrence relations with constant coefficients.
Another posibility: You could speed up the program twice by deriving a formula for two steps, i.e., express RR(i) etc. via RR(i-2), etc.
And this can be repeated, so you can jump much faster.

A: One problem is that your calculations are overflowing. If you run it for K=1 and J=9, you get -334328541#510576792#-817751931.
The easiest fix for that is to do % 1000000006 in calculateProduction.
About efficiency, I would look at this problem as performing matrix multiplications.
You start with the vector (i.e. 1*3 matrix):
3 1 0

And at each step you multiply it (mod 1000000006) with the matrix:
1 1 0
0 0 5
3 2 0

Let's call the vector V and the matrix M. Basically you need to calculate V*MN. Since matrix multiplication is associative, you can calculate MN first, and do that recursively:
MN = (MN/2)2 if N is even, or
MN = M*(M[N/2])2 if N is odd

A: You don't need to calculate MM. This is why:
PP[i] = 5*MM[i-1] = 5*(RR[i-2] + 2*PP[i-2])
RR[i] = RR[i-1] + 3*PP[i-1] = (RR[i-2] + 3*PP[i-2]) + 3*PP[i-1]

See? You don't need to calculate MM at each step. This should be the algorithm:
public class RecurrenceMachine {
    private static final int max = 1000000006;

    public String calculate(int k, int j) {
        long n = k * j;
        if (n < 1)
            return "error";
        long RRi2 = 3;
        long PPi2 = 0;
        long RRi1 = 3 + 3 * PPi2;
        long PPi1 = 5 * 1;
        if (n == 1)
            return RRi1 + "##" + (RRi2 + 2 * PPi2) + "##" + PPi1;
        Long PPi = (long) 0, RRi = (long) 0, temp;
        int i;
        for (i = 2; i <= n; i++) {
            temp = RRi2 + 2 * PPi2;
            PPi = 5 * temp;
            if (PPi >= max)
                PPi %= max;
            RRi = temp + PPi2 + 3 * PPi1;
            if (RRi >= max)
                RRi %= max;
            RRi2 = RRi1;
            PPi2 = PPi1;
            RRi1 = RRi;
            PPi1 = PPi;
        }
        return RRi + "##" + (RRi2 + 2 * PPi2) % max + "##" + PPi1;
    }
}

I tried only with small values and it seems to work.


text:
Q: Rerouting the SAS logs to a specific location in shell scripting I have created a shell script which runs a SAS program which is created log in the same folder where I'm running Shell script. But, I'm trying to save the logs to a specific folder on LINUX. I used -log option and it is throwing me error...I'm running following command in my shell script...
/saspath/sas /homesas/test.sas   -log home/sasu1/log/test.log.$rundatetime \

I'm getting this error... -log: command not found

A: It is normal Unix convention to put the options (-log) before the parameters (filename) to a command.
sas -log xxx.log xxx.sas

Your real problem might be that you need to construct your log filename first.
pgm=test
log=${pgm}.${rundatetime}.log
sas -log $log &pgm

Another thing to check is that some sites have build scripts to launch SAS and they do not properly pass the command line arguments through to the actual command that launches SAS. Check whether /saspath/sas is the actual command provided by SAS or something your local IT group created.


text:
Q: Apostrophe or assume the possessive? This question has divided the office into two camps.  Camp 1 believes the correct way to indicate the relationship in this sentence is to use the client's name as a possessive, as in "When UltraGalactic's employees call the Customer Service line..."  Camp 2 believes the apostrophe can be dropped because "UltraGalactic" is modifying "employees," and therefore the possessive is assumed. Frankly, I don't understand the uproar over typing two additional characters, but I'd appreciate your feedback.

A: Both are grammatically correct.

UltraGalactic's employees...

Indicates that the employees belong to UltraGalactic.
and

UltraGalactic employees

Indicates that employees are employees at UltraGalactic.


text:
Q: How to use npapi plugins in b2g firefox OS This is my first time on this site. I have a HTML/CSS/JS application. For that application to work, we also have a browser npapi plugin ".so" file that is installed in plugins dir of firefox. This works on firefox browser on Linux. Now I want my application to run on Firefox OS (B2G). How do I port that ".so" plugin to firefox OS?.
What I have done is, I have built B2G and flashed it on my test device. I have built that plugin for android platform by using gecko sdk and firefox OS source. I have pushed my .so file in FFOS phone in /system/lib as well as /system/b2g (the folders where I can see other .so files.). Is that the correct approach? What else do I need to do to make it work. Currently my application is unable to load that plugin ( I checked using ./run-gdb ).
Any pointers would be helpful. I have gone through the documentation on mozilla website and also googled it alot but couldn't find the solution.
Thanks.

A: You are right, NPAPI is not supported on Firefox OS / B2G.
You do see code for it in the tree (and maybe even in the object directories) because much of the code is actually being used over different products (desktop Firefox, mobile Firefox, Firefox OS, ...).

A: Mozilla use single gecko engine to support all platform browsers. Those plugins are only used by desktop browsers.


text:
Q: How to reduce errors in dynamic language such as python, and improve my code quality? I've always have trouble with dynamic language like Python.
Several troubles:

*

*Typo error, I can use pylint to reduce some of these errors. But there's still some errors that pylint can not figure out.

*Object type error, I often forgot what type of the parameter is, int? str? some object? Also, forgot the type of some object in my code.

Unit test might help me sometimes, but I'm not always have enough time to do UT. When I need a script to do a small job, the line of code are 100 - 200 lines, not big, but I don't have time to do the unit test, because I need to use the script as soon as possible. So, many errors appear.
So, any idea on how to reduce the number of these troubles?

A: Unit testing is the best way to handle this. If you think the testing is taking too much time, ask yourself how much time you are loosing on defects - identifying, diagnosing and rectifying - after you have released the code.
In effect, you are testing in production, and there's plenty of evidence to show that defects found later in the development cycle can be orders of magnitude more expensive to fix.

A: In addition to unittesting (see chamila_c's answer), sticking to good conventions and coding style helps.  I think I know the sort of one-use scripts you're talking about (assuming that is what you're talking about), and often writing a full test suite for them seems like overkill.  A few other tips which might help:

*

*Break your code up into functions.  It is often easier to identify a problem, especially a naming problem if you are dealing with a small, isolated piece of code.  It is also much easier to write a unit test for small function.  I find that using this approach means you don't need a full testing suite to test and isolate an identified problem.

*Stick to a consistent, and expressive naming convention.  For example, use min_value = min(all_values) rather than something arbitrary like a = min(b).  Same goes for function names, use def calculate_mean(sequence) rather than def f(s)

*Read and apply PEP8.

*Document your code with comments.  This only takes a few seconds while writing the code, and it makes it much easier to figure out what's going on when you come back to it.  Its amazing the detail you can forget just in one day!


text:
Q: how can i make this into one div how can i make this in one div? currently it has two divs but i need to make it in one div like the images showing on the left and the text is on the right.

first paragraph

second paragraph

A: no need for another div, give your image an align attribute, like

A: You can use clear: left:
See: http://jsfiddle.net/thirtydot/FN4h4/
CSS:
img {
    float: left;
    clear: left;
    margin: 0 6px
}

HTML:

Lorem ipsum..

Lorem ipsum..

A: Why do you want to avoid using more than one div?  I'd do it something like this:
HTML

Paragraph 1

Paragraph 2

CSS
.article
{
    clear: both;
    width: 400px;
}
.article img
{
    float: left;
}
.article p
{
    float: right;
}

Working Demo

A: If you are asking why the img tags and the text nodes are in the same div (which is what it sounds like to me), its because you have all of the sub-nodes belonging to a single div node (id="div_left"). Html, Xml, and XHtml are all based upon a hierarchical node structure. Anything you want to separate into divs, to handle separate float rules for example, should be split into separate divs. You could still sub-node them into a parent div, but if you want to define individual styling you should explicitly put them into div or span tags.
For example, when I have different styling on multiple sub-nodes, I invariably use the template:


text:
Q: Configure interrupt handler for different GPIO pins of same port I want to use 5 Gpios as user input buttons in mqx TWRK60D100. I followed configuration as
#define LEFT_BUTTON         (GPIO_PORT_E | GPIO_PIN26)
#define LEFT_BUTTON_MUX_IRQ     (LWGPIO_MUX_E26_GPIO)

#define RIGHT_BUTTON             (GPIO_PORT_A | GPIO_PIN19)
#define RIGHT_BUTTON_MUX_IRQ     (LWGPIO_MUX_A19_GPIO)

#define UP_BUTTON            (GPIO_PORT_C | GPIO_PIN5)
#define UP_BUTTON_MUX_IRQ    (LWGPIO_MUX_C5_GPIO)

#define DOWN_BUTTON              (GPIO_PORT_C | GPIO_PIN4)
#define DOWN_BUTTON_MUX_IRQ      (LWGPIO_MUX_C4_GPIO)

#define TEST_BUTTON              (GPIO_PORT_C | GPIO_PIN1)
#define TEST_BUTTON_MUX_IRQ      (LWGPIO_MUX_C1_GPIO)

#define BUTTON_PRESS_NOT_PENDING 0
#define LEFT_BUTTON_PRESSED     1
#define RIGHT_BUTTON_PRESSED    2
#define UP_BUTTON_PRESSED       3
#define DOWN_BUTTON_PRESSED     4
#define TEST_BUTTON_PRESSED     5

void int_service_routine(void *);

LWGPIO_STRUCT Left_Button;
LWGPIO_STRUCT Right_Button;
LWGPIO_STRUCT Up_Button;
LWGPIO_STRUCT Down_Button;
LWGPIO_STRUCT Test_Button;

volatile uint_8 Button_Press_Status = BUTTON_PRESS_NOT_PENDING;
/*ISR*-----------------------------------------------------
*
* Task Name    : int_service_routine
* Comments     :
* Button press ISR
*END*-----------------------------------------------------*/
void int_service_routine(void *pin)
{

    printf("In Isr %u \n",pin);

    if(pin==&Left_Button)
    {
        Button_Press_Status=LEFT_BUTTON_PRESSED;
    }
    else if(pin==&Right_Button)
    {
        Button_Press_Status=RIGHT_BUTTON_PRESSED;
    }
    else if(pin==&Up_Button)
    {
        Button_Press_Status=UP_BUTTON_PRESSED;
    }
    else if(pin==&Down_Button)
    {
        Button_Press_Status=DOWN_BUTTON_PRESSED;
    }
    else if(pin==&Test_Button)
    {
        Button_Press_Status=TEST_BUTTON_PRESSED;
    }

    lwgpio_int_clear_flag((LWGPIO_STRUCT_PTR) pin);
}

void Individual_Button_Config(LWGPIO_STRUCT_PTR button_name,
       LWGPIO_PIN_ID pin_id,uint_32 button_mux_irq)
{

    /*
     Open the pin for input, initialize interrupt and set handler.
     */
    /* opening pins for input */
    if (!lwgpio_init(button_name, pin_id,
             LWGPIO_DIR_INPUT,LWGPIO_VALUE_NOCHANGE))
    {
        printf("Initializing button GPIO as input failed.\n");
        _task_block();
    }

    /* Some platforms require to setup MUX to IRQ functionality,
     for the rest just set MUXto GPIO functionality */
    lwgpio_set_functionality(button_name, button_mux_irq);
    lwgpio_set_attribute(button_name, LWGPIO_ATTR_PULL_UP, LWGPIO_AVAL_ENABLE);

    /* enable gpio functionality for given pin, react on falling edge */
    if (!lwgpio_int_init(button_name, LWGPIO_INT_MODE_FALLING))
    {
        printf("Initializing button GPIO for interrupt failed.\n");
        _task_block();
    }

    /* install gpio interrupt service routine */
    _int_install_isr(lwgpio_int_get_vector(button_name),
               int_service_routine, (void *) button_name);
    /* set the interrupt level, and unmask the
       interrupt in interrupt controller*/
    _bsp_int_init(lwgpio_int_get_vector(button_name), 3, 0, TRUE);
    /* enable interrupt on GPIO peripheral module*/
    lwgpio_int_enable(button_name, TRUE );

    printf("\n Button pin has been configured as input GPIO interrupt pin.\n");
}

/*
 * Function Name    : Button_Init
 * Returned Value    : None
 * Comments          : This function will initialise gpio buttons as input
 *
 */
void Button_Init(void)
{
    //Configuring Left Button
    Individual_Button_Config(&Left_Button,LEFT_BUTTON,LEFT_BUTTON_MUX_IRQ);
    //Configuring Right Button
    Individual_Button_Config(&Right_Button,RIGHT_BUTTON,RIGHT_BUTTON_MUX_IRQ);
    //Configuring Up Button
    Individual_Button_Config(&Up_Button,UP_BUTTON,UP_BUTTON_MUX_IRQ);
    //Configuring Down Button
    Individual_Button_Config(&Down_Button,DOWN_BUTTON,DOWN_BUTTON_MUX_IRQ);
    //Configuring Test Button
    Individual_Button_Config(&Test_Button,TEST_BUTTON,TEST_BUTTON_MUX_IRQ);
}

Interrupt handling of different pins say (GPIO_PORT_E | GPIO_PIN26) ,(GPIO_PORT_A | GPIO_PIN19) worked fine.
But from (GPIO_PORT_C | GPIO_PIN5), (GPIO_PORT_C | GPIO_PIN4), (GPIO_PORT_C | GPIO_PIN1), only last configured (GPIO_PORT_C | GPIO_PIN1) was only worked.Other pin's interrupt handler get executes repeatedly without clearing interrupt flag.
When i commented (GPIO_PORT_C | GPIO_PIN1) pin configuration, (GPIO_PORT_C | GPIO_PIN4) worked fine but problem remained with (GPIO_PORT_C | GPIO_PIN5).
When I looked the address of pin in the interrupt handler, all of the port c interrupts show the address of last configured GPIO C PIN1.
What could be wrong with my code?
How to configure interrupt handler for different pins of same port?


text:
Q: Caused by: org.postgresql.util.PSQLException: ERROR: unrecognized configuration parameter on PL/pgSQL function I've created postgresql function on DB and defined trigger for after update on table.
Postgresql has a current_setting() option and in the function i need to check one specific parameter.
On DBeaver sql editor it works fine with the following lines;
BEGIN;
SELECT set_config('myapp.my_unique_id', 1, true);

update my_table set name = 'test' where my_table_id =1234;
COMMIT;

My question is; how can i set this configuration parameter via hibernate - springboot application ?
This parameter will update dynamically in the application before each DB transaction (insert-update-delete).I mean the value of the parameter will be different each time.
For now, when I try to update my_table on DB, it gets the following error;
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3449)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3311)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3723)
    at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:201)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478)
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1360)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:451)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3210)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2378)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534)
    ... 102 more
Caused by: org.postgresql.util.PSQLException: ERROR: unrecognized configuration parameter "myapp.my_unique_id"
  Where: SQL statement "select
    current_setting('myapp.my_unique_id')"
PL/pgSQL function my_function() line 49 at SQL statement
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2468)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2211)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:309)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:446)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:370)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:149)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)

Here is the sample function;
CREATE OR REPLACE FUNCTION my_function()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
    declare
     my_id numeric := 0;
    begin
       select current_setting('myapp.my_unique_id') into my_id;
        raise notice 'my_id: %', my_id;

        update my_table set row_id = my_id where  my_table_id = 124;

     RETURN NEW;
    END;
    $function$
;

CREATE TRIGGER my_function
after UPDATE ON my_table
FOR EACH ROW EXECUTE PROCEDURE my_function();

I need this parameter for logging each DB operation and that parameter will be user_id.
I may be proceeding wrong, if you have a different idea, we can take into account.
Thank you all.

A: Use
SELECT current_setting('myapp.my_unique_id', TRUE);

Then you will get NULL instead of an error message if the parameter doesn't exist.


text:
Q: How to get name from a value in an R vector with names I know that with a vector such as
v <- c("MA", "NY", "PA")
names(v) <- c("Massachusetts", "New York", "Pennsylvania")

It is possible to get a value from a name using syntax such as
v["New York"]

But is it possible to get a name from a value (like the PHP key() function)? Thanks.

A: Use match
names(v)[match("NY",v)]

or use which
names(v)[which(v=="NY")]

A: Lots of ways to do this.
names(v)[v == "NY"] # extract the names, subset by equality to NY
# or
names(which(v == "NY")) # extract entries that == NY and get names

to name a few.


text:
Q: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get' I'm getting error like

An object reference is required for the non-static field, method, or
  property 'System.Web.UI.Page.Session.get'

Can you suggest me to recover from this problem in session.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Services;
    using System.Configuration;
    using System.Data.SqlClient;
    using System.Web.SessionState;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    //Onclick Submit Button
    [WebMethod(EnableSession = true)]
    //[System.Web.Services.WebMethod(EnableSession = true)]
    public static string Login(string email, string password)
    {
        var con = new SqlConnection(ConfigurationManager.ConnectionStrings["blogConnString"].ConnectionString);
        con.Open();
        string res = "0";
        SqlDataReader reader;
        string sql = "select uid,username from personal where email='" + email + "' and password='" + password + "'";
        SqlCommand cmd1 = new SqlCommand(sql, con);
        reader = cmd1.ExecuteReader();
        while (reader.Read())
        {
            res = "1";
            Session["UID"] = reader["uid"].ToString();           //error line here
            Session["UNAME"] = reader["username"].ToString();    //error line here
         }
        return res;
        con.Close();
    }
}

A: Don't make your method static. It doesn't need to be static and it prevents you from using any non-static properties (like Session). Make it:
public string Login(string email, string password)
{
    ....
}

Also, don't concatenate SQL queries, especially with the values that come from the UI. This leaves you vulnerable to SQL injection. Use SQLParameters.

A: Try this code and please be-ware of SQL Injection - to prevent it, use a Parametrized Query as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.SessionState;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    //Onclick Submit Button
    [WebMethod(EnableSession = true)]
    //[System.Web.Services.WebMethod(EnableSession = true)]
    public static string Login(string email, string password)
    {
        var con = ConfigurationManager.ConnectionStrings["blogConnString"].ConnectionString;
        con.Open();
        string res = "0";
        SqlDataReader reader;
        string sql = "select uid,username from personal where email=@Email and password=@Password";
        using(SqlConnection connection = new SqlConnection(con))
        {
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.Add("@Email", SqlDbType.String);
            command.Parameters["@Email"].Value = email;

            command.Parameters.AddWithValue("@Password", password);
            reader = command.ExecuteReader();
            while (reader.Read())
            {
               res = "1";
               HttpContext.Current.Session["UID"] = reader["uid"].ToString();           //Either Remove Static from Method Declaration or use HttpContext.Current along with session.
               HttpContext.Current.Session["UNAME"] = reader["username"].ToString();
            }
        }
        return res;
        con.Close();
    }
}

A: can you use it for insert a variable to the session :
HttpContext.Current.Session["UID"] = reader["uid"].ToString();

and don't use static
public string Login(string email, string password)
{
}


text:
Q: Hibernate named query I'm trying to fetch a set of results between two dates
Using HQL
@NamedQuery(
           name = "getAppointmentsByDateWeek",
           query = "select a from Appointment a where a.appointmentDate BETWEEN :date1 AND :date2 "
           ),

however the named parameter's do not work and I am unsure on how to set the correctly


text:
Q: Compare two set of object and create new set with javascript and form jsx Hi i am new to react and javascript
I have two set of objects
set1
const set1 = {
  men: { value: "men", label: "Men", type: "select" },
  women: { value: "women", label: "Women", type: "select" },
  kids: { value: "kids", label: "Kids", type: "select" },
};

and set2
const set2 = {
  men: { code: "men", title: "Men" },
  women: { code: "men", title: "Men" },
};

I want to compare both the set of object and if key is same i want to get the result as new object
const resultobj = {
  men: { value: "men", label: "Men", type: "select" },
  women: { value: "women", label: "Women", type: "select" },
};

And i want to display label from result obj in a div using jsx   exmaple
return
{resultobj.label}
;

A: Please try the following example

const set1 = {
  men: { value: "men", label: "Men", type: "select" },
  women: { value: "women", label: "Women", type: "select" },
  kids: { value: "kids", label: "Kids", type: "select" },
};

const set2 = {
  men: { code: "men", title: "Men" },
  women: { code: "men", title: "Men" },
};

// get keys of both arrays
const array1 = Object.keys(set1);
const array2 = Object.keys(set2);

// get interesction
const diff = array1.filter((entry) => array2.includes(entry));

// reduce to result object
const output = diff.reduce((previousValue, currentValue) => {
  previousValue[currentValue] = set1[currentValue];

  return previousValue;
}, {});

console.log(output);

Update 0
Because you can have 1 or more results you must list them for example
return (

    {output.map(entry =>
{entry.label}
)}

)

Update 1
The data you show is not properly formatted, please try the following

const data1 = {
  women: {
    value: "women",
    label: "Women",
    type: "select",
    options: {
      1: {
        label: "lady",
        value_string: "1",
      },
      2: {
        label: "girl",
        value_string: "2",
      },
    },
  },
};

for (const key in data1.women.options) {
  console.log(data1.women.options[key].label);
}

I understand you can get more than one data, if it is the case you can try the following

const data2 = {
  women: {
    value: "women",
    label: "Women",
    type: "select",
    options: {
      1: {
        label: "lady",
        value_string: "1",
      },
      2: {
        label: "girl",
        value_string: "2",
      },
    },
  },
  men: {
    value: "women",
    label: "Women",
    type: "select",
    options: {
      1: {
        label: "lady",
        value_string: "1",
      },
      2: {
        label: "girl",
        value_string: "2",
      },
    },
  },
};

for (const property in data2) {
  for (const key in data2[property].options) {
    console.log(data2[property].options[key].label);
  }
}

Now, to render in react you will need to use map, for this you can pass each object to an array in which you will then use map, see the following example
Following the logic of the second example
let output1 = [];

for (const property in data2) {
  for (const key in data2[property].options) {
    output1 = [...output1, data2[property].options[key]];
  }
}

return (

    output1.map(entry =>
{entry.label}
)

)

See

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
This is a very common scenario, I recommend you keep reference to this answer https://stackoverflow.com/a/33034768/615274

A: you need to get the intersection for keys and then get first object values with intersected keys

const set1 = {
  men: { value: "men", label: "Men", type: "select" },
  women: { value: "women", label: "Women", type: "select" },
  kids: { value: "kids", label: "Kids", type: "select" },
};

const set2 = {
  men: { code: "men", title: "Men" },
  women: { code: "men", title: "Men" },
};

let keys = Object.keys(set1).filter(key => key in set2)

let result = {}
keys.forEach((key)=>{
      result = {...result,...{[key]:set1[key]}}
})

console.log(result)

for displaying label of all the values in the object we need to iterate over the values and display them
{Object.values(result).map((value)=>
{value.label}
)}

A: Use foreach and key values

const set1 = {
  men: { value: "men", label: "Men", type: "select" },
  women: { value: "women", label: "Women", type: "select" },
  kids: { value: "kids", label: "Kids", type: "select" },
};
const set2 = {
  men: { code: "men", title: "Men" },
  women: { code: "men", title: "Men" },
};
filter={}
Object.entries(set2).forEach((o)=>{
  Object.entries(set1).forEach(k=>{
       if(o[0]==k[0]) filter[k[0]]=k[1]
  })
})

console.log(filter)


text:
Q: can not be resolved or is not a field, android error I am writing an android based application, which has many activities, I want to move between them but I am getting this error:  cannot be resolved or is not a filed.
here is the main code:
    public void onButtonClicker(View v)
            {
                Intent intent;

                switch (v.getId()) {
                case R.id.hotels_bt:
                    intent = new Intent(this, hotels.class);
                    startActivity(intent);
                    break;

                case R.id.restaurants_bt:
                    intent = new Intent(this, restaurants.class);
                    startActivity(intent);
                    break;

                case R.id.airports_bt:
                    intent = new Intent(this, airports.class);
                    startActivity(intent);
                    break;

                case R.id.currency_bt:
                    intent = new Intent(this, currency.class);
                    startActivity(intent);
                    break;

                case R.id.praytime_bt:
                    intent = new Intent(this, prayTime.class);
                    startActivity(intent);
                    break;

                case R.id.about_bt:
                    intent = new Intent(this, about.class);
                    startActivity(intent);
                    break;
                default:
                    break;
                }

 }

at each class name I am getting this error, I don't know what is the cause of it.

A: the second parameter of new Intent takes a type-specific class name. so you need to make sure that if you name your files Hotels.java, that you specifically type Hotels.class and make sure Hotels is imported at the top of your activity.

A: Make sure both the name of the .java file (class name) and the reference to it (Activity.class) start with a capital.


text:
Q: Is there a Function for actors that does the same thing as the function "move component to"? - UE4 Blueprint i need some sort of "move component to" function that does the same thing but for actors. I´ve searched but I found none
move component to function

A: You could use the root component of the actor and it should move the whole actor. If you wanted to move the actor between two points you could use a lerp


text:
Q: How to make my proofs and analysis more rigorous? A similar question was asked here but is yet to be answered.
The problem I face is that when I try proving certain statements be it from geometry or algebra I get the general idea on how to approach it for instance using AM-GM Inequality but I am not able to set up questions in the form to properly apply the property. Similarly in geometry questions even though I know how to go about solving the problem like I figure out that a given set of triangles are congruent in the figure proves my result but I can't seem to find out how exactly to prove them.
As far as practice is concerned I try to solve almost all my study material problems myself and look up solutions only when no hope is left but still when a question which is different from the typical questions arrive I am unable to find a reasonable approach during the exams or even when I am practicing alone.
Any advise would be very helpful

A: The short answer is that practice makes perfect.  A longer answer, that works for me, is: many textbooks and lecture notes present things the opposite way round to how they're developed.  Modern textbooks sets the goal out in the statement of the result (Theorem, Proposition, whatever) and then give a step-by-step process (with steps of varying sizes depending on the target audience) of how to get there.  But when you're faced with trying to establish a result, generally we do that by identifying steps that might reach that goal, and then refining each step until they're small enough for us to be certain that they are safe.  Older textbooks (from a hundred years ago or so) actually tended to present the steps first in a discursive format and reach a statement of the result at the end (and they didn't always write it as clearly as "Theorem:" either).
So, perhaps an example instead of abstract wittering?  Let's take something on my desk at the moment: Given a Banach space $\ell_2^2$ show that its norm $\|\cdot\|_2$ is locally uniformly convex.
First things first: I write down the definition of locally uniformly convex so that I know what exactly I have to work with and what I'm trying to prove.  This means I have a sequence $\{x_n\}_{n\in {\mathbb N}} \subset \ell_2^2$ that converges in norm, so $\|x_n\|_2\rightarrow \|x\|_2 \in \ell^2_2$ as $n \rightarrow \infty$ and for which $\lim_n \|x_n+x\|_2 = 2$.  I need to show that $\lim_n \|x_n-x\|_2=0$.
Next thoughts: I know that not all Banach spaces have a locally uniformly convex norm, so that means that I cannot prove this using only generic properties of a norm.  That's a critical thought, because it tells me that I need to use the specific properties of the $\ell^2_2$ norm in order to prove this.  So at this point I write down the definition of the $\ell^2_2$ norm because I know I have to make use of that.
Next thoughts: convergence of sequences in norm is pretty standard in Banach space theory, so I should look at the additional condition and see what I can do with that.  I've obviously got a triangle inequality: $\|x_n+x\|_2 \leq \|x_n\|_2 + \|x\|_2$ and as soon as I write that down I can see that I can now apply the norm-convergence to get $\lim_n\|x_n + x\|_2 \leq 2\|x\|_2$
And finally, for this, I note that this is $\ell^2_2$ and so I have the parallelogram identity to help me out, and now I've found all the big ideas: I can see I can use the parallelogram rule to get $\|x_n-x\|_2$ in terms of $\|x_n+x\|_2$ and the convergence in norm to make all of the terms not involving $\|x_n-x\|_2$ disappear.  What's left is now filling in the details between each big step.
[By the way, I saw you updated your question on meta: Unfriendly Behaviour in Maths SE so it's probably worth me noting that this question is probably both too broad and too opinion-based to avoid closure, for which I'm sorry.]


text:
Q: DRF : How to sum value from nested object and order by sum value I've created serializing nested be using serializers as document
models.py
class Category(models.Model):
    name = models.CharField("Name", "name", max_length=255)
    iconname = models.CharField("Icon Name", "iconname", max_length=255)
    budgetamount = models.DecimalField(
        max_digits=19, decimal_places=2, default=0)
    iconcolor = models.CharField(
        "Icon Color", "iconcolor", default='4294951175', max_length=255)

    def __str__(self):
        return self.name

class DailyExpense(models.Model):
    payee_item_desc = models.CharField(
        "Payee Item Description", "payee_item_desc", max_length=255)
    category = models.ForeignKey(
        Category, related_name='dailyexpense_category', on_delete=models.CASCADE, blank=True, null=True)
    amount = models.DecimalField(max_digits=19, decimal_places=2)
    remarks = models.CharField(
        "Remarks", "remarks", max_length=255, blank=True, null=True)
    tran_date = models.DateTimeField()
    isnotclear = models.BooleanField(default=False)

    def __str__(self):
        return self.payee_item_desc

serializers.py
class DailyExpenseSerializer(serializers.ModelSerializer):
    class Meta:
        model = DailyExpense
        fields = "__all__"

class CategoryWithDailyExpenseSerializer(serializers.ModelSerializer):
    dailyexpense_category = DailyExpenseSerializer(
        source='filtered_dailyexpense_category', many=True, read_only=True)

    class Meta:
        model = Category
        fields = ('id', 'name', 'iconname',
                  'budgetamount', 'iconcolor', 'dailyexpense_category')

views.py
class CategoryWithDailyExpenseViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        fromDate = parse_datetime(self.request.query_params.get(
            'fromDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S')
        toDate = parse_datetime(self.request.query_params.get(
            'toDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S')
        queryset = Category.objects.prefetch_related(
            Prefetch('dailyexpense_category', queryset=DailyExpense.objects.filter(
                tran_date__range=[fromDate, toDate]).order_by('tran_date'), to_attr='filtered_dailyexpense_category')
        )
        return queryset

    # queryset = Category.objects.all().order_by('name')
    serializer_class = CategoryWithDailyExpenseSerializer
    filter_class = CategoryFilter

And the result that I got as below
[
     {
        "id": 2,
        "name": "Foods:Breakfast",
        "iconname": "emoji_food_beverage",
        "budgetamount": "0.00",
        "iconcolor": "4294951175",
        "dailyexpense_category": [
            {
                "id": 24574,
                "payee_item_desc": "เซเว่น",
                "amount": "-100.00",
                "remarks": "เฟิส",
                "tran_date": "2022-04-01T00:00:00Z",
                "isnotclear": false,
                "category": 2
            },
            {
                "id": 19933,
                "payee_item_desc": "เซเว่น",
                "amount": "-100.00",
                "remarks": "เฟิส",
                "tran_date": "2022-04-03T00:00:00Z",
                "isnotclear": false,
                "category": 2
            }
        ]
    },
     {
        "id": 31,
        "name": "Sport",
        "iconname": "sports_basketball_outlined",
        "budgetamount": "0.00",
        "iconcolor": "4294951175",
        "dailyexpense_category": [
            {
                "id": 25636,
                "payee_item_desc": "น้ำเกลือแร่",
                "amount": "-20.00",
                "remarks": "",
                "tran_date": "2022-04-01T00:00:00Z",
                "isnotclear": false,
                "category": 31
            },
            {
                "id": 26682,
                "payee_item_desc": "ดีแคทล่อน",
                "amount": "-6700.00",
                "remarks": "",
                "tran_date": "2022-04-01T00:00:00Z",
                "isnotclear": false,
                "category": 31
            },
            {
                "id": 28592,
                "payee_item_desc": "น้ำเกลือแร่",
                "amount": "-20.00",
                "remarks": "",
                "tran_date": "2022-04-02T00:00:00Z",
                "isnotclear": false,
                "category": 31
            }
        ]
    },
]

I wanted to sum amount value in nested objects to show in each parent object as below and order by sum amount
[
     {
        "id": 31,
        "name": "Sport",
        "iconname": "sports_basketball_outlined",
        "budgetamount": "0.00",
        "iconcolor": "4294951175",
        "sum_amount": "-6740.00",
        "dailyexpense_category": [
            {
                "id": 25636,
                "payee_item_desc": "น้ำเกลือแร่",
                "amount": "-20.00",
                "remarks": "",
                "tran_date": "2022-04-01T00:00:00Z",
                "isnotclear": false,
                "category": 31
            },
            {
                "id": 26682,
                "payee_item_desc": "ดีแคทล่อน",
                "amount": "-6700.00",
                "remarks": "",
                "tran_date": "2022-04-01T00:00:00Z",
                "isnotclear": false,
                "category": 31
            },
            {
                "id": 28592,
                "payee_item_desc": "น้ำเกลือแร่",
                "amount": "-20.00",
                "remarks": "",
                "tran_date": "2022-04-02T00:00:00Z",
                "isnotclear": false,
                "category": 31
            }
        ]
    },
    {
        "id": 2,
        "name": "Foods:Breakfast",
        "iconname": "emoji_food_beverage",
        "budgetamount": "0.00",
        "iconcolor": "4294951175",
        "sum_amount": "-200.00",
        "dailyexpense_category": [
            {
                "id": 24574,
                "payee_item_desc": "เซเว่น",
                "amount": "-100.00",
                "remarks": "เฟิส",
                "tran_date": "2022-04-01T00:00:00Z",
                "isnotclear": false,
                "category": 2
            },
            {
                "id": 19933,
                "payee_item_desc": "เซเว่น",
                "amount": "-100.00",
                "remarks": "เฟิส",
                "tran_date": "2022-04-03T00:00:00Z",
                "isnotclear": false,
                "category": 2
            }
        ]
    }
]

Is it possible to do this in django rest framework or I have to sum it in front end language?

A: You can use the SerializerMethodField in the serializer class.
class CategoryWithDailyExpenseSerializer(serializers.ModelSerializer):
    dailyexpense_category = DailyExpenseSerializer(
        source='filtered_dailyexpense_category', many=True, read_only=True)
    sum_amount = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ('id', 'name', 'iconname', 'sum_amount',
                  'budgetamount', 'iconcolor', 'dailyexpense_category')

    def get_sum_amount(self, obj):
        fromDate = parse_datetime(self.context['request'].query_params.get(
            'fromDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S')
        toDate = parse_datetime(self.context['request'].query_params.get(
            'toDate') + ' ' + '00:00:00').strftime('%Y-%m-%d %H:%M:%S')
        return obj.dailyexpense_category.aggregate(Sum('amount', filter = Q(dailyexpense_category__tran_date__range=[fromDate, toDate])))['amount__sum']

Or you can add this aggregate functions into the queryset in the serializer.
class CategoryWithDailyExpenseViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        ...
        queryset = Category.objects.prefetch_related(
            Prefetch('dailyexpense_category', queryset=DailyExpense.objects.filter(
                tran_date__range=[fromDate, toDate]).order_by('tran_date'), to_attr='filtered_dailyexpense_category')
        ).aggregate(Sum('amount', filter = Q(dailyexpense_category__tran_date__range=[fromDate, toDate]))).orderBy('-amount')
        return queryset


text:
Q: Measuring incremental revenue / uplift I run a campaign with an experimental design setup. The target and control group is representative and split 70/30.
The target group receives an email communication
The dynamics of the campaign require the user to register for the offer via the email and then make a purchase
(The control group has no registration process)
Therefore, the possible scenarios are as follows

Target | registered | converted
  Target | registered | ! converted
Target | ! registered | converted
  Target | ! registered | ! converted
Control | converted
  Control | ! converted

Note - Target | ! registered | converted are users who may or may not have seen the email but arrive at the website and purchase anyway. Only those who register actually avail the offer.
Question
In order to measure the impact of the email on conversion rate & total spend, which group/subgroup would be compared with the control group

A: I understand the questions to be:

*

*Does the additional step of registration complicate the treatment effect analysis?

You can compare the conversion rate/spend between the control and treatment group directly. Your estimate will then be conditional on the registration process. In other words, you predict the increase in conversion probability given an email with an offer for which the user has to register.
However, if you make a cost-based decision to target, then you will have to include in your decision the chance that the user actually registers and uses the offer. I'd suggest you subtract the actual offer cost from the net return of each customer.

*Can I estimate the treatment effect on the conversion rate/spend if some customer overlook the treatment email?

If customer assigned to the target group might not receive or interact with the treatment, your estimate will be the intention to treat effect. This is a common problem in medicine, where not all patients take their prescribed medicine correctly.
Your estimate will be lower than the pure treatment effect, since customers that don't receive the email will be counted as treated but will not show any effect. Your model will include the chance that a customer sees the email, so targeting will favor customer more likely to look at and act because of the email, which is likely what you want from targeting.
(If you want to compare different email headers or improve opening rates in others ways, you might want to come back and try to disentangle the effect in the future.)


text:
Q: Does a CLR stored procedure for SQL Server need to access the database? Currently I'm in a bit of a sticky situation where we can't get access to an external database and instead are pulling the data via their REST API. This data needs to be pulled prior to the execution of a stored procedure that performs analysis on the external data and our own.
My idea is to create a CLR stored procedure that would be called by the stored procedure doing the analysis which would run HTTP requests, deserialize the JSON, then stuff the data into our database.
Are there any potential timeout errors? Does a CLR stored procedure need to be pure HttpClient code? Why is this idea so terrible that I felt the need to confirm it with y'all on StackOverflow?
Thanks

A: This might be a good candidate for using SQL Server Service Broker.  The procedure call could simply put a message on a service queue.  You could then create a program that is activated when a message arrives to pull the requested data from the API and then responds with a message when it's done or errors out.  It also allows you to offload the API work from your SQL server if needed.  It's an Asynchronous solution, so whatever program is calling the procedure can do other work while it's waiting for the results if needed.


text:
Q: GridGain Out of Memory Exception I am trying to load around 600MB of data in the GridGain cache, I am trying to use the Swap Space to reduce the load on my RAM. I am loading the data from CSV files. I load the first 10000 keys in the memory then load the rest in the swap space. I was able to load 1350000 keys, but after that I am getting the below error :
[16:58:34,701][SEVERE][exchange-worker-#54%null%][GridWorker] Runtime error caught during grid runnable execution: GridWorker [name=partition-exchanger, gridName=null, finished=false, isCancelled=false, hashCode=20495511, interrupted=false, runner=exchange-worker-#54%null%]
java.lang.OutOfMemoryError: Java heap space
    at java.util.HashMap.resize(HashMap.java:559)
    at java.util.HashMap.addEntry(HashMap.java:851)
    at java.util.HashMap.put(HashMap.java:484)
    .
    .
    .
    at java.lang.Thread.run(Thread.java:722)

GridGain node stopped OK [uptime=00:21:14:384]

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

A: I think you are clearly running out of Heap space. In order for swap space to get utilized, you should configure eviction policy. Please refer to OffHeap Memory documentation for more information on how to configure Swap and OffHeap spaces.
Also, there is some more explanation for memory utilization in this post: Can I reduce the space of my cache memory?


text:
Q: Swift: conditional compilation flags must be valid Swift identifiers Today i downloaded the XCode 9.0 Beta 4 and after building my project i get the next warning messages
<unknown>:0: error: conditional compilation flags must be valid Swift identifiers (rather than '-Xfrontend')
<unknown>:0: error: conditional compilation flags must be valid Swift identifiers (rather than '-debug-time-function-bodies')
Command /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

I have tried several options like i have searched it here but cannot find any solution to this.

*

*Cleaned the project

*Cleaned the build folder

*Restarted XCode

*Restarted laptop

Anyone on this?

A: This issue appeared for me, while I started the app for the first time in Xcode 9.
I had duplicated values in Build Settings -> Other Swift Flags. After removal of duplications the app started to work as expected.

A: Locate in your project settings and individual target settings the following:
Other Swift Flags
Delete it.
Compile.

A: Other Swift Flags cannot have a value that contains a dash "-", but in Swift 3.2 the values do need a "-D" prefix

A: At some point, you or a coworker included those flags to see how long Xcode takes Swift files to compile. You can remove them as they don't affect compilation. Not sure if they are still supported but if they are, Active Compilation Conditions don't take the format of starting with a dash anymore it seems.

A: This worked for me, hopefully this may help other people:
Steps:

*

*Click on your project name in the upper left corner.

*Make sure you select your project, not targets

*Check if the Debug/Release fields in the "Active Compilation Conditions" contain '-Xfrontend' and/or '-debug-time-function-bodies', if so, try removing them (maybe write them down in case it doesn't work so you don't fuck things up even more lol)

*Clean Project, Restart Xcode, and if you're using CocoaPods, run a pod update

This is how I fixed my issue, which was almost exactly the same as yours, hope this helps. Good luck.


text:
Q: in rails erb file i want to display an output as a decimal only at one place where actually it is showing as a float value

    {{:stats.tot_fte}} Employees Assigned
      {{:stats.tot_fte_effort}} Total Effort

    {{:stats.tot_users}} Users Assigned
        {{:stats.tot_user_effort}} Total Effort

this is the code which i wrote to display total effort as output where i calculate total effort at some other place,where it should always be float value as i use it for other calculations.But while displaying this here i want it to be a decimal value with two numbers after the decimal.please help me in completing this as i am a beginner.
The output is as follows,

340 Employees Assigned   340.89666666666665 Total Effort
453 Users Assigned     452.6066666666666 Total Effort

i want the total effort display as a decimal value only here.

A: Since you are using Rails, it comes with a numbers helper in ActionView. You can use number_with_precision(number, options = {}).
For example:
number_with_precision 123.456, precision: 2

A: Old School:
sprintf('%.2f', number)

Other:
(340.89666666666665).round(2)

Example:
{{:stats.tot_user_effort.round(2)}} Total Effort
{{sprintf('%.2f', :stats.tot_user_effort)}} Total Effort


text:
Q: nginx add_header is not working I'm using nginx-1.7.0 on windows 7. I am trying to use add_header to get to a json file I have residing in /data/TESTFOLDER.
This is what my location block looks like:
    location /data/TESTFOLDER/ {
        add_header 'Content-Type' 'application/json';
        autoindex on;
    }

When I run my website, where in my javascript I have a jquery ajax request to get json files from this folder, firebug gives me this information:
ResponseHeaders
Connection  keep-alive
Content-Type    text/html
Date    Wed, 09 Jul 2014 14:01:29 GMT
Server  nginx/1.7.0
Transfer-Encoding   chunked

Request Headers
Accept  application/json
Accept-Encoding gzip, deflate
Accept-Language en-us,is;q=0.7,en;q=0.3
Content-Type    application/json
Host    localhost
Referer http:// local host/index.html
User-Agent  Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0
X-Requested-With    XMLHttpRequest

so you see the content-type hasn't changed as I would like it to. I have no add_header's elsewhere in my config file and the default is set to octet_stream like it should be.
A couple of things to note:

*

*The request "works", that is, I can access local host/data/TESTFOLDER/ from my browser

*mime.types are included in my config file

*mime.types contains application/json        json;

*my error log has no errors about this

Also, I'm very new to nginx and web servers in general, so please make your explanations simple to understand. :)

A: add_header does not replace existing header but adds a new one, possibly leading to duplicate that might be filtered when it is supposed to be unique and/or only the first one of its type is read.
Another possibility is that the HTTP status code from your response does not match the list defined in the docs for this directive, since you did not use the always parameter. The text/html you see might then be nginx' default 404 page.
Anyhow, what you want to use for your need is the default_type directive:
location /data/TESTFOLDER/ {
    default_type application/json;
    autoindex on;
}


text:
Q: How to continue play music on Ubuntu while switching users? I have ubuntu 12.04 installed. If i start playing music via built-in rhythmbox music player and switch user - music stops until i switch back :(. Is it possible to continue play music while switching to another user?

A: There is a launchpad bug concerning this issue. The suggested remedy is to change the 0 to a 1 for the "SYSTEM_START"-option in /etc/default/pulseaudio:
# Start the PulseAudio sound server in system mode.
# (enables the pulseaudio init script)
# System mode is not the recommended way to run PulseAudio as it has some
# limitations (such as no shared memory access) and could potentially allow
# users to disconnect or redirect each others audio streams. The
# recommend way to run PulseAudio is as a per-session daemon. For GNOME
# sessions you can install pulseaudio-esound-compat and GNOME will
# automatically start PulseAudio on login (if ESD is enabled in
# System->Preferences->Sound). For other sessions, you can simply start
# PulseAudio with "pulseaudio --daemonize".
# 0 = don't start, 1 = start
    PULSEAUDIO_SYSTEM_START=1

It is actually not a bug though, but a feature. For most people this is expected behavior. They don't want to have other users sound playing over their own. Additionally it is standard conformant.

A: I don't believe this is possible.
By the very nature of what you are doing "switching user" you are effectively logging out to transition from an environment with differing permissions and values of the other

A: You could open a screen-session (by using the "screen"-command, the "screen"-package may be installed by default, but I'm not sure)
Then, you could use something like mplayer (without a gui) from the command line. As the screen-session isn't terminated when logging out, mplayer will go on playing. This should work for every commandline-app, btw.


text:
Q: E488: Trailing characters in Vim mapping I want to map F5 on a command and typed:
:cmap <F5> :make | vert copen 100<CR>

Then I get E488. What to do?

A: Escape your |:
:cmap <F5> :make \| vert copen 100<CR>

Right now it tries to
cmap <F5> :make
and then
vert copen 100<CR>

Escaping the | delimiter ensure your mapping is preserved.
Be aware that the \| escaping may not always work, as stated in :help map_bar. Alternatives are: <Bar> and ^V|.
Thanks @Randy Morris.


text:
Q: Css :hover without "click" event for touch devices Let's say i have this html structure:

button

I need to show the button on .big-square:hover. It's simple, but what about touch devices? If i'll use simply .big-square:hover css rule, then if user will accidentally click at the location of button, then button will appear and will be clicked instantly. I want to avoid this situation. I've tried to use misc transition delays, but this doesn't work.
Here an example, to make it easier to understand and answer:
https://jsfiddle.net/hznjb8ur/
Jquery is there for sake of simplicity. I would like to avoid using jquery and even js for this case, because i have dozens and hundreds elements like that on a single page, so i'd prefer to solve this with simple css trick.

A: The actual "touchables" devices don't support hover because the screens don't know about the pointer (finger or anything else) position.
Microsoft actually is working on that http://www.theverge.com/2016/5/5/11595564/microsoft-3d-touch-kinect-gestures-windows-phones maybe in a near future we can see that behaviour

A: :hover is not supported by touch devices. :hover functions will only be activated when you click on it on touchscreens.
Why not displaying the button on touch devices instead of hiding it?
Else only jquery can help you.


text:
Q: How to edit native google documents programmatically? I found few quite depressive QA here which mentioned that google documents cannot be modified programmatically in Google Drive API - there`s just upload/download option.
I checked those similar topics :

*

*How to programmatically manipulate native google doc files

*How do you create a document in Google Docs programmatically?
As I suppose we cannot download and upload directly native google doc formats. Is there any other way how to solve this requirement ?
Has anyone tried to trigger google app script programmatically on selected document, is that possible ? Is possible to start google app script programmatically with some parameters on the input ?
I just need to replace few pieces of text in native google doc`s but i cannot use download->modify->upload (e.g. with formats word/html/pdf) flow as i would broken formatting of pictures,borders etc...  (customer requirement : full google integration no proprietary formats)
Do you have any innovative ideas or tips which would be good to explore ?
We are trying to use Google Drive as some kind of very simple templating system (~ thousands of users, hundreds of google documents) but it seems to be a really wrong idea as there is a lot of limitations on the way.

A: You can't use the Drive API to programmatically manage the content of a Google Document but you can use the Document Service in Apps Script to perform text replacing and other editing:
https://developers.google.com/apps-script/service_document

A: We invoke google app script deployed on the same domain as webapp which changes content of documents before we download them to proprietary format. We are just replacing few strings nothing complex.
This solution works but its a bit fragile (you have to install g app script + google app engine app in one domain), we are not sure how quickly are changes propagated after you trigger script so we wait always small amount of time e.g. 10 seconds before we try to download modified document.
Important disadvantage is that you cannot invoke GScript from localhost so development is a bit slower as we have to upload our app each time into google app engine.

A: Nowadays it's possible to use Java and other programming languages without having to use Google Apps Script by using the Google Docs API.
Also it is possible by using execute Google Apps Script code from other programming platforms by using Google Apps Script API, but it doesn't work with service accounts.
Notes:
There are some features available in the Google Docs user interface that aren't available in the Google Docs API.
Inserting content inside tables, that have rows and columns of different sizes might be complex due to the way that the indices work. Something that might help is to build the document from bottom to top.


text:
Q: Convert multiple tables from a html file to Excel preserving the CSS styles I have a html file and there are some tables, and I want to convert this html to Excel. Actually I can copy all page and paste it in Excel but I will have to repeat this process other html files. Can I use python for this process?

A: tablepyxl is supposed to do what you want.

A: You can use Pandas in Python.
import pandas as pd

df = pd.read_html(html_file)

writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

df.to_excel(writer, sheet_name='Sheet1')

writer.save()


text:
Q: What data modeling tools are nosql (couchdb) developers using? At some point, I assume that anyone developing for couchdb (or other nosql option) must still identify what must be stored in each document. And it would seem that, although very rarely, every once in a while we would need to have some relationships between these documents.
So, are people still using ER-type software (like Workbench for instance) to create a visual representation of the data stored in the different documents?  Is anyone working on developing nosql specific methods to identify the data that must be capture?
Right now we are using a bullet list in wiki pages, any suggestion for something better?

A: I don't anticipate tools like this to show up for a while, especially considering that CouchDB just released 1.0 a few months ago and there is still a lot that can change in the project. In addition, tools like this need to hold off until the real best practices come to light, but that can only come after years of real-world experience.
Although there are other reasons for this, relational databases simply didn't have graphical tools for years, if not decades. I can't imagine new database systems like these would progress much faster.

A: I would use a class diagram:

*

*replace every association with a composition or aggregation,

*see which classes must be read (as a whole) and modified,

*add simple attributes (strings or ints).

With this diagram, you have design hints:

*

*for "documents" granularity,

*URLs patterns,

*JSON "schemas".


text:
Q: Passing an inner array to a function I am trying to pass an inner array to a function in Perl.
Here is my Perl program.
#!/usr/bin/perl
use strict;
use warnings;

my %data = (
    'a' => (
        x => 'Hello',
        y => 'World'
    ),
    'b' => (
        x => 'Foo',
        y => 'Bar'
    )
);

#prototype
sub p(\%);

{ #main
    p(%data{'a'}); # should print "Hello Wolrd".
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}

Instead, I get the following error: Type of arg 1 to main::p must be hash (not key/value hash slice).
This works:
#!/usr/bin/perl
use strict;
use warnings;

#prototype
sub p(\%);

{ #main
    my %a = (
        x => 'Hello',
        y => 'World'
    );
    p(%a);
}

sub p(\%) {
    print "$_[0]{x} $_[0]{y}\n";
}

So there must be something wrong with the method call. But what? The content of a is a hash, so the first character after p( must be % (I tried p($data{'a'}); too, but it leaves me with another error (which seems logical, since the content of a isn't a scalar). I do not have to manually create a reference to the hash and dereference because I declare the function prototype. What am I missing?

A: Your definition of the structure is wrong. Inner hashes need to use {}, not ().
my %data = (
    a => {
        x => 'Hello',
        y => 'World'
    },
    b => {
        x => 'Foo',
        y => 'Bar'
    }
);

Also, to get a single hash element, use $data{'a'} (or even $data{a}), not %data{'a'}.
Moreover, see Why are Perl 5's function prototypes bad? on why not to use prototypes. After correcting the syntax as above, the code works even without the prototype. If you really need the prototype, use %, not \%. But you clearly don't know exactly what purpose prototypes serve, so don't use them.

A: There are no arrays in your code. And there are no method calls in your code.
Your hash is defined incorrectly. You cannot embed hashes inside other hashes. You need to use hash references. Like this:
my %data = (
    'a' => {
        x => 'Hello',
        y => 'World'
    },
    'b' => {
        x => 'Foo',
        y => 'Bar'
    }
);

Note, I'm using { ... } to define your inner hashes, not ( ... ).
That still gives us an error though.

Type of arg 1 to main::p must be hash (not hash element) at passhash line 20, near "})"

If that's unclear, we can always try adding use diagnostics to get more details of the error:

(F) This function requires the argument in that position to be of a certain type.  Arrays must be @NAME or @{EXPR}.  Hashes must be %NAME or %{EXPR}.  No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference.  See perlref.

Parameter type definitions come from prototypes. Your prototype is \%. People often think that means a hash reference. It doesn't. It means, "give me a real hash in this position and I'll take a reference to it and pass that reference to the subroutine".
(See, this is why people say that prototypes shouldn't be used in Perl - they often don't do what you think they do.)
You're not passing a hash. You're passing a hash reference. You can fix it by dereferencing the hash in the subroutine call.
p(%{$data{a}});

But that's a really silly idea. Take a hash reference and turn it into a hash, so that Perl can take its reference to pass it into a subroutine.
What you really want to do is to change the prototype to just $ so the subroutine accepts a hash reference. You can then check that you have a hash reference using ref.
But that's still overkill. People advise against using Perl prototypes for very good reasons. Just remove it.


text:
Q: JQuery: Script is working in console but not in attached file I'm working on a custom Wordpress site that has a lot of javascript (all developed by another developer)
I'm trying to add a script to the bottom of the scripts.js file and it's not working everywhere. It works in the console. It works in firefox.
It's inside it's own document ready function.
The document ready is working (I used an alert to test this), however my alert, console log and script inside this doc ready function will only work inside of the console (or firefox), but not from the scripts.js file in chrome and safari.
Here is my code (it's to make a video play and pause on click of the video window, not just the play controls)
  jQuery(document).ready(function () {
   // alert('working')
    /**
     *  This module controls the video players
     */
      jQuery('video').click(function(){
        //alert('working');
        this.paused?this.play():
        this.pause();
        //console.log(this);
    });

});

Any help is greatly appreciated.

A: Maybe it is a problem with the different JS-Engines !
Did you try what happens, if you move jQuery('video').click(function(){console.log(this);}); within the ready part of the old source of the file ?

A: I'm assuming this is because your video element is not actually present, or is being switched out, after the ready event fires.
It's possible that firefox happens to be loading the video element before your ready event fires, but this would likely vary on how fast the javascript and html are intepreted.
Instead of putting the event directly on the 'video' elements, put it on the document with a 'video' filter.
http://jsfiddle.net/2kmxL1h4/1/
jQuery(document).on('click', 'video', function () {
        //alert('working');
        this.paused ? this.play() : this.pause();
        //console.log(this);
    });


text:
Q: Convert pair of integers to tuples in Swift 4? I have an array, each element of which is an array of two ints (like coordinate pairs):
`[ [1, 2], [2, 2], [11, 9], ... ]`

Elsewhere in my program there are places that need that info but as type Coord, which is defined as a tuple of (x: Int, y: Int).
What would be the best way to iterate over each element in the array and convert it to Coord tuples of (x: Int, y: Int)?

A: When you are sure that there exists only two objects in an internal array of main array, then you should try this
func getToupleFrom(arr: [Int]) -> (Int, Int) {
    return (arr[0], arr[1])
}

Then define a global var to store the tuples, if you need them all together.
var arrayWithTuple: [(Int, Int)] = []

Your example array can have these values and can be iterated like this.
let arrayInt: [[Int]] = [[1,2], [3,4]]
    for arr in arrayInt {
        arrayWithTuple.append(getToupleFrom(arr: arr))
}

Try it and share results

A: You don't need to iterate, use map
let array = [ [1, 2], [2, 2], [11, 9]]
let tuples = array.map { ($0[0], $0[1]) }

However this will crash if the number of items in the inner arrays is less than 2.


text:
Q: How to keep edited values in an output datatable using shiny I am building a shiny app to add all input variables to a datatable.
I also have another button used to enable a second tabPanel and shows an editable datatable.
I would like to edit the table in the second tabPanel and update the datatable. So, when I continue to add more values it can keep the updates that have been done.
library("shiny")
library("dplyr")
library("DT")

ui <- fluidPage(
  tabsetPanel(
    id = "idTabset",
    tabPanel(
      value = "input_data",
      title = "Inpute Data",
      textInput(inputId   = 'item1', label = 'Item 1'),
      textInput(inputId   = 'item2', label = 'Item 2'),
      actionButton('save_data', 'Add'),
      actionButton('review_data', 'Save and Review')
    ),
    tabPanel(
      value = "input_tbl",
      title = "Raw Data",
      DT::dataTableOutput('output_tbl'),
      actionButton('submit_tbl', 'Upload')
    )
  )
)

server <- function(input, output, session) {
  hideTab(inputId = "idTabset", target = "input_tbl")

  user_tbl <- tibble(`Item 1` = as.character(),
                     `Item 2` = as.character())

  user_data <- reactive({
    tibble(`Item 1` = as.character(input$item1),
           `Item 2` = as.character(input$item2))
  })

  observeEvent(input$save_data, {
    user_tbl <<- user_tbl %>%
      bind_rows(user_data())

    output$output_tbl = DT::renderDataTable({
      DT::datatable(user_tbl, editable = TRUE)

    })

    sapply(c('item1','item2'),
           function(x) {updateTextInput(session, x, value = "")})
  })

  observeEvent(input$review_data, {
    showTab(inputId = "idTabset", target = "input_tbl")
  })

}

shinyApp(ui = ui, server = server)

Does anyone know how to keep the updated values?
Update: Thanks to @YBS
I am also creating the user_tbl outside, so I don't need to use a reactiveValues to assign the results.
library("shiny")
library("dplyr")
library("DT")

user_tbl <- data.frame(`Item 1` = as.character(),
                   `Item 2` = as.character(),
                   stringsAsFactors = FALSE)

ui <- fluidPage(
  tabsetPanel(
    id = "idTabset",
    tabPanel(
      value = "input_data",
      title = "Inpute Data",
      textInput(inputId   = 'item1', label = 'Item 1'),
      textInput(inputId   = 'item2', label = 'Item 2'),
      actionButton('save_data', 'Add'),
      actionButton('review_data', 'Save and Review')
    ),
    tabPanel(
      value = "input_tbl",
      title = "Raw Data",
      DT::dataTableOutput('output_tbl'),
    )
  )
)

server <- function(input, output, session) {
  hideTab(inputId = "idTabset", target = "input_tbl")

  user_data <- reactive({
    data.frame(`Item 1` = as.character(input$item1),
           `Item 2` = as.character(input$item2),
           stringsAsFactors = FALSE)
  })

  observeEvent(input$save_data, {
    user_tbl <<- user_tbl %>%
      bind_rows(user_data())

    output$output_tbl <- DT::renderDataTable({
      DT::datatable(user_tbl, editable = TRUE)

    })

    sapply(c('item1','item2'), function(x) {updateTextInput(session, x, value = "")})
  })

  observeEvent(input$output_tbl_cell_edit, {
    info = input$output_tbl_cell_edit
    i = info$row
    j = info$col
    v = info$value
    user_tbl[i, j] <<- DT::coerceValue(v, user_tbl[i, j])

  })

  observeEvent(input$review_data, {
    showTab(inputId = "idTabset", target = "input_tbl")
  })

}

shinyApp(ui = ui, server = server)

Thank you.

A: Perhaps you are looking for table_cell_edit feature of DT.  You need a reactiveValues object to keep track of changes in tab1 and tab2.  Try this
library("shiny")
library("dplyr")
library("DT")

ui <- fluidPage(
  tabsetPanel(
    id = "idTabset",
    tabPanel(
      value = "input_data",
      title = "Inpute Data",
      textInput(inputId   = 'item1', label = 'Item 1'),
      textInput(inputId   = 'item2', label = 'Item 2'),
      actionButton('save_data', 'Add'),
      actionButton('review_data', 'Save and Review')
    ),
    tabPanel(
      value = "input_tbl",
      title = "Raw Data",
      DT::dataTableOutput('output_tbl'),
      actionButton('submit_tbl', 'Upload')
    )
  )
)

server <- function(input, output, session) {
  hideTab(inputId = "idTabset", target = "input_tbl")

  user_tbl <- tibble(`Item 1` = as.character(),
                     `Item 2` = as.character())

  rv <- reactiveValues(data=user_tbl)

  user_data <- reactive({
    tibble(`Item 1` = as.character(input$item1),
           `Item 2` = as.character(input$item2))
  })

  observeEvent(input$save_data, {
    rv$data <<- rv$data %>%
      bind_rows(user_data())
    output$output_tbl = DT::renderDataTable({
      DT::datatable(rv$data, editable = TRUE)

    })

    sapply(c('item1','item2'),
           function(x) {updateTextInput(session, x, value = "")})
  })

  observeEvent(input$output_tbl_cell_edit, {
    info = input$output_tbl_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value

    rv$data[i, j] <<- DT::coerceValue(v, rv$data[i, j])

  })

  observeEvent(input$review_data, {
    showTab(inputId = "idTabset", target = "input_tbl")
  })

}

shinyApp(ui = ui, server = server)


text:
Q: large ccc forcing that preserves CH Can you name a ccc forcing with the following properties?
1) Atomless and separative
2) The least size of a dense set is large, say at least $\aleph_3$, hopefully as big as you like.
3) Existence is consistent with CH.
4) Preserves CH.
If you can think of any, please list as many as you can.

A: Thanks to Michael Blackmon for this idea:
If P has the ccc and preserves CH, then there is a contiuum sized regular suborder R that adds all the reals P will add.  The factor forcing P/R is ccc and $\omega$-distributive, a Suslin algebra.  A theorem (of Jech?) says that any Suslin algebra has size at most $2^{\omega_1}$.  So there is a bound on the size of P.

A: Here is a way to produce examples with arbitrarily large densities.
Let $\mathbb{P}$ be any c.c.c. forcing that preserves CH, such as
the forcing to add a Cohen real, and let $\mathbb{Q}=\kappa^\ast$
be the decreasing linear order of length $\kappa$, a large regular
cardinal. Consider the product partial order
$\mathbb{P}\times\mathbb{Q}$ as a notion of forcing. This is still
c.c.c., since all conditions in the second coordinate are
compatible as it is linear. But every dense set must also be dense
in the second coordinate and therefore have size at least $\kappa$.
Since the second coordinate is trivial as a forcing notion,
the product $\mathbb{P}\times\mathbb{Q}$ is forcing equivalent to
$\mathbb{P}$, which preserves CH, and so
$\mathbb{P}\times\mathbb{Q}$ has all your desired properties.
This kind of example, however, may lead you to modify the question, since it is not separative.