text:
Q: How to Display EC2 Instance name using Boto 3 I am using the below code for displaying instance_id,instance_type but I am unable to display the Instance name which I want
print (instance.id, instance.instance_type, region) this is working but this not instance.instance_name
import boto3
access_key = "AKIAJ5G2FAUVO3TXXXXXXXX"
secret_key = "nk7eytkWfoSDU0GwvBZVawQvXXXXXX"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name='us-east-1')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
                conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)
                instances = conn.instances.filter()
                for instance in instances:
                    if instance.state["Name"] == "running":
                        print (instance.instance_name,instance.id, instance.instance_type, region)

A: There instance object you are using does not have a name attribute. The reason is that the "Name" of an instance, is only based on a tag called Name. So you have to get tags, and find a tag name of Name:
def get_tag(tags, key='Name'):

  if not tags: return ''

  for tag in tags:

    if tag['Key'] == key:
      return tag['Value']

  return ''

ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]

for region in ec2_regions:
    conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)
    instances = conn.instances.filter()
    for instance in instances:
        instance_name = get_tag(instance.tags)
        print (instance_name, instance.id, instance.instance_type, region)


text:
Q: Script to check if SSH service in Docker is up My docker container has two services: a web service and a SSH server.
The SSH server is openssh-server and I need to run the command docker exec -it my-container sudo service ssh restart from outside the container to start the SSH server.
However, the command doesn't succeed all the time. Every time I need to manually check if the SSH server is up in the container using the command: ssh root@localhost:
1) If the SSH server fails to start, the result is ssh_exchange_identification: Connection closed by remote host
2) Otherwise, it asks for the password. (Which indicates that the SSH server is up)
Since I have to deploy multiple containers at the same time, it is unrealistic to check every container manually. Therefore, I want to retry the docker exec -it my-container sudo service ssh restart command automatically if the SSH serve fails to start. But I am not sure how to write the bash script to achieve this. It basically should work like this:
while (ssh_server_fails_to_start):
    docker exec -it my-container sudo service ssh restart

Any comments or ideas are appreciated. Thanks in advance!

A: If the sshd is up an running, it will accept connections on its certain port.  Otherwise, the connection attempt will fail.
If you run the following command:
ssh -o PasswordAuthentication=No root@localhost true

This will fail in either way, but the output will be different.  In the case that the server is running and accepting connections, the explicit switch-off of password authentication will make it fail with this message:
Permission denied (publickey,password).

Otherwise it will print out a message like this:
ssh: connect to host localhost port 22: Connection refused

So I propose to scan the error message for a hint like this:
if ssh -o PasswordAuthentication=No root@localhost true \
     |& grep -q "Connection refused"
then
    echo "No server reachable!"
else
    echo "Server reachable."
fi

So you could write your script like this:
while ssh -o PasswordAuthentication=No root@localhost true \
        |& grep -q "Connection refused"
do
  docker exec -it my-container sudo service ssh restart
done

You might want to add some sleep delays to avoid hurried restarts.  Maybe the ssh server just needs some time to accept connections after being restarted.

A: To test the ssh connection, we can use sshpass package to provide a password in the command line.
while : ; do
    docker exec -it my-container sudo service ssh restart
    sleep 5s
    sshpass -p 'root' ssh -q root@localhost -p 2222 exit
    if [ $? == 0 ]; then
            echo "SSH server is running."
            break
    fi
    echo "SSH server is not running. Restarting..."
done

redpajama_set_name: RedPajamaStackExchange


text:
Q: implement the URL match in C++ Given a list of URLs, such as a/b/e/f, b/c/d/k/g, s/e/c/d, how to match an input URL to the one in the list, for example, an input c/d should be matched to s/e/c/d, not b/c/d/k/g

A: Why not b/c/d/k/g? Are the "Url"s simply strings? If so simply search it using strstr or one of its derivative (wcsstr, _mbsstr, _mbsstr_l).

A: Just check if input is equal to input.size() trailing characters in the possible url match.


text:
Q: Beside semantic and syntax, is there any other level at which a program can be correct or incorrect? How does this relate to SFINAE? tl;dr
I want to understand the logic by which I can make the following comments about a non-working code:

*

*Oh, it's obvious it fails, there's syntactic error there at line 5

*Mmm, look, I think between lines 10 and 13 there's a semantic error

*No, you cannot call a variable a±b, that's a lexical error

*At line 50 there's a X error, for any X type of error beside semantic and syntactic.

Original question
I add the C++ because I use an example from this language, and the language-lawyer tag in case the answer is language-dependent, even though my question is more general.
If I write this code in C++,
x x x;

it won't compile with error like this
$ g++ -std=c++17 uffa.cpp && ./a.out
uffa.cpp: In function 'int main()':
uffa.cpp:4:6: error: expected ';' before 'x'
    4 |     x x x;
      |      ^~
      |      ;

My understanding is that x x x; is just syntactically wrong; ill-formed is a better term? Or syntactically ill-formed?
On the other hand, code this
    s.append("!");

can be valid, e.g. if it is preceded by std::string s{"Ciao"};, or invalid, e.g. if preceded by int s{3};, in the latter case the error being like this
$ g++ -std=c++17 uffa.cpp && ./a.out
uffa.cpp: In function 'int main()':
uffa.cpp:5:7: error: request for member 'append' in 's', which is of non-class type 'int'
    5 |     s.append("!");
      |       ^~~~~~

Despite the errors have the same "shape", my understanding is that this latter error has to do with the code being invalid at a different "level" than it is in the first example. Is it semantically invalid/incorrect/ill-formed?
How does this "classification" of errors relate to SFINAE and if constexpr?


text:
Q: Learning more about componentDidMount and its warning on the console I don't know why, but I'm seeing the following warning when I'm running my React application:
react-dom.development.js:12357 Warning: componentWillMount has been renamed, and is not recommended for use. See *documentation* for details.

* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

Please update the following components: SideEffect(NullComponent)

I'm getting confused because I'm not using this lifecycle method. Instead, I'm using useEffect, useMemo and useState hooks in my code. I wish I had some way of get rid of this warning.

A: I was also getting this warning. It was because I was using react-router-dom and react-select which was internally using componentWillUnmount that was the cause of the warning.
What did I do?
First I did npm update for the affected modules.
But still, there were other modules that had not released new versions. So in order to get rid of this warning and see a relevant warning, I did console.disableYellowBox = true;
This was purely for my case.
In case if you don't know these warnings, they will only be shown in development mode and not in production. See documentation here.


text:
Q: static variable initialization I have a template class that implements a singleton:
template<typename T>
class Singleton {
     static Singleton const& get() const { return _instance; }
   private:
      Singleton();
      static Singleton _instance;
};

There are some specializations of this template, for example, for Type1 and Type2. And its constructors there are calls of get() of each other. I see a problem. Let's assume that Singleton of Type1 is constructed at first:
Singleton<Type1>::Singleton() {
   Singletion<Type2>::get();
}

So the Singleton of Type2 is not constructed yet. What will be returned by get()?

A: You need to make the _instance a static inside the get function.
template<typename T>
class Singleton {
     static Singleton const& get() const {
       static Singleton _instance;
       return _instance;
     }
   private:
      Singleton();
};

This way, the instance will be initialized the first time get is called.

A: The cyclic dependency is bad:
struct Singleton2;

struct Singleton1 {
     static Singleton1 const& get() {
       static Singleton1 _instance;
       return _instance;
     }
   private:
      Singleton1();
      Singleton2 const& _s2;
};

struct Singleton2 {
     static Singleton2 const& get() {
       static Singleton2 _instance;
       return _instance;
     }
   private:
      Singleton2();
      Singleton1 const& _s1;
};

Singleton1::Singleton1() : _s2(Singleton2::get()) { }
Singleton2::Singleton2() : _s1(Singleton1::get()) { }

int main()
{
    auto& s1 = Singleton1::get();
    auto& s2 = Singleton2::get();
}

Will result in a failure (see http://liveworkspace.org/code/4rPFDo$0).
Like in all cases where you need to break cycles, make at least one link in the chain lazy.
Solve it in the obvious way by not requiring a reference to the other singleton during construction:
struct Singleton2;

struct Singleton1 {
     static Singleton1 const& get() {
       static Singleton1 _instance;
       return _instance;
     }
   private:
      Singleton1() {}
      static Singleton2 const& getOther();
};

struct Singleton2 {
     static Singleton2 const& get() {
       static Singleton2 _instance;
       return _instance;
     }
   private:
      Singleton2() {}
      static Singleton1 const& getOther();
};

Singleton2 const& Singleton1::getOther() { return Singleton2::get(); }
Singleton1 const& Singleton2::getOther() { return Singleton1::get(); }

int main()
{
    auto& s1 = Singleton1::get();
    auto& s2 = Singleton2::get();
}

Alternatively delay-initialize using boost::optional, boost::flyweight or a custom 'lazy_ptr': https://stackoverflow.com/a/878298/85371


text:
Q: Reflection - read a property of type class rather than string or int I'm using Reflection to read properties and their values of a class. There are Strings, Booleans and properties of a class type. How to get the value of the class type.
User.java
private String firstName;
private String lastName;
private SupportLangauge flang;
private SupportLangauge mlang;

SupportLanguage.java
private String languageCode;
private Boolean flang;
private Boolean mlang;

I am able to save the data of flang, mlang using reflection, but unable to read value. When I do read, the object is being returned. See sample below.
Result:
       "flang": "com.sample.entity.user.SupportLanguage@3080037d
          [\r\n     languageCode=EN_US\r\n]",
       "mlang": "com.sample.entity.user.SupportLanguage@3080037d
          [\r\n  languageCode=EN_US\r\n]",

My code below for saving the language types.
SavingUser.java
for (User user : CollectionsUtilService.nullGuard(userList)) {
 PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(
   user.getClass()).getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if (fieldValueMap.containsKey(propertyDescriptor.getName())) {
if   (propertyDescriptor.getPropertyType().getName().
 equalsIgnoreCase("com.sample.entity.user.SupportLanguage")) {
                    String langString =   fieldValueMap.
             get(propertyDescriptor.getName());
             SupportLanguage s = new SupportLanguage();
                    s.setLanguageCode(langString);
                    propertyDescriptor.getWriteMethod().invoke(user, s);
                }

            }
        }
    }

