text:
Q: Overlapping notification and incoming ringer vibration I vibrate phone when RINGER_MODE_VIBRATE and RINGER_MODE_NORMAL and stop vibrate to answering call or cancelling call. But exactly at this point
foreground notification is working and notification vibration is overlapping incomingRinger notification. Therefore vibration is not working when startForeground(notification) function is working.
I have tried disable vibration for notification like this question : Disable vibration for a notification
but enableVibration(false) or setVibrate(new long[]{0L}) is not working.
All of them are not working at Oreo (android 8). Other all versions are working.
IncomingRinger:
    public class IncomingRinger {

    private static final String TAG = IncomingRinger.class.getSimpleName();

    private static final long[] VIBRATE_PATTERN = {0, 1000, 1000};

    private final Context context;
    private final Vibrator vibrator;
    private final AudioManager audioManager;

    public IncomingRinger(Context context) {
        this.context = context.getApplicationContext();
        this.vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

        start(!audioManager.isWiredHeadsetOn() && !audioManager.isBluetoothScoOn());
    }

    private void start(boolean speakerphone) {

        ringerMode = audioManager.getRingerMode();

        switch (ringerMode) {

            case AudioManager.RINGER_MODE_SILENT:
                stop();
                break;

            case AudioManager.RINGER_MODE_VIBRATE:
            case AudioManager.RINGER_MODE_NORMAL:

                vibrate();
                break;

            default:
                audioManager.setSpeakerphoneOn(false);
                break;
        }

    }

    private void vibrate() {
        if (shouldVibrate()) {
            vibrator.vibrate(VIBRATE_PATTERN, 1);
        }
    }

    public void stop() {
        audioManager.setSpeakerphoneOn(false);
        cancelVibrator();
    }

    public void cancelVibrator() {
        vibrator.cancel();
    }

    private boolean shouldVibrate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return shouldVibrateNew();
        } else {
            return shouldVibrateOld();
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private boolean shouldVibrateNew() {
        if (vibrator == null || !vibrator.hasVibrator()) {
            return false;
        }

        boolean vibrateWhenRinging = Settings.System.getInt(context.getContentResolver(), "vibrate_when_ringing", 0) != 0;
        int ringerMode = audioManager.getRingerMode();

        if (vibrateWhenRinging) {
            return ringerMode != AudioManager.RINGER_MODE_SILENT;
        } else {
            return ringerMode == AudioManager.RINGER_MODE_VIBRATE;
        }
    }

    private boolean shouldVibrateOld() {
        return audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER);
    }

}

Manifest permissions:
 <uses-permission android:name="android.permission.VIBRATE" />
 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

CallNotificationBuilder:
public class CallNotificationBuilder {

public static final int WEBRTC_NOTIFICATION = 313388;

public static final int TYPE_INCOMING_RINGING = 1;
public static final int TYPE_OUTGOING_RINGING = 2;
public static final int TYPE_ESTABLISHED = 3;

private static final String callChannelId = "23455";
private static NotificationCompat.Builder builder;

public static Notification getCallInProgressNotification(Context context, int type) {

    builder = new NotificationCompat.Builder(context, callChannelId)
            .setContentIntent(goActivity(context, null))
            .setLights(Color.GREEN, 3000, 3000)
            .setOngoing(true)
            .setShowWhen(true)
            .setWhen(System.currentTimeMillis());

    initialize(context);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PUBLIC);
    }

    NotificationManager notificationManager = ServiceUtil.getNotificationManager(context);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel mChannel = new NotificationChannel(callChannelId, context.getString(R.string.app_name), importance);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        mChannel.setLockscreenVisibility(android.app.Notification.VISIBILITY_PUBLIC);
        mChannel.setShowBadge(true);
        mChannel.enableLights(true);
        notificationManager.createNotificationChannel(mChannel);
    }

    String contentTitle = new UserQueries().getDisplayNameInRealm(friendId);
    if (contentTitle.isEmpty()) {
        contentTitle = context.getString(R.string.app_name);
    }
    builder.setContentTitle(contentTitle);

    if (type == TYPE_INCOMING_RINGING) {
        builder.setContentText(context.getString(R.string.incoming_call));
        builder.setSmallIcon(R.drawable.call_in);

        builder.addAction(getActivityNotificationAction(context, friendId, callServerId, isOffer, isVideo, CallActivity.END_CALL_ACTION, R.drawable.ic_call_end_grey600_32dp, R.string.deny_call));
        builder.addAction(getActivityNotificationAction(context, friendId, callServerId, isOffer, isVideo, CallActivity.ANSWER_ACTION, R.drawable.ic_phone_grey600_32dp, R.string.answer_call));

    } else if (type == TYPE_OUTGOING_RINGING) {

        builder.setSmallIcon(R.drawable.call_out);

        builder.setContentText(context.getString(R.string.dialing));
        builder.addAction(getActivityNotificationAction(context, friendId, callServerId, isOffer, isVideo, CallActivity.END_CALL_ACTION, R.drawable.ic_call_end_grey600_32dp, R.string.cancel_call));

    } else {

        builder.setSmallIcon(R.drawable.call_icon);

        builder.setContentText(context.getString(R.string.call_in_progress));
        builder.addAction(getActivityNotificationAction(context, friendId, callServerId, isOffer, isVideo, CallActivity.END_CALL_ACTION, R.drawable.ic_call_end_grey600_32dp, R.string.end_call));

        builder.setUsesChronometer(true);
        builder.setShowWhen(false);
    }

    return builder.build();
}

private static PendingIntent goActivity(Context context, String action) {

    Intent activityIntent = new Intent(MyApplication.getContext(), CallActivity.class);

    if (action != null) {
        activityIntent.setAction(action);
    }

    activityIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
            | Intent.FLAG_ACTIVITY_MULTIPLE_TASK
            | Intent.FLAG_ACTIVITY_NEW_TASK);

    return PendingIntent.getActivity(context, (int) System.currentTimeMillis(), activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}

private static void initialize(Context context) {

    //For when the screen might have been locked
    context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

    //Just in case the screen didn't get a chance to finish turning off but still locked
    context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));

    //For when the user unlocks the device
    context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_USER_PRESENT));

    //For when the user changes users
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_USER_BACKGROUND));
        context.registerReceiver(notificationUpdateReceiver, new IntentFilter(Intent.ACTION_USER_FOREGROUND));
    }

}

private static BroadcastReceiver notificationUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (keyguardManager != null && keyguardManager.isKeyguardLocked()) {
                builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            }
        }
    }
};

private static NotificationCompat.Action getActivityNotificationAction(Context context,
                                                                       @NonNull String action,
                                                                       @DrawableRes int iconResId,
                                                                       @StringRes int titleResId) {

    return new NotificationCompat.Action(iconResId, MyApplication.getContext().getString(titleResId), goActivity(context, friendId, isOffer, callServerId, isVideo, action));
}

startForeground function:
startForeground(CallNotificationBuilder.WEBRTC_NOTIFICATION,
                CallNotificationBuilder.getCallInProgressNotification(getApplicationContext(), type));

A: I only changed importance level and ran it:
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, appName, importance);

A: I do not see any issue with your code,I tested in Nexus 6P 8.1.0 devices.
this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

I was calling stop and vibrator was being stopped properly.


text:
Q: how can i print two digit number up to 99 and three digit number 999 to 100 using one text box? i am newer to developer solving this problem i am not getting three digit number up to 100. when i am giving in between 999 to 100 to print up to 100.
this is my html code
<script type="text/javascript" src="logic.js"></script>
<input type="text" id="number">
<input type="button" onClick="logic()" Value="choice" />

this is my javascript..
function logic() {
    var number = document.getElementById("number").value;
    if(number.length<=99){
        for(var i=number;i<=99;i++){
            console.log(i);
        }
    }
    else if(number.length<=999){
        for(var j=number;j>=100;j--){
            console.log(j);
        }
    }
}

if i am giving in between 10 to 99 to print up to 99 and 999 to 100 to print up to 100  so please help me...

