text:
Q: Image path null in Android I have code like this, the problem is when i want to save it to sqlite, the error message shown that i got null in image path.
Here is the main activity
public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                System.out.println("Data Image : "+selectedImageUri);
                selectedImagePath = getPath(selectedImageUri);
                System.out.println("Image Path : " + selectedImagePath);
                image1.setVisibility(View.VISIBLE);
                image1.setImageURI(selectedImageUri);
            }
        }
    }
private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }
public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

A: I use this method to take photos from camera.
private void capturePhoto() {
// save this Uri in a field variable.
    uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new ContentValues());
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, CAMERA_REQUEST);
}

then onActivityResult will look like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
        // use the field Uri, it now points to the path to the image taken from the camera.
    }
}

A: *

*In manifest file set permission

*Check permission granted in onActivityResult method and after its granted READ_EXTERNAL_STORAGE

*If it has Permission then call doCreatePath() and set the same in onRequestPermissionsResult on permission granted.

void doCreatePath()
 {

        try {

            Uri originalUri = filePath;
            String pathsegment[] = originalUri.getLastPathSegment().split(":");
            String id = pathsegment[0];
            final String[] imageColumns = {MediaStore.Images.Media.DATA};
            final String imageOrderBy = null;
            Uri uri = getUri();
            Cursor imageCursor = getActivity().getContentResolver().query(uri, imageColumns,
                    null, null, null);

            if (imageCursor.moveToFirst()) {
                int column_index_data = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                realPath = imageCursor.getString(column_index_data);
                System.out.print("value" + realPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

It works!.


text:
Q: Clear form on success submit in grails Is there is some way to clear fields after success submit in grails application?
<g:formRemote name="songList" url="[controller: 'SongList', action:'create']"
              update="[success: 'updateSongList', failure: 'error']">

        Enter name of song list:
        <g:textField name="title"  class="form-control" id="songList"/>

    <g:submitButton name="Create" />
</g:formRemote>

or I should write custom code for this? In grails tag g:formRemote there is method onSuccess, but how correct use it in this case don't imagine.
Thank you.

A: Just put this:
$('form[name="songList"]')[0].reset()

with in your success method: updateSongList()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Porting C Code to C# / dereferencing a pointer How would I port this piece of C Code to C#? It is a UPC Key Recovery Tool.
hv is a uint32_t array with 4 elements. h1 is a uint8_t array with 16 elements
uint32_t hv[4] = ...
uint8_t h1[16] = ...

for (i = 0; i < 4; i++) {
    hv[i] = *(uint16_t *)(h1 + i*2);
}

While this is valid C code I cannot seem to port this to C# without it giving me errors. Does anybody have an idea what I could do?
I've tried declaring hv as a uint array and h1 as a byte array.

A: Break it down.  What are we doing?  Work from the semantic level, not from the level of pointers.

*

*We have a byte array with some number of bytes.

*We take two bytes at a time and alias them as 16-bit unsigned integers

*We extract the 16-bit unsigned integer, convert it to a 32-bit unsigned integer, and assign that to an array element.

Now we have a specification. Write a method for each interesting operation. The only interesting operation is turning two bytes into one ushort; everything else is done for you by the compiler.
static ushort BytesToUshort(byte b1, byte b2)
{
   // You can implement this method
}

Great. Now we have a tool we can use.  What bytes do we want? The bytes at i*2 and i*2+1.  So:
for (i = 0; i < 4; i++) {
    hv[i] = BytesToUshort(h1[i*2], h1[i*2+1]);
}

And we're done.
Don't try to translate pointer manipulation code to C#; you can do it but it will not be good C# code. Write code that has the same effect but uses the conventions of C#.
A technique that might help is to rewrite the code so that it is less awful C code; this is terrible.  If you rewrote the original code into C like this first:
uint16_t *ps = (uint16_t*)h1;
for (i = 0; i < 4; i++)
  hv[i] = ps[i];

I daresay that it would have been a lot easier to understand conceptually what was going on here.

A: Essentially:
        ushort[] hv = new ushort[4];
        byte[] h1 = new byte[16];

        for (int i = 0; i < 4; i++)
        {
            // note: this call is CPU-endian; if your data is not CPU-endian,
            // you will need to write a known-endian op - aka "shift" and "or"
            hv[i] = BitConverter.ToUInt16(h1, i * 2);
        }

Although I wonder if a blit might be more appropriate.
Note that you can also use unsafe C# code to have essentially the same code as the C code (via fixed), and in the upcoming bits: this would be a good fit for Span<T> which allows for simple thunks between different T.


text:
Q: Converts Degrees/Minutes/Seconds to Decimals using SQL Is there any SQL script that converts Degrees/Minutes/Seconds (saved in Column A) to Decimals (to be saved in new Column B)? I googled for existing solutions, but all examples refer to Decimals->Deg/Min/Sec. I appreciate any example, because I'm not strong in SQL scripting.

A: The following seems to work:
SELECT DMS, DEGREES + (MINUTES / 60) + (SECONDS / (60 * 60)) AS DECIMAL_DEGREES
  FROM (SELECT DMS,
               TRUNC(DMS) AS DEGREES,
               TRUNC((DMS - TRUNC(DMS)) * 100) AS MINUTES,
               ((DMS * 100) - TRUNC(DMS * 100)) * 100 AS SECONDS
          FROM TEST_DMS)

or, if you prefer it all as one expression:
SELECT DMS,
       TRUNC(DMS) +
         (TRUNC((DMS - TRUNC(DMS)) * 100) / 60) +
         (((DMS * 100) - TRUNC(DMS * 100)) * 100) / (60 * 60) AS DECIMAL_DEGREES
  FROM TEST_DMS

At the very least these agree with the results returned by my trusty, rusty HP-41C.  :-)
Share and enjoy.

A: I worked on a project...I used script to solve issue on DMS conversion on oracle db
SELECT
CASE
WHEN LENGTH(longitude)=7 THEN ROUND (cast(substr(longitude, 1, 1) as numeric(10,5)) +  cast(substr(longitude, 3, 2) as numeric(10,5))/60 +  cast(substr(longitude, 6, 2) as numeric(10,5))/3600,4)
WHEN LENGTH(longitude)=8  THEN ROUND (cast(substr(longitude, 1, 2) as numeric(10,5)) +  cast(substr(longitude, 4, 2) as numeric(10,5))/60 +  cast(substr(longitude, 7, 2) as numeric(10,5))/3600,4)
ELSE
ROUND (CAST (longitude as Numeric(10,5)),4)
END AS LONGITUDE,
CASE
WHEN LENGTH(latitude)=7 THEN ROUND (cast(substr(latitude, 1, 1) as numeric(10,5)) +  cast(substr(latitude, 3, 2) as numeric(10,5))/60 +  cast(substr(latitude, 6, 2) as numeric(10,5))/3600,4)
WHEN LENGTH(latitude)=8  THEN ROUND (cast(substr(latitude, 1, 2) as numeric(10,5)) +  cast(substr(latitude, 4, 2) as numeric(10,5))/60 +  cast(substr(latitude, 7, 2) as numeric(10,5))/3600,4)
ELSE
ROUND (CAST (latitude as Numeric(10,5)),4)
END AS LATITUDE

A: I use the below to do the same
declare @cord  varchar (max)

set  @cord=  '2504N 05534E'

select

case when  CHARINDEX(' ', @cord,1)>0 then
case when  right(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),1) = 'N' then
(left(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),2))
+
(SUBSTRING(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),3,2)/60.0)
else
-1*(
(left(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),2))
+
(SUBSTRING(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),3,2)/60.0)
)
end
end latitude
,case when  CHARINDEX(' ', @cord,1)>0 then
 case when right(LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ', @cord,1),100))),1) = 'E' then
(left(LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ', @cord,1),100))),3) )
+
(SUBSTRING( LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ', @cord,1),100))),4
,2)/60.0)
else
-1*(
(left(LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ', @cord,1),100))),3) )
+
(SUBSTRING( LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ', @cord,1),100))),4
,2)/60.0)
 )
 end
 end  longitude

,geography::Point(
     case when  CHARINDEX(' ', @cord,1)>0 then
        case when  right(LTrIM(RTRIM(left( @cord, CHARINDEX(' ',
 @cord,1)-1))),1) = 'N' then
        (left(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),2))
        +
        (SUBSTRING(LTrIM(RTRIM(left( @cord, CHARINDEX(' ',
 @cord,1)-1))),3,2)/60.0)
        else
        -1*(
        (left(LTrIM(RTRIM(left( @cord, CHARINDEX(' ', @cord,1)-1))),2))
        +
        (SUBSTRING(LTrIM(RTRIM(left( @cord, CHARINDEX(' ',
 @cord,1)-1))),3,2)/60.0)
        )
        end
     end
     ,case when  CHARINDEX(' ', @cord,1)>0 then
        case when right(LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ',
 @cord,1),100))),1) = 'E' then
        (left(LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ',
 @cord,1),100))),3) )
        +
        (SUBSTRING( LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ',
 @cord,1),100))),4 ,2)/60.0)
        else
        -1*(
        (left(LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ',
 @cord,1),100))),3) )
        +
        (SUBSTRING( LTrIM(RTRIM(SUBSTRING( @cord, CHARINDEX(' ',
 @cord,1),100))),4 ,2)/60.0)
        )
        end
    end
    , 4326)
      as geography_Point

A: Based on @user2621989 answer here is tested SQL Server version of his query:
DECLARE @longitude varchar(max) = '50°03''10"'
DECLARE @latitude varchar(max) = '15°00''50"'

