text:
Q: Add android dependency to module in Android Studio? How do I add android dependency to a module in Android Studio? Is there a simpler way than manually copying the android.jar?

A: You can find the gradle version and set it in build.gradle onder dependencies:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"

    defaultConfig {
        applicationId "geert.berkers.cartracker"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.google.firebase:firebase-database:9.8.0'
    compile 'com.android.support:design:25.0.0'
    //Add it here!
}

apply plugin: 'com.google.gms.google-services'

A: yes you do.

*

*select your project -> open module settings

*select your modules -> click Dependency tab

*click '+' -> select library dependency

then search and add your library. It will automatically add dependency to your project and gradle file.


text:
Q: Keep original page position when opening new window I have a hotspot map of our office.  The hotspots can be clicked and a small window pops up but the larger page with the map moves back to its original position.  How can I get my larger map page to stay in the same position in the browser?

<title>Office Map</title>

<map name="Map">

<area shape="rect" title="MKTP51"   coords="1856,391,1874,420" alt="MKTP51" a href="#" onClick="window.open('PrinterPages/mktp51.html','mywindow','width=400,height=200,toolbar=no,location=no,directories=no,statu s=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no')">

<area shape="rect" title="MKTP40"   coords="772,322,790,358"   alt="MKTP40" a href="#" onClick=    "window.open('PrinterPages/mktp40.html','mywindow','width=400,height=200,toolbar=no,location=no,directories=no,statu s=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no')">

Thank you in advance.

A: Try putting return false; at the end of the onclick attribute.  (Note, you will need to put a ; at the end of the current statement)
That should stop the standard link processing, and stop it going to the start of the page due to the href="#"
Just to confirm, the endof the onclick attribute should be something like...
... resizable=no'); return false;">

redpajama_set_name: RedPajamaStackExchange


text:
Q: KIVY zindex dynamic change I am trying to add 4 boxes in Relativelayout. Able to horizontally move only the box which gets added last in relativelayout. All other box gets strucked up when it is moved closer to its box which got added later. In given sample code below 'Actor 400' freely moves horizontally across the scene. 'Actor 300' able to move freely over 'Actor 200' and 'Actor 100'. But when I try to move Actor 300 above Actor 400, it get strucked and only after mouse moves beyond Actor 400, I am able to move.
Can I change the zindex of the widget dynamically when I touch it.
from kivy.app import App
from kivy.graphics import Line, Color
from kivy.uix.scatter import Scatter
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.lang import Builder

KV = '''
<Actor>:
    canvas:
        Color:
            rgba: 0,1,0,.8
        Rectangle:
            id: _rect_
            size: 100, 30
            pos: 0, root.height - 30
        Line:
            points: 50, root.height - 30, 50, 20
            width:2
    Label:
        id: _actr_lbl
        text: 'Hello World'
        color: 0,0,0,1
        size_hint: None, None
        size: 100, 30
        pos: 0, root.height - 30
'''

Builder.load_string(KV)
class Actor(Scatter):
    def __init__(self, **kwargs) :
        Name = kwargs.pop('Name', 'Actor-NoName')
        super(Actor, self).__init__(**kwargs)
        self.Name = Name
        self.ids._actr_lbl.text = Name

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
           self.selected = True
           self.pos_hint = {'top':1}
           self.hint_diff_touch_to_x = self.right - touch.x
           return True
        return super(Actor, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        if (self.selected) :
            future_right = touch.x +  self.hint_diff_touch_to_x
            if (future_right <= self.parent.size[0]) and ((future_right - self.width) >= 0) :
               self.right = future_right
               self.pos_hint = {'top':1}
               return True
        return super(Actor, self).on_touch_move(touch)

    def on_touch_up(self, touch):
        if (self.selected) :
            self.selected = False
            self.hint_diff_touch_to_x = 0
            self.iy = 0
            return True
        return super(Actor, self).on_touch_up(touch)

class MyPaintApp(App):

    def build(self):
        root = RelativeLayout()

        (ix, iy) = (100,100)

        clr = Color(0.2, 0.2, 1)

        for ix in [100, 200, 300, 400 ] :
            root.add_widget(Actor(Name = 'Actor ' + str(ix), pos=(ix,0), size_hint=(None,1)))

        return root

if __name__ == '__main__':
    Window.clearcolor = (1, 1, 1, 1)
    MyPaintApp().run()

A: When one of your Actor Widgets is selected, you can move it to the top by removing it and re-adding it, like this:
def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
       self.selected = True
       self.pos_hint = {'top':1}
       self.hint_diff_touch_to_x = self.right - touch.x
       parent = self.parent

       # move this Actor to the front
       parent.remove_widget(self)
       parent.add_widget(self)

       return True
    return super(Actor, self).on_touch_down(touch)


text:
Q: GeoDjango create model with LineStringField with buffer I've created a street model which is made of segments. Each segment starts and ends with a Sign (model). I decided to use LineStringField for the street representation but In order to intersect future points with it, I want to add some buffer to it so when users come to street, I'll be able to tell if they're within this street within buffer.
class Segment(models.Model):
    starts_with_sign = models.ForeignKey(Sign)
    ends_with_sign = models.ForeignKey(Sign)
    seg = models.LineStringField()

class Street(models.Model):
    name = models.CharField(max_length=200)
    is_one_way = models.BooleanField(blank=True, null=True, default=False)
    is_avenue = models.BooleanField(blank=True, null=True, default=False)
    has_public_transportation_lane = models.BooleanField(blank=True, null=True, default=False)
    parking_area = models.ForeignKey(Area) # for cities with parking areas
    segments = models.ForeignKey
    created = models.DateTimeField(auto_now_add=True)
    objects = models.GeoManager()
    def __unicode__(self):
        return self.name

My questions are:

*

*How do I add this buffer to the LineStringField?

*How do I assign Signs (points) to the
LineStringField?

*With a given coordinate, how do I query for the
segment which the point is in?

A: So after digging and rethinking all day long I've come up with some implementation ideas:

*

*Instead of adding buffer to each LineString which will make it a
Polygon (waste of data space?) and perform a point search for a relevant Polygon with a
given Point, after going over again on PostGIS ST_Buffer's docs
(Geom.buffer on GeoDjango) I understood a better (and faster) use for future queries would be
with PostGIS ST_DWithin ( <field>__<distance
lookup>=(<geometry>, <distance value>[, 'spheroid']) on
GeoDjango GeoQuerySets) and by that storing a Segment or street in this case would be with LineString.

*Thanks to this post, I've come up with this piece of code:
class Sign(models.Model):
    name = models.CharField(max_length=10)
    gps_point = models.PointField()
    objects = models.GeoManager()

    def __unicode__(self):
        return self.name

class Segment(models.Model):
    start_sign = models.ForeignKey(Sign, related_name='seg_start')
    end_sign = models.ForeignKey(Sign, related_name='seg_end')
    line = models.LineStringField(blank=True, null=True)
    objects = models.GeoManager()

    def save(self):
        super(Segment,self).save()
        if not self.line and self.start_sign and self.end_sign:
            self.line = LineString(self.start_sign.gps_point,self.end_sign.gps_point)
            self.save()

so by overriding save() I could assign LineString(self.start_sign.gps_point,self.end_sign.gps_point) to LineStringField once save is done.
Now all I have to deal with is assigning a start sign for segment's start point and end sign for segment's ending and the LineString object will be created for me :)

*So now I can just filter out the relevant street/segment just by Segment.objects.filter(line__distance_lte=(Point(lat,lon),D(m=required_distance)).

Cheers


text:
Q: Inline Edit (how to render a vuetifiy component based on the condition) Haii can anyone help me. I'm looping a array I want to render a field based on the condition. which I loop in simple table.my problem is that I'm directly
comparing the index value  (which is index === 0 and secondIndex === 0 ) like that  it seems to be a hardcode. It could be dynamic. I couldn't able to get as a dynamic.Could Anyone help me.
 <v-row v-for="(item, index) in list" :key="index" no-gutters>
          <v-col cols="12" sm="12" lg="12" xl="12">
            <v-card class="mt-2 rounded-xl" hover>
              <v-card-title v-if="index === 0" @mouseover="mouseOver = true" @mouseleave="mouseOver = false">
              </v-card-title>
              <v-card-subtitle class="pb-5 mt-3">
                <v-row class="ml-1 mt-1 text--primary">
                  <v-icon color="primary">{{item.icon}}</v-icon>

{{item.name}}

                </v-row>
                <v-file-input style="display: none" ref="file" accept="image/*" v-model="systemAndTenantConfig.systemconfiguration.logo" @change="uploadProfile()"></v-file-input>
              </v-card-subtitle>
                <v-card-text>
                 <v-form ref="configReference">

                      <v-simple-table align="justify" style="text-align:justify" v-for="(record, secondIndex) in item.tableValue" :key="secondIndex">
<v-hover v-slot:default="{ hover }">

                        {{record.label}}

{{record.value}}

                         <v-col cols="12" md="12" lg="12" xl="12" v-if=" index === 0 && secondIndex === 0  && indexValue === index && secondIndexValue === secondIndex ? show : false">
                            <v-text-field dense hide-details outlined :rules="systemAndTenantConfig.systemconfiguration.email ? $_emailValidation : []" :label="$t('email')" v-model="systemAndTenantConfig.systemconfiguration.email"></v-text-field>
                          </v-col>
                          <v-col cols="12" lg="12" v-if="index === 0 && secondIndex === 1 && indexValue === index && secondIndexValue === secondIndex ? show : false">
                           <v-autocomplete dense hide-details outlined :label="$t('timezone')" v-model="systemAndTenantConfig.systemconfiguration.timezone" :items="listOfTimeZones" item-text="displayname" item-value="standardname"></v-autocomplete>
                          </v-col>
                          </v-col>
                          <v-col cols="12" lg="12" v-if="index === 0 && secondIndex === 2 && indexValue === index && secondIndexValue === secondIndex ? show : false">
                            <v-textarea dense hide-details outlined :label="$t('companyAddress')" v-model="systemAndTenantConfig.systemconfiguration.companyaddress"></v-textarea>
                     </v-col>
                    <v-expand-transition>
                      <v-layout justify-end v-if="hover">
                        <v-fade-transition>

                            <v-btn text x-small icon color="info" v-if="showEdit">
                              <v-icon style="float:right" small  @click="getSingleRecord(index, secondIndex)" color="primary">{{record.icon}}</v-icon>
                            </v-btn>

                        </v-fade-transition>
                      </v-layout>
                    </v-expand-transition>

          </v-row>

     list:  [
            {
              name: this.$t('general'),
              icon: 'mdi-folder-multiple-outline',
              tableValue: [
              {
                label: 'Email',
                value: this.systemAndTenantConfig.systemconfiguration.email,
                icon: 'mdi-pencil',
                name: 'email'
              },
              {
                label: 'Phone',
                value: this.systemAndTenantConfig.systemconfiguration.phone,
                icon: 'mdi-pencil',
                name: 'phone'
              },
              {
                label: 'Company Address',
                value: this.systemAndTenantConfig.systemconfiguration.companyaddress,
                icon: 'mdi-pencil',
                name: 'address'
              }
              ]
         }]
     indexValue: ''
     secondIndexValue: ''

 getSingleRecord (firstIndex, secondIndex) {
      this.indexValue = firstIndex
      this.secondIndexValue = secondIndex

}


text:
Q: Abort GCM message broadcast not working below Android 4 Can't find a solution for this behavior:
When receiving a message from GCM the broadcast receiver from the manifest handles it correctly (creating a notification) but I want it to do another thing if the app is on screen (show a toast and cancel the notification).
Here is the code on the manifest:
    <receiver android:name="com.google.android.gcm.GCMBroadcastReceiverPlus"
              android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
    <!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<!-- Category -->
<category android:name="org.example.hello" />
</intent-filter>

And this is the code that works on JB, but not below:
    public BroadcastReceiver registerCustomBR(){
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.google.android.c2dm.intent.RECEIVE");
    filter.setPriority(1);
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getExtras().getString("text");
            CharSequence text = "Message received in app: " + message;
            Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
            toast.show();
            Log.i(TAG, "Message received: "+message);
            ElementWave.messageReceived(context, intent);
            abortBroadcast();
         }
     };

     this.registerReceiver(receiver, filter);
     return receiver;
}

