text:
Q: Index correlation with Buffer Gets I have a questions that keep playing on my mind about the index relations with buffer gets on Oracle.

Is that true if I put on an Index and the buffer gets decreased then the Index is considered as worked well?
And is it also true that Index could also increase buffer gets and that considered as Index is not suitable for that query?

I really need an explanation for this questions.  Thanks in advance! :)

A: An index is added to provide better access paths to data in tables, and/or to police a unique constraint.
Buffer gets is just a measure of how many blocks Oracle had to read in order to service a query. It might read each buffer from the buffer cache, or if not found, from disk.
Since most of the time taken by queries, generally, is in reading blocks (whether from the buffer cache or from disk), I'd expect that improving a query by giving it a better access path (e.g. by adding an index) should reduce the number of buffers required, rather than increase them.


text:
Q: Custom View Extending Relative Layout package com.binod.customviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.RelativeLayout;

public class CustomView extends RelativeLayout{

    public CustomView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

//      LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater mInflater = LayoutInflater.from(context);
        mInflater.inflate(R.layout.custom_view  , this, true);
    }

}

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

    <com.binod.customviewtest.CustomView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ></com.binod.customviewtest.CustomView>

</RelativeLayout>

Custom View as
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

Just started adding a new custom view and got the error once If I clear this then can move forward
I am getting crash "Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class"

A: You need to have 2 more constructors. To know why
Do I need all three constructors for an Android custom view?
public class CustomView extends RelativeLayout{

    LayoutInflater mInflater;
    public CustomView(Context context) {
        super(context);
         mInflater = LayoutInflater.from(context);
         init();

    }
    public CustomView(Context context, AttributeSet attrs, int defStyle)
    {
    super(context, attrs, defStyle);
    mInflater = LayoutInflater.from(context);
    init();
    }
    public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mInflater = LayoutInflater.from(context);
    init();
    }
   public void init()
   {
       View v = mInflater.inflate(R.layout.custom_view, this, true);
       TextView tv = (TextView) v.findViewById(R.id.textView1);
   tv.setText(" Custom RelativeLayout");
   }
}

I am posting an example. My packagename is different
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<com.example.testall.CustomView
        android:id="@+id/timer1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</RelativeLayout>

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="My Custom View" />

</RelativeLayout>

MainActivity.java
public class MainActivity extends Activity {

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

Snap

As pskink suggested there in a RelativeLayout in activity_main.xml with a child CustomView. Then CustomView extends RealtiveLayout and then again you inflate a customview with RelativeLayout and a child TextView. No need for all these. Just a CustomView. Have a TextView created programatically and then add textview to RelativeLayout
Edit:
activity_main.xml
<com.example.testall.CustomView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/timer1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

CustomView
public class CustomView extends RelativeLayout{

    TextView tv;
    public CustomView(Context context) {
        super(context);
         tv = new TextView(context);
         init();

    }
    public CustomView(Context context, AttributeSet attrs, int defStyle)
    {
    super(context, attrs, defStyle);
    tv = new TextView(context);
    init();
    }
    public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    tv = new TextView(context);
    init();
    }
   public void init()
   {
       this.addView(tv);
       tv.setText(" Custom RelativeLayout");
   }
}

A: Try to get Activity and use this
 {
    LayoutInflater inflter = activity.getLayoutInflater();
    View v = inflter.inflate(R.layout.custom_view,null);
    this.addView(v); or addView(v);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is "total" in the output of "ls" command? I have an empty directory. I am using following command to view the contents of that directory.
ls -lart

The output I get is below.
total 12
drwxr-xr-x 5 root  root  4096 Oct  2 12:26 ..
drwxr-xr-x 2 apx   aim   4096 Nov 29 18:40 .

I don't have any files in this directory, then what counts out to 12 here (total 12)?

A: The "total" is the disk usage of listed files (because of -a including the  . and .. entries) in blocks (1024 bytes or if POSIXLY_CORRECT is set in 512 bytes), not including the content of subdirectories.
If same files are not referenced and therefore listed twice (hard-links), you can get the same output with
du -Ss

or in human readable units
du -Ssh

A: That is the total number of blocks taken up by the files, although I would expect the total to be 8 instead of 12 (using 1k blocks).  Try ls -as1 to see the size in blocks of each file.

A: total count of blocks, it includes also indirect blocks.


text:
Q: How Call for a BAT script in UNC folder and avoid Win32Exception (0x80004005): The operation was canceled by the user I use VS 2017 Community, Windows Forms app, and I try call to BAT script (in UNC folder):
Process.Start(@"\\sharefolder\editHosts.bat");

Sometimes I get the error:

ComponentModel.Win32Exception (0x80004005): The operation was canceled by the user
  at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
  at System.Diagnostics.Process.Start()

I have already checked the following things:

*

*The folder exists

*The user has rights to the folder (can open it in Explorer)

Any suggestions?


text:
Q: Print output of httpie command, then pipe to grep how can I print output of httpie request then pipe to grep to check if request has succeeded or failed?
http --print=hb POST http://localhost:8080 | grep -c "HTTP/1.1 200" && echo "succeeded" && exit 0 || echo "failed" && exit 1
I tried to use xargs with
http://localhost:8080 | xargs sh -c 'response=$1' sh | grep ...
but that didn't work, any idea

A: tee is the standard utility for sending a copy of stdin elsewhere.
>() is a bash construct that passes stdin into an arbitrary commmand.  Normally, we just pipe, '|' directly, but in our case where we want to send a copy of stdin on unaltered, this feature has some usage here.
Combine them, like so:
$ command1 | tee >( command2) | command3

command2 and command3 see the same thing
For your use case, try:
$ http --print=h http://www.google.com | tee >( grep -c "HTTP/1.1 200" >/dev/null && echo "succeeded" > /dev/stderr || echo "failed" > /dev/stderr) | sed 's/^/# /'
# HTTP/1.1 200 OK
# Date: Thu, 26 May 2022 00:32:29 GMT
... elided ...
# Set-Cookie: NID=511=CEilmSmMThJIS-KWlutGVDxrE; expires=Fri, 25-Nov-2022 00:32:29 GMT; path=/; domain=.google.com; HttpOnly
#
succeeded

I have sed as command3 to illustrate the contents it gets through the pipe -- a complete copy of http(ie)'s output.
Be careful!  grep wants to write to stdout by default (as do our echoes).  Thus, in command2, I redirect grep's output to /dev/null, and the two echoes to /dev/error.  Without these, stdin is altered before sed begins its work.
Here's a snippet without command2's redirection:
$ http --print=h http://www.google.com | tee >( grep -c "HTTP/1.1 200" && echo "succeeded" || echo "failed") | sed 's/^/# /'
# HTTP/1.1 200 OK
# Date: Thu, 26 May 2022 00:35:01 GMT
... elided ...
# Set-Cookie: NID=511=L6sDnkpxBHQMA_L0JQCFqM; expires=Fri, 25-Nov-2022 00:35:01 GMT; path=/; domain=.google.com; HttpOnly
#
# 1
# succeeded

sed sees the grep -c count of one, and the echo succeeded -- it prepends '#'

A: I figured out a workaround
response=$(http --print=hb POST http://localhost:8080)
echo $response
echo $response | grep -c "HTTP/1.1 200" && echo "succeeded" || echo "failed")


text:
Q: Create associative array with numbers in php - merge 3 arrays I'm trying to create dropdown from associative array starting with:
`None` => `None`

after that numbers from 01 to 24 in format -> 01, 02, 03...10,11...24
and finally add:
`25+` => `25+`

Keys and values of dropdown should be the same.
I tried the following:
$format_numbers1 = array();
$format_numbers1['None'] = 'None';
for($i=1;$i<=9;$i++) {
$numbers[] = $i;
}

foreach($numbers as $number) {
$n = str_pad($number, 2, '0', STR_PAD_LEFT);
$format_numbers2[$n] = str_pad($number, 2, '0', STR_PAD_LEFT);
}
for($j=10;$j<=24;$j++) {
$format_numbers3[$j] = $j;
}
$format_numbers_new = array_merge($format_numbers1, $format_numbers2);
$format_numbers = array_merge($format_numbers_new, $format_numbers3);
$format_numbers['25+'] = '25+';

But I get this output:
array(26) { ["None"]=> string(4) "None" ["01"]=> string(2) "01" ["02"]=> string(2) "02" ["03"]=> string(2) "03" ["04"]=> string(2) "04" ["05"]=> string(2) "05" ["06"]=> string(2) "06" ["07"]=> string(2) "07" ["08"]=> string(2) "08" ["09"]=> string(2) "09" [0]=> int(10) [1]=> int(11) [2]=> int(12) [3]=> int(13) [4]=> int(14) [5]=> int(15) [6]=> int(16) [7]=> int(17) [8]=> int(18) [9]=> int(19) [10]=> int(20) [11]=> int(21) [12]=> int(22) [13]=> int(23) [14]=> int(24) ["25+"]=> string(3) "25+" }

Dropdown keys from 10 to 24 aren't correct.

A: The other answer points out that you are using integers and not strings so you lose the 0 prefix, so here is much shorter code for the entire array:
$numbers['None'] = 'None';
for($i=1;$i<=24;$i++) {
    $n = str_pad($i, 2, '0', STR_PAD_LEFT);
    $numbers[$n] = $n;
}
$numbers['25+'] = '25+';

A: For the range of 10..24 you're using integers as your keys, instead of strings:
for ($j = 10; $j <=24; $j++) {
    $format_numbers3["$j"] = "$j";
    # here ----------^--^----^--^
}

But frankly, you're over-complicating things. str_pad can handle values it doesn't need to pad, so you can handle all the numbers 1..24 in a single loop:
$format_numbers = array();
$format_numbers['None'] = 'None';
for ($i = 1 ;$i <= 24; $i++) {
    $n = str_pad($i, 2, '0', STR_PAD_LEFT);
    $format_numbers2[$n] = $n;
}
$format_numbers['25+'] = '25+';

A: Don't use array_merge, but the + operator:
$format_numbers = $format_numbers1 +  $format_numbers2 +  $format_numbers3;

Documentation on array_merge says:

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

This is something that the + operator does not do.


text:
Q: How can I send a userInfo dict using CFNotificationCenterGetDarwinNotifyCenter() I need to send an object using CFNotificationCenterGetDarwinNotifyCenter() however, I'm noticing that whenever I send a notification using
const void *tkeys[1] = { @"testKey" };
const void *tvalues[1] = { @"testValue" };
CFDictionaryRef userInfo = CFDictionaryCreate(NULL, tkeys, tvalues, 1, NULL, NULL);
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(),
                                       CFSTR("foo"),
                                       object,
                                       userInfo,
                                       true);