SELECT
CASE
WHEN LEN(@longitude)=8 THEN ROUND (cast(SUBSTRING(@longitude, 1, 1) as numeric(9,6)) +  cast(SUBSTRING(@longitude, 3, 2) as numeric(9,6))/60 +  cast(SUBSTRING(@longitude, 6, 2) as numeric(9,6))/3600,4)
WHEN LEN(@longitude)=9  THEN ROUND (cast(SUBSTRING(@longitude, 1, 2) as numeric(9,6)) +  cast(SUBSTRING(@longitude, 4, 2) as numeric(9,6))/60 +  cast(SUBSTRING(@longitude, 7, 2) as numeric(9,6))/3600,4)
ELSE
ROUND (CAST (@longitude as numeric(9,6)),4)
END AS longitude,
CASE
WHEN LEN(@latitude)=8 THEN ROUND (cast(SUBSTRING(@latitude, 1, 1) as numeric(9,6)) +  cast(SUBSTRING(@latitude, 3, 2) as numeric(9,6))/60 +  cast(SUBSTRING(@latitude, 6, 2) as numeric(9,6))/3600,4)
WHEN LEN(@latitude)=9  THEN ROUND (cast(SUBSTRING(@latitude, 1, 2) as numeric(9,6)) +  cast(SUBSTRING(@latitude, 4, 2) as numeric(9,6))/60 +  cast(SUBSTRING(@latitude, 7, 2) as numeric(9,6))/3600,4)
ELSE
ROUND (CAST (@latitude as numeric(9,6)),4)
END AS latitude

Returns
longitude       latitude
50.05280000000  15.01390000000

A: Another example if your lat/lng parts are represented in separate columns: hemisphere, degrees, minutes, seconds.
/*
lat/long sign key
+ + : North and East
+ - : North and West
- - : South and West
- + : South and East
*/
SELECT
    ROUND(
        CASE WHEN LatitudeHemisphere = 'N' THEN 1 ELSE -1 END *
        ([LatitudeDegrees] +
        (CAST([LatitudeMinutes] AS FLOAT)/60) +
        (CAST([LatitudeSeconds] AS FLOAT)/3600)), 7, 1) AS Latitude,
    ROUND(
        CASE WHEN LongitudeHemisphere = 'E' THEN 1 ELSE -1 END *
        ([LongitudeDegrees] +
        (CAST([LongitudeMinutes] AS FLOAT)/60) +
        (CAST([LongitudeSeconds] AS FLOAT)/3600)), 7, 1) AS Longitude
    FROM [your_table]


text:
Q: Pause YouTube iframe embed when playing another I have multiple YouTube iFrames embedded on a page. If one of the movies is already playing, and a user then decides to start playing a different movie, is it possible to stop playing the first movie so there is only ever one playing at a time?
I have looked at the 'YouTube Player API Reference for iframe Embeds' https://developers.google.com/youtube/iframe_api_reference but if i'm honest I just don't understand it. My developer skills are very limited.... clearly.
Pitiful I know, but this is all I have at the moment (just the iFrames)... http://jsfiddle.net/YGMUJ/

I thought all I needed to do was add '&enablejsapi=1' at the end of the video URLs.
Any help would be much appreciated.
Thank you in advance.

A: Instead of using iframes, you actually want to use the iFrame Player API.  Depending on how many videos you actually wanted to embed, you might want to make this javascript more dynamic, but this working example should give you enough to get started.
Basically what I'm doing here is initializing the two players, and pausing the opposite video when a player state changes to play.
You can play with the following code at http://jsfiddle.net/mattkoskela/Whxjx/

One:

Two:

A: Here is an advanced version of @Matt Koskela's version. It does not require you to create the videos by JavaScript. It works for example if the videos are generated on the PHP side (think Wordpress).
JsFiddle demo here.

One:

Two:

Edit: Check out Jennie Sadler's fine-tuned version below if your videos start as thumbnails.

A: The above script of vbence works perfectly.
Here is the same script in javascript.
var tag = document.createElement("script");
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubeIframeAPIReady() {
  var i,
    frames,
    players = [];
  frames = document.getElementsByTagName("iframe");
  const arr = Array.from(frames);
  const arrnew = arr.filter((e) => {
    return e.src.indexOf("https://www.youtube.com/") == 0;
  });
  arrnew.forEach((ele, index) => {
    if (!ele.id) {
      ele.id = "embeddedvideoiframe" + index;
    }
    players.push(
      new YT.Player(ele.id, {
        events: {
          onStateChange: (event) => {
            if (event.data == YT.PlayerState.PLAYING) {
              players.forEach((ply) => {
                if (ply.getIframe().id != event.target.getIframe().id) {
                  ply.pauseVideo();
                }
              });
            }
          },
        },
      })
    );
  });
}

A: I'm super new to this. I am posting this to see if this is fine.
Also I do not know jQuery so this was just a simpler way for me.
I also only have one iframe and change src. Is this a problem???
I put an id on an iframe to populate it with an array of videos.
I ran into a problem where it would keep playing it after I closed a modal box.
After looking for answers I decided to try making the iframe reference nothing.
It works but probably is not the best solution if you want both videos on screen.
function stopVid(){
  var iframe = document.getElementById("videoPlayer");
  iframe.src = "";
 }

A: Vanilla JS based on answer by Jennie Sadler.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubeIframeAPIReady() {
var players = [];
Array.prototype.slice.call(document.getElementsByTagName("iframe")).filter(function(e) {
    return e.src.indexOf("https://www.youtube.com/") == 0;
}).forEach(function(youtubevideo, k, v) {
    if (!youtubevideo.id) {
        youtubevideo.id = 'embeddedvideoiframe' + k;
    }
    players.push(new YT.Player(youtubevideo.id, {
        events: {
            'onStateChange': function(event) {
                if (event.data == YT.PlayerState.PLAYING) {
                    Array.prototype.slice.call(players).forEach(function(youtubevideo, k, v) {
                        if (youtubevideo.getPlayerState() == YT.PlayerState.PLAYING //# checks for only players that are playing
                            && youtubevideo.getIframe().id != event.target.getIframe().id) {
                            youtubevideo.pauseVideo();
                        }
                    });
                }
            }
        }
    }))
});

}


text:
Q: How to get the frequency array and extract a range of frequency from wav file readWave('hello.wav',from=0,to=1,units='seconds')
plot(hello@left,xlab="time",ylab="freq")

But how to get the frequency array before applying short-time fourier transform and take out a specific range of the frequency in R? For example, [60,300] Hz for adult men and save it as another wav. file.

A: It sounds like you're asking for a frequency band-pass filter. The package seewave has a suitable function, fir, (and a lot of other useful things).
library(tuneR)
library(seewave)

hello <- readWave("hello.wav")

hello.bp <- fir(hello, from=60, to=300, output="Wave")
hello.bp <- normalize(hello.bp, unit=as.character(hello.bp@bit))
meanspec(hello.bp, log="x")
writeWave(hello.bp, "hello.bp.wav")


text:
Q: Getting null pointer exception on radio buttons toggle method so I have radio buttons turnOn and turnOff grouped together and loud, vibrate and silent grouped as a RadioGroup. they are initailozid after the setContentView();
    turnOn = (RadioButton) findViewById(R.id.on);
    turnOff = (RadioButton) findViewById(R.id.off);
    loud = (RadioButton) findViewById(R.id.sound);
    vibrate = (RadioButton) findViewById(R.id.vibrate);
    silent = (RadioButton) findViewById(R.id.Silent);

the exception ocurres when I try to check a radio button
    if(s.onoff){
        turnOn.setChecked(true);
    }
    else{
        turnOff.setChecked(true);
    }
    Log.d("update ui", "profile");
        if(s.profile.equals("0")){
        loud.toggle();
        }
    else if(s.profile.equals("1")){
        vibrate.toggle();
    }
    else{
        silent.toggle();
    }

when I commented them out the radiobuttons toggle method it doesn't crash.
07-14 17:32:55.350: E/AndroidRuntime(8120): FATAL EXCEPTION: main
07-14 17:32:55.350: E/AndroidRuntime(8120): java.lang.RuntimeException: Unable to start activity ComponentInfo{hasebou.karim.simplify/hasebou.karim.simplify.Volume}: java.lang.NullPointerException
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.os.Looper.loop(Looper.java:137)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.ActivityThread.main(ActivityThread.java:4898)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at java.lang.reflect.Method.invokeNative(Native Method)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at java.lang.reflect.Method.invoke(Method.java:511)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at dalvik.system.NativeStart.main(Native Method)
07-14 17:32:55.350: E/AndroidRuntime(8120): Caused by: java.lang.NullPointerException
07-14 17:32:55.350: E/AndroidRuntime(8120):     at hasebou.karim.simplify.Volume.updateUi(Volume.java:78)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at hasebou.karim.simplify.Volume.onCreate(Volume.java:43)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.Activity.performCreate(Activity.java:5206)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
07-14 17:32:55.350: E/AndroidRuntime(8120):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
07-14 17:32:55.350: E/AndroidRuntime(8120):     ... 11 more

here is my xml file
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Volume"
    android:orientation="vertical"
    >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="#FFFFFF"
     >

    <TimePicker
        android:id="@+id/ChoosenTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center" >

        <RadioButton
            android:id="@+id/on"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Turn on"
            android:onClick="onoff"
             />

        <RadioButton
            android:id="@+id/off"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onoff"
            android:text="Turn off" />

    </RadioGroup>
</LinearLayout>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Action schedule"
        android:textSize="18sp"/>
    <View
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:background="#31B6E7"/>
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        >
       <ToggleButton
        android:id="@+id/sun"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Sun"
        android:textOff="Sun"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton"
         />
       <ToggleButton
        android:id="@+id/mon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Mon"
        android:textOff="Mon"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton"
         />
       <ToggleButton
        android:id="@+id/tue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Tue"
        android:textOff="Tue"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton"
         />
       <ToggleButton
        android:id="@+id/wed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Wed"
        android:textOff="Wed"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton"
         />
       <ToggleButton
        android:id="@+id/thu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Thu"
        android:textOff="Thu"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton"
         />
       <ToggleButton
        android:id="@+id/fri"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Fri"
        android:textOff="Fri"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton" />
       <ToggleButton
        android:id="@+id/sat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Sat"
        android:textOff="Sat"
        android:onClick="daysOfWeek"
        android:background="@drawable/togglebutton"
         />

    </LinearLayout>
    </HorizontalScrollView >
<View
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:background="#31B6E7"/>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <CheckBox
        android:id="@+id/wifi"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Wi-Fi"
        android:onClick="checkBoxClicked" />

    <CheckBox
        android:id="@+id/internet"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:onClick="checkBoxClicked"
        android:text="Mobile data" />

</LinearLayout>
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
      <CheckBox
        android:id="@+id/gps"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="GPS"
        android:onClick="checkBoxClicked" />
    <CheckBox
        android:id="@+id/bluetooth"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Bluetooth"
        android:onClick="checkBoxClicked" />