Pretty new to android, so I hope there is a simple solution or anything obvious that I am missing...


text:
Q: Receiving push notifications twice We have been using Firebase to send push notifications for a couple of months in our app, and I have used it in other of my apps . Everything had gone well, however a week ago we started receiving duplicate notifications (not always). The strange thing is that we did not change any code, it just started to happen in both Android and iOS. It only happens sometimes not always, and only in some users/devices.
I want to know if someone else is going through this with Firebase. I think it is a  Firebase bug but I would like to see if someone can confirm something about it.
The ios app is made in swift, and the android app in Java.
BTW. We are sending it based on this with FCM in our back-end. And we have no duplicated topics. I have checked and devices are only subscribed once.
https://fcm.googleapis.com/fcm/send

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
  "to": "/topics/foo-bar",
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

Here my c# code in our back-end to send notifications
public void sendPushNotification(string _title, string _message, string _topic, object customData = null)
    {
        var requestUri = "https://fcm.googleapis.com/fcm/send";

        WebRequest webRequest = WebRequest.Create(requestUri);
        webRequest.Method = "POST";
        webRequest.Headers.Add(string.Format("Authorization: key={0}", FCM_SERVER_API_KEY));
        webRequest.Headers.Add(string.Format("Sender: id={0}", FCM_SENDER_ID));
        webRequest.ContentType = "application/json";

        var data = new
        {
            to = "/topics/" + _topic, // this is for topic
            notification = new
            {
                title = _title,
                body = _message,
                sound = "default"
            },
            data = customData, //custom data (got it from firebase documentation)
            content_available = true
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(data);
        Byte[] byteArray = Encoding.UTF8.GetBytes(json);
        webRequest.ContentLength = byteArray.Length;
        using (Stream dataStream = webRequest.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);

            using (WebResponse webResponse = webRequest.GetResponse())
            {
                using (Stream dataStreamResponse = webResponse.GetResponseStream())
                {
                    using (StreamReader tReader = new StreamReader(dataStreamResponse))
                    {
                        String sResponseFromServer = tReader.ReadToEnd();
                    }
                }
            }
        }
    }


text:
Q: Function to write in Excel I have written a function which writes data in an excel using POI. However at present I have to specify the rows and columns where the data is to be written in the parameters. I want to make this function generic that it should write the data automatically in the next column for a particular test case and should change the row when the test case changes.
public void WritetoExcel(String filepath,String DatatoWrite,int RowNum, int ColNum, int sheetnumber) throws Exception
    {
         FileInputStream ExcelFile = new FileInputStream(filepath);
         ExcelWBook = new XSSFWorkbook(ExcelFile);
        ExcelWSheet = ExcelWBook.getSheetAt(sheetnumber);

        try{
            Row  = ExcelWSheet.getRow(RowNum);
            Cell = Row.getCell(ColNum, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL);
            if (Cell == null) {
                Cell = Row.createCell(ColNum);
                Cell.setCellValue(DatatoWrite);
                } else {
                    Cell.setCellValue(DatatoWrite);
                }
            FileOutputStream fileOut = new FileOutputStream(filepath);
                ExcelWBook.write(fileOut);
                fileOut.flush();
                fileOut.close();
            }catch(Exception e){
                throw (e);
            }
        }

Can someone help me how can I do this?

A: public void WritetoExcel(String filepath, String DatatoWrite, int sheetnumber, boolean newTest) throws Exception {
        FileInputStream ExcelFile = new FileInputStream(filepath);
        ExcelWBook = new XSSFWorkbook(ExcelFile);
        ExcelWSheet = ExcelWBook.getSheetAt(sheetnumber);

        try {
            if (newTest) {
                Row = ExcelWSheet.createRow(RowNum++);
                cellnum=0;
            }
            Cell = Row.creatCell(cellnum++);
            Cell.setCellValue(DatatoWrite);
            FileOutputStream fileOut = new FileOutputStream(filepath);
            ExcelWBook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        } catch (Exception e) {
            throw (e);
        }
    }

so as i understand it, you have a blank excel sheet, which you want to fill with data. therefore you need to create a new row every time your boolean is true and always a new cell. the boolean is only true, if a new test case is run. make rownum and cellnum a member variable and set their value at startup to 0. this code requires an empty excel file.


text:
Q: How to do bar plot in the same scale and dimension as an image? I have an image, then I am projecting it on one of it's edges by some aggregation functions like mean. I am getting 1D digitized data this way. How to plot it exactly below source image in exactly the same horizontal or vertical scale?
Sample code:
% loading image
image = imread('..\..\FruitSample_small.png');

%computing gradients
dx=double(image(1:end-1,2:end,:))-double(image(1:end-1,1:end-1,:));
dy=double(image(2:end,1:end-1,:))-double(image(1:end-1,1:end-1,:));

% computing total magnitude
a=sqrt(sum(dx.^2,3)+sum(dy.^2,3));

% projection on bottom
h = mean(a,1);

% drawing
figure;
subplot(2,1,1);
imshow(image);

subplot(2,1,2);

bar(h);
axis image;

I want bar plot here to be of the same width as image above. Also I want histogram to spread exactly to the same horizontal coordinate, as image does.

A: The challenge here is that "axis image" enforces an aspect ratio on the image axis, which allows the display size of the image to vary from its set dimensions.  My suggestion is to forget the auto-sizing capabilities that come from normalized units, and adjust the sizes based on pixel sizing.  If you set the size of the image axis to exactly the size of the image in pixels, then it will have the correct aspect ratio, and you can use the same size for the bar plot.
load clown; % use a built-in demo image.  Note the image is now in X

%computing gradients
dx=double(X(1:end-1,2:end,:))-double(X(1:end-1,1:end-1,:));
dy=double(X(2:end,1:end-1,:))-double(X(1:end-1,1:end-1,:));

% computing total magnitude
a=sqrt(sum(dx.^2,3)+sum(dy.^2,3));

% projection on bottom
h = mean(a,1);

% drawing
figure;
subplot(2,1,1);
imagesc(X);
size_x = size(X,2);
size_y = size(X,1);
set(gcf, 'Units', 'pixels')
fp=get(gcf, 'Position');
set(gca, 'Units', 'pixels');
set(gca, 'Position', [(fp(3)-size_x) / 2, (fp(4)-size_y) / 2 + 100, ...
                      size_x, size_y]);

subplot(2,1,2);
bar(h);
set(gca, 'Units', 'pixels');
set(gca, 'Position', [(fp(3)-size_x) / 2, 100, size_x, 100]);
set(gca, 'XLim', [1 size_x]);

I'm computing the offsets automatically from the figure size, to center the results on the figure.  This is not resizeable.  You'd have to rerun the set('Position') stuff to readjust the locations if you resize the figure itself.  If you need it to be dynamically resizeable, you'd have to add a handler for a resize event, and adjust the sizes on every resize.


text:
Q: If $x$, $y$ and $z$ are distinct positive integers and $x+y+z=11$ then what is the maximum value of $(xyz+xy+yz+zx)$?
If $x$, $y$ and $z$ are distinct positive integers and $x+y+z=11$ then what is the maximum value of $(xyz+xy+yz+zx)$?

We know that product is maximum when difference between $x$, $y$ and $z$ is minimum.
So, I assumed $x=3$, $y=4$ and $z=4$.
Now putting this value in $xyz+xy+yz+zx$ I got my answer $88$. But actual answer is $78$. Where am I doing it wrong?

A: Note that $(x+1)(y+1)(z+1)=1+(x+y+z)+(xy+yx+zx)+xyz$ so the sum you want is $$(x+1)(y+1)(z+1)-12$$ which justifies your comment about the product.
If $a\gt a-1\ge b+1\gt b$ we have $$(a-1)(b+1)=ab+(a-b)-1\gt ab$$ since $a-b\ge 2$.
The best selection of distinct integers is (as others have noted) $5+4+2=11$. And the product formula gives $90-12=78$.

A: put $z=11-x-y$ in the equation and differentiate it with respect to $x$.
here are the values of $x$,$y$,$z$  for maximum value.
y=4.18   x=3.40   z=3.42  and maximum value is $77.11$.
However, I solved it using wolfram-math but you can solve it by following the instructions given.
However, my solution is for real numbers but you want it for integers.

A: the way the question is worded, $x$ and $y$ and $z$ cannot be equal (they must instead be distinct) so $y$ and $z$ cannot be $4$.
so the correct answer is choosing $5$, $4$ and $2$ for $x$, $y$ and $z$.

