text:
Q: Excel vba to insert conditional format if cell in Sheet1 does not match same cell in Sheet2 I have tried to program this so when I create a workbook which is saved as an xlsx file, the vba in the workbook I am copying the data from copies conditional formatting to sheet1 of the new workbook. I need it to have the formula A1 <> Sheet2!A1 then text font is red. and then the next cell would be B1 <> Sheet2"B1 text font is red.
I need this to be copied to the active range. I tried this code, but it does not work for me. Have spent 2 weeks trying to find answers for this with no joy.
Application.CutCopyMode =False

Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
    "=A1<>Sheet2!A1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

With Selection.FormatConditions(1).Font
    .Color =-16776961
    .TintAndShade =0
EndWith

Selection.FormatConditions(1).StopIfTrue =False
Selection.Copy
Range("A1:S200").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False

A: Try replacing all of your code with this:
Dim newCondition As FormatCondition 'Red text if Sheet1 cell doesn't match Sheet2 cell.
Dim conditionFormula As String      'Formula for the format condition

' Compare each cell using indirect addressing of the current row and column. Result is
' true if the sheet cells don't match, false if they do.
conditionFormula = "=(INDIRECT(ADDRESS(ROW(),COLUMN(),1,1,""Sheet1"")) <>" & _
                   "  INDIRECT(ADDRESS(ROW(),COLUMN(),1,1,""Sheet2"")))"

' Create the condition and get a pointer to it.
Set newCondition = Range("A1:S200").FormatConditions.Add( _
                                    Type:=xlExpression, _
                                    Formula1:=conditionFormula)

' Add the formatting, priority, stop rule to the condition.
With newCondition
    .SetFirstPriority
    With .Font
        .Color = -16776961  ' Red
        .TintAndShade = 0
    End With
    .StopIfTrue = False
End With

' Clear the pointer
Set newCondition = Nothing

Naturally, the conditionFormula string declaration isn't necessary, but I like to write code that is easy to read and understand later. I've had too many times where I've come back later and wondered what #@%*&! I was trying to do.
Note that you could use ActiveSheet.UsedRange instead of Range("A1:S200"). That will guarantee that you always get all the cells that have data.
Finally, I have not fully qualified the Range() method in my code. Therefore Excel will guess which sheet you want to use. It might be better to be more explicit about which workbook and sheet you're talking about.  So, for example, when you create your new workbook, do something like this:
Dim newWorkbook As Workbook

Set newWorkbook = Workbooks.Open(.... whatever you do here...)

Then, you can replace Range("A1:S200") with
newWorkbook.Worksheets(1).Range("A1:S200")

or even
newWorkbook.Worksheets(1).UsedRange

Hope all that helps. Sorry for the length.


text:
Q: Kotlin Android Navigation to Fragment don't work in setOnItemClickListener I am in a fragment with listview and a working onItemClickListener.
When I test the onItemClickListener e.g. by showing a toast everything works.
This is how my file looks like:
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        with (binding) {
            val arrayAdapter: ArrayAdapter<*>
            val employeeCategories = arrayOf(
                "Test", "Test2", "Test3"
            )

            arrayAdapter = ArrayAdapter(
                activity!!,
                android.R.layout.simple_list_item_1, employeeCategories)

            employeeListView.apply {
                adapter = arrayAdapter
            }

            employeeListView.setOnItemClickListener{parent, view, position, id ->
                if (position==0){
                    Toast.makeText(activity, "Item One",   Toast.LENGTH_SHORT).show()
                }

            }
        }
    }

To navigate from this fragment to another, I want to do the following when a List Item is clicked:
            activity!!.findNavController(R.id.nav_host_fragment).popBackStack()
            activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_help)