A: You will get a type of string from the input.
You have to change it to a type of number to compare it to a number.
parseInt()
.length is an array and string property. That is why you get unexpected numbers.
It seems that you need to do a course on programming and java script.
Roughly as a start maybe this is what you wanted to create until some point.
function logic()
{
  var number = parseInt ( document.getElementById("number").value );

  if(number <= 99)

  {
     for(var i=number;i<=99;i++)
     {
       console.log(i);
     }
  }
  else if(number <= 999 && number > 99 ){

      for(var j=number;j>=100;j--)
      {
        console.log(j);
      }

  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is self-initialization 'A a = a;' allowed? This code fails at runtime in the copy constructor.
But the compiler (MSVS2008) issues no warnings.
Could you explain (preferably cite the standard) whether this code is illegal or what?
I understand that A a = a; should never be written at the first place,
but I am looking for a theoretical background.
 class A
 {
 public:

    A()
    :p(new int)
    {
    }

    A(const A& rv)
    {
        p = new int(*rv.p);
    }

    ~A()
    {
        delete p;
    }

 private:

    int *p;
 };

 int main()
 {
    A a = a;
 }

A: Your code is not calling the standard constructor but the copy constructor, so you are accessing an uninitialized pointer.

A: According to the standard (12.6.1 [class.expl.init] ) self initialization is perfectly legal.
Therefore the following is legal.
A a = a;

You just need to write your copy constructor to deal with it correctly.
A(const A& rv)
{
    if(&rv == this) {
        p = new int(0);
        return;
    }

    p = new int(*rv.p);
}

Edit: Updated code based on comments.

A: Interesting reading on self-assignment: http://www.gotw.ca/gotw/011.htm
In particular, note "Postscript #1" in relation to this question and some of the answers given.

A: A a = a; definitely should not be written. But a = a could be written.  Your assignment operator must check for &rv == this and do nothing in case of a self-copy.
Oh, yes, you do need to write an assignment operator for class A.


text:
Q: activex component can't create object error with word.application I am using the below mentioned code to copy some values in word and then copying it back to excel.
But getting the

runtime error 429 Activex component can't create object.

This same piece of code was working before I formatted my system. But after the new installations this is not working and I'm getting the error.
 Sub Word()
    Application.DisplayAlerts = False
    Dim ws As Worksheet
    Dim Path As String
    Dim objWord As Object
    Dim objDoc As Object

    Path = ActiveWorkbook.Path
    Set inv = Workbooks.Open(Path & "\inv.xls")
    Set test = Workbooks.Open(Path & "\test.xlsx")
    Set ws = inv.Sheets("inv")
    Set Wb = test.Sheets("Sheet1")
    ws.Range("A1").Copy
    Set objWord = CreateObject("Word.Application") <---The error is here
    Set objWord.Visible = True
    Set objDoc = objWord.Documents.Open(Path & "\test.docx")
    objWord.Selection.Paste
    Application.CutCopyMode = False
       objDoc.Range(0, objDoc.Range.End).Copy
    Wb.Range("A1").Select
    ActiveSheet.Paste
    inv.Close Savechanges:=False
    test.Close Savechanges:=True
    objWord.ActiveDocument.Close Savechanges:=wdDoNotSaveChange
    objWord.Quit
    Set objWord = Nothing
    Set objDoc = Nothing
    End Sub

A: to properly handle any word instance you could use a helper Function
Function GetWord(objWord As Object) As Boolean
    On Error Resume Next
    Set objWord = GetObject(, "Word.Application") ' try getting an already running instance of Word
    If objWord Is Nothing Then Set objWord = CreateObject("Word.Application")  ' if no running instance of Word then try setting a new one

    GetWord = Not objWord Is Nothing ' return the function result

    If Not GetWord Then MsgBox "Couldn't get Word", vbCritical ' inform the user that something went wrong

hence your macro could exploit it as follows
Sub Word()
    Dim objWord As Object

    If Not GetWord(objWord) Then Exit Sub

    objWord.Visible = True

    ... rest of your code
    End Function

before trying this solution you should close your excel instances and run a new Excel form scratch not to suffer from any residual word instances scattered from your previous attempts
should all this not fix the issue, then you have to check more deeply ...

A: The line you have indicated for the error seems ok (as long word is normally installed that I'm sure it is the case).
What is NOT ok is the successive line: ...Set objWord.Visible = True..,
Certainly this line WILL generate an error cause that is simply a property to set  but not an object.
That should be simply a : objWord.Visible = True.
Hope this helps.
KR.

A: Please check the below link to track your error.
Microsoft Help for Automation Error


text:
Q: Count numbers in a "for loop" and give back average, min, max value in java A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;

public class Statistic
{
public static void main (String[] args)
 {
    // Variables
    Scanner input = new Scanner(System.in);
    int number1;
    int numbers;
    double averageValue;

    // Input
    System.out.println("\n\n####################################################################");
    System.out.print("\n Pls enter a number: ");
    number1 = input.nextInt();
    System.out.print(" Pls enter " + number1 +" numbers: ");
    numbers = input.nextInt();

    for (int count = 0; count < number1; count ++) {
        System.out.println(numbers); //Just for me to see which numbers are read by the programm
    }
    averageValue = numbers / number1;

    // Output
    System.out.println("\n Biggest number: " + Math.max(numbers));
    System.out.println("\n Smallest number: " + Math.min(numbers));
    System.out.print("\n Average value: " + averageValue);

 }
}

But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.

A: The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();

nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.

A: You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:

*

*input how many numbers you want to enter -> store in variable count

*use some loop to loop count number of times and in each iteration store
users value in variable num.

*Increment sum by number user entered. sum += num;

*check if entered number is less than current min. If true store min as that number.

*Same as min do for max variable.

*When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.

A: Some errors that I can see

System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();

You need here a loop and array to read and store all elements.

To get average value you need first to sum all elements in array and then to divide by length of array.

To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.

Your code should be something like this
Notes

*

*If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.

*If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.

.
public class Statistic {
    public static void main(String[] args) {
        // Variables
        Scanner input = new Scanner(System.in);

        // Input
        System.out.println("\n\n####################################################################");
        System.out.print("\n Pls enter a number: ");

        int number1 = input.nextInt();
        System.out.println(" Pls enter " + number1 + " numbers: ");
        int[] numbers = new int[number1];
        for (int i = 0; i < number1; i++) {
            System.out.println("Enter next number");
            numbers[i] = input.nextInt();
        }

        // Find min and max values
        int max = Arrays.stream(numbers).max().getAsInt();
        int min = Arrays.stream(numbers).min().getAsInt();
        System.out.println("\n Biggest number: " + max);
        System.out.println("\n Smallest number: " + min);

        // Get average value
        int sum = 0;
        for (int num : numbers) {
            sum = sum + num;
        }
        double averageValue = (double) sum / number1;
        System.out.print("\n Average value: " + averageValue);

    }
}

A: First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
    Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
    After sorting first will me min and last will be max.
    Math.min and Math.max only works for comparing 2 numbers not an undefined list.
    Again i would say the best solution would be if u check for the number is min or max at input time.
    As you are new to java you can try that out your self.
import java.util.*;

public class ZahlenStatistik
{
    public static void main (String[] args)
    {
        // Variables
        Scanner input = new Scanner(System.in);
        int number1;
        List<Integer> numbers = new ArrayList<Integer>(); // change it to list
        double averageValue;
        int sum= 0;

        // Input
        System.out.println("\n\n####################################################################");
        System.out.print("\n Bitte geben Sie eine Zahl ein: ");
        number1 = input.nextInt();
        System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");

        //Define the number of times loop goes
        for (int count = 0; count < number1; count ++)
        {
            numbers.add(input.nextInt());
        }

        for(Integer number:numbers)
        {
            sum = sum + number;
        }

        averageValue = sum / number1;
        Collections.sort(numbers);
        // Output
        System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
        System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
        System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);

    }
}

A: import java.util.Scanner;

public class SumOf2
{

    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter 2 integer values");
        int m = s.nextInt();
        int n = s.nextInt();
        int sum=0;
        int count=0;
        for(int i=m ; i<=n ; i++)
        {
            if(count < n)
            {
                sum=sum+i;
                count++;
            }
        }
        System.out.println("Sum of two numbers is: "+sum);
        System.out.println("Count between 2 numbers is : "+count);

    }

}


text:
Q: how to represent parallel acitvities in use case diagram One of the use case is application has to support parallel activities. when user clicks on a button alogirthms should run in different threads,but each one is independent of each other.
It is possible to show using activity diagram. But wanted to know how parallel activities can be shown in use case diagram.

A: You do not show that on a use case diagram. Rather link a constraint to the use case telling that it must run concurrent.
You can model the behavior in an activity diagram which you can put inside the use case.


text:
Q: call action from valuechanged method Java Swing I want to call a action which is in the separate class.
public class ShowMPCAction extends AbstractAction {

    @Override
    public void actionPerformed(ActionEvent e) {
        // action code
    }

}

from the class
public class PLListSelectionListener implements ListSelectionListener {

    @Override
    public void valueChanged(ListSelectionEvent e) {
        // some code
        if (!lsm.getValueIsAdjusting()) {
            // from here I want to call the action which is in the class ShowMPCAction
        }
    }

how can I do this ?

A: The best way is to inject ShowMPCAction into PL ListSelectionListener, for example via constructor

A: Simplest way is to create a dummy JButton and call it's click event like this.
In your public void valueChanged(ListSelectionEvent e) { method,
javax.swing.JButton jb = new javax.swing.JButton(new ShowMPCAction());
jb.doClick();

A: You could just create an instance of ShowMPCAction and call the method directly.
ShowMPCAction object = new ShowMPCAction();
object.actionPerformed(e);

Is this what your looking for?


text:
Q: Sending Discord Webhook with java I want something like this, but with a file attachment, so i can send an embed and under it the image. It doesnt have to like this exactly, but it should like something like this: enter image description here
   package com.StrgC;
    import java.io.OutputStream;
    import java.net.URL;

    import javax.net.ssl.HttpsURLConnection;

    public class WarningSending {
        public static void SendWarning() {
            ///////////////////////////////////////////////
            // CONFIG

            String tokenWebhook = "";
            String title = "";
            String message = "";
            ///////////////////////////////////////////////
            String jsonBrut = "";
            jsonBrut += "{\"embeds\": [{"
                    + "\"title\": \""+ title +"\","
                    + "\"description\": \""+ message +"\","
                    + "\"color\": 15925248"
                    + "}]}";
            try {
                URL url = new URL(tokenWebhook);
                HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
                con.addRequestProperty("Content-Type", "application/json");
                con.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_");
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                OutputStream stream = con.getOutputStream();
                stream.write(jsonBrut.getBytes());
                stream.flush();
                stream.close();
                con.getInputStream().close();
                con.disconnect();
            } catch (Exception e) {
                e.printStackTrace()
            }

                }
    }


text:
Q: Not possible to serialize object singleton in Kotlin One common uses for sealed classes, in Kotlin, is to have a combination of cases that have some data (using data class) and others that are singletons (using object) like this:
sealed class Location {
    object Unknown : Location()
    data class Known(val lat: Float, val lon: Float) : Location()
}

The system we are using requires the model to implement Serializable. To my surprise, this doesn't work with object singletons as you can see on this demo:
https://pl.kotl.in/vd_TgUR6a
Which outputs the following:
Success: Known(lat=37.563934, lon=-116.85123) and Known(lat=37.563934, lon=-116.85123) are equal
Failure: sample.Location$Unknown@7c3df479 and sample.Location$Unknown@452b3a41 are not equal

The instance id is different. My guess is that the JVM deserializes it using "artifitial" means. Be it Reflexion or another synthetic way.
How can I make this work?

A: I found out a "bester" solution. Using the hidden JVM API of readResolve():
sealed class Location: Serializable {
    object Unknown : Location() {
        private fun readResolve() : Any? = Location.Unknown
    }
    data class Known(val lat: Float, val lon: Float) : Location()
}

Code here: https://pl.kotl.in/tMGf-AIfq
Produces the following output:
Success: Known(lat=37.563934, lon=-116.85123) and Known(lat=37.563934, lon=-116.85123) are equal
Success: sample.Location$Unknown@452b3a41 and sample.Location$Unknown@452b3a41 are equal

This function is called after an object is loaded from a stream and allows to return a different object instead of the one loaded from memory.
This means that it's safe to use even if our object has a state (not that it should though. And should be much more memory efficient.
There is a ticket about this here: https://youtrack.jetbrains.com/issue/KT-9499
And it looks like it may be coming as part of this other ticket to add the @JVMSerializable annotation: https://youtrack.jetbrains.com/issue/KT-14528
Old Answer:
The best solution I found was to make the singleton object override the default equals, hashCode and toString to make it functionally speaking identical:
sealed class Location: Serializable {
    object Unknown : Location() {
        override fun equals(other: Any?) = other is Unknown
        override fun hashCode() = toString().hashCode()
        override fun toString(): String = "Location.Unknown"
    }
    data class Known(val lat: Float, val lon: Float) : Location()
}

Here is the demo: https://pl.kotl.in/oNd-mnWlQ
And the output is:
Success: Known(lat=37.563934, lon=-116.85123) and Known(lat=37.563934, lon=-116.85123) are equal
Success: Location.Unknown and Location.Unknown are equal

This is a possible solution if memory is not an extreme concern as it will create an object for each of the deserialized objects. Albeit, the object has a very small footprint, which shouldn't be a concern for most cases but something to be aware of.
This wouldn't have been a problem if Kotlin could have implemented object using enum classes as they are serialized differently in the JVM. However, they can't extend classes (only interfaces) so it wouldn't work for this instance.
All that said Oracle plans to drop it eventually:
https://www.infoworld.com/article/3275924/oracle-plans-to-dump-risky-java-serialization.html
In the meantime, we are stuck with this.
Note: This works as long as the object is not mutable. If we allow changing states all hell breaks open as we start having different states on each deserialised object.


text:
Q: Прошу помощи в парсенге XML в C# Есть  такой  XML:
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="PartUsage.XSL" ?>
<Report>
    <Infomation>
        <Title>Part usage</Title>
        <CreateDate>2020/06/16 00:58:54</CreateDate>
        <CreateUser>DefaultUser</CreateUser>
    </Infomation>
    <Search>
        <FromDate>2020/06/16 00:45:00</FromDate>
        <ToDate>2020/06/16 00:55:00</ToDate>
        <LineName></LineName>
        <MachineName></MachineName>
        <Recipes>
        </Recipes>
        <Option>0</Option>
        <ReportType>Type-A</ReportType>
    </Search>
    <Result>
        <Machines>
            <Machine>
                <Name>NXT1</Name>
                <Recipes>
                    <Recipe>
                        <Key>717</Key>
                        <Name>Recipe1</Name>
                        <StartTime>2020/06/16 00:45:00</StartTime>
                        <EndTime>2020/06/16 00:55:00</EndTime>
                        <Items>
                            <Item>
                                <PartName>PART1NXT1</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                            <Item>
                                <PartName>PART2NXT1</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                            <Item>
                                <PartName>PART3NXT1</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                        </Items>
                    </Recipe>
                    <Recipe>
                        <Key>717</Key>
                        <Name>Recipe2</Name>
                        <StartTime>2020/06/16 00:45:00</StartTime>
                        <EndTime>2020/06/16 00:55:00</EndTime>
                        <Items>
                            <Item>
                                <PartName>PART1</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                            <Item>
                                <PartName>PART2</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                            <Item>
                                <PartName>PART3</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                        </Items>
                    </Recipe>
                </Recipes>
            </Machine>
            <Machine>
                <Name>NXT2</Name>
                <Recipes>
                    <Recipe>
                        <Key>2125</Key>
                        <Name>Recipe2232</Name>
                        <StartTime>2020/06/16 00:45:00</StartTime>
                        <EndTime>2020/06/16 00:55:00</EndTime>
                        <Items>
                            <Item>
                                <PartName>Part112</PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                        </Items>
                    </Recipe>
                </Recipes>
            </Machine>
            <Machine>
                <Name>NXT3</Name>
                <Recipes>
                    <Recipe>
                        <Key>2884</Key>
                        <Name>Recipe12121</Name>
                        <StartTime>2020/06/16 00:45:00</StartTime>
                        <EndTime>2020/06/16 00:55:00</EndTime>
                        <Items>
                            <Item>
                                <PartName></PartName>
                                <Stage>0</Stage>
                                <GroupKey>0</GroupKey>
                                <Pos>0</Pos>
                                <SubPos>0</SubPos>
                                <Class></Class>
                                <PickupCount>0</PickupCount>
                                <TotalPartsUsed>0</TotalPartsUsed>
                                <RejectParts>0</RejectParts>
                                <PickupMiss>0</PickupMiss>
                                <ErrorParts>0</ErrorParts>
                                <DislodgedParts>0</DislodgedParts>
                                <DislodgedRate>0.000</DislodgedRate>
                                <RescanCount>0</RescanCount>
                                <LCRCheckUsed>0</LCRCheckUsed>
                                <PickupRate>0.000</PickupRate>
                                <RejectRate>0.000</RejectRate>
                                <ErrorRate>0.000</ErrorRate>
                                <SuccessRate>0.000</SuccessRate>
                                <UnitName>0</UnitName>
                                <FIDL></FIDL>
                            </Item>
                        </Items>
                    </Recipe>
                </Recipes>
            </Machine>
        </Machines>
    </Result>
</Report>

Мне  нужно  запарсить  ветку Result для  последующего  переноса в  DataGrid.
Со  зачениеми  элементов  Machine Name, Recipe Name, StartTime, EndTime, PartName, Stage  и  т.д.
Используя LinQ to  XML, равно как и System.XML, не помогает мне добраться до вложенных элементов начиная с <item>, то есть я начинаю через foreach обходить  все элементы начиная c уровня machine, но не получаю все PartName принадлежащие  одному recipe и одной machine.
Код с которым я играюсь вот такой:
XDocument xdoc = XDocument.Load(@"C:\From\reports\history\DefaultUser\DefaultUser\PUS20200616004500000.XML");
foreach (XElement el in xdoc.Element("Report").Elements("Result").Elements("Machines").Elements("Machine"))
{
    XElement NameElement = el.Element("Name");
    XElement ReciepeName = el.Element("Recipes").Element("Recipe").Element("Name");
    XElement StartTime = el.Element("Recipes").Element("Recipe").Element("StartTime");
    XElement EndTime = el.Element("Recipes").Element("Recipe").Element("EndTime");

    XElement PartName = el.Element("Recipes").Element("Recipe").Element("Items").Element("Item").Element("PartName");

    Console.WriteLine($"Name: {NameElement.Value}");
    Console.WriteLine($"RecipeName:{ReciepeName.Value}");
    Console.WriteLine($"StartTime:{StartTime.Value}");
    Console.WriteLine($"EndTime:{EndTime.Value}");
    Console.WriteLine($"PartName:{PartName.Value}");
}
Console.ReadLine();

Выход  вот такой:
Name: NXT1
RecipeName:Recipe1
StartTime:2020/06/16 00:45:00
EndTime:2020/06/16 00:55:00
PartName:PART1NXT1
Name: NXT2
RecipeName:Recipe2232
StartTime:2020/06/16 00:45:00
EndTime:2020/06/16 00:55:00
PartName:Part112
Name: NXT3
RecipeName:Recipe12121
StartTime:2020/06/16 00:45:00
EndTime:2020/06/16 00:55:00
PartName:Part108329329832

Направьте в нужную сторону.

A: Вы можете попытаться достичь того, что вам нужно, используя LINQ to XML API.
Один цикл без осложнений.

c#

void Main()
{
    const string FILENAME = @"e:\temp\PUS20200616004500000.XML";

    XDocument doc = XDocument.Load(FILENAME);

    foreach (var el in doc.Descendants("Item"))
    {
        Console.WriteLine("Name: '{0}', RecipeName: '{1}', StartTime: '{2}', EndTime: '{3}', PartName: '{4}'"
            , el.Ancestors("Machine").Elements("Name").FirstOrDefault()?.Value
            , el.Ancestors("Recipe").Elements("Name").FirstOrDefault()?.Value
            , el.Ancestors("Recipe").Elements("StartTime").FirstOrDefault()?.Value
            , el.Ancestors("Recipe").Elements("EndTime").FirstOrDefault()?.Value
            , el.Element("PartName").Value);
    }
}

Вывод

Name: 'NXT1', RecipeName: 'Recipe1', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'PART1NXT1'
Name: 'NXT1', RecipeName: 'Recipe1', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'PART2NXT1'
Name: 'NXT1', RecipeName: 'Recipe1', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'PART3NXT1'
Name: 'NXT1', RecipeName: 'Recipe2', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'PART1'
Name: 'NXT1', RecipeName: 'Recipe2', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'PART2'
Name: 'NXT1', RecipeName: 'Recipe2', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'PART3'
Name: 'NXT2', RecipeName: 'Recipe2232', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: 'Part112'
Name: 'NXT3', RecipeName: 'Recipe12121', StartTime: '2020/06/16 00:45:00', EndTime: '2020/06/16 00:55:00', PartName: ''

A: var xdoc = XDocument.Load(...);

var machines = xdoc.Element("Report")
    .Elements("Result")
    .Elements("Machines")
    .Elements("Machine");

foreach (var machine in machines)
{
    var machineName = machine.Element("Name").Value;
    Console.WriteLine($"MachineName: {machineName}");

    foreach (var recipe in machine.Elements("Recipes").Elements("Recipe"))
    {
        var recipeName = recipe.Element("Name").Value;

        var startTime = (DateTime)recipe.Element("StartTime");
        var endTime = (DateTime)recipe.Element("EndTime");

        var partNames = recipe.Elements("Items")
            .Elements("Item")
            .Elements("PartName")
            .Select(x => x.Value);

        Console.WriteLine();
        Console.WriteLine($"RecipeName: {recipeName}");
        Console.WriteLine($"StartTime: {startTime}");
        Console.WriteLine($"EndTime: {endTime}");
        Console.WriteLine($"PartNames: {string.Join(", ", partNames)}");
    }

    Console.WriteLine();
}


text:
Q: SQLite Database Browser "Temp Table already exists" I was following this tutorial in order to integrate a pre made database to my Android App.
Everything was going well until it asked me to rename my Primary Key Field to "_id". Well for one I don't have a PK (I know it's bad DB practice), and two, the PK is not an integer type, giving a type mismatch error. Now, I tried to rename one of my fields (non integer) to "_id" and now I can't rename it back. Also, I tried removing an extra field that I don't need and it gives me this error:

Error removing field. Message from database engine:  table TEMP_TABLE already exists

or this

Error editing field. Message from database engine:  table TEMP_TABLE already exists

Not quite sure how to work this out since I'm not familiar with using the terminal to work with databases. I tried looking around and there are no extra unaccounted for tables so I don't know where these are coming from.

A: You should get SQLite Manager (a FireFox extension) to work with your DB on your desktop, it's free and works pretty well.  It's got a fairly reasonable GUI... so it's much more friendly than using the command line.
And yeah, android wants a primary key field called "_id" and it needs to be an integer.  It seems they based all of their list-type widgets upon this premise.  I can tell you from personal experience that the ListView widget won't work if you don't have an _id column in the cursor!


text:
Q: OpenGL flood fill not recognizing boundary I'm trying to implement the flood fill algorithm in OpenGL, but I'm encountering an error doing so. The error is that the algorithm does not stop at the boundary, and simply keeps going until the edge of the window, and eventually crashes with a bad memory access error. I'm working on MacOS Mojave 10.14.4.
I think my implementation's logic is correct, however, I've printed out the color of each pixel from getPixel, and it is always white (the background color), even when getting the color of boundary pixels.
The code below draws a circle using Bresenham's Line algorithm (midpoint algorithm), and then flood fills it (unsuccessfully).
#include <GLUT/GLUT.h>
#include <iostream>

struct Color {
    GLubyte r;
    GLubyte g;
    GLubyte b;
};

Color getPixelColor(GLint x, GLint y) {
    Color color;
    glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &color);
    return color;
}

void setPixel (GLint x, GLint y) {
    glBegin(GL_POINTS);
    glVertex2i(x, y);
    glEnd();
    Color color = getPixelColor(x, y);
}

void setPixelColor(GLint x, GLint y, Color color) {
    glColor3ub(color.r, color.g, color.b);
    setPixel(x, y);
    glEnd();
    glFlush();
}

void floodFill4 (GLint x, GLint y, Color fillColor, Color interiorColor) {
    Color color = getPixelColor(x, y);
    if (color.r == interiorColor.r && color.g == interiorColor.g &&
        color.b == interiorColor.b) {
        setPixelColor(x, y, fillColor);
        floodFill4 (x + 1, y, fillColor, interiorColor);
        floodFill4 (x - 1, y, fillColor, interiorColor);
        floodFill4 (x, y + 1, fillColor, interiorColor);
        floodFill4 (x, y - 1, fillColor, interiorColor);
    }
}

void drawCirclePoint(GLint x, GLint y, GLint cx, GLint cy) {
    setPixel(cx+x, cy+y);
    setPixel(cx+y, cy+x);
    setPixel(cx-y, cy+x);
    setPixel(cx-x, cy+y);
    setPixel(cx-x, cy-y);
    setPixel(cx-y, cy-x);
    setPixel(cx+y, cy-x);
    setPixel(cx+x, cy-y);
}

void drawCircle(GLint cx, GLint cy, GLint radius) {
    int p = 1 - radius;
    GLint x = 0;
    GLint y = radius;
    while (x < y) {
        drawCirclePoint(x, y, cx, cy);
        if (p < 0) {
            x++;
            p += (2 * x) + 1;
        } else {
            x++;
            y--;
            p += (2 * x) + 1 - (2 * y);
        }
    }
}

void displayMe(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3ub(0, 0, 0);
    GLint cx = 0;
    GLint cy = 0;
    GLint radius = 200;
    // Draw head
    glColor3ub(0, 0, 0);
    drawCircle(cx, cy, radius);
    glEnd();
    glFlush();
    Color interiorColor = {255, 255, 255};
    Color fillColor = {0, 0, 255};
//    floodFill4(100, 100, fillColor, interiorColor);
}

void init (void) {
    glClearColor(1.0, 1.0, 1.0, 0.0);  // Set display-window color to white.
    glMatrixMode(GL_PROJECTION);       // Set projection parameters.
    glLoadIdentity();
    gluOrtho2D(-1000.0, 1000.0, -1000.0, 1000.0);
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(1000, 1000);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("My Drawing");
    init();
    glutDisplayFunc(displayMe);
    glutMainLoop();
    return 0;
}

I've looked at this post, which seems similar, but wasn't able to find a solution.

A: If you're going to persist with glVertex() for point plotting make sure you set up your matrix stack transforms (GL_PROJECTION/GL_MODELVIEW) so they match the glReadPixels() coordinate system:
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0, glutGet(GLUT_WINDOW_WIDTH), 0, glutGet(GLUT_WINDOW_HEIGHT) );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();

