text:
Q: Dialog.dimiss() not working So I have a dialog that opens that should close when the exit button is clicked. It seems to close quickly and then comes back again. It is as if a second dialog is opened once I dismiss the first one. Anyone have any ideas?
(Edited to include more code)
This is my dialog code:
    buildMoreButton = (Button) findViewById(R.id.buildMore);
    buildMoreButton.setText("BUILD");
    buildMoreButton.setBackgroundColor(-65536);
    buildMoreButton.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                buildMoreButton.setBackgroundColor(-1);
            }//end if
            else if (event.getAction() == MotionEvent.ACTION_UP)
            {
                buildMoreButton.setBackgroundColor(-65536);
            }//end else if

            //open dialog for building choices
            buildingSelect = new Dialog(runGraphics.this);
            buildingSelect.setContentView(R.layout.dialog);
            buildingSelect.setTitle("Building Selection");

            exit = (Button) buildingSelect.findViewById(R.id.exit);
            exit.setText("X");
            exit.setBackgroundColor(-65536);
            exit.setOnTouchListener(new OnTouchListener()
            {
                @Override
                public boolean onTouch(View v, MotionEvent event)
                {
                    if (event.getAction() == MotionEvent.ACTION_DOWN)
                    {
                        exit.setBackgroundColor(-1);
                    }//end if
                    else if (event.getAction() == MotionEvent.ACTION_UP)
                    {
                        exit.setBackgroundColor(-65536);
                        buildingSelect.dismiss();
                    }//end else if

                    return false;
                }//end onTouch
            });//end OnTouchListener

            colonyHut = (ImageView) buildingSelect.findViewById(R.id.colonyHut);

            buildingSelect.show();
            return false;
        }//end onTouch function

    });//end OnTouchListener

Any help is appreciated.
Not positive exactly why it seems that a second dialog is popping up when the dismiss is called.

A: Dismiss the Dialog when it detects the MotionEvent.ACTION_UP not after and before you clicked because you are calling dismiss twice.
solution:
  buildMoreButton = (Button) findViewById(R.id.buildMore);
    buildMoreButton.setText("BUILD");
    buildMoreButton.setBackgroundColor(-65536);
    buildMoreButton.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
            {
                buildMoreButton.setBackgroundColor(-1);
            }//end if
            else if (event.getAction() == MotionEvent.ACTION_UP)
            {
                buildMoreButton.setBackgroundColor(-65536);
            }//end else if

    });//end OnTouchListener

//open dialog for building choices
            buildingSelect = new Dialog(runGraphics.this);
            buildingSelect.setContentView(R.layout.dialog);
            buildingSelect.setTitle("Building Selection");

            exit = (Button) buildingSelect.findViewById(R.id.exit);
            exit.setText("X");
            exit.setBackgroundColor(-65536);
            exit.setOnTouchListener(new OnTouchListener()
            {
                @Override
                public boolean onTouch(View v, MotionEvent event)
                {
                    if (event.getAction() == MotionEvent.ACTION_DOWN)
                    {
                        exit.setBackgroundColor(-1);
                    }//end if
                    else if (event.getAction() == MotionEvent.ACTION_UP)
                    {
                        exit.setBackgroundColor(-65536);
                        buildingSelect.dismiss();
                    }//end else if

                    return false;
                }//end onTouch
            });//end OnTouchListener

            colonyHut = (ImageView) buildingSelect.findViewById(R.id.colonyHut);

            buildingSelect.show();
            return false;
    }//end onTouch function


text:
Q: Stepping Through Array & Returning Matched/Non-Matched Value in Array Based on Search Term In my searchForANumber method, I'm trying to display if a number is found within my array or not. The problem is, I'm using and if, else to determine if the searchValue matches a value in the array statement in my for loop, and when I do this, the last variable in the array is tested, and my returned value is based on only the final value. How can I make so that my return phrase is based on all elements in the array and not just the last one? Do I use a while, do-while, switch loop? Any help is appreciated.
    import java.util.Scanner;

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

    System.out.println("Enter your minimum number: ");
    int minNumber = input.nextInt();

    System.out.println("Enter your maximum number: ");
    int maxNumber = input.nextInt();

    int[] array = new int[(maxNumber-minNumber)+1];
    int[]readInArray = new int[maxNumber-minNumber+1];

    readInArray=readNumbers(minNumber, maxNumber, array);

    printNumbers(readInArray, minNumber);

    searchForANumber(readInArray, minNumber);

    sumNumbers(readInArray);

    printBackward(readInArray);

}//end of main method

private static void printBackward(int[] readInArray) {
    for (int i=(readInArray.length-1);i>0;i--){
        System.out.print(readInArray[i] + " ");
    }

}

private static void sumNumbers(int[] readInArray) {
    int total = 0;
    for (int i=0;i<readInArray.length;i++){

        total = total + readInArray[i];
    }
    System.out.println(total);

}

private static void searchForANumber(int[] readInArray, int minNumber) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter number to search for: ");
    int searchValue = input.nextInt();
    boolean returnValue = false;
    for (int i = 0; i < readInArray.length;i++) {
        if (searchValue == readInArray[i])
            returnValue=true;
            break;

    }// end of for
    System.out.println(returnValue);

}

private static void printNumbers(int[] readInArray, int minNumber) {
    for (int i = 0; i < readInArray.length;i++) {
        System.out.print(readInArray[i] + " ");
        minNumber++;
    }
    System.out.println(" ");

}

private static int[] readNumbers(int minNumber, int maxNumber, int[] array) {
    for (int i = 0; i < array.length;i++) {// input grades for each students
        array[i]=minNumber;
        minNumber++;
    } // end of for loop

    return array;
} // end of readArray method

}//end of class

A: you can do it in two ways.

*

*make your method searchForANumber return boolean.
private static boolean searchForANumber(int[] readInArray, int minNumber) {
//before for loop
for (int i = 0; i < readInArray.length;i++) {
    if (searchValue == readInArray[i])
        return true;
    }
return false;
}

