text:
Q: How to set image button backgroundimage for different state? I want imagebutton with two states i) normal ii) touch(or click).
I have set normal image in the imagebutton background and I am trying to change image(pressed) from onclick method, but it doesn't change.
I want that if I pressed image button then image should change from normal to pressed until I press other button but it doesn't happen.
Can anyone suggest to me how can I do this with selector or at run time?
Here is my imagebuttonpanel code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="horizontal"
  android:gravity="bottom"
  android:id="@+id/buttonpanel">
  <ImageButton android:id="@+id/buttonhome"
               android:layout_width="80dp"
               android:layout_height="36dp"
               android:focusable="true"
               android:background="@drawable/homeselector">
               </ImageButton>
  <ImageButton android:id="@+id/buttonsearch"
               android:layout_height="36dp"
               android:layout_width="80dp"
               android:background="@drawable/searchselector"
               android:focusable="true">
               </ImageButton>>
  <ImageButton android:id="@+id/buttonreg"
               android:layout_height="36dp"
               android:layout_width="80dp"
               android:background="@drawable/registerselector"
               android:focusable="true">
               </ImageButton>>
  <ImageButton android:id="@+id/buttonlogin"
               android:layout_height="36dp"
               android:layout_width="80dp"
               android:background="@drawable/loginselector"
               android:focusable="true">
               </ImageButton>
</LinearLayout>

and my selector xml is
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--<item android:state_pressed="true" android:drawable="@drawable/homehover"
        /> <item android:state_focused="true" android:drawable="@drawable/homehover"
        /> <item android:drawable="@drawable/home" /> <item android:state_window_focused="true"
        android:drawable="@drawable/homehover" /> -->
    <item android:state_enabled="false" android:drawable="@drawable/homehover" />
    <item android:state_pressed="true" android:state_enabled="true"
        android:drawable="@drawable/homehover" />
    <item android:state_focused="true" android:state_enabled="true"
        android:drawable="@drawable/homehover" />
    <item android:state_enabled="true" android:drawable="@drawable/home" />

</selector>

And I have also tried to change image resource on ontouch and onclick event, but it does not help.

A: mhh. I got another solution which helped me, 'cause I just have two different sates:

*

*either the item is not clicked

*or it is clicked and so it will be highlighted

In my .xml I define the ImageButton like this:
 <ImageButton
    android:id="@+id/imageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/selector" />

The corresponding selector file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ico_100_checked" android:state_selected="true"/>
    <item android:drawable="@drawable/ico_100_unchecked"/>

</selector>

And in my onCreate I call:
final ImageButton ib = (ImageButton) value.findViewById(R.id.imageButton);

    OnClickListener ocl =new OnClickListener() {
        @Override
        public void onClick(View button) {
            if (button.isSelected()){
                button.setSelected(false);
            } else {
                ib.setSelected(false);
                //put all the other buttons you might want to disable here...
                button.setSelected(true);
            }
        }
    };

ib.setOnClickListener(ocl);
//add ocl to all the other buttons

done. hope this helps. took me a while to figure out.

A: Hi try the following code it will be useful to you,
((ImageView)findViewById(R.id.ImageViewButton)).setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_over);

        if(event.getAction() == MotionEvent.ACTION_UP)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_normal);

        return false;
    }
});

A: i think you problem is not the selector file.
you have to add
<imagebutton ..
    android:clickable="true"
/>

to your image buttons.
by default the onClick is handled at the listitem level (parent). and the imageButtons dont recieve the onClick.
when you add the above attribute the image button will receive the event and the selector will be used.
check this POST which explains the same for checkbox.

A: Create an xml file in your drawable like this :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/btn_sendemail_disable" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/btn_send_email_click" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/btn_sendemail_roll" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/btn_sendemail" />
</selector>

And set images accordingly and then set this xml as background of your imageButton.

A: Try this
btn.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        btn.setBackgroundResource(R.drawable.icon);
    }
});

A: what you are trying to do is more a segmentedbutton than an imagebutton list.
here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need

A: if you want pressed image button then image should be change from normal to pressed
But I best way will be to customize the RadioButton and use them in a group. I have see an example of that.
Sorry I did not remember that link.
but if you want to avoid that.
You need to add this to your selector.xml

Once Done. Just got to your code and add this
public void onClick ( View v ) {
    myImageButton.setSelected ( true ) ;
 }

You will see the result. But you have to mange the states which button was recently press. So that you can set
  myOLDImageButton.setSelected ( false ) ;

I suggest you to put all button reference in a array.

A: Have you tried CompoundButton? CompoundButton has the checkable property that exactly matches your need. Replace ImageButtons with these.
  <CompoundButton android:id="@+id/buttonhome"
                  android:layout_width="80dp"
                  android:layout_height="36dp"
                  android:background="@drawable/homeselector"/>

Change selector xml to the following. May need some modification but be sure to use state_checked in place of state_pressed.
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/homehover" />
    <item android:state_checked="true" android:state_enabled="true"
          android:drawable="@drawable/homehover" />
    <item android:state_focused="true" android:state_enabled="true"
          android:drawable="@drawable/homehover" />
    <item android:state_enabled="true" android:drawable="@drawable/home" />

</selector>

In CompoundButton.OnCheckedChangeListener you need to check and uncheck other based on your conditions.
 mButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

   public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // Uncheck others.
        }
   }
});

Similarly set a OnCheckedChangeListener to each button, which will uncheck other buttons when it is checked. Hope this Helps.

A: you can create selector file in res/drawable
example:
res/drawable/selector_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn_disabled" android:state_enabled="false" />
    <item android:drawable="@drawable/btn_enabled" />
</selector>

and in layout activity, fragment or etc
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/selector_bg_rectangle_black"/>


text:
Q: Returning particular arrays from objects in mongodb [
  {
    _id: 555,
    names:['John','Doe','David']
  },
  {
    _id: 625,
    names:['David','Mark','Carl']
  },
  {
    _id: 299,
    names:['Bill','Carlos','Ventus']
  }
]

How can I return only the names(object) of all the object having _id in MongoDB ?
Please help me..

A: model.find({_id : { $exists : 1} }, "-_id names", { lean : true })

As each document in mongoDB has _id : model.find({}, "-_id names", { lean : true }) this would be fine.
You could also use mongo aggregate as follows :
model.aggregate({ $project : { _id : 0, names : 1 })

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check conditions and write text into text file oracle forms I am creating Procedure in Oracle Forms in which Check Validation data and insert data into table. Also check Validation data If condition true then write Some texts into text file and If condition is not true then write some texts into text file.
Like:
Validation No.1 : OK
Validation No.2 : OK

I created procedure successfully for "TRUE" Condition. Now I want If One Condition is True and 2nd Condition is False then write texts into text file.
Like:
Validation No.1 : OK
Validation No.2 : ERROR

And If both conditions "FALSE" Then
Validation No.1 : ERROR
Validation No.2 : ERROR

Code:
PROCEDURE VALIDATION_TEST
(p_mid we_group_hof_k.mstatusid%TYPE,
 p_status we_group_hof_k.cardstatus%TYPE
) is

LC$Line  Varchar2(4000);
TFile    CLIENT_TEXT_IO.FILE_TYPE ;

begin
insert into test
select mstatusid, cardstatus
from we_group_hof_k
where mstatusid = p_mid
and cardstatus = p_status;

IF p_mid = 1 AND p_status = 'A' THEN
LC$Line := 'log_' || TO_CHAR (SYSDATE, 'yyyymmdd_HH24miss') || '.log';
TFile := CLIENT_TEXT_IO.FOpen( 'E:\HMIS\State\test.log', 'W' );
CLIENT_TEXT_IO.put_line (TFile, 'Log file ' || LC$Line);
CLIENT_TEXT_IO.new_line (TFile);
CLIENT_TEXT_IO.put_line (TFile, 'Job started at: ' || TO_CHAR (SYSDATE, 'dd-mm-yyyy HH24:mi:ss'));
CLIENT_TEXT_IO.new_line (TFile);
CLIENT_TEXT_IO.put_line (TFile, 'Validation No.1 : ' || 'OK');

CLIENT_TEXT_IO.new_line (TFile);
CLIENT_TEXT_IO.put_line (TFile, 'Validation No.2 : ' || 'OK');

CLIENT_TEXT_IO.fclose (TFile);

END IF;
end;

A: You haven't told us what the conditions actually are so you'll need to fill in the details.
CLIENT_TEXT_IO.put (TFile, 'Validation No.1 : ' );
if condition_1 then
    CLIENT_TEXT_IO.put_line (TFile, 'OK');
else
    CLIENT_TEXT_IO.put_line (TFile, 'ERROR');
end if;

CLIENT_TEXT_IO.new_line (TFile);

CLIENT_TEXT_IO.put (TFile, 'Validation No.2 : ' );
if condition_2 then
    CLIENT_TEXT_IO.put_line (TFile, 'OK');
else
    CLIENT_TEXT_IO.put_line (TFile, 'ERROR');
end if;

I have total 15 Conditions

In which case you might want to wrap that up into helper function:
PROCEDURE VALIDATION_TEST (p_mid we_group_hof_k.mstatusid%TYPE,
 p_status we_group_hof_k.cardstatus%TYPE ) is
    LC$Line  Varchar2(4000);
    TFile    CLIENT_TEXT_IO.FILE_TYPE ;

    procedure print_validation (
        p_file in CLIENT_TEXT_IO.FILE_TYPE
        , p_validation_number in number
        , p_condition in Boolean )
    is
    begin
        CLIENT_TEXT_IO.new_line (p_file);
        CLIENT_TEXT_IO.put (p_file, 'Validation No.'||to_char(p_validation_number) || ': ' );
        if p_condition then
            CLIENT_TEXT_IO.put_line (p_file, 'OK');
        else
            CLIENT_TEXT_IO.put_line (p_file, 'ERROR');
        end if;
    end print_validation;
begin
    insert into test
    select mstatusid, cardstatus
    from we_group_hof_k
    where mstatusid = p_mid
    and cardstatus = p_status;

    IF p_mid = 1 AND p_status = 'A' THEN
        LC$Line := 'log_' || TO_CHAR (SYSDATE, 'yyyymmdd_HH24miss') || '.log';
        TFile := CLIENT_TEXT_IO.FOpen( 'E:\HMIS\State\test.log', 'W' );
        CLIENT_TEXT_IO.put_line (TFile, 'Log file ' || LC$Line);

        print_validation(TFile, 1, condition_1);
        print_validation(TFile, 2, condition_2);
        ...
        print_validation(TFile, 15, condition_15);

        CLIENT_TEXT_IO.fclose (TFile);

    END IF;
end;


text:
Q: Is Binary Search O(log n) or O(n log n)? I have encountered times when it was O(log n), and times when it was O(n log n). This is also a very popular interview question. So when the interviewer blindly asks you what is the run time of a binary search (with no context)? What should you say?

A: Sounds like a trick question, since there is no context. Looks like interviewer wants to cover cases when binary search is good, and when its not.
So, binary search is great when you have sorted list of elements and you search for single element, and in such case it costs O(logn).
Now, if we don't have sorted array, cost of sorting it is O(n logn), and then you can apply first case. In such case, its better to place values in set or map and then search (execution time will be O(n) for inserting, O(1) for search).
Both of this cases rests on single search. Binary search is not for searching n elements in single execution (or any number of elements depending on n, like n/2 elements, n/4, or even logn elements - for fixed number its ok). For such cases, there are better ways (sets and maps).

A: O(log n), for average and worst case. Never heard someone claim it is O(n log n).


text:
Q: issue with slowly geting data from api to vue view I have issue with very slowly getting data from laravel api to vue view, I did tutorial where I have:
import axios from 'axios';

const client = axios.create({
    baseURL: '/api',
});

export default {
    all(params) {
        return client.get('users', params);
    },
    find(id) {
        return client.get(`users/${id}`);
    },
    update(id, data) {
        return client.put(`users/${id}`, data);
    },
    delete(id) {
        return client.delete(`users/${id}`);
    },
};

<script>
import api from "../api/users";

export default {
  data() {
    return {
      message: null,
      loaded: false,
      saving: false,
      user: {
        id: null,
        name: "",
        email: ""
      }
    };
  },
  methods: {
    onDelete() {
      this.saving = true;
      api.delete(this.user.id).then(response => {
        this.message = "User Deleted";
        setTimeout(() => this.$router.push({ name: "users.index" }), 1000);
      });
    },
    onSubmit(event) {
      this.saving = true;

      api
        .update(this.user.id, {
          name: this.user.name,
          email: this.user.email
        })
        .then(response => {
          this.message = "User updated";
          setTimeout(() => (this.message = null), 10000);
          this.user = response.data.data;
        })
        .catch(error => {
          console.log(error);
        })
        .then(_ => (this.saving = false));
    }
  },
  created() {
    api.find(this.$route.params.id).then(response => {
      this.loaded = true;
      this.user = response.data.data;
    });
  }
};
</script>

It's load data from api very slowly I see firstly empty inputs in view and after some short time I see data, if I open api data from laravel I see data immediately, so my question is How speed up it? Or maby I did something wrong?

A: Whenever I am using an API with Vue, I usually make most of my API calls before opening the Vue then passing it in like this.
<vue-component :user="'{!! $user_data !!}'"></vue-component>

But if you have to do it in the Vue component, I am not sure if this will show improvement over your method but I would set it up with the "mounted" like so.
export default {
    mounted() {
        api.find(this.$route.params.id).then(response => {
          this.loaded = true;
          this.user = response.data.data;
        });
    }
}

Also heres a good tutorial on Axios and how to use HTTP Requets with Vue.
Hopefully this answered your question, good luck!


text:
Q: How could I get django query from one model and add the information from the model ForeignKey to it? I want to get all Blogs in one query, and at the same time, I want to know each Blog's Entry(or Entries), if the Blog has.
class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

Like access the blog.ENTRY attributes. Here is the way come to mind at first. 1) get all Blogs, 2) set each Blog ENTRY attr with its entries:
for blog in Blog.objects.all():
    entry = Entry.objects.filter(blog=blog)
    setattr(blog, 'ENTRY', entry)

