Should I keep foreign keys in sync with references when using POCOs

Question: I see a lot of examples on using EF code first with POCOs that show something like this:
public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

Now, look at the Blog property. Should not it be like this instead:
private Blog blog;
public virtual Blog Blog
{
    get
    {
        return blog;
    }
    set
    {
        blog = value;
        if (blog != null)
        {
            BlogId = blog.BlogId;
        }
    }
}

I mean, since you already are "polluting" your model with the foreign key, should not you at least keep it in sync with the reference? Or you should not rely on BlogId when reading data anyway (eg. like you want to know if a specific BlogId is on a list). Or maybe there is a magic property on DbContext (like KeepForeingKeysPropertiesSyncronizedWithReferences) that does that to me and I am the only sad programmer that are woried about this? Or am I paranoid? (also, sorry for my poor english)
EDIT
Sorry for that - this really was a stupid question. Stefan is right, EF really does this for you. I wasn't seen this because the references I was passing was loaded with AsNoTracking(). Only in this condition you will have a reference with ID and the foreing key field will be 0. As long as you pass a reference that is already on the context, it should work.
Comment: Don't know about EF, but had you used NHibernate you would not put in the BlogId property at all.
Comment: I think that having the possibility of using the BlogId it is nice, so I do not need to have a Blog reference and still can save the association. I'm just confused about mantain it in sync - for me it looks like the obvious thing to do but I never seen someone doing it so maybe I am wrong :/
Answer: You don't need to do this per se, EF does this for you.
If you set the independent association property, EF will synchronize the foreign key property to reflect your change and vice versa. It doesn't happen immediately automatically mind you, I think this happens after calling SaveChanges but I'm not sure.
If you want to know why some people use the foreign key property: it's more convenient in detached apps like web apps. When you need to scale your app, it can also help to improve performance (read this in a recent MS blog post somewhere).
Basically, you only need to do this yourself if you're mixing and matching; when in one method you're using the independent association property and in another you're using the foreign key property.
Answer: Database First code generated.
It appears you do yes otherwise you will receive the following error.

A referential integrity constraint violation occurred: The property
  values that define the referential constraints are not consistent
  between principal and dependent objects in the relationship.