*use break and a boolean
private static void searchForANumber(int[] readInArray, int minNumber) {
//before for loop
boolean found = false;
for (int i = 0; i < readInArray.length;i++) {
    if (searchValue == readInArray[i]){
       found = true;
       break;
      }
    }
if(found)
 System.out.println("Found");
else
 System.out.println("Not Found");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: LiveData - Using SingleLiveEvent with Transformations I am now using the recent Android Architecture Components and in particular the ViewModel and LiveData.
I am in a case where the SingleLiveEvent suggested here is relevant, i.e. I am returning an error and I want to display an alert only once. Before emitting a value to the Activity, I need to map my error to a more appropriate object for the view. I am using a Transformation for this.
So in the end, I have a ViewModel that looks like:
public LiveData<ViewState> getStateForView() {
    final LiveData<NetworkState> liveState = myRepository.getState();
    return Transformations.map(liveState, myMapper::map);
}

Where in my repository I am using a SingleLiveEvent:
public LiveData<NetworkState> getState() {
    myNetworkState = new SingleLiveEvent<>();
    return myNetworkState;
}

This works fairly well but I notice that my event is not propagated all the time when orientation changes multiple times. When debugging, I have noticed that there is no symmetry between the observer registration and removal:

*

*at registration time the observer of my SingleLiveEvent is the anonymous Observer class in my SingleLiveEvent

*

*at removal time the observer to be removed from my SingleLiveEvent is a MediatorLiveData (which is actually observing the earlier anonymous class in my SingleLiveEvent)

What happens is that my initial observer is never removed from the observers of the SingleLiveEvent (so if orientation changes multiple times my SingleLiveEvent has multiple observers).
I cannot figure out why this is not the same observer at removal time. When reproducing it without a Transformation step, there is no such issue.
Does anyone have a hint about this behaviour? Are SingleLiveEvent (not part of the framework) and Transformations not supposed to work together?

A: I have found out that this is due to the fact that Transformations use a MediatorLiveData, which uses the SingleLiveEvent as a referenced source. This source is used for registration and removal of itself as an observer.
However, the SingleLiveEvent introduces an intermediate observer at registration time. The SingleLiveEvent references this intermediate observer and does not know about the MediatorLiveData.
At removal time, the MediatorLiveData tries to unregister itself as an observer from the SingleLiveEvent. Since the SingleLiveEvent does not know about it, it keeps the intermediate observer.
In the end, the process is not symmetrical and over time (as the user turns the phone), the SingleLiveEvent has more and more observers.
I don't know if I missed something or if the MediatorLiveData is not to be used with SingleLiveEvent, but I found a solution for my specific problem.
I added a reference to the intermediate observer in the SingleLiveEvent and I have overriden its removeObserver() method to remove the intermediate observer and not (only) the MediatorLiveData. I am not so confident about this solution because I am not familiar with the internals of the LiveData. In  particular, this solution would only work if the SingleLiveEvent is used only with MediatorLiveData as observers (i.e. not if the Activity observes the SingleLiveEvent), and only if there is a single observer (which makes sense in the case of a SingleLiveEvent). There might be other limitations.
Here is the code I added to remove the right observer (singleLiveEventIntermediateObserver is the anonymous Observer instantiated in the observe() method):
@Override
public void removeObserver(@NonNull Observer<T> observer) {
    super.removeObserver(observer);
    if (this.singleLiveEventIntermediateObserver != null) {
        super.removeObserver(this.singleLiveEventIntermediateObserver);
    }
}


text:
Q: How to represent an empty IntSet in Haskell? As the title asks, how would I represent an empty IntSet?
For example, I know that an empty list is represented as []. I know that IntSet has type [(Int, Int)], and I was wondering what an empty IntSet would look like. I suppose it's not [()], nor [(,)].
Thanks!

A: If you have defined
type IntSet = [(Int, Int)]

as implied in the question (but why? what is the other Int for?), then the empty list is an empty IntSet:
empty :: IntSet
empty = []

Indeed, the empty list is an empty list of any type, including of the type [(Int, Int)].


text:
Q: Spline Interpolation with increased deviation in R I'm trying to effectively increase the temporal resolution of a daily time series data to 6-hourly time series (modeled weather data). I've been using na.spline from the zoo. Here is how I've been doing this:
library(zoo)
temp = c(260.9394, 264.3018, 270.2295,269.3193, 270.9833, 271.4790, 269.2528 ,271.5263, 271.0616, 263.4052, 260.7776 ,262.1539, 260.4698 ,259.6320 ,266.3442, 261.2173 ,253.5278, 252.5940 ,255.2761,253.0223, 255.4660, 258.4136, 268.4329 ,269.1272, 268.3249, 267.6087, 269.4851, 270.2795 ,266.0357 ,260.9807, 263.3990, 266.6847 ,266.0555, 268.3860 ,270.5075 ,270.7101, 266.2647, 263.1466, 261.3249, 264.5570 ,262.4109, 267.3654 ,268.7764, 269.1429 ,275.2494 ,276.8388, 276.0056, 282.2490 ,279.3987, 266.1445 ,263.2737,257.9539, 254.9523, 260.2066, 264.2155, 270.5643, 269.1971, 267.3094, 260.6333, 260.4092, 263.7590,267.1073, 269.1791, 268.7179, 268.1320, 258.5653, 256.9442, 260.8293,267.6224, 270.4454, 270.9205, 272.4834, 276.7073, 272.9083, 281.7278, 280.7053, 286.0500, 284.9832, 271.0922, 270.2727, 272.9502, 279.6241, 279.6601, 278.8676, 276.0311,278.0432, 276.0992, 273.0579, 275.3508, 276.2788, 274.1192, 274.7629, 276.9832, 280.6208, 270.1893, 265.8163, 268.5312, 273.1192, 271.2437, 273.2898, 274.9559, 271.3247,274.0296, 274.3720, 268.9793, 274.1874, 276.5400, 277.8003,272.9678,272.7812, 271.1283, 276.2137, 278.8361, 283.7280, 280.6618, 277.1862, 275.4617, 273.6890, 275.6335,275.7692, 278.0294,278.6085, 278.1408 ,278.5306 ,276.4064, 277.5828, 282.4601 ,286.0646, 285.5323 ,283.9420 ,280.9373, 283.5115 ,285.5747, 285.3726 ,284.7168, 283.4072,283.6460, 285.8925 ,287.7186 ,285.3997, 289.1151,289.2271, 293.4171, 289.7754 ,290.3863, 289.6272, 291.9551, 293.8194, 285.5756, 284.0607, 287.2251 ,290.9961 ,288.9530,288.9829, 289.4866, 293.2368 ,287.5108, 294.7983 ,296.1631,294.4269, 292.5922 ,286.9019, 282.8738, 283.4177, 285.9086, 285.5735, 286.2843 ,288.2936, 289.9575 ,287.3752,287.7389, 287.6944, 288.7362, 291.3151 ,292.0483, 295.6626 ,295.1491, 294.6186 ,295.1886, 295.6821, 294.5723, 295.5624, 296.3948, 297.0867, 294.7425, 293.2665, 295.3842,297.3065, 297.6444, 297.3771, 294.2589, 293.1402,297.9673, 303.8832, 300.2515, 294.8088, 292.9465, 294.5560, 293.5795, 291.2845, 292.0042, 292.8047, 292.5544, 291.4802,291.2924, 296.4316, 290.7670, 292.6044, 295.0291, 297.4236, 297.8194, 298.4617, 294.3469,290.6657, 291.5336, 296.0067, 295.8909, 294.7652, 295.9294, 297.0009 ,297.5438,297.5055, 299.8651, 296.5216 ,295.9416, 294.6706, 292.8246 ,295.4045, 291.9977 ,291.4641, 291.8502 ,292.5085, 292.4158, 294.8775, 292.9365, 294.1278, 294.0945, 292.2523,293.9971, 299.8319, 296.3214, 292.7899, 289.1313, 289.3746, 290.2141, 292.0596, 295.5131, 295.3895, 294.5305, 290.8510, 288.0043, 291.1497, 293.4218,291.4864,294.8860,296.5399,284.8989,286.2889,286.7507,283.6707,285.038,288.5444,290.2072,289.3766,288.4058,289.9024,287.7706,282.0836,279.6411,280.878,283.8073, 287.0587,282.0472, 279.3339, 278.4666, 279.7615, 277.9067, 277.3667, 277.5933,276.9392,277.3469,276.4537,277.2365,279.1784,281.6197,284.2389,283.7059 ,283.4021, 281.3361,280.0453, 281.8986 ,281.1670, 282.5850, 286.6981 ,281.8985 ,277.7366, 275.4608, 278.4460 ,282.3974, 282.1050, 279.2068, 278.6987, 274.1590, 268.1413 ,270.9254, 277.8294,283.1120 ,281.8789, 285.1766, 284.1758, 283.2682 ,276.6518, 270.9003,269.9474, 272.6488 ,272.3387, 273.6503, 276.1812, 276.1082, 277.7733, 279.2593, 280.6460, 278.0175,278.0469 ,278.6865, 275.7430, 273.8073, 276.0212, 275.1905, 272.0544, 262.0764, 261.9173, 260.7959, 265.9595, 262.9587, 259.9734, 258.0081, 256.6400, 253.1440, 253.5497,256.5918, 259.1784,263.0086,265.8650 ,263.2765 ,257.5844 ,259.9606 ,262.6104, 263.2550, 268.3223, 268.7100, 266.7353, 264.8430, 262.4933, 259.9666 ,262.5295 ,260.8611,256.8401 ,259.5594, 264.9890, 264.5033 ,268.2536 ,271.1512, 268.5712 ,267.4058)

temp = data.frame(temp)
six_hour = data.frame()

#Place 3 NAs in between each daily value from temp
for (x in seq(from=0, to=1460, by=4)){
   six_hour[x,1] = temp[x/4,1]}

spline.met = list()
spline.met = na.spline(six_hour)
spline.met = data.frame(spline.met)

I'm working with modeled data above. While this is a quick and dirty way, it doesn't have the same variability or random deviation that observed data will show. For example, if I look at a real dataset complete with observed 6 hourly values from the same location, it will show much greater variability. For this, I will average my observed dataset for each day, then go through the code above to show the differences between actual 6 hour data and spline interpolated data. (I can only show half of a year though due to R list limits)
obs = c(0,53,70,0,0,40,38,0,0,28,27,0,0,16,23,0,0,28,30,0,0,36,27,0,0,15,32,0,0,55,38,0,0,62,143,0,0,200,190,0,0,134,176,0,0,129,131,0,0,39,109,0,0,162,138,0,0,131,137,0,0,26,31,0,0,31,43,0,0,123,211,0,0,39,29,0,0,45,94,0,0,214,196,0,0,42,28,0,0,228,167,0,0,66,85,0,0,194,235,0,0,206,231,0,0,203,227,0,0,169,84,0,0,28,49,0,0,83,79,0,0,150,129,0,0,42,49,0,0,128,236,0,0,23,42,0,0,74,124,0,0,129,230,0,0,256,292,0,0,219,263,0,0,176,291,0,0,175,207,0,0,59,50,0,0,149,120,0,0,112,179,0,0,140,298,0,0,107,130,0,0,315,267,0,0,83,75,0,0,281,331,0,0,322,352,0,0,328,352,0,0,332,327,0,0,311,305,0,0,147,272,0,0,234,348,0,0,104,90,0,0,344,373,0,0,300,223,0,0,234,383,0,0,271,349,0,0,208,221,0,0,220,314,0,0,125,279,0,0,386,397,0,0,160,119,0,0,185,122,0,0,142,261,0,0,90,129,0,0,287,336,0,0,357,357,0,0,353,245,0,0,376,209,0,0,42,135,0,0,166,219,0,0,412,420,0,0,392,413,0,0,444,474,0,0,460,479,0,0,470,478,0,0,457,461,0,0,441,476,0,0,463,401,0,0,228,175,0,0,240,246,0,0,246,287,0,0,491,506,0,0,491,482,0,0,493,495,0,0,484,490,0,0,184,111,0,0,106,180,0,0,131,426,0,0,66,63,0,0,491,537,1,1,544,539,1,2,534,323,0,0,232,300,0,2,420,562,2,2,560,523,2,2,483,352,1,0,397,507,2,2,482,272,0,0,446,453,3,5,337,163,3,4,543,498,3,4,550,505,2,2,493,558,2,5,590,571,4,4,584,562,3,2,288,283,4,7,204,326,9,0,187,301,1,5,236,220,5,2,186,505,6,7,353,171,1,11,637,614,7,10,622,581,8,10,621,590,7,11,584,390,2,3,251,191,1,0,78,40,0,0,52,63,1,3,160,315,5,4,565,618,9,16,430,328,3,5,225,312,8,16,393,502,4,16,623,255,10,17,159,85,4,1,97,200,2,10,300,448,10,3,98,104,1,4,160,94,5,2,127,182,7,6,381,187,2,6,174,185,9,13,247,467,16,6,541,580,11,7,422,617,11,10,535,646,16,24,412,340,19,26,708,569,18,26,681,652,19,30,656,626,13,16,353,406,3,5,240,338,23,19,535,436,17,17,531,371,5,13,580,621,17,24,638,577,7,0,465,479,9,25,604,593,21,16,532,489,17,28,669,611,22,28,690,530,21,30,692,656,22,26,654,449,11,10,154,321,11,27,652,648,21,30,691,672,21,26,578,278,9,32,687,669,22,21,668,568,19,32,669,560,20,10,446,342,17,25,629,622,25,18,530,464,15,16,599,526,11,23,560,512,11,9,516,597,26,30,340,529,26,31,504,211,7,14,585,559,19,28,524,661,28,30,672,644,18,4,355,363,14,3,343,620,33,29,673,635,20,4,504,419,16,17,264,615,26,22,635,584,23,18,595,580,14,3,384,458,26,23,655)

obs = data.frame(obs)
reso = floor(365/2)
step = 4
daily.obs = data.frame()
for (x in 1:reso){
  daily.obs[x,1] <- mean(obs[(x*step-step+1):(x*step),1])}
tem.obs = data.frame()
for (x in seq(from=0, to=732, by=4)){
  tem.obs[x,1] = daily.obs[x/4,1]}

spline.obs = list()
spline.obs = na.spline(tem.obs[1])
spline.obs = data.frame(spline.obs[1:730])

Now if we plot up the comparison between observed and spline interpolated..
plot(obs$obs,type = 'l', col = "blue")
lines(spline.obs, col = "red")
legend("topleft", legend =  c("Spline Interpolation","Observations"), cex     =0.8, col=c("red","blue"), lty=1:1)

We can clearly see some differences. Is there any way to alter the spline function to increase it's variability/deviation to capture more of the randomness associated with real data? Is there another package I could be using to tackle this problem?
Note: I do not have access to the original modeling code and cannot increase the resolution of the actual model. I must downscale the product of the model.


text:
Q: is there a faster way to remove all keyup eventListeners on a document i have a function that removes and adds keyup listeners to a webpage
function addFunc1() {
  document.addEventListener('keyup', func1);
  document.removeEventListener("keyup", func2);
  document.removeEventListener("keyup", func3);
  document.removeEventListener("keyup", func4);
  document.removeEventListener("keyup", func5);
  document.removeEventListener("keyup", func6);
  document.removeEventListener("keyup", func7);
}
function addFunc2() {
  document.addEventListener("keyup", func2);
  document.removeEventListener('keyup', func1);
  document.removeEventListener("keyup", func3);
  document.removeEventListener("keyup", func4);
  document.removeEventListener("keyup", func5);
  document.removeEventListener("keyup", func6);
  document.removeEventListener("keyup", func7);
}
function addFunc3() {
  document.addEventListener("keyup", func3);
  document.removeEventListener('keyup', func1);
  document.removeEventListener("keyup", func2);
  document.removeEventListener("keyup", func4);
  document.removeEventListener("keyup", func5);
  document.removeEventListener("keyup", func6);
  document.removeEventListener("keyup", func7);
}
...etc

but im wondering if there is a faster way to remove them? because i think its very slow if i remove them one by one
i tried searching but only found solutions with cloneNode like this to remove all event handlers in an element
var clone = element.cloneNode(true);

but i dont think this will work for what i want
this question has probably been asked before but i just couldn't find it
Thanks in advance

A: Put the functions into an array
const fns = [func1, func2, ...];

Then instead of
function addFunc1() {

function addFunc2() {

do
function addFunc(indexToAdd) {
  for (const fn of fns) {
    document.removeEventListener("keyup", fn);
  }
  document.addEventListener("keyup", fns[indexToAdd]);
}
addFunc(0);
// or
// addFunc(1);

Another approach would be to have only a single function, active all the time, and you reassign the active index:
let activeIndex = 0; // for example: have keyups run the first function
document.addEventListener('keyup', () => {
  fns[activeIndex]();
});

Then to, for example, switch to func3 instead of func1, just do
activeIndex = 2;


text:
Q: opennlp Span class in eclipse java I am new to java opennlp and i am trying to implement a program that extracts city names from a file but i am testing my code on a string first and i get some errors
the code is
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;

 import main.java.opennlp.tools.namefind.NameFinderME;
 import main.java.opennlp.tools.namefind.TokenNameFinderModel;
 import main.java.opennlp.tools.util.InvalidFormatException;
 import main.java.opennlp.tools.util.Span;
 import opennlp.tools.tokenize.Tokenizer;
 import opennlp.tools.tokenize.TokenizerME;
 import opennlp.tools.tokenize.TokenizerModel;
 import opennlp.tools.tokenize.SimpleTokenizer;
 import opennlp.tools.sentdetect.SentenceDetectorME;
 import opennlp.tools.sentdetect.SentenceModel;

  import org.xml.sax.SAXException;

 public class CityFinder {

public String Tokens[];

public static void main(String[] args) throws IOException, SAXException {

    CityFinder toi = new CityFinder();
    String cnt;
    cnt="John is planning to specialize in Electrical Engineering in UC Berkley and  pursue a career with IBM.";
    toi.tokenization(cnt);
    String cities = toi.namefind(toi.Tokens);
    String org = toi.orgfind(toi.Tokens);

    System.out.println("City name is : "+cities);
    System.out.println("organization name is: "+org);

}
    public String namefind(String cnt[]) {
    InputStream is;
    TokenNameFinderModel tnf;
    NameFinderME nf;
    String sd = "";
    try {
        is = new FileInputStream("en-ner-location.bin");
        tnf = new TokenNameFinderModel(is);
        nf = new NameFinderME(tnf);
        Span sp[] = nf.find(cnt);
        StringBuilder fd = new StringBuilder();
        int l = a.length;

        for (int j = 0; j < l; j++) {
            fd = fd.append(a[j] + "\n");

        }
        sd = fd.toString();

    } catch (FileNotFoundException e) {

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

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

        e.printStackTrace();
    }
    return sd;
}

public String orgfind(String cnt[]) {
    InputStream is;
    TokenNameFinderModel tnf;
    NameFinderME nf;
    String sd = "";
    try {
        is = new FileInputStream("en-ner-organization.bin");
        tnf = new TokenNameFinderModel(is);
        nf = new NameFinderME(tnf);
        Span sp[] = nf.find(cnt);
        String a[] = Span.spansToStrings(sp, cnt);
        StringBuilder fd = new StringBuilder();
        int l = a.length;
        for (int j = 0; j < l; j++) {
            fd = fd.append(a[j] + "\n");

        }

        sd = fd.toString();

    } catch (FileNotFoundException e) {

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

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

        e.printStackTrace();
    }
    return sd;

}
public void tokenization(String tokens) {

    InputStream is;
    TokenizerModel tm;
    try {
        is = new FileInputStream("en-token.bin");
        tm = new TokenizerModel(is);
        Tokenizer tz = new TokenizerME(tm);
        Tokens = tz.tokenize(tokens);
        // System.out.println(Tokens[1]);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

  }

and the errors i am getting with the span verialble
    Span sp[] = nf.find(cnt);
the error is Type mismatch: cannot convert from opennlp.tools.util.Span[] to main.java.opennlp.tools.util.Span[]
I don't know how to solve it in both locations
Any suggestions....??
thanks in advance

A: You should import all your classes from the packages within opennlp.tools package.
 import opennlp.tools.namefind.NameFinderME;
 import opennlp.tools.namefind.TokenNameFinderModel;
 import opennlp.tools.util.InvalidFormatException;
 import opennlp.tools.util.Span;


text:
Q: Bias variance tradeoff of ridge regression with independent but non identically distributed error? I am trying to figure out how the solution for ridge regression changes when the error term is independent but NOT identically distributed such as  $\mathbb\epsilon = \mathcal{N}(0, \Sigma)$ rather than $\mathbb\epsilon = \mathcal{N}(0, \sigma^{2})$
In standard ridge regression we have:
$$\hat \beta(\lambda) = \arg\min_{\beta}\left\{\frac 1 n \sum_{i=1}^n (y_i -x_i^T \beta)^2 + \lambda \|\beta\|_2^2\right\}$$
which can be solved as:
$$\hat\beta(\lambda) = (X^TX + \lambda I)^{-1} X^T y$$
when we use $\mathbb\epsilon = \mathcal{N}(0, \sigma^{2})$.
I am struggling with how to determine the difference when one would assume $\mathbb\epsilon = \mathcal{N}(0, \Sigma)$ instead.  My initial thought was it would be:
$$\hat\beta(\lambda) = (X^TX + \lambda \Sigma)^{-1} X^T y$$
but I think I am off track there.  In the end I want to calculate MSE, Bias and Varience using this alternate error distribution as described here,
Ridge Regression: how to show squared bias increases as $\lambda$ increases

A: To be clear, the solution to the ridge problem
$$ \min_{\beta}\left\{\frac 1 n \sum_{i=1}^n (y_i -x_i^T \beta)^2 + \lambda \|\beta\|_2^2\right\}$$
does not depend on the distribution of the error. Use, e.g., standard calculus to see this. This means that you do not have to modify the estimator if the error is not identically distributed. Sure, its theoretical properties may change but the estimator will remain the same.

A: As JohnK noted, the optimization problem that defines the ridge regression estimator can be defined without making any distributional assumptions on the noise; in particular the solution $\hat{\beta}_r = (X^\top X + \lambda I)^{-1} X^\top y$ remains the same.
I'll use the same notation $K = (X^\top X + \lambda)^{-1} X^\top X$ and $\hat{\beta} = (X^\top X)^{-1} X^\top y$ as in the answer you linked.
The bias term does not change, since the only information about $\epsilon$ that you use in that computation is $E[\epsilon] = 0$.
The variance term does depend on $\Sigma$. Specifically,
$$\hat{\beta}_r - E[\hat{\beta}_r] = K(\hat{\beta} - E[\hat{\beta}])
= K(X^\top X)^{-1} X^\top \epsilon$$
and
\begin{align}
E[(\hat{\beta}_r - E[\hat{\beta}_r])^\top (\hat{\beta}_r - E[\hat{\beta}_r])]
&= E[\text{tr}((\hat{\beta}_r - E[\hat{\beta}_r])(\hat{\beta}_r - E[\hat{\beta}_r])^\top)]
\\
&= E[\text{tr}(K(X^\top X)^{-1} X^\top \epsilon \epsilon^\top X (X^\top X)^{-1} K^\top)]
\\
&= \text{tr}(K(X^\top X)^{-1} X^\top E[\epsilon \epsilon^\top] X(X^\top X)^{-1} K^\top)
\\
&= \text{tr}(K(X^\top X)^{-1} X^\top \Sigma X(X^\top X)^{-1} K^\top).
\end{align}
When $\Sigma = \sigma^2 I$, you can simplify the last expression to $\sigma^2 \text{tr}(K(X^\top X)^{-1} K^\top)$ which is the variance mentioned in the answer you linked.
But for more general $\Sigma$ I don't think there is a nice simplification beyond the above.


text:
Q: Universal closure of a formula I am confused about the following: I read yesterday that for a formula $\phi(x_1,\ldots,x_n)$ in a first order language $\mathcal{L}$ and an $\mathcal{L}$-structure $\mathcal{A}$, $\mathcal{A} \models \phi(x_1,\ldots,x_n)$ iff $\mathcal{A} \models \forall x_1 \ldots \forall x_n \phi(x_1,\ldots,x_n)$. This seems perfectly fine to me; if I understand it right, it's like saying something like $x^2 \geq 0$ is true iff $\forall x (x^2 \geq 0)$ is true.
Now consider a predicate $Q(x)$; then according to the above $\models Q(x)$ iff $\models \forall x Q(x)$. Isn't this equivalent to $\models Q(x) \leftrightarrow \forall x Q(x)$? However, $\not \models Q(x) \rightarrow \forall x Q(x)$; take for example $\mathcal{A} = (A, Q^{\mathcal{A}})$, where $A=\{a,b\}$,  $Q^{\mathcal{A}}=\{a\}$ and $w: \mathrm{Var} \rightarrow A$, $w(x) = a$. What am I doing wrong?

A: I believe you are mixing two different conventions:

*

*Some authors include a variable assignment along with each model when defining the satisfaction relation, so that a model consists of a structure $\mathcal{A}$ and a function $w$ assigning some element of $|\mathcal{A}|$ to each variable. It is possible to have two such functions $w,w'$ such that $\mathcal{A},w \models \phi$ but $\mathcal{A},w' \not \models \phi$. Using only this definition, it is impossible to write $\mathcal{A} \models \phi$ when $\phi$ has free variables, as the definition requires $w$ to be fixed first.  Enderton's book uses essentially this approach, writing $\models_\mathcal{A}\, \phi[w]$.

*Other authors go on to define $\mathcal{A} \models \phi$, when $\phi$ has free variables, to mean $\mathcal{A},w\models \phi$ for every variable assignment function $w$ from $\mathcal{A}$. Letting $\phi^u$ be the universal closure of $\phi$, these authors would indeed say that $\mathcal{A} \models \phi$ if and only if $\mathcal{A} \models \phi^u$, because this is an immediate consequence of their definitions. This approach is used by Kleene's 1967 book and I believe it is also common in universal algebra.
One additional point of confusion is that the authors who take the first approach continue by defining ``$\models \phi$'' to mean that $\mathcal{A},w\models \phi$ for every structure $\mathcal{A}$ in the language and every variable assignment $w$ from $\mathcal{A}$. So authors who take the first approach can still prove that $\models \phi$ if and only if $\models \phi^u$ even if $\phi$ has free variables. This is exercise 6 on page 99 of Enderton's book, for example.
In the example in the second paragraph in the question, the trouble is that under the second convention I described, $\mathcal{A} \not \models Q(x)$, although it is true that $\mathcal{A},w \models Q(x)$.  In fact neither $Q(x)$ nor $(\forall x)Q(x)$ is a logically valid formula.


text:
Q: Change Dual Monitor Behavior When you setup dual monitors, to move a windows to a different display (monitor), you move it sideways (right or left). Is it possible to change the behavior to move the window by moving vertically, i.e. up or down.
I have two monitors setup in a special case above each other (instead or side by side). I want to make it easier by dragging windows up and down instead of sideways since it happens to be confusing.
I am using Windows 8.1
Thanks!

A: In the windows control pannel "Display", go to the resolution section

With the mouse Click on and drag the visual represenation of the monitors, into the desired configuration.


text:
Q: Can multiple iOS apps on the same device connect to the same peripheral and not share the connection? I've read posts that say that multiple iOS apps on the same iPhone can connect to the same device.  But are they sharing one connection or does each app have its own connection?  If they are sharing a connection, isn't that a security problem for one app to see data for the second app?
More specifically, see the following conceptual diagram.  Is there a Connection 1 and a Connection 2 as diagramed even though the user would only see one connection in Bluetooth Settings?
Apple docs, here, list the method to use in CBCentralManager to connect to a connected device (look at last paragraph).
If there is one connection, why would Apple allow this due to the security issues?


text:
Q: How to fix vscode icon in numix icon circle theme? Due to the generic code name, the Numix team have decide not to use the code.desktop icon provided by the VS Code package.
So it's icon is configured as a common text editor by default.
How to fix it?

A: Here's a one liner that will achieve what these guys are saying for you. I've aliased this in bash because I have to execute this every FREAKING time vscode updates...
sudo sed -i "s/Icon=code/Icon=vscode/g" /usr/share/applications/code.desktop

A: Looks like that the Numix team has provided an alternative icon with the name of vscode.desktop, in order to fix it we need to:

*

*Copy and rename the default code.desktop to the local user directory:

cp /usr/share/applications/code.desktop  ~/.local/share/applications/vscode.desktop

*Edit the new vscode.desktop and rename all Icon properties from Icon=code to Icon=vscode.

The result should be something like this:
[Desktop Entry]
Name=Visual Studio Code
Comment=Code Editing. Redefined.
GenericName=Text Editor
Exec=/usr/share/code/code --unity-launch %U
Icon=vscode
Type=Application
StartupNotify=true
StartupWMClass=Code
Categories=Utility;TextEditor;Development;IDE;
MimeType=text/plain;inode/directory;
Actions=new-window;
Keywords=vscode;

X-Desktop-File-Install-Version=0.22

[Desktop Action new-window]
Name=New Window
Name[de]=Neues Fenster
Name[es]=Nueva ventana
Name[fr]=Nouvelle fenêtre
Name[it]=Nuova finestra
Name[ja]=新規ウインドウ
Name[ko]=새 창
Name[ru]=Новое окно
Name[zh_CN]=新建窗口
Name[zh_TW]=開新視窗
Exec=/usr/share/code/code --new-window %U
Icon=vscode

*Restart the session to apply the new icon.

A: If you're absolutely sure Visual Studio Code will be the only 'code' executable,
just copying the vscode.svg icon seems to be a better solution
as it'll also theme the icon if you launch vscode via terminal command: code.
sudo ln -s visualstudiocode.svg /usr/share/icons/Numix-Circle/48/apps/code.svg
sudo dpkg-reconfigure numix-icon-theme numix-icon-theme-circle

A: This little script should do the job. Since a copy is placed in .local/share, it shouldn't be changed when apt upgrades. (Here the Numix-Icon-Circle is choosen.)
#!/bin/bash
# Description: change the vs-code icon to the specific numix icon

cp /usr/share/applications/code.desktop ~/.local/share/applications/code.desktop
sed -i "s/Icon=\/usr\/share\/pixmaps\/com.visualstudio.code.png/Icon=\/usr\/share\/icons\/Numix-Circle\/48\/apps\/vscode.svg/g" ~/.local/share/applications/code.desktop

A: go to :
sudo nano /usr/share/applications/code.desktop

and change
Icon=vscode

to
Icon=/usr/share/pixmaps/com.visualstudio.code.png


text:
Q: Rationalization of a fraction Can someone please explain how i can rationalize the fraction $\frac{2 +\sqrt{3}}{(2-\sqrt{3})^3}$ so that i obtain an answer that has an exponent of 6. I basically need to compare this value with $\dfrac{(10)^6}{(3)^6}$ to see which is greater. Thanks in advance for helping out!

A: Hint : Multiply numerator and denominator with $$(2+\sqrt{3})^3$$

A: \begin{align*}
\frac{2+\sqrt{3}}{(2-\sqrt{3})^3}&=\frac{2+\sqrt{3}}{(2-\sqrt{3})^3}\cdot\frac{(2+\sqrt{3})^3}{(2+\sqrt{3})^3}\\
&=\frac{(2+\sqrt{3})^4}{(2^2-3)^3}\\
&=\frac{(2+\sqrt{3})^4}{1}\\
&=(2+\sqrt{3})^4
\end{align*}

A: You could multiply top and bottom of your fraction by $(2+\sqrt{3})^3$ and obtain $(2+\sqrt{3})^4$ since $(2+\sqrt{3})(2-\sqrt{3})=1$


text:
Q: What's a good way to display a loading image until an ajax query completes? Right now it contacts the server every time a user toggles "Comments (X)"
I'd like to make it so as soon as a user clicks ".info .reply" (Comments (X)), an ajax loader appears just until the data is finished loading, then the loader disappears.
// Replies - Toggle display of comments
$('.info .reply').click( function() {
    $('.reply', this.parentNode.parentNode).toggle();
    return false;
});

// Load comments
$('.info .reply', this).mousedown( function() {
    var id = $('form #id', this.parentNode.parentNode).val();
    $.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
        success: function(data) {
            for (var i in data) {
                // Do AJAX Updates
            }
        }
    });
    return false;
});

What's the proper way to do this?
Thanks!

A: Basically
Show the image on mousedown using show() or fadeIn() or whatever tickles your fancy, then hide it inside your success callback. Like this
$('.info .reply', this).mousedown( function() {
    $("#loading-image").show(); // Show the progress indicator
    var id = $('form #id', this.parentNode.parentNode).val();
    $.ajax({ url: location.href, type: 'post', data: 'id=' + id, dataType: 'json',
        success: function(data) {
            $("#loading-image").hide(); // Hide the progress indicator
            for (var i in data) {
                // Do AJAX Updates
            }
        }
    });
    return false;
});

A: You can use a plugin such as jQuery BlockUI to do this. Just call $.blockUI() before calling $.ajax. Then at the end of the success event, call $.unblockUI().


text:
Q: laravel eloquent - check if all values of array in table I have a table options and I have an array of strings ["value1", "value2", "value3"].
What I'd like to do is check if all of the values within the array are present in the table.
I've tried whereIn but I think it checks if any values exist in the table.
This is what I have done currently:
$v = ["value1", "value2", "value3"];

$options = Options::whereIn('value', $v)->get();

if ($options->count() != count($v)) {
//something must be missing
}

This works, but I wonder if there is a better way? The table has millions of records so I'd like to do only 1 query if possible.
Thanks!

A: The answer in the comments by justcarty is technically correct, but you can reduce the load by not pulling in the options if you don't intend to use them.
if (Option::whereIn('value', [...])->count() != count([...])) {
    //perform action
}

Also note, as justcarty mentioned, this won't work if you have multiple occurrences of a value in your database, but you can get around this by adding DISTINCT clause to your query.
if (Option::distinct(['value'])->whereIn('value', [...])->count() != count([...])) {
    //perform action
}

A: whereIn check specifically for that one value in the arrays.
You can try this:
$search_values = ['value1', 'value2', 'value3'];
$found = true;
foreach ($search_values as $search) {
    if (!Search::where('column', $search)->first()) {
        $found = false;
    }
}

if (!$found) {
    // Something must be missing
}


text:
Q: Google Cloud Run - Container failed to start workarounds Similarly to Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable I cannot start my container because it does not (need to) listen on a port. It is a Discord bot that just needs outbound connections for the APIs.
Is there a way I can get around this error? I've tried listening on port 0.0.0.0:8080 using socket module with
import socket

s = socket.socket()
s.bind(("0.0.0.0", 8080))
s.listen()

A: Cloud Run is oriented to request-driven tasks and this explains Cloud Run's listen requirement.
Generally (!) clients make requests to your Cloud Run service endpoint triggering the creation of instances to process the requests and generate responses.
Generally (!) if there are no outstanding responses to be sent, the service scales down to zero instances.
Running a bot, you will need to configure Cloud Run artificially to:

*

*Always run (and pay for) at least one instance (so that the bot isn't terminated)

*Respond (!) to incoming requests (on one thread|process)

*Run your bot (on one thread|process)

To do both #2 and #3 you'll need to consider Python multithreading|multiprocessing.
For #2, the code in your question is insufficient. You can use low-level sockets, but it will need to respond to incoming requests and so you will need to implement a server. It would be simpler to use e.g. Flask which gives you an HTTP server with very little code.
And this server code only exists to satisfy the Cloud Run requirement, it is not required for your bot.
If I were you, I'd run the bot on a Compute Engine VM. You can do this for Free.
If your bot is already packaged using a container, you can deploy the container directly to a VM.


text: Q: Eclipse RCP - Wrong plugin version is refered I have eclipse rcp 4 application, which i migrating from mars to oxygen. It is a feature based application. All the required plugins are added to feature tab but some plugins like org.apache.batik.css, org.apache.batik.util and org.apache.batik.util.gui causing dependency issues. plugin tab by default taking 1.8 version of these plugins. But it seems that it has refer 1.7 version because if select only 1.7 from run configuration window application runs fine. Is there any way to make feature tab to select only 1.7 version instead of 1.8 permanently.? I tried to remove 1.8 version from eclipse plugin folder and it worked. But is there any better solution other than manually altering physical files?


text:
Q: Type '{ distinctByField: any; }' is not assignable to type 'IntrinsicAttributes i have some problem related to Type '{ distinctByField: any; }' is not assignable to type 'IntrinsicAttributes, I checked passing props but the error still appears
[1]: https://i.stack.imgur.com/e1Ebj.png
[2]: https://i.stack.imgur.com/9Z34x.png
[3]: https://i.stack.imgur.com/NY5Or.png
[4]: https://i.stack.imgur.com/zBsgm.png
[5]: https://i.stack.imgur.com/lrw0v.png


text:
Q: Eagle - placing pin number silkscreen I'm fairly new to PCB designing, and it's my first board design.
If I want to add pin number silkscreen on the board, do I have to do it all manually on the board design page?
Can't I do it on schematic design page and pass it over to board page?
Like putting labels on connections and make Eagle automatically show labels on silkscreen layer.
Any help would be appreciated.

A: You can add the pin numbering in the footprint of you component. This is how usually this thing is done. In this way, each time you add your connector in the schematics you get the desired pin numbering in the board.

A: As RodezIO mentioned, you can do it in the footprint of the part, however, if you need some custom text, and repeated text(This is purely for the silkscreen):
You need to add an attribute to the 'tNames' layer that is assigned to each part. And convert the existing 'tNames' layer stuff to the 'tValues' layer.
Note that this is per part attribution, and not per pin.
For example, in the schematic:

*

*Select a part, then click on 'define attributes'> 'attribute'

*Put the Name field: PIN_1 (This is unique per part)

3. Put the Value field: GND (input the name you want to write for each pin here. The same name can be repeated for multiple pins)
4. Put the display field: value

*you can add more attributes and follow the above steps.

*click ok and ok

*Click on the generated attribute field, and edit its font, style, etc.

*Resize and reposition it in the schematic

*Generate the board file.

*Click on the component name in the attribute name on the board file and change it to layer '25 tNames'

*Change the value of the pin(P1, P2, etc) to the layer '27 tValues'

*When you generate the preview or the 3d part, the silkscreen will generate with the 'GND' name and not the value

The default name attribute (in this case J1) could not be changed. Hence, I have pushed it to the 'tValues layer' and pulled the other attributes on the 'tNames' layer.

A: The industry standard is to place a pin one indicator when you make the PCB footprint or to make pin 1 square and the others round. Anything beyond that you add manually to the PCB.
I personally don't annotate the schematic.
However I find adding the actual signal names to the bottom silkscreen a lot more informative than the pins numbers:

(Company name has been removed)
You can also see that pin 1 has a square solder mask, the others have a round solder mask.
If you work in a company with a PCB lay-out team you normally have to give a lot of instructions when you hand over the design. Those can contain anything from detailed component placement to what should be on the bottom and top silkscreen.


text:
Q: Why does not the + operator change a list while .append() does? I'm working through Udacity and Dave Evans introduced an exercise about list properties
list1 = [1,2,3,4]
list2 = [1,2,3,4]

list1=list1+[6]
print(list1)
list2.append(6)
print(list2)

list1 = [1,2,3,4]
list2 = [1,2,3,4]

def proc(mylist):
    mylist = mylist + [6]

def proc2(mylist):
    mylist.append(6)

# Can you explain the results given by the four print statements below? Remove
# the hashes # and run the code to check.

print (list1)
proc(list1)
print (list1)

print (list2)
proc2(list2)
print (list2)

The output is
[1, 2, 3, 4, 6]
[1, 2, 3, 4, 6]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 6]

So in a function the adding a 6 to the set doesn't show but it does when not in a function?

A: Variables in python can always be thought of as references.  When you call a function with an argument, you are passing in a reference to the actual data.
When you use the assignment operator (=), you're assigning that name to refer to an entirely new object.  So, mylist = mylist + [6] creates a new list containing the old contents of mylist, as well as 6, and assigns the variable mylist to refer to the new list.  list1 is still pointing to the old list, so nothing changes.
On the other hand, when you use .append, that is actually appending an element to the list that the variable refers to - it is not assigning anything new to the variable.  So your second function modifies the list that list2 refers to.

A: Ordinarily, in the first case in function proc you would only be able to change the global list by assignment if you declared
global mylist

first and did not pass mylist as a parameter. However, in this case you'd get an error message that mylist is global and local:
name 'mylist' is local and global. What happens in proc is that a local list is created when the assignment takes place. Since local variables go away when the function ends, the effect of any changes to the local list doesn't propagate to the rest of the program when it is printed out subsequently.
But in the second function proc2 you are modifying the list by appending rather than assigning to it, so the global keyword is not required and changes to the list show elsewhere.

A: As well as the comprehensive answers already given, it's also worth being aware that if you want the same looking syntax as:
mylist = mylist + [6]

...but still want the list to be updated "in place", you can do:
mylist += [6]

Which, while it looks like it would do the same thing as the first version, is actually the same as:
mylist.extend([6])

(Note that extend takes the contents of an iterable and adds them one by one, whereas append takes whatever it is given and adds that as a single item. See append vs. extend for a full explanation.)

A:
So in a function the adding a 6 to the set doesn't show but it does when not in a function?

No, that is not what happens.
What happens is that, when you execute mylist = mylist + [6], you are effectively creating an entirely new list and putting it in the local mylist variable. This mylist variable will vanish after the execution of the function and the newly created list will vanish as well.
OTOH when you execute mylist.append(6) you do not create a new list. You get the list already in the mylist variable and add a new element to this same list. The result is that the list (which is pointed by list2 too) will be altered itself. The mylist variable will vanish again, but in tis case you altered the original list.
Let us see if a more visual explanation can help you :)
What happens when you call proc()
When you write list1 = [1, 2, 3, 4, 5] you are creating a new list object (at the right side of the equals sign) and creating a new variable, list1, which will point to this object.

Then, when you call proc(), you create another new variable, mylist, and since you pass list1 as parameter, mylist will point to the same object:

However, the operation mylist + [6] creates a whole new list object whose contents are the contents of the object pointed by mylist plus the content of the following list object - that is, [6]. Since you attribute this new object to mylist, our scenario changes a bit and mylist does not point to the same object pointed by list1 anymore:

What I have not said is that mylist  is a local variable: it will disappear after the end of the proc() function. So, when the proc() execution ended, the mylist is gone:

Since no other variable points to the object generated by mylist + [6], it will disappear, too (since the garbage collector* will collect it):

Note that, in the end, the object pointed by list1 is not changed.
What happens when you call proc2()
Everything changes when you call proc2(). At first, it is the same thing: you create a list...

...and pass it as a parameter to a function, which will generate a local variable:

However, instead of using the + concatenation operator, which generates a new list, you apply the append() method to the existing list. The append() method does not create a new object; instead, it _changes the existing one:

After the end of the function, the local variable will disappear, but the original object pointed by it and by list1 will be already altered:

Since it is still pointed by list1, the original list is not destroyed.
EDIT: if you want to take a look at all this stuff happening before your eyes just go to this radically amazing simulator:

* If you do not know what is garbage collector... well, you will discover soon after understanding your own question.

A: This, in one form or another, is a very common question. I took a whack at explaining Python parameter passing myself a couple days ago. Basically, one of these creates a new list and the other modifies the existing one. In the latter case, all variables that refer to the list "see" the change because it's still the same object.

A: In the third line, you did this
list1=list1+[6]

So, when you did the below after the above line,
print (list1)

which printed list1 that you created at the start and proc procedure which adds list1 + [6] which is creating a new list inside the function proc. Where as when you are appending [6], you are not creating a new list rather you are appending a list item to already existing list.
But, keep in mind. In line 7, you again created the list
list1 = [1,2,3,4]

Now you wanted to print the list1 by calling it explicitly, which will print out the list1 that you reinitialized again but not the previous one.


text:
Q: Upgraded to .net core 2.1 and now I can't serialize a claim I currently send claims (System.Security.Claims.Claim type) between two Azure micro-services. When I was on .net Core 2.0 this worked fine. The service fabric comms layer serialised and deserialised as expected. When I upgrade to .net core 2.1 I now get the error:

System.Runtime.Serialization.InvalidDataContractException: 'Type 'System.Security.Claims.Claim' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.'

A: I see you've answered this by having a separate claim type. Not sure what changed on the .NET claim type, but it must have. https://fuget.org/packages/System.Security.Claims/4.3.0/lib/netstandard1.3/diff/4.0.1/ doesn't immediately show anything, may have to really diassemble things to see the difference.
You can also get around this by having a custom serializer that you can control and which is more permissive. This works particularly well with your own types since you can explicitly control the process.
More info on that is here: https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-reliable-collections-serialization#custom-serialization


text:
Q: Graphql base64 image data and Gastby Starting this gatsby site and i have data that come from remote PIM software.
The response :
"data": {
  "pim": {
    "getProducts": {
        "name": "000F office grey jeans",
        "image": {
          "mimetype": "image/jpeg",
          "type": "image",
          "data": "/9j/2wCEAAQDAwMDAwQDAwQGBAMEBgcFBA  .....

The question is if there is a plugin or a more friendly way to display image on Gatsby without have to compose the image src attribute i.e :
<img src="data:{data.pim.getProducts.image.mimetype};base64,{data.pim.getProducts.image.data}

I tried with StaticImage, GatsbyImage, getImage through
import { StaticImage, GatsbyImage, getImage} from 'gatsby-plugin-image'

but could not display the image on site.
Im using gatsby-source-graphql plugin.
Thanks in advance.

A: You won't be able to use GatsbyImage because to use it, Gatsby needs to treat the asset with its transformers and sharps to create the proper GraphQL node data (gatsbyImageData). In your case, the image is a base64 encoded string and can't be locally analyzed, hence it's not an option as is.
Regarding the StaticImage, I'm afraid it only works with URL paths, not in base64-like assets.
I don't see anything wrong with your <img> tag, but of course you're free to use any third-party dependency to lazy-load or to recreate the performances that Gatsby does with images when builds the site.


text:
Q: Detect when mobx observable has changed Is it possible to detect when an observable changes in any way?
For instance, say you have this:
@observable myObject = [{id: 1, name: 'apples'}, {id: 2, name: 'banana' }]

And later on, with some user input, the values change. How can I detect this easily?
I want to add a global "save" button, but only make it clickable if that observable has changed since the initial load.
My current solution is to add another observable myObjectChanged that returns true/false, and wherever a component changes the data in the myObject, I also add a line that changes the myObjectChanged to true. And if the save button is clicked, it saves and changes that observable back to false.
This results in lots of extra lines of code sprinkled throughout. Is there a better/cleaner way to do it?

A: You could use autorun to achieve this:
@observable myObject = [{id: 1, name: 'apples'}, {id: 2, name: 'banana' }]
@observable state = { dirty: false }

let firstAutorun = true;
autorun(() => {
  // `JSON.stringify` will touch all properties of `myObject` so
  // they are automatically observed.
  const json = JSON.stringify(myObject);
  if (!firstAutorun) {
    state.dirty = true;
  }
  firstAutorun = false;
});

A: Create an action that will push to myObject and set myObjectChanged
@action add(item) {
    this.myObject.push(item);
    this.myObjectChanged = true;
}

A: As capvidel mentioned, you can use autorun to track if variable changes, but to avoid adding additional variable firstAutorun you can replace autorun with reaction:
@observable myObject = [{id: 1, name: 'apples'}, {id: 2, name: 'banana' }]
@observable state = { dirty: false }

reaction(
   () => JSON.stringify(myObject),
   () => state.dirty = true
);


text:
Q: Querying Google Analytics API for less than one day I am looking to use the Google Analytics API (v4) to try get around some sampling issues we have. Even when I query for just one day, the data is coming back sampled. Does anyone know how to run a query for less than a day, given the required format is YYYY-MM-DD? At the moment, Premium is not an option for us.
We have roughly 33k sessions in a day and 350k pageviews so I don't think we hit the 500k visits in a day limit. I am able to get unsampled data if I look at today (ie. a day that is not complete) but not for yesterday (ie. a complete 24 hours).
Here is my sample for pulling yesterday's data - which returns sampled data (using api_client batchGet method)
sample_request = {
      'viewId': view_id,
      'dateRanges': {'startDate': datetime.strftime(datetime.now() - timedelta(days = 1,'%Y-%m-%d'),
          'endDate': datetime.strftime(datetime.now()- timedelta(days = 1),'%Y-%m-%d')},
      'dimensions': [{'name':'ga:pagePath'},{'name':'ga:previousPagePath'}],
      'metrics': [{'expression': 'ga:pageviews'}],
    'samplingLevel':'Large'
    }

I would ideally like to query for less than a day (eg. from 1:00 - 05:00 for example) but would also like to understand why I am getting sampled on this.
Edit: I get sampled with more than one dimension (even standard dimensions)


text:
Q: Show InternalFrame in front of Glasspane I want an InternalFrame to be shown in front of a GlassPane.
In my program the user should be able to click on FILE -> Settings and an InternalFrame should be displayed. Everything in the background should be covered with a GlassPane.
Does somebody have an idea?
m21.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Settings settings = new Settings();

        //get the InternalFrame
        settings.getFrame().setBounds(100,100,getWidth()-200, getHeight()-200);
        settings.getFrame().toFront();

        setGlassPane(new Glass());
        getGlassPane().setVisible(true);

        //get the InternalFrame
        getLayeredPane().add(settings.getFrame(), BorderLayout.NORTH);
        getLayeredPane().moveToFront(settings.getFrame());

        repaint();
    }
});

A: The point of the glass pane is to be in front of everything else:

However, you can set any component as glass pane. My suggestion would be that you  push the content of your settings frame as glass pane.


text: Q: NodeJs with Visual Studio not launching browser I am working on a node js application created using visual studio. Earlier I used verson 6 of node js and I was able to debug the code(the browser used to come up while debugging the app). Recently the browser stopped to launch when I debug the app. Someone suggested to update node and I did the same. Now, I have version 8 of node js but the problem still remains. I also get DeprecationWarning: 'node--debug' and 'node--debug--brk' are ivalid message when I debug the app and the browser doesn't come up as well. I can run without debugging though. How can this be fixed?


text:
Q: npm Fails to Install over Socks5 Proxy I am having trouble running npm install over a socks5 proxy.
Proxy is running locally, to tunnel http(s) over ssh to company intranet: ssh -vvv -D 5000 -N <SERVER_IP>
I have configured npm's proxy:
npm config set proxy socks5h://localhost:5000
npm config set https-proxy=socks5h://localhost:5000

I just get:
npm ERR! git clone https://<INTRANET>/repo fatal: unable to access 'https://<INTRANET>/repo/': Could not resolve host: <INTRANET>

Any ideas?
P.S.: git clone from the same git repo address works perfectly.

A: Ok, as of now, npm does not support socks proxy: https://github.com/npm/npm/issues/6204
I now use ProxyCap.
http://www.proxycap.com
Works great. It will manage the ssh tunnel + socks proxy and route all traffic automatically (also for npm) through it.

A: Proxifier works for me. Simply add a proxy and npm install ...
.com/mac/

A: You can use polipo to convert sock5 proxy to http proxy, and it's super convenient if you're under Linux.
You can reference this page for further detail:

*

*Convert Socks Proxy To Http Proxy: Using Polipo

A: For a workaround that works on both Linux and Windows, you can use http-proxy-to-socks.
$ npm install -g http-proxy-to-socks
$ hpts -s 127.0.0.1:1080 -p 8080

Now you have you http proxy at port 8080.

A: Use v2rayN as client.
It will launch both socks5 and http proxy.
Then you can use its http proxy for npm proxy and socks5 for other proxy at same time.
// http for npm
npm config set http-proxy http://127.0.0.1:10809

// socks5 for git
git config --global http.proxy 'socks5://127.0.0.1:10808

v2raN UI Screen Shot


text:
Q: How to access data inside a Vuex array when Proxied? I have an array in Vuex. When I render the data to the DOM with a v-for directive it works fine. But if I try to access it in any other way, like:
mounted() {
   console.log(this.$store.state.myArray[0].property1)
}

I get an error, the property1 can't be read.
If I console.log the whole array, I get undefined.
I have read on other posts that the Proxy system in Vue does not alter the normal array behaviour, but then how come I can't access the array data other than with v-for?
Thanks!

A: I am answering my own question as I realised my mistake when trying to write a more reproductible example. It was a simple synchronisation issue. The component was loaded before the array was assigned any data. So v-for worked as it is reactive. But accessing the array in the mounted hook failed because when the componented mounted, there was no data in the array yet.


text:
Q: Send PHP array from one form to other in HTML I have two forms.
One reads a file using PHP and returns an array. I then what to send this array as an input to another form for some querying.
How do I go about it? Thanks
So far, I have something like this.
 <form  name ="INPUT" method="POST" enctype="multipart/form-data" ">

        <textarea name="queryList" id="queryList" cols="35" rows="10" wrap="physical" value='' onclick ="document.INPUT.queryList.value='';">
        Enter input here...
        </textarea>

        <input name=INPUTS type=hidden value=$entries[]/>

        File:
        <input action="readInput.php" name="uploadedfile" type="file" size="30" onchange='fillTextArea()'/>

     </form>

    <form  name ="SUBMIT_INPUT" action ="viewPDBs.php" method="POST" enctype="multipart/form-data"  >

            <input type="submit" name="submit" value="Submit" />

            <input name=IDS type=hidden value="<?php urlencode(serialize($entries)); ?>"/>

     </form>

A: Although I don't full know what you want, and I think you are doing something that could be inefficient and also open to security holes, you can do this:
<?php foreach($entries as $k => $e) : ?>
<input type="hidden" name="entries[<?php echo $k ?>]" value="<?php echo addslashes($e) ?>">
<?php endforeach; ?>

Then once submitted, check the variable $_POST['entries'] and you will find it is an array


text:
Q: Table footer with linked margin note creating large break in text I am using the tint template in R Markdown for an HTML rendering. I don't think that this issue is specific to R or R Markdown, though. I think the fix can be accomplished with CSS or HTML. Although, I would guess that Dirk, Jon, or JJ, Yihui, or Dave could probably tell me how to fix this properly in R Markdown since they authored or contributed to the development of tint.
How can I modify this to prevent the margin notes from affecting the spacing below the table?
I did try setting the table tag with the styles align: left; and float: left; to see if that would work. Neither impacted the spacing at the bottom.
Here is the table footer with the margin note as HTML script:

          Note.  This is the data dictionary based on the data adapted from CFPB (n.d.)3<input type="checkbox" id="tufte-sn-3"
            class="margin-toggle">3 Consumer Financial Protection Bureau. (n.d.) Consumer complaint database API docs [data set and code book]. Office of Civil Rights. Retrieved
            April 28, 2021, from https://cfpb.github.io/api/ccdb/index.html and Rozzi (2021).4<input
            type="checkbox" id="tufte-sn-4" class="margin-toggle">4 Rozzi, G. (2021). Data & functions for working with US zip codes. GitHub. https://github.com/gavinrozzi/zipcodeR/

I realize it's not all that pretty. While I will likely modify the HTML directly, I didn't write it. It was generated through the use of R Markdown. I typically find that tables can be far less painful, for how often I'm using it, to adjust in the script.
When I render the HTML, there's this huge gap between the table and the next line of text. This is what's happening in the HTML when I run the script:

However, when I use the margin outside of the table, I don't have this problem. (Don't mind the writing; it's definitely not proofread.) If you look, you can see that the second margin note in this image is not impacting the next

.

Please let me know if there is other information I could provide to get help faster.

A: It may not be right, but it works. I took the footer off the table and added a  block with the footer content. Issue solved. I don't know why I didn't think of that sooner. (sigh)


text:
Q: Better regex to get matching groups from html text? I have a text which will contain plain text with html span tags and I need to extract matching groups from that text.
Sample Text:

This is post

   newpost
    with intention to make

   newchannel
     and see how

  textforthis
    gets genrated.

Now what I want to extract from this is newpost,newchannel,textforthis in group match at server side regex.
What I tried is as below,
New Regex("]*?data-value=[\\""|']{1,2}[^""']*[\\""|']>(?<hashtag>[^""<\/]+)<\/span>", RegexOptions.Compiled)
Which works great and gives me the groups I require. But I am not good at writing regex and was thinking that can I optimize this regex ?
Here is the RegExr link

A: In order to optimize the regex, you have several options. Flexibility will come at a prize.
These four regexes have less steps than the 2 regexes you provided (3785 and 1296)

*

*If you can be sure that the spans you want to fetch just have the data-value attribute an no other one, you may use: ]+>(?<hashtag>[^\s<]+) See Demo. This is the fastest solution (279 steps) I could figure out. However, if a span has some additional attribute before the data-value, It will fail

*This ([^>d]*)data-value[^>]+>(?<hashtag>[^\s<]+)) is similar in concept to case 1. It is not much slower (342 steps) and can work with attributes before data-value as long as there is no a d letter on them

*This ((?>[^>d]*)(?(?=data-value)[^>]+|d))*>(?<hashtag>[^\s<]+)) will work for any case, even if you find some attributes before data-value. It is 903 steps

*This (]*?data-value[^>]+>(?<hashtag>[^\s<]+)) will also work for any case. It is easier to read, but it costs some more (1146 steps)