then I find that in the observer callback, the userInfo dict is NULL. Is there something I am missing here? Is there some other way by which I can possibly send the userInfo object? I was looking at http://nshipster.com/inter-process-communication/ and the Distributed Notifications part, however whenever I use :
CFNotificationCenterRef distributedCenter =
CFNotificationCenterGetDistributedCenter();

then I get an error Invalid Use of Function error whenever I try it.

A: If you read the documentation for CFNotificationCenterGetDarwinNotifyCenter, you'll find this caveat:

Several function parameters are ignored by Darwin notification
  centers. To ensure future compatibility, you should pass NULL or 0 for
  all ignored arguments.

userInfo is one of those parameters. CFNotificationCenter.h goes into more detail:
// For this center, there are limitations in the API. There are no notification "objects",
// "userInfo" cannot be passed in the notification, ...
// - CFNotificationCenterPostNotification(): the 'object', 'userInfo', and 'deliverImmediately' arguments are ignored.

Why? Dig a little deeper. The documentation also mentions that this type of notification center is built on the Core OS notify mechanism declared in notify.h. If you look that up, you'll find that there is only one way to post a notification, by calling notify_post(), which takes only a single string argument. There is no way to add additional data to the notification. This is a very old and rudimentary IPC mechanism that doesn't know anything about CoreFoundation data structures.
As for CFNotificationCenterGetDistributedCenter, that isn't available on iOS.


text:
Q: Compiling Fortran IV code with Fortran 77 compiler I have a code in Fortran IV that I need to run. I was told to try to compile it in Fortran 77 and fix the error. So I named the file with a .f extension and tried to compile it with gfortran. I got the next error referring to the Fortran IV function copied below:
abel.f:432.24:

      REAL FUNCTION DGDT*8(IX,NV,XNG,FNG,GNG,X)
                        1
Error: Expected formal argument list in function definition at (1)

Since I'm not too familiar with Fortran I'd appreciate if someone can tell me how to fix this problem .
      REAL FUNCTION DGDT*8(IX,NV,XNG,FNG,GNG,X)                         AAOK0429
C                                                                       AAOK0430
C     THIS SUBROUTINE COMPUTES THE VALUE OF THE DERIVATIVE OF THE       AAOK0431
C     G-FUNCTION FOR A SLIT TRANSMISSION FUNCTION GIVEN BY A            AAOK0432
C     PIECE-WISE CUBIC SPLINE , WHOSE PARAMETERS ARE                    AAOK0433
C     CONTAINED IN XNG,FNG AND GNG.                                     AAOK0434
C                                                                       AAOK0435
      IMPLICIT REAL*8(A-H,O-Z)                                          AAOK0436
C                                                                       AAOK0437
C     ALLOWABLE ROUNDING ERROR ON POINTS AT EXTREAMS OF KNOT RANGE      AAOK0438
C     IS 2**IEPS*MAX(!XNG(1)!,!XNG(NV)!).                               AAOK0439
      INTEGER*4 IFLG/0/,IEPS/-50/                                       AAOK0440
      DIMENSION XNG(1),FNG(1),GNG(1)                                    AAOK0441
C                                                                       AAOK0442
C       TEST WETHER POINT IN RANGE.                                     AAOK0443
      IF(X.LT.XNG(1)) GO TO 990                                         AAOK0444
      IF(X.GT.XNG(NV)) GO TO 991                                        AAOK0445
C                                                                       AAOK0446
C       ESTIMATE KNOT INTERVAL BY ASSUMING EQUALLY SPACED KNOTS.        AAOK0447
   12 J=DABS(X-XNG(1))/(XNG(NV)-XNG(1))*(NV-1)+1                        AAOK0448
C       ENSURE CASE X=XNG(NV) GIVES J=NV-1                              AAOK0449
      J=MIN0(J,NV-1)                                                    AAOK0450
C       INDICATE THAT KNOT INTERVAL INSIDE RANGE HAS BEEN USED.         AAOK0451
      IFLG=1                                                            AAOK0452
C       SEARCH FOR KNOT INTERVAL CONTAINING X.                          AAOK0453
      IF(X.LT.XNG(J)) GO TO 2                                           AAOK0454
C       LOOP TILL INTERVAL FOUND.                                       AAOK0455
    1 J=J+1                                                             AAOK0456
   11 IF(X.GT.XNG(J+1)) GO TO 1                                         AAOK0457
      GO TO 7                                                           AAOK0458
    2 J=J-1                                                             AAOK0459
      IF(X.LT.XNG(J)) GO TO 2                                           AAOK0460
C                                                                       AAOK0461
C       CALCULATE SPLINE PARAMETERS FOR JTH INTERVAL.                   AAOK0462
    7 H=XNG(J+1)-XNG(J)                                                 AAOK0463
      Q1=H*GNG(J)                                                       AAOK0464
      Q2=H*GNG(J+1)                                                     AAOK0465
      SS=FNG(J+1)-FNG(J)                                                AAOK0466
      B=3D0*SS-2D0*Q1-Q2                                                AAOK0467
      A=Q1+Q2-2D0*SS                                                    AAOK0468
C                                                                       AAOK0469
C       CALCULATE SPLINE VALUE.                                         AAOK0470
    8 Z=(X-XNG(J))/H                                                    AAOK0471
C     TF=((A*Z+B)*Z+Q1)*Z+FNG(J)                                        AAOK0472
C     TG=((3.*A*Z+2.*B)*Z+Q1)/H                                         AAOK0473
C     DGDT=(TG-TF/X)/X                                                  AAOK0474
      DGDT=(3.*A*Z*Z+2.*B*Z+Q1)/H                                       AAOK0475
      RETURN                                                            AAOK0476
C       TEST IF X WITHIN ROUNDING ERROR OF XNG(1).                      AAOK0477
  990 IF(X.LE.XNG(1)-2D0**IEPS*DMAX1(DABS(XNG(1)),DABS(XNG(NV)))) GO    AAOK0478
     1 TO 99                                                            AAOK0479
      J=1                                                               AAOK0480
      GO TO 7                                                           AAOK0481
C       TEST IF X WITHIN ROUNDING ERROR OF XNG(NV).                     AAOK0482
  991 IF(X.GE.XNG(NV)+2D0**IEPS*DMAX1(DABS(XNG(1)),DABS(XNG(NV)))) GO   AAOK0483
     1 TO 99                                                            AAOK0484
      J=NV-1                                                            AAOK0485
      GO TO 7                                                           AAOK0486
   99 IFLG=0                                                            AAOK0487
C       FUNCTION VALUE SET TO ZERO FOR POINTS OUTSIDE THE RANGE.        AAOK0488
      DGDT=0D0                                                          AAOK0489
      RETURN                                                            AAOK0490
      END                                                               AAOK0491

A: This doesn't look so bad. Modern compilers still accept the real*8 syntax although it isn't standard. So you should (as mentioned) replace the line
  REAL FUNCTION DGDT*8(IX,NV,XNG,FNG,GNG,X)                         AAOK0429

with
  REAL*8 FUNCTION DGDT(IX,NV,XNG,FNG,GNG,X)                         AAOK0429

which compiled successfully for me using gfortran 4.6.2 using gfortran -c DGDT.f.
Good luck, and be on the lookout for other problems. Just because the code compiles does not mean it is running the same way it was designed!