Or switch to glRasterPos() + glDrawPixels() for setPixel*().
Better yet, do the flood-fill logic host-side & upload the results to a GL texture for display.
Either way you're going to run into a stack overflow with that recursive solution on even fairly reasonably sized inputs so you'll probably want to switch to an explicit stack/queue:
void floodFill4( GLint aX, GLint aY, Color fillColor, Color interiorColor )
{
    typedef std::pair< GLint, GLint > Location;
    std::queue< Location > locations;

    locations.push( Location( aX, aY ) );
    while( !locations.empty() )
    {
        const Location loc = locations.front();
        locations.pop();

        GLint x = loc.first;
        GLint y = loc.second;

        Color color = getPixelColor( x, y );
        if( color.r == interiorColor.r &&
            color.g == interiorColor.g &&
            color.b == interiorColor.b )
        {
            setPixelColor( x, y, fillColor );
            locations.push( Location( x, y - 1 ) );
            locations.push( Location( x, y + 1 ) );
            locations.push( Location( x - 1, y ) );
            locations.push( Location( x + 1, y ) );
        }
    }
}


text:
Q: How to access an included module's methods from within another included module? module Foo
  attr_accessor :val
end

module Bar
  def bar
    val = 50
  end
end

class FooBar
  include Foo
  include Bar