My Code for Reading the value;
RenderingUser.java
               if (propertyDescriptor.getPropertyType().
                 getName().equalsIgnoreCase
               ("com.sample.entity.
                  user.SupportLanguage")) {
                  Method m = propertyDescriptor.getReadMethod();
                  SupportLanguage s = new SupportLanguage();
                  System.out.println("m.invoke(SupportLanguage) "
                  +  m.invoke(s));

A: Your reading is almost correct. But you must use the root object (User) not the property object.
User user = ...; // Initialized user object
           if (propertyDescriptor.getPropertyType().
             getName().equalsIgnoreCase
           ("com.sample.entity.
              user.SupportLanguage")) {
              Method m = propertyDescriptor.getReadMethod();
              SupportLanguage s = m.invoke(user);
              System.out.println("languageCode: " + s.getLanguageCode());

A: if you implement the Java Bean standard (i.e. have getter methods with proper names) then I recommend the Apache BeanUtils package.
The PropertyUtils.getSimpleProperty(Object, String) will get you the property you need and there is also an easy way to get nested properties
lastly, you have one neat method that gives oyu ALL properties that have getters into a map

A: instead of using the java bean API you can also use pure reflection like the following example. the point is to set the private field accessible what may cause a accessibility-exception if the vm runs on a secure environment that has restrictions on that. but for this cases you may can make your properties protected.
public class GetPropertyTest {

@Test
public void testGetFLang() throws Exception {
    User user = new User();

    Field declaredField = user.getClass().getDeclaredField( "flang" );
    declaredField.setAccessible( true );

    // get the value
    SupportLanguage flang = (SupportLanguage) declaredField.get( user );

    assertEquals(
        "SupportLanguage [languageCode=lang1, flang=true, mlang=true]",
        flang.toString()
    );

    // set new value
    declaredField.set( user, new SupportLanguage( "lang3", false, false ) );
    assertEquals(
        "User [firstName=null, lastName=null, "
        + "flang=SupportLanguage [languageCode=lang3, flang=false, mlang=false], "
        + "mlang=SupportLanguage [languageCode=lang2, flang=true, mlang=true]]",
        user.toString()
    );
}

@Test
public void testSetValuesFromMap() throws Exception {
    Map<String, Object> valueMap = new HashMap<String, Object>();
    valueMap.put( "firstName", "Jon" );
    valueMap.put( "lastName", "Doo" );
    valueMap.put( "flang", new SupportLanguage( "langFormMap1", true, true ) );
    valueMap.put( "mlang", new SupportLanguage( "langFormMap2", true, true ) );

    User user = new User();

    for ( Map.Entry<String, Object> entry : valueMap.entrySet() ) {
        String fieldName = entry.getKey();
        Object fieldValue = entry.getValue();
        Field declaredField = user.getClass().getDeclaredField( fieldName );
        declaredField.setAccessible( true );
        declaredField.set( user, fieldValue );
    }

    assertEquals(
        "User ["
        + "firstName=Jon, "
        + "lastName=Doo, "
        + "flang=SupportLanguage [languageCode=langFormMap1, flang=true, mlang=true], "
        + "mlang=SupportLanguage [languageCode=langFormMap2, flang=true, mlang=true]]",
        user.toString()
    );
}

public class User {
    private String firstName;
    private String lastName;
    private SupportLanguage flang = new SupportLanguage( "lang1", true, true );
    private SupportLanguage mlang = new SupportLanguage( "lang2", true, true );
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append( "User [firstName=" );
        builder.append( firstName );
        builder.append( ", lastName=" );
        builder.append( lastName );
        builder.append( ", flang=" );
        builder.append( flang );
        builder.append( ", mlang=" );
        builder.append( mlang );
        builder.append( "]" );
        return builder.toString();
    }

}

public class SupportLanguage {

    private String languageCode;
    private Boolean flang;
    private Boolean mlang;

    public SupportLanguage( String languageCode, Boolean flang, Boolean mlang ) {
        super();
        this.languageCode = languageCode;
        this.flang = flang;
        this.mlang = mlang;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append( "SupportLanguage [languageCode=" );
        builder.append( languageCode );
        builder.append( ", flang=" );
        builder.append( flang );
        builder.append( ", mlang=" );
        builder.append( mlang );
        builder.append( "]" );
        return builder.toString();
    }
}

}


text:
Q: I have a load of data on Google Sheets. I would to use this to practice running SQL queries. How can I do this? I have decided to learn SQL as I am running into limitations on excel.
I have a bunch of data on sheets/excel which would be perfect for me to practice using SQL. Unfortunately, whilst I have spent a lot of time learning how to run queries I know little about how to starting using SQL in the first place.
So my question is, how do I go from having my data in xls to querying a database?
At this point it's not huge amounts of data and its just for private use; preferably this would be doable on ChromeOS (or, if not, on Mac OS X) and for free.
This is what I think I will need to do, am I on the right track or is there a simpler way to achieve what I want?

*

*convert the xls file to csv

*convert the csv files to sql using an online converter

*signup for a free trial of (eg) google cloud services

*create an SQL instance

*connect to the SQL instance using a mysql client

*import the sql files into the SQL instance

A: Convert your Google Sheets to excel. Then follow the instructions on MySQL docs to import your excel data into a MySQL table. You can find the instructions here: https://dev.mysql.com/doc/mysql-for-excel/en/mysql-for-excel-export.html


text:
Q: Style invalid  using :invalid I have a <select>:

select:invalid {
  color: red;
}
<select required>
  <option disabled selected>- please choose -</option>
  <option value="1">A</option>
  <option value="2">B</option>
</select>

Unfortunately the disabled select is not marked red.
Any idea?
It's not the option I like to style, I like to style the select!

A: You need to specify value="" for the first option. Without value="", the value of an option is implicitly equal to its text content, meaning it fulfils the required constraint.
Demo:

select:invalid { color: red; }
<select required>
  <option disabled value="" selected>- please choose -</option>
  <option value="1">A</option>
  <option value="2">B</option>
</select>

The above will make the select + all options red until a value has been chosen.
If you want the options to always be black, just extend the CSS a little:

select:invalid { color: red; }
select option { color: black; }
<select required>
  <option disabled value="" selected>- please choose -</option>
  <option value="1">A</option>
  <option value="2">B</option>
</select>

A: Try to use option:disabled.

select option:disabled {
  color: red;
}
<select required>
  <option disabled selected>- please choose -</option>
  <option value="1">A</option>
  <option value="2">B</option>
</select>

A:

.choose_elements{
    background-color : red;
}
.elements{
    background-color : white;
}
<select required
    onchange="this.className=this.options[this.selectedIndex].className"
    class="choose_elements">
    <option value="0" class="choose_elements">- please choose -</option>
    <option value="1" class = "elements">A</option>
    <option value="2" class = "elements">B</option>
</select>


text:
Q: Retrieve data from dataset webservice in Xamarin and set it to textview Here is my code. Im getting the data but name1 return's null value. I want to display the data obtain from the webservice in form of dataset in textView and imageview. Can you help me please?
When it executes line  name1.SetText(productName);
the error get is
Unhandled Exception:

System.NullReferenceException: Object reference not set to an instance
  of an object. occurred

below is what the local variable stored.

Name  Value Type
detailOfproduct         "The botle is"            string
fdetail                 "The botle is"            string
fimage                  "iVBORw0"                 string
fname                   "Bottle"                  string
imageproduct            "iVBORw0"                 string
productName             "Bottle"                  string
name1                   (null)
  Android.Widget.TextView
detail                  (null)
  Android.Widget.TextView

WebReferencec.WebService add = new WebReferencec.WebService();
DataSet result = add.getData("bottle");

DataTable dt = result.Tables["product"];

        //DataRow row = dt.NewRow();

       fname = dt.Rows[0]["name"];
       fdetail= dt.Rows[0]["detail"];
       fimage = dt.Rows[0]["image"];

       // dt.Rows.Add(row);

         imageproduct = Convert.ToString(fimage);
         productName = Convert.ToString(fname);
         detailOfproduct = Convert.ToString(fdetail);

        byte[] ba = Convert.FromBase64String(imageproduct);
        using (var stream = new MemoryStream(ba))
        {
            ImageView image = FindViewById<ImageView>(Resource.Id.ivgallery);
            TextView name1 = FindViewById<TextView>(Resource.Id.tvname);
            TextView detail = FindViewById<TextView>(Resource.Id.tvdetail);
            Bitmap bitmap = BitmapFactory.DecodeByteArray(ba, 0, ba.Length);
            RunOnUiThread(() =>
            {
                image.SetImageBitmap(bitmap);
                name1.SetTextKeepState( productName);
                detail.SetTextKeepState( detailOfproduct);

                }
            );

        }

A: When i declared the variable image name and detail by puting imageview and text view the variable are not in string. So i had to put var infront to convert it to string.
Var image = FindViewById(Resource.Id.ivgallery);
Var name1 = FindViewById(Resource.Id.tvname);
var detail = FindViewById(Resource.Id.tvdetail);


text:
Q: URI rerouting issue in codeigniter (version 2.2.0) I am struggle with URI rerouting in my codeigniter version(2.2.0)application.
Here is my routes.php
$route['details/(:num)'] = 'agent/manage_agents/$1';

And in my view file
foreach($data as $value) {?>

<a href="<?php base_url();?>details/<?php echo $value['id']; ?>" class="btn btn-primary">Manage
}?>

But i will get 404 error.
In my Controller file
class Agent extends CI_Controller {

   public function manage_agents($id)
    {
        echo $id;
    }
}

UPDATE
Finally i found Which causes the problem.In my routes.php
$route['(:any)'] = "spotmyticket/$1";

when hide this line everything works  fine.
Here is my complete routes.php
$route['404_override'] = '';
$route['default_controller'] = "spotmyticket";
$route['ticket']="ticket";
$route['ticket/(:any)'] = $route['ticket'].'/$1';

$route['captcha'] = "captcha";
$route['captcha/(:any)'] = "captcha/$1";
$route['admin'] = "admin";
$route['admin/(:any)'] = "admin/$1";
$route['userdashboard'] = "userdashboard";
$route['userdashboard/(:any)'] = "userdashboard/$1";
$route['fbci'] = "fbci";
$route['fbci/(:any)'] = "fbci/$1";

$route['(:any)'] = "spotmyticket/$1";

$route['agent-management'] = 'agent/index';
$route['register'] = "agent/agent_register";
$route['test'] = 'agent/test';
$route['details/(:any)'] = 'agent/manage_agents/$1';

Here spotmyticket is the default controller of my site

A: Place this line at the end of file. $route['(:any)'] its breaking the execution of your other routing rules.
$route['(:any)'] = "spotmyticket/$1";


text:
Q: Apache Camel - Split and aggregate - Old Exchange is always null I see that this question has been asked a number of times but none of post helped or had a conclusive solution. I am splitting a message and then aggregating it using Aggregator2. The code was throwing exception because oldExchange was always null. So to test I designed a small code.
I read an orders,xml file which looks like this
<Orders xmlns="http://some/schema/Order">
    <Order>
            <orderNum>1</orderNum>
    </Order>
    <Order>
            <orderNum>2</orderNum>
    </Order>
    <Order>
            <orderNum>3</orderNum>
    </Order>
    <Order>
            <orderNum>5</orderNum>
    </Order>
    <Order>
            <orderNum>6</orderNum>
    </Order>

My camel Context Looks like this

<camel:route>
<camel:from uri="file:src/data/catask/test?noop=true"/>
<camel:log message="${body}"></camel:log>
<camel:split>
<camel:xpath>//te:Orders/*</camel:xpath>
<camel:to uri="direct:logQueries"/>
<camel:to uri="direct:aggegateQueries"/>
</camel:split>

</camel:route>

<camel:route>
<camel:from uri="direct:logQueries"/>
<camel:log message="After the call : \n ${body}"></camel:log>
</camel:route>

 <camel:route>
<camel:from uri="direct:aggegateQueries"/>
<camel:aggregate strategyRef="aggrTask" completionInterval="8000" >
<camel:correlationExpression>
<camel:xpath>//te:Order</camel:xpath>
</camel:correlationExpression>
<camel:to uri="file:src/data/catask/output?fileName=output.xml"/>

</camel:aggregate>
</camel:route>

My Aggregation Strategy class looks like this
   public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
            if (oldExchange == null) {
            System.out.println("Returning new exchange");
                return newExchange;
            }

            String oldBody = oldExchange.getIn().getBody(String.class);
            String newBody = newExchange.getIn().getBody(String.class);
            oldExchange.getIn().setBody(oldBody + "+" + newBody);
            return oldExchange;
        }

The problem is that when the aggregated result is saved in output.xml file it contains only the last record it read from Orders.xml.
i.e.
<Order xmlns="http://some/schema/Order">
            <orderNum>6</orderNum>
    </Order>

I looked into it further and found that this was happening because after the first call oldExchange should have some value but it turns out it is always null. I think that because it is reading everything from a single file and splitting it, there is only exchange.
> Any suggestions??
UPDATE 1: Per Claus I can use Splitter only to solve this issue. I did that and was able to successfully join all the messages. However I am still looking for a way to use Aggregator2. Here how I did it using Splitter only.
camel:route>
<camel:from uri="file:src/data/catask/test?noop=true"/>
<camel:log message="${body}"></camel:log>
<camel:split strategyRef="aggrTask">
<camel:xpath>//te:Orders/*</camel:xpath>
<camel:to uri="direct:logQueries"/>
 <
</camel:split>

</camel:route>

<camel:route>
<camel:from uri="direct:logQueries"/>
<camel:log message="After the call : \n ${body}"></camel:log>
</camel:route>

A: I think I figured it out how to aggregate the messages using Aggregator. I added a headerName called id and use it as my correlation id.
<camel:route>
  <camel:from uri="file:src/data/catask/test?noop=true"/>
  <camel:log message="${body}"></camel:log>
  <camel:split>
    <camel:xpath>//te:Orders/*</camel:xpath>
    <camel:to uri="direct:addHeaders"/>
    <camel:to uri="direct:aggegateQueries"/>
  </camel:split>
</camel:route>

<camel:route>
  <camel:from uri="direct:addHeaders"/>
  <camel:setHeader headerName="id">
    <camel:constant>order</camel:constant>
  </camel:setHeader>
</camel:route>

<camel:route>
  <camel:from uri="direct:aggegateQueries"/>
  <camel:aggregate strategyRef="aggrTask" completionInterval="8000" >
    <camel:correlationExpression>
      <simple>header.id</simple>
    </camel:correlationExpression>
    <camel:to uri="file:src/data/catask/output?fileName=output.xml"/>
    <camel:log message="MERGED:: /n ${body}"></camel:log>
  </camel:aggregate>
</camel:route>

This aggregates my messages. However I am still not sure that despite using correct XPATH why does Camel thinks that it is different type of message?
COPYING CLAUS's explanation from camel forums:
"Looks like its your correlation expression that is a new group for
each message, eg each xpath result is different.
If you want to split and join the same messages then see this eip
http://camel.apache.org/composed-message-processor.html
And see the example using only splitter. That is much easier to do. "
I tested the Xpath expression using a Xpath Evaluator tool and also printed out the coorelation expression results and all my messages with //Order are same. Ex-
Group 1:
<Order>
  <orderNum>1</orderNum>
</Order>

Group 2:
<Order>
  <orderNum>2</orderNum>
</Order>

A: <camel:correlationExpression>
  <simple>header.id</simple>
</camel:correlationExpression>

could be replaced by:
<!-- Required! The expression to retrieve the correlation key. When no key the constant true could be used. -->
<camel:correlationExpression>
  <constant>true</constant>
</camel:correlationExpression>


text:
Q: ProcessBuilder launching of X11 app fails with java7, worked with java6 I have a server process written in java that uses ProcessBuilder to launch a command line program (the R statistic engine) that can cause X11 to start up when run with the Apple 1.6 jvm. However, this does not work with the Oracle 1.7 jvm. I get no error messages on stdout, stderr, or in the console.
Any ideas what might be the problem?
The java process listens to the network and needs to start R with command line options that can very, i.e. it can start/stop R multiple times. There would be a tremendous amount of work required to launch R outside of java.

A: Please try to upgrade your Java to >= 1.7.0.11.
We had a similar problem where we executed a wine program out of our java application using ProcessBuilder under CentOS 5. It worked with Java 1.6 but broke with Java 1.7.0.9. After upgrading to 1.7.0.11 the problem was gone.


text:
Q: Python: How to read images from zip file in memory? I have seen variations of this question, but not in this exact context. What I have is a file called 100-Test.zip which contains 100 .jpg images. I want to open this file in memory and process each file doing PIL operations. The rest of the code is already written, I just want to concentrate on getting from the zip file to the first PIL image. This is what the code looks like now from suggestions I've gathered from reading other questions, but it's not working. Can you guys take a look and help?
import zipfile
from StringIO import StringIO
from PIL import Image

imgzip = open('100-Test.zip', 'rb')
z = zipfile.ZipFile(imgzip)
data = z.read(z.namelist()[0])
dataEnc = StringIO(data)
img = Image.open(dataEnc)

print img

But I am getting this error when I run it:
 IOError: cannot identify image file <StringIO.StringIO instance at
 0x7f606ecffab8>

Alternatives: I have seen other sources saying to use this instead:
image_file = StringIO(open("test.jpg",'rb').read())
im = Image.open(image_file)

But the problem is I'm not opening a file, it's already in memory inside the data variable. I also tried using dataEnc = StringIO.read(data) but got this error:
TypeError: unbound method read() must be called with StringIO instance as
first argument (got str instance instead)

A: There is no need to use StringIO. zipfile can read image file in memory. The following loops through all images in your .zip file:
import zipfile
from PIL import Image

imgzip = zipfile.ZipFile("100-Test.zip")
inflist = imgzip.infolist()

for f in inflist:
    ifile = imgzip.open(f)
    img = Image.open(ifile)
    print(img)
    # display(img)

A: Turns out the problem was there was an extra empty element in namelist() due to the images being zipped inside a direcotory insde the zip file. Here is the full code that will check for that and iterate through the 100 images.
import zipfile
from StringIO import StringIO
from PIL import Image
import imghdr

imgzip = open('100-Test.zip')
zippedImgs = zipfile.ZipFile(imgzip)

for i in xrange(len(zippedImgs.namelist())):
    print "iter", i, " ",
    file_in_zip = zippedImgs.namelist()[i]
    if (".jpg" in file_in_zip or ".JPG" in file_in_zip):
        print "Found image: ", file_in_zip, " -- ",
        data = zippedImgs.read(file_in_zip)
        dataEnc = StringIO(data)
        img = Image.open(dataEnc)
        print img
    else:
        print ""

Thanks guys!

A: I have the same issue, thanks for @alfredox, I modified the answer, use io.BytesIO not StringIo in python3.
z = zipfile.ZipFile(zip_file)
for i in range(len(z.namelist())):

    file_in_zip = z.namelist()[i]
    if (".jpg" in file_in_zip or ".JPG" in file_in_zip):

        data = z.read(file_in_zip)
        dataEnc = io.BytesIO(data)
        img = Image.open(dataEnc)
        print(img)

A: If you need to work on pixel data then you can load an image stream data from zip file as numpy array keeping the original data shape (i.e. 32x32 RGB) following the steps:

*

*use zipfile to get the ZipExtFile format

*use PIL.Image to convert ZipExtFile into image like data structure

*convert PIL.image into numpy array

No need to reshape numpy array with original data shape because PIL.Image already has the information. So the output will be a numpy array with shape=(32,32,3)
import numpy as np
import zipfile
from PIL import Image

with zipfile.ZipFile(zip_data_path, "r") as zip_data:
    content_list = zip_data.namelist()
    for name_file in content_list:
        img_bytes = zip_data.open(name_file)          # 1
        img_data = Image.open(img_bytes)              # 2
        # ndarray with shape=(32,32,3)
        image_as_array = np.array(img_data, np.uint8) # 3

A: cv2.imdecode() version:
with zipfile.ZipFile(zip_data_path, "r") as z:
    for img_name in z.namelist():
        buf = z.read(name)
        np_buf = np.frombuffer(buf, np.uint8)
        img = cv2.imdecode(np_buf, cv2.IMREAD_UNCHANGED)
        # Saving image as an example.
        cv2.imwrite(name, img)


text:
Q: Show that $G$ is a Groebner bases of $I$ if division of $f$ on $G$ is zero for all $f\in I$.
Let $I=\langle g_1,\dots, g_t\rangle$ be an ideal in $k[x_1,\dots,x_n]$ with $k$ a field. Let $G=\{g_1,\dots,g_t\}$. Show that if the remainder of $f$ on division by $G$ is $0$ for all $f\in I$, then $G$ is a Groebner basis.

My attempt:
We need to show that $\text{LT}(f)$ is divisible by $\text{LT}(g_i)$ for some $g_i\in G$, for all $f\in I$, where $\text{LT}(\cdot)$ means the leading term of the polynomial.
Since $f\in I$, and $G$ is a bases of $I$, we can write
$$f=\sum_{i=0}^t h_i g_i$$
for some $h_i\in k[x_1,\dots, x_n]$. I don't know how to continue then, since I cannot write the leading term of $f$ in terms of a single $g_i$. It can be combination of $g_i$'s. So I cannot say it is divisible by one of them.
Thank you for any help!

A: Take ${\rm LT}$ in $$f=\sum_{i=0}^t h_i g_i.$$ Then ${\rm LT}(f)=\sum_j{\rm LT}(h_j){\rm LT}(g_j)\in\langle{\rm LT}(g_1),\dots,{\rm LT}(g_t)\rangle$.


text:
Q: MongoDB how to find by index ignore case How can I find document using nickname as index? I don't know is it in upper/lower case.
_id: ...
credits: {
  nickname: "test"
  password: "hash"
}

Right now I'm trying to do something like this, but unsuccessful.
mongo.createIndex(new Document("credits.nickname", "text"),
 new IndexOptions().name("nickname").unique(true)
  .collation(Collation.builder()
    .locale("simple").caseLevel(false).collationStrength(CollationStrength.PRIMARY)
  .build()))

// null
mongo.collection().find(new Document("credits.nickname", "TEST")).projection(Projections.include("credits"))

A: It seems you are looking for something like that https://www.mongodb.com/docs/manual/core/index-case-insensitive/#examples
Also you can consider saving same info with new field name with always lowercase value and making searches against it with lowercased query text.


text:
Q: linux ident protocol equivalent for localhost connections How to make perl script access equivalent for ident protocol provided info for loopback/localhost/127.0.0.1 tcp connections?
In short: I want to check local OS account at the other end of tcp connection over loopback interface (from this host to this host).  As far as I vaguely remember it is possible without any local server service.


text:
Q: Selenium split webelement text and use to click I'm trying to take value from decimal field which will be dynamic eg. value of that field is "12.01". Then I need to take all the numbers and convert those to separate int's and use is as input for the numpad keyboard.
Steps:

*

*Getting value from the field

*Transferring those into string:
var nums = new string(textFromElement.Where(Char.IsDigit).ToArray());
From value: "12.01" I have variable nums as: "1201"

*Use this numbers as separate int's inside a method

driver.FindElement(By.XPath(string.Format(locator, Separatenumber))).Click();
I suppose I need to create foreach loop but first of all I need to separate ints, how it can be done?

A: You can convert the string into a char array and then convert it into an int array
int[] intArray = Array.ConvertAll(nums, c => (int)Char.GetNumericValue(c));


text:
Q: Change linux multicast interface Why my multicast traffic always goes through wlan0 interface?
I try
ip route add 224.0.0.0/4 dev lo
ip link set dev lo multicast on
ip route flush cache

But VLC casting to 224.0.0.1:1111 always goes through wlan0 interface.
ip route:
default via 192.168.0.1 dev wlan0  proto static  metric 600
192.168.0.0/24 dev wlan0  proto kernel  scope link  src 192.168.0.102  metric 600
224.0.0.0/4 dev lo  scope link

A: Ok the problem you are running into is VLC is defaulting to the interface of your default route, but you need the device of the default route to be a different network card.
You can't have two default routes but you can do a little hackary to get around this.
1) Set the default route to be the network card you want to receive multicast packets on. For example eth4
ip route del default
ip route add default dev eth4

Your computer will no longer be able to route traffic to your gateway so your internet will break.
2) To fix it route all traffic to your gateway.
ip route add 0.0.0.0/1 via (ip of gateway) dev wan1
ip route add 128.0.0.0/1 via (ip of gateway) dev wan1