A: Not really an answer, see the one from Ross. But I just can't stand the requirement for fixed form. Here is how this code probably would look like in F90 with free form:
function DGDT(IX, NV, XNG, FNG, GNG, X)
  !  THIS FUNCTION COMPUTES THE VALUE OF THE DERIVATIVE OF THE
  !  G-FUNCTION FOR A SLIT TRANSMISSION FUNCTION GIVEN BY A
  !  PIECE-WISE CUBIC SPLINE, WHOSE PARAMETERS ARE
  !  CONTAINED IN XNG,FNG AND GNG.

  implicit none

  integer, parameter :: rk = selected_real_kind(15)

  integer :: ix, nv
  real(kind=rk) :: dgdt
  real(kind=rk) :: xng(nv)
  real(kind=rk) :: fng(nv)
  real(kind=rk) :: gng(nv)
  real(kind=rk) :: x

  ! ALLOWABLE ROUNDING ERROR ON POINTS AT EXTREAMS OF KNOT RANGE
  ! IS 2**IEPS*MAX(!XNG(1)!,!XNG(NV)!).
  integer, parameter :: ieps = -50
  integer, save :: iflg = 0
  integer :: j

  real(kind=rk) :: tolerance
  real(kind=rk) :: H
  real(kind=rk) :: A, B
  real(kind=rk) :: Q1, Q2
  real(kind=rk) :: SS
  real(kind=rk) :: Z

  tolerance = 2.0_rk**IEPS * MAXVAL(ABS(XNG([1,NV])))

  ! TEST WETHER POINT IN RANGE.
  if ((X < XNG(1) - tolerance) .or. (X > XNG(NV) + tolerance)) then
    ! FUNCTION VALUE SET TO ZERO FOR POINTS OUTSIDE THE RANGE.
    iflg = 0
    DGDT = 0.0_rk
    return
  end if

  ! ESTIMATE KNOT INTERVAL BY ASSUMING EQUALLY SPACED KNOTS.
  J = abs(x-xng(1)) / (xng(nv)-xng(1)) * (nv-1) + 1

  ! ENSURE CASE X=XNG(NV) GIVES J=NV-1
  J = MIN(J,NV-1)

  ! INDICATE THAT KNOT INTERVAL INSIDE RANGE HAS BEEN USED.
  IFLG = 1

  ! SEARCH FOR KNOT INTERVAL CONTAINING X.
  do
    if ( (x >= xng(j)) .or. (j==1) ) EXIT
    j = j-1
    ! LOOP TILL INTERVAL FOUND.
  end do
  do
    if ( (x <= xng(j+1)) .or. (j==nv-1) ) EXIT
    j = j+1
    ! LOOP TILL INTERVAL FOUND.
  end do

  ! CALCULATE SPLINE PARAMETERS FOR JTH INTERVAL.
  H = XNG(J+1) - XNG(J)
  Q1 = H*GNG(J)
  Q2 = H*GNG(J+1)
  SS = FNG(J+1) - FNG(J)
  B = 3.0_rk*SS - 2.0_rk*Q1 - Q2
  A = Q1 + Q2 - 2.0_rk*SS

  ! CALCULATE SPLINE VALUE.
  Z = (X-XNG(J))/H
  DGDT = ( (3.0_rk*A*Z + 2.0_rk*B)*Z + Q1 ) / H

end function DGDT

Note, I did not test this in any way, also there might be some wrong guesses in there, like that ieps should be a constant. Also, I am not so sure about iflg, and the ix argument does not appear to be used at all. So I might got something wrong. For the tolerance it is better to use a factor instead of a difference and a 2.**-50 will not change the value for a the maxval in a double precision number here. Also note, I am using some other F90 features besides the free form now.

A: DISCLAIMER: Just mentioning a possible solution here, not recommending it...
As much as all other answers are valid and that supporting some Fortran IV code as is is a nightmare, you still might want / need to avoid touching it as much as possible. And since Fortran IV had some strange behaviours when it comes to loops for example (with loops always cycled at least once IINM), using a "proper" Fortran IV compiler might be a "good" idea.
Anyway, all this to say that the Intel compiler for example, supports Fortran IV natively with the -f66 compiler switch, and I'm sure other compilers do as well. This may be worth checking.


text:
Q: How to use grooupby properly with previous filter I have a dataframe looks like this
       Seats  Saw_Flop WTSD WMSD WWSF
0  _M3M3N7O_         0   No   No   No
1   aladin03         0   No   No  Yes
2   aladin03         1   No   No  Yes
3   aladin03         0   No   No   No
4   aladin03         0   No   No   No
5   aladin03         0   No   No   No
6   aladin03         1   No   No   No
7  kingbel81         0   No   No   No
8  kingbel81         1   No   No   No
9  kingbel81         1   No   No  Yes

What i want to do is groupby seats and calculate when Yes appear in columns WMSD, WWSF and WTSD but only for rows where Saw_Flop == 1.
What i have done is:
dfWTSD = df2[df2['Saw_Flop'] == 1].groupby('Seats').WTSD.value_counts().groupby(level=0).apply(lambda x: x/x.sum()*100).loc(axis=0)[slice(None), 'Yes'].reset_index(drop=True, level=1).reset_index(name = 'WTSD%')
dfWWSF = df2[df2['Saw_Flop'] == 1].groupby('Seats').WWSF.value_counts().groupby(level=0).apply(lambda x: x/x.sum()*100).loc(axis=0)[slice(None), 'Yes'].reset_index(drop=True, level=1).reset_index(name = 'WWSF%')
dfWMSD = df2[df2['Saw_Flop'] == 1].groupby('Seats').WMSD.value_counts().groupby(level=0).apply(lambda x: x/x.sum()*100).loc(axis=0)[slice(None), 'Yes'].reset_index(drop=True, level=1).reset_index(name = 'WMSD%')

So first i filtered data for Saw_Flop == 1 and then groupby to calculate % of Yes appearing.
I dont know if my logic is correct because i recieved average % like 20 but should be around 40-45.
Can u tell me if my way to calculate this is correct and show another way to do groupby?

A: It looks like your solution working nice if need percentages from filtered rows only.
You can simplify it by compare valeus to mask and get mean:
mask = df2['Saw_Flop'] == 1
cols = ['WTSD','WMSD','WWSF']
df = df2.loc[mask, cols].eq('Yes').groupby(df2['Seats']).mean().mul(100).add_suffix('%')
print (df)
           WTSD%  WMSD%  WWSF%
Seats
aladin03     0.0    0.0   50.0
kingbel81    0.0    0.0   50.0

Detail:
print (df2.loc[mask, cols].eq('Yes'))
    WTSD   WMSD   WWSF
2  False  False   True
6  False  False  False
8  False  False  False
9  False  False   True

But if need to count how many filtered values from all values of columns:
m1 = df2['Saw_Flop'] == 1
cols = ['WTSD','WMSD','WWSF']
m2 = df2[cols] == 'Yes'

mask = m2.mul(m1, axis=0)
df = mask.groupby(df2['Seats']).mean().mul(100).add_suffix('%')
print (df)
           WTSD%  WMSD%      WWSF%
Seats
_M3M3N7O_    0.0    0.0   0.000000
aladin03     0.0    0.0  16.666667
kingbel81    0.0    0.0  33.333333

Detail:
print (mask)
    WTSD   WMSD   WWSF
0  False  False  False
1  False  False  False
2  False  False   True
3  False  False  False
4  False  False  False
5  False  False  False
6  False  False  False
7  False  False  False
8  False  False  False
9  False  False   True