end

fb = FooBar.new
puts fb.bar # 50
puts fb.val # nil

I would like to, from within Bar, change Foo's "val" value.
Just so you know, I'm trying to do this because I want to add user authentication through a Facebook Canvas app in Clearance (0.8.2 (old, I know)). The variable that I want to change is https://github.com/thoughtbot/clearance/blob/b8ccca00d91cb336e044b76b5c6ae1d8de9d2d8d/lib/clearance/authentication.rb#L25.
This module gets included into ApplicationController, and I'm including another module afterwards (FacebookAuthenticationHelper) that does something like
def authenticate_facebook
  current_user ||= facebook_user if coming_from_facebook?
end

I would love to know if there's a better way to do this as well. I'm not using OAuth, I'm just saving Facebook's user_id sends to my app from signed_request into my DB.
Thanks!

A: In ruby, any statement of the form varname = value will create a local variable named varname if it doesn't already exist.  This is even true within class methods where the class has a setter method of the same name.  Furthermore, if a local variable exists, it takes precedence over getters and setters.  For example:
class Demo
    attr_accessor :foo

    def demonstrate!
        @foo = 1      #1: Set member variable foo, so we get meaningful output
        puts foo      #2: Prints 1 (this calls the getter)
        puts self.foo #3: Prints 1 (also calls the getter)

        foo = 2       #4: Creates a LOCAL variable named foo with the value 2
        puts foo      #5: Prints 2 (locals take precedence over getters)
        puts self.foo #6: Prints 1 (calls the getter - the member variable hasn't changed)

        self.foo = 3  #7: Use SELF to ensure you call a getter or setter
        puts foo      #8: Prints 2 (the local again)
        puts self.foo #9: Prints 3 (the member, which is now 3)
    end