A: this work for me
ip route add 224.0.0.0/4 dev lo table local

verify with
ip route get 224.0.0.1


text:
Q: What is the common design to return processed value and message to the user? When a method is called and must return a value for further processing, but for instance a message has also to be provided to the UI : what is the best or most common way to deal with those 2 outputs of a single method ?
ex :
public string exportStuffToFile() {
 (...)
 //do some work, that should be notified to the user
 //for instance, number of item processed, etc.
 (...)
 return pathTotheFileCreated;
}

In this simple casse, How to transmit the "log of operations" and the Path ?
Custom return Type ? Caller put himself as Delegate for the message ? Caller access a "Log" property after execution (bad design)

A: Yes, "custom return type", but that is just the first step toward a good design.
In object-orientation the "data" that is returned should be hidden (encapsulated). There should be no "accessors" to get at the various things in the result. Instead, the appropriate business-methods to work with the result need to be created. Display it to the user, continue work with the result, combine with other results, etc.
Functional-programming is essentially the same, but there are more readily available abstractions. We would say that there is a result (the path) and a "context", like a log of things that happened, etc. This is called a functor or a monad. The names are weird, but the concept is just as before to encapsulate the data and provide functions that you can use to work with the result.

A:
How to transmit the "log of operations" and the Path ? Custom return Type ? Caller put himself as Delegate for the message ? Caller access a "Log" property after execution (bad design)