text:
Q: Structure theorem for non-Noetherian local rings Is there a structure theorem (like Cohen 's structure theorem) for non-Noetherian local rings?
I am adding what I am looking for as someone asked in the comment.
If $R$ is a local domain (not necessarily complete) containing a field $k$ , then I am looking for something like that there exist $S=k[[x_1,x_2, \ldots, ..]]$  (infinitely many variables if  $R$ has infinite Krull dimension ) such that $ S \subset R$ and $R$ is finitely generated as a module over $S$?

A: Here is a paper by Nagata that provides an answer for rings satisfying Krull's intersection theorem.


text:
Q: Crank-Nickolson I have these two equation
$$
\frac{\partial q(t,x)}{\partial t} =
\frac{\partial^2 q(t,x)}{\partial x^2}
- \frac{L_1 a(t, x) q(t, x)}{1 + \frac{L_2}{L} (1 - q(t,x))}\\
\frac{\partial a(t,x)}{\partial t} =
\frac{\partial^2 a(t,x)}{\partial x^2}
- \frac{L_1 a(t, x) q(t, x)}{1 + \frac{L_2}{L} (1 - q(t,x))}\\
$$
with boundary condition
$$
q\big|_{t=0} = 0, \quad
a\big|_{t=0} = y, \quad
q\big|_{t>=0, x-> infinity} = 0, \quad
a\big|_{t>=0, x-> infinity} = y, \quad
da/dx\big|_{x=0} = 0, \quad
q\big|_{x=0} = \frac{1}{1 + \exp(f - g t)},
$$
and $f,g,L_1,L_2,L$ are all constants.
I need to know what is $\frac{\partial q(t,x)}{\partial x}$ at $x=0$.
I think I need to use Crank-Nickolson but don't know how. The info on the website wasn't enough. :(
I'd really appreciate if you help me.
Thanks a lot.


text:
Q: Is it possible to convert my web API to an OData API? Context:
I have an existing Web API of the following form:
http://site/api/{area}?slicer1=alpha&slicer1=beta&starttime=sometime&endtime=sometime
It's implemented in ASP MVC. The API's function processes the parameters and feeds them into a SQL query. On success, it returns a IHttpActionResult with JSON data from SQL.
Note that the API lacks an entity model or entity relationship diagram. It's essentially just a wrapper around a SQL query.
Question:
Recently, I started learning about OData. It seems like OData is designed for the URL itself to control how data is filtered, as opposed to authoring a custom SQL query to filter.
Hence, I'd like an answer on whether my Web API could be converted to an OData API and, if so, what OData capabilities I'd need to do that (for instance, might OData v4 functions be useful)?
Clarifications:

*

*I don't have any code written, nor am I asking for code as an answer.

*I am looking to know what OData capabilities might enable my scenario (v4 functions, actions, etc...), or if OData and Web APIs are so different that my ask doesn't make sense.

*Anticipating the "Why are you asking" this questions - I'm just interested in technically feasibility as a learning exercise.

A: You could switch to a OData API but if you have no entities, i.e. no IQueryable to query, you'd still have to do the SQL command generation by yourself. It's not too hard though - we did it in the project I'm working in.
You also have to ask yourself to what extent you want to switch to OData. For example, you could decide to just use its (type-safe) query-string parsing capabilities and from the parsed filter tree generate your own SQL (as mentioned above).
On the other hand, having a fully fledged OData API would also dictate the response format to comply to the standard. This would mean that you can start connecting to your API using OData aware tools (e.g. Excel, KendoUI Grid, etc.). I don't know if that would give you any benefit for your use-case.
Your question

what OData capabilities I'd need to do that

is not exactly clear to me. There are no OData capabilities that would help you to migrate from a Web API to an OData API. OData is just a set of standardized query (CRUD) and response formats. You can also be OData compliant by implementing all on your own using out-of-the-box Web API facilities but probably you'd want to use the Web API OData package.
The most important question for you is to ask yourself what advantage you'd have using OData.


text:
Q: Cannot get mappings to work I have the following directory structure:
| SITES_FOLDER

    |___ WEBSITE1

        |___ WEBSITE_CFC

    |___ CFC_DIR

WEBSITE1 contains an Application.cfc and some pages. Then I have a component ShoppingCart.cfc inside the WEBSITE_CFC directory that is instantiated on session start using this code:
createObject("component","WEBSITE_CFC.ShoppingCart").Init() />

This works.
Now I move ShoppingCart.cfc to the CFC_DIR directory and change my instantiate code to:
createObject("component","CFC_DIR.ShoppingCart").Init() />

Obviously this does not work because ColdFusion searches for a "CFC_DIR" directory under the root directory "WEBSITE1" and doesn't find it.
I thought this problem would be solved by using mappings so I go to the CFIDE administrator. Server Settings > Mappings.
Logical path: "CFC_DIR"

Directory path: "C:\some\folders\SITES_FOLDER\CFC_DIR"

No luck. So then I tried in Application.cfc:
<cfset THIS.mappings["/CFC_DIR"] = "C:\some\folders\SITES_FOLDER\CFC_DIR" />

This did not work either!
EDIT:
Maybe I understand: if I try to create the CFC from a cfm template, it works.
The error comes up when I try to create it inside the OnSessionStart Application.cfc's method:

Ensure that the name is correct and that the component or interface
  exists. Message    Could not find the ColdFusion component or interface
  C:\some\folders\SITES_FOLDER\WEBSITE1|WEBSITE_CFC\ShoppingCart.cfc.

In other words, it keeps looking for it in the wrong dir.
WHY?

A: If you're changing the file to /CFC_DIR but it's still using /WEBSITE_CFC it sounds like the cache needs clearing.
Clear the Cache in CF Admin
Clearing the cache can be done manually in the ColdFusion Administrator. After login, the third item in "Server Settings" is "Caching". Scroll to the bottom of the page for buttons to clear the cache.
For development purposes you may want to consider disabling the various caching options on this page entirely - they can be useful for performance improvement on live servers, but are generally an unnecessary hindrance on your development machine.
Clear the Cache Programmatically
If you have an automated deployment, you don't want to have to login to the CF Admin on remote servers and press buttons. Fortunately, you can also clear the cache programmatically:
<cfscript>
    createObject("Component", "cfide.adminapi.administrator")
        .login("**replace with admin password**");

    RuntimeService = createObject("component", "cfide.adminapi.runtime");

    // Clear whole cache:
    RuntimeService.clearTrustedCache();

    // Clear cache for individual files:
    RuntimeService.clearTrustedCache("/path/to/file1.cfm,/path/to/file2.cfm");

    // Clear component cache:
    RuntimeService.clearComponentCache();
</cfscript>

(Code adapted from Charlie's blog entry.)
The API for the Admin Runtime component can be found at http://www.cfexecute.com/admin-api-documentation/runtime-cfc/


text:
Q: logger.debug functionality in c++ Is there any logging functionality in c++ which can be enabled by setting debug=True or something like that to print debug messages to stdout ?

A: The usual trick goes like this:
void writeLog(const char* message); // Define elsewhere to do your logging

#ifdef DEBUG
#define Log(x) writeLog(x)
#else
#define Log(x)
#endif

// Somewhere in your main code
Log("This message is only seen if DEBUG is defined at compilation");

A: Not automatically. But you can define your own methods selectively.
#ifdef DEBUG
#define DEBUG_MSG(msg) debug(msg)
#else
#define DEBUG_MSG(msg)
#endif


text:
Q: Dagger 2 generated files are unreachable I perform the first use of Dagger 2 in my life and I think I encounter some issues that are considered insignificant by expirienced users and thus omitted in their guides.
So I created a simple absolutely empty class that does nothing, marked its constructor with @Inject, then created an interface with @Component annotation with method return type of which is my empty class. Then I invoked gradlew build and Dagger actually generated files that it must have generated. But these files are in build/generated/source/apt/main/com/warden/bot/ directory of my IDEA project whilst source code is in src/main/java/com/warden/bot/ directory of the project, so I can't use Dagger generated code in my program. Should there be a special setup for Dagger before use and what do I do now?
UPD
My build.gradle file is:
plugins {
    id "net.ltgt.apt" version "0.12"
}

version '2.0'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.dagger:dagger:2.11'
    apt 'com.google.dagger:dagger-compiler:2.11'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

jar {
    manifest {
        attributes(
            'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
            'Main-Class': 'com.warden.bot.Main'
    )
}
    from {
        configurations.compile.collect { it.isDirectory() ? it : zipTree(it)     }
    }
}


text:
Q: An error occurred while processing the post-install hook of the Podfile Tengo problemas con mi app en iOS, estoy trabajando con Flutter 2.2.2 pero al momento de ejecutarla me sale este error Consistency issue: build setting IPHONEOS_DEPLOYMENT_TARGEThas multiple values:{"Release"=>"14.0", "Debug"=>"8.0", "Profile"=>"8.0"}``
En XCode modifiqué mi deployment target a iOS 14.0 en Release, Debug y Profile pero aún así me sale el mismo error, también modifiqué mi podfile, descomentando la linea principal del target ios a 14.0, hay algo que me falte modificar porque no encuentro solución en ninguna parte. Si sirve de algo estoy utilizando pod en la versión 1.11.3
Este es mi podfile modificado
# Uncomment this line to define a global platform for your project
 platform :ios, '14.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!
pod 'Firebase'
pod 'Firebase/Auth'
pod 'Firebase/Analytics'
pod 'Firebase/Messaging'
pod 'Firebase/Core'
pod 'Firebase/Crashlytics'
pod 'FBSDKLoginKit'
pod 'Branch'
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']='14.0'
    flutter_additional_ios_build_settings(target)
    end
  end
end
target 'OneSignalNotificationServiceExtension' do
  use_frameworks!
  pod 'OneSignalXCFramework', '>= 2.6.4', '< 4.0'
end


text:
Q: Filtering Characters from a String I need to make a function that takes two strings as imnput and returns a copy of str 1 with all characters from str2 removed.
First thing is to iterate over str1 with a for loop, then compare to str2, to accomplish subtraction I should create a 3rd string in which to store the output but I'm a little lost after that.
def filter_string(str1, str2):
    str3 = str1
    for character in str1:
       if character in str2:
           str3 = str1 - str2
    return str3

This is what I've been playing with but I don't understand how I should proceed.

A: Use replace:
def filter_string(str1, str2):
    for c in str2:
        str1 = str1.replace(c, '')
    return str1

Or a simple list comprehension:
''.join(c for c in str1 if c not in str2)

A: Just use str.translate():
In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'

From the documentation:

string.translate(s, table[, deletechars])

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

If -- for educational purposes -- you'd like to code it up yourself, you could use something like:
''.join(c for c in str1 if c not in str2)


text:
Q: Using API Keys: When and when not to use I am using JavaScript and I am not entirely sure what I am doing.
https://developers.google.com/youtube/v3/docs/search/list#http-request

*

*I was told that I had to use a key, but when I scroll down to the example, they are not using a key, why?

*When are you required/not required to use an API key?
Thank you.

A: *

*If you check out the GO and Java examples, they do make use of a key. For example, the GO example has:
...
const developerKey = "YOUR DEVELOPER KEY"

func main() {
    flag.Parse()

    client := &http.Client{
            Transport: &transport.APIKey{Key: developerKey},
}
...

You can see they provide a placeholder for your API key. The APPS examples don't make use of a key, likely because they expect a separate authentication script to run. For example, Google has an auth.js that is needed for JavaScript.

*Any time you send a request to an API, you will need to be authenticated in some way. This authentication lets the owner of the API properly limit how many requests are made against the API, what data is given, and what parts of the API are visible. Keys are just one way of authentication.


text:
Q: How can I have a trigger on the same table in multiple databases without modifying the DBs? I have a server with dozens of "child" databases that all have the same schema/structure.  I also have a controller DB which is totally different.  What I need to do, without creating triggers in each of the child databases, is to have a trigger on the same table in each child DB... like maybe have it reside in the controller DB?  Is something like this possible?  And if so, how?

A:
What I need to do, without creating triggers in each of the child databases, is to have a trigger on the same table in each child DB... like maybe have it reside in the controller DB? Is something like this possible?

No. A trigger is tightly coupled to the object it references, and therefore has to live inside the same schema, inside the same database.

*

*Perhaps you can have a central queue table in the controller DB, the triggers just insert their relevant data into that central table, and a background process comes around and applies whatever the trigger was supposed to do to the relevant database. This at least minimizes the business logic inside the triggers.

*If a central queue table doesn't make sense, then you should be able to mitigate most of the concern through automation / deployment. I once managed 100s of databases with identical schema / procedures / triggers, and deploying a change to all of them was not really any harder than deploying a single change to one of them.


text:
Q: React-Final-Form delays in taking input with render props in Field I am currently working on a react project. I am using react-final-form for fetching the data in the form. As I am using the material UI component to create the form I am creating the form somewhat like this.
Code
 <Form
     onSubmit={onSubmit}
     validate={validate}
     render={({ handleSubmit, values }) => (
         <form onSubmit={handleSubmit}>
              <FormControl variant="outlined" className={classes.formControl} key={fieldKey}>
                     <Field
                        name={field.fieldName}
                        render={({ input }) => (
                           <TextField
                             {...input}
                             className={classes.textField}
                             variant="outlined"
                             label={props.field.label}
                             placeholder={props.field.description}
                             required={props.field.isMandatory}
                             InputLabelProps={{
                               shrink: true,
                             }}
                          />
                      )}
                      type="text"
                   />
                 </FormControl>
             </form>
          )}
      />

Now as soon as I remove the input props from the render props it is working fine. but with the input props, it delays in taking input. Without input props, I could not fetch the value from the form.

Is there any way to resolve this time delay?
Thanks in advance.

A: If you want a simple field. Maybe you can pass on only essential props.
<TextField
  name={input.name}
  value={input.value}
  onChange={input.onChange}
/>

A: The solution to this is subscriptions.
The form is initially rendered on every action, react-final-form allows to handle subscription,
<Form subscription={{handeleSubmit: true}} ...> </Form>

We can do somewhat like this
There is a video link for this. Video
Hope you find this helpful


text:
Q: How to tell classes from interfaces in Roslyn's `BaseList`? I am using Roslyn to analyze C# code. One of the things I need to have is analyzing a class declaration node and get information about:

*

*Its base class

*Its implemented interfaces

I can get access to the class declaration node (type ClassDeclarationSyntax), and from there I can get access to the BaseList:
ClassDeclarationSyntax node = ...; // The class declaration
BaseListSyntax baseList = node.BaseList;

However baseList contains both interfaces and classes. I need ti distinguish classes from interfaces. How?
Do I need to use the SemanticModel?
I've searched Roslyn's Wiki and discovered that it is possible to access semantic information from my AST.
SyntaxTree programRoot = ...; // Getting the AST root
CSharpCompilation compilation = CSharpCompilation.Create("Program")
    .AddReferences(MetadataReference.CreateFromFile(
    typeof(object).Assembly.Location))
    .AddSyntaxTrees(programRoot);

But how to get those info from here?
Thanks

A: Yes.
The syntax tree just knows what words are where; it doesn't know anything about what an identifier refers to.
You need to get the SemanticModel from the compilation), then call GetSymbolInfo() on each identifier node in the list.  You can then cast the symbol to ITypeSymbol to find out about the type.


text:
Q: Every User Access Denied in Whole web application I access whole web application but while, I check Permission in every List message "Sorry, this site hasn't been shared with you."
I have Web application Primary admin/Full access rights
Tried Solution : I've already added myself through Application Mangement > Manage Applications > User Policy
Also, logged int the site as sharepointadmin and shared with myself

A: I would check to verify the following...

*

*You are a site collection administrator

*Your account has access to SQL as a DBO

*You are not in a user policy on the web application where you explicitly added the "Deny" permission level.

*Login with a a Service Account on the server and see if you can access it.

Also always make sure you are using IE and not Chrome for these types of troubleshooting.
It is possible for Farm level administrators to be locked out of a Site Collection if they are not given access.
I hope this helps :)


text:
Q: htaccess add query to the end of the link I need to know how to redirect
http://test.com/test.php to http://test.com/test.php?var=foo
& also if it's http://test.com/test.php?var=foo to be http://test.com/test.php?var=foo&var2=foo
If this will cause a loop just tell me how to achieve it and I am going to test
Thanks in advance

A: You can use these rules:
RewriteEngine On

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^([^.]+\.php)$ /$1?var=foo [L]

RewriteCond %{QUERY_STRING} (?:^|&)var=foo(?:&|$)
RewriteRule ^([^.]+\.php)$ /$1?var2=foo [L,QSA]


text:
Q: Magento 2 Category page toolbar showing wrong item count Magento version 2.4.5
Can anyone help to fix items count in category page toolbar if magento 2 catalog setting out of stock enabled?
If I disable to show out of stock on category page then item count working fine.
Out of stock setting -> Admin -> Store -> Config -> Catalog -> Inventory -> Out of stock -> Yes

A: To fix this, you need to override this magento file.
/vendor/magento/module-inventory-catalog/Plugin/Catalog/Block/ProductList/UpdateToolbarCount.php
Override in your extension di.xml
<type name="Magento\Catalog\Block\Product\ProductList\Toolbar"><plugin name="update_toolbar_count" disabled="true"/></type>


text:
Q: Check condition and return name of column for which the condition is fulfilled I have a dataframe that looks like this:
df_start <- data.frame(
  a = c(1, 1, 1, 1, 1),
  b = c(0, 1, 0, 0, 0),
  c = c(1, 0, 0, 0, 0),
  n = c(0, 0, 0, 1, 0))

I want to test the condition if any of the columns from df_start[,2:n] (where n shows the last column of the dataframe) are equal to df$a then create two new columns out of which the first one returns 1 if the condition is TRUE and 0 if it is not, and the other gives the name of the column for which the condition was TRUE.
I managed to create the first column like this:
library(dplyr)

# check condition
df_start <- df_start %>% mutate(cond = ifelse(a == b | a == c | a == n, 1, 0))

Even though I think I need a different approach since I may have different number of columns every time. So I need to test the condition for column a and all columns from the 2 to the last one but I also would need to know for which column the condition was fulfilled.
Desired output:
# desired output
df_end <- data.frame(a = c(1, 1, 1, 1, 1),
                     b = c(0, 1, 0, 0, 0),
                     c = c(1, 0, 0, 0, 0),
                     n = c(0, 0, 0, 1, 0),
                     cond = c(1,1,0,1,0),
                     col_name = c("c", "b", NA, "n", NA))

Is there a way to do this with dplyr maybe or base R ? Although any other solutions are appreciated.

A: Another base R solution:
m <- df_start[,1] == df_start[,2:4]

df_start$cond <- rowSums(m)
df_start$col_name[!!rowSums(m)] <- names(df_start[2:4])[max.col(m) * rowSums(m)]

which gives:

> df_start
  a b c n cond col_name
1 1 0 1 0    1        c
2 1 1 0 0    1        b
3 1 0 0 0    0     <NA>
4 1 0 0 1    1        n
5 1 0 0 0    0     <NA>

A: The following uses base R only.
Note that in order to create column cond there is no need for ifelse.
df_end <- df_start
df_end$cond <- with(df_start, as.integer(a == b | a == c | a == n))
df_end$col_name <- NA
inx <- apply(df_start[-1] == df_start[[1]], 1, function(x) min(which(x)) + 1)
is.na(inx) <- is.infinite(inx)
df_end$col_name <- names(df_start)[inx]

df_end
#  a b c n cond col_name
#1 1 0 1 0    1        c
#2 1 1 0 0    1        b
#3 1 0 0 0    0     <NA>
#4 1 0 0 1    1        n
#5 1 0 0 0    0     <NA>

A: You can try a tidyverse. I like to use gather and spread for such approaches.
library(tidyverse)
df_start %>%
  rownames_to_column() %>%
  gather(k, v, -a, -rowname) %>%
  group_by(rowname) %>%
  mutate(cond=ifelse(any(a==v), 1, 0)) %>%
  mutate(col_name=ifelse(cond==1, k[v==1], NA)) %>%
  ungroup() %>%
  spread(k, v) %>%
  select(-rowname)
# A tibble: 5 x 6
      a  cond col_name     b     c     n
  <dbl> <dbl> <chr>    <dbl> <dbl> <dbl>
1     1     1 c            0     1     0
2     1     1 b            1     0     0
3     1     0 NA           0     0     0
4     1     1 n            0     0     1
5     1     0 NA           0     0     0

Or without transforming a piping/apply-solution like
df_start %>%
  mutate(col_name=apply(.[-1], 1, function(x, y) y[x==1], colnames(.)[-1])) %>%
  mutate(cond=as.numeric(apply(.[-ncol(.)], 1, function(x) any(x[1] == x[-1]))))
  a b c n col_name cond
1 1 0 1 0        c    1
2 1 1 0 0        b    1
3 1 0 0 0             0
4 1 0 0 1        n    1
5 1 0 0 0             0

A: Great solution @Jimbou with tidyverse. For completion, you can arrange the outcome by changing the last line in Jimbous code with:
select(-c(rowname, cond, col_name), c(cond, col_name))


text:
Q: How are daemon processes started in Python? I want to start two daemon process in python like following code:
daemon_main = DaemonImplMain()
daemon_check = DaemonImplCheck()
pid = os.fork()
if pid:
    daemon_main.start()
else:
    daemon_check.start()

in this code , daemon_main is a http server with wsgi, daemon_check is a check process. But the daemon_main cannot accept request when i run this code.

A: Do DaemonImplMain and DaemonImplCheck inherit from threading.Thread? If so, then you can set the daemon to true before starting the threads.
For eg.
daemon_main.daemon = True
daemon_main.start()

Same goes for daemon_check


text:
Q: New version of app gives error "Storyboard doesn't contain a view controller with identifier" Closed
I have come across a problem that I can't seem to find the answer to. When I run my app as a fresh install everything works perfectly but if I first install the current version of my app that is on the App Store and then starts my new version of the app from Xcode on my device I get this error on startup.
What I've changed in the version I'm currently developing I've added a new initial view controller that is displayed while I load data from the server at startup and then show the view controller that was the initial view controller in the last version. In the last version this view controller, which is called BannerTabBarController, did not have a Storyboard ID and I guess that's what causing this problem but why? And most importantly how do I fix it without forcing my users to first uninstall my app before downloading the new version?
I have changed both the version and build of the app if that could have anything to do with this. Below you can see how I load my view controller from the storyboard and displays it.
Just to point it out again, the app works perfectly when running from a fresh install but not if I have the old version installed.
BannerTabBarController *tabBarController = (BannerTabBarController *) [[UIStoryboard storyboardWithName:@"MainStoryboard" instantiateViewControllerWithIdentifier:@"BannerTabBarController"];
self.window.rootViewController = tabBarController;

If anyone can help me with this I would really appreciate it. Thank you.


text:
Q: Definition of a quirky update Based on Itzik Ben-Gan's article in ITProToday

Microsoft's implementation follows the physical data independence
  principle, and therefore does not guarantee that you will get the data
  back from a query in any particular order unless you add an ORDER BY
  clause in the outer query. A similar violation of the principle is
  when people update data and the solution's correctness relies on the
  data being updated in clustered index order (do a Web search on
  "quirky update" to see what I mean).

I tried to find what a quirky update means but in vain.
I am looking for an example to understand the concept.

A: Here's an example of the "Quirky Update"
use tempdb
go
drop table if exists t
go
create table t(id int primary key, Amount int, RunningTotal int)

insert into t(id,Amount,RunningTotal) values (1,4,0),(2,2,0),(3,6,0)

declare @t int = 0

update t set @t = RunningTotal = @t + Amount

select * from t

outputs
id          Amount      RunningTotal
----------- ----------- ------------
1           4           4
2           2           6
3           6           12


text:
Q: javascript: setTimeout and clearTimeout issue I am trying to do polling via AJAX and want to clear the timeout after the AJAX call is successful. The problem is the timeout never clears and new AJAX requests keep on getting fired.
I looked up similar questions on SO, but they all suggest the problem to be a locally scoped variable. However, I am declaring the poll_xhr variable outside my function.

<script>
var poll_xhr = null;
(function poll() {
    poll_xhr = setTimeout(function () {
     $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'check-status/',
            success: function (data) {
                console.log(data);
                if(data === 'OK') {
                    clearTimeout(poll_xhr);
                    window.location.href = '../'
                }
            },
            complete: poll
        });
    }, 3000);
})();
</script>

A: This is what your code does:

*

*Start a timeout

*When the timeout expires: Send an HTTP request

*When the HTTP response arrives: Clear the timeout (too late, its already fired) and call poll which starts a new one.

Remove complete: poll and put poll() inside an if statement (where you currently have clearTimeout) if you want to make another request.

A: In order to check, put some alert inside data==='OK'. if it doesn't came means, there is data type mismatch. To resolve this try with data=='OK'.


text:
Q: How to get the io_context from a strand in Boost 1.68? I have a boost::asio::strand<boost::asio::io_context::executor_type> object and need to get its io_context. I thought that I could use get_io_context() but that has been deprecated. Then I thought that I could use context() but that one returns a boost::asio::execution_context.
I cannot see how I can convert this into an instance of io_context instead...
So, how can I get a strand's io_context in boost 1.68?

A: Call get_inner_executor on strand instance then context on executor:
#include <boost/asio.hpp>
int main() {
    boost::asio::io_context io;
    boost::asio::strand<boost::asio::io_context::executor_type> strand{io.get_executor()};

    boost::asio::io_context::executor_type executor = strand.get_inner_executor();
    boost::asio::io_context& refIO = executor.context();
}


text:
Q: my dataframe contains '/' in column name , How can i plot certain column values in that column name? i need to plot the state called 'kerala' in the column 'state/unionterritory' and 'confirmed' to create a lineplot.
so far I have written till
1sns.lineplot(x=my_data['state/unionterritory'],y=my_data['confirmed'])
[https://www.kaggle.com/essentialguy/exercise-final-project]
this is the dataframe.head() , see the column name

A: I assume you want to get a column state/unionterritory from your DataFrame and filter it so it contains only Kerala state:
my_data_kerala = my_data[my_data['state/unionterritory'] == 'Kerala']['state/unionterritory']


text:
Q: How to change Cluster Queue Manager status from running to inactive, and change from inactive to running As below display, I need to change the Cluster Queue Manager(not the queue manager) from INACTIVE to Running. And after it is changed to Running, what command should I use if I need to change it from Running to Inactive. Anyone can tell me the command on this? Thanks!
DISPLAY CLUSQMGR (PWRCSHK03) STATUS
     8 : DISPLAY CLUSQMGR (PWRCSHK03) STATUS
AMQ8441: Display Cluster Queue Manager details.
   CLUSQMGR(PWRCSHK03)                     CHANNEL(TO.PWRCSHK03.PHK02)
   CLUSTER(PHKCLUS02)                      STATUS(INACTIVE)
DISPLAY QMSTATUS
     9 : DISPLAY QMSTATUS
AMQ8705: Display Queue Manager Status Details.
   QMNAME(PWRCSHK03)                       STATUS(RUNNING)

A: The STATUS shown  on a CLUSQMGR is the status of the channel. So when you see STATUS(INACTIVE) this means that the channel isn't running.
The channel will start running automatically when it has messages to deliver - one of the benefits of clustering, but if you really want to start it up, assuming it is a CLUSSDR channel, you can use:-
START CHANNEL(TO.PWRCSHK03.PHK02)

If it is a CLUSRCVR then to see STATUS(RUNNING) you need to start one of the CLUSSDR channels on another queue manager in the cluster to connect to this queue manager's CLUSRCVR.


text:
Q: null pointer exception can't assign value in asynctask I know there are billions of the same question but I actually can't handle this one. Here's my code that causes the the problem:
public class CategoryActivity extends AppCompatActivity implements CategoryAdapter.CategoryAdapterClickHandler {
    @Override
    public void onClick(String name) {

    }

    RecyclerView recyclerView;
    CategoryAdapter mAdapter;
    ArrayList<String> items;

    static String catName;

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

        //get intent and extra text
        Intent intent = getIntent();
        catName = intent.getStringExtra("categoryName");
        Log.e("fwdf", catName);

        //execute categoryTask;
        new CategoryAsyncTask(){
            @Override
            protected void onPostExecute(ArrayList<String> categoryItems) {
                super.onPostExecute(categoryItems);
                items = categoryItems;
            }
        }.execute(catName);

        //initialize recyclerview and set it to its adapter
        recyclerView = (RecyclerView) findViewById(R.id.list);
        LinearLayoutManager layoutManager =
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        Log.e("fgjhkkl;",items.get(1));
        mAdapter = new CategoryAdapter(this, this, items, false);
        recyclerView.setAdapter(mAdapter);
    }
}

The error happened because items variable is null although the categoryItems isn't null and I assigned items to categryItems.

A: You are trying to use the items before the AsyncTask is done.
To solve (for example), move
recyclerView = (RecyclerView) findViewById(R.id.list);
LinearLayoutManager layoutManager =
        new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
mAdapter = new CategoryAdapter(this, this, items, false);
recyclerView.setAdapter(mAdapter);

to the end of the onPostExecute function


text:
Q: Parsing complex JSON with an array in flutter I want to parse a complex JSON API that consists of an array and it shows the following error. The API has the details of weather and I want to display the time and wave height in the console.
The error
E/flutter ( 5675): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

E/flutter ( 5675): #0      _JsonDemoState.getJsonData
package:bottom_nav/APISample/JsonParsing.dart:25
E/flutter ( 5675): <asynchronous suspension>
E/flutter ( 5675):

This is the json which I need to parse.
    {
    "hours": [
        {
            "time": "2021-03-23T00:00:00+00:00",
            "waveHeight": {
                "icon": 1.35,
                "meteo": 1.25,
                "noaa": 0.97,
                "sg": 1.25
            }
        },
        {
            "time": "2021-03-23T01:00:00+00:00",
            "waveHeight": {
                "icon": 1.36,
                "meteo": 1.26,
                "noaa": 0.97,
                "sg": 1.26
            }
        }
]
}

THis is the function which parses the json
void getJsonData() async {

    String url2 =
        'https://api.stormglass.io/v2/weather/point?lat=5.9774&lng=80.4288&params=waveHeight&start=2021-03-23&end=2021-03-24';

    String apiKey =
        'the API key';

    Response response = await get(Uri.parse(url2),
        headers: {HttpHeaders.authorizationHeader: apiKey});

    List data = jsonDecode(response.body);
    data.forEach((element) {
      Map obj = element;
      String hours = obj['hours'];
      Map wave = obj['waveHeight'];
      int icon = wave['icon'];
      print(icon);
    });
  }

A: Would you mind to try this
 var jsonData = jsonDecode(response.body);
    List data = jsonData["hours"];

    data.forEach((element) {
      Map obj = element;
      Map wave = obj['waveHeight'];
      double icon = wave['icon'];
      print(icon);
    });

A: JSON deserialization of response.body will return a Map not a List, hence an option is to access the value associated to the 'hours' key and cast it as a List of Map with key of type String and value of type dynamic.
final mapList = data['hours'] as List<Map<String, dynamic>>;

mapList.forEach((item) => print(item.values.last['icon']));


text:
Q: Puma .NET exception 'System.Runtime.InteropServices.COMException' Trying to recognise a set of images in a folder (using Puma .NET OCR library), the first image is recognised successfully, but after that I get an error:
An unhandled exception of type 'System.Runtime.InteropServices.COMException'
occurred in Puma.Net.dll

Additional information: <0x00000000>: ?????? ???.

I have a special class for recognition, and the error happens on this line:
Puma.Net.PumaPage inputFile = new Puma.Net.PumaPage(imagePath);

I found this link and this one, but they don't seem to help in my case.
Thank you

A: I found the answer by using 'using' statement
 using(Puma.Net.PumaPage inputFile = new Puma.Net.PumaPage(imagePath))
        {
        }


text:
Q: how to refer to resources created with for_each in terraform This is what I'm trying to do. I have 3 NAT gateways deployed into separate AZs. I am now trying to create 1 route table for my private subnets pointing to the NAT gateway. In terraform I have created the NAT Gateways using for_each. I am now trying to associate these NAT gateways with a private route table and getting an error because I created the NAT gateways using for_each. Essentially, I am trying to refer to resources created with for_each in a resource that I do not need to use "for_each." Below is the code and error message. Any advice would be appreciated.
resource "aws_route_table" "nat" {
  vpc_id = aws_vpc.main.id

  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.main[each.key].id
  }

  tags = {
    Name = "${var.vpc_tags}_PrivRT"
  }
}