</LinearLayout>
    <CheckBox
        android:id="@+id/airplaneMode"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Airplane mode"
        android:onClick="checkBoxClicked" />
        <View
    android:layout_width="fill_parent"
    android:layout_height="2dp"
    android:background="#31B6E7"/>
        <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Phone profile"
        android:textSize="18sp"/>
     <RadioGroup
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/sound"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onoff"
            android:layout_weight="1"
            android:text="Sound" />
        <RadioButton
            android:id="@+id/vibrate"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onoff"
            android:layout_weight="1"
            android:text="Vibrate" />
        <RadioButton
            android:id="@+id/Silent"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Silent"
            android:layout_weight="1"
            android:onClick="onoff"
             />
    </RadioGroup>

     <EditText
         android:id="@+id/EventName"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:ems="10"
         android:text="Event name" >
     </EditText>

</LinearLayout>


text:
Q: Terminal pager: How to display a list in columns? I'm sure it's very simple, but I can't remember how to tell a terminal pager (more/less/pg/most) to display a long list in columns.
Since my input is just a list of short elements, displaying it the same way ls does it by default would save me needless scrolling and precious screen real estate.
bad:
aaa
bbb
ccc
ddd
eee
fff
ggg
hhh
iii

good:
aaa ddd ggg
bbb eee hhh
ccc fff iii

A: Use column.
Example:
ls -1 | column -c 100

This will format the output of ls -1 (one entry per line) to fit as many columns of equal size as possible in rows that are 100 character wide.

A: You can use paste to join lines from stdin:
paste - - - < filename

A: Similar to Daniel Beck's answer:
$ echo {a..c}{a..c}{a..c}| tr \  \\n | column | sed 's/\t/ /g' | $PAGER
aaa aba aca baa bba bca caa cba cca
aab abb acb bab bbb bcb cab cbb ccb
aac abc acc bac bbc bcc cac cbc ccc

The key is to make the output more compact by substituting tabs with spaces.


text:
Q: symfony2 syntax error I have the following code:
public function postFormAction(Request $request)
{

    $cityId = $request->request->get('shopiousUserBundle_user')['location']['city'];
    .....
}

for some reason this is giving me a syntax error, any idea why?
When I remove the array indexing to be just like:
$cityId = $request->request->get('shopiousUserBundle_user')

works fine.

A: Array dereferencing from the result of a function call is only available in PHP 5.4 or later.
See http://php.net/manual/en/language.types.array.php#example-88
If you are using an earlier PHP version, you will have to do the following
$data = $request->request->get('shopiousUserBundle_user');
$cityId = $data['location']['city'];


text:
Q: How to make a simple Wine-based installer for Windows application My Windows application runs under Wine, but the installation is a bit of a headache for laymen, and the wrappers I've seen online (PlayOnLinux, Wine Doors) require even more packages to be installed. Is there a way to make a package that will install Wine if the user needs it to be installed, install the application and shortcuts, all with minimal user hassle?

A: I don't believe there's any pre-made way to do this, but you could probably make a Debian package pretty easily that would depend on Wine, copy an MSI onto the machine, then run Wine's msiexec /i /q as the post-install script
Edit: Make sure to think about the uninstall case too! I.e. in the pre-uninstall script, run msiexec again as well.

A: You can bundle Wine -- that's what Picasa does -- or you can just make your package list Wine as a dependency; then the user's package manager will automatically install Wine for the user when they install your package.
Ideally your Linux package wouldn't run the Windows installer, but rather have all the files already unpacked.
The trick is to arrange for the files your package installs in /usr to show up in each user's .wine directory.  You can look at how Picasa does this, but really the Wine community needs to document how to do this much better.
As always, ask at winehq.org if you need more info.

A: If you'd like to target the Mac OS, you can use WineBottler:
http://winebottler.kronenberg.org/
This project exists just for bundling Wine into a native Mac .app bundle in a way that's fairly hidden from the user.

A: Answer is simple:

*

*Create Elf installer.

*Pack Elf installer onto Exe installer resources.

*Exe installer should unpack Elf installer on startup.

*Exe installer must tries to run Elf installer after unpack (system call or some think).

*If operation fail, we do normal install.

*If operation didn't fail, we close Exe installer.


text:
Q: Create new dictionary of value combinations from another dictionary I have the following dictionary.
dict = {}
dict['key1'] = ['A', 'B', 'C']
dict['key2'] = ['B', 'D']
dict['key3'] = ['A', 'C', 'E']

I'd like to create a new dictionary that holds all combinations of letters to other letters in the same list.
I'd like the final result to look like this.
{
    'A': ['B', 'C', 'E'],
    'B': ['A', 'C', 'D'],
    'C': ['A', 'B', 'E'],
    'D': ['B'],
    'E': ['A', 'C']
}

I tried to initialize a new dictionary of empty lists and iterate through each list to get the combination and append to the dictionary of lists, but I seem to be missing something.
dict = {}
dict['key1'] = ['A', 'B', 'C']
dict['key2'] = ['B', 'D']
dict['key3'] = ['A', 'C', 'E']

dict2={}
list = ['A', 'B', 'C', 'D', 'E']

# instantiate dict2
for i in list:
    dict2[i]=[]

for idx, key in enumerate(dict):
    print(key, dict[key])
    tmp = dict[key]
        for x in tmp:
           tmp.remove(x)
           for y in tmp:
               dict2[x].append(y)

A: I'd suggest using a dict of sets as an intermediate step and then converting to lists for the final result:
# Initial data.  (Don't use 'dict' as a variable name!)
my_dict = {
    'key1': ['A', 'B', 'C'],
    'key2': ['B', 'D'],
    'key3': ['A', 'C', 'E'],
}

# Build all combinations as a dict of sets.
all_combos = {}
for v in my_dict.values():
    for x in v:
        all_combos.setdefault(x, set()).update(v)
        all_combos[x].remove(x)

# Convert dict of sets to dict of sorted lists.
final_dict = {k: sorted(v) for k, v in all_combos.items()}

from pprint import pprint
pprint(final_dict)

prints:
{'A': ['B', 'C', 'E'],
 'B': ['A', 'C', 'D'],
 'C': ['A', 'B', 'E'],
 'D': ['B'],
 'E': ['A', 'C']}

A: Just to complement Samwise's way by a set comprehension method:
dict = {}
dict['key1'] = ['A', 'B', 'C']
dict['key2'] = ['B', 'D']
dict['key3'] = ['A', 'C', 'E']

dict2 = {key: val for key, val in zip(set([item for sublist in dict.values() for item in sublist]), [set([item for sublist in [x for x in dict.values() if key in x] for item in sublist]) for key in set([item for sublist in dict.values() for item in sublist])])}

Last step would only be to remove the key from each set, but I am sure you'd be able to do this :)

A: Using a collections.defaultdict we can first create a dictionary listing all characters that occur with each character.
Then we can use a dictionary comprehension to convert those lists to a set and remove the actual key character.
from collections import defaultdict

d = defaultdict(list)

for k, v in my_dict.items():
  s = set(v)
  for c in s:
    d[c] += list(s)

# d = defaultdict(<class 'list'>, {'A': ['A', 'C', 'B', 'A', 'C', 'E'], 'C': ['A', 'C', 'B', 'A', 'C', 'E'], 'B': ['A', 'C', 'B', 'D', 'B'], 'D': ['D', 'B'], 'E': ['A', 'C', 'E']})

e = {k: set(v) ^ set([k]) for k, v in d.items()}

# e = {'A': {'C', 'B', 'E'}, 'C': {'A', 'B', 'E'}, 'B': {'C', 'A', 'D'}, 'D': {'B'}, 'E': {'A', 'C'}}


text:
Q: Pass the same value in two different arrays - VBA i m passing the same value to two different arrays using:
arrHo(0) = BoTeHa
arrAw(0) = BoTeHa

The above code works fine BUT i m wondering if there any other way to pass the value in both arrays in the same line like:
arrHo(0)  And arrAw(0) =BoTeHa


text:
Q: SSMS Registered Servers with ReadOnly Application Intent We are working on SQL Server 2014 POC testing with AlwaysOn and one of the user asked about saving the configuration of SSMS with ReadOnly Intent using the registered servers in Local server group. This way they don't have to type in the alias name every time they need to access the ReadOnly replica.
Unfortunately there is no option within registered servers to add the ApplicationIntent Option unlike the regular object explorer.
I came across this article from Microsoft about changing the connection string in RegSrvr.xml.
https://connect.microsoft.com/SQLServer/feedback/details/786323/ssms-sql-server-management-studio-2012-missing-connection-properties-for-availability-groups
I tried their suggestion and it did not connect to the right replica node when connecting via the local server in the registered servers.
The ReadOnly option works fine from object explorer when using the options in the connect window > Additional Connection Parameters. But it does not save the changes made to the connection.
Does anyone know of any alternate solutions on saving the configurations with ReadOnly Intent property with SSMS? Thanks in advance for your help.

A: SQL Management Studio (versions prior to 2016)
Unfortunately, there are some caveats that make using Application Intent in SQL Management Studio somewhat painful:
To connect manually with ReadOnly intent, after bringing up the Connect
       to Server dialog from the Object Explorer, users must remember to:

*

*Click Options >>.

*Go to the Additional Connection Parameters tab.

*Enter the additional parameter as ApplicationIntent=ReadOnly;

*(Note: Users must not click the Options << button after entering
        the Additional Connection Parameters or the parameters will be
        lost.)

*Click Connect.

*Always launch query windows by right-clicking on the desired database in the Object Explorer view and choosing New Query to avoid running into the #3 caveat below.

The caveats that apply are as follows:

*

*Although you can get SQL Management Studio to connect with Read Only Intent, it does not store the Additional Connection Parameters when a connection is added to Registered Servers.

*Behavior when hand editing the locally registered servers in the RegSrvr.xml file to add the Application Intent is extremely inconsistent and will be overwritten any time a change is made through the GUI making this workaround unreliable.

*The Always On database must be selected before the query window is opened; otherwise, the connection gets routed to the primary server. If you attempt to select the database using the query window's drop down after the query window has already been opened to a non-Always On database, you will get an error dialog. If you try to change the database to an Always On database with a USE statement after the query window has already been opened to a non-Always On database, the results look like this when you attempt to execute the SQL query:

      Msg 979, Level 14, State 1, Line 1
      The target database ('AlwaysOnDatabase') is in an availability group
      and currently does not allow read only connections. For more
      information about application intent, see SQL Server Books Online.