There are many ways to solve your problem.
As you are talking about a "log of operations", I am inclined to use an actual logging mechanism that places the log messages in a location where the UI can access them when needed.
If the information for the UI is instead needed to update a progress indication (like a progress bar, showing also information on the percentage of work completed), then I would either use the logging mechanism or a callback/delegate mechanism for the updates to the UI. The reason for this is that this way the UI can receive live update while the function is still busy. That might not be a requirement today, but it is more likely to become a new requirement than that the caller suddenly needs intermediate updates.
As a final option, I would consider a custom return type with both pieces of information, but that is less suitable if the information is actually meant for different consumers.


text:
Q: ModelChoiceFilter not working using django-filter I am using Django 1.8, I want to list all the merchant using the django_filters, I have two models Shipment and Merchant
class Merchant(models.Model):
        merchant_id = models.CharField(max_length=100,db_index=True,verbose_name='Merchant ID',null=True,blank=True)

class Shipment(models.Model):
          merchant_related = models.ForeignKey(Merchant,on_delete=models.CASCADE,verbose_name="merchant related to shipment")

I have the shipments list page with all the shipments and related merchants, I need to add the merchant filter in shipment_list.html with all merchant created ids as choices.
filter.py

class MerchantFilter(django_filters.FilterSet):
    merchants = django_filters.ModelChoiceFilter(queryset=Merchant.objects.all())
    class Meta:
        model = Merchant
        fields = ['merchants']

views.py
def search_merchant(request):
    merchant_filter = MerchantFilter(request.GET,queryset=Merchant.objects.all())
    context = {

        'filter':merchant_filter

    }

    return render(request,"shipment_list.html",context)

In shipment_list.html:

<div>
      <form method="get">
        {{ filter.form.as_p }}
        <button type="submit">Search</button>
      </form>
    </div>

I am getting the search button.But not getting the merchant created ids as choices.Thanks in Advance ..


text:
Q: sscanf equivalent in shell script I have a file which has some stats and counters stored for some ACL rules. I want to design a shell script to read that file and parse those counters.
I have done the similar thing in c programming language where I have opened and stored the content of the file in some buffer and with sscanf, I have parsed the output of the file
Below is the content of files
vlan_id: 0
HITS    ACL rules:
0   0: allow icmp src 1.1.1.1 dst 1.1.0.0 mask 255.255.0.0,
0   1: deny icmp dst 6.8.9.1,
0   2: deny icmp src 3.2.2.1,
0   3: deny tcp src port 3210,
0   4: deny tcp src 6.0.9.9,
0   5: deny udp src port 432,
0   6: deny udp src 43.43.43.1,
0   7: deny tcp src port 435,
0   8: deny udp dst port 554,
22  9: deny all,
the number of passed packets: 0
the number of dropped packets: 22

In c programming language, I have wrote the below code to parse it
   //Read atmost 127 characters or till it encounter comma(,).
   num = sscanf(line, "%d %d: %127[^,\n]",&hits,&n,&rule[0]);
   if (num ==  3)
   {
       g_list_of_rules[i].hits = hits;
       strncpy_s(g_list_of_rules[i].rule,
                 ACL_MAX_STR_LEN, rule,
                 ACL_MAX_STR_LEN-1);
       i++;

   }

Similar thing I want to accomplish in the shell script.
I mean this sscanf functionality ( sscanf(line, "%d %d: %127[^,\n]",&hits,&n,&rule[0]); ) where I am parsing and storing three values in three different variables. So similar kind of functionality I am looking in shell script or in any other linux utility like sed or grep
For example, for the below rule,
0   0: allow icmp src 1.1.1.1 dst 1.1.0.0 mask 255.255.0.0,
all three values I want in separate variables.
So if I do echo $n1, $n2, $str
then n1 should print 0, n2 should print 0 and n3 should print allow icmp src 1.1.1.1 dst 1.1.0.0 mask 255.255.0.0
if someone has idea or thoughts, please share it.

A: You can try this with awk
awk -F': ' -v OFS="," '{split($1,a," "); split($2,b,","); print a[1],a[2],b[1]}' input_file

This will put in variable a[1] the first zero, in a[2] the second zero and in b[1] the rest of the line (w/o comma)


text:
Q: What would it take to add support for the Contacts API to google-api-ruby-client? I'd like to use the official Ruby client library to access the Contacts API, but that one is not on the list of supported APIs. What would it take to change that? I'm willing to pitch in, but a shove in the right direction would help. Thanks!

A: Isn't this already supported with the Google Data on Rails API? Integrating this in the official Ruby client library shouldn't be that much work.


text:
Q: One search form to 3 Gridview in same page Friends,
I have an INDEX page with 3 GRIDVIEW components (model Keys, model Products, model Indicators). And on that same page I have a search form with a dropdownlist (company).
I need to: When you select for example company 02 the 3 GRIDVIEW are filtered only company records 02.
_search.php
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
?>

<div class="ideas-search">

    <?php $form = ActiveForm::begin([
        'options' => [
                    'class' => 'form-inline',
                    ],
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'pa')->dropdownList([..])?>

...

index.php
<?php echo $this->render('_search', ['model' => $searchBase]); ?>

        <?php Pjax::begin(['id' => '1']) ?>
        <?= GridView::widget([
            'id' => 'grid1',
            'dataProvider' => $dataProviderKey,
            'columns' => [
                ...
            ],
        ]); ?>
        <?php Pjax::end() ?>

        <?php Pjax::begin(['id' => '2']) ?>
        <?= GridView::widget([
            'id' => 'grid2',
            'dataProvider' => $dataProviderProduct,
            'columns' => [
                ...
            ],
        ]); ?>
        <?php Pjax::end() ?>

        <?= GridView::widget([
            'dataProvider' => $dataProviderIndicators,
            'summary' => false,
            'columns' => [
                ...
            ],
        ]); ?>

== UPDATE==
BaseController
public function actionIndex()
{
    $searchBase = new BaseSearch();
    $searchBase->pa = 0;
    $searchBase->data = date("Y-m-d");
    $dataProviderBase = $searchBase->search(Yii::$app->request->queryParams);

    $searchMobilizadores = new MobilizadoresSearch();
    $dataProviderMobilizadores = $searchMobilizadores->search(Yii::$app->request->queryParams);

    $searchIndicadores = new IndicadoresSearch();
    $dataProviderIndicadores = $searchIndicadores->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchBase' => $searchBase,
        'dataProviderBase' => $dataProviderBase,
        'searchMobilizadores' => $searchMobilizadores,
        'dataProviderMobilizadores' => $dataProviderMobilizadores,
        'searchIndicadores' => $searchIndicadores,
        'dataProviderIndicadores' => $dataProviderIndicadores,
    ]);
}