Also, I would consider the number of steps just an starting point or a guide. In the end, I would rely on some benchmarks to decide.


text:
Q: Hosting a web site at home: ISP Blocking port 80? I presume this is a better place to put this rather than server fault.
I'm interested in setting up a small site to host at home as a "proof of concept" exercise, i.e. to prove that I know how to do it. I've got a (virtual) server 2003 machine with a site on it, all configured with port forwarding through to 80 on my server. I have a Belkin F5D7634 which I have put my DYNDNS details in but when I try to go to my DYNDNS address it comes up with the page cannot be displayed.
My ISP is Carphone Warehouse/AOL and I've been unable to find any information if they block port 80. If they do, can anybody recomend a home provider that does not block port 80?

A: More ISP's than not will block port 80 nowadays to prevent incoming traffic.  Usually they won't tell you they are blocking it and your odds of getting a straight or accurate answer if you call tech support are about 50/50.  Some ISP's will allow you to set up a server if you work with them to set it up (sometimes with additional monthly fees, sometimes not).  About the only way to find out is to call the various ISP's that serve your area and see what they say.  Oh, and call the tech support number, not the sales office.  The salespeople will either have no idea or they will just tell you what you want to hear.

A: For testing, take DynDNS out of the list of possible problems:

*

*Go to whatismyip.com.