If I add this outside the onItemClickListener, it also navigates successfully. However, if I add the same in the onItemClickListener, at the place where the toast was before for testing, it does not work anymore. There is no navigation after I have clicked on an item:

            activity!!.findNavController(R.id.nav_host_fragment).popBackStack()
            activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_help)  <---- WORKS!

            employeeListView.setOnItemClickListener{parent, view, position, id ->
                if (position==0){
                    activity!!.findNavController(R.id.nav_host_fragment).popBackStack()
                    activity!!.findNavController(R.id.nav_host_fragment).navigate(R.id.navigation_help)  <---- DONT WORKS! :(
                }

I am still relatively new to Kotlin and unfortunately cannot explain why this works outside of the onItemClickListener but not in combination with it. Can someone possibly tell me what this could be related to?

A: Can you add as a global variable (outside of your onViewCreated method) the following:
private val navController by lazy { findNavController() }

and afterwards do the this:
employeeListView.setOnItemClickListener{parent, view, position, id ->
                if (position==0){
                   navController.popBackStack()
                   navController.navigate(R.id.navigation_help)
                }

and let me know if it works now?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to connect properly to Elasticsearch cloud using API key and python lib? Created API key under Elastic cloud (hosted on aws).
Doc declare a proper auth header should be attached:
Authorization: ApiKey $EC_API_KEY

Using curl it works:
curl -i -H "authorization: ApiKey LONG_KEY_STRING=="  https://12345.us-east-2.aws.elastic-cloud.com:9243/_health

HTTP/2 200
x-cloud-request-id: 1234abc
content-type: text/plain; charset=utf-8
content-length: 34
date: Thu, 22 Oct 2020 12:36:54 GMT

{
  "ok": true,
  "status": 200
}

But the following python code (elasticsearch-7.9.1) fail:
es = Elasticsearch(['https://12345.us-east-2.aws.elastic-cloud.com:9243'], api_key="LONG_KEY_STRING==")
print(es.cluster.health())

With error:
{
    "errorMessage": "AuthenticationException(401, 'security_exception', 'missing authentication credentials for REST request [/_cluster/health]')",
    "stackTrace": [
        "  File \"/path/venv/lib64/python3.7/site-packages/lambda_local/main.py\", line 153, in execute\n    result = func(event, context._activate())\n",
        "  File \"main.py\", line 35, in handler\n    post_ping_doc(ping, msg[KEY_ID])\n",
        "  File \"main.py\", line 45, in post_ping_doc\n    print(es.cluster.health())\n",
        "  File \"/path/elasticsearch/client/utils.py\", line 152, in _wrapped\n    return func(*args, params=params, headers=headers, **kwargs)\n",
        "  File \"/path/elasticsearch/client/cluster.py\", line 69, in health\n    headers=headers,\n",
        "  File \"/path/elasticsearch/transport.py\", line 392, in perform_request\n    raise e\n",
        "  File \"/path/elasticsearch/transport.py\", line 365, in perform_request\n    timeout=timeout,\n",
        "  File \"/path/elasticsearch/connection/http_urllib3.py\", line 269, in perform_request\n    self._raise_error(response.status, raw_data)\n",
        "  File \"/path/elasticsearch/connection/base.py\", line 301, in _raise_error\n    status_code, error_message, additional_info\n"
    ],
    "errorType": "AuthenticationException"
}

Tried other variations while browsing the net, all with the same result.
Fired up a local ncat -l 1234 and redirected the request to it. request seems legit...
GET / HTTP/1.1
Host: 127.0.0.1:1234
Accept-Encoding: identity
connection: keep-alive
content-type: application/json
user-agent: elasticsearch-py/7.9.1 (Python 3.7.5)
authorization: ApiKey LONG_KEY_STRING==

Python code does work with local unsecured ES on docker (not requiring any key).
Currently out of idea, any help is appreciated.

A: According to the docs you do not need to specify the host. I have tried this and it works for me.
es = Elasticsearch(api_key="LONG_KEY_STRING==")
print(es.cluster.health()) # should print a healthy status!


text:
Q: Php form (using PDO) to insert into other tables (foreign keys) I need some help, I am trying to insert into multiple tables using PDO - Can someone see what I am doing wrong - I am not getting a parse errors (nor did I set up an asset error):
Here is my form:
addcontact.php
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Add New Contact</title>
<link rel="stylesheet" href="css/table.css" type="text/css" />

<form action="insert.php" method="post">

Contact Name:
    <input type="text" name="ContactName" id="ContactName">

 Contact Type:

<select name="ContactTypeId">
<option value="1">Contact</option>
<option value="2">Organization</option>

</select>

 Address Type:

<select name="AddressTypeId">
<option value="1">Home</option>
<option value="2">Office</option>
<option value="3">Other</option>

</select>

Address 1:
    <input type="text" name="Address1" id="Address1">

Address 2:
    <input type="text" name="Address2" id="Address1">

City:
    <input type="text" name="City" id="Address1">

 State:

<select name="StateId">
<option value="1">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">Califorina</option>
<option value="6">Colorado</option>
<option value="7">Connecticut</option>
<option value="8">Delaware</option>
<option value="9">District of Columbia</option>
<option value="10">Florida</option>
<option value="11">Georgia</option>
<option value="12">Hawaii</option>
<option value="13">Idaho</option>
<option value="14">Illinois</option>
<option value="15">Indiana</option>
<option value="16">Iowa</option>
<option value="17">Kansas</option>
<option value="18">Kentucky</option>
<option value="19">Louisana</option>
<option value="20">Maine</option>
<option value="21">Maryland</option>
<option value="22">Massachusetts</option>
<option value="23">Michigan</option>
<option value="24">Minnesota</option>
<option value="25">Mississippi</option>
<option value="26">Missouri</option>
<option value="27">Montana</option>
<option value="28">Nebraska</option>
<option value="29">Nevada</option>
<option value="30">New Hampshire</option>
<option value="31">New Jersey</option>
<option value="32">New Mexico</option>
<option value="33">New York</option>
<option value="34">North Carolina</option>
<option value="35">North Dakota</option>
<option value="36">Ohio</option>
<option value="37">Oklahoma</option>
<option value="38">Oregon</option>
<option value="39">Pennsylvania</option>
<option value="40">Rhode Island</option>
<option value="41">South Carolina</option>
<option value="42">South Dakota</option>
<option value="43">Tennessee</option>
<option value="44">Texas</option>
<option value="45">Utah</option>
<option value="46">Vermont</option>
<option value="47">Virginia</option>
<option value="48">Washington</option>
<option value="49">West Virginia</option>
<option value="50">Wisconsin</option>
<option value="51">Wyoming</option>
</select>

<input type="submit" value="Add Record">

</form>

Here is insert.php
<?php

$servername = "localhost";

$username = "root";

$password = "root";

$dbname = "crm";

//making an array with the data received, to use as named placeholders   for INSERT by PDO.

$data = array('ContactName' => $_POST['ContactName'] , 'ContactTypeId'
=> $_POST['ContactTypeId'],

'ContactId'=> $_POST['ContactId'],'AddressTypeId'=>

$_POST['AddressTypeId'],'Address1'=>$_POST['Address1'],
 'Address2'=>$_POST['
  Address2'],'City'=>$_POST['City'],'StateId'=>$_POST['StateId']);
 try {
 // preparing database handle $dbh

 $dbh = new PDO("mysql:host=$servername;dbname=$dbname",

 $username,$password);
// set the PDO error mode to exception

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$currentID = mysql_inserted_id();

// query with named placeholders to avoid sql injections

$query = "INSERT INTO Contacts (ContactName, ContactTypeId)
VALUES(:ContactName, :ContactTypeId )";

 $query2= "INSERT INTO
 Addresses(ContactId,AddressTypeId,Address1,Address2,City,StateId)
VALUES(:$currentID,:AddressTypeId,:Address1,:Address2,:City,:StateId)";
//statement handle $sth
$sth = $dbh->prepare($query);
$sth->execute($data);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "
" . $e->getMessage();
}
$dbh = null;
?>

A: You need to create two arrays $data for $query & $data1 for $query1 and need   use $dbh->lastInsertId() for last id. Use the below code. I think it will work:
<?php

    $servername = "localhost";

    $username = "root";

    $password = "root";

    $dbname = "crm";

    //making an array with the data received, to use as named placeholders   for INSERT by PDO.

    $data = array('ContactName' => $_POST['ContactName'] , 'ContactTypeId'
    => $_POST['ContactTypeId']);

    $data1=array('AddressTypeId'=>$_POST['AddressTypeId'],'Address1'=>$_POST['Address1'],
     'Address2'=>$_POST['
      Address2'],'City'=>$_POST['City'],'StateId'=>$_POST['StateId']);
     try {
     // preparing database handle $dbh

     $dbh = new PDO("mysql:host=$servername;dbname=$dbname",

     $username,$password);
    // set the PDO error mode to exception

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // query with named placeholders to avoid sql injections

    $query = "INSERT INTO Contacts (ContactName, ContactTypeId)
    VALUES(:ContactName, :ContactTypeId )";
    $sth = $dbh->prepare($query);
    $sth->execute($data);

    $currentID = $dbh->lastInsertId();

     $query2= "INSERT INTO
     Addresses(ContactId,AddressTypeId,Address1,Address2,City,StateId)
    VALUES($currentID,:AddressTypeId,:Address1,:Address2,:City,:StateId)";

    $sth = $dbh->prepare($query2);
    $sth->execute($data1);

    //statement handle $sth

    echo "New record created successfully";
    }
    catch(PDOException $e)
    {
    echo $sql . "
" . $e->getMessage();
    }
    $dbh = null;
    ?>


text:
Q: Translate minicart , captcha module and other module Magento2 I have a website with 3 differents language : arabic, french , english. i created the i18n under my

app/code/Maget/MyModule/i18n

but there is the minicart, captcha module, strength of password and other text not translated to the french none to arabic. Can any one explain to me how to create and install the french and arabic patch of translation step by step?


text:
Q: How to stop Windows 10 Home from automatic restarts I did run my overnight computations and when I came to my computer, it is restarted :-( I am not sure why, but it is quite possible that it could have been automatic restart due to updates.
How do I stop Windows 10 from automatic restarts?
I have found this setting:

and I did apply it now, but is it enough to block all automatic restarts, even when I am not present at the computer and cannot react to the notification? In the past I noticed that some similar notifications had a countdown timer and if you didn't react, it restarted the computer (quite stupid, but that's how it SW nowadays...).

A: Yes, this is enough to stop the computer from automatically restarting, after installing updates you will be prompted to manually schedule a restart.


text:
Q: vb6:Dynamically changing Combo box to text box I have a form with a combo box. Currently It displays the available values from the database. But for a particular scenario, I wants it dynamically change to a text box so that the user can manually enter the value. Can I do it in the same form. If I use a second form,I can solve this problem. But I want to do it with little code changes. Can someone provide some ideas?

A: You can set DropDownStyle to DropDown.
My bad. Indeed, in vb6 the style property can't be changed during runtime.

*

*You can hide/show desired control.

*Try using Locked property.

A: I used a combo array(combobox(0),combobox(1)) with two different styles(simple combo and dropdowncombo) and made it visible and disable at runtime using the Visible property


text:
Q: PDF creation is ok but retrieve from the database getting row space I am using HTML to PDF method for PDF geneartion in PHP.I retrieved data from the database successfully.I am getting the More Spaces between the rows why??
Please advise me.
This is my code...
require('WriteHTML.php');
include('connection.php');
$result = pg_query($db,"SELECT dvn_cd, allotment_date,allotment_no,quantity FROM ddhs_receipt_entry ");

$pdf=new PDF_HTML();

$pdf->AliasNbPages();
$pdf->SetAutoPageBreak(true, 15);

$pdf->AddPage();
$pdf->Image('logo.png',18,13,33);
$pdf->SetFont('Arial','B',14);
$pdf->WriteHTML('<para>
Title

');

$pdf->SetFont('Arial','B',7);
$htmlTable='

Name
Email
URl
Comment

';

$pdf->WriteHTML2("$htmlTable");
while($value = pg_fetch_array($result)) {

$htmlTable2='

'.$value['dvn_cd'].'
'.$value['allotment_date'].'
'.$value['allotment_no'].'
'.$value['quantity'].'

';
$pdf->WriteHTML2("$htmlTable2");
$pdf->SetFont('Arial','B',6);

 }

 $pdf->Output();

A: What you're doing is actually outputting lots of separate tables, and you want a single one. Try moving
 outside the while loop:
$htmlTable = '

    Name
    Email
    URl
    Comment

';    // The table is opened at the start of this block, and headers are output

while($value = pg_fetch_array($result)) {

    $htmlTable .= '

        '.$value['dvn_cd'].'
        '.$value['allotment_date'].'
        '.$value['allotment_no'].'
        '.$value['quantity'].'

';    // Each row of your table is added to the string here

}

$htmlTable .= '
';    // The table is closed here

$pdf->WriteHTML2("$htmlTable");    // The table is written here

$pdf->Output();

A: Try this :
while($value = pg_fetch_array($result)) {

$htmlTable2='

    '.$value['dvn_cd'].'
    '.$value['allotment_date'].'
    '.$value['allotment_no'].'
    '.$value['quantity'].'

';
$pdf->WriteHTML2("$htmlTable2");
$pdf->SetFont('Arial','B',6);

 }
$htmlTable='
';


text:
Q: Bulk Insert with Mariasql Node js I want to perform bulk insert operation using Mariasql Node Js module, but it is showing error "Column count dosen't match value count at Row 1"
Below is my code :
var queryObj= [["Test1","false"],["Test2","true"]]
mariaDb.query("INSERT INTO apps (app_name,status) values (app_name=?,status=?)",queryObj,{useArray:true},mycallback)

Database scheme is also having two columns with varchar(10)
Could anyone please help what I am doing wrong


text:
Q: Importing Django 2.0 utility functions (vs. django 1.1) I'm upgrading my application from Django 1.11 to Django 2.0.
I understand from the documentation on utility functions in v.2.0:
from django.core.urlresolvers import reverse needs to change to from django.urls import reverse
But does this also apply to importing resolve? For example, should from django.core.urlresolvers import resolve be changed to from django.urls import resolve?

A: As the Django-2.0 release notes specify:

*

*The django.core.urlresolvers module is removed in favor of its new location, django.urls.

So yes, all the functions that originally resided in the django.core.urlresolvers now are located in the django.urls module.
The page you link to is named django.urls utility functions, so all the documented functions are part of the django.urls module.
In case you migrate, I advise to read the release-notes. Especially the Backwards incompatible changes in 2.0 section is useful, since it tells what changes you have to make to migrate your project to the next Django version.


text:
Q: Many users update the same data at the same time in mongdb I am new to mongdb. I store a counter variable in the database. Every time a user performs a certain action, the counter variable's value will be incremented by 1. The question I wonder is if multiple users update the counter at the same time, will the counter hold the correct value? (expect that the counter will increment exactly by the number of updates). If this causes a logic error, how do I resolve it?

A: A good question, this race condition can be solved in the similar fashion that you have mentioned already.
{
  item_id : <id>,
  version : <Number>,
  updated_by : <something>
}

When you fetch this document to update you will get the whole document, now during the write the system takes a granular document level lock, so that won't be a problem.
While updating update's query part should have both item_id & version and along with other content you update - increment the version of the document as well.
If two copy of the same document has been received for update by the backend, the one which comes late will have previous version therefore it won't be able to update anything.
Now handle that flow where the document was changed before the user can push their change to the system.


text:
Q: Parsing binary message stream in C/C++ I'm writing a decoder for a binary protocol (Javad GRIL protocol). It consists of about a hundred messages, with data in the following format:
struct MsgData {
    uint8_t num;
    float x, y, z;
    uint8_t elevation;
    ...
};

The fields are ANSI-encoded binary numbers which follow each other with no gaps. The simplest way to parse such messages is to cast an input array of bytes to the appropriate type. The problem is that the data in stream are packed, i.e. unaligned.
On x86 this can be solved by using #pragma pack(1). However, that won't work on some other platforms or will incur performance overhead due to further work with misaligned data.
Another way is to write a specific parse function for each message type, but as I've mentioned, the protocol includes hundreds of messages.
Yet another alternative is to use something like the Perl unpack() function and store the message format somewhere. Say, we can #define MsgDataFormat "CfffC" and then call unpack(pMsgBody, MsgDataFormat). This is much shorter but still error-prone and redundant. Moreover, the format can be more complicated because messages can contain arrays, so the parser will be slow and complex.
Is there any common and effective solution? I've read this post and Googled around but didn't find a better way to do it.
Maybe C++ has a solution?

A: Ok, the following compiles for me with VC10 and with GCC 4.5.1 (on ideone.com). I think all this needs of C++1x is <tuple>, which should be available (as std::tr1::tuple) in older compilers as well.
It still needs you to type some code for each member, but that is very minimal code. (See my explanation at the end.)
#include <iostream>
#include <tuple>

typedef unsigned char uint8_t;
typedef unsigned char byte_t;

struct MsgData {
    uint8_t num;
    float x;
    uint8_t elevation;

    static const std::size_t buffer_size = sizeof(uint8_t)
                                         + sizeof(float)
                                         + sizeof(uint8_t);

    std::tuple<uint8_t&,float&,uint8_t&> get_tied_tuple()
    {return std::tie(num, x, elevation);}
    std::tuple<const uint8_t&,const float&,const uint8_t&> get_tied_tuple() const
    {return std::tie(num, x, elevation);}
};

// needed only for test output
inline std::ostream& operator<<(std::ostream& os, const MsgData& msgData)
{
    os << '[' << static_cast<int>(msgData.num) << ' '
       << msgData.x << ' ' << static_cast<int>(msgData.elevation) << ']';
    return os;
}

namespace detail {

    // overload the following two for types that need special treatment
    template<typename T>
    const byte_t* read_value(const byte_t* bin, T& val)
    {
        val = *reinterpret_cast<const T*>(bin);
        return bin + sizeof(T)/sizeof(byte_t);
    }
    template<typename T>
    byte_t* write_value(byte_t* bin, const T& val)
    {
        *reinterpret_cast<T*>(bin) = val;
        return bin + sizeof(T)/sizeof(byte_t);
    }

    template< typename MsgTuple, unsigned int Size = std::tuple_size<MsgTuple>::value >
    struct msg_serializer;

    template< typename MsgTuple >
    struct msg_serializer<MsgTuple,0> {
        static const byte_t* read(const byte_t* bin, MsgTuple&) {return bin;}
        static byte_t* write(byte_t* bin, const MsgTuple&)      {return bin;}
    };

    template< typename MsgTuple, unsigned int Size >
    struct msg_serializer {
        static const byte_t* read(const byte_t* bin, MsgTuple& msg)
        {
            return read_value( msg_serializer<MsgTuple,Size-1>::read(bin, msg)
                             , std::get<Size-1>(msg) );
        }
        static byte_t* write(byte_t* bin, const MsgTuple& msg)
        {
            return write_value( msg_serializer<MsgTuple,Size-1>::write(bin, msg)
                              , std::get<Size-1>(msg) );
        }
    };

    template< class MsgTuple >
    inline const byte_t* do_read_msg(const byte_t* bin, MsgTuple msg)
    {
        return msg_serializer<MsgTuple>::read(bin, msg);
    }

    template< class MsgTuple >
    inline byte_t* do_write_msg(byte_t* bin, const MsgTuple& msg)
    {
        return msg_serializer<MsgTuple>::write(bin, msg);
    }
}

template< class Msg >
inline const byte_t* read_msg(const byte_t* bin, Msg& msg)
{
    return detail::do_read_msg(bin, msg.get_tied_tuple());
}

template< class Msg >
inline const byte_t* write_msg(byte_t* bin, const Msg& msg)
{
    return detail::do_write_msg(bin, msg.get_tied_tuple());
}

int main()
{
    byte_t buffer[MsgData::buffer_size];

    std::cout << "buffer size is " << MsgData::buffer_size << '\n';

    MsgData msgData;
    std::cout << "initializing data...";
    msgData.num = 42;
    msgData.x = 1.7f;
    msgData.elevation = 17;
    std::cout << "data is now " << msgData << '\n';
    write_msg(buffer, msgData);

    std::cout << "clearing data...";
    msgData = MsgData();
    std::cout << "data is now " << msgData << '\n';

    std::cout << "reading data...";
    read_msg(buffer, msgData);
    std::cout << "data is now " << msgData << '\n';

    return 0;
}

For me this prints

buffer size is 6
initializing data...data is now [0x2a 1.7 0x11]
clearing data...data is now [0x0 0 0x0]
reading data...data is now [0x2a 1.7 0x11]

(I've shortened your MsgData type to only contain three data members, but this was just for testing.)
For each message type, you need to define its buffer_size static constant and two get_tied_tuple() member functions, one const and one non-const, both implemented in the same way. (Of course, these could just as well be non-members, but I tried to keep them close to the list of data members they are tied to.)
For some types (like std::string) you will need to add special overloads of those detail::read_value() and detail::write_value() functions.
The rest of the machinery stays the same for all message types.
With full C++1x support you might be able to get rid of having to fully type out the explicit return types of the get_tied_tuple() member functions, but I haven't actually tried this.

A: My solution for parsing binary input is to use a Reader class, so per message entry you can define what is read and the reader can check for overruns,underruns,... .
In you case:
msg.num = Reader.getChar();
msg.x = Reader.getFloat();
msg.y = Reader.getFloat();
msg.z = Reader.getFloat();
msg.elevation = Reader.getChar();

It still is a lot of work and error-prone, but at least it helps checking for errors.

A: Simple answer is no, if the message is a specific binary format that cannot be simply casted, you have no choice but to write a parser for it. If you have the message descriptions (say xml or some form of easily parsed description), why don't you generate the parsing code automatically from that description? It won't be as fast as a cast, but will be damn sight faster generating than writing each message by hand...

A: I don't think you can avoid writing specicfic parsing routine for every message in pure C++ (without using pragma).
If all your messages are simple, POD, C-like structures, I think the easiest solution would be to write a code generator: put your structs in a header without other C++ stuff and write a simple parser (a perl/python/bash script using a couple of regular expressions should be enough) -or look for one- that is able to find the variable names in any message; then use it to automatically generate some code for any message to read it, like this:
YourStreamType & operator>>( YourStreamType &stream, MsgData &msg ) {
    stream >> msg.num >> msg.x >> msg.y >> msg.z >> msg.elevation;
    return stream;
}

specialize YourStreamType's operator>> for any basic type your messages contain and you should be done:
MsgData msg;
your_stream >> msg;

A: You can always align your memory yourself:
uint8_t msg[TOTAL_SIZE_OF_THE_PARTS_OF_MsgData];

As sizeof(MsgData) returns the size of MsgData + padding bytes, you can calculate
enum { TOTAL_SIZE_OF_THE_PARTS_OF_MsgData =
    2*sizeof(uint8_t)+
    3*sizeof(float)+sizeof(THE_OTHER_FIELDS)
}

Using enums for such constants is a well proven concept on several machines.
read a binary message into the msg array. Later you can cast the values into the MsgData values:
unsigned ofs = 0;
MsgData M;
M.num = (uint8_t)(&msg[ofs]);
ofs += sizeof(M.num);
M.x = (float)(&msg[ofs]);
ofs += sizeof(M.x);

and so forth...
or use memcpy if you don't like the type casts:
memcpy(&M.x,&msg[ofs],sizeof(M.x)); ...


text:
Q: How to use PCA for time-series predictions on highly correlated variables? say I have a dataset called Economic_Trends, and it contains 5 columns with 10 years of data. So for example,
Economic_Trend <- matrix(c(1:10, 2:11, rnorm(30)), byrow = FALSE, nrow = 10, ncol = 5)

Then this is the code that I run:
mu <- colMeans(Economic_Trend)

Econ_pca <- prcomp(Economic_Trend)

PCA1 <- Econ_pca$x[,1]
PCA2 <- Econ_pca$x[,2]

plot(Econ_pca$x[,1], Econ_pca$x[,2])
plot(lm(PCA1 ~ PCA2))

I see that I now have the two principal components, but I am not sure where to find the order because what if the years are messed up? I want to do prediction such that I can find the next 10 years, for example. How do I fit my PC's to a regression model, find the next steps in the time series, then reconstruct the original data?
Thanks!

A: The big thing is to save your PCs as times series (ts) objects, to retain their order. Here's some code to help with that, and to plot the PCs:
require(xts)  ## Makes autoplot work
require(ggfortify)  ## Allows multiple PCs to be plotted in one graph
## Maybe some others

## Given code:
Economic_Trend <- matrix(c(1:10, 2:11, rnorm(30)), byrow = FALSE, nrow = 10,
ncol = 5)
mu <- colMeans(Economic_Trend)

## Tweaked code:
Econ_pca <- prcomp(Economic_Trend[,3:5]) ## First two columns are order
## number
PCA1 <- ts(Econ_pca$x[,1])  ## Save first PC as a time series object
PCA2 <- ts(Econ_pca$x[,2])  ## Save second PC as a time series object
p <- autoplot(ts(cbind(PCA1,PCA2)), facets = FALSE) +
     ## Create ggplot object plotting first 2 PCs
     ggtitle("First two PCs") + ylab("Econ ($?)") + ## Add plot and y-axis labels
     theme_bw() +  ## Remove grayscale background grid
     theme(axis.text=element_text(size=rel(1)),legend.text = element_text(size = 12))
p  ## Display plot

A: I do not see your data. However, if there is 'trend' in names, then probably the series have trends and you want to forecast them.
It is better to apply a special version of PCA designed for time series. This is singular spectrum analysis (SSA).
library(Rssa)
library(lattice)
# Decompose 'EuStockMarkets' series with default parameters
ss <- ssa(EuStockMarkets, kind = "mssa")
rec <- reconstruct(ss, groups = list(Trend = 1:2))

foreca <- rforecast(ss, groups = list(Trend = 1:2),
                    len = 200, only.new = TRUE)
data <- cbind(EuStockMarkets, rec$Trend, foreca)
xyplot(data, type = "l", superpose = TRUE,
       auto.key = list(columns = 3),
       col = c("blue", "darkgreen", "red", "violet"),
       lty = c(rep(2, 4), rep(1, 4), rep(3, 4)))


text:
Q: Excel file locked after opening in Microsoft Data Report Designer I develop an application in VB6 and my data source is Excel 2007. And I have created 2 reports in Microsoft Data Report Designer.
My program is working. I can save data (update)in excel file and view existing data via VB6. And I have written code to backup (copy paste) the excel file in another folder. This is also working as I wanted.
But after I open or view the DataReports, I cant save the data in the Excel and backup the excel file. Then I will have to close the application to update and backup excel sheet.
When I try to save data in Excel file after viewing the report I receive the message

The excel file already exists

When I try to backup after viewing and closing the report I receive the error message

Run time error 70" Permission denied

Need help please.


text: Q: Терминал Wsl и Power shell не выполняют команду node.js Пытаюсь освоить Node.js и как-то не выходит. Пакет установил под виндоус, в Path указал путь, через npm поставил в Wsl терминал, но тем не менее когда пытаюсь запустить файл командой node index.js, выдаёт ошибку. Сижу туплю.


text:
Q: Apache Storm on windows 8 or ubuntu (VMware Player)? I want to set up Apache Storm on Windows 8 but I'm not sure whether this is the best choice and what would be needed to do this. Or would you recommend to set up Storm on a VM (VMware player) with Ubuntu instead? At the end I want to scale-out Apache Storm on the EC2 Cloud.
Thanks for any tips in advance!

A: I would use ubuntu on some form of virtual machine for several reasons.  First, it's always good to develop on at least a variant of the production OS.  Second, installs of server software are sometimes a bit complicated and invasive.  It often helps to use a virtual machine to isolate those changes from your system making it easier to throw the VM out and try again.  Also, as newer versions of, in this case, Storm come out, you can install those versions on a clean system without overloading your existing dev environments.  There are costs and you'll need a decent host system to handle to load.


text:
Q: Pushing to heroku fails due to sqlite3 on Mac I've seen multiple questions, all with the same problems as me. I tried all the solutions proposed, such as making the following my Gemfile
group :development, :test do
    gem 'sqlite3'
end
group :production do
    gem 'pg'
end

Added, committed, and nothing. Still the same issue when I run git push heroku master:
em::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
tmp/build_d2c698fb-cf76-40cd-b046-9866c3432e8b/vendor/ruby-2.0.0/bin/ruby extconf.rb
   checking for sqlite3.h... no
   sqlite3.h is missing. Try 'port install sqlite3 +universal',
   'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'
   and check your shared library search path (the
   location where your sqlite3 shared library is located).

I tried installing Xcode to see if that solves it, but it didn't. Ran brew install sqlite3 which also didn't solve it.
I also checked the dependencies of my gems in my Gemfile, with gem dependency and also checking the Gemfile.lock file, which shows no dependencies for the sqlite3 gem.
I can't find a solution to this problem from existing questions. Maybe I skimmed over something I am missing, but I can't find it.
Some extra information:
$ rails -v
Rails 4.1.1

$ ruby -v
ruby 2.0.0p451 (2014-02-24 revision 45167) [x86_64-darwin13.1.0]

$ gem -v
2.2.2

$ sqlite3 -version
3.7.13 2012-07-17


text:
Q: Using ruby map method and excluding current user I have an activity feed that currently show all activity including current user. My goal is to only update the feed with friends' activity and not the current user's activity. I believe it has something to do with the map(&:id) method, but I'm not positive. Any guidance would be super awesome!
activity.rb:
class Activity < ActiveRecord::Base
    belongs_to :user
    belongs_to :targetable, polymorphic: true

  self.per_page = 10

  def self.for_user(user, options={})
    options[:page] ||= 1
    # return WillPaginate::Collection.new(1, per_page, 1) unless user
    friend_ids = user.friends.map(&:id).push(user.id)
    collection = where("user_id in (?)", friend_ids).order("created_at desc")

    if options[:since] && !options[:since].blank?
      since = DateTime.strptime( options[:since], '%s' )
      collection = collection.where("created_at > ?", since) if since
    end
    collection.page(options[:page])
  end

  def user_name
    user.name
  end

  def username
    user.username
  end

  def as_json(options={})
    super(
        only: [:action, :id, :targetable_id, :targetable_type, :created_at, :id],
        include: :targetable,
        methods: [:user_name, :username]
    ).merge(options)
  end
end

A: The .push(user.id) is adding the user's own ID onto this list of friend IDs so if you just remove that you'll get the activities for just the friends.
friends.map(&:id) takes the list of the user's friends and maps this to a list of the IDs for those friends ready for use in the where condition on the next line i.e. it calls id on each friend and returns an array of the results of that.


text:
Q: jquery setting value to null option of select how to setting default value for empty or null value of option:
HTML:
<select name="master_id" id='master_id' >
    <option value="">  -   -   -   </option>

or
<select name="master_id" id='master_id' >
    <option>  -   -   -   </option>

DEMO

A: i found it:
<select name="master_id" id='master_id' >
    <option>  -   -   -   </option>

JQUERY
$('#test option:not([value])').prop('selected', true)


text:
Q: How to scale different sized videos proportionally in flash? So I have created my vdeo player , but Im havin problems handling different sized videos. How to properly scale videos proportionally?
I get original width and height from metadata object:
        private function onMetaData(newMeta:Object):void
        {
            _height = newMeta.height;
            _width = newMeta.width;
            scaleProportional();
        }

A: 1. Proportional factor
One way to do this is to calculate the proportional factor.  It is equal to the width divided by the height:
var proportions: Number = video.width / video.height;

You can apply that factor to any new width or height you set the video to:
function scaleProportionalByWidth ( newWidth:Number ) : void {
    video.width = newWidth;
    video.height = newWidth / proportions;
}

function scaleProportionalByHeight ( newHeight : Number ) : void {
    video.height = newHeight;
    video.width = newHeight * proportions;
}

2. Scaling factor
Another way to do it is to find out by which factor to scale the video, then set scaleX and scaleY instead of width and height:
function scaleProportionalByWidth ( newWidth : Number ) : void {
    scaleProportional ( newWidth, video.width );
}

function scaleProportionalByHeight ( newHeight : Number ) : void {
    scaleProportional ( newHeight, video.height );
}

function scaleProportional ( newValue:Number, oldValue : Number ) : void {
    var scale:Number = newValue / oldValue;
    video.scaleX *= scale;
    video.scaleY *= scale;
}

3. Proportional display object classes
You can also use the approach in 2. to create a proportional subclass of any DisplayObject by overriding the setters for width, height, scaleXand scaleY to make all scaling proportional:
                                           //  works for Sprite, MovieClip...
public class ProportionalDisplayObject extends DisplayObject {
    override public function set width ( width:Number ) : void {
        scaleX = width / super.width;
    }

    override public function set height ( height:Number ) : void {
        scaleY = height / super.height;
    }

    override public function set scaleX ( scaleX : Number ) : void {
        super.scaleX = super.scaleY = scaleX;
    }

    override public function set scaleY ( scaleY : Number ) : void {
        super.scaleY = super.scaleX = scaleY;
    }
}

A: you can do something like this:
// set video dimensions to match player;
video.width = player.width;
video.height = player.height;

// choose the larger scale property and match the other to it;
( video.scaleX < video.scaleY ) ? video.scaleY = video.scaleX : video.scaleX = video.scaleY;

// maybe center video in player ...


text:
Q: R problems with encoding after reading from MS SQL via ODBC We have a database and R scripts running on different virtual machines.
First we connect to db
con <- dbConnect(
  odbc(),
  Driver = "SQL Server",
  Server = "server", Database = "db", UID = "uid", PWD = "pwd",
  encoding = "UTF-8"
)

and gathering the data
data <- dbGetQuery(con, "SELECT * FROM TableName")

The problem is following: when different machines running the same script, for some of these we face character variables encoding issues.
For example, this is what we have on machine A
> data$char_var[1]
[1] "фамилия"
> Encoding(data$char_var[1])
[1] "UTF-8"
> Sys.getlocale()
[1] "LC_COLLATE=Russian_Russia.1251;LC_CTYPE=Russian_Russia.1251;LC_MONETARY=Russian_Russia.1251;LC_NUMERIC=C;LC_TIME=Russian_Russia.1251"
> Encoding(data$char_var[1]) <- "1251"
> data$char_var[1]
[1] "гревцев"

and this is what we have on machine B
> data$char_var[1]
[1] "<e3><f0><e5><e2><f6><e5><e2>"
> Encoding(data$char_var[1])
[1] "UTF-8"
> Sys.getlocale()
[1] "LC_COLLATE=Russian_Russia.1251;LC_CTYPE=Russian_Russia.1251;LC_MONETARY=Russian_Russia.1251;LC_NUMERIC=C;LC_TIME=Russian_Russia.1251"
> Encoding(data$char_var[1]) <- "1251"
> data$char_var[1]
[1] "фамилия"

First script returns gibberish, but it prints the initial value correctly. The same code running on machine B initially prints utf-8 and then returns encoded values. What could be the reason for such a difference?
As a result we want a script that would have the same "фамилия" output value to show it on a dashboard.

A: According to the result of your call to Encoding(data$char_var[1]), both machines are declaring the returned results to be encoded using UTF-8.
On the first machine, that appears to be true, because you're seeing valid output.  Then you mess it up by declaring the encoding incorrectly as "1251", and you see gibberish.
On the second machine, the result comes to you declared as UTF-8, but it isn't (which is why it looks like gibberish to start).  When you change the declared encoding to be "1251" it looks okay, so that's what it must have been all along.
So you have two choices:

*

*Make sure both machines are consistent about what they return from the dbGetQuery.  You can handle either encoding, but you need to know what it is and make sure it's declared correctly.

*Alternatively, try to detect what is being returned, and declare it appropriately.  One way to do this might be to put a known string in the database and compare the result to that.  If you know you should get "фамилия" and you get something else, switch the declared encoding. You could also try the readr::guess_encoding() function.
One other issue is that some downstream function might only be able handle one or the other of UTF-8 and 1251 encodings.  (Windows R is really bad at non-native encodings, and UTF-8 is never native on Windows.)  In that case you may want to actually convert to a common encoding.  You use the iconv() function to do that, e.g.
iconv(char_var, from = "cp1251", to = "UTF-8")

will try to convert to UTF-8.


text:
Q: Capture progressbar value onMouseClick I have progress bar, when I click on progressbar it should get the value(of progressbar where mouse is clicked)
here is the XAML of progressbar
<ProgressBar x:Name="seekBar" Height="21" Margin="30,36,43,0" VerticalAlignment="Top" ValueChanged="seekBar_ValueChanged" BorderBrush="#FF9B99C3" BorderThickness="2">
    <ProgressBar.Foreground>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FF505285" Offset="0"/>
            <GradientStop Color="#FF858AF0" Offset="1"/>
        </LinearGradientBrush>
    </ProgressBar.Foreground>
    <ProgressBar.Background>
        <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
            <GradientStop Color="White" Offset="1"/>
            <GradientStop Color="White"/>
            <GradientStop Color="#FF0F0F0F" Offset="1"/>
            <GradientStop Color="#FF326ED6" Offset="1"/>
            <GradientStop Color="#FFD1DBEE" Offset="0.491"/>
        </LinearGradientBrush>
    </ProgressBar.Background>
    <ProgressBar.Effect>
        <DropShadowEffect Opacity="0.15"/>
    </ProgressBar.Effect>
</ProgressBar>

When the value is changed it calls the function C# code
private void seekBar_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    this.seekBar.Value = //what should i do here??
    //how to get the value of progressbar(where mouse is clicked)
}

A: Try this :
private void seekBar_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    double MousePosition = e.GetPosition(seekBar).X;
    this.seekBar.Value = SetProgressBarValue(MousePosition);
}

private double SetProgressBarValue(double MousePosition)
{
    double ratio = MousePosition/seekBar.ActualWidth;
    double ProgressBarValue = ratio*seekBar.Maximum;
    return ProgressBarValue;
}

Codes adapted from following reference (see codes posted at the end of discussion) : http://bytes.com/topic/c-sharp/answers/722714-allowing-user-click-progressbar


text:
Q: What do you need from a test harness? I'm one of the people involved in the Test Anything Protocol (TAP) IETF group (if interested, feel free to join the mailing list).  Many programming languages are starting to adopt TAP as their primary testing protocol and they want more from it than what we currently offer.  As a result, we'd like to get feedback from people who have a background in xUnit, TestNG or any other testing framework/methodology.
Basically, aside from a simple pass/fail, what information do you need from a test harness?  Just to give you some examples:

*

*Filename and line number (if applicable)

*Start and end time

*Diagnostic output such as the difference between what you got and what you expected.

And so on ...

A: Most definitely all things from your list for each individual item:

*

*Filename

*Line number

*Namespace/class/function name

*Test coverage

*Start time and end time

*And/or total time (this would be more useful for me than the top two items)

*Diagnostic output such as the
difference between what you got and
what you expected.

From the top of my head not much else but for the group of tests I would like to know

*

*group name

*total execution time

A: It must be very, very easy to write a test, and equally easy to run them. That, to me, is the single most important feature of a testing harness. If someone has to fire up a GUI or jump through a bunch of hoops to write a test, they won't use it.

A: An arbitrary set of tags - so I can mark a test as, for example "integration, UI, admin".
(you knew I was going to ask for this didn't you :-)

A: To what you said I'd add:

*

*Method/function/class name

*Coverage counting tool, with exceptions (Do not count these methods)

*Result of N last runs available

*Mandate that ways to easily parse test results must exist

A: Any sort of diagnostic output - especially on failure is critical. If a test fails, you don't want to always have to rerun the test under a debugger to see what happened - there should be some cludes in the output.
I also like to see a before and after snapshot of critical system variables like memory or hard disk space available as those can provide great clues as well.
Finally, if you're using random seeds for any of the tests, write the seed out to the logfile so that the test can be reproduced if necessary.

A: I'd like the ability to concatenate and nest TAP streams.

A: A unique id (uuid, md5sum) to be able to identify an individual test -- say, for use when inserting test results in a database, or identifying them in a bug tracker to make it possible for QA to rerun an individual test.
This would also make it possible to trace an individual test's behavior from build-to-build through the entire lifecycle of multiple revisions of a product.  This could eventually allow larger-scale correlations between 'historic' events (new hire, product release, hardware upgrades) and the profile(s) of tests that fail as a result of such events.
I'm also thinking that TAP should be emitted through a dedicated side-channel rather than mixed in with stdout.  I'm not sure this is under the scope of the protocol definition.

A: I use TAP as output protocol for a set of simple C++ test methods, and have seen the following shortcomings:

*

*test steps cannot be put into groups (there's only the grouping into several test scripts; but for running all tests in our software, I need at least one more level of grouping, so that a single test step would be identified by like "DB connection" -> "Reconnection Test" -> "test step #3")

*seeing differences between expected and actual output is useful; I either print the diff to stderr (as comment) or actually launch a graphical diff tool

*the protocol and tools must be really language-independent. For example, so far I only know of the Perl "prove" tool for running tests, which is limited to running Perl scripts

In the end, the test output must be suitable as basis for easily generating an HTML report file which lists succeeded tests very concisely, gives detailed output for failed tests, and makes it possible to quickly jump into the IDE to the failing test line.

A: *

*optional ascii coloured output, green for good, yellow for pending, red for errors

*the idea of things being pending

*a summary at the end of the test report of commands that will run the individual tests where

*List item

*

*something went wrong

*something in the test was pending

A: Extension idea for TAP:
1..4
ok 1 - yay
not ok 2 - boo
ok 3 - yay #json:{...}
ok 4 - see my json

Ability to attach a #json comment...
 - can be safely ignored by existing code
 - well-defined tags can be easily reserved at testanything.org
 - easy to produce, parse and read complex types
 - yaml is a pain


text:
Q: Terminate jar file process through If commands using batch Using batch file, Is there any way to terminate a jar file that is running constantly even whenever/if the service has stopped.
In this case, the batch file runs through an "application as service" provider to start the batch as service.


text:
Q: How to enable button? On page load using javascript, I disable the button.
That is
protected void Page_Load(object sender, EventArgs e){
{
  btnExcel.Attributes.Add("onclick", " this.disabled = true; " +
  ClientScript.GetPostBackEventReference(btnExcel, null) + ";");
}

Now, I want is to enable the button control
protected void btnExcel_Click(object sender, EventArgs e)
{
    1.  Rpt.ExportToHttpResponse(ExportFormatType.Excel, Response, true, "Project Summary Report");

    2.  btnexcel.enable=true;
}

After executing 1 statement on the btn_click event,
why 2 statement is not executed?
If 2 statement not executed then my button control not enable?

A: Try this:
On page_Load:
Code-behind:
 System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "Script1", "disable();", True)

After button Click:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "Script2", "enable();", True)

In your head tag:
disable(){
 $("#somebtn").attr("disabled", true);
}

enable(){
 $('#somebtn').removeAttr('disabled');
}


text:
Q: Sorting does not work for the customized ProductListComponentService.(CustomProductListComponentService) Spartacus lists 10 products in the pagination defualt on its product listing page. But I wanted it to be 12.
In my .ts file normally for PLP
protected productListComponentServiceDefault: ProductListComponentService,

I was using the structure.
but I created "CutomProductListComponentService" by customizing the "ProductListComponentService" file.
protected defaultPageSize = 12;
I did what I wanted by adding. Pagination artok 12 works.
But after this customization, the "SORTING" operation within the page does not work anymore.
Inside CutomProductListComponentService I added the following:
import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import {
  ActivatedRouterStateSnapshot,
  CurrencyService,
  LanguageService,
  ProductSearchPage,
  ProductSearchService,
  RouterState,
  RoutingService,
} from '@spartacus/core';
import { combineLatest, Observable, using } from 'rxjs';
import {
  debounceTime,
  distinctUntilChanged,
  filter,
  map,
  shareReplay,
  tap,
} from 'rxjs/operators';
// @ts-ignore
import { ProductListRouteParams, SearchCriteria } from './product-list.model';

/**
 * The `ProductListComponentService` is used to search products. The service is used
 * on the Product Listing Page, for listing products and the facet navigation.
 *
 * The service exposes the product search results based on the category and search
 * route parameters. The route parameters are used to query products by the help of
 * the `ProductSearchService`.
 */
@Injectable({ providedIn: 'root' })
export class CustomProductListComponentService {
  // TODO: make it configurable
  protected defaultPageSize = 12;

  protected readonly RELEVANCE_ALLCATEGORIES = ':relevance:allCategories:';

  constructor(
    protected productSearchService: ProductSearchService,
    protected routing: RoutingService,
    protected activatedRoute: ActivatedRoute,
    protected currencyService: CurrencyService,
    protected languageService: LanguageService,
    protected router: Router
  ) {}

  /**
   * Emits the search results for the current search query.
   *
   * The `searchResults$` is _not_ concerned with querying, it only observes the
   * `productSearchService.getResults()`
   */
  protected searchResults$: Observable<
    ProductSearchPage
    > = this.productSearchService
    .getResults()
    .pipe(filter((searchResult) => Object.keys(searchResult).length > 0));

  /**
   * Observes the route and performs a search on each route change.
   *
   * Context changes, such as language and currencies are also taken
   * into account, so that the search is performed again.
   */
  protected searchByRouting$: Observable<
    ActivatedRouterStateSnapshot
    > = combineLatest([
    this.routing.getRouterState().pipe(
      distinctUntilChanged((x, y) => {
        // router emits new value also when the anticipated `nextState` changes
        // but we want to perform search only when current url changes
        return x.state.url === y.state.url;
      })
    ),
    ...this.siteContext,
  ]).pipe(
    debounceTime(0),
    map(([routerState, ..._context]) => (routerState as RouterState).state),
    tap((state: ActivatedRouterStateSnapshot) => {
      const criteria = this.getCriteriaFromRoute(
        state.params,
        state.queryParams
      );
      this.search(criteria);
    })
  );

  /**
   * This stream is used for the Product Listing and Product Facets.
   *
   * It not only emits search results, but also performs a search on every change
   * of the route (i.e. route params or query params).
   *
   * When a user leaves the PLP route, the PLP component unsubscribes from this stream
   * so no longer the search is performed on route change.
   */
  readonly model$: Observable<ProductSearchPage> = using(
    () => this.searchByRouting$.subscribe(),
    () => this.searchResults$
  ).pipe(shareReplay({ bufferSize: 1, refCount: true }));

  /**
   * Expose the `SearchCriteria`. The search criteria are driven by the route parameters.
   *
   * This search route configuration is not yet configurable
   * (see https://github.com/SAP/spartacus/issues/7191).
   */
  protected getCriteriaFromRoute(
    routeParams: ProductListRouteParams,
    queryParams: SearchCriteria
  ): SearchCriteria {
    return {
      query: queryParams.query || this.getQueryFromRouteParams(routeParams),
      pageSize: queryParams.pageSize || this.defaultPageSize,
      currentPage: queryParams.currentPage,
      sortCode: queryParams.sortCode,
    };
  }

  /**
   * Resolves the search query from the given `ProductListRouteParams`.
   */
  protected getQueryFromRouteParams({
                                      query,
                                      categoryCode,
                                      brandCode,
                                    }: ProductListRouteParams) {
    if (query) {
      return query;
    }
    if (categoryCode) {
      return this.RELEVANCE_ALLCATEGORIES + categoryCode;
    }

    // TODO: drop support for brands as they should be treated
    // similarly as any category.
    if (brandCode) {
      return this.RELEVANCE_ALLCATEGORIES + brandCode;
    }
  }

  /**
   * Performs a search based on the given search criteria.
   *
   * The search is delegated to the `ProductSearchService`.
   */
  protected search(criteria: SearchCriteria): void {
    const currentPage = criteria.currentPage;
    const pageSize = criteria.pageSize;
    const sort = criteria.sortCode;

    this.productSearchService.search(
      criteria.query,
      // TODO: consider dropping this complex passing of cleaned object
      Object.assign(
        {},
        currentPage && { currentPage },
        pageSize && { pageSize },
        sort && { sort }
      )
    );
  }

  /**
   * Get items from a given page without using navigation
   */
  getPageItems(pageNumber: number): void {
    this.routing
      .getRouterState()
      .subscribe((route) => {
        const routeCriteria = this.getCriteriaFromRoute(
          route.state.params,
          route.state.queryParams
        );
        const criteria = {
          ...routeCriteria,
          currentPage: pageNumber,
        };
        this.search(criteria);
      })
      .unsubscribe();
  }

  /**
   * Sort the search results by the given sort code.
   */
  sort(sortCode: string): void {
    this.route({ sortCode });
  }

  /**
   * Routes to the next product listing page, using the given `queryParams`. The
   * `queryParams` support sorting, pagination and querying.
   *
   * The `queryParams` are delegated to the Angular router `NavigationExtras`.
   */
  protected route(queryParams: SearchCriteria): void {
    this.router.navigate([], {
      queryParams,
      queryParamsHandling: 'merge',
      relativeTo: this.activatedRoute,
    });
  }

  /**
   * The site context is used to update the search query in case of a
   * changing context. The context will typically influence the search data.
   *
   * We keep this private for now, as we're likely refactoring this in the next
   * major version.
   */
  private get siteContext(): Observable<string>[] {
    // TODO: we should refactor this so that custom context will be taken
    // into account automatically. Ideally, we drop the specific context
    // from the constructor, and query a ContextService for all contexts.

    return [this.languageService.getActive(), this.currencyService.getActive()];
  }
}

I call the Sort function in plp.ts as follows.
constructor(
    protected productListComponentService: CustomProductListComponentService,

  ) {}

sortList(sortCode: string): void {
    this.productListComponentService.sort(sortCode);
  }

Sort process doesn't work. Can you help me? Thank you very much in advance.

A: You also need to replace "ProductListComponentService" to "CustomProductListComponentService" in "ProductFacetService".
The better way to do this is:
In providers of "ProductListModule", add:
{
  provide: ProductListComponentService,
  useClass: CustomProductListComponentService,
},


text:
Q: Delayed start using RunOnce I have a program that I want to start at Windows start up. So I wrote the program to the registry value SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce. The program runs immediately when Windows starts up.
However, it runs the program before any of the other processes are started. I would like to have my program start up after my Desktop has started and all the other system processes have started. How would I do this?
Edit: So I have added a delay in my program. None of the processes like desktop start until after my program has run no matter what kind of delay I put in my program.

A: According to Microsoft:

With the exception of the HKEY_LOCAL_MACHINE...\RunOnce key, all keys and their entries are loaded asynchronously. Therefore, all entries in the RunServices and RunServicesOnce keys can potentially run at the same time.
Entries in the HKEY_LOCAL_MACHINE...\RunOnce key are loaded synchronously in an undefined order.
Because the HKEY_LOCAL_MACHINE...\RunOnce key is loaded synchronously, all of its entries must finish loading before the HKEY_LOCAL_MACHINE...\Run, HKEY_CURRENT_USER...\Run, HKEY_CURRENT_USER...\RunOnce, and Startup Folder entries can be loaded.

So does that mean if you put a program that does Sleep(INFINITE) in the RunOnce key, it will prevent your machine from starting up?  Interesting.
Just use one of the other keys mentioned in that article.  Or if you need the semantics of RunOnce, use a helper program that exits after launching the real program.


text:
Q: how to read json file in functional component in reactjs and iterate over the data I have a functional component filter()
My json file has some data which I want to pass into the filter() function and want that function to generate text fields where user can write and submit it.
So far, I tried to use a map function to read the json file.
I want to read the line from the map function then check the datatype of the column and make a text field accordingly.
import React, {useState}  from 'react';
import './Form.css';
import data from './data.json'
import axios from 'axios';

const filter= (props) =>{

    const [data,setdata]= useState({
        column:"",
        datatype:""
    });

    {data.map((details,index)=>{
        column= details.column;
        datatype=details.datatype;

        if (props.datatype === "string") {
            return(

                {props.columns}:

                <input type="text"
                name= {props.columns}
                placeholder={props.columns}/>

            );
        }

        if (props.datatype === "date") {
            return(

                 {props.columns}

                 From:
                <input type="date"
                name= {props.columns}
                placeholder="{props.columns}"/>
                 To:
                <input type="date"
                name= {props.columns}
                placeholder={props.columns}/>

            );
        }

        if (props.datatype === "integer") {
            return(

                {props.columns}:

                <input type="text"
                name= {props.columns}
                placeholder={props.columns}/>

            );
        }

    })}

    return (

           <button>Submit</button>

        );
};

export default filter````

My json data file:

[
    {
      "column": "Name",
      "datatype" : "String"
    },
    {
        "column": "Dob",
        "datatype" : "date"
      }
]

The error I'm getting is :

Line 11:  React Hook "useState" is called in function "filter" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks
  Line 17:   'keycolumn' is not defined                                                                                no-undef
  Line 18:   'datatype' is not defined                                                                                no-undef

Search for the keywords to learn more about each error.

The output I expect is: 2 input fields and 1 submit button on the
but because of the error Im not getting anything.

A: You can give a try to capitalize 'filter' functional component as below:
const Filter = props => {...}

export default Filter;

Also, make sure you are running with latest version of React that support State Hooks.


text:
Q: NoMethodError in Blog::PostsController#create Note: Rails newb here.
So, I recently created a Rails app with mongoid gem for use of MongoDB. I have a namespace route of :blog with a nest of resource of posts
Routes.rb:
Rails.application.routes.draw do
  namespace :blog do
    resources :posts
  end
end

The error comes from app/controllers/blog/posts_controller.rb:
Class Blog::PostsController < ApplicationController
  def create
   @post = Post.new(post_params)

  if @post.save
    redirect_to @post
  else
    render 'new'
  end
 end

 private
 def post_params
 params.require(:post).permit(:title, :body)
 end
end

I also have a 'post' model that comes with a title and body:
Class Post
 include Mongoid::Document
 field :title, type: String
 field :body, type: String
end

In new.html.erb:

Rails Sample Blog

<%= form_for @post, url: blog_post_path do |f| %>

<%= f.label :title %><%= f.text_field :title %>

<%= f.label :body %><%= f.text_area :body %>

<% end %>

Is there something I left out that I didn't catch? It's slowly haunting me.
Edit: See this Git repo: https://github.com/hackathons-com/Rails-MongoDB-Devise-test
Edit 2:
undefined method `post_url' for #<Blog::PostsController:0x007f3d19105ee8>

A:  app/controllers/blog/post_controller.rb:

Shouldn't this be posts_controller.rb?
Also
Class Blog::PostController < ApplicationController

should be
Class Blog::PostsController < ApplicationController

A: Try this:
 def create

 @blog = Blog.find(params[:blog_id])

 @post= @blog.posts.build(post_params)

(This assumes that you already added a column of blog_id and have your associations correct, although looking at your model it looks like you may have missing associations?)


text:
Q: "TypeError: argument 1 must be pygame.Surface, not method" Error Python I am working on a game and seem to be having some issues here. This is my first time working with sprite sheets, so I apologize if my error is simple.
I apologize in advance for the large amount of code, but unfortunately I believe the problem could be anywhere in this code. The error I am receiving says "TypeError: argument 1 must be pygame.Surface, not method
". This is referring to the all_sprites.draw(screen) command. I know screen is formatted correctly, so its not that. My teacher said it is likely any of the sprites. One of them is not formatted correctly, or doesn't properly interact with the images. Please let me know if you find the solution to my issue, and again I apologize for the large extent of the code.
Thanks!
(I labeled my different files btw, gsettings, gmain, and gsprites. You can see I use them in the imports, shouldn't be a big deal, just thought I would clarify)
FULL EXCEPTION `
Traceback (most recent call last):
  File "/Users/AddisonWeatherhead/PycharmProjects/PyGame/Game 2/gmain.py", line 191, in <module>
    game_play()
  File "/Users/AddisonWeatherhead/PycharmProjects/PyGame/Game 2/gmain.py", line 128, in game_play
    all_sprites.draw(screen)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pygame/sprite.py", line 475, in draw
    self.spritedict[spr] = surface_blit(spr.image, spr.rect)
TypeError: argument 1 must be pygame.Surface, not method

Process finished with exit code 1

gsettings
WHITE = (255, 255, 255)
BLACK = (0, 0, 0,)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (180, 180, 180)
MAROON = (128, 0, 0)
NAVY = (0, 0, 128)
YELLOW = (255, 255, 0)
LIGHT_GRAY = (250, 250, 250)
LIGHT_BLUE = (144, 195, 212)

DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 800
FPS=60

gsprites
class sprite_sheet():
    def __init__ (self, filename):
        self.spritesheet = pygame.image.load(filename)

    def get_image(self, x, y, width, height):
        image = pygame.Surface((width, height))
        image.blit(self.spritesheet, (0,0), (x, y, width, height))
        return image

class Player(pygame.sprite.Sprite):
    def __init__(self, hero_left_list, hero_right_list, left_shoot, right_shoot):
        pygame.sprite.Sprite.__init__(self)

        self.hero_left_list=hero_left_list
        self.hero_right_list=hero_right_list
        self.left_shoot=left_shoot
        self.right_shoot=right_shoot

        self.image = self.hero_right_list[0]
        self.rect=self.image.get_rect()
        self.rect.x=self.rect.x
        self.rect.y=self.rect.y

        self.changex=0 #Horizontal movement speed
        self.changey=0 #Vertical movement speed

        self.current_frame=0
        self.delay=50 #In millisecond, this will be the delay BETWEEN each frame of a spritesheet (character walking, explosion exploding, etc)
        self.last=pygame.time.get_ticks() #gets the time in milliseconds since pygame.init() was called

        self.running_right=False
        self.running_left=False

    def update(self):
        self.rect.x+=self.changex
        self.rect.y+=self.changey

        if pygame.key.get_pressed()[pygame.K_RIGHT]:
            self.now=pygame.time.get_ticks() #also gets the time in milliseconds since pygame.init() was called, however this time its LATER than self.delay
            self.running_right=True
            self.changex=5

            if self.now - self.last >self.delay: #Confirming that at least 5 milliseconds has passed since the last call of the function
                self.last=self.now
                self.current_frame=(self.current_frame+1)%(int(len(self.hero_right_list)))
                self.image=self.hero_right_list[self.current_frame]

            self.image=sprite_sheet("hero.png").get_image

        elif pygame.key.get_pressed()[pygame.K_LEFT]:
            self.running_left=True
            self.changey=5

            self.image=sprite_sheet.get_image("hero.png", )

        elif pygame.key.get_pressed()[pygame.K_UP]:
            self.running_left=False
            self.running_right=False
            self.image=sprite_sheet.get_image("hero.png")

gmain
import pygame
from gsettings import *
from gsprites import *
import time

pygame.init()

clock = pygame.time.Clock()
##########################################################################################
def score(score, lives):
    background = sprite_sheet("background.jpg").get_image(0, 0, 800, 800)
    screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    screen.blit(background, [0,0])

    font = pygame.font.SysFont('Impact', 40, True, False)
    text = font.render(('Score'+str(score)), True, WHITE)
    screen.blit(text, (200, 50))

##########################################################################################

def game_start():
    screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
    text = "Press enter to play"
    font = pygame.font.SysFont('Impact', 50, True, False)
    text_render=font.render(text, True, BLACK)

    background=sprite_sheet("background.jpg").get_image(0, 0, 800, 800)
    screen.blit(background, [0, 0])

    started=False
    while started == False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            quit()

        sprite_sheet("background.jpg").get_image(0, 0, 800, 800)

        screen.blit(text_render, [(DISPLAY_WIDTH / 2) - 150, (DISPLAY_HEIGHT / 2)])
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
            screen.blit(background, [0, 0])
            print('last')
            return True

        print(started)
        pygame.display.flip()
        clock.tick(FPS)

##########################################################################################
def game_play():
    pygame.init()
    screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))

    hero_right_list = []
    for x in range(6):
        for y in range(2, 3):
            right_image = sprite_sheet("hero.png").get_image(80 * x, 94 * y, 80, 94)
            hero_right_list.append(right_image)
            # Player is 80 wide 94 tall

    hero_left_list = []
    for image in hero_right_list:
        hero_left_list.append(pygame.transform.flip(image, True, False))

    explosion_list = []
    for x in range(25):
        for y in range(1, 2):
            explosion_image = sprite_sheet("Explosion.png").get_image(192 * x, 195 * y, 192, 195)
            explosion_list.append(explosion_image)

    shoot_right=(sprite_sheet("hero.png").get_image(0, 94*3, 80, 94))
    shoot_left=pygame.transform.flip(shoot_right, True, False)

    #Creating Sprite groups
    all_sprites=pygame.sprite.Group()

    enemy_sprites=pygame.sprite.Group()
    player_sprite=pygame.sprite.Group()
    laser_sprites=pygame.sprite.Group()
    explosion_sprite=pygame.sprite.Group()

    #sprite objects
    player=Player(hero_left_list, hero_right_list, shoot_left, shoot_right)
    all_sprites.add(player)
    player_sprite.add(player)

    for val in range(10):
        enemy_right=Enemy('right')
        enemy_left=Enemy('left')
        enemy_sprites.add(enemy_right)
        enemy_sprites.add(enemy_left)
        all_sprites.add(enemy_right)
        all_sprites.add(enemy_left)

        global game_score
        game_score = 0

    started=True
    while started==True:
        for event in pygame.event.get():
                   # events to end the game
                   if event.type == pygame.QUIT:
                       quit()
        player.update()

        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            player.image=shoot_right

        laser_hits=pygame.sprite.groupcollide(laser_sprites, enemy_sprites, True, True)
        for hit in laser_hits:
            game_score+=5
            explosion=Explosion(explosion_list)
            explosion_sprite.add(explosion)
            all_sprites.add(explosion)
            enemy=Enemy()
            enemy_sprites.add(enemy)
            all_sprites.add(enemy)

        score(score, 5)

        #enemy_sprites.draw(screen) #NO ISSUES
        #explosion_sprite.draw(screen) #NO ISSUES
        #laser_sprites.draw(screen) #NO ISSUES
        player_sprite.draw(screen) #ISSUES

        pygame.display.flip()
        clock.tick(FPS)

##########################################################################################

def game_over(score):
    over_screen=pygame.display.set_mode([DISPLAY_WIDTH, DISPLAY_HEIGHT])
    clock.tick(FPS)

    end_message_1="GAME OVER!"
    end_message_2="Your score was", score

    end_message_3="Replay"
    end_message_4="Quit"

    font = pygame.font.SysFont('Comic Sans', 75, True, False)

    #rendering text

    end_message_1_render=font.render(end_message_1, True, RED)
    end_message_2_render=font.render(end_message_2, True, BLACK)

    end_message_3_render=font.render(end_message_3, True, BLACK)
    end_message_4_render=font.render(end_message_4, True, BLACK)
    started=False
    while started == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

        clicked=pygame.mouse.get_pressed()
        pos=pygame.mouse.get_pos()
        if pos[0]>0 and pos[0]<100 and pos[1]>0 and pos[1]<100:
            if pygame.mouse.get_pressed()[0] ==1:
                started=False

        over_screen.fill(WHITE)

        over_screen.blit(end_message_1, [(DISPLAY_WIDTH//2), (DISPLAY_HEIGHT//2)])
        over_screen.blit(end_message_2, ((DISPLAY_WIDTH//2), ((DISPLAY_HEIGHT//2)+50)))
        over_screen.blit(end_message_3, [((DISPLAY_WIDTH // 2)-20), ((DISPLAY_HEIGHT // 2) + 120)])
        over_screen.blit(end_message_4, [((DISPLAY_WIDTH // 2)+20), ((DISPLAY_HEIGHT // 2) + 120)])

        pygame.display.flip()
        pygame.time.clock.tick(FPS)

    started=True
##########################################################################################

game_start()

while True:
    game_play()
    game_over(game_score)

pygame.quit()

A: On the line of the error, spr.image is a method, not a pygame.Surface, which is what's expected by surface_blit().
EDIT (in response to comments):
The error is on line 475 of sprite.py.


text:
Q: How to write soapui - Teststep level custom property values in file? I am very new to SoapUI, and need some help,
I want to test multiple SOAP requests - just kind of smoke test and save result in text file along with error message of failed response.
I have created testcase with all SOAP request and used invalid HTTP assertion to validate pass/fail one [as mentioned just smoke test] and wirting result in to txt file using tear down script.
I have created Custom properties for each SOAP request and using property transfer step fetched Error message & reporting entity.
Now my concern is, how to write those property values in txt file along with result.
I am using below mentioned teardown script to store result.
`import org.codehaus.groovy.scriptom.*
 import org.codehaus.groovy.scriptom.tlb.office.excel.*

 def testsuitename=testRunner.testCase.testSuite.name
 def testcasename=testRunner.testCase.name
 groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
 def results = testRunner.results
 f = new File( "C:\\Users\\%user%\\Documents\\Downloads\\Smoke Test Result\\result.txt")

 for( r in testRunner.results )
 {
    f.append(r.testStep.name + "," + r.status + "\r\n")

 }`

Output is something like this:
step-1-name,FAILED
step-2-name,OK
step-3-name,OK

I am looking for output with error message
step-1-name,FAILED,Error message,Reporting Entity
step-2-name,OK,null,null
step-3-name,OK,null,null

I have already fetched Error message & entity using XPATH in properties.


text:
Q: Why does the export of a styled pandas dataframe to Excel not work? I would like to apply the same background color to cells that have for each PEOPLE instance the name and the related name. I have tried to df.style.applymap, it does not return an error but it does not seem to work.  Anyone has any ideas why? Thank you.
   clrs = list(mcolors.CSS4_COLORS.keys())
   for k in range(len(PEOPLE)):
        if PEOPLE[k].attribute == 'child':
            df1_data = [PEOPLE[k].name, PEOPLE[k].related]

            df.style.applymap([lambda x: 'background-color: yellow' if x in df1_data else 'background-color: red'])

    df.to_excel('styledz.xlsx', engine='openpyxl')

A: Here is some more info on df.style. Here I'm using some simple example because I don't have your data available:
import pandas as pd
import numpy as np

df = pd.DataFrame({'a': np.random.randint(0, 10, 10), 'b': np.random.randint(0, 10, 10), 'late': np.random.choice([0, 1], 10).astype(np.bool)})

def highlight_late(s):
    return ['background-color: red' if s['late'] else 'background-color: green' for s_ in s]
df = df.style.apply(highlight_late, axis=1)
df.to_excel('style.xlsx', engine='openpyxl')

Looks in the excel file like this:

For cell based coloring use:
def highlight_late(s):
    return ['background-color: red' if s_ else 'background-color: green' for s_ in s]

df = df.style.apply(highlight_late, subset=["late"], axis=1)

This gives you:

A: Basically your solution will be a modification of the following:
df = DataFrame([['mark', 2], ['mike', 4], ['manny', 6]], columns=['name', 'attribute'])
def style_row(row, people):
    output = Series("", index=row.index)
    if row["name"] in people:
        output['attribute'] = "background-color:red;"
    return output
styler = df.style.apply(style_row, axis=1, people=['mark', 'manny'])
styler


text:
Q: Visual Studio: every time I switch to a different Salesforce org it stays authenticated to the previous one I've been dealing with this issue for a while now, I most recently tried completely uninstalling VS code and reinstalling it and then going through and creating new SFDX project with manifest and authorizing yet the issue persists. Basically, if I have one org open, then close it (or if I keep it open and open a new VS code window with another org), every time I try to push changes or "open default org" it always opens the one from the previous org I had open (or the one I opened first if I have 2 VS code windows open).
So every time I switch to doing work for a different org I have to go and reauthenticate.
OS: Mac
I've been researching this issue but so far have not found a solution. Any advice around this would be helpful even if you aren't sure of the solution, thanks.

A: In my case, it was related to conflicts between the ForceCode project I had made before switching to Source, and and SFDX project I'd created separately in the same dir. Deleting .forceCode and .sfdx and reinitializing resolved the issue for me.
Hope that's useful.


text:
Q: Android history stack clear without one I have a some activities likr
A-> Splash Screen
B-> Home Screen
C-> a List activity
D-> a View activty
E-> a List activity
F-> a View activty

Normaly application start with A -> B
Then user select a list activity
then user select a view from list activity.
my problem is clearing activty stack.
my application will jump list or view activity to an activity (with facefook style navigation)
For example user select a list activity C and than select view activity D. at hat point user can jump to acitivty E. When in activity E, if user press o back button, user go to the activity D.
I want that to go to the activty B(Home).
I mean ı want to clear activity stact without home activity.
how can ı do this ?.
sory for awasome English.
Thanks.

A: You can intercept the back button press like so:
@Override
public void onBackPressed() {
    // You want to start B Activity
    Intent a = new Intent(this, B.class);

    // But you dont want it on top of E.
    a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Launching this will now remove every activity on top of B and bring B to front, not! relaunch it.
    startActivity(a);
}

You might want to check out the Android Intent flags and the Tasks and Back Stack Documentation.
Have a nice day!
EDIT:
If you want to close your app when back is pressed:
@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

A: If you want users to go back to B from all your activities, you can call finish() from every other activity when calling any Intent. This way, they'll be removed from activity stack.
Moreover you can override the back button behaviour:
@Override
public void onBackPressed() {
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   startActivity(setIntent);
}

But make sure it's really what you want. because it looks like you're doing something very bad for user experience. Read more on acitivty stack and tasks. Overriding the default behavior of back button should be avoided.

A: You can use tag android:noHistory="true" to activity elements at you AndroidManifest.xml file. This tag allow to not write activity in stack of activities.


text:
Q: Tkinter defaulting to all radiobuttons being selected, despite value being set The following code gives weird results. Despite having a value set for every one, they all default to selected. Outside of a class, this code (minus the self call) works perfectly.
from tkinter import *
from threading import *

class fire():
    def __init__(self, root):

        self.var = IntVar()
        self.var.set(2)
        r1 = Radiobutton(root, text="1",variable=self.var, value=1)
        r1.pack()
        r2 = Radiobutton(root, text="2", variable=self.var, value=2)
        r2.pack()
        r3 = Radiobutton(root, text="2", variable=self.var, value=3)
        r3.pack()

root = Tk()
root.geometry("50x175")

fire(root)

root.mainloop()

Doing some reading online, there's no reason this shouldn't work, right?

A: You need to save a reference to the instance of fire:
f = fire(root)

Without the reference, the python garbage collected will destroy the variables.


text:
Q: What are these set operations? I'm not sure how to do these math problems:
U=Names of the states in the US
A = States that begin with "a" = {AK, AL, AZ. AR}
B = States that border Mexico = {AZ, CA, NM, TX}
C = States on the Pacific coast = {AL, CA, OR, WA}
Find (A union B union C)'

Find (B union C} intersection A

Find (A intersection B) union C

A: Consider that $Q^\prime=U\setminus Q$. For example: $\{x:x\text{ is a state that is not VA}\}'$ is $\{\text{VA}\}$, since $U\setminus\{x:x\text{ is a state that is not VA}\}=\{\text{VA}\}$. (Note that $Q\setminus A$ is the elements in $Q$ not in $A$.)
So, the first problem stands as thus:
$$U\setminus(A\cup B\cup C).$$
Now, when they throw parenthesis in, you must evaluate them first. For example, let $A=\{1,2,3\}$, $B=\{3,4,5\}$, $C=\{5,6,7\}$. So, $(B\cup C)\cap A=\{3,4,5,6,7\}\cap\{1,2,3\}=\{3\}$. The third problem follows the same schematic.
Does this clarify your problems?


text:
Q: Post-hoc tests in mixed model using lsmeans and glht I have a mixed model with two fixed factors (Insecte and temperature) with two random factors (bloc and date) nested in the temperature treatment. I also include interactions between the fixed factor Insecte and the random factors. The response variable is aphid density. This give the following model:
m2.nlmer = lmer(aphid_density~ Insecte*amp_freq
                              +(1|bloc:(date:amp_freq))+(1|date:amp_freq)+(1|Insecte:(bloc:(date:amp_freq)))+(1|Insecte:(date:amp_freq)),
                              na.action=na.exclude,
                              data = fr2)

where amp_freq are the temperature treatments. I detected significant interaction between Insecte and amp_freq and want to analyse Insecte effect for each temperature levels as follows:
> lsmeans(m2.nlmer, pairwise ~ Insecte|amp_freq, adjustSigma = TRUE, adjust = "tukey")

$lsmeans
amp_freq = 23-const:
Insecte        lsmean       SE   df  lower.CL  upper.CL
COCCINELLE  568.17947 160.6389 5.39  164.0381  972.3208
PUCERON    1783.53300 160.0224 5.32 1379.5075 2187.5585

amp_freq = 30-jour:
Insecte        lsmean       SE   df  lower.CL  upper.CL
COCCINELLE  570.64910 161.6708 5.48  165.8695  975.4287
PUCERON    1314.53794 160.0629 5.32  910.4669 1718.6089

amp_freq = 30-semaine:
Insecte        lsmean       SE   df  lower.CL  upper.CL
COCCINELLE  738.12107 163.2045 5.74  334.3272 1141.9149
PUCERON    1867.47572 160.0204 5.32 1463.4669 2271.4845

amp_freq = 40-jour:
Insecte        lsmean       SE   df  lower.CL  upper.CL
 COCCINELLE   84.87312 162.5806 5.64 -319.1406  488.8869
 PUCERON     256.55122 159.6785 5.27 -147.5851  660.6875

amp_freq = 40-semaine:
 Insecte        lsmean       SE   df  lower.CL  upper.CL
COCCINELLE  296.63947 159.6828 5.27 -107.5317  700.8107
PUCERON     837.65225 160.0241 5.32  433.6129 1241.6916

  Confidence level used: 0.95

$contrasts
amp_freq = 23-const:
contrast               estimate       SE   df t.ratio p.value
COCCINELLE - PUCERON -1215.3535 61.59491 4.44 -19.731  <.0001

amp_freq = 30-jour:
contrast               estimate       SE   df t.ratio p.value
COCCINELLE - PUCERON  -743.8888 64.11036 4.99 -11.603  0.0001

amp_freq = 30-semaine:
 contrast               estimate       SE   df t.ratio p.value
 COCCINELLE - PUCERON -1129.3546 68.03274 6.60 -16.600  <.0001

amp_freq = 40-jour:
 contrast               estimate       SE   df t.ratio p.value
 COCCINELLE - PUCERON  -171.6781 65.61395 5.69  -2.616  0.0418

amp_freq = 40-semaine:
contrast               estimate       SE   df t.ratio p.value
COCCINELLE - PUCERON  -541.0128 58.89646 3.77  -9.186  0.0010

However, I get a different results if I split the data set by temperature level and run again the model. For instance:
m40_jour = lmer(aphid_density~ Insecte+(1|bloc:(date:amp_freq))+(1|date:amp_freq)+(1|Insecte:(bloc:(date:amp_freq)))+(1|Insecte:(date:amp_freq)),
            na.action=na.exclude,
            data = fr2[which(fr2$amp_freq == "40-jour"),])

 lsmeans(m40_jour, pairwise ~ Insecte, adjustSigma = TRUE, adjust = "tukey")

$lsmeans
 Insecte       lsmean       SE   df  lower.CL upper.CL
 COCCINELLE  81.90721 29.60546 2.37 -28.08425 191.8987
 PUCERON    258.15338 25.84196 1.58 113.00870 403.2981

 Confidence level used: 0.95

 $contrasts
 contrast              estimate       SE   df t.ratio p.value
 COCCINELLE - PUCERON -176.2462 34.73064 1.02  -5.075  0.1202

Finally, I get a different result if I use the glht function with mcp:
 summary(glht(m40_jour, mcp(Insecte="Tukey")))

 Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Tukey Contrasts
Fit: lmer(formula = aphid_density ~ Insecte + (1 | bloc:(date:amp_freq)) +
(1 | date:amp_freq) + (1 | Insecte:(bloc:(date:amp_freq))) +
(1 | Insecte:(date:amp_freq)), data = fr2[which(fr2$amp_freq ==
"40-jour"), ], na.action = na.exclude)

Linear Hypotheses:
                          Estimate Std. Error z value Pr(>|z|)
PUCERON - COCCINELLE == 0   176.25      33.43   5.273 1.34e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Adjusted p values reported -- single-step method)

So I do not understand why (1) I get different results between lsmeans with the interaction between fixed factor and lsmeans with the split dataset and model m40-day and (2) lsmeans and glht produce different results?
What is the correct/more robust approach?
Thank you for your help!

A: This is apparently a messy dataset (as opposed to a nice balance experiment). When you fit a model to only a subset, only the data in that subset are available to obtain estimates. But there may be partial information about those effects in the other parts of the dataset. Also, in a mixed model with unbalanced data, the random effects can affect the fixed-effect estimates, and , that can cause a discrepancy between the full-data and the subset models as well.
Which is better? Well, that's not cut-and-dried. How well do you believe the underlying assumptions for the fuill model? They include the idea that the variances of each random effect is the same for each level of amp_freq. If that's believable, then the full-data model is preferable because you can pool the information about those effects from the whole dataset, making the tests more powerful and the confidence intervals shorter. But if you doubt those assumptions, then separate models may be better, or a more sophisticated model that allows for different variances across amp_freq.
For the 2nd part of your question, the main reason is degrees of freedom. The test from lsmeans uses 1.02 df and the one from glht uses infinite df (asymptotic z test). That makes a huge difference in the P value. Also, while the estimates match, the SEs differ slightly. That's because lsmeans uses an adjusted covariance matrix from the pbkrtest package. That package is also used to get the degrees of freedom. So, if you do lsm.options(disable.pbkrtest = TRUE), the lsmeans results will match those from glht. But I suggest that isn't a good idea, because that 1.02 df is a warning that you really don't have a lot of information about your estimate of that difference.


text:
Q: How to compare array from file with sql database query? I tried to select all columns from my table at database that is same as on row in array in file. For example:
TABLE:
id name
1 A
2 B
3 C

FILE:
A
B

I want to select only A and B.
My source:
use DBI;
use CGI;
my $file = '.\input.txt';       # Name the file
    open(FILE, $file) or die("Unable to open file");
    my @data = <FILE>;
    foreach my $line (@data)
    {
      #print $line;
      my $sth = $dbh->prepare("SELECT columnA FROM table WHERE columnA LIKE '%$line%'");
      $sth->execute;
      my $result = $sth->fetchall_arrayref;

      foreach my $row ( @$result ) {
      print "- ";
      print "@$row\n";
      print "<BR />";
      }

     }

but it write only last line of select hmmm...
OUTPUT I GET

B

OUTPUT I WANT TO GET

A
B

I tried it with this:
INPUT:
bengalske_stehno
cesnakova_polievka
drzkova_polievka
kuraci_spiz
polievka_fazulova
polievka_mrkvova
polievka_rybacia

DATABASE:
fasirky
cesnakova_polievka
chlebicek_biskupsky
drzkova_polievka
polievka_fazulova
polievka_mrkvova
polievka_rybacia
bengalske_stehno

OUTPUT:
- polievka_rybacia

A: It seems you forgot to chomp $line after reading from the input file. The newline is not present on the last line in the file, that's why it works.


text:
Q: Can I remove outdated file from makefile? I'm not a C++ guy, so please bear with me. It seems to me that the latest ddccontrol tarball is missing a C++ file that the makefile calls for, but it refers to outdated hardware that I don't need anyway. Can I simply remove the line from the makefile which requires this file and happily go on my way? While running make check, I get the following error:
 - bruno():ddccontrol-0.4.2$ make check
Making check in src
make[1]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/src'
Making check in lib
make[2]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/src/lib'
make[2]: Nothing to be done for `check'.
make[2]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/src/lib'
Making check in ddccontrol
make[2]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/src/ddccontrol'
make[2]: Nothing to be done for `check'.
make[2]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/src/ddccontrol'
Making check in gddccontrol
make[2]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/src/gddccontrol'
make[2]: Nothing to be done for `check'.
make[2]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/src/gddccontrol'
Making check in ddcpci
make[2]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/src/ddcpci'
make[2]: Nothing to be done for `check'.
make[2]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/src/ddcpci'
make[2]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/src'
make[2]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/src'
make[1]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/src'
Making check in po
make[1]: Entering directory `/home/dotancohen/ddccontrol-0.4.2/po'
make[1]: *** No rule to make target `../src/ddcpci/intel740.c', needed by `ddccontrol.pot'.  Stop.
make[1]: Leaving directory `/home/dotancohen/ddccontrol-0.4.2/po'
make: *** [check-recursive] Error 1

Consider this copy-and-paste from /home/dotancohen/ddccontrol-0.4.2/po/Makefile:
POTFILES = \
    ../src/ddccontrol/main.c \
    ../src/ddcpci/i2c-algo-bit.c \
    ../src/ddcpci/intel740.c \
    ../src/ddcpci/intel810.c \
    ../src/ddcpci/main.c \
    ../src/ddcpci/nvidia.c \
    ../src/ddcpci/radeon.c \
    ../src/gddccontrol/fspatterns.c \
    ../src/gddccontrol/gddccontrol.desktop.in \
    ../src/gddccontrol/gprofile.c \
    ../src/gddccontrol/main.c \
    ../src/gddccontrol/notebook.c \
    ../src/gnome-ddcc-applet/GNOME_ddcc-applet.server.in.in \
    ../src/gnome-ddcc-applet/GNOME_ddcc-applet.xml \
    ../src/gnome-ddcc-applet/ddcc-applet.c \
    ../src/lib/conf.c \
    ../src/lib/ddcci.c \
    ../src/lib/monitor_db.c

And consider these files that do exist:
 - bruno():ddccontrol-0.4.2$ ls -la src/ddcpci/
total 544
drwxrwxr-x 4 dotancohen dotancohen   4096 Nov 14 08:29 .
drwxrwxr-x 7 dotancohen dotancohen   4096 Nov 14 08:28 ..
-rwxrwxr-x 1 dotancohen dotancohen 139344 Nov 14 08:29 ddcpci
-rw-r--r-- 1 dotancohen dotancohen   1900 Mar  9  2006 ddcpci.h
drwxrwxr-x 2 dotancohen dotancohen   4096 Nov 14 08:29 .deps
-rw-r--r-- 1 dotancohen dotancohen  13597 Jun 15  2006 i2c-algo-bit.c
-rw-r--r-- 1 dotancohen dotancohen   2573 Jan 10  2005 i2c-algo-bit.h
-rw-rw-r-- 1 dotancohen dotancohen  92536 Nov 14 08:29 i2c-algo-bit.o
-rw-r--r-- 1 dotancohen dotancohen   8029 Apr  5  2006 intel810.c
-rw-rw-r-- 1 dotancohen dotancohen  27432 Nov 14 08:29 intel810.o
drwxrwxr-x 2 dotancohen dotancohen   4096 Nov 14 08:29 .libs
-rw-r--r-- 1 dotancohen dotancohen   8706 Mar  3  2006 main.c
-rw-rw-r-- 1 dotancohen dotancohen  47752 Nov 14 08:29 main.o
-rw-rw-r-- 1 dotancohen dotancohen  19944 Nov 14 08:28 Makefile
-rw-r--r-- 1 dotancohen dotancohen    265 Mar  3  2006 Makefile.am
-rw-r--r-- 1 dotancohen dotancohen  17227 Jul 27  2006 Makefile.in
-rw-r--r-- 1 dotancohen dotancohen   5647 Feb 14  2006 nvidia.c
-rw-rw-r-- 1 dotancohen dotancohen  21720 Nov 14 08:29 nvidia.o
-rw-r--r-- 1 dotancohen dotancohen   6982 Jul 11  2006 radeon.c
-rw-rw-r-- 1 dotancohen dotancohen  25416 Nov 14 08:29 radeon.o
-rw-r--r-- 1 dotancohen dotancohen   4832 Mar  3  2006 sis.c
-rw-rw-r-- 1 dotancohen dotancohen  24504 Nov 14 08:29 sis.o
-rw-r--r-- 1 dotancohen dotancohen   5814 Mar  3  2006 via.c
-rw-rw-r-- 1 dotancohen dotancohen  22200 Nov 14 08:29 via.o

Note that for ./configure to succeed I did have to install a few packages:
sudo aptitude install libxml2-dev pciutils-dev libgtk2.0-dev

Can I simply remove the line ../src/ddcpci/intel740.c \ from the makefile?

A: Try removing it. It will probably just mean that the functionality in that file (which you don't need any ways) will be missing.
Depending on how the makefile is made up, you might get an error from the linker when it can't find the object file for that module, but it will probably be handled automatically.
What's a worse risk however is that there is other code that is dependent on the code in that missing file; in that case the linker will report unresolved dependencies and to fix that you will have to modify the code, not just the makefile.