But I want to do this in just one query, because I don't want to do Entry filter query in the for loop.

A: Code:
Entry.objects.all().select_related('blog')

will fetch all Entry objects and populate it's blog attribute in single quest.
Doing same with Blog model is not possible in single query as relation is one-to-many.
To get better idea of what is possible and what is not, look at recommended in comments topics related to select_related and prefetch_related. Especially second one.


text:
Q: Could not autowire field using @Autowired annotation I tried to autowire the fields from property file. I just keep the property file in class path.
@Autowired
public BlankDisk(@Value("${disk.title}") String title, @Value("${disk.artist}") String artist) {

        this.title = title;
        this.artist = artist;
    }

app.properties
disc.title=New Songs
disc.artist=Illayarajah

I have written the above code to autowire the fields. But I am getting below exception.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'autowireDemo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.springinaction.autowiring.BlankDisk com.springinaction.autowiring.AutowireDemo.blankDisk; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'disk.title' in string value "${disk.title}"

Can anyone please suggest why I am getting this issue?

A: If you still get the exception after changing the spelling mistake, please make sure if you have added @PropertySource("classpath:application.properties") on top of the configuration class

A: I had a similar issue, and I found the error to be in the discrepancies between my src/main/resources/application.properties
src/test/resources/application.properties
The property I was trying to inject was not in the latter file and when SpringBoot tried to run the test as part of the build, it could not find the property.


text:
Q: Swing: Visual interface connect to second frame I have 2 frames. I want from the first frame to open the second. I tried this, but it leads to an exception.
class aboutaction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            frame.dispose();
            aboutInfo about = new aboutInfo();
            about.frame.setVisible(true);
        }
    }
about.addActionListener(new aboutaction());

This is the full program: https://github.com/Zhelyazkov97/Fuel-calculator.git.

A: You're basic problem is a NullPointerException create from a misunderstanding of how Swing works and a bad design.
Basically, you define your class as...
public class aboutInfo extends JFrame {

    private JPanel contentPane;
    javax.swing.JFrame frame;

Now, here the confusion starts, you basically have two frames, but you only ever add components to the instance of aboutInfo.
The basic answer here is, get rid of frame, it's just confusing the issue.  In fact, you shouldn't be extending from JFrame in the first place, you should really use something like JPanel and simply add instances of the class to instances of JFrame or JDialog or what ever container you want


text:
Q: Calculating distance between geo coordinates from a mysql database In my project i get geo coordinates from my users and i want a result sorted by distance from my mysql database. But the distance is 30% more or less what i get when i check google maps.
user data = $latitude & $longitude
my current query:
$sql = "SELECT *, (((acos(sin((" . $latitude . "*pi()/180)) * "
            . "sin((`latitude`*pi()/180))+"
            . "cos((" . $latitude . "*pi()/180)) * "
            . "cos((`latitude`*pi()/180)) * "
            . "cos(((" . $longitude . "- `longitude`)*pi()/180))))*180/pi())*60*1.1515*1.609344)*1.5 "
            . "as distance FROM `partners` HAVING distance <= '10' ORDER BY distance ASC LIMIT 0, 25";

Any tips on improving this?

*

*https://www.miammiam.lu/en/livraison/Differdange


text:
Q: FaultException with SlSvcUtil generated code I have a WebService with following wsdl file:
<?xml version='1.0' encoding='UTF-8'?><wsdl:definitions name="BBAppWebAccessService" targetNamespace="com.test" xmlns:ns1="http://schemas.xmlsoap.org/soap/http" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="com.test" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <wsdl:types>
  <xs:schema elementFormDefault="unqualified" targetNamespace="com.test" version="1.0" xmlns:tns="com.test" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="getPOI" type="tns:getPOI" />
  <xs:element name="getPOIResponse" type="tns:getPOIResponse" />

  <xs:complexType name="poi">
  <xs:complexContent>
  <xs:extension base="tns:poiPreview">
  <xs:sequence>
  <xs:element maxOccurs="unbounded" minOccurs="0" name="images" nillable="true" type="tns:bbImage" />
  </xs:sequence>
  </xs:extension>
  </xs:complexContent>
  </xs:complexType>
    <xs:complexType name="poiPreview">

      <xs:sequence>
        <xs:element name="poiID" type="xs:int" />
        <xs:element maxOccurs="unbounded" minOccurs="0" name="thumbsnails" nillable="true" type="tns:bbImage" />
      </xs:sequence>
    </xs:complexType>
    <xs:complexType name="bbImage">
      <xs:sequence>
        <xs:element maxOccurs="unbounded" minOccurs="0" name="imageData" nillable="true" type="xs:byte" />
        <xs:element minOccurs="0" name="imageName" type="xs:string" />
        <xs:element name="imageID" type="xs:int" />
      </xs:sequence>
    </xs:complexType>
  <xs:complexType name="getPOI">
  <xs:sequence>
  <xs:element name="ID" type="xs:int" />
  </xs:sequence>
  </xs:complexType>
  <xs:complexType name="getPOIResponse">
  <xs:sequence>
  <xs:element minOccurs="0" name="return" type="tns:poi" />
  </xs:sequence>
  </xs:complexType>
  </xs:schema>
    </wsdl:types>
    <wsdl:message name="getPOI">
      <wsdl:part element="tns:getPOI" name="parameters">
      </wsdl:part>
    </wsdl:message>
    <wsdl:message name="getPOIResponse">
      <wsdl:part element="tns:getPOIResponse" name="parameters">
      </wsdl:part>
    </wsdl:message>
    <wsdl:portType name="BBAppWebAccess">
      <wsdl:operation name="getPOI">
        <wsdl:input message="tns:getPOI" name="getPOI">
      </wsdl:input>
        <wsdl:output message="tns:getPOIResponse" name="getPOIResponse">
      </wsdl:output>
      </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="BBAppWebAccessServiceSoapBinding" type="tns:BBAppWebAccess">
      <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
      <wsdl:operation name="getPOI">
        <soap:operation soapAction="" style="document" />
        <wsdl:input name="getPOI">
          <soap:body use="literal" />
        </wsdl:input>
        <wsdl:output name="getPOIResponse">
          <soap:body use="literal" />
        </wsdl:output>
      </wsdl:operation>
    </wsdl:binding>