SQL Management Studio (versions 2016 or later)
SQL Server Management Studio 2016 or higher can connect with Read Only Application Intent (using the same 6 steps as prior versions) and it does store the Additional Connection Parameters. There are still some caveats:

*

*The Object Explorer view will not enumerate any of the tables or
other objects in the AlwaysOn databases. Attempting to expand them
results in an access denied message.

*You cannot have a Read Only and a non-Read Only connection to the
    same listener open at the same time.

*Intellisense for object names in the database does not work. (Oddly
    enough, Objects get enumerated just fine in the Query Designer that
    you can launch using Design Query in Editor... from the
    right-click menu.)

*Caveat 3 from the prior versions' caveats still applies.

Third-Party Products
LinqPad stores the whole connection string including Application Intent and the database when you save a connection and therefore might be a viable option for performing Read Only queries against Always On databases.

A: Is it possible that you create a configuration file and then you auto create the necessary registered servers in SSMS? Just as mentioned in my MSSQLTips article:
Automate Registering and Maintaining Servers in SQL Server Management Studio (SSMS)

A: Have you tried the PowerShell script, but use another spelling (with a space) for application intent? Or have I got the connection methods mixed up?
Server=$regsrv ; integrated security=true;Initial Catalog=dbname;
Application Intent=ReadOnly");

Connect to SQL Server Using Application Intent Read-Only

A: This has been fixed in SQL 2016 SSMS when using with registered servers. I was able to register a ReadOnly Intent connection as part of local servers group and open the saved connection for future use. Thanks for the help with this.

A: I can't comment but am adding to DBAUser's answer.
I couldn't see an option to add Application Intent in the GUI when setting up the connection within the registered servers area.
I had to either connect using object explorer (using Data Source=<Listener>;Initial Catalog=<Database>;ApplicationIntent=ReadOnly) then register the server once I was connected.
Or add Initial Catalog=<Database>;ApplicationIntent=ReadOnly to the connection string in the .regsrvr file.

A: You may be missing an important part of the puzzle or at least I didn't see it anywhere in your question:
ApplicationIntent=readonly is one half of the equation. You also need to pass the parameter MultiSubnetFailover=True.
For instance, in the Additional Connection Parameters tab, you want to enter the following:
MultiSubnetFailover=True;ApplicationIntent=readonly;


text:
Q: Proof of Theorem 1.41(d) on Rudin's Functional Analysis. Inducing an invariant metric on the quotient space $X/N$. I have a question from the proof of Theorem 1.41 (d) in Rudin's Functional Analysis.
Namely, let $N$ be a closed subspace of a topological vector space $X$. Let $\tau$ be the topology of $X$ and define $\tau_N$ as the quotient topology on $X /N$.
In this case, 1.41 (d) shows that if $\tau$ is induced by a complete invariant metric $d$, then $\tau_N$ is also induced by some complete invariant metric $\rho$.
Proof: Suppose that $d$ is an invariant metric on $X$, compatible with $\tau$. Define $\rho$ by
$$\rho(\pi(x),\pi(y))= \inf\{d(x-y,z):z \in N\}.$$ This may be interpreted as the distance from $x-y$ to $N$. We omit the verifications that are now needed to show that $\rho$ is well defined and that it is an invariant metric on $X/N$. Since
$$\pi(\{x:d(x,0)<r\})=\{u:\rho(u,0)<r\},$$ it follows from (b) that $\rho$ is compatible with $\tau_N$.
In this proof, how do we show that $\rho$ is well-defined invariant, i.e., if $x_1 - x_2 \in N$ and $y_1-y_2 \in N$, then $d(x_1-y_1,N)=d(x_2-y_2,N)$?
Also, how do we show that $\pi(\{x:d(x,0)<r\})=\{u:\rho(u,0)<r\}$?
I would greatly appreciate any help with these questions.

A: I think I have proved this.
Well-defined : Suppose we have $x_1 - x_2 \in N$ and $y_1 - y_2 \in N$.
Then for any $z \in N$, $d(x_1 - y_1, z)=d(x_1 - y_1 + x_2 - y_2, z + x_2 - y_2) = d(x_2 - y_2, z+ x_2 - y_2 - x_1 + y_1)$.
Now, on the right, $x_2-y_2 - x_1 + y_1 \in N$, and $z$ varies over the linear subspace $N$, so by taking the infimum on both sides over $z \in N$, we get $d(x_1-y_1,N)= d(x_2-y_2,N)$.
$\pi\{x:d(x,0)<r\} = \{u: \rho (u,0)<r\}$:
Suppose $d(x,0)<r$ for some $x \in X$. Then $\rho(\pi(x),\pi(0)) = d(x,N)$. This is $0$ if $x \in N$ and if $x \notin N$, we have $d(x,N) \le d(x,0) < r$. So we have $\rho(\pi(x),0)<r$.
Next, suppose $\rho(u,0)<r$. Then $u = x + N = \pi(x)$ for some $x \in X$. This means that for some $n \in N$, we have $d(x,n)<r$. By invariance, $d(x-n,0)<r$. But $\pi(x-n)=\pi(x) - \pi(n) = \pi(x) = u$. So we get the left inclusion as well.


text:
Q: How can I retrieve database data and present it in an application I am currently working on an application in android studio as I am trying to learn how to use it in my spare time, my knowledge is very low so I was hoping I can explain the concept of my app and ask people for some pointers in different techniques I could use. The basic idea of my app is that it works by allowing people to search for a celebrity and it shows a few facts about them, their date of birth etc. I know its nothing special but it is literally a concept to help me improve my android studio knowledge.
My main issue with this is getting the information from the database into the application in an easy to read and presentable way, what sort of things should I be researching to help me achieve this, from my knowledge I believe I would need to set up a scanner to take the users input, then search the database to find the information and then I need to find a way to return the results in a presentable manner.
Apologies if this is too long winded a question, and thank you to everybody who takes the time to read and respond to me.

A: If you are looking for some API then check this out this can be help full.
https://api-ninjas.com/api/celebrity

You can even check if Wikipedia have any API for providing info.
I found this also
http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot#APIs%5Ffor%5Fbots

It appears there's also an API for IMDB: http://www.deanclatworthy.com/imdb/


text:
Q: Moment is not using local automatically Shouldn't moment use the local timezone for everything when created with moment()?

It definitely doesn't. Is there any way around using .local() everywhere? Or am I doing anything wrong? This might cause many bugs in my application and it is the first time I come across it.
I have to add that I had the node application running and put my PC in sleep - after waking it up this occurs! A new node instance doesn't let me reproduce it!


text:
Q: How to set up Github CI for Rails + Rspec + Capybara & Selenium Webdrivers for a multi domain app? The problem
When running on Github's CI, I get a SocketError: getaddrinfo: Name or service not known when trying to visit a page.
     2.1) Failure/Error: visit '/'

          SocketError:
            getaddrinfo: Name or service not known

          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:110:in `initialize'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:110:in `new'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:110:in `find_available_port'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:37:in `initialize'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/session.rb:93:in `new'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/session.rb:93:in `initialize'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara.rb:424:in `new'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara.rb:424:in `block in session_pool'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara.rb:315:in `current_session'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/dsl.rb:46:in `page'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/dsl.rb:58:in `block (2 levels) in <module:DSL>'
          # ./spec/system/register_system_spec.rb:8:in `block (3 levels) in <main>'

     2.2) Failure/Error: server = TCPServer.new(host, 0)

          SocketError:
            getaddrinfo: Name or service not known

          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:110:in `initialize'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:110:in `new'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:110:in `find_available_port'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/server.rb:37:in `initialize'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/session.rb:93:in `new'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/session.rb:93:in `initialize'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara.rb:424:in `new'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara.rb:424:in `block in session_pool'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara.rb:315:in `current_session'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/capybara-3.33.0/lib/capybara/dsl.rb:46:in `page'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/actionpack-5.2.4.2/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb:54:in `save_image'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/actionpack-5.2.4.2/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb:25:in `take_screenshot'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/actionpack-5.2.4.2/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb:37:in `take_failed_screenshot'
          # /usr/share/rvm/gems/ruby-2.5.5/gems/actionpack-5.2.4.2/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb:21:in `after_teardown'

Tests run correctly on my local environment with rspec and both selenium_google_chrome_headless or selenium_google_chrome.
The app

*

*It's a multi domain app so my tests run with

before { Capybara.app_host = "http://#{subdomain}.myapp.test" }

*

*Library versions

*

*Ruby 2.5.5

*gem 'rails', '~> 5.2.4'

*gem 'rspec-rails', '~> 3.8'

*capybara (3.33.0)

*webdrivers (4.4.1)

*

*selenium-webdriver (3.142.7)

*Here is my Github CI workflow

env:
  RUBY_VERSION: 2.5.5
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Start database
        run: |
          sudo systemctl start mysql
      - name: Set up Ruby 2.5.5
        run: |
          sudo apt-add-repository -y ppa:rael-gc/rvm
          sudo apt-get update
          sudo apt-get -y install rvm
          source /etc/profile.d/rvm.sh
          rvm install ${{ env.RUBY_VERSION }}
      - name: setup-chromedriver
        uses: nanasess/setup-chromedriver@v1.0.1
      - name: Build and test
        env:
          DATABASE_PASSWORD: root
        run: |
          source /etc/profile.d/rvm.sh
          rvm use ${{ env.RUBY_VERSION }}
          gem install bundler
          bundle install --jobs 4 --retry 3
          mysql -uroot -p${{ env.DATABASE_PASSWORD }} --execute="CREATE DATABASE myapp_test"
          RAILS_ENV=test rails db:setup
          bundle exec rspec spec/system

A: Using :headless_chrome as javascript browser with this configurations in spec/spec_helper.rb

A: Adding
Capybara.server = :puma

to my spec/rails_helper.rb file seems to fix my main issue.
My tests are still not passing on Github Actions but it looks to be a different issue.


text:
Q: Unpacking a nested matrix in pandas I've got some data like
moved_to_matrix    [[0, 1, 0]]
companies          [Barcelona, Madrid, Amsterdam]
moved_from_matrix  [[0, 0, 1]]