resource "aws_eip" "main" {
  for_each = aws_subnet.public
  vpc      = true

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_nat_gateway" "main" {
  for_each      = aws_subnet.public
  subnet_id     = each.value.id
  allocation_id = aws_eip.main[each.key].id
}

resource "aws_subnet" "public" {
  for_each                = var.pub_subnet
  vpc_id                  = aws_vpc.main.id
  cidr_block              = cidrsubnet(aws_vpc.main.cidr_block, 8, each.value)
  availability_zone       = each.key
  map_public_ip_on_launch = true
  tags = {
    Name = "PubSub-${each.key}"
  }
}

Error
Error: Reference to "each" in context without for_each

on vpc.tf line 89, in resource "aws_route_table" "nat":
  89:     nat_gateway_id = aws_nat_gateway.main[each.key].id

The "each" object can be used only in "resource" blocks, and only when the
"for_each" argument is set.

A: The problem is that you are referencing each.key in the nat_gateway_id  property of the "aws_route_table" "nat" resource without a for_each anywhere in that resource or sub-block.
Add a for_each to that resource and that should do the trick:
Here is some sample code (untested):
resource "aws_route_table" "nat" {
  for_each = var.pub_subnet

  vpc_id = aws_vpc.main.id

  route {
      cidr_block     = "0.0.0.0/0"
      nat_gateway_id = aws_nat_gateway.main[each.key].id
  }
}