    <wsdl:service name="BBAppWebAccessService">
      <wsdl:port binding="tns:BBAppWebAccessServiceSoapBinding" name="BBAppWebAccessPort">
        <soap:address location="http://localhost:8080/BBAppWeb/HelloWorld" />
      </wsdl:port>
    </wsdl:service>
  </wsdl:definitions>

I used the SlSvcUtil from the Windows Phone SDK to generate the proxy classes for c# SlSvcUtil.exe test.wsdl.
This is a part from the generated code:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="getPOI", WrapperNamespace="com.test", IsWrapped=true)]
public partial class getPOI {

        [System.ServiceModel.MessageBodyMemberAttribute(Order=0)]
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public int ID;

        public getPOI() {
        }

        public getPOI(int ID) {
            this.ID = ID;
        }
}

private class BBAppWebAccessClientChannel : ChannelBase<BBAppWebAccess>, BBAppWebAccess
{

    public BBAppWebAccessClientChannel(System.ServiceModel.ClientBase<BBAppWebAccess> client) :
            base(client)
    {
    }

    public System.IAsyncResult BegingetPOI(getPOI request, System.AsyncCallback callback, object asyncState)
    {
        object[] _args = new object[1];
        _args[0] = request;
        System.IAsyncResult _result = base.BeginInvoke("getPOI", _args, callback, asyncState);
        return _result;
    }

    public getPOIResponse EndgetPOI(System.IAsyncResult result)
    {
        object[] _args = new object[0];
        getPOIResponse _result = ((getPOIResponse)(base.EndInvoke("getPOI", _args, result)));
        return _result;
    }
}

The FaultException is thrown by that getPOIResponse _result = ((getPOIResponse)(base.EndInvoke("getPOI", _args, result)));.
I call the WebService with following code:
private void Load_Initial_Data()
{
    try
    {
        BBAppWebAccessClient wac = new BBAppWebAccessClient();
        wac.getPOICompleted += new EventHandler<getPOICompletedEventArgs>(client_GetDataCompleted);
        wac.getPOIAsync(1);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.StackTrace);
    }

}
void client_GetDataCompleted(object sender, getPOICompletedEventArgs e)
{
    //this.DataContext = e.Result;
    Console.WriteLine(e.Result.poiID);
}

On the server side there is following exception:
22:27:23,789 WARN  [org.apache.cxf.phase.PhaseInterceptorChain] Interceptor for {com.test}BBAppWebAccessService#{com.test}getPOI has thrown exception, unwinding now: org.apache.cxf.interceptor.Fault: Unmarshalling Error: unexpected element (uri:"com.test", local:"ID").
        at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:787) [:2.3.1-patch-01]
        at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:628) [:2.3.1-patch-01]
        at org.apache.cxf.jaxb.io.DataReaderImpl.read(DataReaderImpl.java:133) [:2.3.1-patch-01]
        at org.apache.cxf.interceptor.DocLiteralInInterceptor.handleMessage(DocLiteralInInterceptor.java:109) [:2.3.1-patch-01]
        at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255) [:2.3.1-patch-01]
        at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:113) [:2.3.1-patch-01]
        at org.apache.cxf.transport.servlet.ServletDestination.invoke(ServletDestination.java:97) [:2.3.1-patch-01]
        at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:461) [:2.3.1-patch-01]
        at org.jboss.wsf.stack.cxf.ServletControllerExt.invoke(ServletControllerExt.java:172) [:3.4.1.GA]
        at org.jboss.wsf.stack.cxf.RequestHandlerImpl.handleHttpRequest(RequestHandlerImpl.java:57) [:3.4.1.GA]
        at org.jboss.wsf.stack.cxf.transport.ServletHelper.callRequestHandler(ServletHelper.java:156) [:3.4.1.GA]
        at org.jboss.wsf.stack.cxf.CXFNonSpringServletExt.invoke(CXFNonSpringServletExt.java:90) [:3.4.1.GA]
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:179) [:2.3.1-patch-01]
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:103) [:2.3.1-patch-01]
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) [:1.0.0.Final]
        at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:159) [:2.3.1-patch-01]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324) [:6.1.0.Final]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242) [:6.1.0.Final]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [:6.1.0.Final]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [:6.1.0.Final]
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181) [:6.1.0.Final]
        at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285) [:1.1.0.Final]
        at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261) [:1.1.0.Final]
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88) [:6.1.0.Final]
        at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100) [:6.1.0.Final]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159) [:6.1.0.Final]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [:6.1.0.Final]
        at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) [:6.1.0.Final]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [:6.1.0.Final]
        at org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53) [:6.1.0.Final]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [:6.1.0.Final]
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [:6.1.0.Final]
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654) [:6.1.0.Final]
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951) [:6.1.0.Final]
        at java.lang.Thread.run(Unknown Source) [:1.7.0]
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[com.sun.istack.SAXParseException2; lineNumber: 1; columnNumber: 197; unexpected element (uri:"com.test", local:"ID"). Expected elements are <{}ID>]
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:425) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:362) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:339) [:2.2]
        at org.apache.cxf.jaxb.JAXBEncoderDecoder.unmarshall(JAXBEncoderDecoder.java:764) [:2.3.1-patch-01]
        ... 34 more
Caused by: com.sun.istack.SAXParseException2; lineNumber: 1; columnNumber: 197; unexpected element (uri:"com.test", local:"ID"). Expected elements are <{}ID>
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:642) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:254) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:249) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:116) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.childElement(Loader.java:101) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.StructureLoader.childElement(StructureLoader.java:243) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:478) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:459) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:242) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:176) [:2.2]
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:360) [:2.2]
        ... 36 more
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"com.test", local:"ID"). Expected elements are <{}ID>
        ... 47 more

ClientConfig:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BBAppWebAccessServiceSoapBinding" maxBufferSize="2147483647"
                    maxReceivedMessageSize="2147483647">
                    <security mode="None" />
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:8080/BBAppWeb/HelloWorld"
                binding="basicHttpBinding" bindingConfiguration="BBAppWebAccessServiceSoapBinding"
                contract="SilverlightApplication1.ServiceReference1.BBAppWebAccess"
                name="BBAppWebAccessPort" />
        </client>
    </system.serviceModel>
</configuration>

Message captured with Fiddler (Windows Phone):
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <getPOI xmlns="com.test">
            <ID>1</ID>
        </getPOI><
    /s:Body>
</s:Envelope>

Message captured with Fiddler (Axis2):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns1:getPOI xmlns:ns1="com.test">
            <ID>1</ID>
        </ns1:getPOI>
    </soapenv:Body>
</soapenv:Envelope>

How can I fix it? The generated java code (Apache Axis2) works great.
Thanks for any advices.

A: I found the solution. When you are creating the WebService with Java EE you have to add all namespaces, otherwise you will get the errors above.
After fixing the FaultException, I got a NullReferenceException, which indicates that I have to fix the response handling, too.
Thanks a lot to @calum.
Here is a sample implementation of the WebService, which works together with Axis2 and the SLsvcUtil tool:
package com.test;

//imports here

@WebService(targetNamespace = "com.test")
public class BBAppWebAccess {
    @WebMethod
    @WebResult(targetNamespace="com.test.poi")
    public POI getPOI(
            @WebParam(name="ID", targetNamespace="com.test.poi")
            int id) {

        return new POI(id);
    }
}

The new message looks like following:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <getPOI xmlns="com.test">
            <ID xmlns="com.test.poi">1</ID>
        </getPOI>
    </s:Body>
</s:Envelope>

The new genereated getPOI class:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="getPOI", WrapperNamespace="com.test", IsWrapped=true)]
public partial class getPOI {

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="com.test.poi", Order=0)]
    public int ID;

    public getPOI() {
    }

    public getPOI(int ID) {
        this.ID = ID;
    }
}

A: It looks like you are sending the service the wrong type (I assume this as the error states that an unexpected element 'ID' was found and that means that your request is not properly formed).
Use fiddler (if possible) to see what you are sending to the server. You will probably be able to figure out what is happening and then you can update the generated code so that the correct type is sent.


text:
Q: Need to end a loop of a subprocess through userinput (GPIO.input) I need to execute a bash-command in a python program on a raspberry pi, which starts a record, which really starts recording if their is the sound above a certain frequency and finishes after 8sec or if there is silence. After a record finished, it starts itself an waits for new sound to record. Each record is labeled with time. That's the code doing I quoted here:
while GPIO.input(26) == False:
    timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    process = subprocess.Popen ("rec -c 2 -r 192000 --buffer 50000 -b 32" + filepath + timestamp + ".wav sinc 0.1k silence 1 0.1 0.8% 1 0.4 0.8% vol 6 trim 0 8", shell = True)
    process.communicate()