And I want to figure out how to convert this to a transition matrix in Pandas/Numpy. Has anyone any ideas. I tried pd.melt but it didn't work out for me.

A: You can use:
df = pd.DataFrame({'a':['moved_to_matrix','companies','moved_from_matrix'],
                   'b':[[[0, 1, 0]], ['Barcelona', 'Madrid', 'Amsterdam'], [[0, 0, 1]]]})

print (df)
                   a                               b
0    moved_to_matrix                     [[0, 1, 0]]
1          companies  [Barcelona, Madrid, Amsterdam]
2  moved_from_matrix                     [[0, 0, 1]]

#remove nested list
df.b = df.b.mask(df.b.str.len() == 1, df.b.str[0])
print (df)
                   a                               b
0    moved_to_matrix                       [0, 1, 0]
1          companies  [Barcelona, Madrid, Amsterdam]
2  moved_from_matrix                       [0, 0, 1]

#create columns by df constructor
df = pd.DataFrame(df.b.values.tolist(), index=df.a).reset_index()
df.columns = ['a','b','c','d']
print (df)
                   a          b       c          d
0    moved_to_matrix          0       1          0
1          companies  Barcelona  Madrid  Amsterdam
2  moved_from_matrix          0       0          1


text:
Q: How to output NLTK pos_tag in the string instead of a list? I need to run nltk.pos_tag on a large dataset and need to have its output like the one that is offered by Stanford tagger.
For example while running the following code I have;
import nltk
text=nltk.word_tokenize("We are going out.Just you and me.")
print nltk.pos_tag(text)

the output is:
[('We', 'PRP'), ('are', 'VBP'), ('going', 'VBG'), ('out.Just', 'IN'), ('you', 'PRP'), ('and', 'CC'), ('me', 'PRP'), ('.', '.')]
In the case that I need it to be like:
 We/PRP are/VBP going/VBG out.Just/NN you/PRP and/CC me/PRP ./.

I prefer to not using string functions and need a dirrect output because the amount of the text is so high and it adds lots of time complexities to the processing

A: In short:
' '.join([word + '/' + pos for word, pos in tagged_sent]

In long:
I think you're overthinking about using string functions to concat the strings, it's really not that expensive.
import time
from nltk.corpus import brown

tagged_corpus = brown.tagged_sents()

start = time.time()

with open('output.txt', 'w') as fout:
    for i, sent in enumerate(tagged_corpus):
        print(' '.join([word + '/' + pos for word, pos in sent]), end='\n', file=fout)

end = time.time() - start
print (i, end)

It took 2.955 seconds on my laptop for all 57339 sentences from the brown corpus.
[out]:
$ head -n1 output.txt
The/AT Fulton/NP-TL County/NN-TL Grand/JJ-TL Jury/NN-TL said/VBD Friday/NR an/AT investigation/NN of/IN Atlanta's/NP$ recent/JJ primary/NN election/NN produced/VBD ``/`` no/AT evidence/NN ''/'' that/CS any/DTI irregularities/NNS took/VBD place/NN ./.

But using string to concatenate the word and POS can cause trouble later on when you need to read your tagged output, e.g.
>>> from nltk import pos_tag
>>> tagged_sent = pos_tag('cat / dog'.split())
>>> tagged_sent_str = ' '.join([word + '/' + pos for word, pos in tagged_sent])
>>> tagged_sent_str
'cat/NN //CD dog/NN'
>>> [tuple(wordpos.split('/')) for wordpos in tagged_sent_str.split()]
[('cat', 'NN'), ('', '', 'CD'), ('dog', 'NN')]

If you want to saved the tagged output and then read it later, it's better to use pickle to save the tagged_output, e.g.
>>> import pickle
>>> tagged_sent = pos_tag('cat / dog'.split())
>>> with open('tagged_sent.pkl', 'wb') as fout:
...     pickle.dump(tagged_sent, fout)
...
>>> tagged_sent = None
>>> tagged_sent
>>> with open('tagged_sent.pkl', 'rb') as fin:
...     tagged_sent = pickle.load(fin)
...
>>> tagged_sent
[('cat', 'NN'), ('/', 'CD'), ('dog', 'NN')]


text:
Q: Which Google-Map-API is suitable for my usage? I am not a web developer and I have not any experience about Web Software Development.
I need to prepare a web site, which get location of some devices every 15 seconds and show location of them on Google Map. To real time connection I need to use TCP or UDP, and I preferred to use NodeJS but I am not sure which Google service API is more suitable for me.
As I checked the Google Web Services, there is a service which is called "Google Maps Roads API". This API is interested for me but Google says it is available as part of Java or Python.
So I need to know:

*

*Is any advantages
    to use Road Map API?

*Do you suggest me I use Java or Python and
    don't use NodeJS?

*Can I combine Java or Python with NodeJS ?

And At the end, I am glad to hear any recommend from experienced members.


text:
Q: how to retrieve facebook friends list in react native app I'm trying to retrieve all user's friends and render them in a list view using facebook graph request.
const infoRequest = new GraphRequest(
      '/me',
         {
           parameters: {
               fields: {
                        string: 'email, name, first_name, middle_name,
                 last_name, picture.type(large), cover, birthday, location, friends'
                    }
                }
            },
            this._responseInfoCallback
        );

A: Facebook doesn't allow you to access your full friends list anymore since API 2.0, just those who also use your app. https://developers.facebook.com/docs/graph-api/reference/v2.2/user/friends.
For further reference you can also check the post Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app
If you still have any queries please let me know. :)
EDIT
You can get the list of friends of the user which are not using this app with the api call given below:-

https://graph.facebook.com/' + facebookUserId +
  '/invitable_friends?access_token=' + userToken

and then inside the callback of the above api call you can make a new api call and get the list of users friends which are using the app with the call given below:-

https://graph.facebook.com/' + facebookUserId + '/friends?access_token=' + userToken

and then you can concat the result of both the api calls and get the list of all the friends of the user as below:-

let allFriends = firstApiResponseArray.concat(SecondApiResponseArray)

Now allFriends will give the list of all the friends of the user. I hope this is what you are looking for :)


text:
Q: Not able to send mail from my host I am using java mail api for sending mail. I am able to send mail using Google account but facing some issue sending from my domain using SSL.
Here is the implementation, please let me know where i am lacking.
// Create all the needed properties
        Properties connectionProperties = new Properties();
        // SMTP host
        connectionProperties.put("mail.smtp.host", "abc.example.com");
        // Is authentication enabled
        connectionProperties.put("mail.smtp.auth", "true");
        // Is StartTLS enabled
        connectionProperties.put("mail.smtp.starttls.enable", "true");
        // SSL Port
        connectionProperties.put("mail.smtp.socketFactory.port", "465");
        // SSL Socket Factory class
        connectionProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // SMTP port, the same as SSL port :)
        connectionProperties.put("mail.smtp.port", "465");

        // Create the session
        Session session = Session.getDefaultInstance(connectionProperties, new javax.mail.Authenticator()
        { // Define the authenticator
            protected PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("abc@example.net", "abcxdsjdf123");
            }
        });

        System.out.println("done!");

        // Create and send the message
        try
        {
            // Create the message
            Message message = new MimeMessage(session);
            // Set sender
            message.setFrom(new InternetAddress("abc@example.net"));
            // Set the recipients
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xyz@example.net"));
            // Set message subject
            message.setSubject("Hello from Test");
            // Set message text
            message.setText("This is test mail;)");

            System.out.print("Sending message...");

            // Send the message
             Transport.send(message);

            System.out.println("done!");
        }
        catch (MessagingException e)
        {
            System.out.println(e.toString());
        }

Below is the exception i am getting:
javax.mail.MessagingException: Exception reading response;
  nested exception is:
    java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)

Any sort of help would be appreciable.
Thanks in advance.

A: Try this..
   public class SentMail {
        public boolean deliverMail(String username, String email, String subject, String content) {
            boolean sent = false;
            try {
                String delim = "\n\n";
                String text = "Hi ," + delim + content + delim + "Thank you ," + delim + username + "\n" + email;
                String from = "from_email";
                String pass = "from_pass";
                String to = "to_email";
                <!--Your host-->
                String host = "smtp.zoho.com";
                <!--Host port-->
                String port = "465";
                Properties properties = System.getProperties();
                properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.setProperty("mail.smtp.socketFactory.fallback", "false");
                properties.setProperty("mail.smtp.socketFactory.port", port);
                properties.put("mail.smtp.startssl.enable", "true");
                Session session = Session.getDefaultInstance(properties);
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(to));
                message.setSubject(subject);
                message.setText(text);
                Transport transport = session.getTransport("smtp");
                transport.connect(host, from, pass);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                sent = true;
            } catch (Exception e) {

            }
            return sent;

        }
    }


text:
Q: Styling autogenerated DataGrid column on validation failure I have a DataGrid filled with instances of a class that exposes a double type property. This property is shown into the DataGrid. I want to implement a custom validation, and I want to color the whole cell red if this validation fails. I think I am close to making it work, but not quite yet, and now I'm stumped.
My problem is that I cannot make the conditional (on validation fail) formatting work. The result is that the cells are correctly colored at the start, but when I insert a value that makes the falidating function return false, I get the usual red border, white background cell style.
How am I supposed to input this formatting style?
XAML code:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
  <DataGrid x:Name="dg" ItemsSource="{Binding Data}">
    <DataGrid.Resources>
      <ControlTemplate x:Key="validationTemplate">
        <DockPanel>
          <AdornedElementPlaceholder/>
          <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
        </DockPanel>
      </ControlTemplate>

      <Style TargetType="{x:Type TextBox}">
        <Setter Property="Background" Value="Yellow"/>
        <Setter Property="Validation.ErrorTemplate" Value="{StaticResource validationTemplate}"></Setter>
      </Style>
    </DataGrid.Resources>
  </DataGrid>
</Window>

Code behind:
public partial class MainWindow : Window
{
  ...