A: dont forget define filterModel in your Gridview Widget
view file
GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,

1st Approach :
You may use a single model that extend from model that joint all 3 table and create a search model for it. If u insist on separating all 3 table in the view, you may just declare different column for each grid.
a tip to achieve this, you may create a view and use gii tool to generate view file.
the tricky part is that 1 model can only hold one table except you joint. But, by joining table, you may get extra rows that are not necessarily needed for lets say your $dataProviderKey grid.
2nd Approach :
manually check for params from Yii::$app->request->get() add filter for each $dataprovider.
controller file
if(isset($id = Yii::$app->request->get('company_id'))) {
    $dataProviderKey->query->andFilterWhere(['company.id' => $id]);
    $dataProviderProduct->query->andFilterWhere(['company.id' => $id]);
    $dataProviderIndicators->query->andFilterWhere(['company.id' => $id]);
}

== UPDATE ==
to answer your update question, you may assign your base search attributes to the respective attributes from others searchModel like this :
public function actionIndex()
{
    $searchBase = new BaseSearch();
    $searchBase->pa = 0;
    $searchBase->data = date("Y-m-d");
    $dataProviderBase = $searchBase->search(Yii::$app->request->queryParams);

    $searchMobilizadores = new MobilizadoresSearch();
    $searchMobilizadores->company = $searchBase->company; -->add this
    $dataProviderMobilizadores = $searchMobilizadores->search(Yii::$app->request->queryParams);

    $searchIndicadores = new IndicadoresSearch();
    $searchIndicadores->company = $searchBase->company; -->add this
    $dataProviderIndicadores = $searchIndicadores->search(Yii::$app->request->queryParams);


text:
Q: How to get the text of a input box which is showing value from backend I am using selenium webdriver. My test case is
Select a address on shipping page which inturn shows the details of the address in different fields below.
Now I want to check whatever the text is coming on those field is correct or not?
Problem is niether it is coming as a text nor a value on that particular field.  So get text or getattribute ("value") is not working.
It is coming from javascript written on it and I am not able to inspect it.
Please help

A: Actually, I figured out. The field was showing values fetched by javascript so I ran the same javascript using javascript executor.
JavascriptExecutor js=(JavascriptExecutor)driver;
String val = (String) js.executeScript("return $(\".id of field.val()");

then used val for my function.


text:
Q: Mysql to PostgreSql Rails 3 heroku app true/false Everything works fine until I push to heroku, I gathered that it has to do with diffirent ways mysql and postgres display the boolean values?
I am using Ruby 1.9.2p318 and Rails 3.2.2 with Mysql 5.2.35 on Max OSX
Here is the query I am trying to run
@special_offers = Wine.find(:all, :include => [:inventories], :conditions => ["inventories.special = ? AND inventories.warehouse_id IN (?)", "true", @wharehouses_array], :order => "inventories.updated_at DESC", :limit => 3)

It seems the problem lies with the inventories.special = ?, "true"
This works fine on mysql but not when I push to heroku, wich is using postgres
I have tried replacing the "true" with 1 and "1" and "t" and t and true but nothing seems to work?

UPDATE:
Heroku log file

2012-04-04T14:06:58+00:00 app[web.1]: [2012-04-04 14:06:58] INFO  WEBrick 1.3.1
2012-04-04T14:06:58+00:00 app[web.1]: [2012-04-04 14:06:58] INFO  WEBrick::HTTPServer#start: pid=1 port=54181
2012-04-04T14:06:58+00:00 app[web.1]: [2012-04-04 14:06:58] INFO  ruby 1.9.2 (2011-07-09) [x86_64-linux]
2012-04-04T14:06:59+00:00 heroku[web.1]: State changed from starting to up
2012-04-04T14:07:01+00:00 app[web.1]: => Booting WEBrick
2012-04-04T14:07:01+00:00 app[web.1]: => Call with -d to detach
2012-04-04T14:07:01+00:00 app[web.1]: => Ctrl-C to shutdown server
2012-04-04T14:07:01+00:00 app[web.1]:
2012-04-04T14:07:01+00:00 app[web.1]: => Rails 3.2.2 application starting in production on http://0.0.0.0:54181
2012-04-04T14:07:01+00:00 app[web.1]:
2012-04-04T14:07:01+00:00 app[web.1]: Started GET "/" for 41.119.121.138 at 2012-04-04 14:07:01 +0000
2012-04-04T14:07:02+00:00 app[web.1]: Processing by HomeController#index as HTML
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered partials/_display_wines.html.erb (169.1ms)
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered partials/_display_wines.html.erb (0.0ms)
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered partials/_display_wines.html.erb (8.1ms)
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered home/index.html.erb within layouts/application (259.9ms)
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered partials/_header_bar.html.erb (6.5ms)
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered partials/_main_links.html.erb (0.3ms)
2012-04-04T14:07:03+00:00 app[web.1]:   Rendered partials/_footer.html.erb (4.9ms)
2012-04-04T14:07:03+00:00 app[web.1]: Completed 200 OK in 1081ms (Views: 345.8ms | ActiveRecord: 175.7ms | Solr: 0.0ms)
2012-04-04T14:07:03+00:00 app[web.1]: cache: [GET /] miss
2012-04-04T14:07:03+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/ dyno=web.1 queue=0 wait=0ms service=1350ms status=200 bytes=36808
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/javascripts/jquery.js dyno=web.1 queue=0 wait=0ms service=137ms status=304 bytes=0
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/stylesheets/style1.css dyno=web.1 queue=0 wait=0ms service=179ms status=304 bytes=0
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /stylesheets/style1.css] miss
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /javascripts/jquery.js] miss

+00:00 app[web.1]: cache: [GET /javascripts/script1.js] miss
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/javascripts/script1.js dyno=web.1 queue=0 wait=0ms service=187ms status=304 bytes=0
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/javascripts/PIE.js dyno=web.1 queue=0 wait=0ms service=185ms status=304 bytes=0
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/javascripts/rails.js dyno=web.1 queue=0 wait=0ms service=189ms status=304 bytes=0
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /javascripts/PIE.js] miss
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /javascripts/rails.js] miss
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /images/header_tile.png] miss
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/header_tile.png dyno=web.1 queue=0 wait=0ms service=16ms status=304 bytes=0
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /images/none.png] miss
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/none.png dyno=web.1 queue=0 wait=0ms service=35ms status=304 bytes=0
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /images/cybercellar_logo.jpg] miss
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /images/flags.png] miss
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/flags.png dyno=web.1 queue=0 wait=0ms service=96ms status=304 bytes=0
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/cybercellar_logo.jpg dyno=web.1 queue=0 wait=0ms service=84ms status=304 bytes=0
2012-04-04T14:07:04+00:00 app[web.1]: cache: [GET /images/header_login.png] miss
2012-04-04T14:07:04+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/header_login.png dyno=web.1 queue=0 wait=0ms service=44ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/no_wine.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/no_wine.png dyno=web.1 queue=0 wait=0ms service=22ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/buttons2.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/buttons2.png dyno=web.1 queue=0 wait=0ms service=19ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/find_wine_wrap.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/find_wine_wrap.png dyno=web.1 queue=0 wait=0ms service=22ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/comment.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/comment.png dyno=web.1 queue=0 wait=0ms service=5ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/bullet.png] miss

4:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/bullet.png dyno=web.1 queue=0 wait=0ms service=13ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/buttons.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/buttons.png dyno=web.1 queue=0 wait=0ms service=12ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/links_bar.png] miss
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/hr_light.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/hr_light.png dyno=web.1 queue=0 wait=0ms service=12ms status=304 bytes=0
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/links_bar.png dyno=web.1 queue=0 wait=0ms service=17ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/cart_background.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/cart_background.png dyno=web.1 queue=0 wait=0ms service=4ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/home_page_image.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/home_page_image.png dyno=web.1 queue=0 wait=0ms service=6ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/find_wine.png] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/find_wine.png dyno=web.1 queue=0 wait=0ms service=10ms status=304 bytes=0
2012-04-04T14:07:05+00:00 app[web.1]: cache: [GET /images/footer_tile.jpg] miss
2012-04-04T14:07:05+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/footer_tile.jpg dyno=web.1 queue=0 wait=0ms service=7ms status=304 bytes=0
2012-04-04T14:07:06+00:00 app[web.1]: cache: [GET /images/social.png] miss
2012-04-04T14:07:06+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/hr_dark.jpg dyno=web.1 queue=0 wait=0ms service=5ms status=304 bytes=0
2012-04-04T14:07:06+00:00 app[web.1]: cache: [GET /images/hr_dark.jpg] miss
2012-04-04T14:07:06+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/social.png dyno=web.1 queue=0 wait=0ms service=6ms status=304 bytes=0
2012-04-04T14:07:06+00:00 app[web.1]: cache: [GET /images/credit_cards.png] miss
2012-04-04T14:07:06+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/credit_cards.png dyno=web.1 queue=0 wait=0ms service=14ms status=304 bytes=0
2012-04-04T14:07:06+00:00 app[web.1]: cache: [GET /images/money_back.png] miss
2012-04-04T14:07:06+00:00 heroku[router]: GET stormy-fog-6888.herokuapp.com/images/money_back.png dyno=web.1 queue=0 wait=0ms service=5ms status=304 bytes=0

Schema file: for the inventories table
create_table "inventories", :force => true do |t|
    t.integer   "wine_id"
    t.integer   "warehouse_id"
    t.integer   "stock"
    t.float     "price"
    t.integer   "quantity_id"
    t.timestamp "created_at"
    t.timestamp "updated_at"
    t.boolean   "available",                        :default => false
    t.boolean   "discount",                         :default => false
    t.string    "markupprofile_id",   :limit => 45
    t.string    "discountprofile_id", :limit => 45
    t.float     "discount_price"
    t.boolean   "special",                          :default => false
  end