*Try that IP address directly, but: from some other internet connection, like by using Web-Sniffer.

*Try an online traceroute to that address (that will not use port 80, but might still give you some clue).

If that doesn't work, there are many possible causes other than port blocking, like:

*

*Maybe the port forwarding in the router is incorrect.

*You might be trying to use the DynDNS address (or public IP address) from within your own network, which will likely end up in your router rather than at the web server.

*Maybe (but not likely) you've set up your web server to only bind to localhost, not to any outside requests.

A: I'm going to reply to this as I've now found the answer.
The problem was with the port forwarding of the router. Due to a bug in the firmware, it would only "remember" the TCP port setting, even when changed to UDP/TCP or just UDP. Following a firmware update I can choose to forward both types of port and it seems to be working. I am surpirsed that the ISP doesn't block port 80, but hey, I'm not going to complain.


text:
Q: Material ui v4 withTheme() does not work with redux compose Migrating from v3 to v4.
When using withTheme with compose to provide child components with theme props I get an error
export default compose(
    connect,
    withTheme(),
    withStyles(styles)
)(SearchWrapper);

You are calling withTheme(Component) with an undefined component. You
may have forgotten to import it.

However, when using connect only without relying on compose, I do not get the above error
connect(mapStateToProps)(withTheme(withStyles(styles)(SearchWrapper)));