  private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e)
  {
    foreach (DataGridTextColumn c in dg.Columns)
    {
      c.ElementStyle = (Style)dg.FindResource("s");

      for (int i = 0; i < dg.Items.Count; i++)
      {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);
        if (row == null) // May be virtualized, bring into view and try again.
        {
          dg.UpdateLayout();
          dg.ScrollIntoView(dg.Items[i]);
          row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(i);
        }
        TextBlock tb = (TextBlock)c.GetCellContent(row);

        Binding binding = BindingOperations.GetBinding(tb, TextBlock.TextProperty);
        binding.ValidationRules.Clear();
        binding.ValidationRules.Add(new VR());
      }
    }
  }
}

public class VR : ValidationRule
{
  public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
  {
    ...
  }
}

EDIT: updated XAML code according to dev hedgehog's suggestion, still not working.

A: You seem to be using ErrorTemplate wrong.
Take a look at this:
<ControlTemplate x:Key="validationTemplate">
  <DockPanel>
    <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
    <AdornedElementPlaceholder/>
  </DockPanel>
</ControlTemplate>

<TextBox Name="textBox1" Width="50" FontSize="15"
         Validation.ErrorTemplate="{StaticResource validationTemplate}"
         Style="{StaticResource textBoxInError}"
         Grid.Row="1" Grid.Column="1" Margin="2">
  <TextBox.Text>
    <Binding Path="Age" Source="{StaticResource ods}"
             UpdateSourceTrigger="PropertyChanged" >
      <Binding.ValidationRules>
        <c:AgeRangeRule Min="21" Max="130"/>
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

Validation.ErrorTemplate will allow you to decorate AdornedElementPlaceholder which is in this case TextBox.
In the example I gave you a red ! will be decorated to the left of the TextBox.
Edit:
I changed your code to make it work.
<Grid>
    <DataGrid x:Name="dg" ItemsSource="{Binding Data}" PreparingCellForEdit="OnBeginningEdit">
        <DataGrid.Resources>
            <ControlTemplate x:Key="validationTemplate">
                <DockPanel>
                    <AdornedElementPlaceholder/>
                    <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
                </DockPanel>
            </ControlTemplate>

            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Background" Value="Yellow"/>
                <Setter Property="Validation.ErrorTemplate" Value="{StaticResource validationTemplate}"/>
            </Style>
        </DataGrid.Resources>
    </DataGrid>
</Grid>

This is the code behind
public partial class MainWindow : Window
{
    public List<D> Data { get; set; }

    public MainWindow()
    {
        Data = new List<D>();
        Random r = new Random();
        Data.Add(new D(r.NextDouble()));
        Data.Add(new D(r.NextDouble()));
        Data.Add(new D(r.NextDouble()));

        InitializeComponent();

        DataContext = this;
    }

    private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e)
    {
        foreach (DataGridTextColumn c in dg.Columns)
        {
            c.EditingElementStyle = (Style)dg.FindResource("s");
        }
    }

    private void OnBeginningEdit(object sender, DataGridPreparingCellForEditEventArgs e)
    {
        TextBox tbx = (TextBox)e.EditingElement;
        Binding binding = BindingOperations.GetBinding(tbx, TextBox.TextProperty);
        binding.ValidationRules.Clear();
        binding.ValidationRules.Add(new VR());
    }
}

See you need to work with TextBoxes and when you write something inside one then click away in order to trigger validation.
Try it out. It works for me :)


text:
Q: Merge Multiple Datasets with Identical Column Names in R While Attaching a Suffix to Each Column to Identify its Dataset I am trying to merge3 datasets, which are part of longitudinal study. The variable names are a identical across the waves of the study. What I want to accomplish is to attach a suffix to each variable name to indicate the dataset it belongs to while merging them. I have been able to do that in a roundabout way, but I am thinking there should be an easier way to accomplish that. Below is what I have done so far, just using some fictitious data to illustrate.
## step 1: create three dfs with identical variable names
df1 = data.frame('ID' = 1:10, 'V1' = sample(x=1:5, size=10, replace=T), 'v2' = sample(x=1:5, size=10, replace=T))
df2 = data.frame('ID' = 1:10, 'V1' = sample(x=1:5, size=10, replace=T), 'v2' = sample(x=1:5, size=10, replace=T))
df3 = data.frame('ID' = 1:10, 'V1' = sample(x=1:5, size=10, replace=T), 'v2' = sample(x=1:5, size=10, replace=T))

## step 2: function to rename all columns in a dataset
colsRename <- function(data, nn){

  nn = nn
  df = data %>%
    rename_with(~ paste0(colnames(data), paste0('_'), nn)[which(colnames(data) == .x)],
                .cols = colnames(data)) %>%
    glimpse()

  return(df)

}

## call function to rename columns
w1 = colsRename(df1, 'W1')
w2 = colsRename(df2, 'W2')
w3 = colsRename(df3, 'W3')

# merge the dataframes
dfMerge = merge(w1, w2, by.x = c("ID_W1"), by.y = c("ID_W2"), all = FALSE) %>%
  merge(., w3, by.x = c("ID_W1"), by.y = c("ID_W3"), all = FALSE) %>%
  glimpse()

The final output for the joined/merged dataframes will look something like below
   ID_W1 V1_W1 v2_W1 V1_W2 v2_W2 V1_W3 v2_W3
1      1     3     4     1     5     5     1
2      2     4     2     5     4     5     2
3      3     4     3     2     4     1     3
4      4     5     1     1     2     5     1
5      5     5     1     3     1     5     1
6      6     4     4     3     4     3     5
7      7     2     5     3     2     3     2
8      8     1     1     2     1     2     2
9      9     5     3     2     2     1     3
10    10     5     2     5     3     4     5

A: You can put the dataframe in a named list, rename the dataframes and use reduce -
library(dplyr)
library(purrr)

list(W1 = df1, W2 = df2, W3 = df3) %>%
  imap(function(x, y) x %>% rename_with(~paste(., y, sep = '_'), -ID)) %>%
  reduce(inner_join, by = 'ID')

#   ID V1_W1 v2_W1 V1_W2 v2_W2 V1_W3 v2_W3
#1   1     1     1     5     2     5     5
#2   2     3     2     4     4     3     3
#3   3     4     3     5     4     1     2
#4   4     1     4     2     3     4     5
#5   5     3     5     1     1     1     5
#6   6     5     5     1     2     1     3
#7   7     4     3     3     1     3     2
#8   8     2     1     1     2     4     2
#9   9     5     2     5     4     1     2
#10 10     1     5     1     5     3     4

If there are more dataframe and you don't want to name them individually you can collect all the dataframes from the global environment using mget.
mget(ls(pattern = 'df\\d+')) %>%
  imap(function(x, y) x %>% rename_with(~paste(., y, sep = '_'), -ID)) %>%
  reduce(inner_join, by = 'ID')

A: In R base you may do
d_nm <- c("df1", "df2", "df3")
L <- setNames(mget(d_nm), paste0('_W', seq(d_nm)))
Reduce(merge, Map(\(x, y) {names(x)[-1] <- paste0(names(x), y)[-1];x}, L, names(L)))
#    ID V1_W1 v2_W1 V1_W2 v2_W2 V1_W3 v2_W3
# 1   1     1     1     5     3     2     2
# 2   2     5     5     5     2     3     2
# 3   3     1     4     5     4     1     2
# 4   4     1     2     4     4     5     5
# 5   5     2     2     2     2     2     1
# 6   6     4     3     4     5     2     1
# 7   7     2     1     3     4     2     4
# 8   8     2     1     2     5     4     5
# 9   9     1     3     1     4     3     2
# 10 10     4     4     2     2     5     1

Data:
set.seed(42)
df1 <- data.frame(ID=1:10, V1=sample(x=1:5, size=10, replace=T), v2=sample(x=1:5, size=10, replace=T))
df2 <- data.frame(ID=1:10, V1=sample(x=1:5, size=10, replace=T), v2=sample(x=1:5, size=10, replace=T))
df3 <- data.frame(ID=1:10, V1=sample(x=1:5, size=10, replace=T), v2=sample(x=1:5, size=10, replace=T))


text:
Q: Why defaultContent method is giving staleElementException. Parent window textbox is receiving text here which I'm sending after defaultcontent method Code Trail
WebElement parentTextBox = driver.findElement(By.id("name"));
    parentTextBox.sendKeys("This is parent textbox");

    WebElement newWindowBtn = driver.findElement(By.id("newWindowBtn"));

    newWindowBtn.click();

    String parentWindow = driver.getWindowHandle();

    Set<String> getWindows = driver.getWindowHandles();

    for (String handles : getWindows) {

        if (!handles.equals(parentWindow))

        {
            driver.switchTo().window(handles);
            driver.manage().window().maximize();
            WebElement firstName = driver.findElement(By.id("firstName"));
            firstName.sendKeys("Pankaj");
        }

        Thread.sleep(10000);
        //driver.switchTo().window(parentWindow);

        //driver.switchTo().window("");

        driver.switchTo().defaultContent();

        Thread.sleep(5000);

        parentTextBox.clear();

        parentTextBox.sendKeys("switching back to parent window is success");

Error
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=105.0.5195.126)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-9GE1TC7', ip: '192.168.1.6', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 105.0.5195.126, chrome: {chromedriverVersion: 105.0.5195.52 (412c95e51883..., userDataDir: C:\Users\Admin\AppData\Loca...}, goog:chromeOptions: {debuggerAddress: localhost:65092}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: 2b22a0d3f499205579e31a39c1233d25
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:124)
at switchWindows.SwitchWindows.main(SwitchWindows.java:58)


text:
Q: Returning default link to logo I faced strange issue with SharePoint site collection. I manage 1 site in this site collection. At some moment I've created a wiki-page, just to try it out. Few months later I found that the link behind the Logo is changed. It now directs to the wiki page. It is quite annoying because most of my users don't have access to this page...
I don't know why it is changed and how to change it back. I want the link to behave just in default way. I.e. to direct to the main page of this site.
I've found on internet few good ideas, but none of them worked.

*

*If I use the link /_layouts/15/AreaWelcomePage.aspx I get the window to change the link. But selecting the top page of the site results in error message "The specified welcome page is not valid or does not exist within the current site." Well... Strange, because the other sites of the collection do have this type of links

*Another suggestion was to go Site collection settings and select "Look and feel" option. But I don't have this menu option.

*I don't know how to manage Master pages, but some advises suggest to do that.

Overall, it seems the solution should be much easier. Could you please advice?
Regards,
Alexander