A: Use the actual TrueClass, not a string, and Rails will translate it into the correct query for you.
Correct:
"inventories.special = ?", true

Incorrect:
"inventories.special = ?", "true"

It's not throwing an error because the second one still produces a valid query, it's just looking for records where special is a string with the actual t-r-u-e characters in it.


text:
Q: App for launching activity
Possible Duplicate:
App just for launching an activity

I'm trying to add a shortcut to launch Sound Recorder on App Drawer (not home screen)
So the app should be empty and the only work it has to do is launch Sound Recorder
com.android.soundrecorder/com.android.soundrecorder.SoundRecorder
How can I do that?
I get Force Stop with this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="recorder.audio.dsaif"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Recorder"
            android:label="@string/title_activity_recorder" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

and the java file
package recorder.audio.dsaif;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;

public class Recorder extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.android.soundrecorder.SoundRecorder");
    startActivity(LaunchIntent);
    setContentView(R.layout.activity_recorder);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_recorder, menu);
    return true;

}
}


text:
Q: Is storing just username in a cookie bad practice In the App we are passing UserName value to a Internal API.
Before making a Ajax call to API, I am calling a function named GetUserName() like below. This function basically stores username in a cookie. I don't want to always make Ajax calls to server to get the UserName.
Code:
function GetUserName()
{

//TODO

1. If UserName Cookie exist, return it.
2. If UserName Cookie doesn't exist, then make Ajax call to server to Get
   UserName and set the Cookie.

}

As said here storing username and password in client side is bad practice.
But would like to know is it bad practice to store just username in a cookie for this scenario ? Or should I encrypt the UserName ?
Any help would be great.

A: Well the user can (and will) edit the cookie and use another user's username eventually.
If that GetUserName function is purely cosmetic go ahead, but if you use it for something session-related you are asking for trouble
See OWASP section of session IDs and security on cookies if you plan to do that.


text:
Q: How to achieve direct-server-return with HAProxy and app server? What would be an example method of achieving DSR with HAProxy and an app server like node.js? I've read a few articles on the subject however I don't quite understand how the node server can respond to the request directly when the client connected to the load balancer first.
...unless there's some lower level, virtual interface proxying going on.

A: DSR can't be done through HAProxy, since HAProxy is a reverse proxy.
HAProxy acknowledges the client TCP connection then it creates a new TCP connection to the server on which it forwards the request.
The sever can't answer to the client directly, since it is not aware of the client TCP connection.
If you want to achieve DSR mode, you must use LVS, which has a module for this purpose.
Baptiste

A: I have reason to believe this is possible as the ALOHA appliance from HAProxy Technologies (that runs HAProxy internally) does officially support DSR mode.  However, I still have not figured it out how they do this.
They even have a technical application note about how to set up your backend servers to work with this mode.
See: http://www.haproxy.com/static/media/uploads/eng/resources/aloha_load_balancer_appnotes_0053_server_configuration_for_layer4_dsr_mode_en.pdf
Unfortunately, this document doesn't say anything about how the HAProxy itself is configured.  Still digging!

A: As explained by Baptiste above haproxy cannot do DSR as its reverse proxy in case of aloha you can disable the reverse proxy mode which in this case uses the LVS feature of linux to work as l4 loadbalancer which can be used for DSR.


text:
Q: Excel - Conditional Formatting of Area Codes from Named Range I have a list of phone numbers and a named range "NE" of area codes and I want to highlight the phone numbers that begin with the area codes. I can't for the life of me figure out what that formula should look like.
The area codes are in Z2:Z72. The nine or 10 digit phone numbers are in cells C51:C1587.

A: =SUMPRODUCT(COUNTIF(A1,NE&"*"))

where A1 is the cell you want formatted.

A: You can use a conditional formatting and use a formula as below:
=countif($A:$A,left($B1,3))=1

In my example, all of the Area Codes are strings of 3 digits and are in the Column "A:A" and your cell is in B1. You can adapt it depending on your Digit Codes
You can also use Rory's answer in a conditional formatting and it should work just fine.
Note: as mentioned in one of the comments, this would only work if the numbers are entered as text in both the Area Codes Range and in the phone number Range

A: Select C51:C1587 then create a conditional formatting rule based on the following formula.
=countifs(NE, left($C51, 3), NE, "<>")


text:
Q: Function definition format Please consider as example a simple function that calculate the average between two numbers. It can be defined in both those ways:
let average = fun x y -> (x + y)/2

let average2 x y = (x + y)/2

Is there any kind of implication in those formats? Is it just a matter of style?


text:
Q: how to call javascript function from SmartGWT function hi all i am trying to call a native Js function called test i wrote in the HTML file in the smartGWT project but it sayes test is not a function
the native java script code in the smartGWT class :
public static native void  callTest()/*-{
        window.test();

}-*/;

the java script function in the HTMLfile  :
 <script  type="text/javascript">
    function test(){
        window.alert("test");
    }
    </script>

and i also added :
<script src="org.example.yourcode.Spiffy.nocache.js"></script>

but as i mantaind it sayes test is not a function
so dos any one have any idea or any one can provide any help please ?
thanx
and when i add $window.test() instead window.test() i get the following message ?

and when i use $wnd.test();
i had the following error :

A: just try adding '$' in front of window.test(). i.e. $window.test() and see.

A: Try using $wnd instead of window.

A: GWT JavaScript is loaded in an iframe in the host page, so "window" and "document" in your JavaScript will refer to the iframe. GWT aliases the host page "window" and "document" via $wnd and $doc.
Please read all of this section: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html


text:
Q: Joining fields in Processing Modeler of QGIS I am trying to join field district layer with output A .
How can I do this?
I added Vector field input but i cannot see the output A field to make the join by fields .
I have attached an image to illustrate this case.


text:
Q: How to write the underscore dash in LaTeX I would like to write the following attached letter

I have tried $Hu_(x,\theta)$  but it is not printing what I want. Thank you

A: Try this:
\documentclass{article}
\begin{document}
\noindent
The underscore character shape is set by the font designer: $Hu\_(x,\theta)$

\medskip\noindent
But you can draw your own rules: $Hu \hbox to 3em{\thinspace\hrulefill\thinspace}(x,\theta)$

\medskip\noindent
Possibly you want it like this: $\hbox to 4em{Hu\thinspace\hrulefill\thinspace}(x,\theta)$
\end{document}

Notes

*

*My apologies for using plain TeX \hbox -- you can do the same with LaTeX \makebox but I can never remember the syntax.


text:
Q: 2007 Infopath URLs embedded in Word document We will be using Word documents to point to our 2007 InfoPath Forms Library.  This forms library is using InfoPath as the client application >> Advanced Settings >> "Opening browser-enabled documents" is set to "Open in the client Application"
The right+click "copy shortcut" InfoPath form url has the .xml extension on the end of the URL when pasted into Word like:
http://myServerFullURL%20InfoPathEntry_Upload2015-05-18.xml
If someone clicks the URL from within Word, the .xml is just displayed in the browser...not with the formatting of the xsn file.
Is there a way to append the .xsn onto the URL to force the InfoPath form to use the template to users are just looking @ XML in a browser?
Our form template is located @:
http://myServerFullURL/Forms/template.xsn
Thank you!

A: When I do this same test and I put my form URL .xml as a link into a word doc, then CTRL + Click to open it I get an "Open, Save or Save as" box, if I choose "Open" it opens in the InfoPath filler client.
I know the file associations can mess with this as some people have another application as their default XML editor and it opens there.
Perhaps you can change the IE behavior this way?
To turn off RSS feed reading. In Internet Explorer 7 or greater, go to Tools–>Internet Options–>Content tab–>Feeds and Web Slices-settings Uncheck the box "Turn on Feed Reading View" then click OK.


text:
Q: Postgresql: Select value difference between values in Integer column My question is simple. Say I have the following column:
order_in_group
integer
------
1
2
3
5
6
9

I would like the query result to be the difference between the current and next values which is bigger then 1:
value1   value2   difference
integer  integer  integer
-------  -------  -------
3        5        2
6        9        3

Any help will be great.

A: Try this:
with q(i) as (
    select unnest(array[1,2,3,5,6,9])
    )
select prev, curr, curr- prev diff
from (
    select i curr, lag(i) over (order by i) prev
    from q
    ) s
where curr > prev+ 1;

 prev | curr | diff
------+------+------
    3 |    5 |    2
    6 |    9 |    3
(2 rows)

A: You should be able to just use LAG to get the previous row to compare with;
WITH cte AS (
  SELECT order_in_group value2,
     LAG(order_in_group) OVER (ORDER BY order_in_group) value1
  FROM mytable
)
SELECT value1, value2, value2-value1 difference
FROM cte
WHERE value2-value1 > 1;


text:
Q: R: training random forest using PCA data I have a data set called Data, with 30 scaled and centered features and 1 outcome with column name OUTCOME, referred to 700k records, stored in data.table format. I computed its PCA, and observed that its first 8 components account for the 95% of the variance. I want to train a random forest in h2o, so this is what I do:
Data.pca=prcomp(Data,retx=TRUE) # compute the PCA of Data
Data.rotated=as.data.table(Data.pca$x)[,c(1:8)] # keep only first 8 components
Data.dump=cbind(Data.rotated,subset(Data,select=c(OUTCOME))) # PCA dataset plus outcomes for training

This way I have a dataset Data.dump where I have 8 features that are rotated on the PCA components, and at each record I associated its outcome.
First question: is this rational? or do I have to permute somehow the outcomes vector? or the two things are unrelated?
Then I split Data.dump in two sets, Data.train for training and Data.test for testing, all as.h2o. The I feed them to a random forest:
rf=h2o.randomForest(training_frame=Data.train,x=1:8,y=9,stopping_rounds=2,
                    ntrees=200,score_each_iteration=T,seed=1000000)
rf.pred=as.data.table(h2o.predict(rf,Data.test))

What happens is that rf.pred seems not so similar to the original outcomes Data.test$OUTCOME. I tried to train a neural network as well, and did not even converge, crashing R.
Second question: is it because I am carrying on some mistake from the PCA treatment? or because I badly set up the random forest? Or I am just dealing with annoying data?
I do not know where to start, as I am new to data science, but the workflow seems correct to me.
Thanks a lot in advance.