A: For $x=5$, $y=4$ and $z=2$ we get a value $78$.
We'll prove that it's a maximal value.
Indeed, let $x<y<z$, $x=1+a$, $y=2+a+b$ and $z=3+a+b+c$,
where $a$, $b$ and $c$ are no-negative integer numbers.
Thus, the condition gives
$$1+a+2+a+b+3+a+b+c=11$$ or
$$3a+2b+c=5,$$
which says that $a\in\{0,1\}$.
Now, let $a=0$.
Thus, $x=1$, $y+z=10$ and we need to prove that
$$y+z+2yz\leq78$$ or
$$yz\leq68,$$
which follows from AM-GM:
$$yz\leq\left(\frac{y+z}{2}\right)^2=25<68.$$
Let $a=1$.
Hence, $x=2$, $y+z=9$, $z\geq5$ and we need to prove that
$$2y+2z+3yz\leq78$$ or
$$yz\leq20$$ or
$$(9-z)z\leq20$$ or
$$(z-4)(z-5)\geq0,$$
which is obvious.
By the same way we can prove that $42$ is a minimal value,
where the equality occurs for $(x,y,z)=(1,2,8)$.
Indeed, if $a=0$ then we get $x=1$, $y\geq2$, $y+z=10$, $6\leq z\leq8$ and we need to prove that
$$xy+xz+yz+xyz\geq42$$ or
$$y+z+2yz\geq42$$ or
$$yz\geq16$$ or
$$(10z)z\geq16$$ or
$$(8-z)(z-2)\geq0,$$ which is obvious.
If $a=1$ then $x=2$, $y\geq3$, $y+z=9$, $5\leq z\leq6$ and we need to prove that
$$2(y+z)+3yz\geq42$$ or
$$yz\geq8$$ or
$$(9-z)z\geq8$$ or
$$(8-z)(z-1)\geq0,$$
which is obvious.
Done!

A: $11$ is reasonably small. So we can search exhaustively through the options to find maximum $f=xyz+xy+yz+zx$.
Take $x<y<z$. Then smallest values for $x,y$ are $1,2$ and thus greatest $z=8$. Then we can work down values of $z$ and partition the residue accordingly, avoiding duplicates.
$\begin{array}{|c|c|} \hline
(x,y,z) & f\\ \hline
(1,2,8) & 42 \\
(1,3,7) & 52 \\
(1,4,6) & 58 \\
(2,3,6) & 72 \\
(2,4,5) & 78 \\ \hline
\end{array}$


text:
Q: Nested exception org.hibernate.MappingException: Duplicate column solution in mapping for entity @Entity
public class Tar {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Foo fooOne;
    private Foo fooTwo;
    //Getters and setters, equals and hashCode methods omitted for brevity
}

@Embeddable
public class Foo {

    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    private Bar bar;

    //Getters and setters, equals and hashCode methods omitted for brevity
}

@Entity

public class Bar {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NaturalId
    private String name;

    //Getters and setters, equals and hashCode methods omitted for brevity
}

################  Solution   ################

@Entity
@AttributeOverrides({
        @AttributeOverride(
                name = "fooOne.name",
                column = @Column(name = "foo_one_name")
        ),
        @AttributeOverride(
                name = "fooTwo.name",
                column = @Column(name = "foo_two_name")
        )
})
@AssociationOverrides({
        @AssociationOverride(
                name = "fooOne.bar",
                joinColumns = @JoinColumn(name = "foo_one_bar_id")
        ),
        @AssociationOverride(
                name = "fooTwo.bar",
                joinColumns = @JoinColumn(name = "foo_two_bar_id")
        )
})
public class Tar {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Foo fooOne;
    private Foo fooTwo;
    //Getters and setters, equals and hashCode methods omitted for brevity
}

in case we need to use the same type of attributes, we can use them by overriding them and putting them in the appropriate format as stated above.
Hibernate: create table tar (id int8 generated by default as identity, foo_one_name varchar(255), foo_two_name varchar(255), foo_one_bar_id int8, foo_two_bar_id int8, primary key (id))
Remember that you cannot create columns from the same names in a table.


text:
Q: How to build buffers for each polygon, which requires the buffer area approximately equal the polygon area in Google Earth Engine? I want to build buffers for each irregular polygon in featurecollections in Google Earth Engine. The buffer area is required to approximately equal the polygon area. I am very new to GEE.

A: I don't think there is a "established" way to compute buffer in GEE based on obtaining approximately equal area. Well "approximate" is kind of a loose term but I have gotten more than 1.9 in area of buffered feature and original feature for differently shaped feature with this method.
First, we assume a regular rectangle and try to calculate the buffered area based on that.
It should be

original perimeter X buffer distance + 4 x (buffer distance)^2

and that should be equal to the area of the original feature. Since that is a simple quadratic equation, solving that gave me

buffer distance = ( -p + sqrt(p^2 +16a))/8

taking only positive values coz we know we want to grow the feature. So i put that formula in gee. You can see the full code here
function bufferequal(feature){
  var ar = feature.area();
  var perim = feature.perimeter();

  var rooted = perim.pow(2).add(ar.multiply(16)).sqrt();
  var nomin = rooted.subtract(perim);

  var soln = nomin.divide(8);

  var buff = feature.buffer(soln);

  return buff;
}

The next thing for your question should be how to apply this to each feature of a feature collection. That would be to use this function as a mapping function as follows.
var bufferedCollection = yourFeatureCollection.map(bufferequal);

Once again, this WILL NOT give you exactly equal area but since you said you wanted approximate area, i like this method over the iterative methods.


text:
Q: I want to go back to specific page of a tabViewController from different viewController I have implemented a tabViewController with some pages. one of those page is a tableview controller. after clicking on tableview item i am opening another viewController. Now i want to go back to that specific page. the selectedIndex of that tab Page is 1.
How can i do this?
Thanks for your help
store board

A: Try this
let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController

tabBar.selectedIndex = 1

A: If you are outside from tabBar Controller.
self.tabBarController?.selectedIndex = 1

If you are already in tabBar Controller and move to another tabBar Controller. Go to the ViewDid of TabBar method and paste the code.
     override func viewDidLoad() {
        super.viewDidLoad()
        self.selectedIndex = 1
    }

A: If you want the user to be able to go back to tableViewController after clicking on a cell you should use a navigationController instead.

A: You are using UITabBarController as rootViewController then can do this:
if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
        if let rootTabBarController = appDelegate.window?.rootViewController as? UITabBarController{
            rootTabBarController.selectedIndex = 1
        }
    }


text:
Q: Why am I getting "you may delete this post in 2 days" when trying to delete my question I've just tried to delete my previous question. Instead of being deleted, this naughty question throws this error:

Why is that?

*

*today I deleted only one post of mine

*today I voted to delete two posts and having three daily votes left

*the two-days limit typically applies only when deleting not my posts

I thought this was fixed...