A: Open the site and SharePoint designer and select your old page as your home page.  It sounds like when you made your new page, it made it your default page for the site.  Should be an easy fix.

A: Navigate to the page you want to set as home page. Under ribbon, go to page tab and select make home page.


text:
Q: declaring jsx element as a global variable Hello is there a way to declare react component globally so that when I render the same component the values are persisted, I am aware the redux or some other state management lib can be used, but for the time being I want to use this option cuz I'm in the middle of the project. For example
constructor() {
    this.accountInfoJSX = <AccountInformation ref={(sender) => {
        this.accountInformationMod = sender;
    }} />;
}

I can try to save the element in the global variable but each time when the render is called it initializes a new instance.
Edit:
yes sure. i have this method. I have 2 buttons on screen based on which i render different components. User can made some changes on each component, so i am trying to to use same component so that the changes made in component are persisted. i have tried returning this.accountInfoJSX as well as this.accountInformationMod not its not working. On former it re render the new component and values are lost and on latter it show nothing on screen.
get getCurrentScreen() {
    if (this.state.selectedScreen == Screens.accountInformation) {
      return this.accountInformationMod;
    } else if (this.state.selectedScreen == Screens.myInformation) {
      return <MyInformation />;
    }
  }


text:
Q: Golang Templates - Update and Print Counter Variable I am trying to update and print a counter variable inside of a Go template when iterating through a nested for loop.
I am not trying to print the index of either of my data structures as I loop through. I am not going to print every object in each data structure, and I want this counter  variable to only increment when an equality statement is true.
What am I doing wrong here?
Go Playground link: https://play.golang.org/p/RsuEk1PqZ7a
type a struct {
    Numbers []string
    Letters []string
}

var data = &a{
    Numbers: []string{"one", "two"},
    Letters: []string{"a","b","b", "c"},
}

var tmplSrc = `start
{{with $i := 0}}
  {{range $number := .Numbers}}
    {{range $letter := .Letters}}
      {{if eq $letter "b"}}
        {{$i = add $i 1}}
        {{$i}}
      {{end}}
    {{end}}
  {{end}}
{{end}}
fin
`

func main() {
    funcMap := template.FuncMap{
        "add": func(a int, b int) int {
            return a + b
        },
    }
    tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(tmplSrc))
    tmpl.Execute(os.Stdout, data)
}

A: The error returned from tmpl.Execute execute hints at the problem:

test:3:21: executing "test" at <.Numbers>: can't evaluate field Numbers in type int

Always handle errors!
The problem is that {{with $i := 0}} sets . to the 0. The template expects . to be the data argument to the template. Fix by using $ to refer to the data argument.  A similar change is required for .Letters because {{range}} also sets ..
{{with $i := 1}}
  {{range $number := $.Numbers}}
    {{range $letter := $.Letters}}
    {{if eq $letter "b"}}
      {{$i = add $i 1}}
      {{$i}}
    {{end}}
    {{end}}
  {{end}}
{{end}}

I used {{with $i := 1}} to match the code in the playground.  The question uses {{with $i := 0}}.  The code in the question introduces yet another problem: the contents of the {{with}} is skipped because the condition evaluates to false (0 is false in template conditions).  Fix by removing the {{with}} directive. It's not needed.
{{$i := 0}}
{{range $number := $.Numbers}}
  {{range $letter := $.Letters}}
    {{if eq $letter "b"}}
      {{$i = add $i 1}}
        {{$i}}
     {{end}}
  {{end}}
{{end}}


text:
Q: Setting up authentication on virtual machine I'm creating a system similar to a cloud computing provider using the libvirt python bindings.
I would like to give users the ability to specify a custom virtual machine image, in a similar fashion to AWS.
I would like to generate SSH key pairs on the fly and set the VM up for public key authentication.
Which is the best method to do this? Which requirements should I impose on the user-specified VM image for this to work?
I was thinking at a passwordless root account to allow my piece of software to login and set up what needed, but this leaves a (short) timespan during which everyone could login as root. Are there better solutions? Can I edit the virtual machine image before starting it?
In practice, I need to login to be able to login to the machine and execute some commands, before giving it to the user.
Edit:
Some additional details:

*

*I know about Eucalyptus, Cloudstack and Openstack. This implementation is for a very specific environment/requirements (HPC clusters, batch job scheduling) and does not allow to run these.

*I actually don't care (or, for the purpose of this question, it is not relevant) where the key pair comes from, I only want to know how the service provider can possibly access the machine, by requiring as less setup as possible on the VM image on the user part; ErikA replied to this suggesting a service specific key pair. Fair enough. Are there other solutions?

*The final user does not have to have access to the new virtual machine, he will run jobs on it through SLURM (though, he could access it if he wants to, I don't care).

*The provider takes care of:

*

*Allocating and spawning new domains (virtual machines)

*Spawning the SLURM daemon (which does not have to happen at startup, but at a certain point in time, thus the need for the provider to be able to access the machine)

A: Perhaps you should try and not re-invent the wheel.  There are many frameworks out there that will do exactly what you want... and even free/open-source ones.  Try looking at cloudstack or eucalyptus for two such environments.

A: I solved it in the following way:
As I needed the IP address assigned to the VM, and as libvirt doesn't offer means to retrieve it (as opposed to, i.e. VMWare which offers the VMWare tools suite for such operations), I ended setting up a serial (on the guest) to tcp (on the host) channel between the VM and the Host, using libvirt's virtual devices support.
A simple shell script on the guest waits then until an IP address is assigned to a given interface and writes it to the serial device. When the TCP server sitting on the host receives the IP address, it sends back it's public key, which the script on the guest reads (again, from the serial port) and writes back to the correct authorized_keys file.
This solution can be used without the IP exchange part, with only the guest reading the key from the serial port on booting. The advantages of such a solution are that the guest OS has not to be customized with a given key (so different, key pairs can be used for different system "partitions") and that it can manage where to put it; the downside is that the guest has to be configured to run the script.
Another solution would be to mount the disk image prior the VM booting by using something like libguestfs, copy the public key, unmount it and boot the guest. This solution is preferable over the TCP<->SerialPort one, but as I needed the IP address anyway I proceeded the other way around.
The third solution, as suggested by ErikA in his first comment, would be to let the user creating the image doing all the setup by giving them your public key. This is probably the best (cleanest and more elegant) solution for the most generic case.


text:
Q: @media queries in a very odd React implementation using .tsx and .ts files I have been working with React for the past two or so years, and with @media queries since the early 2000's. I have just been onboarded onto a new project where they are building React components in a fairly novel way, at least to my experience.
I'll place a snippet below to illustrate what I mean, but essentially they do not use .js and .css files as I usually do, but rather use .tsx and .ts files. They create a component in the .ts file and immediately apply the styling. It looks like this:
//.ts file
export const Container = styled.div`
  .second-chart {
    margin-top: 44px;
  }
`;

//.tsx file
import {Container} from "./styles";
...
<Container>
   <div className="second-chart">
   ...
   </div>
</Container>

I perfectly get how this works, and it seems simple enough to use. I am however concerned about how I would write @media queries for this type of implementation? I don't even know what to call it so I might be able to search for suggestions online.
Does anyone know a term I can use for this type of implementation? Or better yet, could someone please let me know how I can write a @media query for it? I was thinking that if I knew how to add a class to the 'styled.div' portion in the .ts file, I could always add my @media queries to a separate .css file.
Any advice would be greatly appreciated.

A: It looks as though the project is using Styled Components. As @phunder has pointed out, you can include all your normal css within the styled element which includes your media queries like so:
export const Container = styled.div`
  font-size: 16px

  @media only screen and (max-width: 600px) {
    font-size: 12px
  }
`;

A: Thanks to Abin Thaha's comment I was able to find the answer to the question. You simply add it to the declaration as a child, like so:
export const Container = styled.div`
  display:flex;
  .second-chart {
    margin-top: 44px;
  }
  @media only screen and (max-width: 1200px) {
    flex-direction: column;
    justify-content: center;
    .second-chart {
        margin-top: 35px;
    }
  }
`;


text:
Q: How to migrate sonar embedded H2 database to oracle database I am trying to migrate sonar's H2(default database) to oracle database. For this I have edited sonar.properties file. I commented sonar URL and uncommented oracle URL(I made jdbc connection with oracle database and pasted that URL in sonar.properties). I have also changed sonar usename and password in sonar.properties. When I start sonar it gives me error and ask me to create tables in oracle database and even if I create tables in oracle it still ask me to create such more tables.
Do I need to make some more configuration/file changes? Am I missing something?
Any help would be highly appreciated.


text:
Q: How Pushed Filters work with Parquet files in databricks? How does pushedFilters work while using parquet files ?
Below are the two queries that I submitted in databricks.
HighVolume = spark.read.parquet("/FileStore/shared_uploads/highVolume/*.parquet") \
  .where("originating_base_num in ('B02764','B02617')").count()

HighVolume_wofilter = spark.read.parquet("/FileStore/shared_uploads/highVolume/*.parquet") \
  .count()

Physical Plan: Clearly mentions PushedFilter is not null for HighVolume dataframe.
HighVolume :
  PushedFilters: [In(originating_base_num, [B02617,B02764])]

HighVolume_wofilter:
  PushedFilters: []

But while checking Spark UI, I observed that spark is reading all the rows in both the cases ( ignoring the filters).
snippet:
HighVolume :

HighVolume_wofilter:

Can someone please help me understand that why instead of having the filters in Physical plan, all the rows are being read. ?
Thanks!

A: When you working with parquet there are few types of optimizations:

*

*Skipping reading the not necessary files when table is partitioned, and there is a condition on that partition.  In the explain it will be visible as PartitionFilters: [p#503 IN (1,2)] (p is the partition column).  In this case Spark will read only files related to the given partitions - it's most efficient way for Parquet.

*Skipping some data inside the files - Parquet format has internal statistics, such as, min/max per column, etc. that allows to skip reading blocks inside Parquet that doesn't contain your data.  These filters will be shown as PushedFilters: [In(p, [1,2])].  But this may not be efficient if your data is inside min/max range, so Spark needs to read all blocks and filter on the Spark level.
P.S. Please take into account that Delta Lake format allows to access data more efficiently because of the data skipping, bloom filters, Z-ordering, etc.


text:
Q: Only showing the info window of second pin After I add info windows to my pin array, when I click on the second pin the infowindow pops up over the first pin. And when I click on the first pin the second pin's infowindow pops up.
This is the pin array:
function setMarkers(map) {
// Adds markers to the map.

var image = {
    url: 'http://localhost:8888/wp-content/plugins/wp_cat_map/assets/img/home_pin.png',
    size: new google.maps.Size(35, 42),
    origin: new google.maps.Point(0, 0),
    anchor: new google.maps.Point(0, 42)
};

var shape = {
    coords: [0, 0, 35, 42],
    type: 'rect'
};

for (var i = 0; i < thePins.length; i++) {

    var pin = thePins[i];

    var contentString = pin[0];

    var infowindow = new google.maps.InfoWindow({
        content: contentString,
        maxWidth: 200
    });

    var marker = new google.maps.Marker({
        position: {lat: pin[1], lng: pin[2]},
        map: map,
        icon: image,
        //shape: shape,
        title: pin[0],
        zIndex: pin[3]
    });

    marker.addListener('click', function() {
        infowindow.open(map, marker);
    });
}
}

A: Thanks to variable hoisting, all of those marker and infowindow references are to the same variable, whose declaration is basically moved up to the top of the containing function.
You either need to wrap the handler-creating in an anonymous function, or just move it to a separate, regular function.  e.g.
function addMarker(pin, map, image, contentString) {
  var infowindow = new google.maps.InfoWindow({
    content: contentString,
    maxWidth: 200
  });

  var marker = new google.maps.Marker({
    position: {lat: pin[1], lng: pin[2]},
    map: map,
    icon: image,
    title: pin[0],
    zIndex: pin[3]
  });

  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });
}