end

The bad thing about this system is:  Look at lines 2 and 5.  The same exact code does different things!  On line 2, the local variable foo didn't exist yet, so ruby did the "next best" thing and called the getter.  But on line 5, the local foo exists, so it takes precedence.
I'd say that this is bad language design:  If setters can't be called without self, why should it be okay for getters - especially when it can lead to rickety, context-sensitive code like the above?  But it's what we have to work with, and it leads to some general guidelines:

*

*If you can, use @foo.  It's obvious what that does.

*If you're using a getter or setter, always use self, even when it's not strictly necessary.  This makes it obvious what you're calling.  It also guarantees your code won't behave differently if you add a local with the same name later.

*If you do 1 and 2, you can assume that anything without a @ or a self is a local variable (or a function call, but you can probably tell those apart by name).

And that ended up being a bit long-winded, but I was unable to find a good demonstration of the getter/setter/local problem to link to.  So maybe this is it - hope it's helpful!


text:
Q: How to Get the Index of an Array Elemnt which Contains an specific String having an array like
 var arr = ['best app in', 'Not q big deal', 'volvu is good-1',' volvu is good-0'];

how can I get the index and full text of the elemnt which contains exact match of is good-1 in the array?

A: Use the code below. I basically for looped through the array, and use .includes() to see if it had the is good-1 inside it. If it did, I console.log() the index and full text. This code works if there is multiple strings with that value in your array. I added an extra value into your array to show that.

var arr = ['best app in', 'Not q big deal', 'volvu is good-1', ' volvu is good-0', 'this is good-1'];

for(var i = 0; i < arr.length; i++) {
  if (arr[i].includes("is good-1")) {
    console.log(`Index: ${i} Full text: ${arr[i]}`);
  }
}