How can I retain the compose(...) hierarchy of adding functions.


text:
Q: how to compare modified rows and update into database using linq? I am working on handsontable with asp.net. If user changes data on table and click on save button. Data comes on Jason format through AJAX call. Then I am able to convert JSON format data to List (of T). Till it is fine to me.
The problem is I will have List (Of T) but don't know which column is modified. So How can
compare modified [row][column] with database row and if it is modified, how to update it with LINQ using Entity Framework?
 <OperationContract()>
    Public Function SaveGridData(ByVal input As String) As String
        Dim initiativeData As List(Of InitiativeData) = JsonConvert.DeserializeObject(Of List(Of InitiativeData))(input)
        '' Update to database
        Return "ok"
    End Function

    #Region "Properties"

    Private _ClientIdx As Integer
    Public Property ClientIdx() As Integer
        Get
            Return _ClientIdx
        End Get
        Set(ByVal value As Integer)
            _ClientIdx = value
        End Set
    End Property

    Private _HierarchyIdx As Integer
    Public Property HierarchyIdx() As Integer
        Get
            Return _HierarchyIdx
        End Get
        Set(ByVal value As Integer)
            _HierarchyIdx = value
        End Set
    End Property

    Private _CostCenterIdx As Integer
    Public Property CostCenterIdx() As Integer
        Get
            Return _CostCenterIdx
        End Get
        Set(ByVal value As Integer)
            _CostCenterIdx = value
        End Set
    End Property

    Private _LocationIdx As Integer
    Public Property LocationIdx() As Integer
        Get
            Return _LocationIdx
        End Get
        Set(ByVal value As Integer)
            _LocationIdx = value
        End Set
    End Property