A: You have no idea how convoluted the deletion voting code is... seems I missed an edge case with 10K rep users when originally removing the self-delete restriction of closed questions.
A test has been written (for what that's worth) and a fix will be push out shortly.


text:
Q: Ember.js hasDirtyAttributes still returns true after save         this.store.findRecord('meeting',this.get('model.meeting.id')).then(function(meeting) {
            meeting.save();
            console.log(meeting.get('hasDirtyAttributes'));
        });

Why does this console log 'true'? Shouldn't this save all the attributes and make it so that none are dirty?

A: model.save() will sent a request to the server to save the attributes. Until that request is is done hasDirtyAttributes will remain true.
If you want to be sure that your model is in a saved state you have to wait for the promise to resolve:
model.save().then(m => {
  console.log(Ember.get(m, 'hasDirtyAttributes')); // false
});


text:
Q: Is there a way to display column relationships with a third column? So I have these tables in a database:
fish (id, f.name, image, cooking_type_id)
cooking_type (id, name, thumbnail)
If I display a list of all the fishes, how do I display the correct thumbnails for type_id?
I'm having troubles finding the right information. Right now I'm stuck with this query:
$query = "SELECT `f.name`, `image`, `type_id`
            FROM fish";

    $result = $mysqli->query($query);
    $mysqli->set_charset("utf8");
    while($row = mysqli_fetch_array($result)){
        echo '
';

        echo '
';
        echo '
';
        echo $row['image'];
        echo '

';

        echo '
';
        echo '

';
        echo $row['f.name'];
        echo '

';

        echo '
';
        echo '
';
        echo '';
        echo '

';

A: You want this query.
 SELECT f.name, f.image, c.thumbnail
   FROM fish f
   JOIN cooking_type c ON f.cooking_type_id = c.id

You use the the ON clause in your JOIN operation to express how the rows of fish relate to the rows of cooking_type.
If you have multiple tables, you can use a series of JOIN operations to relate them. For example:
 SELECT f.name, f.image, c.thumbnail, m.market_name, m.price, p.pan_type
   FROM fish f
   JOIN cooking_type c ON f.cooking_type_id = c.id
   JOIN fishmarket m ON f.name = m.species_name
   JOIN pan p ON c.name = p.cooking_type_name


text:
Q: PHP : Fixing server time (localhost) For  my page when user  logs in  i've to save his  first login time , in my DB i've a field called loggedin,  and  in my login  function  i do this in query
set loggedin= now()

this saves something like  this   2015-12-21 09:43:57. now when user logs in again I've to   compare todays date with saved time in db to check  if there is already a  logged in entry for today,
but problem is that when i enter  time using NOW() it  enters my server time but when i try to make a  comparison by todays time
$today= time();
echo(date("Y-m-d",$today))

this shows me one day back i mean if its 21 today its showing  me  2015-12-20
so whats wrong with this ?

A: use date_default_timezone_set
date_default_timezone_set(your timezone);
$today= time();
echo(date("Y-m-d",$today))

A: date_default_timezone_set('Asia/Dubai');
$today= time();
echo(date("d-m-Y",$today));
echo "
";
echo date("h:i:sa");
echo "
";

Try this code if it helps you.


text:
Q: need to convert each line of file in to separate files in PowerShell I have text file with 2 to 3 lines of text, each line is a path. I have to take that file as an input and each line has to be converted to a seperate file. Please help me with the syntax to do with in powershell
below is an input file content
Explore/XXx/XXXX/APC-SMTXXX.AI_SERVICE_CONNECTOR.xml
Explore/XXX/XXX/APC-SMTPYYY_SERVICE_CONNECTOR.xml
each line has to be in 2 separate text files


text:
Q: Regex for range 0.01-100000 JS How to create regEx from getting result is number in range from 0.01 to 1 000 000
Thanks

A: The answer is that you wouldn't want a regular expression for that.
Instead you can simply test your number like n >= 0.01 && n <= 100000.


text:
Q: Sporadic timeouts from directline endpoint We have deployed a simple Echobot using the Azure template when creating a Web App Bot.
It is currently live at this url: http://18.194.88.194/echobot/
We often experience the following timeout error (about 40% of the time)

WebSocket connection to
  'wss://directline.botframework.com/v3/directline/conversations/EH9EbbBIasz8o90sZSeAwT-9/stream?watermark=-&t=ew0KICAiYWxnIj...(snip)
  failed: Error in connection establishment:
  net::ERR_CONNECTION_TIMED_OUT

Here is our client code:
botclient.js
(async function() {
  let {token, conversationId} = sessionStorage;

  const delay = 1800000;
  //const delay = 20000;
  const currentTime = new Date();
  const currentTimeUnix = currentTime.getTime();

  if (
    sessionStorage['startTime'] &&
    currentTimeUnix - sessionStorage['startTime'] > delay
  ) {
    sessionStorage.removeItem('token');
    token = sessionStorage['token'];
  }

  const payload = JSON.stringify({botname: 'echobot'});

  if (!token) {
    const res = await fetch(
      'https://ox38xh0fx5.execute-api.eu-central-1.amazonaws.com/dev/directline/token',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: payload,
      },
    );
    const {token: directLineToken} = await res.json();
    sessionStorage['token'] = directLineToken;
    token = directLineToken;

    console.log('token', token);
    const startTime = new Date();
    const startTimeUnix = startTime.getTime();
    sessionStorage['startTime'] = startTimeUnix;
  }

  const data = {
    // from: user,
    name: 'requestWelcomeDialog',
    type: 'event',
    value: {
      url: window.location.href,
    },
  };

  var botConnection = new window.WebChat.createDirectLine({token});

  window.WebChat.renderWebChat(
    {
      directLine: botConnection,
      userID: 'YOUR_USER_ID',
      username: 'Web Chat User',
      locale: 'en-US',
    },
    document.getElementById('webchat'),
  );
})().catch(err => console.log(err));

index.html
<!DOCTYPE html>

The token is being retrieved from an AWS lambda function with the following code:
import json
import boto3
from urllib.parse import urlencode
from urllib.request import Request, urlopen

BOT_SECRET = 'defaultSecret'

URL = 'https://directline.botframework.com/v3/directline/tokens/generate'
POST_FIELDS = {'foo': 'bar'}

def set_headers(req, secret):
    req.add_header('Content-Type', 'application/json')
    req.add_header('Authorization', f'Bearer {secret}')
    return req

def lambda_handler(event, context):
    print(event)
    s3 = boto3.client('s3')

    if event.get('botname', None) == 'echobot':
        response = s3.get_object(Bucket='directline', Key='echobotSecret')
    else:
        response = s3.get_object(Bucket='directline', Key=BOT_SECRET)
    secret = response['Body'].read().decode('utf-8').rstrip()
    request = Request(URL, urlencode(POST_FIELDS).encode())
    request = set_headers(request, secret)
    jsonresponse = urlopen(request).read()

    print(jsonresponse)
    return jsonresponse

We suspect that there is an issue with the local network configuration, and packets are being dropped. Are there any pointers for how to handle this?

A: I looked into our backend logs for the conversation ID you included and it looks like the token needs to be refreshed. See the Authentication docs for refreshing tokens.
It looks like your code attempts to account for token expiration, but:

*

*1800000 is the default expiration. It might be best to shorten your delay a bit to account for request travel time and other factors to ensure your tokens don't expire.

*You appear to only get the token once, when the chat window is opened. It may expire mid-conversation

That being said, this may not be a token issue. Can you try disabling websockets with:
[...]
window.WebChat.renderWebChat(
    {
      directLine: botConnection,
      userID: 'YOUR_USER_ID',
      username: 'Web Chat User',
      locale: 'en-US',
      webSocket: false // ADD THIS !!!!
    },
    document.getElementById('webchat'),
[...]

If this is a local packet loss issue, I'm afraid there's not much support I can provide as it's no longer a botframework problem and is likely very specific to your local network. If you can provide additional Conversation IDs, I might be able to dig into this further. But over the last 2 days, your bot appears pretty normal on our side.


text:
Q: What is your system for avoiding keyword naming clashes? Typically languages have keywords that you are unable to use directly with the exact same spelling and case for naming things (variables,functions,classes ...) in your program. Yet sometimes a keyword is the only natural choice for naming something. What is your system for avoiding/getting around this clash in your chosen technology?

A: I just avoid the name, usually. Either find a different name or change it slightly - e.g. clazz instead of class in C# or Java. In C# you can use the @ prefix, but it's horrible:
int @int = 5; // Ick!

A: There is nothing intrinsically all-encompassing about a keyword, in that it should stop you from being able to name your variables. Since all names are just generalized instances of some type to one degree or another, you can always go up or down in the abstraction to find another useful name.
For example, if your writing a system that tracks students and you want an object to represent their study in a specific field, i.e. they've taken a "class" in something, if you can't use the term directly, or the plural "classes", or an alternative like "studies", you might find a more "instanced" variation: studentClass, currentClass, etc. or a higher perspective: "courses", "courseClass" or a specfic type attribute: dailyClass, nightClass, etc.
Lots of options, you should just prefer the simplest and most obvious one, that's all.
I always like to listen to the users talk, because the scope of their language helps define the scope of the problem, often if you listen long enough you'll find they have many multiple terms for the same underlying things (with only subtle differences). They usually have the answer ...
Paul.

A: My system is don't use keywords period!
If I have a function/variable/class and it only seems logical to name it with a keyword, I'll use a descriptive word in front of the keyword.
(adjectiveNoun) format. ie: personName instead of Name where "Name" is a keyword.

A: I just use a more descriptive name. For instance, 'id' becomes identifier, 'string' becomes 'descriptionString,' and so on.

A: In Python I usually use proper namespacing on my modules to avoid name clashes.
import re
re.compile()

instead of:
from re import *
compile()

Sometimes, when I can't avoid keyword name clashes I simply drop the last letter off the name of my variable.
for fil in files:
    pass

A: As stated before either change class to clazz in Java/C#, or use some underscore as a prefix, for example
int _int = 0;

A: There should be no reason to use keywords as variable names.  Either use a more detailed word or use a thesaraus.  Capitalizing certain letters of the word to make it not exactly like the keyword is not going to help much to someone inheriting your code later.

A: Happy those with a language without ANY keywords...
But joke apart, I think in the seldom situations where "Yet sometimes a keyword is the only natural choice for naming something." you can get along by prefixing it with "my", "do", "_" or similar.
I honestly can't really think of many such instances where the keyword alone makes a good name ("int", "for" and "if" are definitely bad anyway). The only few in the C-language family which might make sense are "continue" (make it "doContinue"), "break" (how about "breakWhenEOFIsreached" or similar ?) and the already mentioned "class" (how about "classOfThingy" ?).
In other words: make the names more reasonable.
And always remember: code is WRITTEN only once, but usualy READ very often.

A: Typically I follow Hungarian Notation.  So if, for whatever reason, I wanted to use 'End' as a variable of type integer I would declare it as 'iEnd'.  A string would be 'strEnd', etc.  This usually gives me some room as far as variables go.
If I'm working on a particular personal project that other people will only ever look at to see what I did, for example, when making an add-on to a game using the UnrealEngine, I might use my initials somewhere in the name.  'DS_iEnd' perhaps.

A: I write my own [vim] syntax highlighters for each language, and I give all keywords an obvious colour so that I notice them when I'm coding. Languages like PHP and Perl use $ for variables, making it a non-issue.

A: Developing in Ruby on Rails I sometime look up this list of reserved words.

A: In 15 years of programming, I've rarely had this problem.
One place I can immediately think of, is perhaps a css class, and in that case, I'd use a more descriptive name.  So instead of 'class', I might use 'targetClass' or something similar.

A: In python the generally accepted method is to append an '_'
class -> class_
or -> or_
and -> and_

you can see this exemplified in the operator module.

A: I switched to a language which doesn't restrict identifier names at all.

A: First of all, most code conventions prevent such a thing from happening.
If not, I usually add a descriptive prose prefix or suffix:
the_class or theClass infix_or (prefix_or(class_param, in_class) , a_class) or_postfix

A practice, that is usually in keeping with every code style advice you can find ("long names don't kill", "Longer variable names don't take up more space in memory, I promise.")
Generally, if you think the keyword is the best description, a slightly worse one would be better.
Note that, by the very premise of your question you introduce ambiguity, which is bad for the reader, be it a compiler or human. Even if it is a custom to use class, clazz or klass and even if that custom is not so custom that it is a custom: it takes a word word, precisely descriptive as word may be, and distorts it, effectively shooting w0rd's precision in the "wrd". Somebody used to another w_Rd convention or language might have a few harsh wordz for your wolds.
Most of us have more to say about things than "Flower", "House" or "Car", so there's usually more to say about typeNames, decoratees, class_params, BaseClasses and typeReferences.
This is where my personal code obfuscation tolerance ends:
Never(!!!) rely on scoping or arcane syntax rules to prevent name clashes with "key words". (Don't know any compiler that would allow that, but, these days, you never know...).
Try that and someone will w**d you in the wörd so __rd, Word will look like TeX to you!

A: My system in Java is to capitalize the second letter of the word, so for example:
 int dEfault;
 boolean tRansient;
 Class cLass;


text:
Q: RoR nested categories folks!
I wonder how to make url like: site.com/coding/ruby/rails/article-name
As you can see there is nested category. I've already looked at acts-as-tree and awesome nested sets, but it makes urls like site.com/rails/article-name.
So, please help me

A: If you want to use a resource-ful controller, make a route like this:
scope '(*categories)' do
  resources :articles
end

this will require using 'article' at the end of your urls: /coding/ruby/rails/articles/article-name
or you can use a route like this:
match '(*categories)/:id' => 'articles#show', :as => :article

this will let you do article_path(:categories => 'coding/ruby/rails', :id => article.friendly_id)
to get /coding/ruby/rails/article-name
If you are using awesome_nested_set, you could generate the categories string by doing something like
article.category.self_and_ancestors.join("/")

A: You could try using Friendly-id.

A: To set this up, you start with a route that does "route globbing":
match "*category" => "categories#show"
or
match "categories/*category" => "categories#show"
in your controller, you will receive all the parts of of the url through the params hash. To keep things clean, define the search logic in your model
def show
  @category = Category.find_recursive(*params[:categories])
end

in your model, define a method to find the category. I am assuming acts_as_tree is defined in your model
def self.find_recursive(*categories)
  children = roots
  last = nil
  categories.each do |category|
    return unless children

    last = children.find_by_permalink(category)
    children = last.children
  end
  last
end


text:
Q: $w =\sum_{1\leq i< j\leq 7}z_i z_j =0$ If $z_i$ lies on a unit circle. Let $z_1, z_2, ......,z_7$ be the vertices of a regular
heptagon that is inscribed in the unit circle with
centre at the origin in the complex plane. Let
$w =\sum_{1\leq i< j\leq 7}z_i z_j$, then |w| is equal to ______
My Attempt : If one of the vertex is $(1,0)$ then I am done. $w =\sum_{1\leq i< j\leq 7}z_i z_j  =0$
But if we tilt the polygon in any direction with respect to the origin so that $(1,0)$ does not remain a vertex of the polygon  then what will happen?

A: $$\sum_{1 \le i <j \le 7} z_i z_j= \frac{1}{2} \left[\left(\sum_{k=1}^7 z_k\right )^2-\sum_{k=0}^7  z_k^2\right]$$ Since $z_k$ are the roots of $z^7=1$ so  both $\sum_k z_k$ and $\sum_k z_k^2$ are zero, hemce $w=0$.
Or simply the required expression the value of sum of the par-wise products of rotts $z_k$ of $z^7-1=0$


text:
Q: How to program relative path from string in Java I have the following problem. I am writing a program that imitates Windows Command prompt. For example user enters: cd C:\\Intel and in my code I solve it like this:
setCurrentPath(Paths.get(string));

where setCurrentPath is a method which sets the current path to the one which is entered (string). My problem is that, how can I set new path if the entered path is relative. For example, if I am currently in C:\\Intel and user wants to go to C:\\Intel\\Logs and enters: cd Logs (instead of C:\\Intel\\Logs). I suppose there are some methods build in Java which can help me out but I am learning Java only a few months so I am unaware of them. Be aware that I threat path as a string.

A: You could test if path from user is absolute or not and based on result either set it directly, or use Path.resolve.
DEMO:
Path currentPath = Paths.get("C:\\projects\\project1");
String pathFromUser = "..\\project2";

Path userPath = Paths.get(pathFromUser);

if (userPath.isAbsolute()){
    currentPath = userPath;
}else{//is relative
    currentPath = currentPath.resolve(userPath).normalize();
}

System.out.println(currentPath);

Output: C:\projects\project2

A: Use the isAbsolute() method to check the input and then use the resolvePath if the isAbsolute() method returns false.
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#isAbsolute()
The reason why you have to check if the path is absolute first is described below for the resolve method:
Path resolve(Path other)

Resolve the given path against this path. If the other parameter is an
  absolute path then this method trivially returns other. If other is an
  empty path then this method trivially returns this path. Otherwise
  this method considers this path to be a directory and resolves the
  given path against this path. In the simplest case, the given path
  does not have a root component, in which case this method joins the
  given path to this path and returns a resulting path that ends with
  the given path. Where the given path has a root component then
  resolution is highly implementation dependent and therefore
  unspecified.

https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#resolve(java.nio.file.Path)


text:
Q: Create table of records from subsets of a dataframe in python using datetime column Be the following pandas DataFrame in Python:

ID
date
direction

0
2022-01-03 10:00:01
IN

0
2022-01-03 11:00:01
IN

0
2022-01-03 11:10:01
OUT

0
2022-01-03 12:00:03
IN

0
2022-01-03 14:32:01
OUT

1
2022-01-03 10:32:01
OUT

1
2022-01-04 11:32:01
IN

1
2022-01-04 14:32:01
OUT

2
2022-01-02 08:00:01
OUT

2
2022-01-02 08:02:01
IN

I need to get the check-in and check-out for each group by ID. Considering that an entry_date is registered by direction = IN and an exit_date by direction = OUT. The idea is to create the record as follows:

ID
entry_date
exit_date

0
2022-01-03 10:00:01
2022-01-03 11:10:01

0
2022-01-03 12:00:03
2022-01-03 14:32:01

1
2022-01-04 11:32:01
2022-01-04 14:32:01

They are only recorded if a row with IN appears first and closes the record with a row with OUT as value for direction column (there may be more rows in between with a value of direction IN, as can be seen in the example).
I hope you can help me, thank you in advance.

A: I'm not sure I completely understand, but here's an attempt.
After sorting along the date column (date should be datetime): Group on ID and then eliminate in three steps all rows that don't fit into the required pattern: 1. eliminate OUT-blocks at the beginning of every group. 2. reduce consecutive blocks of IN/OUTs in each group to the first one. 3. Remove the the last row of the group if it is an IN-row. The rest is essentially splitting the resulting dataframe in 2 interlaced parts and concatenating them next to another.
def connect(df):
    df = df[df["direction"].cummax()]
    df = df[df["direction"].diff().fillna(True)]
    if df.shape[0] % 2:
        df = df.iloc[:-1]
    return df

result = (
    df
    .assign(direction=df["direction"].replace({"IN": True, "OUT": False}))
    .sort_values(["ID", "date"])
    .groupby("ID").apply(connect)
    .drop(columns="direction")
    .droplevel(-1, axis=0)
)
result = pd.concat(
    [result.iloc[0::2], result[["date"]].iloc[1::2]], axis=1
).reset_index(drop=True)
result.columns = ["ID", "entry_date", "exit_date"]

Result:
   ID          entry_date           exit_date
0   0 2022-01-03 10:00:01 2022-01-03 11:10:01
1   0 2022-01-03 12:00:03 2022-01-03 14:32:01
2   1 2022-01-04 11:32:01 2022-01-04 14:32:01

Another solution would be to group by ID, and then, in each group, split the directions in 2 stacks, the ins and outs, and run through them to gather the connections:
def connect(df):
    mask = df["direction"].eq("IN")
    ins = list(reversed(df.loc[mask, "date"].values))
    outs = list(reversed(df.loc[~mask, "date"].values))
    connects = []
    if ins:
        dt_out = ins[-1] + pd.Timedelta(days=-1)
    while ins and outs:
        dt_in = None
        while ins:
            dt = ins.pop()
            if dt > dt_out:
                dt_in = dt
                break
        while dt_in and outs:
            dt_out = outs.pop()
            if dt_in < dt_out:
                connects.append([dt_in, dt_out])
                break
    return pd.DataFrame(
        connects, columns=["entry_date", "exit_date"]
    )

result = (
    df.sort_values(["ID", "date"]).groupby("ID").apply(connect)
      .droplevel(1, axis=0).reset_index()
)


text:
Q: String Parsing using tcl I am trying to parse a string to return the text between two sets. For example, my string is: "faultstring>Item not valid: The specified Standard SIP1 Profile was not found faultstring>"
I want to write a function that will return the string: Item not valid: The specified Standard SIP1 Profile was not found
I am new to tcl and your help is very much appreciated.
Please let me know.
Thanks.

A: Assuming there is no faultstring> inside the interesting string, and there might be some uninteresting garbage before and after specified fragment:
set testString "faultstring>Item not valid: The specified Standard SIP1 Profile was not found faultstring>"

if {[regexp {faultstring>(.*)faultstring>} $testString _ extracted]} {
     puts "Got it: $extracted"
}

The answer may vary for other assumptions.


text:
Q: FileNotFoundException when accessing an image with Korge I have an Android application and I used Korge dependencies to make my game. I'm trying to load an image and I got a FileNotFoundException exception, wherever I put the file. Here's my code :
val topArrowImg = resourcesVfs["top_arrow.png"].readBitmap()

And my project structure :

Does anyone know where I have to put this file ?
Thanks,

A: resourcesVfs points to files in src/main/res, e.g. resourcesVfs["top_arrow.png"] points to the file at src/main/res/top_arrow.png


text:
Q: DNS leak with Shrew Soft VPN client on Windows 10 I am using the Shrew Soft VPN client v2.2.2 to connect to a remote network. Everything works fine, except that I am experiencing a DNS leak according to https://dnsleaktest.com/.
In the VPN client, I already checked to use the DNS servers provided by the VPN server:

I also checked to Obtain Topology Automatically or Tunnel All:

According to https://dnsleaktest.com/ both DNS servers are used: the local one and the remote one (VPN). So some kind of load balancing occurs. Using Get-DnsClientServerAddress in PowerShell, I can confirm that Windows is aware of both DNS servers (local and remote). The local DNS servers are received from the physical NIC and the remote DNS servers are received from the virtual Shrew Soft NIC. So I am quite sure, that load balancing is occuring, which is very undesirable in this scenario.
Is there anything I can configure comfortably to use the local DNS servers when not connected to a VPN and to only use the VPN DNS servers when connected to a VPN?

A: You could run a command script to modify the DNS servers on your leaking interface.
I.e., if your physical interface is named "Ethernet" and its IP is statically configured with DNS statically confgured, then run a command script as administrator with this line:
netsh dnsclient delete dnsserver "Ethernet" all

You will get a message
There are no Domain Name Servers (DNS) configured on this computer.

perhaps, or maybe you just get that in my case where I only have the one. When I tried this on a DHCP config for this interface, the DNS server was set by DHCP when I removed the static one. Windows really wants you to have a DNS server.
After your VPN is up. See if you get leaks then.
Before you tear down your VPN, add back your DNS server to the interface with
netsh dnsclient add dnsserver "Ethernet" 192.168.1.1 (for example)

A: TL;DR
Apply the highest priority (lowest metric value) to your VPN interface in comparison to other interfaces and reboot your machine to make all services aware of the new metric:
Set-NetIPInterface -InterfaceIndex <INDEX_OF_VPN_IF> -InterfaceMetric 1

Explanation
Windows 10 uses the Automatic Metric feature to determine the metric of each network interface automatically. You might expect, that Windows uses the metric just for routing purposes, but it also uses it to select the primary DNS server. You can read more about this in this excellent answer.
In my case, a metric of 55 was assigned to my virtual VPN interface, 50 to my physical WiFi interface and 5 to my physical Ethernet interface. You can check the current metrics with the following PowerShell command:
Get-NetIPInterface | Select-Object -Property InterfaceIndex, InterfaceAlias, InterfaceMetric

I then changed the metric of my virtual VPN interface to 1:
Set-NetIPInterface -InterfaceIndex <INDEX_OF_VPN_IF> -InterfaceMetric 1

The change was visible with Get-NetIPInterface immediately, but the services did not seem to be aware of that change already. After a reboot, everything worked as expected. The VPN interface with its DNS server was highest priority and I did not suffer a DNS leak anymore.
It might not be 100% stable though, as the other DNS servers are still available and will be chosen, if the DNS server of VPN connection does not answer in time.


text:
Q: Rails Devise Mailer undefined method I'm having issues now that i've added devise to my web app, theres a few SO questions on this but they just all point to a readme file and don't actually provide any fixes. I've had to include devise helpers as shown below in order to remove an issue saying the authentication method didn't exist
class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
 fixtures :all

      # Add more helper methods to be used by all tests here...
  include Devise::TestHelpers
end

If i don't include it i end up with a huge amount of authentication errors:
ActionView::Template::Error: undefined method `authenticate' for nil:NilClass

but if it is included
 NoMethodError: undefined method `env' for nil:NilClass

Simply occurs in different places instead, is there an actual fix?
Example
ContactMailerTest#test_should_return_contact_email:
NoMethodError: undefined method `env' for nil:NilClass

Method:
test "should return contact email" do
mail = ContactMailer.contact_email("Email@Email.com", "Example",
                                   "SomeExample", @comment = "Hello")
assert_equal ['info@mynotes.com'], mail.to
assert_equal ['info@mynotes.com'], mail.from
end

This appears to be an issue with "Apparently there are issues with Devise::TestHelpers and integration testing" i am wondering if there is any known fix
Thanks!


text:
Q: Cannot DROP/ALTER a VIEW because other objects depend on it I need to ALTER a VIEW in order to add an additional field but I am unable to alter/drop it because other objects (several functions and views) depend on it. Is there any way to alter the view without having to drop and create the existing functions and views that depend on it? Do you have any suggestion?
Thanks.


text:
Q: Admob Banner Ads are not working properly in Unity3D I integrate Ad-mob banner ads in my Unity game project android build
But Sometimes the ad is showing but most of time it's not
showing percentage will be just just 4% out of 100%
I don't know why this happening
I got this following code from developers.google and i am able to show ads but it does not show the banner app on every startup frankly speaking it only shows ads in first or 2nd startup after build and not anymore.
I try to find solutions but looks like all solutions are same.
So, I am Stuck in here
using System.Collections;
using System.Collections.Generic;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using UnityEngine;

public class BannerAd : MonoBehaviour
{

    private BannerView bannerView;

    // Use this for initialization
    void Start ()
    {
        string appID = "ca-app-pub-id"; // this is appId

        MobileAds.Initialize (appID);

        string adUnitId = "ca-app-pub-adUnitId"; // adUnitID

        this.showBannerAd (adUnitId);
    }

    private void showBannerAd (string adUnitId)
    {

        //Create a custom ad size at the bottom of the screen

        AdSize adSize = new AdSize (250, 50);
        bannerView = new BannerView (adUnitId, adSize, AdPosition.Bottom);

        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder ().Build ();

        // Load the banner with the request.
        bannerView.LoadAd (request);

        StartCoroutine(bannerAdTime());
    }

    IEnumerator bannerAdTime ()
    {
        yield return new WaitForSeconds (300f);

        RequestNewAd();
    }

    private void RequestNewAd ()
    {
        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder ().Build ();

        // Load the banner with the request.
        bannerView.LoadAd (request);

        StartCoroutine(bannerAdTime());
    }

    // Update is called once per frame
    void Update ()
    {

    }
}

A: 1.Check you have install plugin as document https://github.com/unity-plugins/Unity-Admob
2.Edit AndroidManifest.xml and config Admob APP ID
This configuration is reqired by admob from version 17.0,APP will crash if not config .Add a meta-data tag in application and set value to your admob appid
<meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="your admob app id"/>

Sample code
    <application  android:theme="@style/UnityThemeSelector"
   android:icon="@drawable/app_icon"
   android:label="@string/app_name" >
           <activity
        android:name="com.unity3d.player.UnityPlayerActivity"
        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.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-3940256099942544~3347511713"/>
  </application>

3.Init Admob Unity Plugin
Create A C# script ,drag the script to a object on scene , add the follow code in the script file
using admob;
Admob.Instance().initSDK("admob appid", new AdProperties());//admob id with format ca-app-pub-3940256099942544~3347511713
//Admob.Instance().initAdmob("ca-app-pub-3940256099942544/2934735716", new AdProperties());

4.Add Admob Banner in Unity App
Admob.Instance().showBannerRelative("your admob banner unit id",AdSize.BANNER, AdPosition.BOTTOM_CENTER, 0);

A: I found the solution
The problem was with my Emulator
With The Real Device it work fine
and there's no need to use the co-routine
the following codes will be enough to show the BannderAds
using System.Collections;
using System.Collections.Generic;
using GoogleMobileAds;
using GoogleMobileAds.Api;
using UnityEngine;

public class BannerAd : MonoBehaviour
{

    private BannerView bannerView;

    // Use this for initialization
    void Start ()
    {
        string appID = "ca-app-pub-id"; // this is appId

        MobileAds.Initialize (appID);

        string adUnitId = "ca-app-pub-adUnitId"; // adUnitID

        this.showBannerAd (adUnitId);
    }

    private void showBannerAd (string adUnitId)
    {

        //Create a custom ad size at the bottom of the screen

        AdSize adSize = new AdSize (250, 50);
        bannerView = new BannerView (adUnitId, adSize, AdPosition.Bottom);

        // Create an empty ad request.
        AdRequest request = new AdRequest.Builder ().Build ();

        // Load the banner with the request.
        bannerView.LoadAd (request);

    }

}


text:
Q: WebP image type not shown on ios device chrome browser I am trying to display a webp image on my webpage. I tried many solutions, but every solution has issues on ios device only. The webp is not showing, and also in some cases if you try to download such image in Chrome on ios, it shows the image as txt file.
The current solution is:
<picture class="image mb-5 mb-md-3">
    <source srcset="mywebpimage.webp" type="image/webp">
    <source srcset="myjpgimage.jpg" type="image/jpeg">
    <img src="myjpgimage.jpg" alt="alt">
</picture>

I also tried a php solution - checking the webp support in browsers via http_accept.
    $webp_support = false;
if (isset($_SERVER["HTTP_ACCEPT"])) {
    if (strpos($_SERVER["HTTP_ACCEPT"], "image/webp") > 0) {
        $webp_support = true;
    }
}

This is also working fine except ios.
So is the ios chrome browser cursed or has no support for webp? If I echo the $_SERVER["HTTP_ACCEPT"] on ios, it says TRUE. But if I echo $webp_support on ios chrome browser, it says FALSE.
So it seems webp is not supported, or is there a special way displaying webp on ios?

A: "iOS Chrome" is...
... just iOS Safari Mobile with a Chrome skin.
Neither Safari nor iOS Safari Mobile support WebP (yet).
See: https://caniuse.com/#search=webp


text:
Q: Remove entry from sys.path After installing some Python Modules via homebrew, homebrew told me to run the following code.
I don't need those modules anymore and want to cleanup everything. Can i remove (should i?) remove this entry? And how i remove it?

Python modules have been installed and Homebrew's site-packages is not
  in your Python sys.path, so you will not be able to import the modules
  this formula installed. If you plan to develop with these modules,
  please run:

mkdir -p /Users/rain/.local/lib/python2.7/site-packages
echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/USERNAME/.local/lib/python2.7/site-packages/homebrew.pth

Mac OsX 10.10.2

A: You can safely delete /Users/USERNAME/.local/lib/python2.7/site-packages/homebrew.pth if you aren't using any Homebrew-installed python modules.
.pth files are a way of adding paths to sys.path. Lines in a .pth file which are paths are added to sys.path; lines in a .pth file starting with import are executed.
The line starting with import in the homebrew.pth file makes the site-packages directory under the Homebrew prefix a special site-packages directory, which both adds it to sys.path and ensures that any .pth files that it contains are read and processed.


text:
Q: Backendless workflow with angularjs I want to know how to work with angularjs without using a backend. I know the option of using $httpBackend and mock, but I want a real life example.
In my team we are considering the possibility of using an express server that simply works with JSON files (no database) If there is no alternative.
Any recommendations? Thanks in advance.

A: For tests or to begin work when the backend is not ready yet, I often use services to mock REST or SOAP API, such as: www.mockable.io.
Otherwise you can have a simple server to serve static JSON files.


text:
Q: Let IntelliJ Formatter keep semicolon in a different line in Enums How do I enforce IntelliJ Formatter to keep the semi-colon in a different line in enums?
public enum ExampleEnum {
  A("a"),
  B("b"),
  C("c")
  ;
}

To keep git diffs clean I don't want it to be formatted into something like that:
public enum ExampleEnum {
  A("a"),
  B("b"),
  C("c");
}

I already looked into Formatter settings but couldn't find the right setting.

A: As stated by CrazyCoder in the comments there is an open issue for that.
So for now it is not possible.


text:
Q: JPA entity custom ordering I have a JPA (Hibernate) entity shown below. There might be more than one rule and I need user of my app to be able to change order of rules. Therefore I introduced attribute order. When user decides that the particular rule should be the fifth rule on the list I need to set order to appropriate value and also change (recalculate) order of other entities influenced by this operation. I have some ideas (stored proc or many queries) how to do it but I like none one of them as they doesn't seem simple enough to me. Do you have any ideas how to solve this issue a simple elegant way? Many thans in advance.
@Entity
@Table(name = "rule")
public class RuleVO {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "name", length = 128, nullable = false, unique = true)
    private String name;

    @Column(name = "order", nullable = false)
    private Integer order;
}

A: I see no specific option in JPA for something like this. When the user changes the order, you're going to read all of the rules, set the order attribute and merge the results of all the rules back to the database. What else is there?


text:
Q: getting an error while running .build.sh file in cross compiler dir Here is my console log while running .build.sh command in crosscompiler dir.
version of gcc, g++ and clang is here.
bnr@AM-PC-07:~/osxcross$ gcc --version
gcc (Ubuntu 8.3.0-6ubuntu1~18.04.1) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
bnr@AM-PC-07:~/osxcross$ clang --version
clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
bnr@AM-PC-07:~/osxcross$ g++ --version
g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Here is my error log
CMake Error at /usr/share/cmake-3.10/Modules/CMakeTestCXXCompiler.cmake:45 (message):
The C++ compiler

"/usr/bin/clang++"

is not able to compile a simple test program.

It fails with the following output:

Change Dir: /home/bnr/osxcross/build/apple-libtapi/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/make" "cmTC_5f536/fast"
/usr/bin/make -f CMakeFiles/cmTC_5f536.dir/build.make CMakeFiles/cmTC_5f536.dir/build


text:
Q: How to use SetWinEventHook function? I am using following code from this post,
#include "WinUser.h"

 void CALLBACK HandleWndEvent(HWINEVENTHOOK hWinEventHook, DWORD eventType,
              HWND hWnd, LONG idObject, LONG idChild,
              DWORD eventTypeThread, DWORD dwmsEventTime){
    ...
}

_hWinEventHook = ::SetWinEventHook(_eventMin,
            _eventMax,
            0,
            HandleWndEvent,
            0,
            0, WINEVENT_OUTOFCONTEXT);

however, I cann't compile this code.
The error I get is:

How do I fix this?


text:
Q: writing lines from many text files in sub directories to csv using python I want to derive some statistics out of a large amount of data files that all reside in their own folder. Using python, I want to create a single csv file, look for the data files starting from a root folder at a fairly high level (new folders are added all the time), and write a row with some key values from every file.
I've done this before using the os.walk() method combined with writerows(), but it's giving me problems this time around. When I run the code below, (with a file called XY.txt in my D:/temp/ folder) I get an error that reads: 'unexpected unindent' at the line that reads wr = csv.writer(f,lineterminator='\n',dialect='excel')
I have moved the indentation around but that just moves the mentioned error with it. Can anybody advise me on how to achieve the desired row writing?
import csv, os, math

fname = 'Output.csv'

f = open(fname, 'w') #truncate existing file or generate new one
f.write("count>0.7\n")
merged_files = list()

# look for data files, in sub-folders down from D:/temp
for root, dirs, files in os.walk('D:/temp', topdown=False):
    for name in files:
        if name.startswith('XY') and name.endswith('.txt'):
            try:
                fp = open(root+'/'+name)
                #create a list for storing relevant data from .txt file
                csvRows = list()
                for line in fp:
                    content = line.split()
                    size = float(content[3])
                    #count lines with value over 0.7 in fourth column
                    if size > 0.7:
                        total1 = total1 + 1
                fp.close()
            finally:
                csvRows = [total1]
                merged_files.append(csvRows)

# write new row to file.
wr = csv.writer(f,lineterminator='\n',dialect='excel')
wr.writerows(merged_files)

f.close()

I'm setting this up with rows so I can extract many more items from the .txt file, but I have not included those in the code above for clarity.
*updated code to reflect answer: now the try: sequence is ended with the finally: statement, in which all the information collected during the for loop is written to a line.

A: try attempts to run the block of code, if it fails then it runs the block of code in except. There is an optional finally clause which runs irrespective of whether the code in try succeeds.
For example, the function in the following code snippet will return 2 when executed
def checktry():
   try:
       return 1
   finally:
       return 2

I would recommend an except clause which would print out a helpful message if the code fails.
except Exception as inst:
    print(inst)

Reference : https://docs.python.org/3/tutorial/errors.html#exceptions


text:
Q: Sequelize.js: Model.build returns a blank object I am using Sequelize.js (4.38.0) with Typescript (3.0.3). I also have the package @types/sequelize (at version 4.27.25) installed.
I have the following code which I cannot transpile:
import Sequelize from 'sequelize'

const sequelize = new Sequelize('...');
const model = sequelize.define('Model', {a: Sequelize.INTEGER, b: Sequelize.INTEGER});

var instance = model.build({a: 1, b:1});
instance.save();

tsc returns with the following error:
 Property 'save' does not exist on type '{}'.

So for some reason, build returns a blank object.
When I try to use create instead, the same error appears: create returns a Promise which resolves a blank object.
Any thoughts on that?

A: You need to specify the generic type parameters explicitly, the definitions make no attempt to infer the types for the attributes or the instance type.
import Sequelize, { Instance } from 'sequelize'

const sequelize = new Sequelize('...');

interface Model {
    a: number;
    b: string;
}

const model = sequelize.define<Instance<Model>, Model>('Model', {a: Sequelize.INTEGER, b: Sequelize.INTEGER});

var instance = model.build({a: 1, b:'1'}); // b must be string error is now caught by typescript
instance.save() // ok now


text:
Q: How do I disable desktop icons? (no nautilus in gconf-editor) I switched my file manager from nautilus to nemo. I installed nemo and changed in the files /usr/share/applicatons/nautilus-home.desktop and nautilus-folder-handler.desktop to
Exec=nemo
With nemo there appeared the icons for devices, homefolder and trashbin on the desktop and I want to remove them. I tried to disable them in the gconf-editor, but there is no "nautilus" under "apps", nor did i find any "show desktop" option. Desktop icons are also disabled via gnome-tweak-tool.
What else could I try? These icons are really ruining my desktop.
PS: I am using Ubuntu Gnome 14.04

A: gsettings set org.nemo.desktop show-desktop-icons false

Should do what you want


text:
Q: Quote messing Attribute title I have a snippet like this:
echo "" //and so on

now everything is a mess when $row['title'] contains something like this:

*

*The Great's title

*The "Great" title

What is the best procedure to retain the word in my title and not break the title for the anchor tag
My solution is not that effective using str_replace any good ideas to handle this?

A: With The Great's title as  title, the output looks like this:

Here the attribute value ends prematurely after Great.
You need to escape the attribute value properly:
echo ""

Now the output looks like this:

The interpreted attribute value is still The Great's title.
The same applies to The "Great" title, which then will look like:

A: Simple way
<a href="#" title="<?php echo $title; ?>">link


text:
Q: Font Awesome through CDN does not show required icon I am trying to use Awesome icons in a Laravel/Vue project. But for some reason the icon doesn't show properly, whatever I try.
I now tried the most simple thing with Awesome I could imaging: a simple HTML-page using a CDN. The code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

But, like in my Laravel project, I am not seeing the camera icon, but some kind of dummy icon: a rectangle with F030 in it.
BTW: I run a Xampp stack under Windows.
What am I doing wrong?

A:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

I just edited the link with a cdn link from the font-awesome page
, whatever you embed does not include your desired icon
taken from here


text:
Q: Why does boost split cause double free or corruption issue I developed a web server with C++ and here is a function, which caused a coredump issue but I don't know why.
bool MyClass::hasFamilyAdminPermission(uint32_t uid) {
    ReadMutex mutex(&m_mtx); // this is read lock to lock m_familyOwner and m_familyAdmins
    if (uid == m_familyOwner) {
        return true;
    }
    std::vector<std::string> fields;
    boost::split(fields, m_familyAdmins, boost::is_any_of(","));
    std::string uidStr = boost::lexical_cast<string>(uid);
    for (std::vector<std::string>::iterator itor = fields.begin(); itor != fields.end(); ++itor) {
        if (uidStr == *itor) {
            return true;
        }
    }
    return false;
}

After executing gdb ./myServer coredump_file, I got the output as below:
warning: Unexpected size of section `.reg-xstate/8717' in core file.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./myServer'.
Program terminated with signal SIGABRT, Aborted.

warning: Unexpected size of section `.reg-xstate/8717' in core file.
#0  0x00007f627b2c5428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
54      ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
[Current thread is 1 (Thread 0x7f62277fe700 (LWP 8717))]
(gdb) where
#0  0x00007f627b2c5428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1  0x00007f627b2c702a in __GI_abort () at abort.c:89
#2  0x00007f627b3077ea in __libc_message (do_abort=do_abort@entry=2, fmt=fmt@entry=0x7f627b420ed8 "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#3  0x00007f627b31037a in malloc_printerr (ar_ptr=<optimized out>, ptr=<optimized out>,
    str=0x7f627b420fa0 "double free or corruption (fasttop)", action=3) at malloc.c:5006
#4  _int_free (av=<optimized out>, p=<optimized out>, have_lock=0) at malloc.c:3867
#5  0x00007f627b31453c in __GI___libc_free (mem=<optimized out>) at malloc.c:2968
#6  0x00007f627be650b4 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() ()
   from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x000000000046acc1 in boost::as_literal<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > (r=...)
    at /usr/local/include/boost/range/as_literal.hpp:102
#8  boost::algorithm::iter_split<std::vector<std::string, std::allocator<std::string> >, std::string, boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<char> > > (Result=..., Input="604679400,1430691907,2792989999",
    Finder=<error reading variable: DWARF-2 expression error: DW_OP_reg operations must be used either alone or in conjunction with DW_OP_piece or DW_OP_bit_piece.>) at /usr/local/include/boost/algorithm/string/iter_find.hpp:153
#9  0x0000000000464c17 in boost::algorithm::split<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::string, boost::algorithm::detail::is_any_ofF<char> > (eCompress=<optimized out>, Pred=..., Input=..., Result=...) at /usr/local/include/boost/algorithm/string/split.hpp:149
#10 server::myServer::MyClass::hasFamilyAdminPermission (this=0x7f621c066dd0, uid=<optimized out>) at MyClass.cpp:202
#11 0x0000000000435678 in server::myServer::ServerAPI::onSetMicDataReq (this=0x7fff6da7e750, uid=1430691907, req=0x7f621c094200)
    at ServerAPI.cpp:2291

So it seems that boost::split caused the coredump.
In gdb, I've done as below:
(gdb) frame 10
#10 server::myServer::MyClass::hasFamilyAdminPermission (this=0x7f621c066dd0, uid=<optimized out>) at MyClass.cpp:202
202     MyClass.cpp: No such file or directory.
(gdb) print fields
$1 = std::vector of length 0, capacity 0

For now, fields is an empty vector.
(gdb) frame 8
#8  boost::algorithm::iter_split<std::vector<std::string, std::allocator<std::string> >, std::string, boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<char> > > (Result=..., Input="604679400,1430691907,2792989999",
    Finder=<error reading variable: DWARF-2 expression error: DW_OP_reg operations must be used either alone or in conjunction with DW_OP_piece or DW_OP_bit_piece.>) at /usr/local/include/boost/algorithm/string/iter_find.hpp:153
153     /usr/local/include/boost/algorithm/string/iter_find.hpp: No such file or directory.

Here, the input is "604679400,1430691907,2792989999", which looks like ok.
However, when I execute info loclas (I'm still at the frame 8), I got a segmentation fault.
(gdb) info locals
Tmp = std::vector of length 1891892, capacity 1891893 = {<error reading variable Tmp (Cannot access memory at address 0x0)>
itBegin = {<boost::iterator_adaptor<boost::transform_iterator<boost::algorithm::detail::copy_iterator_rangeF<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, boost::algorithm::split_iterator<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, boost::use_default, boost::use_default>, boost::algorithm::split_iterator<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::use_default, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::use_default>> = {<boost::iterator_facade<boost::transform_iterator<boost::algorithm::detail::copy_iterator_rangeF<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, boost::algorithm::split_iterator<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, boost::use_default, boost::use_default>, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, boost::forward_traversal_tag, std::basic_string<char, std::char_traits<char>, std::allocator<char> >, long>> = {<No data fields>},
    m_iterator = {<boost::iterator_facade<boost::algorithm::split_iterator<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, boost::iterator_range<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const, boost::forward_traversal_tag, boost::iterator_range<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, long>> = {<No data fields>}, <boost::algorithm::detail::find_iterator_base<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >> = {
        m_Finder = {<boost::function_base> = {vtable = 0x89bd9dd2, functor = {obj_ptr = 0x7f627b31453c <__GI___libc_free+76>, type = {
                type = 0x7f627b31453c <__GI___libc_free+76>, const_qualified = false, volatile_qualified = false},
              func_ptr = 0x7f627b31453c <__GI___libc_free+76>, bound_memfunc_ptr = {
                memfunc_ptr = (void (boost::detail::function::X::*)(boost::detail::function::X * const,
    int)) 0x7f627b31453c <__GI___libc_free+76>, obj_ptr = 0xe8436c057b9e1300}, obj_ref = {obj_ptr = 0x7f627b31453c <__GI___libc_free+76>,
                is_const_qualified = false, is_volatile_qualified = false},
              data = 60 '<'}}, <std::binary_function<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, boost::iterator_range<__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >> = {<No data fields>},
/usr/bin/sudo: line 11: 75240 Segmentation fault      (core dumped) ${SUDO} $@

I don't know what caused the coredump, I don't know either why I got the segmentation fault after executing info locals...

A: So, boost::split doesn't crash. You have undefined behavior elsewhere.
Regardless, why are you parsing through a string, allocating a vector of strings, comparing to a temporary string etc. all the time? You could do this on the integer-domain.
Four takes. Starting from a simple skeleton:
#include <shared_mutex>
#include <string>

struct MyClass1 {
    MyClass1(uint32_t owner, std::string admins)
        : m_familyOwner(owner)
        , m_familyAdmins(std::move(admins)) {}

    bool hasFamilyAdminPermission(uint32_t uid) const;

  private:
    mutable std::shared_mutex m_mtx; // guards m_familyOwner and m_familyAdmins
    uint32_t                  m_familyOwner;
    std::string               m_familyAdmins;
};

1. Comparing Ints, No Allocations
I'll use Boost Spirit X3:
#include <boost/spirit/home/x3.hpp>
bool MyClass1::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    if (uid == m_familyOwner)
        return true;

    bool matched = false;
    auto element = boost::spirit::x3::uint32;
    auto check   = [uid, &matched](auto& ctx) {
        if (_attr(ctx) == uid) {
            matched    = true;
            _pass(ctx) = false; // short circuit for perf
        }
    };

    parse(begin(m_familyAdmins), end(m_familyAdmins), element[check] % ',');
    return matched;
}

This still does quite a lot of work under the lock, but certainly never allocates. Also, it does early-out, which helps if the collection of owners can be very large.
2. Comparing Text, But Without Allocations
With a nifty regex you can match the number as text on a constant string (or string view). The overhead here is the allocation(s) for the regex. But arguably, it's much simpler:
#include <regex>
bool MyClass2::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    if (uid == m_familyOwner)
        return true;

    return regex_search(m_familyAdmins, std::regex("(^|,)" + std::to_string(uid) + "(,|$)"));
}

3. Parse Once, At Construction
Why are we dealing with text? We could keep the admins in a set:
#include <set>
struct MyClass3 {
    MyClass3(uint32_t owner, std::string_view admins) : m_familyOwner(owner) {
        parse(admins.begin(), end(admins), boost::spirit::x3::uint32 % ',', m_familyAdmins);
    }
    bool hasFamilyAdminPermission(uint32_t uid) const;

  private:
    mutable std::shared_mutex m_mtx; // guards m_familyOwner and m_familyAdmins
    uint32_t                  m_familyOwner;
    std::set<uint32_t>        m_familyAdmins;
};

bool MyClass3::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    return uid == m_familyOwner || m_familyAdmins.contains(uid);
}

That's even simpler. However, there's some overhead in the set which can be optimized.
4. Parse Once, No Allocations, Speed
std::set has the right semantics. However, for small sets it's sad that there's no locality of reference, and relatively high node allocation overhead. We could replace with:
boost::container::flat_set< //
    uint32_t,               //
    std::less<>,            //
    boost::container::small_vector<uint32_t, 10>>
    m_familyAdmins;

This makes it so that sets <= 10 elements do not allocate at all, and lookup benefits from contiguous storage. However, at this rate - unless you want to deal with duplicate entries - you might keep a linear search and store:
boost::container::small_vector<uint32_t, 10>
    m_familyAdmins;

Combined Demo
Showing all the subtle edge cases. Note that only with the X3 parser

*

*it will be easy to perform input validation on the comma-separated string

*it will be easy to reliably compare differently formatted uid numbers

I snuck in one number that has a leading 0 (089 instead of 89) just to highlight this issue with the std::regex approach. Note that your original code has the same problem.
Live On Coliru/Compiler Explorer
#include <shared_mutex>
#include <string>

struct MyClass1 {
    MyClass1(uint32_t owner, std::string admins)
        : m_familyOwner(owner)
        , m_familyAdmins(std::move(admins)) {}

    bool hasFamilyAdminPermission(uint32_t uid) const;

    private:
    mutable std::shared_mutex m_mtx; // guards m_familyOwner and m_familyAdmins
    uint32_t                  m_familyOwner;
    std::string               m_familyAdmins;
};

#include <boost/spirit/home/x3.hpp>
bool MyClass1::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    if (uid == m_familyOwner)
        return true;

    bool matched = false;
    auto element = boost::spirit::x3::uint32;
    auto check   = [uid, &matched](auto& ctx) {
        if (_attr(ctx) == uid) {
            matched    = true;
            _pass(ctx) = false; // short circuit for perf
        }
    };

    parse(begin(m_familyAdmins), end(m_familyAdmins), element[check] % ',');
    return matched;
}

struct MyClass2 {
    MyClass2(uint32_t owner, std::string admins)
        : m_familyOwner(owner)
        , m_familyAdmins(std::move(admins)) {}
    bool hasFamilyAdminPermission(uint32_t uid) const;

    private:
    mutable std::shared_mutex m_mtx; // guards m_familyOwner and m_familyAdmins
    uint32_t                  m_familyOwner;
    std::string               m_familyAdmins;
};

#include <regex>
bool MyClass2::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    if (uid == m_familyOwner)
        return true;

    return std::regex_search(m_familyAdmins, std::regex("(^|,)" + std::to_string(uid) + "(,|$)"));
}

#include <set>
struct MyClass3 {
    MyClass3(uint32_t owner, std::string_view admins) : m_familyOwner(owner) {
        parse(admins.begin(), end(admins), boost::spirit::x3::uint32 % ',', m_familyAdmins);
    }
    bool hasFamilyAdminPermission(uint32_t uid) const;

    private:
    mutable std::shared_mutex m_mtx; // guards m_familyOwner and m_familyAdmins
    uint32_t                  m_familyOwner;
    std::set<uint32_t>        m_familyAdmins;
};

bool MyClass3::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    return uid == m_familyOwner || m_familyAdmins.contains(uid);
}

#include <boost/container/flat_set.hpp>
#include <boost/container/small_vector.hpp>
struct MyClass4 {
    MyClass4(uint32_t owner, std::string_view admins) : m_familyOwner(owner) {
        parse(admins.begin(), end(admins), boost::spirit::x3::uint32 % ',', m_familyAdmins);
    }
    bool hasFamilyAdminPermission(uint32_t uid) const;

    private:
    mutable std::shared_mutex m_mtx; // guards m_familyOwner and m_familyAdmins
    uint32_t                  m_familyOwner;
#ifdef LINEAR_SEARCH
    // likely faster with small sets, anyways
    boost::container::small_vector<uint32_t, 10> m_familyAdmins;
#else
    boost::container::flat_set< //
        uint32_t,               //
        std::less<>,            //
        boost::container::small_vector<uint32_t, 10>>
            m_familyAdmins;
#endif
};

bool MyClass4::hasFamilyAdminPermission(uint32_t uid) const {
    std::shared_lock mutex(m_mtx);
    return uid == m_familyOwner ||
#ifndef LINEAR_SEARCH
        std::find(begin(m_familyAdmins), end(m_familyAdmins), uid) != end(m_familyAdmins);
#else
    m_familyAdmins.contains(uid);
#endif
}

#include <iostream>
int main() {
    MyClass1 const mc1{42, "21,377,34,233,55,089,144"};
    MyClass2 const mc2{42, "21,377,34,233,55,089,144"};
    MyClass3 const mc3{42, "21,377,34,233,55,089,144"};
    MyClass4 const mc4{42, "21,377,34,233,55,089,144"};

    std::cout << "uid\tdynamic\tregex\tset\tflat_set\n"
        << "\t(x3)\t-\t(x3)\t(x3)\n"
        << std::string(5 * 8, '-') << "\n";

    auto compare = [&](uint32_t uid) {
        std::cout << uid << "\t" << std::boolalpha
            << mc1.hasFamilyAdminPermission(uid) << "\t"
            << mc2.hasFamilyAdminPermission(uid) << "\t"
            << mc3.hasFamilyAdminPermission(uid) << "\t"
            << mc4.hasFamilyAdminPermission(uid) << "\n";
    };

    compare(42);
    // https://en.wikipedia.org/wiki/Fibonacci_number
    for (auto i = 3, j = 5; i < 800; std::tie(i, j) = std::tuple{j, i + j}) {
        compare(i);
    }
}

Prints
id      dynamic regex   set     flat_set
        (x3)    -       (x3)    (x3)
----------------------------------------
42      true    true    true    true
3       false   false   false   false
5       false   false   false   false
8       false   false   false   false
13      false   false   false   false
21      true    true    true    true
34      true    true    true    true
55      true    true    true    true
89      true    false   true    true
144     true    true    true    true
233     true    true    true    true
377     true    true    true    true
610     false   false   false   false


text:
Q: Legend format lost after using: ax.legend(handles, labels ) I have the same problem as in this post: Where the user wants to delete repeated entries in the legend:
Stop matplotlib repeating labels in legend
The answer works for me as well, however, when I use it, the legend format is completely lost. This happens when I apply the ax.legend(handles, labels) method. The following code (copied from http://matplotlib.org/examples/pylab_examples/legend_demo.html) illustrates this issue:
# Example data
a = np.arange(0,3, .02)
b = np.arange(0,3, .02)
c = np.exp(a)
d = c[::-1]

# Create plots with pre-defined labels.
# Alternatively, you can pass labels explicitly when calling `legend`.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c+d, 'k', label='Total message length')

# Now add the legend with some customizations.
legend = ax.legend(loc='upper center', shadow=True)

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels )

# The frame is matplotlib.patches.Rectangle instance surrounding the legend.
frame = legend.get_frame()
frame.set_facecolor('0.90')

# Set the fontsize
for label in legend.get_texts():
    label.set_fontsize('large')

for label in legend.get_lines():
    label.set_linewidth(1.5)  # the legend line width
plt.show()

Result without using 'ax.legend(handles, labels)':

Resul using 'ax.legend(handles, labels)':

Any advice would be most welcomed
EDIT 1: Typo 'without' corrected

A: You have issued legend() call twice and the second time it is called without formatting arguments, replace:
legend = ax.legend(loc='upper center', shadow=True)

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels )

with
handles, labels = ax.get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
ax.legend(by_label.values(), by_label.keys(), loc='upper center', shadow=True)

Should do the trick.