A: The answer to your second question (i.e. "is it the data, or did I do something wrong") is hard to know. This is why you should always try to make a baseline model first, so you have an idea of how learnable the data is.
The baseline could be h2o.glm(), and/or it could be h2o.randomForest(), but either way without the PCA step. (You didn't say if you are doing a regression or a classification, i.e. if OUTCOME is a number or a factor, but both glm and random forest will work either way.)
Going to your first question: yes, it is a reasonable thing to do, and no you don't have to (in fact, should not) involve the outcomes vector.
Another way to answer your first question is: no, it unreasonable. It may be that a random forest can see all the relations itself without needing you to use a PCA. Remember when you use a PCA to reduce the number of input dimensions you are also throwing away a bit of signal, too. You said that the 8 components only capture 95% of the variance. So you are throwing away some signal in return for having fewer inputs, which means you are optimizing for complexity at the expense of prediction quality.
By the way, concatenating the original inputs and your 8 PCA components, is another approach: you might get a better model by giving it this hint about the data. (But you might not, which is why getting some baseline models first is essential, before trying these more exotic ideas.)


text:
Q: how to show contact details after a contact search in kotlin I have working Kotlin code that displays a subset of contacts from a search criteria. Now I want to let the users press a specific contact in that result to display that contact's details.
There are several examples on how to display the contact details in stackoverflow. For example: Pick contact directly from contact picker intent. But it's unclear where to insert this additional feature into the code.
I tried adding in the OnCreate section
    i = Intent(Intent.ACTION_PICK)
     i.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
            startActivityForResult(i, SELECT_PHONE_NUMBER)

and later on in the code
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
                super.onActivityResult(requestCode, resultCode, data)
                if (requestCode == SELECT_PHONE_NUMBER && resultCode == Activity.RESULT_OK) {
                    val contactUri = data?.data ?: return
                    val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Phone.NUMBER)
                    val cursor = requireContext().contentResolver.query(contactUri, projection,
                        null, null, null)

                    if (cursor != null && cursor.moveToFirst()) {
                        val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                        val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                        val name = cursor.getString(nameIndex)
                        val number = cursor.getString(numberIndex)

                        // do something with name and phone
                    }
                    cursor?.close()
                }
            }

But I got an error message ConnectActivity.kt: No value passed for parameter 'p0' for the line in the code that says val cursor = requirecontext().contentResolver.query.....specifically in the() area. If you can show how to fix this or provide a different solution, it would be greatly appreaciated.
The working code without the changes discussed above is here:
    package com.example.myapplication

    import android.Manifest
    import android.app.Activity
    import android.content.Intent
    import android.content.pm.PackageManager
    import android.os.Bundle
    import android.provider.ContactsContract
    import android.widget.ListView
    import androidx.appcompat.widget.SearchView

    import android.widget.SimpleCursorAdapter
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContentProviderCompat.requireContext
    import java.io.IOException

    class ConnectActivity : AppCompatActivity() {
        private lateinit var searchView: SearchView

        private lateinit var listView: ListView
        var cols = listOf<String> (
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone._ID
                ).toTypedArray()

            try {
                //Toast.makeText(getApplicationContext(), "got here", Toast.LENGTH_SHORT).show();
                searchView = findViewById(R.id.searchView)
                listView = findViewById(R.id.listView)
                if (ActivityCompat.checkSelfPermission( this@ConnectActivity, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this@ConnectActivity, Array(1){Manifest.permission.READ_CONTACTS}, 111)
                }
                else {
                    readContact()
                }

            } catch (e: Exception) {
                Toast.makeText(getApplicationContext(), e.message, Toast.LENGTH_LONG).show()
            }

        }
        override fun onRequestPermissionsResult(requestCode: Int,permissions: Array<out String>,grantResults: IntArray){
            super.onRequestPermissionsResult(requestCode,permissions,grantResults)
            Toast.makeText(getApplicationContext(), "then here", Toast.LENGTH_SHORT).show()
            if (requestCode==111 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
               readContact()
        }

        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            if (requestCode == SELECT_PHONE_NUMBER && resultCode == Activity.RESULT_OK) {
                val contactUri = data?.data ?: return
                val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER)
                val cursor = requireContext().contentResolver.query(contactUri, projection,
                    null, null, null)

                if (cursor != null && cursor.moveToFirst()) {
                    val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                    val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                    val name = cursor.getString(nameIndex)
                    val number = cursor.getString(numberIndex)

                    // do something with name and phone
                }
                cursor?.close()
            }
        }
        private fun readContact() {

            var from = listOf<String>(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER).toTypedArray()

            var to = intArrayOf(android.R.id.text1,android.R.id.text2)

            var rs = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                           cols,null,null,
                                           ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
            var adapter = SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,
                                           rs,from,to,0)
            listView.adapter =adapter

            searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
                override fun onQueryTextSubmit(p0: String?):Boolean {
                    return false
                }
                override fun onQueryTextChange(p0:String?):Boolean{
                     rs = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        cols,"${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ?",
                        Array(1){"%$p0%"},
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                     adapter.changeCursor(rs)
                    return false
                }
            })

        }
        companion object {

            private const val SELECT_PHONE_NUMBER = 111

        }

    }

xml file is
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <androidx.appcompat.widget.SearchView
            android:id="@+id/searchView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="20dp"
            android:queryHint="hi"
            />
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="20dp"
            android:layout_below="@+id/searchView"
        />
    </RelativeLayout>


text:
Q: unsigned long long type printing in hexadecimal format I am trying to print out an unsigned long long like this:
  printf("Hex add is: 0x%ux ", hexAdd);

but I am getting type conversion errors since I have an unsigned long long.

A: You can use the same ll size modifier for %x, thus:
#include <stdio.h>

int main() {
    unsigned long long x = 123456789012345ULL;
    printf("%llx\n", x);
    return 0;
}

The full range of conversion and formatting specifiers is in a great table here:

*

*printf documentation on cppeference.com

A: try %llu - this will be long long unsigned in decimal form
%llx prints long long unsigned in hex

A: printf("Hex add is: %llu", hexAdd);

A: I had a similar issue with this using the MinGW libraries. I couldn't get it to recognize the %llu or %llx stuff.
Here is my answer...
void PutValue64(uint64_t value) {
char    a_string[25];   // 16 for the hex data, 2 for the 0x, 1 for the term, and some spare
uint32  MSB_part;
uint32  LSB_part;

    MSB_part = value >> 32;
    LSB_part= value & 0x00000000FFFFFFFF;

    printf(a_string, "0x%04x%08x", MSB_part, LSB_part);
}

Note, I think the %04x can simply be %x, but the %08x is required.
Good luck.
Mark


text:
Q: Python: How to access returned values to put into a table? Note: I am a very beginner in Python so please bear with me!
edit: I have fixed the error but I need help with my question down below!
My question is:
1) If I want to put the minimum value(s) and most common word/number onto a table, how can I index to the minimum value/most common word and extract it and place it in the correct position on my table?
Description
The following code is supposed to transpose the given nested list, A, using the function
def rows2cols(A):,
then run through that list and for every column I check to see if it has numeric values or not using
def isnumericlist(A):.
If the list does have numeric values, I convert the strings to floats and find the minimum value and most common word/number from that list.
The code is the following:
A = [['OrderDate', 'Region', 'Rep', 'Item', 'Units', 'Unit Price'],['4-Jul-2014', 'East', 'Richard', 'Pen Set', '62', '4.99'], ['12-Jul-2014', 'East', 'Nick', 'Binder', '29', '1.99'], ['21-Jul-2014', 'Central', 'Morgan', 'Pen Set', '55', '12.49'], ['29-Jul-2014', 'East', 'Susan', 'Binder', '81', '19.99'],['7-Aug-2014', 'Central', 'Matthew', 'Pen Set', '42', '23.95'], ['15-Aug-2014', 'East', 'Richard', 'Pencil', '35', '4.99'], ['24-Aug-2014', 'West', 'James', 'Desk', '3', '275']]

minVal = []
maxVal = []
hist = []
average = []
stanDev = []
headers = A[0] #this sets the variable "headers" as the first row
rows = A[1:] #skips the first row

def rows2cols(A):
    if len(A) == 0:
        return []                      #this covers the base case of having an empty csv file
    res  = [[] for x in headers]       # would create a list of empty lists
    for line in A:
        for col in range(len(line)):
            res[col].append(line[col])
    return res

def convertstringtofloats(A):
    res = []
    for x in A:
        res.append(float(x))
    return res

def isnumericlist(A):
    for x in A:
        try:
            numeric = float(x)
        except:
            return False
    return True

def getMin(A):
    res = B[0] #first column AFTER you transpose the nested list
    for x in A:
        if x < res:
            res = x
    return res

def most_common(A):
    counts = {}
    for x in A:
        counts[tuple(x)] = counts.get(tuple(x), 0) + 1
    max = -1
    maxKey = ""
    for key,value in counts.items():
        if max < value:
            max = value
            maxKey = key
    return maxKey

def notnumeric(A):
    return "n/a"

cols = rows2cols(rows)

for col in range(len(headers)):
    if isnumericlist(cols[col]):
        B = convertstringtofloats(cols[col])
        minVal.append(getMin(B))
        maxVal.append(getMax(B))
        average.append(getAvg(B))
        stanDev.append(getSD(B))
    else:
        notnumeric(col)

    mode.append(most_common(cols[col]))

tablevalues = [minVal, maxVal, average, stanDev, mode]

My code for producing a table is below, along with a sample table as to how I would like the outcome to be!
def print_table(table):
    longest_cols = [
        (max([len(str(row[i])) for row in table]) + 0) for i in range(len(table[0]))
    ]
    row_format = "|".join([" {:>" + str(longest_col) + "} " for longest_col in longest_cols])
    first = True
    for row in table:
        print(row_format.format(*row))
        if first:
            print((sum(longest_cols) + (len(table[0]) - 0) * 3) * "-")
            first = False

table = [
    ["Columns:", "Min", "Max", "Avg", "Std. Dev.", "Most Common Word"],
    ["OrderDate", "n/a", "n/a", "n/a", "n/a", "John"],
    ["Region", 3.3, 6.29, 4.888, 1.333, 4.911],
    ["Rep", 1.3, 3.2, 1.888, 0.333, 1.9],
    ["Item", 1.3, 3.2, 1.888, 0.333, 1.9],
    ["Units","n/a", "n/a", "n/a", "n/a", "John"],
    ["Unit Price","n/a", "n/a", "n/a", "n/a", "John"]
]
print_table(table)