End Class


text:
Q: What does $\hat{\beta}_i = 0$ signify for OLS? I think this question may be better split into univariate regression and multiple regression using OLS. Here we assume $\hat{\beta}_i$ are the "slopes", where $i > 0$, and $\hat{\beta}_0$ is the intercept.

For univariate regression, if you performed OLS, and obtained $\hat{\beta}_1 = 0$ (slope), then this means the line of best fit determined by OLS is a horizontal line located at some $\hat{\beta}_0$ offset from the horizontal axis. This also means the correlation coefficient between the regressor and response is zero, indicating no linear independence.
My question regarding this univariate case is, beyond linear independence, does the zero slope and zero correlation also indicate no monotonic relationship? If the data was monotonically increasing or decreasing, then there is no way the slope could end up zero?
A slope of zero does not rule out non-monotonic relationships. For example, consider $$
y = \sin(x) + \text{constant}
$$.
If the regressor is distributed from $x \in [0, n\pi]$, where $n$ is some even number, then OLS will give you $\hat{\beta_1} = 0$

For multiple regression, what are some obvious and subtle characteristics of $\hat{\beta}_i = 0$? Does it still indicate that there's no linear relationship between the i-th regressor and the response? Does it say anything about the $j$-th regressor, where $j \neq i$?

A: For the multivariate case, it would mean that there is no significant relationship between that particular predictor and the dependant variable