text:
Q: How to extract json objects into an external file? I have this small code example:
<script type="text/javascript">
    var texts = [{key:'key_1', value:'value_1'},
                 {key:'key_2', value:'value_2'},
                 {key:'key_3', value:'value_3'}];
</script>

I use a json array directly in my xhtml page by using the script tag. The json array "texts" is used by an another java script function in my xhtml page, but that is not important at the moment.
How can a extract this json array into an external file? Which library it must be used?
EDIT:
I use a java maven project and that should be include my external json file!
I tried this code but it doesn´t work:
<script type="text/javascript">
    var placeholderTexts = himjQuery(document).getJSON('placeholder.json');
</script>

A: You can use each loop in jQuery
Just try this
$.each(texts, function(key, value) {   }

A: please try the below.
var arraysel;
var json = { };

for(var i = 0, l = arraysel.length; i < l; i++) {
  json[arraysel= [i].id] = arraysel= [i].value;
}

A: After reading many times your question, I think what you want is this:

*

*Create a .js file, for example data.js, with your data... which is not a JSON-serialized object, but a real literal. Use pure JSON notation if you want.
var DATA = {"a":1, "b":2};

*Import that "script" wherever you want to use your data.
<script type="text/javascript" src="./data.js></script>

*Use this data from any place in your JS code, for instance:
console.log(DATA.a);

A: Please get JSON data from AJAX and evaluate response and store in variable
<script>
var placeholderTexts = new Object();
$(function(){
    $.get('placeholder.json', function(data){
              try{
                placeholderTexts  = jQuery.parseJSON(data);
                console.log(placeholderTexts)
             }catch(e){
              alert(e.toString());
             }
     });
});
</script>


text:
Q: Add DayDream (screen saver) for Android TV to exists Android project I'm trying to add Android TV support to an existing Android project I have, specifically adding Day Dream service to show a screen saver.
I've seems to add all the required things for the app to run on Android TV and I can even see my Dream Service under Screen Saver in settings but when I select it - it is not selected and under Screen saver, there is no name.
Any ideas what I've might be missing?

A: I've found a 3 years-old example for Android TV DayDream and in there was my missing piece: In the manifest, under the service description I had to add android:permission="android.permission.BIND_DREAM_SERVICE".
Full service XML piece:
    <service
        android:name=".bouncer.BouncerDreamService"
        android:exported="true"
        android:label="Bouncing Logo"
        android:permission="android.permission.BIND_DREAM_SERVICE">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.service.dreams.DreamService" />
        </intent-filter>
    </service>


text:
Q: Searching date columns in database having nvarchar data types I am trying to search for all the date columns that could reside in a database. The problem is there are many date columns that are of the data type nvarchar and the column names also don't hint that it is a date column.
The date stored in these columns could also be of any date format. I tried using isdate() but isdate does not recognize dd-mm-yyyy or dd/mm/yyyy or mmm-dd-yyyy (Jun-06-2014).
Is there a way to identify these columns?

A: I probably spent too much time on this, but I think I have an answer.  The following code, based on the three data formats you mentioned (and using some of the easy ones available to the CONVERT() function), will list out all the fields in the database that can be converted using those formats.
Couple of important notes here:
1) the query currently only checks columns with VARCHAR, NVARCHAR, CHAR, NCHAR, DATE, and DATETIME data types.
2) the query only checks for specific formats - the three you mentioned, anything SQL can handle implicitly, and the various format codes that can be passed to the CONVERT() function.  Any other special ones will have to be added manually, by copying the last chunk starting with BEGIN TRY and ending with END CATCH.  If you know of a format, Google can find you SQL code to use it, just add it in.
CREATE TABLE #ListOfColumnsToCheck
  (
    ListID INT IDENTITY(1,1),
    TableName VARCHAR(100),
    ColumnName VARCHAR(100)
  )