A: Probably Pandas might be of help to you. df.describe(include='all') will rovide you with the table you need. you just need to read your data A using pandas and change data types in each column according to your need. top is the most common word in the respective column and freq is times of occurrence of this particular word. you even can save this table as a new dataframe as df2 = df.describe(include='all')
import pandas as pd
A = [['OrderDate', 'Region', 'Rep', 'Item', 'Units', 'Unit Price'],
     ['4-Jul-2014', 'East', 'Richard', 'Pen Set', '62', '4.99'],
     ['12-Jul-2014', 'East', 'Nick', 'Binder', '29', '1.99'],
     ['21-Jul-2014', 'Central', 'Morgan', 'Pen Set', '55', '12.49'],
     ['29-Jul-2014', 'East', 'Susan', 'Binder', '81', '19.99'],
     ['7-Aug-2014', 'Central', 'Matthew', 'Pen Set', '42', '23.95'],
     ['15-Aug-2014', 'East', 'Richard', 'Pencil', '35', '4.99'],
     ['24-Aug-2014', 'West', 'James', 'Desk', '3', '275']]

df = pd.DataFrame(A[1:],columns=A[0])

print(df)

OrderDate   Region  Rep Item    Units   Unit Price
0   04-Jul-2014 East    Richard Pen Set 62  4.99
1   12-Jul-2014 East    Nick    Binder  29  1.99
2   21-Jul-2014 Central Morgan  Pen Set 55  12.49
3   29-Jul-2014 East    Susan   Binder  81  19.99
4   07-Aug-2014 Central Matthew Pen Set 42  23.95
5   15-Aug-2014 East    Richard Pencil  35  4.99
6   24-Aug-2014 West    James   Desk    3   275.00

df = df.astype(dtype={'OrderDate':'str', 'Region':'str',
     'Rep':'str', 'Item':'str', 'Units':'int', 'Unit Price':'float'})

df['OrderDate'] = df.OrderDate.apply(
    lambda x: pd.to_datetime(x).strftime('%d-%b-%Y'))

print(df.dtypes)
OrderDate      object
Region         object
Rep            object
Item           object
Units           int32
Unit Price    float64
dtype: object

print(df.describe(include='all'))

OrderDate   Region  Rep Item    Units   Unit Price
count   7   7   7   7   7.000000    7.000000
unique  7   3   6   4   NaN NaN
top     24-Aug-2014 East    Richard Pen Set NaN NaN
freq    1   4   2   3   NaN         NaN
mean    NaN NaN NaN NaN 43.857143   49.057143
std     NaN NaN NaN NaN 25.182193   99.968112
min     NaN NaN NaN NaN 3.000000    1.990000
25%     NaN NaN NaN NaN 32.000000   4.990000
50%     NaN NaN NaN NaN 42.000000   12.490000
75%     NaN NaN NaN NaN 58.500000   21.970000
max     NaN NaN NaN NaN 81.000000   275.000000


text:
Q: Flutter BloC state executed but the UI didn't change after the state changed I am using the Bloc and Getx for state management and routing. I have solved the problem of the Bloc is nested with different child with the route which causing the Bloc cannot be found/read if I change the route. Which the solution is wrap the GetMaterialApp inside the BlocProvider.
import ;...

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    BlocProvider<AuthBloc>(
      create: (context) => AuthBloc(FirebaseAuthProvider()),
      child: GetMaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
        theme: theme(),
        home: const MainPage(),
        /*BlocProvider<AuthBloc>(
          create: (context) => AuthBloc(FirebaseAuthProvider()),
          child: const MainPage(),
        ),*/
        getPages: RoutesClass.routes,
        // routes: {
        // verifyEmailRoute: (context) => const VerifyEmailView(), // not used
        // },
        // routes: routes, // switch to getx
      ),
    ),
  );
}

But now the Bloc is running well. I use the Bloc for FirebaseAuth. I can do login and logout (the state is correct in logic. I'm sure because it was functioned properly if I didn't click the navigation bar to change route.) if I didn't change the page/view with the bottom navigation bar.
If I change the page/view with the bottom navigation bar and click logout, the Bloc state executed but the UI cannot be changed to logout state. The bottom navigation bar is custom and the routing of changing page is using the Getx to perform routing. using the Get.toNamed() function.
Sorry for my bad explanation. Below is my code for your reference:
import 'package:facerecognitionattendance/services/auth/bloc/auth_bloc.dart';
import 'package:facerecognitionattendance/services/auth/bloc/auth_event.dart';
import 'package:facerecognitionattendance/utilities/dialogs/logout_dialog.dart';
import 'package:facerecognitionattendance/views/profile/components/profile_menu.dart';
import 'package:facerecognitionattendance/views/profile/components/profile_pic.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart' show ReadContext;

class Body extends StatefulWidget {
  const Body({super.key});

  @override
  State<Body> createState() => _BodyState();
}

class _BodyState extends State<Body> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Column(
          children: [
            const ProfilePic(),
            const SizedBox(height: 20),
            ProfileMenu(
              text: "My Account",
              icon: "assets/icons/User Icon.svg",
              press: () => {},
            ),
            ProfileMenu(
              text: "Notifications",
              icon: "assets/icons/notification.svg",
              press: () {},
            ),
            ProfileMenu(
              text: "Settings",
              icon: "assets/icons/Settings.svg",
              press: () {},
            ),
            ProfileMenu(
              text: "Log Out",
              icon: "assets/icons/Log out.svg",
              press: () async {
                final shouldLogout = await showLogOutDialog(context);
                if (shouldLogout) {
                  if (!mounted) return;
                  context.read<AuthBloc>().add(
                        const AuthEventLogOut(),
                      ); // HERE
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

Hope these will help for the explanation. Thanks in advance.
I tried to add the BlocProvider but does not work. Expecting the logout state executed and change the UI back to the sign in form.

A: First of all, your Body widget should be a StatelessWidget in this example if you don't make use of the state, also Bloc handles that for you.
To solve the redirect you should wrap your code in a BlocListener to listen for changes in the state of AuthBloc. Here's an example:
return BlocListener<AuthBloc, AuthState>(
    listener: (BuildContext context, state) {
        // Check here if the state is unathenticated
        if (state is Unauthenticated) {
          Get.toNamed(); // Your login or initial page
        }
    },
    child: SafeArea(
      child: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Column(
          children: [
            // Your code here...
          ],
        ),
      ),
    ),
  );

Also in BlocListener you can just listen to some changes in the state, like for example the authStatus, you can use the property listenWhen for that.
Hope this helps!


text:
Q: Make it out (meaning in a sentence) I saw this sentence and I don't understand the use of "make it out" here:
- Felicia, I was wondering if you'd make it out to Hawthorne.
Is there someone who can explain that to me? And give me some examples?

A: I believe in this context, the speaker is talking about Felicia traveling to Hawthorne (correct me if I'm wrong). So then you can break "make it out to Hawthorne" into:

*

*"make it" meaning "manage to reach" somewhere or something (as in, "we made it!")

*"out to Hawthorne" meaning to the place called Hawthorne, implying that it's pretty out of the way.

If Hawthorne is actually a person, then @Chemomechanics's answer is correct.

A: To make out a document (e.g., a bank check or a note or card) is to designate it to someone (specifically, the recipient) or something. For example, on this past Valentine's Day, my spouse made out two cards: one to me and one to my parents. When I need money, I sometimes go to my bank and make out a check to "cash."


text:
Q: What exactly does nfs4_disable_idmapping parameter do? I've been experimenting with user/group ID mapping (translation) in NFSv4. What I want to achieve is name based ID translation, that is independent of the actual UID/GID on the server and clients.
Many guides and articles mention that to have ID mapping working you have to set nfs4_disable_idmapping parameter to 0 (aka N) in the nfs module on client, and nfsd module on the server. However, I didn't find any information or documentation about what exactly this parameter does.
As an experiment, I configured NFSv4 server and client (with sec=krb5) and I deliberately left these parameters at their default value (mapping disabled).
I can verify that the mapping is disabled on server:
$ cat /sys/module/nfsd/parameters/nfs4_disable_idmapping
Y

and on the client:
$ cat /sys/module/nfs/parameters/nfs4_disable_idmapping
Y

I created users bob(uid=1002) and sam(uid=1001) on the server, and users bob(uid=1003) and sam(uid=1004) on the client. As you can see, the UIDs do not match, however, the users are still mapped correctly. File created by the bob user on the is seen as owned by bob on the server, and vice versa.
Moreover, if I look at the logs on the client:
nfsidmap[1874]: key: 0x322c739a type: uid value: bob@home.lan timeout 600
nfsidmap[1874]: nfs4_name_to_uid: calling nsswitch->name_to_uid
nfsidmap[1874]: nss_getpwnam: name 'bob@home.lan' domain 'home.lan': resulting localname 'bob'
nfsidmap[1874]: nfs4_name_to_uid: nsswitch->name_to_uid returned 0
nfsidmap[1874]: nfs4_name_to_uid: final return value is 0

and on the server:
rpc.idmapd[1717]: nfsdcb: authbuf=gss/krb5p authtype=user
rpc.idmapd[1717]: nfs4_uid_to_name: calling nsswitch->uid_to_name
rpc.idmapd[1717]: nfs4_uid_to_name: nsswitch->uid_to_name returned 0
rpc.idmapd[1717]: nfs4_uid_to_name: final return value is 0
rpc.idmapd[1717]: Server : (user) id "1002" -> name "bob@home.lan"

they both suggest that ID mapping is indeed working "by name" rather then "by id".
So my question is: what is nfs4_disable_idmapping parameter for then, if it seems not to have any observable effect on the ID mapping?

A: You hit a bad test case. According to kernel documentation nfs4_disable_idmapping option makes sense only when sec=sys is used.


text:
Q: Crop Automatically does not work in portrait I have a problem during the crop. It works well when taken in landscape but it does not crop when I take it in portrait. I want the user to take only in portrait as well. Is there anything wrong in my code that makes in not work in portrait or should I add a code?  The first code is for the camera to start and the second imagepickercontroller is for the cropping.
-(IBAction)cameraButtonPressed:(id)sender
{

    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        pickerController.delegate = self;
        [self presentViewController:pickerController
                           animated:YES
                         completion:nil];
    }

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    {
        UIImage *imageTaked = info[UIImagePickerControllerOriginalImage];
        //You can take the metadata here => info [UIImagePickerControllerMediaMetadata];

        UIImage* imageCropped;

        CGFloat side = MIN(imageTaked.size.width, imageTaked.size.height);
        CGFloat x = imageTaked.size.width / 320 - side / 320;
        CGFloat y = imageTaked.size.height / 320 - side / 320;

        CGRect cropRect = CGRectMake(x,y,side,side);
        CGImageRef imageRef = CGImageCreateWithImageInRect([imageTaked CGImage], cropRect);
        imageCropped = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
    }
}