As you can see, to finish the loop, the program waits for a GPIO-input signal (push button). I have an extra code which looks for the name of the subprocess and kills it.
But here is my problem: While the loop runs, it only "looks" for input in the millisecond between one record finishes and a new starts". If I push my button during a record, the loop continues after the record. It only breaks if I push in between.
At first, I thought maybe the while-loop is a bad choice...but if I am not wrong, the problem seems to be the running subprocess.
So here is my question: How can I accomplish this record loop but can stop/kill during a running record through user-input by GPIO. (ctrl+c won't be a viable option)
Many thanks

A: The issue is that the while loop only checks the condition once each time through the loop. The process.communicate() call waits for the rec command to finish, so you are absolutely right - the button is only checked once, just after the rec and before the timestamp = ....
A solution is to watch for the button in a separate thread, running in parallel with the rec.  This answer suggests using event detection from the RPi.GPIO library.  Try something like this:
should_exit = False

def my_callback(channel):
    if GPIO.input(26):
        should_exit = True

GPIO.add_event_detect(26, GPIO.RISING, callback=my_callback, bouncetime=300)

while not should_exit:
    timestamp = ...

The my_callback routine should run when the button is pressed, and set the should_exit flag.  Once the rec finishes, the while will check should_exit and terminate.  (Caution - not tested!)


text:
Q: Extract the line which are in comments with // aa well as /*...*/ I have a file and I need to extract the line which is in comments with // aa well as /*...*/as shown below:
//This is me
/*Multiple line arguments
best way to
use*/
Store the variables.
Swap it

//Done

I tried for single line comments like this as shown below:
grep "//" file_name | sed 's/\/\///g'

Where I got my expected output for single line comments.
This is me
Done

For multi line comments /*....*/ how to extract the lines between them to get my expected output.
Expected output:
This is me
Multiple line arguments
best way to
use
Done

A: With awk could you please try following. Written and tested as per shown samples in GNU awk.
awk '{gsub(/^\/\/|^\/\*|\*\/$/,"")} 1' Input_file

Simple explanation: Using gsub(Globally substitution) function of awk to substitute either starting // OR starting /* OR line ending with */ with NULL in all the lines, then simply printing the lines.

EDIT: In case you want to get only commented lines then following may help, written and tested with shown samples only.
awk '
!NF{
  next
}
/^\/\//{
  sub(/^\/\//,"")
  print
  next
}
/^\/\*/{
  sub(/^\/\*/,"")
  multiFound=1
}
/\*\/$/{
  sub(/\*\/$/,"")
  multiFound=""
  print
  next
}
multiFound
'  Input_file

A: To print only comments as initially requested:
awk '
     BEGIN {
             prnt=0 # Initialise variable to 0
           }
     /^\/\// { # Process lines starting with //
               $0=gensub("/","","g",$0); # Strip out every /
               print; # print the line
               next # process the next line
             }
     /^\/\*/ { # process lines with start with /*
               prnt=1 # set the prnt variable to 1
             }
     /^.*\*\/$/ { # Process lines that end with */
               prnt=0; # Set the prnt variable to 0
               $0=gensub("[/*]","","g",$0); # Strip / and * out of the line
               print
             }
     prnt==1 {
               $0=gensub("[/*]","","g",$0); # When prnt is equal to one, strip the / and * and print
               print
             }
     prnt==0 {  # When prnt is 0, ignore the line and skip to the next line.
               next
             }' file

One liner:
awk 'BEGIN { prnt=0 } /^\/\// { $0=gensub("/","","g",$0);print;next } /^\/\*/ { prnt=1 } /^.*\*\/$/ { prnt=0;$0=gensub("[/*]","","g",$0);print } prnt==1 { $0=gensub("[/*]","","g",$0);;print } prnt==0 { next }' file

Output:
This is me
Multiple line arguments
best way to
use
Done

Awk version:
GNU Awk 4.0.2

GNU independent version using gsub as opposed to gensub:
awk 'BEGIN { prnt=0 } /^\/\// { gsub("/","",$0);print;next } /^\/\*/ { prnt=1 } /^.*\*\/$/ { prnt=0;gsub("[/*]","",$0);print } prnt==1 { gsub("[/*]","",$0);print } prnt==0 { next }' file


text:
Q: Bash error when trying to execute a file i am kinda new to linux and in programming so please excuse my lack of knowledge.
I'm trying to run a basic program named trial.c with an executable file named trying but when I type ./trying in the terminal this error comes up:
bash: ./trying: Permission denied

The folder is on my HDD with 3 partitions, one for home, another for my ubuntu_files, and the other is a fat32 partition named MISC. The folder is inside the fat32 partition of my HDD.
the problem is no matter how much I try to use chownand chmod(both with recursive) to change the permission of the folder containing the trial.c and the executable(trying) file, the bash error message would still stay the same.
The user is nciacrklo, and i typed groups nciacrklo to see what group is associated with that user and tried the codes found below in my terminal.
sudo chown nciacrklo:nciacrklo /media/nciacrklo/MISC/LibUsb -R -v

and after that it said:
ownership of `/media/nciacrklo/MISC/LibUsb/trying' retained as nciacrklo:nciacrklo
ownership of `/media/nciacrklo/MISC/LibUsb/trial.c' retained as nciacrklo:nciacrklo

and then,
sudo chmod 755 /media/nciacrklo/MISC/LibUsb -R -v

it then said,
mode of `/media/nciacrklo/MISC/LibUsb/trying' changed from 0644 (rw-r--r--) to 0755 (rwxr-xr-x)
mode of `/media/nciacrklo/MISC/LibUsb/trial.c' changed from 0644 (rw-r--r--) to 0755 (rwxr-xr-x)

finally, I tried the ./trying again but same error appeared.
bash: ./trying: Permission denied

please please help me I'm struggling with this and yet I have to do lots of programming about the LibUsb topic >.<.
any comments about how to use LibUsb to acquire pictures from webcam would also be much help. Thanks!!! \m/,

A: If all the permissions of the file are ok, as they seem to be, it might be because your partition is mounted with the noexec flag.
To check this: type mount and check if it is the case. You should see something like:
/dev/sdd1 on /media/banana type vfat (rw,noexec,relatime,fmask=0022,dmask=0022,codepage=cp437,iocharset=utf8,shortname=mixed,errors=remount-ro)

(see the noexec there?)
Remount your partition with the noexec flag as so:
sudo mount -o remount,exec /media/banana