INSERT INTO #ListOfColumnsToCheck (TableName, ColumnName)
SELECT
    TABLE_NAME,
    COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN -- expand this list as necessary
  (
    'VARCHAR',
    'NVARCHAR',
    'CHAR',
    'NCHAR',
    'DATETIME',
    'DATE'
  )

CREATE TABLE #DateCheck (DateValue DATE)

CREATE TABLE #Results
  (
    TableName VARCHAR(100),
    ColumnName VARCHAR(100),
    ConvertsToDate BIT
  )

DECLARE @LoopCounter INT
DECLARE @LoopFinishNumber INT
DECLARE @CurrentTableName VARCHAR(100)
DECLARE @CurrentColumnName VARCHAR(100)

SET @LoopCounter = 1
SET @LoopFinishNumber = (SELECT MAX(ListID) FROM #ListOfColumnsToCheck)

WHILE @LoopCounter <= @LoopFinishNumber
  BEGIN

    SELECT @CurrentColumnName = ColumnName, @CurrentTableName = TableName
    FROM #ListOfColumnsToCheck
    WHERE ListID = @LoopCounter

    BEGIN TRY -- add additional date formats to these lists as you come across them
    EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1 ' + @CurrentColumnName + '
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

    INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
    VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
    PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',101)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',102)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',103)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',104)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',105)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',106)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',107)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',108)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',109)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',110)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',111)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',112)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',113)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1  CONVERT(DATETIME, '+@CurrentColumnName+',114)
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH

    -- start of code block (when copying/pasting, start here)
    BEGIN TRY
      EXEC('
        INSERT INTO #DateCheck (DateValue)
        SELECT TOP 1 REPLACE('+@CurrentColumnName+', ''-'', '' '')
        FROM ' + @CurrentTableName + '
        WHERE ' + @CurrentColumnName + ' IS NOT NULL')

      INSERT INTO #Results (TableName, ColumnName, ConvertsToDate)
      VALUES (@CurrentTableName, @CurrentColumnName, 1)
    END TRY
    BEGIN CATCH
      PRINT @CurrentTableName + '.' + @CurrentColumnName + ' is not a valid date'
      PRINT ERROR_MESSAGE()
    END CATCH
    -- end of code block (when copying/pasting, end here then change the SELECT TOP 1 statement to use the format)

    SET @LoopCounter = @LoopCounter + 1

  END

SELECT DISTINCT * FROM #Results

DROP TABLE #DateCheck
DROP TABLE #ListOfColumnsToCheck
DROP TABLE #Results


text:
Q: How do you filter/select a 's  by the contents of the option tag? I have found plenty of answers about how to extract the value of an <option> tag, or the contents of the tag itself, `content here'
However, I am wondering if there is a way to select an option by the text value of the <option>text here</option> - in this case, using text here as a matching term.
I am building a pretty simple form for internal use - that will effectively limit the number of options in a second dropdown based on the selection of the first dropdown. However, since this is part of a CMS, using the value attribute of the block is not going to be a reliable effort. I know that the spelling and the wording of the text parameter of the dropdown is important, and will be what I need it to be.
I know this is not a good practice - believe me I know that. However, right now this is something I need to get done quickly and with as little time invested in this as possible. Without reinventing or redoing all the logic for this decade-old tool, I would opt for this route.
So, is it possible to filter by the inner text of the tag? I KNOW you can extract it, but we want to filter so we can limit the options the user can select from.

    <select id="one">
        <option value="a">eh</option>
        <option value="b">bee</option>
    </select>

    <select id="two">
        <option value="m">emm</option>
        <option value="lw">lolwot</option>
        <option value="p">dinner</option>
    </select>

In this case, if they select 'b' from first drop down -- it will limit their selection to -only- lolwot on the second dropdown - removing emm and dinner.
Just to reiterate, I do not want to extract from a selected option. $('#two').find('option:selected').text() is not what I am looking for.

A: Yes, it's possible. Assuming that you want to keep the one having the inner text of lolwot, you can do the following:
[...document.getElementById("two").children].forEach((item) => {if (item.innerText !== "lolwot") item.remove()})

*

*we get the item by id and its children inside the square brackets

*we convert that to an array, so we have an array of children

*we iterate this array

*if the current item does not meet the criteria, we simply remove it

If you want to get the items to remove, then you can filter:
[...document.getElementById("two").children].filter((item) => (item.innerText !== "lolwot"))


text:
Q: How to call function by not clicking the button? I'm coding on Python 3.5 using PyQt5 GUI. A prototype of my project is an app that creates the matrix of texts and changes the color of each "cell", one by one. Now it happens with clicking button, which is connected with the function.
I need to call the function that changes BrowserText configuration without any user interaction with app. In other words, palettes should change color by themselves in concrete time intervals.
So, is there any method in QPushButton widget (or any inherited one), that, for instance, calls the function after not clicking it for some time period? If there isn't, can I call function automatically in some way?
The design class code looks like:
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def __init__(self):
        self.width = int(20)
        self.height = int(16)
        self.i = 0
        self.j = 0

    def setColor(self):
        if (self.i < self.height) and (self.j < self.width):
            self.texts[self.i][self.j].setStyleSheet("QTextBrowser {background-color:white}")
            if self.j == self.width - 1:
                self.j = -1
                self.i += 1
            self.j += 1
            self.texts[self.i][self.j].setStyleSheet("QTextBrowser {background-color:red}")

    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(40 * int(self.width), 40 * int(self.height) + 10)
        Dialog.setStyleSheet("QPushButton{\n"
                             "    width = 0px;\n"
                             "}")
        self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 40 * self.width, 40 * self.height))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")

        self.texts = [[QtWidgets.QTextBrowser(self.gridLayoutWidget) for j in range(self.width)] for i in
                      range(self.height)]
        for i in range(self.height):
            for j in range(self.width):
                self.texts[i][j] = QtWidgets.QTextBrowser(self.gridLayoutWidget)
                self.texts[i][j].setObjectName("text" + str(i) + str(j))
                self.gridLayout.addWidget(self.texts[i][j], i, j)

        self.pushButton = QtWidgets.QPushButton(self.gridLayoutWidget)
        self.gridLayout.addWidget(self.pushButton, self.height, 1, 1, self.width - 2)
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(lambda: self.setColor())

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