text:
Q: Python:division vs. shift In python, there are
division (//, /) and shift (>>, <<).

*

*In the performance matter, shift operator is more beneficial?!

*Is there any benefits using shift rather than division operator?!

A: After measurement using the following code, the shift seems to be a bit slower but it is not significant and it is on my computer, your results may differ.
I got the following answer:
It took 42.1938125s for division by 2
It took 43.217766499999996s for integer division by 2
It took 47.926054599999986s for shift by 1
It took 41.82601500000001s for division by 4
It took 43.20513730000002s for integer division by 4
It took 48.33005560000004s for shift by 2

import timeit
import random

random.seed(42)
DATA = [random.randint(0,10000) for _ in range(400)]

def measure(func, name):
    time = timeit.timeit(lambda: [func(val) for val in DATA], number=1000000)
    print(f"It took {time}s for {name}")

measure(lambda x:x / 2, "division by 2")
measure(lambda x:x // 2, "integer division by 2")
measure(lambda x:x >> 1, "shift by 1")
measure(lambda x:x / 4, "division by 4")
measure(lambda x:x // 4, "integer division by 4")
measure(lambda x:x >> 2, "shift by 2")


text:
Q: Regular expression that matches number or 100%, but not 99% I'm trying to write a regexp which matches on two groups of digits or 100% separated with 'x' char. Like (first group)x(second group). And "100%" should be captured as is, with percent symbol. And percent sign is allowed only after 100.
For example:
100x100 - OK
100%x100 - OK
99x99 - OK
99%x100 - not OK
99x99% - not OK

Here is my approach:
s = '100%x99%' # this should be failed
match = re.match(r'(100%|\d+(?!%))x(100%|\d+(?!%))', s)
if match:
  x = match.group(1)
  y = match.group(2)

I expect that y will be none and match would be failed, because '99%' is prohibited. But with my regexp I get x = 100% and y = 9.
How can I fix my regex?

A: This would work: (\d+x\d+$)|(100%x\d+$)|(\d+x100%)
This includes the case where 100% could come after the x so if that's not the case, just remove that last group.

A: (100%|\d+)x(100%|\d+)$

demo here

A: The other answers do work, but I would trim off the seemingly unnecessary parts to give the following:
(100%|\d+)x(100%|(\d+(?!\%|\d)))

This also does not require end lines with $. You can see it working here.

A: You could add a word boundary \b after the last \d+ to make sure it is not part of a longer match:
(100%|\d+(?!%))x(100%|\d+\b(?!%))


text:
Q: Algorithm to find the longest fully-internal line of a non-regular 2D-shape? I've been doing some image processing recently, and am looking for an algorithm to determine the longest line segment that is entirely within a non-regular shape. In other words, the line segment should be the longest line segment that touches the shape elusively at its endpoints.
The shape can be represented as a set of (x,y) coordinates or as a binary-array. The outermost layer of pixels (the edge), have already been determined.
A simple example would be an ellipse, to which the solution is the major axis. A more complex example would be a equilateral triangle, which would result in a line between two pixels which are immediately adjacent to two separate corners. Most of my shapes are ellipse-like or 'worm-like' (long and wavy).
Ultimately I wish to use this as a method to divide the 'worm-like' shapes into their segments, using a series of 'cuts' approximately perpendicular to this line. I am hoping that the line formed by this message will be better suited for this task than one determined by a regression. It should be noted that these shapes are high resolution, and therefore may consist of up to 1000 edge-pixels, which is why I'm trying to avoid a simple iterative/brute force approach.
Thank you for any and all suggestions!
Here are some visualizations:

A: I am unsure if I get the idea completely right, but to me it sounds a PCA problem, or in Computer graphics a object oriented bounding box problem.
Example:

The longest  axis of that box will be your longest line.
There are several tutorials online on how to compute this box, but the steps are quite easy:

*

*Compute PCA of your points

*Compute the projection of your points onto the first principal component

*Get max-min

*Reproject (max,0,0) and (min,0,0) in eigenspace to XYZ

*Make a line between them

Note that this will only work for convex figures. An ellipsoid, triangle will be OK for this, but it will compute a diagonal for an "L" shaped geometrical object. If you know that your objects will be convex, then this is the fastest and easiest approach to get the "longest internal line" (because if it is convex all the lines between points are "internal"). If your object are non-convex, then youd need to split them into convex subsections somehow, e.g. as @imaluengo suggests.

A: I believe, if I understood the question properly, that something similar to what you are trying to achieve is called Planar shape decomposition in Computer Vision literature. It is not exactly the same (is not finding the longest line in a shape), but is a way of decomposing a shape into line-separated meaningful segments for later shape-analysis or shape-matching operations (which might be useful for what you want).
Find bellow a sample image extracted from the latter cited paper (1):

If this is what you want to achieve (more or less), have a look to the following paper for a method to calculate shape decomposition (and refer to the bibliography for other methods):
(1) Planar shape decomposition made easy:
http://bmvc2015.swansea.ac.uk/proceedings/papers/paper013/index.html


text:
Q: Running exe in VSCode produces no output I want to compile C++ in VSCode. I followed the walkthrough here
When I run the example program in VSCode terminal, nothing is output into the terminal. I tried in powershell and in cmd using the dropdown in VSCode terminal window.
When I run the .exe from a standalone cmd terminal, it works fine. Could the problem be something about not knowing how to write the output? I'm guessing the program runs but just doesn't know where to output.

A: I opened VS code before adding mingw to my PATH. I simply had to restart VS code. I really figured each time I opened a new terminal in VS Code, it would.. open a new terminal. Perhaps they do some kind of virtual terminal and it's really all one terminal from launch? Who knows. Either way, restart VS code.

A: Command Prompt method :
first changer the directory to where file is located.
g++ -o program Menu-driven-program-DAA.cpp&program.exe

Running Cpp program through powershell terminal in vscode:
g++ -o program Menu-driven-program-DAA.cpp
.\program.exe

I've mentioned both the commands in vscode powershell terminal seperately because it throws an error
Note:- try gcc instead of g++ if it doesn't works for me only g++ did.

A: I encountered the same problem and by pure chance following worked in my case: When I opened VSC from a GIT shell via 'code .', I didn't get any output from a shell within VSC. But when I opened VSC from windows command prompt via 'code .' and executed the same file again and it worked.


text:
Q: Regex - Not containing a string and not ending with a / How do I create a regular expression which don't contain the string "umbraco" and doesn't end with a /
This is the what I have so far but I'm unable to get it fully working, any help would be appreciated.
(?!umbraco)(?![/]$)

Test strings would be:

*

*http://www.domain.com/umbraco/login.aspx - shouldn't match

*http://www.domain.com/pages/1/ - shouldn't match

*http://www.domain.com/pages/1 - should match

A: It should be this regex:
^(?!.*?umbraco).*?[^\/]$

Online Demo: http://regex101.com/r/lM0cS9
Explanation:
^ assert position at start of a line
(?!.*?umbraco) Negative Lookahead - Assert that it is impossible to match the regex below
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed
umbraco matches the characters umbraco literally (case sensitive)
.*? matches any character (except newline)
Quantifier: Between zero and unlimited times, as few times as possible, expanding as needed
[^\/] match a single character not present in the list below
\/ matches the character / literally
$ assert position at end of a line

A: This should be the regex
^(?!.*?umbraco).*?[^\/\s*\n*]$

demo http://rubular.com/r/tEhY7JFjXK


text:
Q: Telerik RadDiagram TreeLayout not showing in a grid I am trying to create a graph similar to this one here
I have xaml code like this:
<Border Grid.Row="1" Margin="0 4 0 0" Background="White" BorderBrush="#FFD6D4D4" BorderThickness="0 0 1 1">
            <Grid>
                <Border BorderThickness="1 1 0 0" BorderBrush="#D6D6D6" />

                <telerik:RadDiagram x:Name="diagram" GraphSource="{Binding GraphSource}"
                            ScrollViewer.HorizontalScrollBarVisibility="Visible"
                            ScrollViewer.VerticalScrollBarVisibility="Visible"
                            Zoom="{Binding ZoomFactor, Mode=TwoWay, Source={StaticResource repGpDataInstance}}" Height="800" />
            </Grid>
        </Border>

In my code behind I do the following: (after initializing components ...etc)
this.treeLayout.Layout(this.diagram, mymodel.ChildTreeLayoutViewModel.CurrentLayoutSettings);

Yet even thought the layout type is set to TreeDown, I get all the nodes on top of each other and I do not see a tree structure. How can I do this the right way? I need a tree structure of the nodes supplied through ObservableCollection<Object>

A: Basically you have two options for such issues:

*

*Add Style for the Shapes that sets default Width and Height of the Shapes. If this does not fill well in your scenario:

*Try invoking the Layout in Dispatcher.BeginInvoke

Dispatcher.BeginInvoke(() => this.treeLayout.Layout(...)


text:
Q: Custom form in email on Outlook Is there a way for me to create a form in an email that can be used for booking items (eg. rooms, vehicles, tools, etc.) on Outlook 2007? So it should allow the receiver to input start date/time, and end date/time, and also some other additional details.
So my scenario is this: A customer will contact me asking me to book an item. Sometimes they give me incomplete details or no details at all and I want to save time by just sending them an email that contains a form that they can fill out. It's also good for record-keeping.
In the future, I am also thinking of making a worksheet on Excel or a connection to a database for the entries I get, but for now, I just want to keep it simple, but not limited to future developments. By "simple", I mean just forms in emails so I can look at them so I can record them manually in the system.

A: I think you want Google Forms ... you take the survey data then it will automatically save it to Google Sheets. You can then install a ODBC driver that will take your Google Sheets and load it into Excel.


text:
Q: Customize Chrome webdriver using selenium to save files without prompting to save or discard files when downloading I am trying to automate downloading files using selenium with chrome as my browser using chromedriver. When i try downloading exe files its prompting me "This type of file can harm your computer, Discard or save it". i want it to download anyway without any prompt.
I have looked into few solutions like below:
chromeOptions = webdriver.ChromeOptions()
prefs = {"browser.helperApps.alwaysAsk.force" :False,"browser.helperApps.neverAsk.saveToDisk" : "application/octet-stream"}
chromeOptions.add_experimental_option("prefs",prefs)
browser = webdriver.Chrome(executable_path=//path//to//chrome_driver,   chrome_options=chromeOptions)

But this didn't help it still throws up the prompt.
Any help on this is greatly appreciated.
Thanks,

A: From what I understand, there is no way to tell Chrome not to warn on potentially dangerous binary file downloads, see:

*

*ChromeDriver has no way to accept dangerous downloads (Archived)

*Add option to automatically accept dangerous downloads (Wontfix)

As the simplest workaround, you might want to approach the problem with Firefox:

Also there have been numerous requests from dev community to allow to
  disable this warning to be able to run automated tests in Chrome. At
  the moment this is the only reason we're running our automated tests
  in Firefox only. Really annoying.


text:
Q: Sending email with gmail smtp with codeigniter email library <?php
class Email extends Controller {

    function Email()
    {
        parent::Controller();
        $this->load->library('email');
    }

    function index()
    {
        $config['protocol']    = 'smtp';
        $config['smtp_host']    = 'ssl://smtp.gmail.com';
        $config['smtp_port']    = '465';
        $config['smtp_timeout'] = '7';
        $config['smtp_user']    = 'mygmail@gmail.com';
        $config['smtp_pass']    = '*******';
        $config['charset']    = 'utf-8';
        $config['newline']    = "\r\n";
        $config['mailtype'] = 'text'; // or html
        $config['validation'] = TRUE; // bool whether to validate email or not

        $this->email->initialize($config);

        $this->email->from('mygmail@gmail.com', 'myname');
        $this->email->to('target@gmail.com');

        $this->email->subject('Email Test');
        $this->email->message('Testing the email class.');

        $this->email->send();

        echo $this->email->print_debugger();

        $this->load->view('email_view');
    }
}

I am getting this error:
A PHP Error was encountered
Severity: Warning
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gmail.com:465 (Connection timed out)
Filename: libraries/Email.php
Line Number: 1641

Using PORT 25/587
I got this error:
A PHP Error was encountered
Severity: Warning
Message: fsockopen() [function.fsockopen]: SSL operation failed with code 1. OpenSSL Error messages: error:140770FC:SSL routines:func(119):reason(252)
Filename: libraries/Email.php
Line Number: 1641

I don't want to use phpmailer now. (Actually I have tried to use phpmailer, but I failed).
How do I solve this problem guys?

A: Change it to the following:
$ci = get_instance();
$ci->load->library('email');
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.gmail.com";
$config['smtp_port'] = "465";
$config['smtp_user'] = "blablabla@gmail.com";
$config['smtp_pass'] = "yourpassword";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";

$ci->email->initialize($config);

$ci->email->from('blablabla@gmail.com', 'Blabla');
$list = array('xxx@gmail.com');
$ci->email->to($list);
$this->email->reply_to('my-email@gmail.com', 'Explendid Videos');
$ci->email->subject('This is an email test');
$ci->email->message('It is working. Great!');
$ci->email->send();

A: send html email via codeiginater
    $this->load->library('email');
    $this->load->library('parser');

    $this->email->clear();
    $config['mailtype'] = "html";
    $this->email->initialize($config);
    $this->email->set_newline("\r\n");
    $this->email->from('email@example.com', 'Website');
    $list = array('xxxxxxxx@archmage.lk', 'xxxxx@gmail.com');
    $this->email->to($list);
    $data = array();
    $htmlMessage = $this->parser->parse('messages/email', $data, true);
    $this->email->subject('This is an email test');
    $this->email->message($htmlMessage);

    if ($this->email->send()) {
        echo 'Your email was sent, thanks chamil.';
    } else {
        show_error($this->email->print_debugger());
    }

A: According to the CI docs (CodeIgniter Email Library)...

If you prefer not to set preferences using the above method, you can
  instead put them into a config file. Simply create a new file called
  the email.php, add the $config array in that file. Then save the file
  at config/email.php and it will be used automatically. You will NOT
  need to use the $this->email->initialize() function if you save your
  preferences in a config file.

I was able to get this to work by putting all the settings into application/config/email.php.
$config['useragent'] = 'CodeIgniter';
$config['protocol'] = 'smtp';
//$config['mailpath'] = '/usr/sbin/sendmail';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = 'YOUREMAILHERE@gmail.com';
$config['smtp_pass'] = 'YOURPASSWORDHERE';
$config['smtp_port'] = 465;
$config['smtp_timeout'] = 5;
$config['wordwrap'] = TRUE;
$config['wrapchars'] = 76;
$config['mailtype'] = 'html';
$config['charset'] = 'utf-8';
$config['validate'] = FALSE;
$config['priority'] = 3;
$config['crlf'] = "\r\n";
$config['newline'] = "\r\n";
$config['bcc_batch_mode'] = FALSE;
$config['bcc_batch_size'] = 200;

Then, in one of the controller methods I have something like:
$this->load->library('email'); // Note: no $config param needed
$this->email->from('YOUREMAILHERE@gmail.com', 'YOUREMAILHERE@gmail.com');
$this->email->to('SOMEEMAILHERE@gmail.com');
$this->email->subject('Test email from CI and Gmail');
$this->email->message('This is a test.');
$this->email->send();

Also, as Cerebro wrote, I had to uncomment out this line in my php.ini file and restart PHP:
extension=php_openssl.dll

A: You need to enable SSL in your PHP config. Load up php.ini and find a line with the following:
;extension=php_openssl.dll
Uncomment it. :D
(by removing the semicolon from the statement)
extension=php_openssl.dll

A: $config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'xxx',
    'smtp_pass' => 'xxx',
    'mailtype'  => 'html',
    'charset'   => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$result = $this->email->send();

From the CodeIgniter Forums

A: Another option I have working, in a linux server with Postfix:
First, configure CI email to use your server's email system: eg, in email.php, for example
# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';

Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd
(docs)
This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.

A: Perhaps your hosting server and email server are located at same place and you don't need to go for smtp authentication. Just keep every thing default like:
$config = array(
    'protocol' => '',
    'smtp_host' => '',
    'smtp_port' => '',
    'smtp_user' => 'yourname@gmail.com',
    'smtp_pass' => '**********'
    );

or
$config['protocol'] = '';
$config['smtp_host'] = '';
$config['smtp_port'] = ;
$config['smtp_user'] = 'yourname@gmail.com';
$config['smtp_pass'] = 'password';

it works for me.

A: It can be this:

If you are using cpanel for your website smtp restrictions are problem
  and cause this error. SMTP Restrictions

Error while sending an email with CodeIgniter

A: There  is very simple answer to this . and the only solution that worked at the en was this configuration ..i only had to chnage the port to 587 and overwrite the codeignitor default "Email.php"
$config = array( 'protocol' => 'smtp', 'smtp_host' => 'smtp.gmail.com', 'smtp_port' => 587, 'smtp_user' => 'admin@cafeadmin.com.au', 'smtp_pass' => '1800@Footscray123!' );$this->load->library('email', $config);$this->email->initialize($config);


text:
Q: Issues with declaring and writing to arrays with Arduino and C++ I'm messing around with an Arduino board for the first time.
I have an array declared like this (I know don't judge me), it's for storing each character of the LCD as a sort of cache:
char* lcd_characters[] = {"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""};

Then later on I'm trying to write to a specific slot of the array, like this, to save that letter to it:
new_char = String(message.charAt(i));

...blah blah blah...
lcd_characters[pos] = new_char; << error here

However it is giving me this error:
error: cannot convert 'String' to 'char*' in assignment

The funny thing is when I do this (below) it do assign the letter to it, however I have a var which is a single letter but can't assign it.
lcd_characters[pos] = "H";

Can someone help me out please. Thanks. I'm brand new to C and been ok so far.
Basically I want an  array of characters and then I want to write on the array positions with a new value.
Why does it even matter what type of string I'm writing to that array position, I should be able to write a number or boolean there too and call it later. Is there something wrong with the way the array is declared initially?
Edit:
I tried...
lcd_characters[pos] = new_char.c_str();

however that's giving me the similar error:
invalid conversion from 'const char*' to 'char'

Wtf? All I want to do is say this array position equals this new value. That's it. I've done this a million times in javascript, ruby, python (even php) etc. I just want to go, this array... x[12] equals my letter in new_char !!!! Ahh.

A: A few remarks:

*

*Are you using C or C++? String is a C++ class, but you are creating a an array of c strings (char *).

*You are creating an array of strings (char* var[] equals to char**), but your naming suggests you want an array of characters. A c string is basically an array of characters, so stick with that (char * or char []).
I would recommend you go for only C code in this case:
char lcdChars[4] = {' ', ' ', ' ', ' '}; // init with spaces
lcdChars[2] = 'x'; // write x to position 3

Note: A string in C++ can output a C string (char *) by calling stringInstance.c_str().


text:
Q: TSQL: Need help optimizing this two-part record I'm trying to build a view that I can use throughout our system that returns a standardized list of users and their access.
Table: Users
UserID    UserName     IsAdmin
----------------------------------
1         John         0
2         Jane         1
3         Mary         0

Table: Clients
ClientID  ParentClientID     ClientName
----------------------------------
1         NULL               Pepsico
2         1                  Pizza Hut
3         1                  Taco Bell
4         1                  KFC
5         NULL               McDonalds

Table: UsersInClients
UserID    ClientID
----------------------------------
1         2
1         3
2         1
3         5

My desired output:
UserID    ClientID
----------------------------------
1         2 --User 1 & 3 are not admins so list only includes IDs in UsersInClients table.
1         3
2         1 --If Users.IsAdmin = 1, it should return
2         2 --all parent client and all child clients,
2         3 --one row per client like this.
2         4
3         5

The only way I can think of doing this is using CTEs and temp tables, cursors, etc, but I was hoping this could be a view so I could join to it in my queries.  Can this be done?
Thanks guys

A: You can do this in the following way, with a UNION of two queries.
(There may be a way to do this all in a single JOIN condition but this is easier to debug.)
SELECT UserId, ClientID
FROM UsersInClients Uic  INNER JOIN Users U ON Uic.UserId = U.UserID
INNER JOIN Clients C ON (C.ClientID = Uic.ClientID OR C.ParentClientID = Uic.ClientID)
WHERE U.IsAdmin = 1

UNION ALL

SELECT UserId, ClientID
FROM UsersInClients Uic  INNER JOIN Users U ON UIC.UserId = U.UserID
INNER JOIN Clients C ON C.ClientID = Uic.ClientID
WHERE U.IsAdmin = 0

A: If you have an unbounded hierarchy, your solution is going to be a CTE.
WITH T AS
(
    SELECT UC.UserId, UC.ClientId, U.IsAdmin
    FROM UsersInClient UC
    INNER JOIN Users U
      ON UC.UserId = U.UserId
  UNION ALL
    SELECT T.UserId, C.ClientId, T.IsAdmin
    FROM T
    INNER JOIN Clients C
      ON T.ClientId = C.ParentClientId AND T.IsAdmin = 1
)
SELECT * FROM T

And by the way this could be a view.


text:
Q: Oracle Dynamic Sampling The optimizer will attempt to use default database statistics in preference to dynamic statistics. In some cases, oracle will auto use dynamic statistics.

*

*parallel execution

*missing statistics

*stale statistics

*insufficient statistics

*have sql plan directives

My question is if a SQL statement with highly selective filters on column that has missing index statistics, will it benefit from dynamic sampling?

A: The amount of benefit from dynamic sampling will depend on the degree of cardinality estimate errors and how the query plan changes after you correct those errors. It is possible that your query will benefit and a good next step for you is to add a DYNAMIC_SAMPLING hint in your query and to observe how the EXPLAIN PLAN changes. However, a better solution would be to just fix your statistics. All queries will benefit from that instead of just the ones that you tune by hand.
In the workloads that I've observed, the queries that benefit the most from dynamic sampling go the other way: the optimizer estimates that very few rows will be returned from a large table which leads to nested loop joins and index use throughout the plan. If the optimizer knew that the large table returned many rows it would pick a better plan. Suppose the following query returns 100% of the data in X_TABLE:
SELECT COUNT(*)
FROM X_TABLE
WHERE NULLIF(X_COLUMN.NETWORKED_ID, 'X') IS NOT NULL;

On my machine Oracle uses a cardinality estimate of 5% of the rows from the table. This is a default cardinality estimate used in some cases when the optimizer doesn't have enough information. If I add a dynamic sampling hint then the estimate is fixed:
SELECT /*+ DYNAMIC_SAMPLING(X_TABLE 10) */ COUNT(*)
FROM X_TABLE
WHERE NULLIF(X_COLUMN.NETWORKED_ID, 'X') IS NOT NULL;

My rule of thumb is to use a sampling level of 10 for small tables and to use something less than 10 for larger tables. If you use 10 then Oracle will read all blocks from the table before generating an EXPLAIN PLAN.


text:
Q: How to do a Vlookup for each row in Google Sheets? I'm creating a Google Sheets to track scores in an event. I have a sheet for each day where we write the name of each player that played that day and the result of each game in which he played. There's a last column with that total.
I'm trying to create a sheet that would centralize all the important results. For now, I can get all the players name but my issue is to get their totals.
I managed to get more or less the result that I want with:
=IF(COUNTIF('05-11'!$A$2:$A$35;$A2)>0;VLOOKUP($A2;'05-11'!$A$2:$R$35;17;false);)

The issue is that I need to drag the formula on each row. I would like to write a formula that could insert in the first cell an that would query all totals in the cells below.
I think I need something like this but it returns a Value Error:
=QUERY('05-11'!A2:R;"SELECT R WHERE A MATCHES "&A2:A;)

Keeping in mind that all the players that appears in that centralizing sheet might not have participate that day.
Here's an example of the document with some data: https://docs.google.com/spreadsheets/d/1twyIsHxc1YcTxFjWq8JzOAC1lUKO04j_qNhX2a9y8Vg/edit?usp=sharing

A: in your test sheet:
=QUERY(Tableau!A1:F; "SELECT A,B WHERE NOT B MATCHES "&TEXTJOIN("|"; 1; C2:C); 1)

should be:
=QUERY(Tableau!A1:F; "SELECT A,B WHERE NOT B MATCHES '"&TEXTJOIN("|"; 1; C2:C)&"'"; 1)

in your Calc Points sheet use this in C2 and drag to the right (ofc after you delete all formulae in C2:Z range:
=ARRAYFORMULA(IFNA(VLOOKUP($A2:$A; INDIRECT(REGEXEXTRACT(TO_TEXT(C1); "\d+-\d+")&"!A2:R41"); 18; 0)))


text:
Q: I am getting Xcode build errors as soon as I insert NSManagedObject in Swift4.2 on Xcode 10.2 Every time I add NSManagedObject subclass to a vanilla app (with CoreData enabled) or to a vanilla app without CoreData enabled at the start but added after, Xcode (10.2.1) / Swift (4.2) is throwing up 3 errors.
I'm trying to create a simple application in Xcode v10.2 (have just updated to 10.2.1) that uses Core Data.  I have tried to do this by two methods ie. starting a brand new app and ensuring Core Data is ticked, and also starting a vanilla app without Core Data ticked and then adding Core Data.  The issue I'm having is occurring after I create an entity and some entity attributes (everything compiles fine up to that point every time), however the issue occurs as soon as I go to add NSManagedObject subclass from the Editor dropdown.
As soon as I've added NSManagedObject, Xcode reindexes and I get 3 errors, two stating that "Multiple commands produce...." and another one that states Command CompileSwiftSources failed with a nonzero exit code.
I've tried to recreate the NSManagedObject, however that makes no difference.  I have followed the instructions to add a build statement (SWIFT_ENABLE_BATCH_MODE set to NO), but it makes no difference.
I'm not trying to do anything fancy here, just get to a point where I have NSManagedObject subclass enabled as part of CoreData so that I can get on and write the rest of my app on Xcode 10.2/Swift 4.2.
Also I have just updated to Xcode 10.2.1 which has made no difference ie. problem still occurs when you try and add the NSManagedObject subclass.
Any ideas anyone?
Screen shot of compiler errors

A: I've found the answer !!! The key is searching for the error on stack overflow for 'Build fails with "Command failed with a nonzero exit code" ' and within those answers there is a post from JeffreyWang23 on Sep16'18 that fixes this.
Link to resolution: stackoverflow.com/a/52357296/11407686 (All credit to the authors of the other article).
I just followed that advice to delete the Entity+CoreDataClass.swift and Entity+CoreDataProperties.swift from within Xcode, then under "class" of the entity model inspector, change "module" to Current Product Module and "codegen" to Manual/None, then recreate NSManagedObject.
All the errors then disappeared ! :) :) :)

A: for solve this issue you should Select the xcdatamodeld file in the project navigator, select the entity and press ⌥⌘3 (Data Model Inspector).
If you created the class manually the Codegen popup must be set to Manual/None otherwise the class file is created implicitly.
refer to this answer


text:
Q: How to get the average of a generic array list in java? i'm having trouble getting the average of a generic array list of type T.

A: You should use <T extends Number> generic signature to specify the type of the Number types, plus, you should use instanceof keyword. A simple dummy demo here;
Test Code
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<Integer>();
        List<Double> doubleList = new ArrayList<Double>();
        List<Float> floatList = new ArrayList<Float>();

        for(int i = 0; i < 10; i++)
        {
            integerList.add(new Integer(i+1));
            doubleList.add(new Double(i+1));
            floatList.add(new Float(i+1));
        }

        Utility<Integer>    utilityInteger  = new Utility<Integer>(integerList);
        Utility<Double>     utilityDouble   = new Utility<Double>(doubleList);
        Utility<Float>      utilityFloat    = new Utility<Float>(floatList);

        System.out.println("Integer average: " + utilityInteger.getAverage());
        System.out.println("Double average : " + utilityDouble.getAverage());
        System.out.println("Float average  : " + utilityFloat.getAverage());
    }

    public static class Utility<T extends Number>
    {

        // Fields
        private List<T> list;
        private Object  average;

        // Constructor
        @SuppressWarnings("unchecked")
        public Utility(List<T> list)
        {
            this.list = list;

            T sample = list.get(0);
            if(sample instanceof Double)
            {
                doAverageDouble((List<Double>) list);
            }
            else if (sample instanceof Integer)
            {
                doAverageInteger((List<Integer>) list);
            }
            else if (sample instanceof Float)
            {
                doAverageFloat((List<Float>) list);
            }
            else
            {
                throw new IllegalStateException("Constructor must be initialiez with either of Double, Integer or Float list");
            }
        }

        // Methods
        private void doAverageDouble(List<Double> list) {
            Double sum = new Double(0);

            for(Double d : list)
            {
                sum += d;
            }

            average = sum/new Double(list.size());
        }

        private void doAverageInteger(List<Integer> list) {
            Integer sum = new Integer(0);

            for(Integer d : list)
            {
                sum += d;
            }

            average = sum/new Integer(list.size());
        }

        private void doAverageFloat(List<Float> list) {
            Float sum = new Float(0);

            for(Float d : list)
            {
                sum += d;
            }

            average = sum/new Float(list.size());
        }

        Object getAverage()
        {
            return average;
        }

    }
}

Console Output
Integer average: 5
Double average : 5.5
Float average  : 5.5


text:
Q: WCF Emulate the Salesforce.com login service How would I accomplish what Salesforce.com does for logging in with WCF? I would like to have an authentication service that returns a token on a correct login. Then, each set of service calls would pass the token back. I don't want to pass the token on each method call.
What is throwing me is how the session header is part of the binding.
I am also looking for why this is or isn't a good idea. I think it is clean and simple.
Thanks!
 // Create service object

  binding = new SforceService();
  // Invoke the login call and save results in LoginResult

  LoginResult lr = binding.login("username","password");
  if (!lr.passwordExpired) {
  // Reset the SOAP endpoint to the returned server URL

  binding.Url = lr.serverUrl;
  // Create a new session header object

  // Add the session ID returned from the login

  binding.SessionHeaderValue = new SessionHeader();
  binding.SessionHeaderValue.sessionId = lr.sessionId;
  GetUserInfoResult userInfo = lr.userInfo;
  } else {
    Console.WriteLine("Your password is expired.");
  }

A: I believe you are looking to leverage the Windows Identity Foundation and it's Security Token Service / STS model.


text:
Q: Count a list of specific strings in an R data frame I have a data frame with 5 columns, but I am interested in one column "Conditions". Within conditions column, I need to find a way to count the number of specific entries in a cell. Each column cell can have one entry or more than one entry separated by ( , ) . So my data frame looks something like
S.NO                   Conditions
11            Eye Color
12            Sound of your voice
13            Certain disease,Size of a palm,Eye Color
16            Eye Color,Hair color
17            Hair color,Height
18            Sound of your voice,Height

I want to count all the differnt entries/string at once.  Total I have 35 list of different string in Conditions column and I want my Output something like this.
OUTPUT
Eye color   Sound of your voice   Certain disease    Size of a palm    Hair color   Height
    3           2                      1                   1              2          2

A: Since i do not know the exact structure of the data, i assumed the data to be as below
data
data <- tribble(
~Conditions, ~value,
'Eye color', '3',
'Sound of your voice', '2',
'Certain disease, Size of a palm, Eye color', '1,1,2',
'Eye color, Hair color', '2,2',
'Hair color, Height', '3,1',
'Sound of your voice, Height', '1,4'
)

for the above data we can write the below code to get the expected result
code
library(tidyverse)

Conditions <- unlist(strsplit(data$Conditions,','))
value <- unlist(strsplit(data$value,','))

df <- bind_cols(Conditions,value) %>% setNames(c('Conditions', 'value')) %>%
mutate(across(everything(), ~trimws(.x)), value=as.numeric(value)) %>%
  arrange(Conditions) %>% group_by(Conditions) %>% slice_head(n=1) %>%
mutate(row=row_number()) %>%
  pivot_wider(names_from = Conditions, values_from =value)

output
# A tibble: 1 × 7
    row `Certain disease` `Eye color` `Hair color` Height `Size of a palm` `Sound of your voice`
  <int>             <dbl>       <dbl>        <dbl>  <dbl>            <dbl>                 <dbl>
1     1                 1           3            2      1                1                     2


text:
Q: How do I become better in math, after being a programmer for several years
Possible Duplicate:
How to improve my math skills to become a better programmer
Basic Math Book for a Programmer

I've had quite a weird career till now.
First I graduated from a medical school. Then I went into marketing (pharmaceuticals).
And then umm, after some time, I decided to go for my (till then) hobby and became a "professional" programmer.
I've been quite successful at this ever since. I have quite some languages "under my belt". I earn not bad and I have been involved in the opensource community quite heavily.
The thing is that I suck at math :). Well, not totally of course, as I get my work done. But I don't know how much I suck. And I don't know how to find out.
Math has never really been of any priority during my middle/high school years. I only picked as little as I could afford, because I was always getting ready to go for Medicine. Of course I know the basics of algebra. Things like "normal" and square equations. Also the basics of geometry. But well, there are things that I have missed.
And lately I am being fascinated by things like probability theory, infinity, chaos/order etc. But every time I try to learn something about these topics, I hit a wall of terminology, special symbols, and some special kind of thinking, that is quite like mine (a programmer), but also a lot different (and appears weird to me).
So, what kinds of books would you recommend me? It's very hard to find something suitable. All that I find are either too easy (and boring) or totally impenetrable.

A:
Of course I know the basics of
  algebra. Things like "normal" and
  square equations. Also the basics of
  geometry. But well, there are things
  that I have missed. And lately I am
  being fascinated by things like
  probability theory, infinity,
  chaos/order etc.

I find that mathematics is a one-way door: if you don't get through early, it's hard to go back.  It's not impossible to pick up, but it is more difficult without discipline.
The key is doing problems.  You don't just read math books - you do problems to work the mechanics into your brain.  If you're just reading, I'd say it's impossible to learn it.
Best to go back to what you know and work up.  If you feel okay about basic algebra and geometry, start thinking about intro calculus or statistics.  Start with the basic stuff: one variable differential and/or integral calculus or statistics.  Do a lot of problems and get comfortable.
If you're a computer scientist, you'll find discrete math, graphs, numerical methods, and linear algebra helpful.
Don't expect to do it quickly, especially if you're casual about it.
I'd recommend two wonderful resources:

*

*Verzani - Using R for Introductory Statistics

*Gil Strang MIT Linear Algebra
Both are free; both are excellent.

A: Assuming you have your basic algebra down, I'd start with single variable calculus.  I've used several calc books, and found Larson's to be the best.  Hope you can find it at a library.
Move on to linear algebra shortly after.  This book is free and very good.
Don't worry about mastering everything, you'll probably want to come back to linear algebra.
Then find a book that emphasizes proofs, sets, relations, functions, and axioms.  I liked Analysis with an introduction to proof by Lay.  Learn proof by induction especially well.
From here, you should be able to break that impenetrable wall you've found yourself against.  You will be armed with the terminology to read just about any undergraduate mathematics textbook.
I recommend graph theory, combinatorics, and linear algebra, for their applications in computer science.
Good luck!

A: The basics:

*

*Basic understanding of real and complex numbers, functions, sets etc.

*(Real) analysis in one variable

*(Real) linear algebra

*(Real) analysis in several variables

*Discrete mathematics

*Vector calculus

*Complex analysis

*Complex linear algebra

*Statistics and probability theory

More advanced stuff:

*

*Abstract algebra

*Fourier analysis (much more important than one may think) (Basic video course from Stanford)

*Transform theory (other than Fourier analysis)

*Differential geometry

*Functional analysis

*Partial differential equations

*Non-linear phenomena and chaos

A: You might check out some of the free course material available online from MIT.

A: Investigate available math classes at a local junior college. Typically, they offer them during the day for enrolled students but they sometimes have night classes as well. Talk to the professor to see if your math skills are sufficient for the class before enrolling, however, or you'll be struggling right out of the gate.