(you'll have to adapt the banana part to your case). And check that it worked by issuing mount again:
/dev/sdd1 on /media/banana type vfat (rw,relatime,fmask=0022,dmask=0022,codepage=cp437,iocharset=utf8,shortname=mixed,errors=remount-ro)

(no more noexec here!).
If that was your problem, you'll have to figure out the partition was mounted with the noexec flag in the first place.


text:
Q: Use singletons in akka scala actor I have an actor that is delegating calls to a stateful singleton. The singleton is stateful since it is maintaining a map of objects. This singleton object is used just in the actor and in a class (not actor) where I am retrieving one object in this map (so just thread safe read).
class MyActor extends Actor{
  def receive()={
    case ACase => singleton.amethod()
    case BCase => singleton.bmethod()
     }
 }

val singleton = new MyActorLogic

class MyActorLogic{
 val map:Map[String, Object] = Map()
 def amethod()=//alter the map

 def readMap(value:String) = map(value)    }

Could there be any side effects/problems?
Thanks

A: Do not do that for any reason in the world.
Trust me.
If you need that sort of things use Agent instead, that's what they are good for:
http://doc.akka.io/docs/akka/2.0.4/scala/agents.html

A: In theory, using MyActorLogic, armed with a simple mutable map, from multiple threads, may lead to concurrent modification exception (when one thread is traversing the map, whilst another's modifying it).
You could do the following to avoid problems :

*

*Put the map into the actor (as a private member). In Akka, you're not working with the Actor instance directly (but rather accessing it through a proxy - ActorRef). In this case, safe access to the map will not only be guaranteed by the actor, that always processes one message at a time - other threads won't be able to access private members even through reflection.

*You can make update/retrieval methods of MyActorLogic thread-safe (e.g., making them synchronized)

*You can use old-good ConcurrentHashMap

*Instead of val map:mutable.Map you can use var map:immutable.Map. Thus, multiple threads accessing map may occasionally work with a stale data, but there will be no concurrent modifications (copy-on-write approach).

Just for the note, true singleton would be:
object MyActorLogic{
 val map:Map[String, Object] = Map()
 ...


text:
Q: How to format a url in order to navigate directly to a specific place in the site? I am using this template agency, which is built with bootstrap v.3. In the portfolio, when you click one of the projects, a page is shown with more info.. How can I format the link, in order to navigate directly to that page?
I added #portfolioModal1 at the end of the url but it doesnt work..

A: You will have to use a script for this, like in this link
Use this:
<script>
  if(window.location.hash) {
    var hash = window.location.hash;
    $(hash).modal('toggle');
  }
  $('.portfolio-link').click(function(){
       window.location.hash = $(this).attr('href');
  });
</script>

Call it like this:
http://ironsummitmedia.github.io/startbootstrap-agency/#portfolioModal1


text:
Q: Xamarin.Forms new project creation has countless errors. Something wrong with nuget? I am new to Visual Studio.
creating a new project with Xamarin.Forms template gives countless errors, such as

"Can not resolve reference: Xamarin.Forms.Xaml, referenced by
  App4. Please add a NuGet package or assembly reference for
  Xamarin.Forms.Xaml, or remove the reference to App4.  App4.Android"
  "the referenced component "system.xml" could not be found." "the
  reference component "system" could not be found."

I think something substantial is wrong with the installation; I have tried uninstalling, repairing, and tried VS 2017 and VS 2019. Nothing seems to work.
I tried to manually install the nuget packages, from the package manager and the console. The package manager indicates all the packages are uptodate, and does not let me install any new packages; from the console, installing any package results in this error:

"Install-Package Xamarin.Forms -Version 3.6.0.344457 Restoring
  packages for
  C:\Users\Navid\source\repos\App4\App4\App4.Android\App4.Android.csproj...
  GET
  https://www.nuget.org/packages/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0
  GET
  https://nuget.org/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0
  NotFound
  https://nuget.org/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0
  121ms Retrying 'FindPackagesByIdAsyncCore' for source
  'https://nuget.org/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0'.
  Response status code does not indicate success: 404 (Not Found).   GET
  https://nuget.org/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0
  NotFound
  https://www.nuget.org/packages/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0
  168ms Install-Package : Failed to retrieve information about
  'System.Numerics.Vectors' from remote source
  'https://nuget.org/FindPackagesById()?id='System.Numerics.Vectors'&semVerLevel=2.0.0'.
  Response status code does not indicate success: 404 (Not Found). At
  line:1 char:1
  + Install-Package Xamarin.Forms -Version 3.6.0.344457
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
  Time Elapsed: 00:00:01.0871186"


text:
Q: Create copy of Object I need to clone object (class, not struct) in .net 4.5 (c#).
 I found two ways:

*

*Implement ICloneable Interface

*Create own clone mechanism like this famous SO answer
I like fist way - it's easier, but I also found Not Implpement ICloneable Interface, but it's very old post and on MSDN I can't find that this interface deprecated.
Could any says me, it is safety to use ICloneable  in .net 4.5?

A: IClonable is just an interface so it does nothing until you implement it. The post which suggests to not use IClonable mentions why: it is not clear if Clone is implemented as deep- or as shallow copy.
So just provide a Copy or DeepClone method and everyone knows what happens.
Quote to explain the two terms:

There are two general ways to implement ICloneable, either as a deep,
  or non-deep copy. Deep-copy copies the cloned object and all objects
  referenced by the object, recursively until all objects in the graph
  are copied. A non-deep copy (referred to as shallow if only the top
  level references are copied) may do none, or part of a deep copy.

A: You should not use the IClonable interface.
Here's a blog from Brad Abrams discussing why not from several years ago. Basically, the reasons are outlined by Tim Schmelter's answer, but this blog is from the horse's mouth.
In relation to implementing cloning via serialization, there is a slightly better way available now because we can specify StreamingContextStates.Clone to allow the cloning to work better with things like unmanaged handles.
There's a canonical implementation in "CLR via C# 4th Edition" by Jeffrey Richter which goes like this:
public static object DeepClone(object original)
{
    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter
        {
            Context = new StreamingContext(StreamingContextStates.Clone)
        };

        formatter.Serialize(stream, original);
        stream.Position = 0;

        return formatter.Deserialize(stream);
    }
}

Or the strongly typed variant:
public static T DeepClone<T>(T original)
{
    if (!typeof(T).IsSerializable)
    {
        throw new ArgumentException("The type must be serializable.", "original");
    }

    if (ReferenceEquals(original, null))
    {
        return default(T);
    }

    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter
        {
            Context = new StreamingContext(StreamingContextStates.Clone)
        };

        formatter.Serialize(stream, original);
        stream.Position = 0;

        return (T) formatter.Deserialize(stream);
    }
}

I reckon you should use that (where possible) instead of implementing IClonable.


text:
Q: What are PPXes? In many projects using ReasonML, the acronym PPX is often used, but rarely explained.
What are PPXes?
Why does ReasonML need them?

A: A PPX (Preprocessor extension) is an Abstract Syntax Tree (AST) rewriter. Essentially just a function ast => ast.
The AST is a representation of the syntax, the tree data structure that results from parsing the source code. Since a PPX can only accept and return this AST, it is restricted to the existing OCaml/ReasonML syntax. However, it can reinterpret the syntax, and it can embed a completely different syntax in a string, enabling a limited and encapsulated form of syntax extension.
PPXes are also not allowed to rewrite the entire AST. They are restricted to nodes that have been tagged by the user using either attributes ([@...)), which are associated with existing nodes, or extension nodes ([%...]) which are stand-alone AST nodes. A PPX will register one or more hooks that will receive the AST associated with them as they are encountered by the compiler, and can the transform these pieces of AST before the compiler continues onto the its phase.
Examples
ppx_deriving is perhaps the most widely used PPX. It allows certain functionality to be "derived" from type signatures. For example:
[@deriving show]
type t = {
  foo: int,
  bar: string,
};

will generate a show function (as well as a few others) that when given a value of type t  will return a pretty-printed string representation of it.
ppx_bx_css and styled-ppx are both PPXes that parse CSS into some OCaml/ReasonML data structure to be used with various CSS-in-JS libraries. These embed the CSS syntax in a quoted string which, for this purpose at least, is just an ordinary string that allows line breaks and does not require escaping of " and \.
  [%style
    {|
      color: red;
      margin: auto 0 10px 1em;
      width: 70%;
      background: url(http://example.com/test.jpg)
    |}
  ];

A: PPX comes from the Ocaml ecosystem, from which ReasonML is a part of. Basically, PPX gives you an API to extend the language syntax.
Check out http://ocamllabs.io/doc/ppx.html
thanks for ephoz


text:
Q: My custom distance for Bayesian Optimization runs very slow in scipy.spatial.distance.cdist function
Greetings,
I am trying to perform bayesian optimization using the bayesian_optimization library with a custom kernel function, concretly a RBF version which uses the kendall distance.
I am trying to pass as an argument the kendall distance, to the cdist and pdist functions located in scipy.spatial.distance. I am reusing the code of the kendalltau function from scipy.stats.kendalltau, concretly, my kendall distance is defined as follows:
def kendall_distance(x,y):
    perm = np.argsort(y)  # sort on y and convert y to dense ranks
    x, y = x[perm], y[perm]
    y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)

    # stable sort on x and convert x to dense ranks
    perm = np.argsort(x, kind='mergesort')
    x, y = x[perm], y[perm]
    x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)

    dis = _kendall_dis(x, y)  # discordant pairs
    return dis

With this distance, I define my custom kernel function,
class PermutationRBF(StationaryKernelMixin, NormalizedKernelMixin, Kernel):
    def __init__(self, alpha=1.0, alpha_bounds=(1e-5, 1e5)):
        self.alpha = alpha
        self.alpha_bounds = alpha_bounds

    @property
    def anisotropic(self):
        return np.iterable(self.alpha) and len(self.alpha) > 1

    @property
    def hyperparameter_length_scale(self):
        if self.anisotropic:
            return Hyperparameter("length_scale", "numeric",
                                  self.alpha_bounds,
                                  len(self.alpha))
        return Hyperparameter(
            "alpha", "numeric", self.alpha_bounds)

    def __call__(self, X, Y=None, eval_gradient=False):
        X = np.atleast_2d(X)
        alpha = _check_length_scale(X, self.alpha)
        if Y is None:
            dists = pdist(X / alpha, kendall_distance) # First change
            K = np.exp(-.5 * dists)
            # convert from upper-triangular matrix to square matrix
            K = squareform(K)
            np.fill_diagonal(K, 1)
        else:
            if eval_gradient:
                raise ValueError(
                    "Gradient can only be evaluated when Y is None.")
            dists = cdist(X / alpha, Y / alpha, kendall_distance) # Second change
            K = np.exp(-.5 * dists)
        if eval_gradient:
            if self.hyperparameter_length_scale.fixed:
                # Hyperparameter l kept fixed
                return K, np.empty((X.shape[0], X.shape[0], 0))
            elif not self.anisotropic or alpha.shape[0] == 1:
                K_gradient = \
                    (K * squareform(dists))[:, :, np.newaxis]
                return K, K_gradient
            elif self.anisotropic:
                # We need to recompute the pairwise dimension-wise distances
                K_gradient = (X[:, np.newaxis, :] - X[np.newaxis, :, :]) ** 2 \
                    / (alpha ** 2)
                K_gradient *= K[..., np.newaxis]
                return K, K_gradient
        else:
            return K

The only change from the original (tagged with comments) is to pass the kendall_distance function as an argument to the cdist and pdist functions.
The problem appears when I run the optimization with that kernel, the performance is very slow compared with the RBF. The computation of Kendall distance O(n log n) is harder than the Euclidean O(n), however, the difference should not be so noticeable in small sizes.
Custom kernel
iteration:  0
time:  0.0008704662322998047
iteration:  1
time:  1.2141697406768799
iteration:  2
time:  2.3469510078430176
iteration:  3
time:  3.5015127658843994
iteration:  4
time:  4.695566892623901

RBF kernel

iteration:  0
time:  0.000415802001953125
iteration:  1
time:  0.020179033279418945
iteration:  2
time:  0.033345937728881836
iteration:  3
time:  0.033483028411865234
iteration:  4
time:  0.0286252498626709

You can see the complete notebook and the results here.
I think the problem is because if I call pdist and cdist functions with some integrated distance, like the Euclidean, the functions runs the following code
    elif isinstance(metric, str):
        mstr = metric.lower()

        mstr, kwargs = _select_weighted_metric(mstr, kwargs, out)

        metric_name = _METRIC_ALIAS.get(mstr, None)

        if metric_name is not None:
            X, typ, kwargs = _validate_pdist_input(X, m, n,
                                                   metric_name, **kwargs)

            if 'w' in kwargs:
                metric_name = _C_WEIGHTED_METRICS.get(metric_name, metric_name)

            # get pdist wrapper
            pdist_fn = getattr(_distance_wrap,
                               "pdist_%s_%s_wrap" % (metric_name, typ))
            pdist_fn(X, dm, **kwargs)
            return dm

which I suppose will be programmed and optimized in C.
On the other hand, if I use my custom metric, the executed code fragment is
    if callable(metric):
        mstr = getattr(metric, '__name__', 'UnknownCustomMetric')
        metric_name = _METRIC_ALIAS.get(mstr, None)

        if metric_name is not None:
            X, typ, kwargs = _validate_pdist_input(X, m, n,
                                                   metric_name, **kwargs)

        k = 0
        for i in range(0, m - 1):
            for j in range(i + 1, m):
                dm[k] = metric(X[i], X[j], **kwargs)
                k = k + 1

which is pure python, slower by default.
Is it possible that this is the reason of the bottleneck? In case it is, I need more efficiency in my execution, is there any way to improve this?
I leave the test code again here Complete Notebook
Edit with new information:
As the comments suggest, I use line_profiler to found the bottleneck and these are the obtained results simplified:
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
.
.
.
58         1        879.0    879.0     92.4          dm = calculate_pdist_dm(metric,dm,m,X)
.
.
.

where calculate_pdist_dm is as follows
def calculate_pdist_dm(metric,dm,m,X):
    k = 0
    for i in range(0, m - 1):
        for j in range(i + 1, m):
            dm[k] = metric(X[i], X[j])
            k = k + 1
    return dm

and the metric function is the previously commented Kendall distance with the following time results.
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     2                                           @do_profile()
     3                                           def kendall_distance(x,y):
     4         1         11.0     11.0      6.9      perm = np.argsort(y)  # sort on y and convert y to dense ranks
     5         1          1.0      1.0      0.6      x, y = x[perm], y[perm]
     6         1         59.0     59.0     37.1      y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
     7
     8                                               # stable sort on x and convert x to dense ranks
     9         1          9.0      9.0      5.7      perm = np.argsort(x, kind='mergesort')
    10         1          1.0      1.0      0.6      x, y = x[perm], y[perm]
    11         1         50.0     50.0     31.4      x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
    12
    13         1         28.0     28.0     17.6      dis = _kendall_dis(x, y)  # discordant pairs
    14         1          0.0      0.0      0.0      return dis

Timer unit: 1e-06 s

Total time: 0.000159 s

Also say that if I use a pure Python implementation for Kendall distance,
def kendall_distance(x,y):
    distance = 0
    for i in range(len(x)):
        for j in range(i,len(x)):
            a = x[i] - x[j]
            b = y[i] - y[j]
            if (a * b < 0):
                distance += 1
    return distance

I can use numba to execute more efficiently but I'm still far from the efficiency of the built-in distances (results below in more advanced iterations 95-99 where Bayesian optimization becomes computationally expensive). Is there any way to improve this?
Custom kernel with Kendall distance and numba
iteration:  95
time:  0.3591618537902832
iteration:  96
time:  0.41269588470458984
iteration:  97
time:  0.40320730209350586
iteration:  98
time:  0.40665769577026367
iteration:  99
time:  0.37867259979248047

RBF kernel with the scipy built-in Euclidean distance
iteration:  95
time:  0.04483485221862793
iteration:  96
time:  0.046830177307128906
iteration:  97
time:  0.03493475914001465
iteration:  98
time:  0.03614163398742676
iteration:  99
time:  0.042229413986206055

The new code with the use of numba is here


text:
Q: EmberJS 2.0 How to avoid Dynamic Segments On route to be always undefined? I want to access to the dynamic segment on a route but the params are always undefined.
I have the next route defined on the router:
this.route('send', {path: '/send/:solName/:id/:userId'}, function() {});

And In my route I have this:
    export default Ember.Route.extend({
        model: function (params){

        console.info(params);

        return {
             solName: params.solName,
             id: params.id,
             userId: params.userId
         }

        }
      });

Any idea why the params are always undefined?

A: It is normal.
The dynamic segment parameters would not passed to inner routes.
You need to use paramsFor method in send.index route to get params sent to the route.
Please check this twiddle out


text:
Q: joomla extension to create forms i want a dynamic form which has a facility to add text field or any field in any order ( as a grid, vertically, in a row) and user(user of that form not developer) should be able to add rows of text field.
Please suggest me some open source/free plugin.
So guide me how can create that type of plugin. i searched it in google but could not find any plugin.

A: Try Fox Contact Form.  It is a free form creating plugin for Joomla.  You can customize fields and change ordering and layout.
It adds an extremely small "Made By ...." at the bottom of the form, but that can be removed with a purchased license, though that isn't necessary because it is hardly noticed.
You can find the plugin http://www.fox.ra.it/joomla-extensions/fox-contact-form.html
Please mark as answer if this helped you - it has been a good plugin for me

A: Try Chronoforms.It is highly customizable with both Plug-in and Modules.Check the demo and use
http://www.chronoengine.com/component/content/article/1-latest/2083-chronoforms-for-j16-is-out.html


text:
Q: 90s (or earlier) short story concerning two mathematicians and "dark numbers" I think I read this short story 20, 30 years ago.  The story concerns two mathematicians in a dark dystopian future. The one is struggling with some project, and can't figure out how to get the thing done; his friend gives him some advice, involving the use of the forbidden "dark numbers", which include such concepts as zero. No fantasy, I thought is was C.J. Cherryh but I can't find any hits there.
It's driving me nuts, what story was this?
I'm reasonably certain I read this in a collection of short stories, most likely bought from a second-hand book store.
The point of the story was a commentary on the rulers (government? religious?) who forbade the use of mathematics that would allow people to solve significant problems (think engineering and the like) -- not individual people, but rather society at large.

A: I wonder if this is "The Masters" collected in Ursula Le Guin's The Wind's Twelve Quarters?

*

*There are no "dark numbers", but there are "black numbers" (i.e. numbers represented using Arabic numerals) and zero is explicitly one of them. The society they live in uses numbers of course, but they are Roman numerals, and are hobbled by a lack of zero, negative numbers, very large numbers, etc.

*The dystopian nature of the setting is a post-apocalyptic anti-enlightenment agrarian non-industrial society.

*The primary characters are a Kabbalistic group of quite illegal engineers and mathematicians rediscovering measurement, algebra, etc.
Le Guin remarked in a brief comment preceding the story in the anthology that "The Masters" had been her first actual science fiction story.


text:
Q: I need to do a membrane pcb for a keyboard or a flexible PCB like a membrane PCB I need to design a membrane PCB for a keyboard and/or flexible double sided PCB that works like a membrane PCB.  My problem here is that I don't know how to do the buttons, with one contact of the button in one layer and the other contact in another layer.  Similar to what can be seen in this image:

Also: Which software is better for doing this, Proteus or Altium?

A: With custom PCB's like flex or membrane usually the manufacturer will take gerbers, so it doesn't matter what software you use. But the manufacturer will have different requirements than a normal PCB. Pick a manufacturer, then work with them on how to draw up the stackup, minimum trace and contact requirements.
Altium does have the ability to create layers\stackup for flex circuits.


text:
Q: Logistic Regression: How to find top three feature that have highest weights? I am working on UCI breast cancer dataset and trying to find the top 3 features that have highest weights. I was able to find the weight of all features using logmodel.coef_ but how can I get the feature names? Below is my code, output and dataset (which is imported from scikit).
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression

cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, stratify=cancer.target, random_state=42)