Principle being your Post object , dependent  being the Blog object.
when you attempt to attach your unallocated context free POCO back to the context
EF 4.1 DBContext:
using (TransactionScope scope = new TransactionScope())
using (ITAMdbContext db = new ITAMdbContext())
{
   db.Entry(post).State = System.Data.EntityState.Unchanged; // error here
   db.Entry(post).State = System.Data.EntityState.Modified;
   db.SaveChnages();

This error is resolved by..
using (TransactionScope scope = new TransactionScope())
using (ITAMdbContext db = new ITAMdbContext())
{
   post.BlogId = post.Blog.BlogId;
 // fix the broken FK value, EF will not do this for
 // you, it does not know if post.BlogId or the post.Blog.BlogId should be chosen.

   db.Entry(post).State = System.Data.EntityState.Unchanged;
   db.Entry(post).State = System.Data.EntityState.Modified;
   db.SaveChnages();

doing it your way is valid if your POCO objects are not auto generated.
the reason you set post to Unchanged then set it to Modified is because the first Entry().State  set on an object will cascade the same state to all child objects ! horrible but that's the way it appears to work.
then when you call it again it only modifies the post object. This stops child objects being modified or added.
EDIT: This is no longer required, its done for you


Need declare protocol in objective c?

Question: I wonder if it is needed to declare the protocol.
So, I delete a part that protocol declare code.
I thought that it will happen compile error.
but, Has been running without any problems.
Why need protocol declare part?
#import <UIKit/UIKit.h>

@interface SingleComponentPickerViewController : UIViewController {
// <UIPickerViewDelegate, UIPickerViewDataSource> {   ==> protocol declare part
    IBOutlet    UIPickerView *singlePicker;
                NSArray *pickerData;
}
@property (nonatomic, retain) UIPickerView *singlePicker;
@property (nonatomic, retain) NSArray *pickerData;
- (IBAction)buttonPressed:(id)sender;
@end

<UIPickerViewDelegate, UIPickerViewDataSource> <= this is what feature?
                                                  When omit this, excute without any problem.

Below is picture After compiled screen.
It has no issues.
And excute without any problems..
Answer: You are not declaring the Protocol here, you are merely specifying that the your class SingleComponentPickerViewController follows the protocols you specify.
The protocol needs to be specified if you are using any components and are setting you SingleComponentPickerViewController as their delegate. This is so the compiler knows that your class follows that specific protocol and you have implemented any required protocol methods.
Answer: <UIPickerViewDelegate, UIPickerViewDataSource>

It doesn't declare a protocol, it tells the compiler that your class conforms to the listed protocols.
It's needed, so other classes can know your class conforms to their protocol(s). If you omit them, you won't get a compiler error, but the delegate methods you declared in your class may not be called.
Comment: the delegate methods *will* be called, but you will get a warning from the compiler when setting the delegate as the compiler has no way to check that the said object conforms to the required protocol.

Need declare protocol in objective c?


Unable to apply patch generated with diff on SunOS server

Question: I generated a patchfile of 2 directories using this command:
diff -ur source-20110125 source > mailpatch3.patch

Now I would like to apply the patch, doing this:
patch -p1 < mailpatch3.patch

But it then asks me for the file to patch. Why?
Something that looks strange to me in the patch file: there are a lot of "common subdirectories" lines. Like this:
Common subdirectories: source-20110125/ac_depository and source/ac_depository
Common subdirectories: source-20110125/ac_depository_jar and source/ac_depository_jar
Common subdirectories: source-20110125/_backoffice and source/_backoffice
Common subdirectories: source-20110125/_csvexport and source/_csvexport
Common subdirectories: source-20110125/_foundation and source/_foundation
Common subdirectories: source-20110125/_impex and source/_impex

And I don't really know why they're there.
The rest of the patch looks normal.
Answer: Most likely you have the wrong -p setting for trimming prefixes from your paths.  If you were below the two source directories when generating the patch, then you should be inside the source directory to apply the patch with -p1.
Comment: I should only have to strip one. However, for the sake of making sure, I've tested -p 0 to 9. Nothing worked.


Values of $a$ for which the series converges

Question: $$\sum_{n=1}^{+\infty}\frac{\sqrt{an + 2} - 3\sqrt{n+1}}{4n}$$
The only thing I suspect I could do is to split the series in two as follows:
$$\sum_{n=1}^{+\infty}\frac{\sqrt{an + 2}}{4n} - \sum_{n=1}^{+\infty}\frac{3\sqrt{n+1}}{4n}$$
From that, I can conclude that the second series diverges, but I don't know what to do next.
Answer: Hint: Multiply top and bottom by $\sqrt{an+2}+3\sqrt{n+1}$  and things should become clear. There will be precisely one "good" $a$.
Remark:  Splitting is not good. We end up looking at the "difference" between two divergent series.
Comment: For $a=9$, we have convergence. For the absolute value of the $n$-th term is $\lt \frac{7}{12n^{3/2}}$. To deal with $a\ne 0$, maybe first note the series is undefined for large $n$ if $a$ is negative, so we only care about positive $a$. After a while sign does not change, so a Limit Comparison with $\sum n^{-1/2}$, which diverges, tells us the series diverges.
Comment: Informally, eliminating that term makes the thing behave like a constant times $\sum \frac{1}{n^{3/2}}$, which converges. If we still have a constant times $n$ in the numerator, the terms are "too big" for the sum to exist.
Comment: When I do that, I end up with $\frac{n(a-9) - 7}{4n(\sqrt{an + 2} + 3\sqrt{n+1}}$. Can I conclude that for the series to converge, I need to eliminate $n(a-9)$, which will mean that it will converge for $a = 9$, or do I need some extra steps before that conclusion? Maybe checking for other values somehow?
Comment: @Proka As an unrelated question, how is eliminating $n(a-9)$ making  the series converge? I'm not understanding your work.
Comment: @VishwaIyer: Well, if $n(a-9)$ is eliminated, I am left with $\frac{-7}{4n(\sqrt{an + 2}+3\sqrt{n+1})}$ and I can conclude that it converges based on the comparison test (I just translated it from my native language, not sure if it's actually called "comparison test" in English).
Comment: If $a=9$, the terms have absolute value $\le \frac{7}{12n^{3/2}}$.
Answer: For $a=0$ you don't have convergence, for $a\neq0$ you can write
$$\sum_{n=1}^{+\infty}\frac{\sqrt{an + 2} - 3\sqrt{n+1}}{4n}=$$$$=\sum_{n=1}^{+\infty}\frac{1}{4n}\left[\sqrt{an}\left(1+\frac{1}{an}+o\left(\frac{1}{n}\right)\right)-3\sqrt{n}\left(1+\frac{1}{n}+o\left(\frac{1}{n}\right)\right)\right]\ ,$$
in order to have convergence you need the leading term to be zero, i.e. $\sqrt{a}=3$, i.e. $a=9$.


Reflections of circles through a circle are circles

Question: To make things easier, we will try to reflect some general circle through the unit circle. We can use the inverse of the Cayley transform to map our analytic arc in the $z$-plane to the real line in the $\zeta$-plane, apply reflection there, then map it all forward using the Cayley transform. The resulting transformation is $1/\overline{z}$.
This is where I fumble. I can't figure out how to map a generic circle. Am I to take four points $\lbrace u,v,w,x \rbrace \subset \lbrace z \ |z\in \mathbb{C}, r\in \mathbb{R}, |z-a|=r \rbrace$ and prove that $\lbrace 1/\overline{u},1/\overline{v},1/\overline{w},1/\overline{x} \rbrace$ are concyclic? Thank you all for your time.
Comment: Rather take four points $\lbrace u,v,w,x \rbrace \subset \lbrace z \ |z\in \mathbb{C}, r\in \mathbb{R}, |z-a|\color{red}{=}r \rbrace$ and prove that $\lbrace 1/\overline{u},1/\overline{v},1/\overline{w},1/\overline{x} \rbrace$ are concyclic.
Answer: The implicit equation of a circle of center $c$ and radius $r$ is
$$r^2=(z-c)\overline{(z-c)}=z\overline z-c\overline z-\overline cz+c\overline c,$$
or
$$z\overline z-c\overline z-\overline cz+d=0$$ where $\color{blue}{d=c\overline c-r^2}.$
Turning $z$ into $1/\overline z$,
$$\frac1{z\overline z}-\frac cz-\frac{\overline c}{\overline z}+d=0.$$
Multiplying by $\dfrac{z\overline z}d$ and rearranging,
$$\frac1d-\frac cd\overline z-\frac{\overline c}dz+z\overline z=0,$$
$$z\overline z-\frac cd\overline z-\frac{\overline c}dz+\frac{c\overline c}{d^2}=\frac{c\overline c}{d^2}-\frac1d.$$
This is a circle of center $\color{blue}{\dfrac cd}$ and radius $\color{blue}{\sqrt{\dfrac{c\overline c}{d^2}-\dfrac1d}}$.
Comment: @prototank: you are quite right, I didn't identify the coefficients correctly, I am fixing that. Also make sure to double check the radius formula, I may have messed up with mental calculation...
Comment: I see now. However, I am fairly certain that it should be $\frac{c}{c\overline{c}-r^2}$, simply by looking at the symmetry of the previous equation and also thinking that reflection in the unit circle should move the center to a scalar multiple of itself.
Answer: I also came up with something. Maybe it works. We know that four points are concyclic if they satisfy $$\frac{(u-v)(w-x)}{(w-v)(u-x)}\in\mathbb{R}$$
Then if we replace $\lbrace u,v,w,x \rbrace$ with $\lbrace 1/\overline{u},1/\overline{v},1/\overline{w},1/\overline{x} \rbrace$ then we get $$\frac{(1/\overline{u}-1/\overline{v})(1/\overline{w}-1/\overline{x})}{(1/\overline{w}-1/\overline{v})(1/\overline{u}-1/\overline{x})}=\overline{\frac{(1/u-1/v)(1/w-1/x)}{(1/w-1/v)(1/u-1/x)}}$$
$$=\overline{\frac{\frac{(v-u)}{vu}\frac{(x-w)}{xw}}{\frac{(v-w)}{vw}\frac{(x-u)}{xu}}} = \overline{\frac{(v-u)(x-w)}{(v-w)(x-u)}}$$
which is justthe same expression that we started with up to subtraction rearrangement, which is only a sign change. Thus this last expression is also real.
Comment: I realize now that the cross-ratio being real means that the points may be concyclic -or- collinear. Thus, I have only shown that circles and lines stay circles and lines.


Operand data type varchar is invalid for sum operator - Procedure Error Correction

Question: I am using SQL Server - 2005...
ALTER Proc [dbo].[ExamResult] (@Course_Id varchar(100), @Semester varchar(10))
as
begin
    declare @subjname varchar(100)
    declare @subjects varchar(7000)
    declare @subjectsselection varchar(7000)
    declare @SumSelection varchar(7000)
    declare @NoOfSubjects int
    set @NoOfSubjects = 0

    set @subjects = ''
    set @subjectsselection = ''
    set @SumSelection = ''

    DECLARE subject_cursor CURSOR
    FOR SELECT distinct Subject_Name FROM Exam_Result where course_id = @Course_Id And Semester = @Semester

    OPEN subject_cursor

    FETCH NEXT FROM subject_cursor
    INTO @subjname

    WHILE @@FETCH_STATUS = 0
    BEGIN
        set @subjects = @subjects + '[' + @subjname + '],'
        set @subjectsselection = @subjectsselection + 'Sum(Isnull([' + @subjname + '],0)) As [' + @subjname + '],'
        set @SumSelection = @SumSelection + 'Sum(Isnull([' + @subjname + '],0))+'

        set @NoOfSubjects = @NoOfSubjects + 1

        FETCH NEXT FROM subject_cursor
        INTO @subjname
    End
    CLOSE subject_cursor;
    DEALLOCATE subject_cursor;

    select @subjects = LEFT(@subjects, LEN(@subjects) - 1)
    select @subjectsselection = LEFT(@subjectsselection, LEN(@subjectsselection) - 1)
    select @SumSelection = LEFT(@SumSelection, LEN(@SumSelection) - 1)

    print @subjects
    print @subjectsselection
    print @SumSelection

    declare @query nvarchar(4000)

    set @query = 'select S.Enroll_Number, pvt.Student_Name, pvt.Course_Id, pvt.Semester, ' + @subjectsselection + ','
    set @query = @query + 'Exam_Type,' + @SumSelection + ' As Grand_Total, '
    set @query = @query + '(' + @SumSelection + ')' + '/' + convert(varchar(10),@NoOfSubjects) + ' As Avg'
    set @query = @query + ' From '
    set @query = @query + '(select Enroll_Number, Student_Name, Course_Id, Semester, Subject_Name, MarksObtained, Exam_Type from Exam_Result ) ps '
    set @query = @query + ' pivot(sum(MarksObtained) for Subject_Name in (' + @subjects + ')) as pvt'
    set @query = @query + ' inner join Stud_Info S on S.Enroll_Number = pvt.Enroll_Number '
    set @query = @query + ' where pvt.Course_Id = ''' + @Course_Id + ''' and pvt.Semester = ''' + @Semester + ''''
    set @query = @query + ' group by S.Enroll_Number, pvt.Student_Name, pvt.Course_Id, pvt.Semester, Exam_Type'
    print @query
    exec sp_executesql @query
end

Exam_Result table:
CREATE TABLE [dbo].[Exam_Result](
    [Result_Id] [int] IDENTITY(1,1) NOT NULL,
    [Enroll_Number] [varchar](50) NULL,
    [Student_Name] [varchar](100) NULL,
    [Course_Id] [varchar](50) NULL,
    [Semester] [varchar](50) NULL,
    [Subject_Id] [varchar](50) NULL,
    [Subject_Name] [varchar](50) NULL,
    [MarksObtained] [Varchar](10) NULL,
    [Exam_Type] [varchar](50) NULL)

Sample data query...
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','1','PS1','ps1','60','Final')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','70','Final')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','80','Final')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','20','Internal')
INSERT into Exam_Result VALUES('11147','Mr.Mack28','CIV','3','PS1','ps1','22','Internal')

Student_Info table: I just use for retrieved Student_Information like Enroll_Number...
CREATE TABLE [dbo].[Stud_Info](
    [Enroll_Number] [varchar](20) NOT NULL,
    [Student_Name] [varchar](20) NULL,
    [Course_Type] [varchar](20) NULL,
    [Course_Id] [varchar](20) NULL,
    [Semester] [varchar](20) NULL,
    [Password] [varchar](20) NULL,
    [Gender] [varchar](6) NULL,
    [City] [varchar](15) NULL,
    [Mobile_Number] [varchar](10) NULL)

It gives me error like this...

Msg 8117, Level 16, State 1, Line 1
  Operand data type varchar is invalid for sum operator.

Rahul: as per you answer I updated like this but it still gives error......
set @query = @query + ' pivot(sum(cast(MarksObtained as int)) for Subject_Name in (' + @subjects + ')) as pvt'

I think it gives error because I am using the MarksObtained column (as varchar(10))...plz give me a suggestion how I can convert varchar to int so that summation of total MarksObtained can be done.
Comment: If the column contains integer values, why did you declare it as VARCHAR?
Comment: Then convert it **in the application**. Don't store it in the database.
Comment: at last time v have ordered to mark it as varchar in case of any student is absent in that subject then we have to insert as ABS...dats way i want to convert it
Comment: oded - is it possible ?? let me try...
Answer: You can convert like this way:
SUM (CONVERT(int,<your varchar column>))

This will work if your varchar column actually holds numeric value. Otherwise, you can try casting it using cast function like:
sum(cast(varchar_column as int))

EDIT:
Created a sample table with just 2 column (name and marksobtained), both of type varchar(10) and inserted some data to it. So that my select * looks like
name            marksobtained
Mr. Anil             30
Mr. sunil            70
Mr. patel            70

Summed the marks like
select SUM(cast(marksobtained as int)) as 'totalmarksobtained' from sampletab

Which returned 170.
What values does @subjects have? Post some sample.
Comment: Mack, please share some sample data for `MarksObtained` column. Will try it once and let you know.
Comment: rahul - thanks for your instant reply but both still not working for me...i have updated my question..u can see it
Comment: Mack, sorry for delay in response. I tried and it worked. See my edit.
Comment: Rahul - its ok. thanks for giving me your important time... i'm unable to find your edit !!! plz tell me...
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/10919/discussion-between-mack28-and-rahul)
Comment: Rahul - ok... thanks but its not working in my cursor which i have described above ?? is there anything going wrong in my cursor / **sum** syntax....
Answer: you can use "cast" in your query
example:
select sum(cast(Enter_your_field_name as int)) from Table_name

Hope it works for you.


What is a positively skewed distribution that can include zero?

Question: I'm modelling data from a behavioural task. Participants do a few hundred trials. On each trial, they see a sequence of letters at a point on the screen and one of these letters appears surrounded by a white circle. Their task is to report the letter within the circle. Any response they make can be mapped onto a point in time on the trial relative to the white circle because there are no repeats in the sequences that they see. A response of the letter in the circle would have a value of 0; one letter before would have a score of -1; the letter after would have a score of 1 and so on. We've been modelling the distribution of these temporal errors with a mixture of a uniform distribution and some other, non-uniform distribution. Up until now the non-uniform distribution has been Gaussian, but certain theoretical considerations have led us to consider that we need a positively skewed component with a domain that is bounded at zero instead of the Gaussian. I considered using the lognormal distribution, but this is a bad choice because it is undefined at zero.
What positively skewed distributions can model values of zero and greater?
I'm using Matlab. Something that has a PDF written in that language would be great (I'm a scientist, not a statistician).
Comment: Truncating nearly any distribution below at $0$ is going to increase its skewness.  That gives you a huge array of possible solutions (and every solution can be expressed in such a form).  To keep this thread from being overly (and uselessly) broad, could you please be more specific about what you're modeling and what you're trying to accomplish?
Comment: Thanks @whuber. I've edited the post with more detail
Answer: You could take any distribution defined on $(0,\infty)$ and simply shift it to the left by a small $\epsilon$. Then you would get negative values in $(-\epsilon,0)$, which I guess is not what you are looking for.
Alternatively, your skewed component might derive from a two-stage data generating process that might either generate a zero or a nonzero value. If this sounds like something that might be present in your application, you might want to look into zero-inflation, i.e., mixtures between a point mass at zero and a second distribution, which in turn could be supported on $(0,\infty)$ or $[0,\infty)$.
Zero inflated models are more common with count-data, but there are applications for zero-inflated gamma distributions. And the gamma distribution has the advantage of being positively skewed. The skewness of a mixture is not overly hard to calculate.


Subscriptions does not send out "update" notifications

Question: I am logged in as user/1 and have subscribed to a particular node. I then edited the content of the node and have ticked the "Send subscriptions notifications" option.
I did not receive an "update" notification. Why might this be the case?
By the way, I've enabled the following modules:
* Subscriptions UI
* Subscriptions Mail (+ Mail Editor + Token)
* Content Subscriptions
I am logged in as user/1 and subscribed to a number of nodes. Updating them does not send email notifications.
The settings I've got turned on are as follows:
admin/config/system/subscriptions
Unlisted content types - none
Blocked content types - none
Node form position - Fieldset above node links
Node form visibility - Always display the fieldset
Expand the node form fieldset
admin/config/system/subscriptions/userdefaults
Nodify poster of own posts Send interval - As soon as possible
On updates - ticked
Send interval - Hidden
On updates - hidden
admin/config/system/subscriptions/intervals
1|As soon as possible 900|Every 15 minutes 3600|Hourly 10800|Every three hours 86400|Daily

Do I need to enable "* Taxonomy Subscriptions (e.g. forums!)" for the subscriptions to work?
Also, not sure if this is required, but I went to admin/config/system/mail-edit and added a template fornode-type-basic_page for the Subscriptions Mail module. However, this made no difference in email updates being sent :(
Answer:
First you need to check your email sending capacity of your website.
Second check that you did the correct configurations for subscriptions module.
Finall you must run the cron (or set the timer for cron) for sending email updates for subscriptions

If you want to test at the final step, just run cron manually
Comment: From the question +1 for checking cron.
Comment: Thank you @StoneVo

I was pretty sure the site was sending out emails the other week. But I just tested the two webforms and they are NOT sending out emails. Uggggh :(
Comment: @AlfredArmstrong do I still need to worry about cron if I am just testing? I mean I am just trying to send out one email notification for one single node...
Comment: I disabled a bunch of "mail" modules which I was using for the simplenews and subscriptions modules and the webforms are being sent out yet again. I hate how fixing one things breaks the other :(
Comment: The settings I've got turned on are as follows:

admin/config/system/subscriptions

Unlisted content types - none

Blocked content types - none

Node form position - Fieldset above node links

Node form visibility - Always display the fieldset

Expand the node form fieldset

admin/config/system/subscriptions/userdefaults

Nodify poster of own posts Send interval - As soon as possible

On updates - ticked

Send interval - Hidden

On updates - hidden

admin/config/system/subscriptions/intervals

1|As soon as possible 900|Every 15 minutes 3600|Hourly 10800|Every three hours 86400|Daily

@Stone Vo
Comment: You must run cron manually to test the subscriptions. You can create a new role user for testing purpose. After you create the new role. Changes the role will receive the subscriptions in User Configuration of Subscription Module.
Comment: Thank you @Stone Vo. I have started receiving emails (user1 that is). However, I only receive one email notification a day, even though multiple updates are made... is this normal?
Comment: I just installed the subscription and mail editor modules on a new site. The emails def work because I receive the contact us form notifications. I ran the cron manually but still haven't received a subscription notification of the node being modified :(


android + google map api v2 + current location

Question: i am creating an app with a google map view and i want this app to detect the current location of the user  and display the lat and long with a  marker on the map but all i can do until now is the display of the google map and the detection of current location without any marker displayed and without any text appear to display the lat and long
i did not add a marker until now because i do not know where to put it in the code and what is the best practice to do that
can anyone help me ???
this is the code of the:
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationgooglemapv2demo"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <permission
        android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationgooglemapv2demo.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="API KEY" />
    </application>

</manifest>

xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

java file
package in.wptrafficanalyzer.locationgooglemapv2demo;

import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends FragmentActivity implements LocationListener {

    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }
    @Override
    public void onLocationChanged(Location location) {

        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Answer: First check the documentation here, it gives good indication on best strategies for getting user position.
Personally I usually start the map with a marker placed at the position retrivied with
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

and then I start listening for position update and move the marker.
It also depend on how accurate position you need for the pourpose of your application, if you don't need really accurate position but the area is sufficient maybe you can just use thelastKnownLocation.
You can try something like this
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        LocationListener locationListener = new LocationListener() {
          void onLocationChanged(Location location) {
          // redraw the marker when get location update.
          drawMarker(location);
        }

        if(location!=null){
           //PLACE THE INITIAL MARKER
           drawMarker(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
    }
}

private void drawMarker(Location location){
    // Remove any existing markers on the map
    googleMap.clear();
    LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
    googleMap.addMarker(new MarkerOptions()
    .position(currentPosition)
    .snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude())
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
    .title("ME"));
}

Also you don't need the Activity class to implements LocationListener, you can just define a listener and register it as I did above
P.S. I don't have an editor son my code can contain typo
Hope this helps, cheers
Comment: @ drChivas that is exactly what i want to do i need to display the current location of the user on the map with the text that contain lat and long but i did not know how to do that
Comment: what if the last known location comes as null
Comment: This was awesome and right on the money. FYI this was a syntax error:
.snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude()));

I had to remove the final parenthesis and semi-colon because it was invalidating the following .icon() etc sections.
Comment: @DrChivas can u tell me how can i show current location if i press button of map on right hand side
Answer: I just had the same problem, and found a way to do it using the Google Maps API:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        mMarker = mMap.addMarker(new MarkerOptions().position(loc));
        if(mMap != null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    }
};

and then set the listener for the map:
    mMap.setOnMyLocationChangeListener(myLocationChangeListener);

This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.
Comment: This works as expected. Thanks. But I want to modify it to be able to return a double[] containing lat and lng. How is that possible? This looks strange to me. :/
Answer: Full shortcut for defining the Google Map android v2 in android......
XML File :
<fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

Menifest file :
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<permission
    android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.mapdemoapiv2.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="Your Key" />

    <uses-library android:name="com.google.android.maps" />
</application>

Activity class :
public class MainActivity extends android.support.v4.app.FragmentActivity
{
   GoogleMap googleMap;
    MarkerOptions markerOptions;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setUpMapIfNeeded();

    GetCurrentLocation();

    }

private void setUpMapIfNeeded() {
    if (googleMap == null) {

        Log.e("", "Into null map");
        googleMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();

        googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
                MainActivity.this));

        if (googleMap != null) {
            Log.e("", "Into full map");
            googleMap.setMapType(googleMap.MAP_TYPE_NORMAL);
            googleMap.getUiSettings().setZoomControlsEnabled(false);
        }
    }
}

private void GetCurrentLocation() {

    double[] d = getlocation();
    Share.lat = d[0];
    Share.lng = d[1];

     googleMap
            .addMarker(new MarkerOptions()
                    .position(new LatLng(Share.lat, Share.lng))
                    .title("Current Location")
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.dot_blue)));

             googleMap
                .animateCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(Share.lat, Share.lng), 5));
}

public double[] getlocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);

    Location l = null;
    for (int i = 0; i < providers.size(); i++) {
        l = lm.getLastKnownLocation(providers.get(i));
        if (l != null)
            break;
    }
    double[] gps = new double[2];

    if (l != null) {
        gps[0] = l.getLatitude();
        gps[1] = l.getLongitude();
    }
    return gps;
}

Comment: Can we get location through Google Maps API? because some devices doesnt have GPS.
Answer: It is better to use:
Location currentLocation =
     LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

Documentation
Answer: easy like that:
after this -
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="Your Key" />

put this -
<meta-data android:name="com.google.android.gms.version" android:value="4030500" />


How to use the header of a second data.frame as axis of a line plot using information of a first data.frame in R?

Question: After reading in my data in R I have two R internal variables, Goats and GoatPositions, that look like this:
> Goats
  GPS_No Goat_ID GoatName
1      5  660294    SIVKA
2      6  777077     MESI
3      7  660300   TONAKA
4      8  630328   ISKREA
5      9  608418    RIBEA
6     10  660290      OTA

and
> GoatPositions
  2020-07-13 18:00:00 2020-07-14 08:00:00 2020-07-14 18:00:00 2020-07-15 08:00:00
1                  33                  46                  NA                  44
2                  71                  59                  57                  71
3                  55                  NA                  40                  50
4                  18                  61                  24                  62
5                  53                   0                  44                   1
6                   4                  54                  54                  52

The data.frames of both R variables have more rows and the variable GoatPositions has also more columns.
What I would like to do, is to plot the data in the following way:

It should be a line graph.
The header (column names) of GoatPositions should be the x-axes.
The variables in the individual cells of GoatPositions should be the values for the y-axes.

(At the moment the label for the y-axis is nowhere indicated. It is going to be "Positions".)

Every row should be plotted as an individual line.
The line labels should be the values of the "GoatName" column in the Goats data.frame.

Of course, ?plot describes its usage:
plot(x, y, type, main, xlab, ylab),
and data referencing in R works as follows:
variablename[ row_conditions , column_conditions ]
So, adapting from that gives:
plot(GoatPositions[,0:3], GoatPositions[0:5,], type="l", {linelab=Goats$GoatName})

Of course {linelab=Goats$GoatName} is placeholder pseudo-code and it does also not run if the {} brackets are removed, but my question which emerges from here on forward is:
How to use the header of a second data.frame as axis of a line plot using information of a first data.frame in R?

Edit
Thanks to the comment from @Eyayaw I could run some code:
GoatPositionsLong <- reshape(GoatPositions, direction = 'long', timevar = 'date', varying = list(1:NCOL(GoatPositions)), times = colnames(GoatPositions), v.names = 'goat_pos')
Goats <- cbind(Goats, 1:nrow(Goats))
names(Goats)[names(Goats)=="1:nrow(Goats)"] <- "id"
GoatMerged <- merge(GoatPositionsLong, Goats, by = "id")

The variable GoatMerged looks now like this:
> GoatMerged
    id                date goat_pos GPS_No Goat_ID GoatName
1    1 2020-07-13 18:00:00       33      5  660294    SIVKA
2    1 2020-07-18 08:00:00      102      5  660294    SIVKA
...
14   2 2020-07-15 08:00:00       71      6  777077     MESI
15   2 2020-07-17 18:00:00       79      6  777077     MESI
...
27   3 2020-07-15 08:00:00       50      7  660300   TONAKA
28   3 2020-07-14 18:00:00       40      7  660300   TONAKA

with a total of 117 rows. Now, if I try to plot this:
plot(GoatMerged$date, GoatMerged$goat_pos, type="l")

I still get errors:
Error in plot.window(...) : finite 'xlim' values necessary
Additional warnings:
1: In min(x) : no no-missing argument for min; give Inf back
2: In max(x) : no no-missing argument for max; give -Inf back

Thank you @Eyayaw for your comment!
Yet, now I still want to ask: How to plot the now long format structured data?

Edit 2
Thanks to the further comment of @Eyayaw I checked the class of GoatMerged$date and made changes accordingly:
> class(GoatMerged$date)
[1] "character"

> GoatMerged$date <- as.POSIXct(GoatMerged$date, tz="Europe/Ljubljana")

> class(GoatMerged$date)
[1] "POSIXct" "POSIXt"

> plot(GoatMerged$date, GoatMerged$goat_pos, type="l")

The resulted plot that I get is this:

The issue with this plot is that it does not look like the desired one:

That raises the question: Why does the plot command try to read out the weekdates of the dates and plot the data as a time loop (?) instead of the individual time points?
So, how to plot DateTime / "POSIXct" "POSIXt" data in a 'sequence of time points' manner?

Edit 3
As asked from @Eyayaw here is the output of
> dput(GoatMerged)
structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L), date = structure(c(1626192000,
1626588000, 1626710400, 1626537600, 1626364800, 1626415200, 1626674400,
1626501600, 1626242400, 1626624000, 1626328800, 1626451200, 1626278400,
1626328800, 1626537600, 1626278400, 1626710400, 1626501600, 1626364800,
1626674400, 1626451200, 1626192000, 1626242400, 1626624000, 1626415200,
1626588000, 1626328800, 1626278400, 1626710400, 1626537600, 1626364800,
1626242400, 1626674400, 1626501600, 1626451200, 1626192000, 1626624000,
1626588000, 1626415200, 1626710400, 1626328800, 1626624000, 1626674400,
1626537600, 1626278400, 1626501600, 1626364800, 1626242400, 1626588000,
1626451200, 1626192000, 1626415200, 1626588000, 1626415200, 1626242400,
1626624000, 1626364800, 1626192000, 1626451200, 1626710400, 1626537600,
1626278400, 1626674400, 1626501600, 1626328800, 1626501600, 1626710400,
1626451200, 1626328800, 1626674400, 1626537600, 1626415200, 1626624000,
1626364800, 1626242400, 1626278400, 1626588000, 1626192000, 1626501600,
1626328800, 1626278400, 1626710400, 1626451200, 1626415200, 1626242400,
1626674400, 1626537600, 1626364800, 1626192000, 1626624000, 1626588000,
1626328800, 1626501600, 1626278400, 1626674400, 1626710400, 1626451200,
1626242400, 1626537600, 1626415200, 1626192000, 1626624000, 1626364800,
1626588000, 1626624000, 1626451200, 1626588000, 1626278400, 1626674400,
1626415200, 1626242400, 1626501600, 1626537600, 1626364800, 1626192000,
1626328800, 1626710400), class = c("POSIXct", "POSIXt"), tzone = "Europe/Ljubljana"),
    goat_pos = c(33L, 102L, 55L, 42L, 50L, 50L, 42L, 28L, 46L,
    28L, 44L, 29L, NA, 71L, 79L, 57L, 88L, 86L, 78L, 78L, 51L,
    71L, 59L, 78L, 69L, 78L, 50L, 40L, 52L, 53L, 55L, NA, 46L,
    54L, 60L, 55L, 58L, 56L, 48L, 61L, 62L, 61L, 61L, 61L, 24L,
    44L, 19L, 61L, 81L, 81L, 18L, 81L, 22L, 6L, 0L, 7L, 9L, 53L,
    5L, 8L, 20L, 44L, 3L, 8L, 1L, 48L, 27L, 64L, 52L, 52L, 69L,
    52L, 34L, 46L, 54L, 54L, 33L, 4L, 4L, 2L, 4L, 2L, 3L, 5L,
    NA, 5L, 1L, 2L, 11L, 3L, 5L, 28L, 61L, 53L, 45L, 47L, 35L,
    37L, 41L, 40L, 49L, 31L, 40L, 28L, 101L, 99L, 99L, 83L, 99L,
    102L, 81L, 102L, 103L, 98L, 81L, 81L, 103L), GPS_No = c(5L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L,
    7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
    8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
    9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
    11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
    12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 13L,
    13L, 13L, 13L, 13L, 13L, 13L, 13L), Goat_ID = c(660294L,
    660294L, 660294L, 660294L, 660294L, 660294L, 660294L, 660294L,
    660294L, 660294L, 660294L, 660294L, 660294L, 777077L, 777077L,
    777077L, 777077L, 777077L, 777077L, 777077L, 777077L, 777077L,
    777077L, 777077L, 777077L, 777077L, 660300L, 660300L, 660300L,
    660300L, 660300L, 660300L, 660300L, 660300L, 660300L, 660300L,
    660300L, 660300L, 660300L, 630328L, 630328L, 630328L, 630328L,
    630328L, 630328L, 630328L, 630328L, 630328L, 630328L, 630328L,
    630328L, 630328L, 608418L, 608418L, 608418L, 608418L, 608418L,
    608418L, 608418L, 608418L, 608418L, 608418L, 608418L, 608418L,
    608418L, 660290L, 660290L, 660290L, 660290L, 660290L, 660290L,
    660290L, 660290L, 660290L, 660290L, 660290L, 660290L, 660290L,
    611145L, 611145L, 611145L, 611145L, 611145L, 611145L, 611145L,
    611145L, 611145L, 611145L, 611145L, 611145L, 611145L, 457088L,
    457088L, 457088L, 457088L, 457088L, 457088L, 457088L, 457088L,
    457088L, 457088L, 457088L, 457088L, 457088L, 611254L, 611254L,
    611254L, 611254L, 611254L, 611254L, 611254L, 611254L, 611254L,
    611254L, 611254L, 611254L, 611254L), GoatName = c("SIVKA",
    "SIVKA", "SIVKA", "SIVKA", "SIVKA", "SIVKA", "SIVKA", "SIVKA",
    "SIVKA", "SIVKA", "SIVKA", "SIVKA", "SIVKA", "MESI", "MESI",
    "MESI", "MESI", "MESI", "MESI", "MESI", "MESI", "MESI", "MESI",
    "MESI", "MESI", "MESI", "TONÄŒKA", "TONÄŒKA", "TONÄŒKA",
    "TONÄŒKA", "TONÄŒKA", "TONÄŒKA", "TONÄŒKA", "TONÄŒKA", "TONÄŒKA",
    "TONÄŒKA", "TONÄŒKA", "TONÄŒKA", "TONÄŒKA", "ISKREÅ ", "ISKREÅ ",
    "ISKREÅ ", "ISKREÅ ", "ISKREÅ ", "ISKREÅ ", "ISKREÅ ", "ISKREÅ ",
    "ISKREŠ", "ISKREŠ", "ISKREŠ", "ISKREŠ", "ISKREŠ", "RIBEŽ",
    "RIBEŽ", "RIBEŽ", "RIBEŽ", "RIBEŽ", "RIBEŽ", "RIBEŽ",
    "RIBEŽ", "RIBEŽ", "RIBEŽ", "RIBEŽ", "RIBEŽ", "RIBEŽ",
    "OTA", "OTA", "OTA", "OTA", "OTA", "OTA", "OTA", "OTA", "OTA",
    "OTA", "OTA", "OTA", "OTA", "ZAJKA", "ZAJKA", "ZAJKA", "ZAJKA",
    "ZAJKA", "ZAJKA", "ZAJKA", "ZAJKA", "ZAJKA", "ZAJKA", "ZAJKA",
    "ZAJKA", "ZAJKA", "BRINA", "BRINA", "BRINA", "BRINA", "BRINA",
    "BRINA", "BRINA", "BRINA", "BRINA", "BRINA", "BRINA", "BRINA",
    "BRINA", "TISA", "TISA", "TISA", "TISA", "TISA", "TISA",
    "TISA", "TISA", "TISA", "TISA", "TISA", "TISA", "TISA"),
    EarStatus = c("Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Control", "Control", "Control", "Control", "Control",
    "Control", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear", "Short-ear", "Short-ear", "Short-ear",
    "Short-ear", "Short-ear")), row.names = c(NA, -117L), class = "data.frame")

Comment: You need to reshape the `GoatPositions` data into what the `plot` function understands. Or to what is called `long format`. Try first this: `reshape(df, direction = 'long', timevar = 'date', varying = list(1:NCOL(df)), times = colnames(df), v.names = 'goat_pos')`. Replace `df` by `GoatPositions`. Then merge this reshaped data with the `Goats` data.frame.
Comment: You're almost there. What class is the `date` variable in GoatMerged? By the look of it, it should be `DateTime`. Do you need the time in the `date`? DateTime class in r is `class(Sys.time())`
`#> "POSIXct" "POSIXt" `
Comment: I meant you can keep only the date, i.e., `yyyy-mm-dd` with `as.Date(df$date)`.
Comment: @Eyayaw Thank you for all of your answers and your comments! Unfortunately yes, I need the time and date information simultaneously. Also, as the second picture now shows, this is required to communicate changes within the same day and allowing to see what data point refers to the morning and which to the evening.
But besides that, thank you for your suggestion of `as.Date(df$date)`!
Comment: I think it'd be better if you could post some part of your data. Can you do `dput(GoatMerged)` and then paste the result here?
Answer: Since the base plot may involve writing for loop to color goat_pos by GoatName, i.e., color each line for each player, ggplot2 would be easier. So here we go:
library(ggplot2)

ggplot(goat, aes(date, goat_pos, color = as.factor(GoatName))) +
    geom_line() +
    scale_x_datetime(date_breaks = '1 day') +
    labs(color = 'Goats', y='Positions') +
    theme_classic()

output
Comment: I hope that is close enough to the plot you are trying to reproduce. You can change `date_breaks` according to your liking; e.g.,  2 days, 3 weeks etc.
Comment: Thank you for your answer and thank you very much for all your help!
Yes, this is in concept the plot I was aiming for. I may change the one or the other aesthetical thing like line width or so, but in general yes, this is what I was looking for - thank you very much!
Comment: I am glad you find it helpful. Cheers!


Configuring nginx as reverse proxy

Question: I am using Passenger with nginx to serve my rails app on a virtual Slice host. I am considering putting a reverse proxy for serving static content as well as handling etagged actions.

Can I use my existing nginx installation and just change it to a
reverse proxy? Do I even need a web server? What would a typical
architecture look like in this case?
nginx rev-proxy -> nginx web server -> passenger?

or
nginx rev-proxy ->  passenger?

Is nginx the best choice in this case?
Can my reverse proxy reside on the same Slice?

Thanks
Answer:
Yes you can use your nginx install.  You don't need to proxy at all, just continue using passenger with nginx and have nginx server static content direct
Popular opinion is probably, if you had Apache or Squid running you might consider using them, but since you have nginx already, nginx is a great choice.  Avoiding using passenger to serve static files may offer significant performance gains - but of course you milage will vary.
Same server/slice probably fine, if your traffic was so large that it had an impact, sure move it to another server, but there is no reason to proxy it, just change the urls accordingly - this is what serverfault does.

An example config file would be:
server {
listen www.example.com:80;

server_name  www.example.com;

    location ~* ^.+\.(jpg|jpeg|gif|png|css|bmp|js|ico|swf)$ {
       root  /home/static/files;
       expires 7d;
    }

    location / {
       root /home/rails_app;
       passenger_enabled on;
    }

}
Obviously add any additional files types as necessary.
Comment: @user55714  1) Well sure you need to change the root location to wherever your files are. 2)What are you trying to achieve with a reverse proxy?  I find it hard to believe that nginx can't handle the load.
Comment: I am trying to cache as many requests possible, using etags in my rails app. I wasn't sure if a non-reverse proxy configuration would support etagging and also in general I hear reverse proxies are lot more scalable, but then again, I am open to suggestions.
Comment: I am trying to cache as many requests possible, using etags in my rails app. I wasn't sure if a non-reverse proxy configuration would support etagging and also in general I hear reverse proxies are lot more scalable, but then again, I am open to suggestions.
Comment: "Avoiding using passenger to serve static files may offer significant performance gains - but of course you milage will vary." -- That doesn't make sense. Phusion Passenger for Nginx serves static files using Nginx.
Comment: Thanks. couple of clarifications. Here is my current nginx.conf file. http://pastie.org/1216283. 1 - It seems in your example, the root for static files is different than that of the rails root, normally my static files are in public folder in rails root, public/stylesheets, public/assets folder, how do I specify that or is this /root is where it is caching them? 2 - Why no need to proxy? If the web server is good enough to handle static assets, why folks put a reverse proxy in front of apache? Isn't the RP capable of handling more requests?

Configuring nginx as reverse proxy


how to change folium/geojson color

Question: i wish make it different color in different layer,
so use the style_function as i googled like below:
style1 = {'fillColor': '#228B22', 'lineColor': '#228B22'}
style2 = {'fillColor': '#00FFFFFF', 'lineColor': '#00FFFFFF'}

test1=gpd.read_file('file2.geojson')
folium.GeoJson(test1,name='test1',style_function=lambda x:style).add_to(mainmap)

test2=gpd.read_file('file1.geojson')
folium.GeoJson(test2,name='test2', style_function=lambda x:style2).add_to(mainmap)

however,it does not work on the line, still the default blue.
Comment: What happens if you use `'color'` rather than `'lineColor'`?
Comment: https://imgur.com/a/4awkXVi
Answer: a simple way to do so is to replace
style1 = {'fillColor': '#228B22', 'lineColor': '#228B22'}
style2 = {'fillColor': '#00FFFFFF', 'lineColor': '#00FFFFFF'}

by
style1 = {'fillColor': '#228B22', 'color': '#228B22'}
style2 = {'fillColor': '#00FFFFFF', 'color': '#00FFFFFF'}

how to change folium/geojson color


Ajuda para enviar dados do PHP para o DB

Question: Sou novo na área de programação e gostaria de uma ajuda
Montei uma pagina para inserir datas em 4 campos e preciso que essas datas sejam armazenadas no DB
E meio que não sei e estou com dificuldade para montar...alguem pode me ajuda?
Outra coisa preciso mostrar essa data depois na mesma pag...e não sei se fiz certo...está comentado para não dar erro na pagina..
Obs: montei a pag em um arq ctp e a função da pag chama em um controller
função na controller:
   public function desligamentocliente()
{
    $this->set( "titulo_da_pagina", "Desligamento de Cliente");
    $idCliente = ( isset( $this->request->params['pass'][0] ) ) ? $this->request->params['pass'][0] : 0;

       //$this->verifica_ausencia_dados( $this->request->data['idCliente'] );
        $this->loadModel( "DesligamentoCliente" );

                   $connect = mysql_connect('nome_do_servidor', 'nome_de_usuario', 'senha');
                    $db = mysql_select_db('nome_bo_banco_de_dados');
                    $query_select = "SELECT login FROM usuarios WHERE login = '$login'";

       $dados = $this->DesligamentoCliente->find( "list", array( "conditions" => array(
            "_esc_codigo" => $idCliente )));
        /*if ($dados['Desligamentos']['id'] ='' ) {
           echo "Data": $dados;
        } else {
            if ($dados['Desligamentos']['id'] == "" || $dados['Desligamentos']['id'] = null) {
            echo "Data não cadastrada";
            }
        }*/

}

Já agradeço a ajuda o/
Comment: Comece bem não use as funções mysql_x, use o mysqli_x ou pdo. Cadê o insert?
Answer: Boa noite,
Ja que esta começando , comece aprendendo sobre o PDO o mysqli , fica mais facil.
No seu codigo , esta faltando o insert dos dados , essas 4 datas você pega de um formulario onde alguem as informa?
Vamos supor que sim. ,entao você faria o insert :
function conexao(){

    $dbuser = "root";
    $dbpass = "1234";

    try {

        $pdo = new PDO('mysql:host=localhost;dbname=crm',  $dbuser, $dbpass);
        $pdo -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
        $pdo->exec("SET CHARACTER SET utf8");//corrige os acentos na hora de gravar no BD
    } catch(Exception $e) {

        echo 'Erro na conexao: ' . $e->getMessage();
    }
}

Funcao para inserir :
function inserirDatas($pdo){
    try {
                $data_1 = $_POST['data_1'];
                $data_2 = $_POST['data_2'];
                $arr = array();
                $sql = 'INSERT INTO suaTabela(campo1,campo2)VALUES(:data_1,:data_2)';
                $stmt = $pdo->prepare($sql);
                $dados = array(
                    ':data_1' => $data_1,
                    ':data_2' => $data_2
                );

                $stmt-> execute($dados);
                $linha = $stmt->rowCount();
                    if($linha == 1){

                        $arr['id'] = $stmt = $pdo->lastInsertId();
                        $arr['retorno'] = 1;
                    }else{
                        $arr['retorno'] = 0;
                    }

                $conexao = desconecta($conexao);
            } catch(Exception $e) {
                $resultado = 'Erro ao inserir os dados no banco: ' . $e->getMessage();
                $conexao = desconecta($conexao);
            }

return $arr;

}

Aqui na função , ela retorna 1 caso tenha obtido sucesso ao gravar os dados e 0 caso não tenha conseguido gravar os dados.
Então , você verifica , se a funcao retornar 1  , ele faz um select no banco trazendo as datas
function pegaUltimaData($pdo,$id){

        try{

            $sql = "SELECT * from suaTabela where id = $id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            if($stmt->rowCount() >= 1){
                $linha = $stmt->fetchAll(PDO::FETCH_ASSOC);
                return $linha;
            }

        } catch (Exception $e){

            print "Ocorreu um erro ao tentar executar esta ação";
            echo  "Erro: Código: " . $e-> getCode() . " Mensagem: " . $e->getMessage();
        }

    }

Acima tem as 3 funçoes que acredito que você terá de usar , para fazer o select no banco voce verifica o retorno da funcao inserirDatas
Espero que possa ajudar.


GUID error while building Windows driver via Visual Studio

Question: I'm building UMDF Smart Card Reader Driver in Visual Studio. I get strange errors like that:
error C2374: 'GUID_DEVINTERFACE_DISK' : redefinition; multiple initialization  C:\Program Files (x86)\Windows Kits\8.0\Include\UM\winioctl.h   43  1   BixVReader
File winioctl.h contains DEFINE_GUIDs for different devices like that (actually I have 1 error for each device here):
DEFINE_GUID(GUID_DEVINTERFACE_DISK,                   0x53f56307L, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b);
I suspect the line I wrote in Internal.h:
DEFINE_GUID(SmartCardReaderGuid,
    0x50DD5230, 0xBA8A, 0x11D1, 0xBF,0x5D,0x00,0x00,0xF8,0x05,0xF5,0x30);
But what's wrong?
Answer: These errors dropped when I swaped #include "winioctl.h" and #include :
//
// Windows IOCTL definitions.
//
#include "winioctl.h"

//
// GUID include
//
#include <initguid.h>

//
// Device Interface GUID
// 0x50DD5230, 0xBA8A, 0x11D1, 0xBF,0x5D,0x00,0x00,0xF8,0x05,0xF5,0x30
//
DEFINE_GUID(GUID_DEVINTERFACE_BixVReader,
    0x50DD5230, 0xBA8A, 0x11D1, 0xBF,0x5D,0x00,0x00,0xF8,0x05,0xF5,0x30);

I'm not an expert in C++ and it seems strange to me, but still. Any comments on this issue are welcome.
Comment: These errors dropped when I swapped #include "winioctl.h" and #include
Answer: Apparently, the proper way to fix this is to #include <windows.h> before both winioctl.h and initguid.h. Doing so fixed the issue for me without having to swap the headers.


Connecting to Multiple cameras which each acts as a WiFi Access Point

Question: I have 7 cameras each acting as a WiFi Access Points and I can not change their configurations.
Camera1 SSID: camera1, pass: 1234, it has static IP: 192.168.42.1 and built-in DHCP server
Camera2 SSID: camera2, pass: 1234, it has static IP: 192.168.42.1 and built-in DHCP server
..
Camera7 SSID: camera7, pass: 1234, it has static IP: 192.168.42.1 and built-in DHCP server

From my windows notebook, by using internal WiFi adaptor, I can connect to camera1's ssid and get videos. Then I need to disconnect from it, connect to camera2's ssid to get video from camera2, and similar to 3,4..7.
What I want is to get simultaneous videos from all of them.
What I tried:
I tried to plug 7 USB WiFi adaptors to my notebook. And each adaptors configured to connect different cameras. In this case, windows shows 7 different ethernet interfaces and each gets their IP from corresponding camera's dhcp server. But all cameras use same IP which is 192.168.42.1. Also as I learnt multiple USB WiFi adaptors are supported by Windows but not by MACOS.
I need a kind of universal solution to this problem, so far I couldn't figure it out how. Your helps and suggestions are highly appreciated.
Thanks.
Further tests:
I believe that I'm close to a solution. But still need help.
I took a Raspberry Pi 4 which runs Ubuntu on it. I'm intended to use it as a router. By Default PI hardware comes with 2 ethernet interfaces;

eth0  -> 1Gbit cable connection
wlan0 -> Embedded WiFi interface

I plugged two extra USB WiFi dongles and now it has two more ethernet interfaces named wlxb8b7f16a0602 and wlxb8b7f16a04cd. Each USB WiFi dongle connected to a different camera. Here is the ifconfig output:
pi@pi:~$ ifconfig -a
eth0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether dc:a6:32:48:55:70  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.0.205  netmask 255.255.255.0  broadcast 192.168.0.255
        inet6 fe80::2c43:aa7a:a4c8:47eb  prefixlen 64  scopeid 0x20<link>
        inet6 2a02:aa14:c480:6c80:9deb:968e:785d:159c  prefixlen 64  scopeid 0x0<global>
        inet6 2a02:aa14:c480:6c80:10b7:8a65:dce6:1f5c  prefixlen 64  scopeid 0x0<global>
        ether dc:a6:32:48:55:71  txqueuelen 1000  (Ethernet)
        RX packets 10535  bytes 2218695 (2.2 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 44536  bytes 63167704 (63.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlxb8b7f16a0602: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.42.24  netmask 255.255.255.0  broadcast 192.168.42.255
        inet6 fe80::6523:f6cd:520b:ee0  prefixlen 64  scopeid 0x20<link>
        ether b8:b7:f1:6a:06:02  txqueuelen 1000  (Ethernet)
        RX packets 9  bytes 1495 (1.4 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 47  bytes 9334 (9.3 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlxb8b7f16a04cd: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.42.170  netmask 255.255.255.0  broadcast 192.168.42.255
        inet6 fe80::ad02:2e2e:cc11:c309  prefixlen 64  scopeid 0x20<link>
        ether b8:b7:f1:6a:04:cd  txqueuelen 1000  (Ethernet)
        RX packets 60  bytes 6531 (6.5 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 130  bytes 19353 (19.3 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

In this configuration;

eth0  -> not connected
wlan0 -> connected to my internet modem (used only for ssh to pi)
wlxb8b7f16a0602 -> connected to Camera1
wlxb8b7f16a04cd -> connected to Camera2

Even though each camera has same IP which is 192.168.42.1, since they are connected to different interfaces, I could ping them successfully by using -I parameter like below:
For Camera1:
pi@pi:~$ ping -I wlxb8b7f16a0602 192.168.42.1
PING 192.168.42.1 (192.168.42.1) from 192.168.42.24 wlxb8b7f16a0602: 56(84) bytes of data.
64 bytes from 192.168.42.1: icmp_seq=2 ttl=64 time=3.77 ms

For Camera2:
pi@pi:~$ ping -I wlxb8b7f16a04cd 192.168.42.1
PING 192.168.42.1 (192.168.42.1) from 192.168.42.170 wlxb8b7f16a04cd: 56(84) bytes of data.
64 bytes from 192.168.42.1: icmp_seq=2 ttl=64 time=2.03 ms

From here, let's say I assign a static IP to my eth0 interface which is 192.168.42.250
I want to forward requests come from

192.168.42.250:443 at eth0 to 192.168.42.1:443 at wlxb8b7f16a0602
192.168.42.250:444 at eth0 to 192.168.42.1:443 at wlxb8b7f16a04cd

If you help me for this remaining point, I accept your answer.
To @A.B:
pi@pi:~$ iw phy phy0 |grep netns
        phy <phyname> set netns { <pid> | name <nsname> }
                    <nsname> - change network namespace by name from /run/netns
                               or by absolute path (man ip-netns)

pi@pi:~$ ll /sys/class/ieee80211
total 0
drwxr-xr-x  2 root root 0 Mai 27 17:13 ./
drwxr-xr-x 78 root root 0 Jan  1  1970 ../
lrwxrwxrwx  1 root root 0 Jun 27 20:18 phy0 -> ../../devices/platform/soc/fe300000.mmcnr/mmc_host/mmc1/mmc1:0001/mmc1:0001:1/ieee80211/phy0/
lrwxrwxrwx  1 root root 0 Mai 27 17:13 phy1 -> ../../devices/platform/scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-1/1-1.2/1-1.2:1.0/ieee80211/phy1/
lrwxrwxrwx  1 root root 0 Mai 27 17:13 phy2 -> ../../devices/platform/scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-1/1-1.3/1-1.3:1.0/ieee80211/phy2/

Comment: Have you considered returning this garbage and buying a more reasonable camera solution?
Comment: @A.B I suppose one could come up with some custom hardware/software do do whatever you want, but that's not practical.  I imagine that if Mehmet had that kind of capability, he wouldn't have asked the question.
Comment: @MehmetFide It's not possible if all your devices have the same address.  Imagine if all your friends/family had the same telephone number.
Comment: For example, any solution with a raspberry 4 as a router which works on Linux and attached 7 USB WiFi dongle on it would be appreciated. It would definitely be accepted by me. With the configuration, I would have one 1Gbit Ethernet port with a cable (that can go to windows or macos) and 7 WiFi adaptors each connected to a different cameras. But what would be the proper network setting for that?
Comment: Also does `iw phy phy0 |grep netns` 's answer include `* set_wiphy_netns` and are there two entries in /sys/class/ieee80211/ ?
Comment: @MichaelHampton Unfortunately this is not possible. Isn't there a kind of router which can connect to different wifi access points at the same time and combine them under one network? Theoretically It should be possible.
Comment: @RonTrunk I'd say it's possible (probably not on Windows) with policy routing (with the interface as selector rather than the IP address), then as an example on Linux with conntrack zones to separate the identical looking flows in the subsequent NAT, or with network namespaces + NAT. But that would be very awkward to implement
Comment: @A.B I use term "camera' because I found it easier to explain my problem with it. In reality they are special measurement props which stream real time measurement data through port 443. Sorry for that :) But the fact is same, they are not configurable, the manufacturer didn't think that someone will come and try to connect multiple probes from a single PC or MAC.
Comment: Using wireless really doesn't help because setup of wireless is more touchy than ethernet. Especially when considering using network namespaces. Are you able to succesfully use static IP addresses instead of DHCP to connect to the "cameras"? Or else are you able to manually configure wpa_supplicant? Can you provide the resulting wpa_supplicant configurations for your two devices? Is there currently a single wpa_supplicant process running, or two (one per device)?
Comment: Well I was curious and worked on the method not using network namespaces. network namespaces should be favored and give a more robust result, but I don't see how to make an answer with namespaces without having to ask the kind of questions I already asked above and more.
Answer: Presentation
This problem could be solved by using network namespaces, thus splitting the single Pi system into X routers doing NAT. That's what should be done. Alas I don't know how to write an answer that would not only have to include how to move the Wifi interfaces to a new network namespace (requires compatible drivers and iw phy phyX set netns ... instead of ip link set wlanX ... netns ...) but also especially their associated wpa_supplicant and DHCP client daemons with corresponding system integration tweaks. This requires good knowledge on how the specific system is configured with wireless and DHCP.
Instead this answer avoids using network namespaces and avoids having to reconfigure the handling of wpa_supplicant and the DHCP client: it uses policy routing.
Involving marks in policy routing is unavoidable for this case where the routing stack will only see destination port 443 rather than 4431/4432 (DNAT already changed it before). Marks will also be user to set conntrack (reply) zones to be sure to handle the case where multiple cameras assign the same IP address to their matching host interface.
Strict Reverse Path Forwarding (SRPF) will have to be relaxed to Loose RPF in case Strict was set by default, because ARP handling wont't receive the marks and can stay blocked.
As the cameras might not have set their default route to the client but might only have a LAN route, double NAT (source and destination) will also be done.
Setup
As OP didn't provide any eth0 setting, there's none here. The answer tries to not depend too much on this, but OP would have to adapt it if needed (especially if the 7 wireless interfaces won't all have their name starting with wlx).
Let's adjust the goal:
192.168.42.0/24 represents multiple overlapping IP networks that must not be reached directly to protect the outside clients from all possible routing complexity.
So the address 192.168.42.250 won't be used. Pi's visible address 192.168.0.205 will be used from the remote clients.
Any HTTPS access will get a bad certificate. Deal with it: I'm providing an answer based on tweaking network settings, but it won't include the setup of a reverse proxy to hide the certificate issue. Adding such reverse proxy also requires more network tweaks (added as an option at the end). Tests can be done from a client (but not the RPi) with:
curl --insecure https://192.168.0.205:4431/
curl --insecure https://192.168.0.205:4432/

Also to show some examples below, I took the case with both cameras having assigned the same IP address to the host so it appears on two interfaces, to raise the bar. It doesn't matter. Most of these settings must be done after all wireless connections are done rather than before. I won't deal on how to integrate this with the specific Linux OS handling it.
All commands should be run as root.
Examples are based on:
# ip route
default via 192.168.0.1 dev wlan0
192.168.0.0/24 dev wlan0 proto kernel scope link src 192.168.0.205
192.168.42.0/24 dev wlxb8b7f16a0602 proto kernel scope link src 192.168.42.10 metric 600
192.168.42.0/24 dev wlxb8b7f16a04cd proto kernel scope link src 192.168.42.10 metric 600

Routing rules to select additional routing tables that will isolate duplicate each camera LAN from the other camera LAN:
ip rule add fwmark 1 lookup 4431
ip rule add fwmark 2 lookup 4432

ip route add 192.168.42.0/24 dev wlxb8b7f16a0602 table 4431
ip route add 192.168.42.0/24 dev wlxb8b7f16a04cd table 4432

This makes routing work from client to cameras (if the RPi doesn't have a default route, examples below using 192.0.2.2 to test routes could use 192.168.0.101 instead):
# ip route get mark 2 from 192.0.2.2 iif wlan0 192.168.42.1
192.168.42.1 from 192.0.2.2 dev wlxb8b7f16a04cd table 4432 mark 2
    cache iif wlan0

but still not for replies if SRPF is enabled:
# ip route get mark 2 from 192.168.42.1 iif wlxb8b7f16a04cd 192.0.2.2
RTNETLINK answers: Invalid cross-device link

So an almost undocumented flag would have to be set on the camera interfaces:
sysctl -w net.ipv4.conf.wlxb8b7f16a0602.src_valid_mark=1
sysctl -w net.ipv4.conf.wlxb8b7f16a04cd.src_valid_mark=1

to get now:
# ip route get mark 2 from 192.168.42.1 iif wlxb8b7f16a04cd 192.0.2.2
192.0.2.2 from 192.168.42.1 via 192.168.0.1 dev wlan0 mark 2
    cache iif wlxb8b7f16a04cd

But actually, anyway ARP (from camera to host) is still disrupted when SRPF is set because ARP doesn't get iptables' marks.
So just use Loose RPF (rp_filter=2) instead (and then the setting for src_valid_mark above is not needed anymore) to solve it. This works whether RPF was disabled or set strict before:
sysctl -w net.ipv4.conf.wlxb8b7f16a0602.rp_filter=2
sysctl -w net.ipv4.conf.wlxb8b7f16a04cd.rp_filter=2

Add iptables rules setting marks to complete the routing part as well as deal with conflicting addresses in NAT later by setting the reply zone selector.
iptables -t raw -A PREROUTING ! -i wlx+ -p tcp --dport 4431 -j MARK --set-mark 1
iptables -t raw -A PREROUTING -i wlxb8b7f16a0602 -j MARK --set-mark 1
iptables -t raw -A PREROUTING -m mark --mark 1 -j CT --zone-reply 1

iptables -t raw -A PREROUTING ! -i wlx+ -p tcp --dport 4432 -j MARK --set-mark 2
iptables -t raw -A PREROUTING -i wlxb8b7f16a04cd -j MARK --set-mark 2
iptables -t raw -A PREROUTING -m mark --mark 2 -j CT --zone-reply 2

Add those rules to NAT to the target IP and port (which are always the same). The correct interface will then be chosen by the routing stack thanks to previous settings:
iptables -t nat -A PREROUTING ! -i wlx+ -p tcp -m mark ! --mark 0 -j DNAT --to-destination 192.168.42.1:443
iptables -t nat -A POSTROUTING -o wlx+ -j MASQUERADE

Should a 3rd interface called wlx3 be added, here are the steps. It can be generalized the same way for more:
Add a new ip rule selected with a new mark (3) that will use a new routing table (4433):
ip rule add fwmark 3 lookup 4433

Add the matching new routing table with its entry more or less duplicated from the main table LAN's route for the new interface:
ip route add 192.168.42.0/24 dev wlx3 table 4433

Loosen RPF on this interface if OS' defaults were SRPF (as told src_valid_mark isn't needed in the end):
sysctl -w net.ipv4.conf.wlx3.rp_filter=2

Choose a new port (4433) and add 3 new raw/PREROUTING iptables rules that include the new port, the new mark and the new interface:
iptables -t raw -A PREROUTING ! -i wlx+ -p tcp --dport 4433 -j MARK --set-mark 3
iptables -t raw -A PREROUTING -i wlx3 -j MARK --set-mark 3
iptables -t raw -A PREROUTING -m mark --mark 3 -j CT --zone-reply 3

(If the new interface name doesn't start with wlx add new nat rules accordingly.)
Here's an example of conntrack handling when a client connects twice, even using the same source port, to the two ports while the RPi got the very same IP address assigned to the two wlx wireless interfaces. The conntrack zone is included in flow selection and allows NAT to be handled correctly even if one side of the flows sees exactly the same addresses and ports:
# conntrack -E
    [NEW] tcp      6 120 SYN_SENT src=192.168.0.101 dst=192.168.0.205 sport=6666 dport=4431 [UNREPLIED] src=192.168.42.1 dst=192.168.42.10 sport=443 dport=6666 zone-reply=1
 [UPDATE] tcp      6 60 SYN_RECV src=192.168.0.101 dst=192.168.0.205 sport=6666 dport=4431 src=192.168.42.1 dst=192.168.42.10 sport=443 dport=6666 zone-reply=1
 [UPDATE] tcp      6 432000 ESTABLISHED src=192.168.0.101 dst=192.168.0.205 sport=6666 dport=4431 src=192.168.42.1 dst=192.168.42.10 sport=443 dport=6666 zone-reply=1 [ASSURED]
    [NEW] tcp      6 120 SYN_SENT src=192.168.0.101 dst=192.168.0.205 sport=6666 dport=4432 [UNREPLIED] src=192.168.42.1 dst=192.168.42.10 sport=443 dport=6666 zone-reply=2
 [UPDATE] tcp      6 60 SYN_RECV src=192.168.0.101 dst=192.168.0.205 sport=6666 dport=4432 src=192.168.42.1 dst=192.168.42.10 sport=443 dport=6666 zone-reply=2
 [UPDATE] tcp      6 432000 ESTABLISHED src=192.168.0.101 dst=192.168.0.205 sport=6666 dport=4432 src=192.168.42.1 dst=192.168.42.10 sport=443 dport=6666 zone-reply=2 [ASSURED]

Miscellaneous

misc 1
For a camera to be able to ping the host or receive ICMP errors from the host, this (global) setting must be added:
sysctl -w net.ipv4.fwmark_reflect=1

else the ICMP answer doesn't follow policy routing. An other better way is to use CONNMARK/connmark, but it would make the answer unnecessarily more complex.

Misc 2
The working result can't be tested correctly from the RPi itself but only from a client on the LAN (or on Internet with support from RPi's router).  Settings are specific to the routing case.
Optionally for the host to be able to work (and allowing a reverse proxy to be put in place), these additional settings can be added:
Select the right interface even before NAT happens (requires kernel >= 4.17), else the socket will choose the wrong source address (of an other interface) later:
ip rule add iif lo ipproto tcp dport 4431 lookup 4431
ip rule add iif lo ipproto tcp dport 4432 lookup 4432

The destination has to be DNATed in nat/OUTPUT. No need for the exact wlx name here, the correct outgoing route was already selected by the routing stack with the new routing rules (reply still requires part of iptables raw/PREROUTING rules from main answer). And a conntrack reply zone is also needed in raw/OUTPUT to handle the rare clash cases.
iptables -t raw -A OUTPUT -o wlx+ -p tcp --dport 4431 -j MARK --set-mark 1
iptables -t raw -A OUTPUT -m mark --mark 1 -j CT --zone-reply 1

iptables -t raw -A OUTPUT -o wlx+ -p tcp --dport 4432 -j MARK --set-mark 2
iptables -t raw -A OUTPUT -m mark --mark 2 -j CT --zone-reply 2

iptables -t nat -A OUTPUT -p tcp -m mark ! --mark 0 -j DNAT --to-destination :443

The tests in this case should be done from the RPi with:
curl --insecure https://192.168.42.1:4431/
curl --insecure https://192.168.42.1:4432/

misc 3
The settings in misc 2 if adapted for local handling of UDP, for a different case than OP, would probably not be enough for some corner cases: UDP always needs support from the local application when in a multi-homed environment.
Answer: I couldn't figure out how to do it with iptables but I solved the problem using socat worked nicely for me:
sudo socat TCP-LISTEN:443,interface=eth0,FORK TCP:192.168.42.1:443,interface=wlxb8b7f16a0602
sudo socat TCP-LISTEN:444,interface=eth0,FORK TCP:192.168.42.1:443,interface=wlxb8b7f16a04cd

All requests come to port 443 at eth0 interface will be redirected to 192.168.42.1:443 at wlxb8b7f16a0602 interface.
And similarly, requests come to port 444 at eth0 interface will be redirected to 192.168.42.1:443 at wlxb8b7f16a04cd interface.
Comment: Looks way simpler with a tool that can bind to an interface.


Searching a ListView does not work - why?

Question: Hi I have a listView in a Dialog, and I have setup a custom adapter for the Dialog.
I lookup up and I setup the addTextChangedListener but does not seem to work.
I just want to search through the list and refresh the list when the user types in the Edit text
Any idea where I am getting it wrong please
Here is my code
private void showCompaniesDialog(List<Company> companies) {
    if(companies != null) {
        final Dialog dialog = new Dialog(getContext());
        // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.dialog_company_listview);

        Button btndialog = (Button) dialog.findViewById(R.id.btndialog);
        btndialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });

        ListView listView = (ListView) dialog.findViewById(R.id.listview);
        //ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), R.layout.company_list_item, R.id.tv, companies);
        CompanyAdapter companyAdapter = new CompanyAdapter(getActivity(), 0, companies);
        listView.setAdapter(companyAdapter);

        //HERE I SET THE TEXT FILTER ENABLED
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //textView.setText("You have clicked : " + companies[position]);
                dialog.dismiss();
            }
        });

        //HERE I ADD CHANGED LISTENER
        EditText etSearch = (EditText) dialog.findViewById(R.id.etSearch);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //companyAdapter.getFilter().filter(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
                companyAdapter.getFilter().filter(editable);
            }
        });

        dialog.show();
    }

}

Here is the custom adapter for the company
public class CompanyAdapter extends ArrayAdapter<Company>{
    private Activity activity;
    private List<Company> lCompany;
    private LayoutInflater inflater = null;

    public CompanyAdapter (Activity activity, int textViewResourceId, List<Company> lCompany){
        super(activity, textViewResourceId, lCompany);
        try{
            this.activity = activity;
            this.lCompany = lCompany;

            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public int getCount(){
        return lCompany.size();
    }

    public Company getItem (Company position){
        return position;
    }

    public  long getItemId(int position){
        return position;
    }

    public  class ViewHolder {
        public TextView display_name;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        final ViewHolder holder;
        try {
            if (convertView == null) {
                vi = inflater.inflate(R.layout.company_list_item, null);
                holder = new ViewHolder();

                holder.display_name = (TextView) vi.findViewById(R.id.tvCompanyName);

                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }
            holder.display_name.setText(lCompany.get(position).getName());

        } catch (Exception e) {
            e.printStackTrace();

        }
        return vi;
    }
}

Any suggestions would be very helpful
Comment: Maybe see https://stackoverflow.com/a/24771174/5909412
Comment: You're keeping your own `List` separate from the one `ArrayAdapter` maintains internally, and filters on. Simply remove your `private List lCompany;` field, and the overrides that are using it, and use `getItem(position)` in place of `lCompany.get(position)` in `getView()`. Then just make sure that your `Company` class has a `toString()` override that returns `getName()` – or its corresponding field – and `ArrayAdapter`'s built-in `Filter` will work for you.
Comment: @MikeM. I tried that, and when I type something in the EditText, it empties the list and does not filter. When you said override toString. In the Company class I have @SerializedName("name")
    private String name;
public String getName() {
        return name;
    }
It is already returning a String so should I be doing anything else here?
Another point, when I type something it empties the list and when I delete the text I have typed the list is back. Any ideas what might be happening
Comment: You have to specifically override the `toString()` method; `@Override public String toString() { return name; }`. In fact, you don't need a custom `Adapter` at all, if the only thing you're doing is setting a `TextView`'s text. Add that `toString()` override to `Company`, then `ArrayAdapter companyAdapter = new ArrayAdapter<>(getActivity(), R.layout.company_list_item, R.id.tvCompanyName, companies);`. That's it.
Answer: I implement this using a SearchView paired with a ListView.  The SearchView has some built in methods that fire when text is changed or Search is clicked, which you can override to set the filter in the ListView.
MyActivity.java
        // Setup the ListView
        // breedListView = (ListView)rootView.findViewById(R.id.breedListView);

        // My 'Activity' is actually a ListFragment so getListView() is how it is done
        breedListView = getListView();
        breedListView.setFastScrollEnabled(true);
        breedListView.setTextFilterEnabled(true);

        // Setup the searchView
        searchView = (SearchView)rootView.findViewById(R.id.searchView);
        setupSearchView();

        // Set some default properties
        private void setupSearchView() {
            searchView.setIconifiedByDefault(false);
            searchView.setOnQueryTextListener(this);
            searchView.setSubmitButtonEnabled(false);
            searchView.setQueryHint("Search");
        }

        // Reset the filter as the user types
        public boolean onQueryTextChange(String newText) {
            if (TextUtils.isEmpty(newText)) {
                breedListView.clearTextFilter();
            } else {
                breedListView.setFilterText(newText.toString());
            }
            return true;
        }

        // Reset the filter when Search is pressed
        public boolean onQueryTextSubmit(String query) {
            if (TextUtils.isEmpty(query)) {
                breedListView.clearTextFilter();
            } else {
                breedListView.setFilterText(query.toString());
            }
            return false;
        }

        // After getting/refreshing the list, do this to reapply the query to the new list
        CharSequence suggestWord = searchView.getQuery();
        searchView.setQuery(suggestWord, true);

MyActivity.xml
        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <SearchView
                android:id="@+id/searchView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </SearchView>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                    <ListView
                      android:id="@android:id/list"
                      android:layout_weight="0.1"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content" >
                    </ListView>

                    <ListView
                        android:id="@+id/listIndex"
                        android:dividerHeight="0dp"
                        android:divider="@null"
                        android:scrollbars="none"
                        android:layout_width="30dp"
                        android:layout_height="wrap_content" >
                    </ListView>
            </LinearLayout>
        </LinearLayout>

Answer: You need to add Filterable interface to your Adapter.
You can add following piece of code to your adapter
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List < String > list = originalData;

            int count = list.size();
            final ArrayList < String > nlist = new ArrayList < String > (count);

            String filterableString;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList < String > ) results.values;
            notifyDataSetChanged();
        }
    }
}

You need to change it as per your requirement
Comment: `ArrayAdapter` already implements `Filterable`, and provides its own `Filter`. This isn't really necessary.


Characterising spaces of linear recurrent sequences.

Question: Let $K$ be a field and $\def\N{\mathbf N}K^\N$ the infinite dimensional space of all sequences of elements of$~K$. Any linear recurrence relation of order $d$ with constant coefficients
$$
a_{i+d} = c_0a_i+c_1a_{i+1}+\cdots c_{d-1}a_{i+d-1}
  \qquad\text{for all $i\in\N$,}
$$
defines a $d$-dimensional subspace $V$ of $K^\N$. In studying these sequences one introduces the shift operator $T:(a_0,a_1,a_2,\ldots)\mapsto(a_1,a_2,a_3,\ldots)$, which defines an endomorphism of $V$, and whose (generalised) eigenspace decomposition is useful for describing linear recurrent sequences explicitly.
The shift operator $T$ is actually well defined on all of $K^\N$, and can be used for instance to characterise geometric sequences as its eigenvectors. For the indicated application to linear recurrences, it is of vital importance that each space$~V$ defined by a specific recurrence relation is $T$-stable, and this is indeed always the case for the recurrence relations considered (the fact that the coefficients of the recurrence relation are constant is essential for this). Now I was just wondering if this precisely describes the finite dimensional $T$-stable subspaces of $K^\N$:

If $V$ is a finite dimensional $T$-stable subspace of $K^\N$, does there exist a linear recurrence relation$~R$ of order $\dim V$ with constant coefficients such that $V$ consists of all sequences in$~K^\N$ satisfying$~R$?

I think the answer should be affirmative; maybe there is some elegant way to see this easily.
Comment: Maybe this old article will be useful for you: N.Zierler, Linear recurring sequences. J.Soc.Ind.Appl.Math., {\bf 7}(1959), No.1, 31-48.
Comment: My first reaction is that why wouldn't the characteristic polynomial of $T$ on $V$ work? In other words, if
$$\chi_{V,T}(x)=x^d-c_{d-1}x^{d-1}-c_{d-2}x^{d-2}-\cdots-c_0,$$ just read the coefficients from there. In coding theory/crypto that polynomial is called the feedback polynomial of the linear recurrence relatio (or was it its reciprocal?). I haven't checked this in detail, but it feels so natural. Have you seen cases, where this would fail?
Comment: Equivalently we could view $K^{\Bbb{N}}$ as a $K[x]$-module $U$ with $x$ acting as $T$. Hmm. A finite dimensional submodule $V$ will be annihilated by the characteristic polynomial of $T$, but why is it cyclic....
Comment: @JyrkiLahtonen: I've found an answer (independently of your suggestion, but it was in that direction).
Answer: In fact, thinking about this it turns out to be relatively easy. One needs a simple
Lemma. Let $P\in K[X]$ be any monic polynomial, and denote by $P[T]\in\operatorname{End}(K^\N)$ the corresponding polynomial in$~T$. Then $\dim\ker(P[T])=\deg P$.
The proof consists simply of observing that our recurrence relation amounts to saying $(a_i)_{i\in\N}\in\ker(-c_oT^0-c_1T^1-\cdots-c_{n-1}T^{n-1}+T^n)$, and that any $P[T]$ is of this form.
Now let $V$ be a finite dimensional $T$-stable subpace of $K^\N$, and let $P$ by the minimal polynomial of the restriction of $T$ to $V$. Then $V\subseteq\ker(P[T])$ by definition, and $\deg P\leq\dim V$ by the Cayley-Hamilton theorem. Therefore the lemma gives $V=\ker(P[T])$, and $V$ consists of the solutions of the linear recurrence encoded by$~P$.
Equivalently, following Jyrki Lahtonen's suggestion, one could take $P$ to be the characteristic polynomial of the restriction of $T$ to$~V$; then $\deg P=\dim V$ is obvious and $V\subseteq\ker(P[T])$ follows from the Cayley-Hamilton theorem.
Incidentally this shows that the restriction of $T$ to any finite dimensional $T$-stable subspace has its minimal and characteristic polynomials equal (and therefore $V$ has a cyclic vector for$~T$, and the centraliser in $L(V,V)$ of the restriction of $T$ is limited to the polynomials in that restriction).