for (var i = 0; i < thePins.length; i++) {
  var pin = thePins[i];
  var contentString = pin[0];

  addMarker( pin, map, image, contentString);
}


text:
Q: XCode 4: adding parsekit library to project I'm using XCode 4.2 and I'm trying to add the parsekit library to my project, this is what I did:

*

*Drag the ParseKit.xcodeproj to my project in XCode as a Sub Project.

*Adding the libparsekit.a to the link binary with libraries list

*Trying to compile, everything still works.

Adding this to my code:
#import <ParseKit/ParseKit.h>

Then I've tried typing some code, and autocomplete works, so it must have found the library... But when I compile, I get this error:
'ParseKit/ParseKit.h' file not found

I also tried to replace the import with the following lines of code, but nothing worked, they all gave the same error...
#import "ParseKit/ParseKit.h"
#import "ParseKit.h"
#import <ParseKit.h>

Anyone got an idea on how to resolve this problem?
Here's a video on how I imported ParseKit into my project:
http://youtu.be/xjF8c2vo9vA

A: Developer of ParseKit here. Please checkout the instructions for ParseKit on iOS here:
http://parsekit.com/iphone.html
Although the instructions are from Xcode 3, I think you are missing steps 7 & 8.


text:
Q: Dimension of a infinite dimensional vector space I have a simple multiple choice I've been trying to understand here for a while now.

Suppose that $F$ is spanned by the functions $f_1,f_2,f_3,f_4$. What can we conclude about $\text{dim}(V)$?

a) $\text{dim}(V)=4$

b) $\text{dim}(V)\geq 4$, but we know nothing else

c) $\text{dim}(V)\leq 4$, but we know nothing else

d) We can conclude nothing about $\text{dim}(V)$

e) None of the above

NORMALLY I would say that the answer is $b)$ but that only holds for a finite dimensional vector space. I'm not sure if I can assume that $b$ is true if $F$ is infinite dimensional.
Can someone guide me on this? Thanks!

A: If $f_1,f_2,f_3,f_4$ are linearly independent, then $\{f_1,f_2,f_3,f_4\}$ is a basis of $F$, hence $\dim (V)=4.$
If $f_1,f_2,f_3,f_4$ are linearly dependent, then $ \dim(V) \le 3.$
The answer is c).


text:
Q: i am getting an error while running this sql statement using sql developer ,oracle CREATE TABLE ward
(
wardnumber int NOT NULL PRIMARY KEY,
type varchar(50),
name varchar(50),
numberofrooms int
);

CREATE TABLE Patient
(
patientid int NOT NULL PRIMARY KEY,
empssn int,
category varchar(50),
discount int,
firstname varchar(50),
lastname varchar(50),
address varchar(50),
city varchar(50),
birthdate date,
gender varchar(50),
age date,
cellnumber varchar(50),
bednumber int,
roomnumber int,
wardnumber int ,
diseaseid int,
 constraint fk_ward_number foreign key (wardnumber) references ward(wardnumber)on update cascade,
constraint fk_disease_id foreign key (diseaseid) references disease(diseaseid)
);

i get the following  error regarding the contraint with update cascade thingy , i have tried a lot but dient get fixed help

Error at Command Line : 19 Column : 83 Error report - SQL Error:
  ORA-00905: missing keyword
  00905. 00000 -  "missing keyword"

A: I think there is an issue with your  Primary Key.
the correct sentence is
CREATE TABLE table_name
(
  column1 datatype null/not null,
  column2 datatype null/not null,
  ...

  CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ... column_n)
);

A: "on update cascade,"  I don't think there's any such thing as UPDATE cascade .. there is a DELETE cascade .. but not UPDATE ... this is causing your error
http://docs.oracle.com/cd/E11882_01/server.112/e41084/clauses002.htm#CJAIHHGC


text:
Q: Problem with dragging mouse cursor with Python Could someone tell me why this doesn't work?
def selectAndCopy(x,y,z,w):
    ctypes.windll.user32.SetCursorPos(x,y)
    time.sleep(1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
    time.sleep(1)
    ctypes.windll.user32.SetCursorPos(z,w)
    time.sleep(1)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0)
    time.sleep(1)
    shell.SendKeys('^c')

the code isn't dragging to the first location to the second, it's only moving it.

A: Don't reinvent the wheel! There's the package pywinauto that has a ready-to-use function for this:
pywinauto.controls.HwndWrapper.DragMouse(button='left', pressed='',
                                         press_coords=(0, 0),
                                         release_coords=(0, 0))


text:
Q: Why does mypy generate different errors depending on running with `.` vs path to specific file? Versions:
Python 3.9.1
mypy==0.910

I'm unsure why mypy will output a different set of errors when run with mypy . vs running with mypy <path to file>
When running mypy . --strict --show-error-codes the result is different to doing mypy <path to file> --strict --show-error-codes.
For example, looking at code from https://github.com/raphaelvallat/pingouin (commit id ea8b560, file being used as an example here is: https://github.com/raphaelvallat/pingouin/blob/f40df480e137af8df35a3a3164d2d900b79091a6/pingouin/utils.py#L10).
Running :  mypy . --strict --show-error-codes  --exclude "./venv/" gives:
(venv) ➜  pingouin git:(master) ✗ mypy . --strict --show-error-codes  --exclude "./venv/" > mypy_all_files.txt
(venv) ➜  pingouin git:(master) ✗ grep "pingouin/utils.py" mypy_all_files.txt
pingouin/utils.py:3: error: Cannot find implementation or library stub for module named "numpy"  [import]
pingouin/utils.py:4: error: Cannot find implementation or library stub for module named "pandas"  [import]
pingouin/utils.py:7: error: Library stubs not installed for "tabulate" (or incompatible with Python 3.9)  [import]
pingouin/utils.py:7: note: Hint: "python3 -m pip install types-tabulate"
pingouin/utils.py:7: note: (or run "mypy --install-types" to install all missing stub packages)
pingouin/utils.py:440: error: Cannot find implementation or library stub for module named "statsmodels"  [import]
pingouin/utils.py:454: error: Cannot find implementation or library stub for module named "sklearn"  [import]
pingouin/utils.py:468: error: Cannot find implementation or library stub for module named "mpmath"  [import]

And running mypy ./pingouin/utils.py --strict --show-error-codes > mypy_single_file.txt gives:
(venv) ➜  pingouin git:(master) ✗ mypy ./pingouin/utils.py --strict --show-error-codes > mypy_single_file.txt
(venv) ➜  pingouin git:(master) ✗ grep "pingouin/utils.py" mypy_single_file.txt
pingouin/utils.py:3: error: Cannot find implementation or library stub for module named "numpy"  [import]
pingouin/utils.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
pingouin/utils.py:4: error: Cannot find implementation or library stub for module named "pandas"  [import]
pingouin/utils.py:7: error: Library stubs not installed for "tabulate" (or incompatible with Python 3.9)  [import]
pingouin/utils.py:7: note: Hint: "python3 -m pip install types-tabulate"
pingouin/utils.py:7: note: (or run "mypy --install-types" to install all missing stub packages)
pingouin/utils.py:16: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:54: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:78: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:113: error: Call to untyped function "_get_round_setting_for" in typed context  [no-untyped-call]
pingouin/utils.py:140: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:157: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:176: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:225: error: Call to untyped function "_remove_na_single" in typed context  [no-untyped-call]
pingouin/utils.py:227: error: Call to untyped function "_remove_na_single" in typed context  [no-untyped-call]
pingouin/utils.py:232: error: Call to untyped function "_remove_na_single" in typed context  [no-untyped-call]
pingouin/utils.py:235: error: Call to untyped function "_remove_na_single" in typed context  [no-untyped-call]
pingouin/utils.py:236: error: Call to untyped function "_remove_na_single" in typed context  [no-untyped-call]
pingouin/utils.py:260: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:303: error: Call to untyped function "_flatten_list" in typed context  [no-untyped-call]
pingouin/utils.py:341: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:379: error: Call to untyped function "_flatten_list" in typed context  [no-untyped-call]
pingouin/utils.py:382: error: Call to untyped function "_flatten_list" in typed context  [no-untyped-call]
pingouin/utils.py:390: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:399: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:437: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:440: error: Cannot find implementation or library stub for module named "statsmodels"  [import]
pingouin/utils.py:451: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:454: error: Cannot find implementation or library stub for module named "sklearn"  [import]
pingouin/utils.py:465: error: Function is missing a type annotation  [no-untyped-def]
pingouin/utils.py:468: error: Cannot find implementation or library stub for module named "mpmath"  [import]

The latter is what I'd be more interested in seeing, and would expect others to be also.
I'm not sure why there's a difference, and how to go about having the latter output as default.