logmodel = LogisticRegression(C=1.0).fit(X_train, y_train)
logmodel.coef_[0]

Above code outputs weights array. Using these weights how can I get the associate feature names?
Output:
    array([  1.90876683e+00,   9.98788148e-02,  -7.65567571e-02,
             1.30875965e-03,  -1.36948317e-01,  -3.86693503e-01,
            -5.71948682e-01,  -2.83323656e-01,  -2.23813863e-01,
            -3.50526844e-02,   3.04455316e-03,   1.25223693e+00,
             9.49523571e-02,  -9.63789785e-02,  -1.32044174e-02,
            -2.43125981e-02,  -5.86034313e-02,  -3.35199227e-02,
            -4.10795998e-02,   1.53205924e-03,   1.24707244e+00,
            -3.19709151e-01,  -9.61881472e-02,  -2.66335879e-02,
            -2.44041661e-01,  -1.24420873e+00,  -1.58319440e+00,
            -5.78354663e-01,  -6.80060645e-01,  -1.30760323e-01])

Thanks. I would really appreciate any help on this.

A: This will do the job:
import numpy as np
coefs=logmodel.coef_[0]
top_three = np.argpartition(coefs, -3)[-3:]
print(cancer.feature_names[top_three])

This prints
['worst radius' 'texture error' 'mean radius']

Note that these features are the top three, but they are not necessarily sorted among themselves. If you want them to be sorted, you can do:
import numpy as np
coefs=logmodel.coef_[0]
top_three = np.argpartition(coefs, -3)[-3:]
top_three_sorted=top_three[np.argsort(coefs[top_three])]
print(cancer.feature_names[top_three_sorted])

A: n=len(data.columns)-1

percentage_change=[]

for i in range (n):

    cp=(difference[i]/wei[i])*100

    percentage_change.append(cp)

columns=list(data.columns.values)

indices=sorted(range(len(percentage_change)), key=lambda i: percentage_change[i])[-3:]

print("the top 3 features which have higher % change in weights ")

for j in indices:

    print(columns[j])


text:
Q: Error while Connecting to a ec2 instance through VSCode Remote SSH I have tried to connect to my amazon instance through SSH before through a program called Bitvise SSH, but today I found out there is a way to directly connect to my instance through a function in VSCode.
my config
This is my config file for the SSH connection for the VS code SSH connection.
And apparently when I try to connect to the instance I get the error
[15:49:16.843] Log Level: 2
[15:49:16.846] remote-ssh@0.70.0
[15:49:16.846] win32 x64
[15:49:16.847] SSH Resolver called for "ssh-remote+ec2-user", attempt 1
[15:49:16.847] "remote.SSH.useLocalServer": false
[15:49:16.848] "remote.SSH.showLoginTerminal": false
[15:49:16.848] "remote.SSH.remotePlatform": {}
[15:49:16.848] "remote.SSH.path": undefined
[15:49:16.848] "remote.SSH.configFile": C:\Users\algoo\.ssh\config\
[15:49:16.848] "remote.SSH.useFlock": true
[15:49:16.848] "remote.SSH.lockfilesInTmp": false
[15:49:16.848] "remote.SSH.localServerDownload": auto
[15:49:16.848] "remote.SSH.remoteServerListenOnSocket": false
[15:49:16.849] "remote.SSH.showLoginTerminal": false
[15:49:16.849] "remote.SSH.defaultExtensions": []
[15:49:16.849] "remote.SSH.loglevel": 2
[15:49:16.849] "remote.SSH.serverPickPortsFromRange": {}
[15:49:16.849] "remote.SSH.enableDynamicForwarding": true
[15:49:16.849] "remote.SSH.serverInstallPath": {}
[15:49:16.850] SSH Resolver called for host: ec2-user
[15:49:16.850] Setting up SSH remote "ec2-user"
[15:49:16.886] Using commit id "899d46d82c4c95423fb7e10e68eba52050e30ba3" and quality "stable" for server
[15:49:16.890] Install and start server if needed
[15:49:19.539] Checking ssh with "ssh -V"
[15:49:19.607] > OpenSSH_for_Windows_8.6p1, LibreSSL 3.3.3