text:
Q: unable to correctly specify headers for CORS request I created an AWS API Gateway endpoint that needs to be called from the browser. This is a simple jquery ajax post:
$.post(
    'https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev',
    {}
  )

(fiddle here: https://jsfiddle.net/7cfyr1mL/)
The browser says that the endpoint does not return appropriate CORS headers:
 No 'Access-Control-Allow-Origin' header is present on the requested resource.

however when I request this endpoint from python I see that the headers do exist:
# testing OPTIONS request
>>> res = requests.options('https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev')
>>> print(res.headers)
200
>>> print(res.status_code)
{'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', ...}

# testing POST request

>>> res = requests.post('https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev', json={})
>>> print(res.headers)
{'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', ...}
>>> print(res.status_code)
400

what is wrong with my headers? How do I change them so that the browser is happy?

A: Your server-side code throws a 500 error and doesn't set the Access-Control-Allow-Origin header if it gets a POST request which isn't JSON encoded.
jQuery POST uses standard form URL encoding by default, so you have to override that.
$.ajax(
  'https://jhntqqm19l.execute-api.us-east-1.amazonaws.com/dev',
  { contentType: 'application/json', data: JSON.stringify({}), method: "post"}
);

You'll also need to change the server-side code to allow a preflight request as currently, you don't allow JSON formatted requests with CORS.

A: In server side code (python in your case) you will have to enable few things along with header
'Access-Control-Allow-Origin': '*'

You can refer to https://www.codecademy.com/articles/what-is-cors
and search how to apply cors based on your framework.
The browser makes an OPTIONS call before it actually makes any call to your application. Make sure it is enabled depending on your application.
For example allowedHttpHeaders, allowedHttpMethods, allowedOrigins.


text:
Q: Kerberos CLIENT_NOT_FOUND while logon from WinXP to Ubuntu16.04 Samba Domain since Samba is meanwhile fully able to act as Active Directory replacement, I plan to setup it for a school network (using old XP and Win7 clients). I installed all my packages from the Ubuntu 16.04 LTS repos.
Setting up the server worked pretty well, but after joining the domain via WinXP, I cannot loggon: "username or domain not found".
/var/log/auth.log
Mar 26 14:41:39 server krb5kdc[967]: AS_REQ (7 etypes {23 -133 -128 3 1 24 -135}) 192.168.0.103: CLIENT_NOT_FOUND: chrglo@FSG for krbtgt/FSG@FSG, Client not found in Kerberos database
Mar 26 14:41:39 server krb5kdc[967]: DISPATCH: repeated (retransmitted?) request from 192.168.0.103, resending previous response

But the account chrglo exists within Kerberos:
fsgadmin@server:~$ kinit chrglo
Password for chrglo@FSG.LAN:
fsgadmin@server:~$ klist
Ticket cache: FILE:/tmp/krb5cc_1000

Default principal: chrglo@FSG.LAN
Valid starting       Expires              Service principal
26.03.2018 14:43:42  27.03.2018 00:43:42  krbtgt/FSG.LAN@FSG.LAN
renew until 27.03.2018 14:43:39`

I tried several(!) google results dealing with various (but not identical) issues of that kind. But none of them helped.
Here's my Kerberos configuration:
/etc/krb5.conf
[libdefaults]
    default_realm = FSG.LAN
    dns_lookup_realm = true
    dns_lookup_kdc = true

[realms]
    FSG.LAN = {
            kdc = server.fsg:88
            admin_server = server.fsg:749
            default_domain = FSG
    }

[domain_realm]
    .fsg.lan = FSG.LAN
    fsg.lan = FSG.LAN

[logging]
    kdc = FILE:/var/log/kerberos/krb5kdc.log
    admin_server = FILE:/var/log/kerberos/kadmin.log
    default = FILE:/var/log/kerberos/krb5lib.log

and my Samba configuration:
/etc/samba/smb.conf
[global]
    workgroup = FSG
    realm = FSG.LAN
    netbios name = SERVER
    server role = active directory domain controller
    dns forwarder = 192.168.0.254
    idmap_ldb:use rfc2307 = yes

Here's some screenshots from the XP client (btw both server and client running within a VirtualBox): the client was added to the domain and offers to logon using it, but stops after the (previously noticed) error message.
Client joined the domain
Client at domain logon screen
Error after logon try
Has anyone an idea where I screwed up the configuration?
Glocke
/EDIT: for the sake of providing more information: DHCP is done via an external piece.
/etc/hosts
127.0.0.1   localhost localhost.fsg

192.168.0.250   server.fsg server

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

/EDIT2: requested ipconfig / ifconfig:
ipconfig /all on xp client
on Server:
fsgadmin@server:~$ ifconfig
enp0s3    Link encap:Ethernet  Hardware Adresse 08:00:27:ef:bc:56
      inet Adresse:192.168.0.250  Bcast:192.168.0.255  Maske:255.255.255.0
      inet6-Adresse: fe80::a00:27ff:feef:bc56/64 Gültigkeitsbereich:Verbindung
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metrik:1
      RX-Pakete:154 Fehler:0 Verloren:0 Überläufe:0 Fenster:0
      TX-Pakete:82 Fehler:0 Verloren:0 Überläufe:0 Träger:0
      Kollisionen:0 Sendewarteschlangenlänge:1000
      RX-Bytes:18341 (18.3 KB)  TX-Bytes:11263 (11.2 KB)

lo        Link encap:Lokale Schleife
      inet Adresse:127.0.0.1  Maske:255.0.0.0
      inet6-Adresse: ::1/128 Gültigkeitsbereich:Maschine
      UP LOOPBACK RUNNING  MTU:65536  Metrik:1
      RX-Pakete:650 Fehler:0 Verloren:0 Überläufe:0 Fenster:0
      TX-Pakete:650 Fehler:0 Verloren:0 Überläufe:0 Träger:0
      Kollisionen:0 Sendewarteschlangenlänge:1
      RX-Bytes:52072 (52.0 KB)  TX-Bytes:52072 (52.0 KB)

Furthermore: While the client joins the domain, some auth.log is happening on the server (I used the Samba builtin Administrator account information while joining):
Apr 10 16:11:54 server krb5kdc[1037]: AS_REQ (7 etypes {23 -133 -128 3 1 24 -135}) 192.168.0.235: CLIENT_NOT_FOUND: Administrator@fsg.lan for krbtgt/fsg.lan@fsg.lan, Client not found in Kerberos database
Apr 10 16:11:54 server krb5kdc[1037]: DISPATCH: repeated (retransmitted?) request from 192.168.0.235, resending previous response
Apr 10 16:11:54 server krb5kdc[1037]: AS_REQ (7 etypes {23 -133 -128 3 1 24 -135}) 192.168.0.235: CLIENT_NOT_FOUND: Administrator@fsg.lan for krbtgt/fsg.lan@fsg.lan, Client not found in Kerberos database
Apr 10 16:11:54 server krb5kdc[1037]: DISPATCH: repeated (retransmitted?) request from 192.168.0.235, resending previous response
Apr 10 16:11:54 server krb5kdc[1037]: AS_REQ (7 etypes {23 -133 -128 3 1 24 -135}) 192.168.0.235: CLIENT_NOT_FOUND: Administrator@fsg.lan for krbtgt/fsg.lan@fsg.lan, Client not found in Kerberos database
Apr 10 16:11:54 server krb5kdc[1037]: DISPATCH: repeated (retransmitted?) request from 192.168.0.235, resending previous response
Apr 10 16:11:54 server krb5kdc[1037]: AS_REQ (7 etypes {23 -133 -128 3 1 24 -135}) 192.168.0.235: CLIENT_NOT_FOUND: Administrator@fsg.lan for krbtgt/fsg.lan@fsg.lan, Client not found in Kerberos database
Apr 10 16:11:54 server krb5kdc[1037]: DISPATCH: repeated (retransmitted?) request from 192.168.0.235, resending previous response

Also, stuff is logged to samba/log.samba
[2018/04/10 16:13:45.999444,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate: Traceback (most recent call last):
[2018/04/10 16:13:46.002791,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate:   File "/usr/sbin/samba_dnsupdate", line 621, in <module>
[2018/04/10 16:13:46.006441,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate:     get_credentials(lp)
[2018/04/10 16:13:46.006826,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate:   File "/usr/sbin/samba_dnsupdate", line 125, in get_credentials
[2018/04/10 16:13:46.006930,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate:     raise e
[2018/04/10 16:13:46.007037,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate: RuntimeError: kinit for SERVER$@FSG.LAN failed (Cannot contact any KDC for requested realm)
[2018/04/10 16:13:46.007099,  0] ../lib/util/util_runcmd.c:328(samba_runcmd_io_handler)
  /usr/sbin/samba_dnsupdate:
[2018/04/10 16:13:46.021901,  0] ../source4/dsdb/dns/dns_update.c:294(dnsupdate_nameupdate_done)
  ../source4/dsdb/dns/dns_update.c:294: Failed DNS update - NT_STATUS_ACCESS_DENIED

A: Problem solved: samba provides its own kerberos admin server - no need to install it on my own :S


text:
Q: Create a random, sequenced id based on cookie session? I have a user sign up or registration form to allow guests to my site become registered members. The form consists of first name, last name, email etc, the action goes to process_reg.php on submit.
The information is then inserted into an sql table 'ptb_registrations'. but it doesn't work yet because i am trying to randomly generate a new user id with the form from a cookie session. I'm not sure if what i'm doing is right. can people please correct me where I'm wrong or point me in the right direction. Thanks.
here's my script for process_reg.php:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php

session_start();

include '_config/connection.php';

function get_user_id() {
    global $connection;
    global $email;
    $query = "SELECT *
                FROM ptb_registrations
                WHERE email = \"$email\"
                ";
        $user_id_set = mysql_query($query, $connection);
        confirm_query($user_id_set);
        return $user_id_set;
        }
?>
<?php
$user_id_set = get_user_id();
while ($user_id = mysql_fetch_array($user_id_set)) {
    $cookie1 = "{$user_id["id"]}";
    setcookie("ptb_registrations", $cookie1, time()+3600);  /* expire in 1 hour */

}
?>
<?

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$display_name = $_POST['display_name'];
$date_of_birth = $_POST['date_of_birth'];
$contact_number = $_POST['contact_number'];
$station = $_POST['station'];
$hobbies = $_POST['hobbies'];
$gender = $_POST['gender'];
$password = $_POST['password'];

$result = mysql_query("SELECT first_name FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT last_name FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT display_name FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT email FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT contact_number FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT date_of_birth FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT hobbies FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT station FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT gender FROM ptb_registrations WHERE id=".$cookie1['user_id']."");
$result = mysql_query("SELECT password FROM ptb_registrations WHERE id=".$cookie1['user_id']."");

if(!$result)
{
echo "The username you entered does not exist";
}
else
if($email!= mysql_result($result, 0))
{
echo "";

    $sql=mysql_query("INSERT ptb_registrations SET first_name='$first_name' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET last_name='$last_name' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET display_name='$display_name' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET email='$email' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET contact_number='$contact_number' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET date_of_birth='$date_of_birth' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET hobbies='$hobbies' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET station='$station' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET gender='$gender' WHERE id=".$cookie1['user_id']."");
    $sql=mysql_query("INSERT ptb_registrations SET password='$password' WHERE id=".$cookie1['user_id']."");

}
    if($sql)
    {
    echo "
 Thank You - We have received your registration details.
";
    }
else
{
echo "
 Oooops! - Something went wrong. Click here to try again.
";
}
?>
<? ob_flush(); ?>

A: A random generated number is not always completely random and after a while you will always get the same number again. This is because these numbers are generated by a PSEUDOrandom number generator. Because you work with a mysql database the best solution for your problem is to use the auto increment attribute. Every time a new user is added to the database  this field will be increased by one.
Here is an example:
CREATE TABLE animals (
     id MEDIUMINT NOT NULL AUTO_INCREMENT,
     name CHAR(30) NOT NULL,
     PRIMARY KEY (id)
) ENGINE=MyISAM;


text:
Q: Configure SocketCluster with nginx and ssl I'm trying to setup my SocketCluster app to use SSL. I'm able to get it working on nginx without ssl but not with it. When ever I visit the site in the browser I get the nginx welcome page. If i visit port 8000 in the browser I'm able to see socket cluster but not if using the https protocol.
nginx config
server {
    listen 443;

    ssl on;
    ssl_certificate /etc/ssl/server.crt;
    ssl_certificate_key /etc/ssl/server.key;

    server_name 104.xxx.54.xxx;
    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass https://localhost:8000;
        proxy_redirect off;
    }
}

server.js
var argv = require('minimist')(process.argv.slice(2));
var SocketCluster = require('socketcluster').SocketCluster;
require('dotenv').config();

var socketCluster = new SocketCluster({
  workers: Number(argv.w) || 3,
  brokers: Number(argv.b) || 1,
  port: Number(argv.p) || 8000,
  path: '/socket',
  appName: '...',
  workerController: __dirname + '/worker.js',
  brokerController: __dirname + '/broker.js',
  socketChannelLimit: 1000,
  crashWorkerOnError: argv['auto-reboot'] != false,
  rejectUnauthorized: false,
  secure: true
});

A: You appear to be terminating SSL in the reverse-proxy. Your service listening on port 8000 is non-SSL. So your proxy-pass should use HTTP for the upstream connection and not HTTPS. Try:
proxy_pass http://localhost:8000;

You may want to add an X-Forwarded-Proto header:
proxy_set_header X-Forwarded-Proto $scheme;


text:
Q: Make h2 inside div also change colour like the rest I am trying to change the colour of an h2 tag inside a div.
The other elements inside this div change to white colour when hovered over, only the h2 does not change colour.
I know I can change this in CSS... .well.sb:hover, .well.sb:hover h2, but the bad thing with that is that the h2 part changes colour separately from the rest. When hovering over the whole thing, everything (including h2) should change text-color into white at the same time and at the same speed and for the same one big and only div section. How to make that work?

h2.title-article-sidebar {
    font-size: 14px;
    font-family: Calibri;
    color: #444;
    font-weight: 700;
    line-height: 1.25em;
    margin-top: 0;
}

.article-image-summary-sidebar {
    border: 0 solid;
    padding-bottom: 0;
    -moz-transition: .9s ease;
    -webkit-transition: .9s ease;
    -o-transition: .9s ease;
    -ms-transition: .9s ease;
    transition: .9s ease;
}

.well.sb:hover {
        color: #FFF;
        background-color: #A10000;
        text-decoration: none;
        -moz-transition: .6s ease-in-out;
        -webkit-transition: .6s ease-in-out;
        -o-transition: .6s ease-in-out;
        -ms-transition: .6s ease-in-out;
        transition: .6s ease-in-out;
    }

                20-November-2010

                TAG

               TITLE WITH H2 TAG!!!!

A: There are 2 things happening. First, you need to target the h2 more specifically (it's overriding your hover styles). Second, you have conflicting transitions.

h2.title-article-sidebar {
    font-size: 14px;
    font-family: Calibri;
    color: #444;
    font-weight: 700;
    line-height: 1.25em;
    margin-top: 0;
}

.article-image-summary-sidebar {
    border: 0 solid;
    padding-bottom: 0;
    /* -moz-transition: .9s ease;
    -webkit-transition: .9s ease;
    -o-transition: .9s ease;
    -ms-transition: .9s ease;
    transition: .9s ease; */
}

.well.sb:hover {
    color: #FFF;
    background-color: #A10000;
    text-decoration: none;
    -moz-transition: .6s ease-in-out;
    -webkit-transition: .6s ease-in-out;
    -o-transition: .6s ease-in-out;
    -ms-transition: .6s ease-in-out;
    transition: .6s ease-in-out;
}
.well.sb:hover h2.title-article-sidebar {
    color: #FFF;
    -moz-transition: .6s ease-in-out;
    -webkit-transition: .6s ease-in-out;
    -o-transition: .6s ease-in-out;
    -ms-transition: .6s ease-in-out;
    transition: .6s ease-in-out;
}

            20-November-2010

            TAG

           TITLE WITH H2 TAG!!!!

A: Just remove color: #444; from h2.title-article-sidebar

A: Recent version of chrome tend to add transitions in nested elements (not sure about it is a bug or a feature).
Just make sure that children don't have an inherited transition

h2.title-article-sidebar {
  font-size: 14px;
  font-family: Calibri;
  color: #444;
  font-weight: 700;
  line-height: 1.25em;
  margin-top: 0;
}
.article-image-summary-sidebar {
  border: 0 solid;
  padding-bottom: 0;
  -moz-transition: .9s ease;
  -webkit-transition: .9s ease;
  -o-transition: .9s ease;
  -ms-transition: .9s ease;
  transition: .9s ease;
}
.well.sb:hover {
  color: #FFF;
  background-color: #A10000;
  text-decoration: none;
  -moz-transition: .6s ease-in-out;
  -webkit-transition: .6s ease-in-out;
  -o-transition: .6s ease-in-out;
  -ms-transition: .6s ease-in-out;
  transition: .6s ease-in-out;
}
.sb * {
  transition: 0s;
}

        20-November-2010

        TAG

               TITLE WITH H2 TAG!!!!

A: This will solve it:

h2.title-article-sidebar {
    font-size: 14px;
    font-family: Calibri;
    /* color: #444;*/
    font-weight: 700;
    line-height: 1.25em;
    margin-top: 0;
}

.article-image-summary-sidebar {
    border: 0 solid;
    padding-bottom: 0;
}

.well.sb:hover {
        color: #FFF;
        background-color: #A10000;
        text-decoration: none;
        -moz-transition: .6s ease-in-out;
        -webkit-transition: .6s ease-in-out;
        -o-transition: .6s ease-in-out;
        -ms-transition: .6s ease-in-out;
        transition: .6s ease-in-out;
    }

                20-November-2010

                TAG

               TITLE WITH H2 TAG!!!!

A: You don't have any problem in your animation as mentioned in some other answers. You have correctly written your code nor there is any specificity problem.
I am attaching a codepen link on which I was trying to solve your problem:
http://codepen.io/Sky-123/pen/mALGQZ
The animations remains intact as you have written them. The only change that I did was added the color:#444 to h2 tag through an inline statement and then removed it on hover in jQuery as it was causing concerns in animation..
Hope it solves your problem.


text:
Q: Add applications to launcher I recently installed Matlab in /usr/matlab. What do I do to make it appear in the application launcher on the top left of the taskbar?

A: You can add a launcher to the panel by right clicking on a free area on the panel and selecting "Add to panel" and then "Custom Application Launcher" (or if the application is already present in the applications menu, you can select "Application Launcher" and then select the application from the menu).
You can add an entry into the applications menu by right clicking on it and selecting "Edit menu".


text:
Q: Syntax Error when I enter a dictionary with multiple values as a DataFrame in Jupyter I'm getting a syntax error when I run this code in Jupyter. I've double and triple checked.
songs = {'Album':' ['thriller','Back','Moon'],
         'Released': [1998, 1976, 12000]}

songs_frame = pd.DataFrame(songs)

A: You have an extra '. Change your code to this:
songs = {'Album': ['thriller', 'Back', 'Moon'], 'Released': [1998, 1976, 12000]}

songs_frame = pd.DataFrame(songs)


text:
Q: Why does C++ let you overload the * and -> operators separately? Given that the * operator returns a reference to the object, and since -> is basically a shorthand for (*a).b, why does C++ define a separate overload? To me it seems like you would want to keep * and -> in sync at all costs to avoid weird bugs, but the * operator already works to define -> as well.
EDIT: for clarification, my reasoning is that if the implementation of -> is just (*a).b. if we just overloaded the * operator and treated -> basically like a macro to the (*a).b form, then the overloaded * would apply to the new expression and we would get an overloaded -> for free

A: Originally, C++ has not put any rules on which operators you define, or whether you define them in a logically symmetric manner. You can choose to implement just 1 comparison operator , or many, though later standards have tried to regularise this somewhat.
A couple of ways you could take advantage of this:

*

*You may want to stop * from being used to get your internal object, and perhaps take its address.

Yes, -> gets your internal object, but it doesn't leave it in an accessible state, a member must be called.
Effectively, -> provides better OOP than *.
Ok, yes, as HBC points out, the object caller can call the method operator->() directly and get the object, but I would like to think that this would be an obvious code smell in any code review. I mean, you could just reinterpret_cast<> the object bytes into the pointer, if we go down that path.
Of course, yes, if you are going to implement *, then you might as well implement ->, but not necessarily vice-versa.

*The other thing you might do is implement * to give you a raw blob of data or simple struct, that you might then transmit or store, but -> gives you a manipulator object paired with the data, so adding some object richness to a simple struct. This would be in a case where you can't simply add the richness directly, perhaps because the data was provided by an older C library.

You could even have the simple blob implement some compact c-style nested struct polymorphism, while -> gives you an equivalent smart manipulator.
In this way -> has provided a "view" on your data. Potentially that might be confusing, or it might be the obvious way to provide object capabilities to a piece of dumb data, that perhaps still needs to also be accessed as dumb data. All these tools are provided to API definers to use wisely.

A: The simple answer is - and you'll find it many times with C++ - why not?
You can see the same for other operators: operator+, operator- unary and binary; operator<, operator<=, operator==, operator>=, operator>, operator!=, and many others - these are deducible from each other if you use them in the standard meaning. Yet - it's possible to override them.
Now, reason for overriding might differ from project to project: sometimes, you'd like to implement an EDSL and unary * might have a radically different meaning than ->; sometimes you'd like to optimize the last bit out of the architecture; sometimes you're porting code that someone copy-pasted from e.g. Java and want to put special checks in ->, which are unneeded in *; your reasons might vary.
However, C++ doesn't enforce one specific 'good' way of doing this. In fact Bjarne himself said (at the C++ Budapest meetup), he'd like to keep C++ diverse and allow many programming styles, paradigms. So the language itself doesn't limit you.