A: The QTimer class provides repetitive and single-shot timers.
The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout() signal to the appropriate slots, and call start(). From then on, it will emit the timeout() signal at constant intervals.
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Ui_Dialog(object):

    def __init__(self):
        self.width = int(20)
        self.height = int(16)
        self.i = 0
        self.j = 0

    """
    def setColor(self):
        if (self.i < self.height) and (self.j < self.width):
            self.texts[self.i][self.j].setStyleSheet("QTextBrowser {background-color:white}")
            if self.j == self.width - 1:
                self.j = -1
                self.i += 1
            self.j += 1
            self.texts[self.i][self.j].setStyleSheet("QTextBrowser {background-color:red}")
    """

    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(40 * int(self.width), 40 * int(self.height) + 10)
        Dialog.setStyleSheet("QPushButton{\n"
                             "    width = 0px;\n"
                             "}")
        self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(0, 0, 40 * self.width, 40 * self.height))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")

        self.texts = [[QtWidgets.QTextBrowser(self.gridLayoutWidget) for j in range(self.width)] for i in
                      range(self.height)]
        for i in range(self.height):
            for j in range(self.width):
                self.texts[i][j] = QtWidgets.QTextBrowser(self.gridLayoutWidget)
                self.texts[i][j].setObjectName("text" + str(i) + str(j))
                self.gridLayout.addWidget(self.texts[i][j], i, j)

        self.pushButton = QtWidgets.QPushButton("Button", self.gridLayoutWidget)
        self.gridLayout.addWidget(self.pushButton, self.height, 1, 1, self.width - 2)
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(lambda: self.setColor())

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

class Window(QWidget, Ui_Dialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.setupUi(self)

        self.width = int(20)
        self.height = int(16)
        self.i = 0
        self.j = 0

        self.timer = QtCore.QTimer(interval=1000)                 # <-------
        self.timer.timeout.connect(self.setColor)
        self.timer.start()

    def setColor(self):
        if (self.i < self.height) and (self.j < self.width):
            self.texts[self.i][self.j].setStyleSheet("QTextBrowser {background-color:white}")
            if self.j == self.width - 1:
                self.j = -1
                self.i += 1
            self.j += 1
            self.texts[self.i][self.j].setStyleSheet("QTextBrowser {background-color:red}")

if __name__ == "__main__":
    application = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setWindowTitle('How to call function by not clicking the button?')
    window.show()
    sys.exit(application.exec_())


text:
Q: How to pass parameter in multipart post request Servlet code
request.getparameter("fname") //I can't able to get value.

HTML code

    <title>File Uploading Form</title>

File Upload:

    Select a file to upload:

    <form action="UploadServlet" method="post"
                            enctype="multipart/form-data">
    <input type="text" name="fname" size="50" />
 <input type="file" name="file" size="50" />
 <input type="submit" value="Upload File" />
    </form>

My question is : How to pass fname parameter in multipart post request?

A: Short answer: you will find the fname in the Parts of the request.
Long answer: For multipart type requests, even the simple <input type="text"> field values are placed in parts. You will have to iterate over the Part objects returned by HttpServletRequest.getParts() and handle them according to their name property:
for( Part p : request.getParts() ) {
    if( "fname".equals(p.getName()) ) {
        ...
    }
    else if( "file".equals(p.getName()) ) {
        ...
    }
}

To complicate things further, the content of the part is available as InputStream - Part.getInputStream() - so you will have to do a little transforming stream → byte[] → String to get the value.

A: Link Each Programms
------------------------------------------------------

import java.sql.*;
import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import java.util.Hashtable;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ParameterParser;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Recent
 */
@WebServlet("/Recent")
@MultipartConfig
public class Recent extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Recent() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub
         Sample  s1=new Sample();
         final String UPLOAD_DIRECTORY = "/home/pradeep/Documents/pradeep/WebContent/Images";
         if(ServletFileUpload.isMultipartContent(request)){
                try {
         List<FileItem> multiparts = new
                            ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                    for(FileItem item : multiparts){
                        if(!item.isFormField())
                        {
                            String name = new File(item.getName()).getName();
                            item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                            String Path= "/home/pradeep/Documents/pradeep/WebContent/Images/" +name;

                          s1.connecting(Path);

                        }
                    }

                        request.setAttribute("message", "File Uploaded Successfully");
                } catch (Exception ex) {
                   request.setAttribute("message", "File Upload Failed due to " + ex);
                }

            }else{
                request.setAttribute("message",
                                     "Sorry this Servlet only handles file upload request");
            }

                request.getRequestDispatcher("/Result.jsp").forward(request, response);

    }

}
-------------------------------------------------------------------------------------------
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dbconnections.Connections;

public class Sample {
    Connections con=new Connections();

    public void connecting(String Path)
    {
        Connection conn=con.Connect();

        PreparedStatement pst;
        String query="INSERT INTO Student1 (Path) values (?)";
       try {

            pst=conn.prepareStatement(query);
            pst.setString(1,Path);
            pst.executeUpdate();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // TODO Auto-generated method stub
    }

}
-------------------------------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

 Choose File to Upload in Server

           <form action="Recent" method="post" enctype="multipart/form-data">

            <input type="file" name="file" />
            <input type="submit" value="upload" />
            </form>


text:
Q: Odd behavior in assembly procedure I am trying to increment the eax variable by 2 within a procedure followed by pushing the eax value onto the stack/passing the result to printf:
; nasm -f elf test.asm && gcc -m32 -o test test.o

section .text
global main
extern printf

add_by_2:
        add     eax, 2
        push    eax
        push    message
        call    printf
        add     esp, 8
        ret

main:
        mov     eax, 1
        call    add_by_2
        call    add_by_2
        call    add_by_2
        ret

message db "%d", 0xa, 3, 0

After the third call the eax variable is not incremented by 2.
stdout:
3
5
5

Expected stdout:
3
5
7

What is wrong with this code?
How do I correct the code to correctly increment eax by 2 even after the third call to add_by_2.
I am open to any method to increment the number stored in eax by two (even if I need to use other registers).


text:
Q: Limit useable host resources in Docker compose without swarm I simply want to limit the resources of some Docker containers in a docker-compose file. The reason is simple: There are multiple apps/services running on the host. So I want to avoid, that a single container can use e.g. all memory, which harms the other containers.
From the docs I learned, that this can be done using resources. But this is beyond deploy. So I have to write my docker-compose file like the following example:
  php:
    image: php:7-fpm
    restart: always
    volumes:
      - ./www:/www
    deploy:
      resources:
        limits:
          memory: 512M

This gave me the warning:

WARNING: Some services (php) use the 'deploy' key, which will be ignored. Compose does not support deploy configuration - use docker stack deploy to deploy to a swarm.

And that seems to be true: docker statsconfirms, the container is able to use all the ram from the host.
The documentation says:

Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.

But I don't need clustering. It seems that there is no other way to limit resources using a docker composer file. Why is it not possible to specify some kind of memorytag like the start-parameter in docker rundoes?
Example: docker run --memory=1g $imageName
This works perfectly for a single container. But I can't use this (at least without violating a clean separation of concerns), since I need to use two different containers.
Edit: Temp workaround
I found out, that I'm able to use mem_limit directly after downgrading from version 3 to version 2 (placing version: '2' on top). But we're currently on version 3.1, so this is not a long-time solution. And the docs say, that deploy.resources is the new replacement for v2 tags like mem_limit.
Someday, version 2 is deprecated. So resource management isn't possible any more with the latest versions, at least without having a swarm? Seems a worsening for me, can't belive this...

A: Since many Docker Compose users have complained about this incompatibility of compose v3 vs v2, the team has developed compatibility mode.
You can retain the same deploy structure that you provided and it will not be ignored, simply by adding the --compatibility flag to the docker-compose command (docker-compose --compatibility up), as explained here. I tested this with version 3.5 and verified with docker stats and can confirm that it works.

A: You can run the docker daemon in swarm mode on a single host. It will add extra un-needed features like the etcd service discovery but that's all behind the scene.
The Docker documentation has a "note" about it here https://docs.docker.com/engine/swarm/swarm-tutorial/#three-networked-host-machines