[15:49:19.614] Using SSH config file "C:\Users\algoo\.ssh\config\"
[15:49:19.614] Running script with connection command: ssh -T -D 59628 -F "C:\Users\algoo\.ssh\config\" "ec2-user" bash
[15:49:19.617] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[15:49:19.860] > u]0;C:\WINDOWS\System32\cmd.exe
[15:49:19.861] Got some output, clearing connection timeout
[15:49:19.874] > sage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
>            [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
>            [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
>            [-i identity_file] [-J [user@]host[:por
[15:49:19.889] > t]] [-L address]
>            [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
>            [-Q query_option] [-R address] [-S ctl_path] [-W host:port]
>            [-w local_tun[:remote_tun]] destination [command]
> The process tried to write to a nonexistent pipe.
[15:49:21.170] "install" terminal command done
[15:49:21.171] Install terminal quit with output:            [-w local_tun[:remote_tun]] destination [command]
[15:49:21.171] Received install output:            [-w local_tun[:remote_tun]] destination [command]
[15:49:21.172] Failed to parse remote port from server output
[15:49:21.173] Resolver error: Error:
    at Function.Create (c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:430425)
    at Object.t.handleInstallOutput (c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:429068)
    at Object.t.tryInstall (c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:524212)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:487216
    at async Object.t.withShowDetailsEvent (c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:490561)
    at async Object.t.resolve (c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:488295)
    at async c:\Users\algoo\.vscode\extensions\ms-vscode-remote.remote-ssh-0.70.0\out\extension.js:1:564197
[15:49:21.177] ------

[16:02:54.387] ConfigFileWatcher: start watching file:///c%3A/Users/algoo/.ssh/config/
[16:02:54.387] ConfigFileWatcher: adding save listener
[16:02:54.387] ConfigFileWatcher: adding close listener

is there anything that i missed out?

A: [15:49:16.848] "remote.SSH.path": undefined

^^^ Try setting the remote.SSH.path in settings.json and see if that works. I use the one that comes with Git Bash
These are my settings by the way:
  "remote.SSH.enableDynamicForwarding": false,
  "remote.SSH.lockfilesInTmp": true,
  "remote.SSH.path": "%ProgramFiles/Git/usr/bin/ssh.exe",
  "remote.SSH.useLocalServer": true,


text:
Q: Order queryset by alternating value I have the following model:
class Entry(models.Model):
    name = models.Charfield(max_length=255)
    client = models.Charfield(max_length=255)

client is the name of the client as could have values like facebook, google, and so on.
Is it possible to order the queryset so that the result is alternating the values of client?
What I expect is something like this:
Entry.objects.order_by('alternate client') -->

| client   | name   |
| google   | robert |
| facebook | linda  |
| google   | kate   |
| facebook | jack   |
| google   | nina   |
| facebook | pierre |

I am using django2.x and postgres if that helps.
EDIT:
Some additional info / requirements.

*

*I have about 10 to 20 differtent clients

*Entry does also have a created DateField. If possible result should also be ordered by date

*I want to use pagination for Entry so solution should be using django's ORM

A: Since you use Postgres you can use its Window Functions which perform a calculation across a set of table rows that are somehow related to the current row. Another good information relies in the fact that you use Django2.x which supports Window Functions(Django docs) which allows adding an OVER clause to Querysets.
Your use-case can be resolved with Single ORM query like:
from django.db.models.expressions import Window
from django.db.models.functions import RowNumber
from django.db.models import F

results = Entry.objects.annotate(row_number=Window(
    expression=RowNumber(),
    partition_by=[F('client')],
    order_by=F('created').desc())
).order_by('row_number', 'client')

for result in results:
    print('Id: {} - client: {} - row_number {}'.format(result.id, result.client, result.row_number))

Output:
Id: 12 - client: facebook - row_number 1
Id: 13 - client: google - row_number 1
Id: 11 - client: facebook - row_number 2
Id: 8 - client: google - row_number 2
Id: 10 - client: facebook - row_number 3
Id: 5 - client: google - row_number 3
Id: 9 - client: facebook - row_number 4
Id: 3 - client: google - row_number 4
Id: 7 - client: facebook - row_number 5
Id: 2 - client: google - row_number 5
Id: 6 - client: facebook - row_number 6
Id: 1 - client: google - row_number 6
Id: 4 - client: facebook - row_number 7

The raw SQL looks like:
SELECT
"orm_entry"."id",
"orm_entry"."name",
"orm_entry"."client",
"orm_entry"."created",
ROW_NUMBER() OVER (PARTITION BY "orm_entry"."client" ORDER BY "orm_entry"."created" DESC) AS "row_number"
FROM "orm_entry"
ORDER BY "row_number" ASC, "orm_entry"."client" ASC

Window functions are declared just as an aggregate function followed by an OVER clause, which indicates exactly how rows are being grouped. The group of rows onto which the window function is applied is called "partition".
You can notice that we grouped the rows by 'client' field and you can conclude that in our example we will have the two partitions. First partition will contain all the 'facebook' entries and second partition will contain all the 'google' entries. In its basic form, a partition is no different than a normal aggregate function group: simply a set of rows considered "equal" by some criteria, and the function will be applied over all these rows to return a single result.
In your example we can use the row_number window function which simply returns the index of the current row within its partition starting from 1. That helped me to establish the alternating output in order_by('row_number', 'client').
Additional information:
If you want to achieve an order like this:
'facebook','facebook', 'google','google','facebook','facebook','google','google'
or
'facebook','facebook','facebook','google','google','google','facebook', 'facebook','facebook'
You will need to do one small math related modification of the previous query like:
GROUP_SIZE = 2
results = Entry.objects.annotate(row_number=Window(
    expression=RowNumber(),
    partition_by=[F('client')],
    order_by=F('created').desc())
).annotate(row_number=(F('row_number') - 1)/GROUP_SIZE + 1).order_by('row_number', 'client')

for result in results:
    print('Id: {} - client: {} - row_number {}'.format(result.id, result.client, result.row_number))

Output:
Id: 12 - client: facebook - row_number 1
Id: 11 - client: facebook - row_number 1
Id: 8 - client: google - row_number 1
Id: 13 - client: google - row_number 1
Id: 10 - client: facebook - row_number 2
Id: 9 - client: facebook - row_number 2
Id: 3 - client: google - row_number 2
Id: 5 - client: google - row_number 2
Id: 7 - client: facebook - row_number 3
Id: 6 - client: facebook - row_number 3
Id: 1 - client: google - row_number 3
Id: 2 - client: google - row_number 3
Id: 4 - client: facebook - row_number 4

You can notice that GROUP_SIZE constant defines how many items will be in the each alternating group.
P.S.
Thank you for asking this question because it helped me to better understand the Window Functions.
Happy coding :)

A: Thats not the most performant way, but works:
from itertools import zip_longest
from django.db.models import Case, When

grouped_pks = []
for client in Entry.objects.values_list('client', flat=True).distinct():
    grouped_pks.append(
        Entry.objects.filter(client=client).values_list('pk', flat=True)
    )

alternated_pks = [
    x for x in
    filter(
        None,
        sum(zip_longest(*grouped_pks), ())
    )
]
alternated_pks_order = Case(
    *[
        When(pk=pk, then=position)
        for position, pk in enumerate(alternated_pks)
    ]
)

entries = Entry.objects.filter(pk__in=alternated_pks).order_by(alternated_pks_order)
for entry in entries:
    print('id: {} - client: {}'.format(entry.id, entry.client))

Expected output:
id: 8901 - client: google
id: 8890 - client: facebook
id: 8884 - client: google
id: 8894 - client: facebook
id: 8748 - client: google
id: 8891 - client: facebook
id: 8906 - client: google
id: 8909 - client: facebook
id: 8888 - client: google
id: 8895 - client: facebook
id: 8919 - client: google
id: 8910 - client: facebook
id: 8878 - client: google
id: 8896 - client: facebook
id: 8916 - client: google
id: 8902 - client: facebook
id: 8917 - client: google
id: 8885 - client: facebook
id: 8918 - client: google
id: 8903 - client: facebook
id: 8920 - client: google
id: 8886 - client: facebook
id: 8904 - client: facebook
id: 8905 - client: facebook
id: 8887 - client: facebook
id: 8911 - client: facebook
id: 8897 - client: facebook
id: 8912 - client: facebook
id: 8898 - client: facebook
id: 8899 - client: facebook
id: 8914 - client: facebook
id: 8900 - client: facebook
id: 8915 - client: facebook

This is python3 code, but if you want to use it with python 2, change the zip_longest function to izip_longest.
This code is nice, because we still work with Queryset, so all other Sorting, Ordering, Managers, Pagination and other stuff will still work.

A: Maybe the following will work, with numpy module
import numpy
queryset = Entry.objects.all()

''' catch the number of distinct Entry considering the client fields '''

queryset_client_entries = Entry.objects.distinct('client')

new_list = list(numpy.resize(queryset_client_entries, queryset.count()))
''' An alternative list of clients depending on the length of queryset '''


text:
Q: give every occurrence of a unique field in mongodb database a new unique field I have a database that has 1.3 million documents with the following schema:
{
    "_id" : ObjectId("592b04226e46690549744e71"),
    "game" : "xyz",
    "game_id" : "161936",
    "username" : "jomonsugi",
    "rating" : 10,
    "comment" : "Good game. "
}

Throughout the database, there are multiple occurrences of the same username. I want to add a new field that gives every user their own unique id. Example: "user_id" : "12345". So in the example above every document in the db with "username" : "jomonsugi" would have a field/value added to it with the same unique user_id for every occurrence.
I have something that works, but it takes hours (literally) and as the db grows it will take days. I use distinct to get a list of all users from the db, then I give all users a unique id number in a dictionary {"username" : "user_id"} then I use update:
client = MongoClient()
    db = client.bgg
    for k,v in id_dic.items():
        print(k,v)
        db.game_comments.update({ 'username': k } ,{ '$set' : { 'user_id': v } }, multi = True )

This works just fine, and I have seen post on how slow the update method is, however is there a way to accomplish this task any faster? Maybe a mongo function I am missing?


text:
Q: Added new columns to table and slow down the whole database .. Why? I've got a table USERDATA and I added few new columns to it.
All are NOT NUL and default 0 or 1. However, my website became slow after doing that.
I mean really slow. And it's because of this query script on my website:
$num_rows = $db->doQuery('SELECT TOP 50 IDNum, IDName, Nation, (SELECT SUM(Loyalty) FROM USERDATA WHERE USERDATA.Knights = KNIGHTS.IDNum AND USERDATA.Authority = 1) as ClanLoyalty, (SELECT SUM(MannerPoint) FROM USERDATA WHERE USERDATA.Knights = KNIGHTS.IDNum AND USERDATA.Authority = 1) as ClanManner FROM KNIGHTS WHERE KNIGHTS.IDNum NOT IN (1,15001) ORDER BY ClanLoyalty DESC, IDName ASC');

It worked all good previously but after adding the new columns which are not included at all in this query above .. it still slow down the website to request TOP 50 .. basically the SUM query is doing it .. why these new columns could produce such a problem?
USERDATA has 32k rows only and it worked all good previously. I didn't specify constaint, could be this the issue?
I use MSSQL Server 2005.

A: Change your query like this.
SELECT TOP 50 IDNum,
              IDName,
              Nation,
              Sum(Loyalty)     ClanLoyalty,
              Sum(MannerPoint)  ClanManner
FROM   KNIGHTS
       LEFT JOIN USERDATA
              ON USERDATA.Knights = KNIGHTS.IDNum
                 AND USERDATA.Authority = 1
WHERE  KNIGHTS.IDNum NOT IN ( 1, 15001 )
Group by IDNum,IDName,Nation
ORDER  BY ClanLoyalty DESC,
          IDName ASC


text:
Q: Block single port forwarding in Windows I have a Windows computer with IP Forwarding activated. However, I want to forward everything except the traffic that goes to port 53 in UDP. In Linux, this is easily solved with iptables: iptables -A FORWARD -p udp --dport 53 -j DROP.
How can I do this with Windows? I think the firewall hasn't got the option of managing forward rules, only input and output.
Thanks for any suggestion.


text:
Q: Using Variable declared in Declare section(Anonymous Block) I want to use a declared variable, that I declare in Declare section ,in Begin End section of anonymous block with out using into statement.Is that possible??
E.g
Declare
   week number :=6;
Begin
   select col1,col2+week from table;
end;

A: Since an anonymous block cannot return any data to the caller, what would you want to happen if this block was executed?  You couldn't return a cursor to the caller so if you're not selecting the data into local variables, I'm not sure what you want to happen.
Potentially, you just want a SQL*Plus script, i.e.
SQL> variable week number;
SQL> exec :week := 6;

PL/SQL procedure successfully completed.

SQL> ed
Wrote file afiedt.buf

  1* select empno, hiredate+:week from emp
SQL> /

     EMPNO HIREDATE+
---------- ---------
      7369 23-DEC-80
      7499 26-FEB-81
      7521 28-FEB-81
      7566 08-APR-81
      7654 04-OCT-81
      7698 07-MAY-81
      7782 15-JUN-81
      7788 25-APR-87
      7839 23-NOV-81
      7844 14-SEP-81
      7876 29-MAY-87

     EMPNO HIREDATE+
---------- ---------
      7900 09-DEC-81
      7902 09-DEC-81
      7934 29-JAN-82
      1234

15 rows selected.

A: It's impossible to use select in an oracle pl-sql block without using INTO
because oracle doesn't accept select statement without use of into statement
so, your block after modify will become like this :
Declare
   week number :=6;
   Column1 table.col1%type;
   Column2 table.col2%type;
Begin
   select col1,col2+week into Column1, Column2 from table;
end;


text:
Q: How to generate HTML using ASP.NET MVC helper without the id property? I need a certain tag to be repeated many times inside a page. I do prevent the possible server requests with the help of JavaScript. The problem is that the helper generated the html which already contains and id with the name of the property on the model.
I can of course delete the id after receiving the HTML.
Or have an empty id by writing something like:
Html.Dropdown(something , new {id=""})

But all these solutions seem some workarounds rather than the semantically correct ones


text:
Q: is it possible to store more than one value in the same session object if yes then tell me how through code .? is it possible to use map to retrieve session object ?
         For Example: HTTPSession session=request.getSession();
          session.setAtrributes("Avr",atr);

A: To store multiple values in one session object you can use collections.Here is the code
List<String> names = new ArrayList<String>();
names.add("Test1");
names.add("Test2");

HTTPSession session=request.getSession();
session.setAtrribute("Avr",names);

When you get the value from session you need to cast it.
List<String> values = (ArrayList)session.getAttribute("Avr");


text: Q: How to scrape a webpage that uses JavaScript to build the HTML? I have a scraper made in python2 using requests and beautifulsoup. We do not want to use selenium. Now the website we are scraping has changed its some page. The page is now building the elements on the page using javascript. I want to scrape the page in which the source code is getting generated with javascript - how can this be done?


text:
Q: Very strange plot from basic ASCII file data Working with Jupyter Lab!
I loaded a simple ASCII file (as I've done 100s of times before...), with three columns and 2000+ lines. I did it with
with open(file) as f:
    d = f.readlines()

and also with NumPy d = np.loadtxt(file, delimiter=',') to see if something would change.
All values in the 2nd column (Latitude) are -32. and something and all values in the 3rd column (Longitude) are -52. and something. However, de variation of the data is about the 5th decimal number... (I think this is making things weird!)
When I printed the data on the screen, it seems ok! But when I try to plot them, I got pretty weird stuff... the numbers in the X and Y axis are nonsense, especially the one scaling the x-axis. 1e-5-5.2103e1
I open the data in a spreadsheet (Libre Calc), and there the plot seems alright. Then I save it with another name and tried to load in the Jupyter again and got the same weird result.
I also tried it also using a different computer... same result!
Tried a script using Atom... same result!
Can someone give a clue about what is going on?
The file is shared at:
https://drive.google.com/file/d/1eDwlijQ7y3KoIRafoE00eqK3UYsIcMvf/view?usp=sharing
First lines o the file...
9738,-32.13689233,-52.10339483
9739,-32.13689233,-52.10339483
9740,-32.13689233,-52.10339483
9741,-32.13689233,-52.10339483
9742,-32.13689233,-52.10339483
9743,-32.13689233,-52.10339483
9744,-32.13689233,-52.10339483
9745,-32.13689233,-52.10339483
9746,-32.13689233,-52.10339483
9747,-32.13689233,-52.10339483
9748,-32.13689233,-52.10339483
9749,-32.13689433,-52.10339417
9750,-32.13689433,-52.10339417
9751,-32.13689433,-52.10339417
9752,-32.13689433,-52.10339417
9753,-32.13689433,-52.10339417
9754,-32.13689433,-52.10339417
9755,-32.13689433,-52.10339417
9756,-32.13689433,-52.10339417
9757,-32.13689433,-52.10339417
9758,-32.13689433,-52.10339417
9759,-32.13688733,-52.10339367

A: It looks like your plot is correct, even though the scaling of the axes is quite strange (likely due to the very small range). I plotted the same data using Altair, which was able to handle the axes ranges much better:
import pandas as pd
import altair as alt
with open("lat_long.csv", newline="") as f:
    frame = pd.read_csv(f, delimiter=",", header=None, names=["index", "longitude", "latitude"])

alt.Chart(frame).mark_circle(size=10).encode(
    alt.X('latitude',
        scale=alt.Scale(zero=False)
    ),
    alt.Y('longitude',
        scale=alt.Scale(zero=False)
    ),
).interactive()

The result matches yours, except for the more sensible axes:

My guess is that the pandas plotter is just doing something strange with displaying the axes, but the data is being read in correctly.

A: This is how matplotlib displays very large and small tick markers. For example, to read the y-axis you take that number at the top and add each tick marker. I'll admit, the number on the x-axis is weird, but you can see a recognizable prefix in there: -5.2103e1. The 1e-5 might just be signifying the decimal place the ticks start at. Looking through the file, the plot makes sense, and the labels do as well.


text:
Q: Is disconnecting a network cable different from VMware "Connected" option? I have an application that connects to a database and retrieves information from it. The way it is written is: for every request received, create a new connection to the DB server and retrieve data.
When testing, if the network cable is removed from the host, and reconnected, the application goes back to retrieving data normally. However, if the "connected" option is unchecked and rechecked to simulate a disconnection, the application cannot connect to the database again, even though all handlers etc are created for each connection.
Question: Is disconnecting the network cable from the host different than unchecking the "Connected" option in VM configuration?

A: No there should be no difference, but if you have transient ports set on your switch it may give you a new port number which may effect the network reconnection in an unexpected manner.
The vswitches don't act like normal switches either, they are more aware of the VM configuration state, so may also be effecting what happens. You would run a wireshark on a port that is in promiscuous mode to try to isolate the problem.

A: No, there is no difference. Unchecking 'Connected' is just breaking the virtual link between the card and vSwitch:
Unchecked 'Connected' and clicked 'OK':
Nov 8 09:11:28 mtasink8 kernel: eth1: NIC Link is Down
Checked 'Connected' and clicked 'OK':
Nov 8 09:11:40 mtasink8 kernel: eth1: NIC Link is Up 10000 Mbps


text:
Q: Exception on deploying myfaces app on tomcat I am trying to deploy my JSF (myfaces) application on tomcat server but as soon as I deploy I get the following exception messages in the logs :
16 Mar, 2012 6:53:33 PM org.apache.catalina.util.LifecycleBase start
INFO: The start() method was called on component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Px10Application]] after start() had already been called. The second call will be ignored.
16 Mar, 2012 6:53:35 PM org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage loadLibraries
SEVERE: Error Loading library: /WEB-INF/facelets/jsfcomps.taglib.xml
java.io.FileNotFoundException: /WEB-INF/facelets/jsfcomps.taglib.xml
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.loadLibraries(FaceletViewDeclarationLanguage.java:2458)
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.createCompiler(FaceletViewDeclarationLanguage.java:2099)
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.initialize(FaceletViewDeclarationLanguage.java:2386)
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.<init>(FaceletViewDeclarationLanguage.java:346)
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguageStrategy.<init>(FaceletViewDeclarationLanguageStrategy.java:52)
    at org.apache.myfaces.view.ViewDeclarationLanguageFactoryImpl.initialize(ViewDeclarationLanguageFactoryImpl.java:106)
    at org.apache.myfaces.view.ViewDeclarationLanguageFactoryImpl.getViewDeclarationLanguage(ViewDeclarationLanguageFactoryImpl.java:79)
    at org.apache.myfaces.application.ViewHandlerImpl.getViewDeclarationLanguage(ViewHandlerImpl.java:179)
    at org.apache.myfaces.shared.application.DefaultViewHandlerSupport.checkResourceExists(DefaultViewHandlerSupport.java:546)
    at org.apache.myfaces.shared.application.DefaultViewHandlerSupport.handleSuffixMapping(DefaultViewHandlerSupport.java:466)
    at org.apache.myfaces.shared.application.DefaultViewHandlerSupport.calculateViewId(DefaultViewHandlerSupport.java:94)
    at org.apache.myfaces.application.ViewHandlerImpl.deriveLogicalViewId(ViewHandlerImpl.java:118)
    at org.apache.myfaces.lifecycle.RestoreViewExecutor.execute(RestoreViewExecutor.java:157)
    at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
    at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)

What does this mean & how do I recitfy this?
Previously I was working with Mojarra implementation on glassfish server for this project, where everything worked fine. This happens after I switched to MyFaces implementation on  Tomcat server. I included the dependencies for MyFaces by adding following to my POM:
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-api</artifactId>
            <version>2.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-impl</artifactId>
            <version>2.1.6</version>
        </dependency>