text:
Q: Java: read a stream of byte from a socket Im setting up a software that send a message in byte [] and receive a stream of byte.
Example, send the array
byte[] replayStatuse = new byte[] { 0x55, (byte) 0xAA, 0x0B, 0x00, 0x0A,
0x1C, 0x03, 0x41, 0x01, 0x00 }

and I receive something similar. I did the test using PacketSender and I can see the answer in Hex when I ask the status.
Im using
InputStream socketInputStream = socket.getInputStream();

I already tried the various method I found here on stack and other forum but it didnt works.
Methods like this:
int read;
while((read = socketInputStream.read(buffer)) != -1)
{
   String output = new String(buffer, 0, read);
   System.out.print(output);
   System.out.flush();
}

I tried to use int read of type char, byte or other format but nothing. In my console it prints strange char (U)
Im using:
InputStream socketInputStream = socket.getInputStream();
socketInputStream.read();

Im expecting to get a byte[] and be able to read with the function:
System.out.println(Arrays.toString(byteArray));

So I can then handle the various cases and transform if need to a String or HEX
Thank you all

A: The character 'U' is not strange, it is the ASCII character for the hexadecimal value of 0x55 (i.e. the same as your first value in the test array).  The next few values in the array may be throwing off the print statement.  I recommend checking/displaying the length of 'buffer' so you know how many bytes were placed into the array.

A: I'm not sure I understand your problem completely but lets try
From the beginning you have a source of bytes, I will assume the size is unknown.
byte[] buffer = new byte[4096]; //I assume you have something like this

//Lets use this to accumulate all the bytes from the inputstream
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

int read;
while((read = socketInputStream.read(buffer)) != -1)
{
    byteStream.write(buffer, 0, read); //accumulates all bytes
}

byteStream.flush(); //writes out any buffered byte

byte[] allBytesRead = byteStream.toByteArray(); //All the bytes read in an array

This is all the bytes that were sent. Say you want to print each byte in hex
for(byte b : allBytesRead) {
    //might not be a good ideia if its something big.
    //build a string with a StringBuilder instead.
    System.out.println(String.format("%02X", b));
}

Now it's up to you how you will process these bytes.


text:
Q: Find the heaviest ball by asking at most 8 questions Given 6 balls with distinct weights. The aim is to find the heaviest of these balls.
The problem proceeds in a question answer fashion, i.e. we have to ask questions and the problem setter provides us an answer.
Each question comprises of giving 5 indexes out of the six. The answer returned with be indices of 3rd heaviest and 2nd heaviest ball (in this order).
We can ask at most 8 such questions to find the heaviest ball.
Example :
Say the indices of balls are - 1,2,3,4,5,6.
Q : 1 2 3 4 5     A : 3 4   (here 3 is the third most and 4 is the second most heaviest of the 5 balls)

Q : 1 2 3 4 6     A : 3 4

Q : 1 2 3 5 6     A : 3 5

Q : 1 2 4 5 6     A : 4 5

Q : 1 3 4 5 6     A : 4 5

Q : 2 3 4 5 6     A : 4 5

These 6 questions are sufficient to establish that ball with index 6 is the heaviest. (2 more questions can still be asked - we don't need to minimise number of questions. Also these queries may or may not order all the 6 numbers, our aim is to find the heaviest only).

I am looking for a general approach to solve this problem (preferably not involving case based analysis).

A: This doesn't seem to be programming.  And I suspect that you made up the puzzle because if it was off of a puzzle site, they should have figured out that it never needs more than 5 questions.
First of all, after the first 3 of your questions, the answer is already known to be 6.  How so?  The fact that the answer didn't change on question 2 says that either 5 and 6 are both > 4 > 3, or both < 3 < 4.  On question 3 it is revealed that 5 > 3 therefore 6 > 3.  And the fact that 5 shows up in #2 says that something is > 5, and the only possible answer is 6.  So we're done!
You just have to know what information you are collecting and apply it fully.
Now let's solve the problem in a more general way where we can figure it out even faster.
Our first round we know nothing, so we weight 1 2 3 4 5.  This will produce an answer x y.  Exchange x with 6 and try again.  Here are the possibilities:

*

*If we get y z with z not 6, then our answer is 6 in 2 questions for the same reasoning that the answer was found before.

*If we get y 6 or 6 y then it isn't x, y or 6.  We exchange x for each of the other three until the second place answer changes.  The one where that happened is the heaviest, in a max of 5 questions.

*If we get z y with z not 6 then 6 is lighter than y (else it would have pushed it down).  We now know that the answer isn't x, y, z or 6.  So we just have to exchange x with the other two in turn applying the same reasoning as before to find the heaviest in a max of 4 questions.

A: I think It could be solved this way, with example:
input: 24, 7, 12, 1986, 6, 99
Q1: Give me second and third from set {24,7,12,1986,6}
A1: second 24, third 12

Now from this answer we know that 24 and 12 would never be the heaviest. So we can just remember that idx's {0,2} won't belong to our answer.
Lets now add idx 5 which we don't know anything about.
Q2: Give me second and third from set that includes our second from first answer {24,7,1986,6,99}
A2: second 99 third 24

Now we got second that is our new value so idx at value 99 can't be the heaviest. The same situation would happen if second from answer 1 would remain the same.
On the other hand if second would become third we already know that something heavier is at idx 5 that everything before, and this is the one.
In current state we have 3 indexes that are not heaviest for sure: (idx 0)24 (idx 2)12 and (idx 5)99.
Now lets ask for some set with idx we don't have any info, like idx 1.
Q3: Give me second and third from set {24,12,1986,6,99}
A3: second 99, third 24

This answer has not chnaged from what we got from answer 2 so we know its not under index 1. Rest of the algorithm is the same deduction step.
I.E:
We don't know anything about idx 3.
Q4: Give me second and third from set {24,7,12,6,99}
A4: second 24 and third 12

Here Second has changed as it was 99 previously that means index 3 made a difference, and its is the one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Socket.io rooms doesn't work I have problem because this example don't work and i don't know why...
Server
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var port = 3250;

app.listen(port);

io.sockets.on('connection', function(socket) {

    socket.on('room', function(room) {

        socket.join(room);
    });

var room = abc123
io.sockets.in(room).emit('m', 'what is going on, party people?');

});

Client
var room = "abc123";

            socket.on('connect', function() {
                socket.emit('room', room);
            });

            socket.on('m', function(data) {
                document.write(data);
            });

I'm trying with this https://gist.github.com/crabasa/2896891 and it not helped :(
Thank you for help!

A: server:
var app = require('http').createServer(function(req,res){});
app.listen(3250);
var io = require('socket.io').listen(app)
//io = socketio.listen(server);

// handle incoming connections from clients
io.sockets.on('connection', function(socket) {
    // once a client has connected, we expect to get a ping from them saying what room they want to join
    socket.on('room', function(room) {
        socket.join(room);
    });

    socket.on('say',function(data){
        io.sockets.in(data.room).emit('message',data.message);
    })
});

client:
<!DOCTYPE HTML>
<html>
<head>
    <script src="http://192.168.1.7:3250/socket.io/socket.io.js"></script>
<script>
// set-up a connection between the client and the server
var socket = io.connect('http://192.168.1.7:3250');

// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";

socket.on('connect', function() {
   // Connected, let's sign-up for to receive messages for this room
   socket.emit('room', room);
});

socket.on('message', function(data) {
   console.log('Incoming message:', data);
});
</script>
</head>
<body>
    <button onclick='socket.emit("say",{"room":room,"message":"hello world"})'>Say hello world</button>

</body>
</html>

change 192.168.1.7 to your ip address,good luck!


text:
Q: Importing KML styles into QGIS Can I import a KML file with styles to QGIS 3? (As of now version 3.4.1)
I have a .kml file with cycling routes that have a different color for the time between sunset and sunrise.
When I import the .kml to QGIS all styles are overridden.
Is there a way to display or even edit the preset KML features in QGIS?
A trivial sample file: https://gist.github.com/mkpaa/a6a6f433366019eabdc2811ecafba2af

A: Sorry but you can't do it using your raw data directly. You should add first some attribute (for instance "Name") readable by qgis. Then you can aplly a categorized style and set, if you wish, the exact same color (ee222222 and eecccccc in your data).
In case your data is not too large you can edit that attribute in google earth/properties in each segment or adding the kml to google maps and then export again to kml.
UPDATE:
There is a way to add the colour attribute in order to be readed by QGIS. Just edit the .kml document with notepad and use this code:
Replace en Notepad -->
<Style><LineStyle><color>eecccccc</color>
By this:
<name>GREY</name><Style><LineStyle><color>eecccccc</color>

Replace in Notepad -->
This:
<Style><LineStyle><color>ee222222</color>
By this:
<name>BLACK</name><Style><LineStyle><color>ee222222</color>

Now you can add it to QGIS and sorry, you will not have those exact colors but if you always name those in the same way, you just need to set the style once and then save that style layer in .qml

A: If you are comfortable with using the command line, and your KML file has the styles referenced in individual placemarks using styleURLs, you can try an approach as follows:

*

*Instead of just importing the KML into QGIS directly, convert it to a gpkg using the command line utility (installed with GDAL/QGIS) ogr2ogr. An example you can build from is at my question here (see Approach 2 there - which doesn't work for me due to multiple folders but should work for you if you have only one folder or a small number of folders).

*Then add layer(s) in QGIS from the resultant gpkg instead. The approach in step 1 will now have added a field called OGR_STYLE to your layer that contains the styleURL in the KML file.

*Now style your layer in QGIS, using an expression depending on OGR_STYLE to change the colour (or anything else you want, e.g. dashed or dotted lines).
As some of the other options, this is not an easy point'n'click solution, but it should get you what you want.

A: Here are some answers for you, but their difficulty may scare you off.
Nethertheless, QGis have a dedicated style file format, named .qml
in order to make one, double-click on the layer in the legend, a box will open, go on the Style tab.
Then you should be able to define the style you want by adding rules and save it for a later use.
Now, you have to apply it. In order to do so, open the python console (Ctrl+Alt+P) and find the vector layer you need, then use this function vl.loadNamedStyle(pathToQml) to apply the stylefile to it.
PS : In order to get the vector layer object you are looking for, you could use this function that makes a list of the layers you selected in the legend.
selectedLayers = iface.legendInterface().selectedLayers()


text:
Q: Dim Form as as specific Form with if-statement I have a Sub, which works for two different Forms. When I call the Sub from one of those forms I give the Form to the Sub as a parameter.
How can I set the correct for as a variable in the Sub?
Here are two ways I have tried this, but they do not work.
Shared Sub SetDataGridViewg(ByRef Form As Form, AusAuftrag As Boolean)
    ' ERROR: A common type can not be derived, and Option Strict On does not allow the assumption of the Object type.
    Dim AdressenÜbersicht = If(AusAuftrag, CType(Form, AdressenÜbersichtAusAuftrag), CType(Form, Startseite))

    ' ERROR: The variable "AdressenÜbersicht" hides a variable in an enclosing block.
    If AusAuftrag Then
        Dim AdressenÜbersicht As AdressenÜbersichtAusAuftrag = CType(Form, AdressenÜbersichtAusAuftrag)
    Else
        Dim AdressenÜbersicht As Startseite = CType(Form, Startseite)
    End If

    ' ...
End Sub


text:
Q: How can I make pagination run automatically with JS? I needed to use Pagination somewhere on the page. I'll show you the data from the service.
I found a sample. It works fine, but when I make the created row and window values 7, does not go to page 3. How can I solve this?
Most importantly, there's something I'd like to add here. I couldn't find a solution.
I want the buttons in the Pagination section to work automatically. For example, I have 3 pages. Opens on Page 1. I want it to go to Page 2 after 20 seconds and Page 3 after 20 seconds.
And as for the last page, he needs to go back to Page 1. I'd like to do a 20-second cycle between pages.
Any idea how I can figure it out?
Example code I found:
https://jsfiddle.net/ivanov11/e18zfsau/
I use these fields as Comment lines
 if (state.page != 1) {
        wrapper.innerHTML = `<button value=${1} class="page btn btn-sm btn-info">« First</button>` + wrapper.innerHTML
    }

    if (state.page != pages) {
        wrapper.innerHTML += `<button value=${pages} class="page btn btn-sm btn-info">Last »</button>`
    }

A: A simple solution would be to use setInterval to click the next page's button.
setInterval(function() {

    var page = state.page + 1;
    var btn = $("button[value=" + page + "]");

    // check if at the end and start again
    if (btn.length == 0)
        btn = $("button[value=1]");

    btn.click();
}, 20000);

Updated fiddle: https://jsfiddle.net/q8e9fnL0/
A better solution would be to move the click callback code to its own function function selectPage(page) {... and call that.  In this case you would need check that the page requested is valid otherwise it would keep going with empty pages.  You'd still need a check against max pages (Math.round(querySet.length / rows);)


text:
Q: Removing all the lines starting with | in a text file using shell I need to remove all the lines starting with an symbol |  using shell
I have a text file which has some lines which starts with | and i need to remove it using shell
Example file
Example
Example of txt file

|I need to remove this
|I need to remove this too

I am new to shell can any one tell me how can i do that or give me some tutorial to achieve this.

A: sed '/^|/d' filename > filename

A: ugurarpaci's approach is good, but fundamentally flawed:
sed '/^|/d' filename

will produce the output you desire, but you cannot simply redirect it back to the file.  You can do several things:
sed '/^|/d' filename > new-file
sed -i '/^|/d' filename  # If your sed supports -i and you don't care
                         # about breaking hard links
sed '/^|/d' filename > tmp-file && mv tmp-file filename


text:
Q: Line break in TextView adds padding This is my TextView:
public IconifiedTextView(Context context, IconifiedText aIconifiedText) {
    super(context);

    /*
     * First Icon and the Text to the right (horizontal), not above and
     * below (vertical)
     */
    this.setOrientation(HORIZONTAL);

    mIcon = new ImageView(context);
    mIcon.setImageDrawable(aIconifiedText.getIcon());
    // left, top, right, bottom
    mIcon.setPadding(0, 3, 7, 3); // 5px to the right

    /*
     * At first, add the Icon to ourself (! we are extending LinearLayout)
     */
    addView(mIcon, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));

    mText = new TextView(context);
    mText.setText(aIconifiedText.getText());
    mText.setTextSize(16);
    /* Now the text (after the icon) */
    addView(mText, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));

    mInfo = new TextView(context);
    mInfo.setText(aIconifiedText.getInfo());
    /* Now the Info (below the Text) */
    addView(mInfo, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
}

And when i call the object I have:
this.directoryEntries.add(new IconifiedText(currentFile
                    .getPath(), currentIcon, "\nInfo"));

Where "\nInfo" will be replaced by something later. When i run this, I get this:
d
 Info
data
    Info
dev
   Info
system
      Info

How do i get rid of this padding to the left of Info so they both start at the same place?

A: this.directoryEntries.add(new IconifiedText(currentFile
                    .getPath(), currentIcon, "\r\nInfo"));


text:
Q: wtf validate on submit only the token, not the fields I use Flask WTF and their token to prevent cross site attacks.  My pages can consist of many fields, some of which are not relevant and contain no user data on POST.  I have separate form submissions for various fields, but Flask validates ALL fields on the entire page, not just the ones in the form submit.
Is there a function in Flask to validate only the token on submit, and not ALL the fields on the entire page, because after validation a redirect back to the page will visually error the non-relevant fields.
I understand that I can use a script before POST to disable the non-relevant fields, but this method seems in excess.
Thanks,
Cliff

A: You can use an Optional validator so empty fields return no errors as they are specifically not required.
You can also hook into the validation process and write your own script such as this snippet http://flask.pocoo.org/snippets/64/
You could use define multiple forms which reference different fields on the page depending on which form is submitted on the page.
You may be able to make use of the pre_validate function defined here http://wtforms.readthedocs.io/en/latest/fields.html#the-field-base-class, although I have not used this myself.


text:
Q: Troubleshooting an Application.OnTime Function in VBA I have a macro that I need to run every 30 min from 6pm until 230pm the following day every day and I keep the sheet open.
Upon opening the sheet, its intended to schedule the UpdateCaller() macro for the next 30 min period. Once that runs, it basically checks if the current time falls within my constraints, if so call PopulateData then schedule for the next 30 min period and repeat.
For some reason - I can't get the actually Call PopulateDate to execute. I've added debug.print lines of code to both the worksheet.open macro and the updatecaller macro and the output is below. I see it outputing the next scheduled time so I know it's successfully running through both macros. Also, when I step into the macro and just hit F5, it runs correctly and PopulateData is called. I also had it working yesterday without any problems.
I've tried closing all excel sheets except this one, restarting excel, restarting the computer but nothing seems to be working.
Any ideas/suggestions would be greatly appreciated.
Private Sub Workbook_Open()

Dim t As Long
Dim opentime As Date

t = 24 / (30 / 60)
Application.OnTime TimeValue(Format(WorksheetFunction.Ceiling(Now * t, 1) / t, "HH:mm:ss")), "UpdateCaller"

opentime = TimeValue(Format(WorksheetFunction.Ceiling(Now * t, 1) / t, "HH:mm:ss"))
Debug.Print opentime

End Sub

Public Sub UpdateCaller()
    Dim tme As Date
    Dim t As Long

    If TimeValue(Format(Now, "HH:mm:ss")) <= TimeValue("14:30:00") Or TimeValue(Format(Now, "HH:mm:ss")) >= TimeValue("18:00:00") Then
        Call PopulateData
    End If

    t = 24 / (30 / 60)
    tme = TimeValue(Format(WorksheetFunction.Ceiling((Now + TimeValue("00:00:05")) * t, 1) / t, "HH:mm:ss"))
    Debug.Print "Procedure ""UpdateCaller"" will next run at: ", tme

    Application.OnTime tme, "UpdateCaller"
End Sub

Edit1: I've also added the following line of code right before Call PopulateData and at 1pm it didn't print that. It seems like for some reason when it's scheduled to run it's not entering that If statement but when I step through the code, it enters it just fine. Any thoughts about what could be wrong with that If statement?
Debug.Print "Entered Execution Block"

Edit: Is it possible that because I have the UpdateCaller in the ThisWorkbook Object and the actual PopulateDate in Module 1 it's causing issue?


text:
Q: Why is svm not so good as decision tree on the same data? I am new to machine learning and try to use scikit-learn(sklearn) to deal with a classification problem. Both DecisionTree and SVM can train a classifier for this problem.
I use sklearn.ensemble.RandomForestClassifier and sklearn.svm.SVC to fit the same training data(about 500,000 entries with 50 features per entry). The RandomForestClassifier comes out with a classifier in about one minute. The SVC uses more than 24 hours and still keeps running.
Why does the SVC perform so inefficiently? Is the data set too big for SVC? Is SVC improper for such problem?

A: "whether a problem is linear or not"
In a binary classification problem, if the dataset can be separated by a hyper-plane, it's a linear problem.
If the dataset is not linear separable, while you try a linear classifier to find such a hyper-plane that is not existed at all, the algorithm may seem to run forever.
One suggestion: You can sample a small portion of your data, and try these algorithms to see if it works in a small dataset. Then increase the dataset to check when does these problem occur.

A: Decision Trees and Random Forests are actually extremely good classifiers. While SVM's (Support Vector Machines) are seen as more complex it does not actually mean they will perform better.
The paper "An Empirical Comparison of Supervised Learning Algorithms" by Rich Caruana compared 10 different binary classifiers,  SVM, Neural-Networks, KNN, Logistic Regression, Naive Bayes, Random Forests, Decision Trees, Bagged Decision Trees, Boosted Decision trees and Bootstrapped Decision Trees on eleven different data sets and compared the results on 8 different performance metrics.
They found that Boosted decision trees came in first with Random Forests second and then Bagged Decision Trees and then SVM
The results will also depend on how many classes you are actually classifying for.

A: Possibilities include the use of an inappropriate kernel (e.g. a linear kernel for a non-linear problem), poor choice of kernel and regularisation hyper-parameters.  Good model selection (choice of kernel and hyper-parameter tuning is the key to getting good performance from SVMs, they can only be expected to give good results when used correctly).
SVMs often do take a long time to train, this is especially true when the choice of kernel and particularly regularisation parameter means that almost all the data end up as support vectors (the sparsity of SVMs is a handy by-product, nothing more).
Lastly, the no free lunch theorems say that there is no a-priori superiority for any classifier system over the others, so the best classifier for a particular task is itself task-dependent.  However there is more compelling theory for the SVM that suggests it is likely to be  better choice than many other approaches for many problems.

A: That is because of the nature of their decision boundaries.
The decision boundary of SVM (with or without kernel) is always linear (in the kernel space or not) while the decision boundary of the decision tree is piece-wise linear ( non-linear).


text:
Q: Attempting to replicate GMSPlacesClient: autoCompleteQuery function to populate a UITableView manually My current code to populate a tableView with addresses from the Google Places API endpoint is as follows:
However, I want to create a custom client to handle the functionality that autoCompleteQuery, provided by Places, takes care of but manually. I'm assuming this calls for the address JSON to be parsed again, and iterated through, then stored in an array. Please let me know if you have a solution. The commented code works perfectly, I'm trying to achieve the same result manually.
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){

//        let mapsClient = GMSPlacesClient()
//        mapsClient.autocompleteQuery(searchText, bounds: nil, filter: nil {(results, error: NSError?) in
//
//            self.resultsArray.removeAll()
//
//            if results == nil{
//                return
//            }
//
//            for result in results! {
//
//                if let result = result as GMSAutocompletePrediction! {
//                    self.resultsArray.append(result.attributedFullText.string)
//                }
//            }
//
//            self.searchResultsClient.reloadDataWithArray(self.resultsArray)
//        }

    gmsFetcher?.sourceTextHasChanged(searchText)

    self.searchResultsClient.reloadDataWithArray(self.resultsArray)
    print(resultsArray)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

extension MainMapViewController: GMSAutocompleteFetcherDelegate {
func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {

    self.resultsArray.count + 1

    let resultsStr = NSMutableString()
    for prediction in predictions {
        resultsStr.appendFormat("%@\n", prediction.attributedPrimaryText)
    }

    resultText?.text = resultsStr as String
    self.resultsArray.append(resultsStr as String)
    self.searchResultsClient.reloadDataWithArray(self.resultsArray)
}
    func didFailAutocompleteWithError(error: NSError) {
        resultText?.text = error.localizedDescription
    }
}

A: You can use GMSAutocompleteFetcher, which wraps the autocompleteQuery method on GMSPlacesClient. The fetcher throttles requests, returning only results for the most recently entered search text and provides no UI elements.
Steps to implement GMSAutocompleteFetcher:

*

*Implement the GMSAutocompleteFetcherDelegate protocol.

*Create a GMSAutocompleteFetcher object.

*Call sourceTextHasChanged on the fetcher as the user types.

*Handle predictions and errors using the didAutcompleteWithPredictions and didFailAutocompleteWithError protocol methods.

Sample code demonstrating the implementation steps in using the fetcher can be found in Use the fetcher.

A: SOLVED: Here's how I ultimately solved the problem of updating UITableView rows with autocomplete when text updated from a UISearchBar.
func searchBar(searchBar: UISearchBar, textDidChange searchText: String){

    self.resultsArray.removeAll()
    gmsFetcher?.sourceTextHasChanged(searchText)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }
}

//Implement GMSAutoCompleteFetcherDelegate protocol to handle custom string prediction
extension MainMapViewController: GMSAutocompleteFetcherDelegate {
    func didAutocompleteWithPredictions(predictions: [GMSAutocompletePrediction]) {

    for prediction in predictions {

        if let prediction = prediction as GMSAutocompletePrediction!{
        self.resultsArray.append(prediction.attributedFullText.string)
        }
    }

    self.searchResultsTable.reloadDataWithArray(self.resultsArray)
    print(resultsArray)
    }
    func didFailAutocompleteWithError(error: NSError) {
        resultText?.text = error.localizedDescription
    }
}


text:
Q: What is file-descriptor? While trying to learn socket programming, I saw the following code:
int sock;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

I browsed through the man page and found that socket returns a file descriptor. I have tried searching the internet and other similar questions here but I couldn't understand what file descriptor really is. That would be great if someone could explain file descriptor in easy language.

A: In Unix/ Linux operating systems, a file descriptor is an abstract indicator (handle) used to access a file or other IO(input/output) resource, such as a pipe or network socket.
Normally a file descriptors index into a per-process file descriptor table maintained by the kernel in Linux/Unix OS, that in turn indexes
into a system-wide table of files opened by all processes, called the file table.
This table records the "mode" with which the file or the other resource has been opened
for the following operations(There are more operations)

*

*reading

*writing

*appending

*writing

and possibly other modes.
It also indexes into a third table called the inode table that describes the actual underlying files.

A: File Descriptors are nothing but mappings to a file. You can also say these are pointers to a file that the process is using.
FDs are just integer values which act as pointers to process resources.
Whenever a process starts, an entry of the running process is added to the /proc/<pid> directory. This is the place where all of the data related to the process is kept. Also, on process start the kernel allocates 3 file-descriptors to the process for communication with the 3 data streams referred to as stdin, stdout and stderr.
the linux kernel uses an algorithm to always create a FD with the lowest possible integer value so these data-streams are mapped to the numbers 0, 1 and 2.
Let's say in you code you opened a file to read from or to write to. This means the process needs access to a resource and it has to create a mapping/pointer for this new resource.
To do this, the kernel automatically creates a FD as soon as the file is opened by your code.
If you run ls -l /proc/<pid>/fd/ you will se an additional FD created there with id 4 (can be some other number also if the program has used other resources)

A: I think of file descriptors as (indirect, higher-level) pointers to opaque file objects maintained by the kernel.
Normally, when you deal with objects maintained by a library, you pass to the library pointers to objects that you're not supposed to  dereference and manipulate yourself.
For kernel objects, this it's not just that you're not supposed to manipulate them yourself -- you literally can't because they live in a different address space that's not at all accessible to you. And because they live in a different address space, pointers wouldn't be a meaningful way of referring to them.
You need a token or handle which the kernel would internally resolve to a pointer that's meaningful in the kernel address space. File descriptors are such tokens in integer form.
For the kernel:
your_process_id + your_file_descriptor => kernels_file_object_pointer

(or an EBADF error if a given filedescriptor may not be resolved to a file object pointer for the given process)

A: There are two related objects: file descriptor and file description. People often confuse these two and think they are the same.
File descriptor is an integer in your application that refers to the file description in the kernel.
File description is the structure in the kernel that maintains the state of an open file (its current position, blocking/non-blocking, etc.). In Linux file descripion is struct file.
POSIX open():

The open() function shall establish the connection between a file and a file descriptor. It shall create an open file description that refers to a file and a file descriptor that refers to that open file description. The file descriptor is used by other I/O functions to refer to that file. The path argument points to a pathname naming the file.
The open() function shall return a file descriptor for the named file that is the lowest file descriptor not currently open for that process. The open file description is new, and therefore the file descriptor shall not share it with any other process in the system.


text:
Q: How super() works with private variables? There is an interesting question on python 3.5. For example I've smth like:
class A:
  __x = 0
  def __init__(self, x):
    self.__x = x

  def set_x(self,x): __x=x
  def get_x(self): return x

class B(A):
  __y = 0
  def __init(self, x, y)
    self.__y = y
    super(B, self).__init__(x)

  def set_y(self,y): __y=y
  def get_y(self): return y

  def toString(self): return "x = {} and y = {}".format(self.__x,
                                                        self.__y);
test = B(7,3)
test.toString()

Why do I have an error here: "B object has no attribute _B__x", if the method super()  let me to use all methods of parante class?
Sure, if I write, like:
def toString(self): return "x = {} and y = {}".format(self.get_x(),
                                                      self.__y);

It works well!

A: You do not get access to private variables/members through super().
So in order to access B.__x, you will have to do
def toString(self): return "x = {} and y = {}".format(self._B__x,
                                                    self.__y);


text:
Q: Something wrong with my validates in Rail 4? I want to show my validates in "users.rb". Can anyone help?. I've watched some video tutorial then found myself that was not "define new" but I did not know how to resolve this.
user_controller.rb
class UsersController::ApplicationController
  def login
    if params[:user]
      @notice   = "LOGIN FAILED"
      @email    = params[:user][:mailaddress]
      @password = params[:user][:password]
      @user     = User.find_by(mailaddress: @email)

      if @user
        @member = Member.find_by(user_id: @user.id)
        if @member
          @hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @member.salt, @password)
          if @hash == @member.hashed_password
            # SUCCESS
            @notice = "LOGIN SUCCESSFULL"
          end
        end
      end
    end
  end
end
-------
user.rb

class User::ActiveRecord::Base
  has_one :member
  validates :mailaddress, presence: {message: "Email need inputed"} #want to show this validates in login.html.haml
end
---------------
login.html.haml

= form_for(:user, url:login_path) do |f|
  %div.login
    = f.label "Email", class:'control-label'
    = f.email_field :mailaddress, class: 'form-control'
    = f.label "Password", class: 'control-label'
    = f.password_field :password, class: 'control-label'
    %div.btn-are
      = f.submit 'Finish', class: 'btn'

A: Validations works only on model create/update but not on some actions like login.
Please see the docs for more info.
You can show flash if some params are missing
user_controller.rb
class UsersController::ApplicationController
  def login
    if params[:user]
      unless params[:user][:mailaddress]
        flash[:error] = "Email is required"
        render :your_login_path
      end
      @notice   = "LOGIN FAILED"
      @email    = params[:user][:mailaddress]
      @password = params[:user][:password]
      @user     = User.find_by(mailaddress: @email)

      if @user
        @member = Member.find_by(user_id: @user.id)
        if @member
          @hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @member.salt, @password)
          if @hash == @member.hashed_password
            # SUCCESS
            @notice = "LOGIN SUCCESSFULL"
          end
        end
      end
    end
  end
end

- flash.each do |name, msg|
  = content_tag :div, msg, class: name

= form_for(:user, url:login_path) do |f|
 %div.login
   = f.label "Email", class:'control-label'
   = f.email_field :mailaddress, class: 'form-control'
   = f.label "Password", class: 'control-label'
   = f.password_field :password, class: 'control-label'
   %div.btn-are
    = f.submit 'Finish', class: 'btn'

The code above is untested, but should work.
Here is the flash documentation
But I'm strongly recommend to use devise to perform sign_in/sign_up of users.


text:
Q: Running dotnet isolated in debug mode I have created an Azure function V4 on .NET6 running in dotnet-isolated mode.
When i start the function using the regular run configuration it starts up fine.
When i then attach the debugger manually i can succesfully debug the function.
However when i start the function using the debug configuration it looks like the process fails to attach and an exception is thrown:
[2023-02-27T09:07:42.258Z] Failed to start a new language worker for runtime: dotnet-isolated.
[2023-02-27T09:07:42.259Z] System.Private.CoreLib: A task was canceled.

The function start up command is the following:
I am using azure toolkit for rider version: 3.50.0.1546-2022.3
I am using rider version 2022.3.2

A: When I have Function Host Arguments as host start --pause-on-error,

then debugging is working fine with this configuration without attaching to any process:

After changing the Function Host Arguments to host start --dotnet-isolated-debug --verbose in the Debug Configuration and do not attach to any process. Keep the breakpoint and hit debug with the Function App Configuration:

It's a .NET 6 Isolated v4 Azure Function Project.

A: Completely reinstalled Azure CLI and Azure functions core tools, i can debug now.


text:
Q: Android recycled bitmap error I'm goning to resize bitmap and insert into imageView.
However I encountered recycle error...
error message :
05-08 13:32:48.948: E/AndroidRuntime(4792):
Process: com.test.myapp, PID: 4792
05-08 13:32:48.948: E/AndroidRuntime(4792):
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@2f1aa6ad
05-08 13:32:48.948: E/AndroidRuntime(4792):     at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1225)
05-08 13:32:48.948: E/AndroidRuntime(4792):     at android.view.GLES20Canvas.drawBitmap(GLES20Canvas.java:600)
05-08 13:32:48.948: E/AndroidRuntime(4792):     at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:544)
05-08 13:32:48.948: E/AndroidRuntime(4792):     at android.widget.ImageView.onDraw(ImageView.java:1187)
05-08 13:32:48.948: E/AndroidRuntime(4792):     at android.view.View.draw(View.java:16209)
Could you give an advice how to resolve my situation..
My Code :
Bitmap photo = BitmapFactory.decodeFile(full_path);
SaveBitmapToFileCache(photo, Environment.getExternalStorageDirectory().getPath() + "/test/"+filename);

imgview.setImageBitmap(photo);

private Bitmap getBitmapSize(Bitmap photo){
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Bitmap bmp = photo;
    Bitmap resizeBmp = null;
    if(bmp.getWidth() > 2000 || bmp.getHeight() > 2000)
        resizeBmp = resizingBitmap(mContext, bmp, bmp.getWidth()/10 , bmp.getHeight()/10, false);
    else if(bmp.getWidth() > 1000 || bmp.getHeight() > 1000)
        resizeBmp = resizingBitmap(mContext, bmp, bmp.getWidth()/5 , bmp.getHeight()/5, false);
    else
        resizeBmp = resizingBitmap(mContext, bmp, bmp.getWidth() , bmp.getHeight(), false);

    resizeBmp.compress(CompressFormat.PNG, 90, os);
    bmp.recycle();

    return resizeBmp;
}

private void SaveBitmapToFileCache(Bitmap bitmap, String strFilePath) {
    File fileCacheItem = new File(strFilePath);
    OutputStream out = null;

    try{
        fileCacheItem.createNewFile();
        out = new FileOutputStream(fileCacheItem);

        bitmap.compress(CompressFormat.JPEG, 100, out);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try{
            out.close();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

Why do I meet recycle error?

A: Use these lines of code..
if(resizeBmp !=null)
{
  resizeBmp .recycle();
  bmp.recycle();
  bmp=null;
  resizeBmp =null;
}


text:
Q: Spring Boot @Autowired Environment throws NullPointerException I have a simple SpringBoot application in which i am using the Environment.class to access the properties under application.properties file. The Environment bean works when it is accessed in the main method of the Application.class
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.cisco.sdp.cdx.consumers")
public class StreamingConsumerApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(StreamingConsumerApplication.class, args);
        Environment env = context.getBean(Environment.class);
        StreamingConsumerFactory factory = context.getBean(StreamingConsumerFactory.class);
        StreamingConsumer streamingConsumer = factory.createStreamingConsumer(StreamType.valueOf(env.getRequiredProperty("streaming.application.type")));
        streamingConsumer.consume();
    }
}

When the same is used in a different class it throws NullPointerException. I tried annotating the class with @Configuration,@Component,@Repository,@Service annotations but did not work.
I tried @Autowired as well as @Resource annotations. But, it didn't work.
@Component
public class InventoryStreamingConsumer implements StreamingConsumer {

    @Autowired
    private Environment env;
    @Autowired
    private JavaSparkSessionSingleton sparksession;
    @Autowired
    private StreamingContext _CONTEXT;
    private final Map<String, String> kafkaParams = new HashMap<String, String>();

    @Override
    public void consume() {
        if(env == null) {
            System.out.println("ENV is NULL");
        }
        System.out.println(env.getRequiredProperty("kafka.brokerlist"));
        kafkaParams.put("metadata.broker.list", env.getRequiredProperty("kafka.brokerlist"));
        Set<String> topics = Collections.singleton(env.getRequiredProperty("kafka.topic"));

    // Unrelated code.
}

I tried following the answers provided in the below questions
Spring Boot - Environment @Autowired throws NullPointerException
Autowired Environment is null
I am looking for suggestions on solving the issue.

A: The @Configuration annotation is misused here for InventoryStreamingConsumer. Try @Component, @Repository or @Service.

UPDATE
Another misuse is
StreamingConsumer streamingConsumer = factory.createStreamingConsumer(StreamType.valueOf(env.getRequiredProperty("streaming.application.type")));

@Autowired or @Resource can only work in bean created by Spring. the streamingConsumer created by your StreamingConsumerFactory factory cannot use @Autowired for injection of its properties.
You should create an @Configuration class, to tell Spring to create streamingConsumer from your factory. Like this
@Configuration
public class ConsumerCreator {

    @Autowired
    StreamingConsumerFactory factory;

    @Bean
    public StreamingConsumer streamingConsumer() {
        return factory.createStreamingConsumer(StreamType.valueOf(env.getRequiredProperty("streaming.application.type")));
    }
}

And use no annotation for InventoryStreamingConsumer, meanwhile use
        StreamingConsumer streamingConsumer = context.getBean(StreamingConsumer.class);

in your StreamingConsumerApplication.main() method instead to retrieve streamingConsumer

A: First, please annotate the main class with only @SpringBootApplication
@SpringBootApplication
public class StreamingConsumerApplication {
}

@ComponentScan is required if your packages are not within the same structure as main class with main class being outside the sub-package and inside parent package with every other class in the same or some sub-package of parent package.
Second, Please create a Configuration class and annotate it with @Configuration separately and define a @Bean there for StreamingConsumer streamingConsumer and than it can be @Autowired or injected in the InventoryStreamingConsumer class.
Third, where is the @Bean for JavaSparkSessionSingleton defined? Are you sure it can be AutoConfigured for injection
Fourth, InventoryStreamingConsumer can be a @Component, injecting Environment with @Autowiring will work once the above things are sorted.
Also, recommending to change your class to this for the sake depending on how consume() method is used.
@Component
public class InventoryStreamingConsumer implements StreamingConsumer {

private final Environment env;

private final JavaSparkSessionSingleton sparksession;

private final StreamingContext _CONTEXT;

private final Map<String, String> kafkaParams = new HashMap<String, String>();

@Autowired
public InventoryStreamingConsumer(Environment env, JavaSparkSessionSingleton sparkSession, StreamingContext context) {
    this.env = env;
    this.sparksession = sparkSession;
    this._CONTEXT = context;
}

@Override
public void consume() {
    if(env == null) {
        System.out.println("ENV is NULL");
    }
    System.out.println(env.getRequiredProperty("kafka.brokerlist"));
    kafkaParams.put("metadata.broker.list", env.getRequiredProperty("kafka.brokerlist"));
    Set<String> topics = Collections.singleton(env.getRequiredProperty("kafka.topic"));

// Unrelated code.
}

A: I have similar issue but read the properties from different file and different location like common/jdbc.properties. I solved this issue by doing this:
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(value = {"classpath:common/jdbc.properties"})
public class ExternalConfig implements EnvironmentAware {

private Environment environment;

public void setEnvironment(Environment environment) {
    this.environment = environment;
}

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
}

public String getJdbcUrl() {
    return environment.getProperty("jdbc.url");
}
}

A: Try adding
@PropertySource("classpath:application.properties")

on InventoryStreamingConsumer class
This is how am using it
@Configuration
@ComponentScan({ "com.spring.config" })
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class HibernateConfiguration {

    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";

    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
        return dataSource;
    }


text:
Q: Open a component in a new tab in Angular? I have a component which I want to open in two places :

*

*inside my application window (as a child component)

*as a new browser tab \ window
I want to keep the component on the same application since it uses common services.
Is there an option to open it in a new browser tab \ window ?
maybe with a router?
If so, how can I pass parameters to it? (using @Input() or something else)?


text:
Q: can't catch "System.IO.DirectoryNotFoundException" in C# I made some code to read a file and have a problem with try-catch block.

A first chance exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll
Additional information: Could not find a part of the path 'D:...\WpfApplicationExample\bin\Debug\KeyWord\ROS\KeyWord_Booting_Time.json'.

I always meet this exception although already handled it.
my directory does definitely not exist, but I already handle it by catch block, so why my app still crashes at this: StreamReader sr = new StreamReader(filePath).
Please take a look at the code below and tell me what is the problem?
        try
        {
            StreamReader sr = new StreamReader(filePath);
            jsonString = sr.ReadToEnd();
            sr.Close();
        }
        catch (System.IO.DirectoryNotFoundException e)
        {
            Log.log(TAG, "getKeyWords", e.Message);
        }
        catch (System.IO.IOException e)
        {
            Log.log(TAG, "getKeyWords", e.Message);
        }
        catch (Exception e)
        {
            Log.log(TAG, "getKeyWords", e.Message);
        }

A: for anyone has same problem: refer below docs for understanding about first chance and second chance exceptions.
[https://learn.microsoft.com/en-us/archive/blogs/davidklinems/what-is-a-first-chance-exceptione]
my app is not really crash.. it just shows me a message to report me when an exception occurs.. if I click "continue" in message box.. it will keep running my app and land to catch block as expected.
FYI
thank all.


text:
Q: When Django models field is empty, set value to the Default value Whenever the user doesn't add a value, I need my Django models to replace the otherwise empty field with the value set in default.
My models looks like this:
not_before = models.TimeField(blank=True, null=True, default='00:00:00')
max_num_per_day = models.IntegerField(blank=True, null=True, default=0)

I tried every combination of null, blank and default but no matter what I do, the fields gets replaced by null instead of '00:00:00' and 0.
Is there anyway I can force it to the default value whenever the field is empty?

A: you can set up your form  with a default function like:
class YourForm(forms.Form):
.....
def clean_field(self):
        data = self.cleaned_data['not_before']
        if not data:
            data = '00:00:00'

or write a function in your model like:
class Molde(models.Model):
  not_before = models.TimeField(blank=True, null=True, default='00:00:00')
  def time(self):
    if self.not_before:
        return self.not_before
    else:
        return '00:00:00'

In this case you would call the function instead of the model field itself. You can also take a look at this.
Hope that helps.

A: from what I understood from your question is you just want to set it to default. you can use:
https://code.djangoproject.com/ticket/6754
don't
not_before = models.TimeField(blank=True, null=True, default='00:00:00')

instead,
import datetime
not_before = models.TimeField(default=datetime.time(0,0))
max_num_per_day = models.IntegerField(default=0)

A: It seems you are using a ModelForm to grab the data from the user.
In this case, the solution proposed by sasuke will not work. First, you would have to set the required param to False in your form fields, so you would stop seing those "This field is required" messages. Still, you would see errors when saving the form. Even if your model instance is initialized with the default value, the form will replace it with None, since there is an existing field in the form matching the field in the model and its value is None.
My solution is to override the values in the model instance before saving them:
model_instance = myform.save(commit=False)
if not model_instance.not_before:
    model_instance.not_before = '00:00:00'
if not model_instance.max_num_per_day:
    model_instance.max_num_per_day = 0
model_instance.save()


text:
Q: Joi validate union type I have union type PaymentTerm:
type PaymentTerm =
    | { type: 'AdvancePayment' }
    | { type: 'PaymentGoal'; netPaymentDays: number }

I want to validate it using Joi.alternatives:
  Joi.object({
    type: Joi.string().required().valid('AdvancePayment')
  }),
  Joi.object({
    type: Joi.string().required().valid('PaymentGoal'),
    netPaymentDays: Joi.number().required().messages({
      'any.required': '{{#label}} is required'
    })
  })
)

const { error, value } = schema.validate({
  type: 'PaymentGoal'
})

Now I would expect to get "netPaymentDays" is required but I get "value" does not match any of the allowed types.
How can I get the "nested" errors instead of the generic ones for the alternatives?

A: You've mentioned the correct way to resolve this but I can't see it being used in your example.

I want to validate it using Joi.alternatives

A possible solution for your schema would be:
Joi.object().keys({
    type: Joi.string().valid('AdvancePayment', 'PaymentGoal').required(),
    netPaymentDays: Joi.alternatives().conditional('type', {
        is: 'PaymentGoal',
        then: Joi.number().required(),
        otherwise: Joi.forbidden()
    })
});


text:
Q: Simple legend box below multiple TikZ pictures I have three subfigures in a figure, each has three TikZ pictures inside and a caption. Now I would like to add a legend for all TikZ pictures together.
I searched through other posts and tried different solutions. However I couldn't find anything to make it work. The closest one I found, was the proposed matrix from this question: TikZ picture: how to add a legend?
I used the matrix in the bottom right TikZ picture with labels without the nodes, since I don't have any symbols.
\documentclass{article}
\usepackage{tikz}
\usepackage{amsmath,amssymb}
\usepackage{caption}
\usepackage{subcaption}
\begin{document}

\begin{figure}%
\centering
\begin{subfigure}[c]{\textwidth}
\begin{tikzpicture}
\draw[step=1cm,gray,very thin] (0,0) grid (4,4);
\end{tikzpicture}
\begin{tikzpicture}
\draw[step=1cm,gray,very thin] (0,0) grid (4,4);
\end{tikzpicture}
\begin{tikzpicture}
\draw[step=1cm,gray,very thin] (0,0) grid (4,4);
\matrix [draw,below left] at (current bounding box.south east) {
  \node [label=right:R...ROBOT] {}; \\
  \node [label=right:G...GOAL] {}; \\
  \node [label=right:O...OBSTACLE] {}; \\
};
\end{tikzpicture}
\end{subfigure}
\end{figure}
\end{document}

In my case, this destroys the layout:

A: Combine the three tikzpictures. Use scope if needed.

\documentclass{article}
\usepackage{tikz}
\usepackage{amsmath,amssymb}
\usepackage{caption}
\usepackage{subcaption}
\begin{document}

\begin{figure}%
\centering
\begin{subfigure}[c]{\textwidth}
\begin{tikzpicture}
\draw[step=1cm,gray,very thin] (0,0) grid ++(4,4);
\draw[step=1cm,gray,very thin] (5,0) grid ++(4,4);
\draw[step=1cm,gray,very thin] (10,0) grid ++(4,4);

\matrix [draw,below left] at (current bounding box.south east) {
  \node [label=right:R...ROBOT] {}; \\
  \node [label=right:G...GOAL] {}; \\
  \node [label=right:O...OBSTACLE] {}; \\
};
\end{tikzpicture}
\subcaption{c}
\end{subfigure}
\end{figure}
\end{document}


text:
Q: Enums in MongoDB I want to store enum values in MongoDB collection. Can I effectively store them as strings? Will it affect index performance in comparison with enum values as ints? Does Mongo indexer optimize string indexes in the case when they contain only few fixed options as string values, to achieve speed similar to querying index by sorted integer?

A: Storing enum values in MongoDB as strings is perfectly fine, and yes, if you index the field I'd expect the performance to be comparable to indexed integer queries.  It's certainly more expressive than using integers.
The only real downside is that they'll take more space if your enum strings are somewhat long, but that's a pretty trivial concern.


text:
Q: Response variable out of range -> using gamlss in r LOGNO I am new to the function GAMLSS in r, and when I run my code I always get this error: Response Variable out of range
After looking into the data frame, I realized the issue was one of response variables was 0.0000.
I was wondering if someone could explain to me why 0 is out of range and possible solutions to go around it (ex. such as replacement the values)?

A: LOGNO family corresponds to the log-normal distribution, which is defined for positive values only.
The possible solutions might be (but highly depend on the context):

*

*use another distribution, which better models the response variable and allows zero values

*sometimes zero values are reported if they are below the limit of detection (LOD).
In this case, one has a censored data set, and you may look for review of the methods, how to tackle it. A pragmatic approach is to substitute zeros with values like LOD/2, reviewed, for example, here. However, it may result in a very biased estimation.


text:
Q: Implementing SSL in WCF I have a small question about SSL implementation with Transport security in wcf.
What i understood from Research is,

*

*First client makes a request to WCF via https.

*Server will send a public key to client.

*Client uses this public key and encrypts the data and then sends across transoport.

*server receives the encrypted data and decrypts it using private key.

Is there anything wrong in my understanding......?
My second question is
Whats the process when service sends the response back (how encryption and decryption occcurs?).
Thanks in advance
Note: My Question is not about how to implement SSL in WCF, it is how ssl workds both in case of request and response.


text:
Q: Why a job in Laravel queue retry a Guzzle http request was successful with status 200 I have a Laravel application and one process put a job on laravel queue. The job trying to execute an asynchronous post http request. When the request fail I catch the exception without problem, but when I have a status 200, the application log the response but few seconds later try to execute again the request.
My request:
 class NotifyPayment implements ShouldQueue {

     /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(SettlementModel $settlement) {
        $this->settlement = $settlement;
    }

     /**
     * Execute the job.
     *
     * @return void
     */
    public function handle() {

        $settlement = $this->settlement;

        $id = $settlement->id;
        Log::info("Executing job: ".$settlement->id);
        $client = new Client();
        try {

            $promise = $client->requestAsync('POST', $settlement->siam_response_url);
            $promise->then(
                function (ResponseInterface $res) use ($id) {
                    Log::info('Status:'.$res->getStatusCode().', NOTIFY SUCCESS: '.$id.'
                    ');
                }
            );
            $promise->wait();
        }
        catch (RequestException $e)
        {
            Log::error("NOTIFY WAS FAILED: ID ".$settlement->id." ".$e->getMessage());
            Log::error( $e->getRequest()->getMethod()." ".$e->getMessage() . "\n");
            $this->job->fail(null);
        }

    }
}

And this is my log file:
[2020-09-10 12:21:16] production.INFO: Settlement paid: 22638
[2020-09-10 12:21:17] production.INFO: Executing job: 23423
[2020-09-10 12:21:18] production.INFO: Status:200, NOTIFY SUCCESS: 22638
[2020-09-10 12:23:02] production.INFO: Executing job: 23423
[2020-09-10 12:23:03] production.ERROR: NOTIFY WAS FAILED: ID 22638 Client error: POST https://some-url-of-my-system/callback-paid?token=8832fa192f059598e064b905 resulted in a 400 Bad Request response
[2020-09-10 12:23:03] production.ERROR: POST Client error: POST https://some-url-of-my-system/callback-paid?token=8832fa192f059598e064b90524dc018ad1331f763e5c45ba21470e0112645f4f22dbb703468998e22cfcb4fe6ce328db9a730e900bbb75757aba3a97210810ef resulted in a 400 Bad Request response
With this log
Log::info("Executing job: ".$settlement->id);

I can see that the jobs was executed two times, whats happening here?
And where raise the notification is here:
NotifyPayment::dispatch($settlement);

PD: the url of the post request only can executed once, the second time throw a status 400.
IMPORTANT INFORMATION
When my process start, that was start in this route /cashier and when the process did all the steps, run the job queue, etc etc. redirect at the same route  /cashier
return redirect()
            ->route('cashier')
            ->withMessages(['type' => 'success', 'text' => 'The payment was successful!!!']);

A: When my process starts, that was start in this route /cashier and when the process did all the steps, run the job queue, etc etc. redirect at the same route /cashier
I only was changed the redirect route to the job on the queue run only once time.
I don't know why the job run twice when you start in a route and after finish your process go to the same route.
The solution:
Change this
return redirect()
            ->route('cashier')
            ->withMessages(['type' => 'success', 'text' => 'The payment was successful!']);

to this:
return redirect()
            ->route('cashier.details') //to any other route from you app
            ->withMessages(['type' => 'success', 'text' => 'The payment was successful!']);


text:
Q: modX If Statement return nothing I want to write only output if needed, but it returns nothing.  No a and no b.
[[+mobilephone]] <- not empty
[[!If? &subject=`[[+mobilephone]]` &operator=`notempty` &then=`a` &else=`b`]]

maybe you have an idea. My Context is a Site which called a Snippet which call a Chunk.
Version Info:
MODX Revolution 2.2.10-pl (sdk)

A: You could try with normal output modifiers:
[[+mobilephone:notempty=`a`:else=`b`]]

A: You seem to be missing the & from subject i.e. try
[[!If? &subject=`[[+mobilephone]]` &operator=`notempty` &then=`a` &else=`b`]]


text:
Q: How to prevent the entry and appearance of non-numeric values in TextBox in VB.NET? I really need to prevent any non-numeric entry (Including paste) to my TextBox and also I want to prevent it from appearing on the TextBox before being erased, It would be wonderful if you put some hints regarding your code suggestion, because I'm just a beginner!

A: Edited : added CtrlV handling and opimized Keypress event.
You could use this code, wich prevent numeric values from being handled :
 Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress

    If Char.IsDigit(e.KeyChar) Then ' Check if the value is a number
        e.KeyChar = ChrW(0)
        e.Handled = True
    End If

End Sub

and for the CtrlV handling you can use this code :
Private Sub TextBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    ' Checking if control + v is clicked or Shift + Insert is clicked
    If (e.Control AndAlso Char.ToLower(ChrW(e.KeyValue)) = "v"c) Or (e.Shift AndAlso e.KeyValue = Keys.Insert) Then
        e.Handled = True
        e.SuppressKeyPress = True
    End If
End Sub

A: Take a look to the following links:
http://www.vbforums.com/showthread.php?570438-Restrict-TextBox-to-only-certain-characters-numeric-or-symbolic
http://www.codigofacilito.com/videos/visual_basic_net_parte_funcion_para_recibir_solo_caracteres_curso_vbnet
If you still have any doubt, let me know.


text:
Q: 'Twilio' already has a dependency I'am new to asp.net and really hoping for help, well you see I'am trying to Install twilio but this error shows
'Twilio' already has a dependency defined for 'Microsoft.IdentityModel.Logging'.


text:
Q: Extremal question on matrices The following question was posed to me a while ago. No one I know has a given a satisfactory (or even a complete) proof:
Suppose that $M$ is an $n$ x $n$ matrix of non-negative integers. Additionally, suppose that if a coordinate of $M$ is zero, then the sum of the entries in its row and its column is at least $n$.
What is the smallest that the sum of all the entries in $M$ can be?
The conjecture posed to me was that it was $\frac{n^2}{2}$ which is obtained by the diagonal matrix with $\frac{n}{2}$ in all diagonal entries.
[I'm guessing that there should be a "suppose that" in describing M. -- GJK]

A: Again, very nice question!
Edit: I can get a lower bound of $\frac{3 - \sqrt{5}}{2} n^2$ as follows: Set $c = \frac{3 - \sqrt{5}}{2}$ for conciseness. Assign a (not necessarily simple) bipartite graph to $M$ in the obvious way. Now if the sum of some row is less than $cn$, there must be at least $(1-c)n$ vertices in the other partite set of the graph that aren't adjacent to the corresponding vertex, which therefore must each have degree at least $(1-c)n$ and so have total degree at least $(1-c)^2n^2 \geq cn^2$.
Unfortunately c is only about 0.38, and that's the highest constant this argument can give us. But maybe it can be modified a little bit to give us 0.5.
Edit 2: This problem really fights back! I'm beginning to think that there's some kind of dichotomy in play here, so that we may end up needing some kind of structure theorem... I've thought about this way more than I should have, and still haven't managed to appreciably improve the above bound (actually I think I have got the constant up to $\frac{3 - \sqrt{2}}{2}$, which is a smidgen under 0.4, by a very similar argument) but I think a record of what I've tried might be useful.

*

*My original plan of attack was to use the existence of a vertex of degree < n/2 to perform some clever counting argument which shows that there are at least $n^2/2$ edges. Of course, there's certainly no guarantee that this wouldn't work, but it appears that you have to be very careful with the counting: the disjoint union of the complete bipartite graphs $K_{m-1, m-1}$ and $K_{m+1, m+1}$ satisfies the desired property and has the maximal allowed number of low-degree vertices, but only has $n^2/2 + 2$ edges! It's not clear to me how to construct a counting argument which can handle both the above situation and more "typical" ones in which the vertices have a wide range of degrees, so this approach was put to the side.

*However, there may be a workaround: we don't actually have to show that $n^2/2$ is a lower bound! In fact if we can show a lower bound of the form $(0.5-o(1))n^2$ then the desired bound follows. Why? Because if we had a matrix with the desired property and density less than 1/2, we could stick a bunch of copies of it together to get arbitrarily large matrices with the same density. This means that we can sacrifice, for example, O(n) factors in our counting arguments.

*By the way, here's one dichotomy which I think might have a chance of leading to a proof. Consider a multigraph with the desired property; let G denote the bipartite complement of its underlying simple graph. If G has a "large" matching, i.e., one of size n-o(n), we get our weak lower bound by a simple counting argument. If G has no large matching, then maybe we can use this property to force some structure on the original multigraph, which then shows that it has density at least 1/2.

A: [Edit: Originally, I gave the bound of $\frac{5-\sqrt{17}}{2}n^2$, but the remaining slack in the problem was easy to eliminate by considering the row with minimal sum. If my calculations are correct, this solves the problem. ]
This is modification of Harrison Brown's argument.
Suppose the total is less than $cn^2$. Let $r_1$ be a row with minimal sum $sn\leq cn$. Let us say that $r_1$ has $tn$ non-zero entries. Of course, $t\leq s$. Consider any other row $r$, which has $c_r n$ zeros at places that $r_1$ does not, and whose sum is $s_r n$. Then the total sum is at least $c_r(1-s_r)n^2+(1-s)(1-t)n^2$. On the other hand, the sum of $r$ restricted to columns where $r_1$ is non-zero is at least $(t-c_r) n$. Hence the total sum is at least $\sum_r (t-c_r) n + (1-s)(1-t) n^2$.
To summarize
$$\begin{align*}
cn^2&\geq (1-s)(1-t)n^2+\max_r c_r(1-s_r)n^2\\\\
cn^2&\geq (1-s)(1-t)n^2+\sum_r (t-c_r)n\\\\
cn^2&\geq \sum_r s_r n
\end{align*}
$$
For a fixed value of $\sum c_r$ and $T=\max c_r(1-s_r)$ the minimum of $\sum s_r$ is achieved when all but one $c_r$ are equal to $T/(1-s)$ or $c$ (that follows by optimizing a sum of two terms of the form $\max(s,1-T/c_r)$ ). Let $p$ be the proportion of rows $r$ such that $c_r=c$. Then
$$\begin{align*}
c&\geq (1-c)(1-t)+T\\\\
c&\geq (1-c)(1-t)+(1-p)(c-T)\\\\
c&\geq p(1-T/c)+(1-p)s\\\\
t&\leq s\leq c
\end{align*}$$
I claim that the minimum of $c$ under these constraints occurs when the firs of these inequalities are equalities. Indeed, if the first inequality is strict, increase $T$. If the second inequality is strict, decrease $p$. Moreover, if $s\neq t$, we can decrease $s$. Thus
$$\begin{align*}
c&= (1-c)(1-s)+T\\\\
c&= (1-c)(1-s)+(1-p)(c-T)\\\\
c&\geq p(1-T/c)+(1-p)s\\\\
s&\leq c
\end{align*}$$
Eliminating $T$ we obtain
$$\begin{align*}
c&=(2-p)(1-c)(1-s),
\end{align*}$$
Solving the equation for $s$ and substituting into the inequality $s\leq c$, we get (please check!)
$$\begin{align*}
p(1-c)^2\geq 2c^2-5c+2
\end{align*}$$
Substituting this inequality for $p$ into $c\geq p(1-T/c)+(1-p)s$ and using the expressing for $s$ and $T$ that we have, we finally arrive (please double check!) to
$$(1-2c)(2-c)(2c^3-6c^2+3c-1)\geq 0$$. Since $2c^3-6c^2+3c-1$ is negative for $c<1$, the inequality $c\geq 1/2$ follows.
[Before the edit, the answer was concluded by the following sentence, to which the comment refers].
In general it is tempting to consider arbitrary sets of $k$ rows, and if the union of their zero sets is large, use that to say that the sum over corresponding columns is large.

A: It's worth noting, perhaps, that the diagonal matrix is not the unique extremal matrix. A checkerboard pattern of 1's and 0's also achieves $n^2/2$.
There are certain transformations that preserve the given properties and simplify the matrix. For example, we can transpose the matrix, we can exchange any pair of rows, we can exchange any pair of columns.
There's another transformation whose effect is more subtle. Suppose $m_{ij}\ge2$. If any $m_{i'j'}\ge2$ with $i'\le i+1$ and $j'\ge j+1$, then we can replace $m_{ij},m_{i',j'},m_{i',j},m_{i,j'}$ with $m_{ij}-1,m_{i'j'}-1,m_{i',j}+1,m_{i,j'}+1$, respectively. This preserves all of the row and column sums, and moves mass away from the lower-left and upper-right corners, and towards the diagonal. The only reason we need $m_{ij}\ge1$ is that we have to be careful about creating 0's in the matrix.
It feels like this is only one or two WOLOGs away from saying that we can assume the matrix is diagonal, in which case the problem is easy (sum is $n^2/2$ or $(n^2+n-2)/2$ depending on the parity of $n$).

A: The odd case.
Cobbling together some posts that have already appeared, we get:
Claim: For $n$ odd, the minimum is $\frac{n^2 + 1}{2}$.
Pf: As Harrison Brown points out, since $\frac{n^2}{2}$ is a lower bound for $n$ even, it is a lower bound for $n$ odd.  Hence, $\lceil\frac{n^2}{2}\rceil = \frac{n^2 + 1}{2}$ is as well.
The checkerboard pattern (with ones in the corners) achieves this bound.
What does the set of all extremal matrices look like?

A: The following looks too simple, so perhaps there's a mistake, but here goes.
Let $m$ be the smallest among all row sums and column sums. If $m\geq n/2$, we are done.
Otherwise, $m=cn$ with $c\lt 1/2$. Suppose it is a column which has sum $m$. This column has at least $n-m$ zeroes, and each of the corresponding rows has sum $\geq n-m$. The remaining $m$ rows each has sum $\geq m$.
In total we have a sum of at least $(n-m)^2+m^2 = ((1-c)^2+c^2)n^2$. Finally, note that $(1-c)^2+c^2\gt 1/2$ when $c\lt 1/2$.
So this gives a lower bound of $n^2/2$, and equality requires that any row and any column sums to exactly $n/2$, so the matrix is a sum of $n/2$ permutation matrices by König's Theorem.
Now what about the case when $n$ is odd?
Edit: Since the sum is an integer, the lower bound $n^2/2$ actually gives $(n^2+1)/2$, which can be attained by for example taking the direct sum of an $m\times m$ matrix of $1$s with an $(n-m)\times (n-m)$ matrix of $1$, where $m=(n-1)/2$. When $n$ is odd, this is the only extremal example up to column and row permutations. Here is a proof.
Let $m$ now, as originally, denote the minimum over all row and column sums. If $m\geq (n+1)/2$, then the total sum is too large: at least $nm\geq n(n+1)/2$. Therefore, $m\leq(n-1)/2$, and the $(n-m)^2+m^2$ lower bound now gives a total sum of at least $(n-n(n-1)/2)^2+((n-1)/2)^2 = (n^2+1)/2$ (using the fact that $(1-c)^2+c^2$ is decreasing when $c\lt 1/2$).
So up to now we have only rederived the lower bound for $n$ odd.
However, if equality now holds, we get that $m=(n-1)/2$, that each row adds up to either $m$ ($m$ times) or $n-m$ ($n-m$ times), and that in a column that adds up to $m$, there are exactly $n-m$ $0$s, so all entries are $0$ or $1$ (and similar statements with columns and rows interchanged). By permuting the rows and columns we may assume that the first $m$ rows [columns] each add up to $m$.There can't be a $0$ in the upper left $m\times m$ submatrix, since then the sum of the row and column containing the $0$ adds up to only $2m\lt n$. We have found a direct sum of an $m\times m$ and an $(n-m)\times(n-m)$ all $1$ matrix.

A: A partial result:  Let $T$ be the total of the entries of $M$.  Define a new matrix $M'$ by the formula
$$M'_{jk} = nM_{jk} + \sum_{\ell \ne j} M_{\ell k} + \sum_{\ell \ne k} M_{j \ell} \ge n.$$
Let $T'$ be the total of $M'$.  Then $T' = (3n-2)T$ and $T' \ge n^3,$ so
$$T \ge \frac{n^3}{3n-2} > \frac{n^2}3.$$
Edit: When I finally got the formulas right, it just looks like a weaker version of Harrison Brown's argument.  Alas.

A: If there is an $n x n$ matrix of non-negative integers satisfying if any entry is zero then the sum of its row and column is $n$ and we want the smallest sum. We start by trying to construct the longest sequence of zeros whose columns coordinates are disjoint and whose row coordinates are disjoint. Say this process stops at $m$. Then the remaining $(n-m) x (n-m)$ entries must be 1 or more. The other entries are covered covered once by a row or column if the have one coordinate equal to used rows or columns or twice if they have two coordinates used in the process thus we get $nxm-m^{2}/2 +m +(n-m)^{2}$ as a lower bound of the sum of points of all entries. Taking the derivative with respect to m gives $n-m+1/2-2n+2m = -n-m/2+1/2$ as the derivative it is always negative so the lower bound is decreasing as $m$ increases thus $m=n$ is a gives a lower bound but in that case we have $n$ zeros and every point is covered twice once for the first coordinate and once for the second so the lower bound is $n^{2}/2$. For $n$ even this can be realized by a checkerboard pattern. For n odd one half must be added and that can be realized as an odd checkerboard pattern. Then the lowest sum for even $n$ is $n^{2}/2$ and for odd $n$ is $n^{2}+1/2$


text:
Q: Delete entire word with single back space in edit text I have one requirement. Have one editText and I can able to add the data from recyclerView to editText. And if we click on back button entire word should delete and again can able to add any item from recyclerView at any position. And need to save the added items in one list. (Simply its like facebook tagging.. In facebook we can tag any friend from list popup and can edit in middle and can delete from middle and can add in middle of that editText. My requirement is exactly like that. I want exactly like facebook tagging including editing post). Can any one please help me out of this. I have no idea about this
Thanks in advance.

A: It is MultiAutoCompleteTextView
<MultiAutoCompleteTextView
                    android:id="@+id/editText2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_gravity="center_horizontal"
                    android:hint="In areas (comma separated)"
                    android:popupBackground="@color/white"
                    android:textColor="@color/text_color" />

You need set adapter for opening listview
search_text = (MultiAutoCompleteTextView) findViewById(R.id.editText2);
    FilterWithSpaceAdapter<String> filterWithSpaceAdapter=new FilterWithSpaceAdapter<String>(getActivity(),R.layout.checked_textview, R.id.text1, autoSearchLists);

                search_text.setAdapter(filterWithSpaceAdapter);
                search_text.setThreshold(1);
                search_text.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());


text:
Q: Problem using android.accounts Authenticator I'm new to the android.accounts apis, and now I'm trying to do something with them but a seemly dummy problem occurs...
I`ve created an Authenticator for my app but did not yet implement the abstract methods. The icon of it successfully appears in the system Add a Account window, and I know that when I click it, the method addAccount in the Authenticator will be invoked.
Now I wish to do some simple thing in this method, and write codes below:
    @Override
public Bundle addAccount(AccountAuthenticatorResponse response,
        String accountType, String authTokenType, String[] requiredFeatures,
        Bundle options) {

    Log.d(LOG_TAG, "RRAuthenticator add account... ");
    String accountName = "example@example.com";
    Account account = new Account(accountName, accountType);
    String password = "example_password";
    AccountManager manager = AccountManager.get(context);
    manager.addAccountExplicitly(account, password, null);

    Bundle bundle = new Bundle();
    bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
    bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    bundle.putString(AccountManager.KEY_AUTHTOKEN, "example_authtoken");
    return bundle;
}

I've seen the demo of SampleSyncAdapter, and make moves like it. But I practice using these APIs by directly adding an account.
But system crashed by the line manager.addAccountExplicitly(account, password, null);
What's wrong with it?

Added later:
Exception in system process. System will crash.
NullPointerException throw by AccountManager.
It seems the problem of the addAccountExplicitly method, as I comment this statement no crash happen.

A: I've worked it out.
It turns out that it's a bug in Android 2.0.
If you add an account to the AccountManager, you must also provide a SynAdapter to the account, under the Android 2.0 platform. But things are all right under Android 2.1 and above.
This is a known issue, please refer to:
http://code.google.com/p/android/issues/detail?id=5009
and
AccountManager without a SyncAdapter?

A:  Account account = new Account(username, AuthConstants.ACCOUNT_TYPE);
            if (am.addAccountExplicitly(account, password, null)) {
                result = new Bundle();
                ContentResolver.setSyncAutomatically(account, DB.AUTHORITY, true);
                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
                return result;
            }

I am using this code in one of my apps which works perfectly. the key here is the AccountAuthenticatorActivity that should set the authentication result bundle which should be registered (the sync adapter from android developers has this.
also here is my addAccount method for the accountAuthentication service
    @Override
public Bundle addAccount(AccountAuthenticatorResponse response,
    String accountType, String authTokenType, String[] requiredFeatures,
    Bundle options) {
    final Intent intent = new Intent(mContext, LoginScreen.class);
    intent.putExtra(LoginScreen.PARAM_AUTHTOKEN_TYPE,
        authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
        response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

UPDATE
Authenticator
Here is a link i used. this is a good project. i believe it is from the last.fm android app. it also has the source code open on git i believe. so try to compare with that.
PERMISSIONS
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
  <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
  <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
  <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
  <uses-permission android:name="android.permission.WRITE_SETTINGS" />
  <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />


text:
Q: Check if variable is a text file How would I go about checking if a variable is a .txt file?
My code isn't working:
if /I "%ph2file%" NEQ "*.txt" echo This file is not a .txt file.

A: the "quick and dirty" way (check last four characters):
if /i "%ph2file:~-4%" neq ".txt" echo no .txt file

the "clean" way (check the extension):
for %a in ("%ph2file%") do echo if "%~xa" neq ".txt" echo no .txt file


text:
Q: Powershell json, includeFields I am trying to request information from one of our APIs using JSON however there is a lot which needs to be filtered out.
According to our API documentation, we have an "IncludeFields" query. How can I make it so when the information is requested, only information with "CS505MA001" is returned instead of the 100s of objects I'm getting.
$CommcellInfo = Invoke-RestMethod -Method Get -Uri $URL -Headers @{ "X-    Auth-Token" = $Global:AuthToken; "includeFields" = "CS505MA001" }

$Include_Query = @{"includeFields"="CS505MA001"}
$ConvertedInclude_Query = ConvertTo-Json $Include_Query
$CommcellInfo = Invoke-RestMethod -Method Get -Uri $URL -Headers @{ "X-Auth-Token" = $Global:AuthToken }

I am trying to only show the returned information which contains certain text, how would I go about achieving this?


text:
Q: Group Jenkins "built jobs list" by parameter used to build each one I have a job that takes the github repository name as a parameter to the build (we'll call this parameter "project" from here on). This is neat because the unit tests for all my companies projects are run the same way, so I can specify the project that I want to test as a parameter. This saves me having to create many very similar jobs and replace them all with one "parameterized" job that runs the unit tests which accepts the "project" as a parameter.
The problem is that the "list of builds" of this job now has a mix of all the different projects. Finding a build which only fails in one project means that I have to go through each of the build jobs until I find the one which has the parameter of the "project" that I'm interested in. In short, debugging is a bit of a pain.
Is there a way to group the list of builds by a certain parameter? This would allow me to quickly see all the builds in each project (the builds would be grouped by the "project" parameter), which would be great.


text:
Q: How to grab UUID from Firefox/Chrome add-on/extenstion I am trying to grab the uuid that is assigned to each extenstion/add-on installation. This is not  the extension ID that is that same across all extension installations. This is the one that is unique for each user per install.

A: you can call browser.runtime.getURL('/'); this will return you a url string like moz-extension://9a08sd798-af1b-4572-95ab-9d6866517ade/ then you can parse the string from that or if you need it to open a tab to your popup just put the url to your popup.
let url = browser.runtime.getURL('/dist/frontend/index.html');
browser.tabs.create({
  url
})


text:
Q: How to get Chrome debugger to break or error when working on undefined variables My Javascript code (hundreds of lines) hangs Chrome and when I debug the issue I find out that a variable was undefined. I don't get errors in the console. So this is making my debugging more time consuming because there are no errors or exceptions or anything that tells me where the issue is.
I don't want to add debugging code. Is there a way to make the debugger put out an error, break in the debugger or give an exception or show anything useful for the developer when hitting an undefined variable during runtime? It doesn't have to be for Chrome only.

A: window.onerror = function() { debugger; }

A: You can break into the DevTools debugger when a JavaScript error occurs using the Pause on JavaScript Exceptions feature. It has two active modes; pause on all exceptions, and pause on uncaught exceptions.
Based on the description of your experience, the application you are working on may have errors that are caught but not re-thrown or logged. Using the "Pause on All Exceptions" (blue colored pause icon), will help in this scenario.
Note: some libraries, like jQuery, catch exceptions and do not re-throw them. If you have this experience, you may need to advance past these exceptions or set the "Pause on All Exceptions" feature after all dependencies have loaded.


text:
Q: Call function in img tag in HTML I have this function and I pass it in img tag in HTML
check(imgNumber)

        <img class="status-icon" src="check(<%= @data.imageEng %>)" width="26" height="auto" />

I got this error  http://localhost:3000/icon/check(3) 404 (Not Found)
and photo is not appearing.
How can I solve this?

A:
<img class="status-icon" src="check(<%= @data.imageEng %>)"

You can't do it like that; the src= tag is not evaluated. You have to do it differently (a library like jQuery might help too):
<img id="id12345" src="about:blank" eng="<%= @data.imageEng %>" />

...

But actually, you could do it all server side with no Javascript at all. The changes are not made client side and the server should have all necessary data.


text:
Q: UITapGestureRecognizer does not work in view which belong to another controller  @IBAction func popView(_ sender: UIButton) {
    let popView = PopView()
    popView.setVisible()
    popView.animateView(view: popView.contentView)

}

popView is a viewcontroller which has some views in it,popView use setup() in its init() to set these views.
    func setup(){
    view.frame = UIScreen.main.bounds

    baseView.frame = view.frame
    baseView.backgroundColor = UIColor.black
    //baseView.alpha = appearence.backgroundAlpha
    view.addSubview(baseView)

    contentView.backgroundColor = UIColor.white
    contentView.layer.cornerRadius = appearence.cornerRadius
    contentView.frame = CGRect(x: 10, y: 10, width: appearence.width, height: appearence.height)
    contentView.layer.masksToBounds = true
    contentView.center = CGPoint(x: self.view.bounds.midX , y: self.view.bounds.midY )

    baseView.addSubview(contentView)

    headView.frame = CGRect(x: 0, y: 0, width: contentView.bounds.width, height: contentView.bounds.height / 2)
    headView.backgroundColor = UIColorFromRGB(0xE64D4D)
    contentView.addSubview(headView)

    headImageView.image = UIImage(named: headImage)
    headImageView.contentMode = .center
    headImageView.frame.size = headImageView.image!.size
    headImageView.center = CGPoint(x: headView.bounds.midX, y: headView.bounds.midY)
    headView.addSubview(headImageView)

    let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.hide(_: )))
    recognizer.numberOfTapsRequired = 1
    contentView.addGestureRecognizer(recognizer)
    print(String(describing: contentView.gestureRecognizers))
}

contentView has a tapgesturerecognizer but when I tap it doesn't work
func hide(_ recognizer: UITapGestureRecognizer){
    self.view.removeFromSuperview()
}

popView is created by the code below in ViewController class
 @IBAction func popView(_ sender: UIButton) {
    let popView = PopView()
    popView.setVisible()
    popView.animateView(view: popView.contentView)

}

func setVisible(){
    let rootView = UIApplication.shared.keyWindow! as UIWindow
    rootView.addSubview(self.view)

}

func animateView(view: UIView){
    view.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.minY - view.bounds.midY)
    UIView.animate(withDuration: 0.2, animations: {
        view.center = CGPoint(x: self.view.bounds.midX , y: self.view.bounds.midY + 50)
    }, completion: {(finished) -> Void in
        UIView.animate(withDuration: 0.1, animations: {
            view.center = CGPoint(x: self.view.bounds.midX , y: self.view.bounds.midY )

        })

    })
}

the popView appears correctly but contentView doesn't respond to the tap  gesture. why??please help me~

A: Add tap gesture on popView's view controller instead of contentview. It will work as below.
let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.hide(_: )))
        recognizer.numberOfTapsRequired = 1
        popView.view.addGestureRecognizer(recognizer)
        print(String(describing: popView.view.gestureRecognizers))

Also move your hide function into button action class. Do Hide and showing into that class itself as below.
func hide(_ recognizer: UITapGestureRecognizer){
        self.popView.view.removeFromSuperview()

        let rootView = UIApplication.shared.keyWindow! as UIWindow
        rootView.addSubview(self.view)

    }

I hope this will help.
Below are my PopView class code:
import UIKit

class PopView: UIViewController {

    var baseView: UIView = UIView()
    var contentView: UIView = UIView()
    var headView: UIView = UIView()
    var headImageView: UIImageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.setup()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setup(){
        view.frame = UIScreen.main.bounds

        baseView.frame = view.frame
        baseView.backgroundColor = UIColor.black
        //baseView.alpha = appearence.backgroundAlpha
        view.addSubview(baseView)

        contentView.backgroundColor = UIColor.white
        contentView.layer.cornerRadius = 0.5
        contentView.frame = CGRect(x: 10, y: 10, width: 200, height: 200)
        contentView.layer.masksToBounds = true
        contentView.center = CGPoint(x: self.view.bounds.midX , y: self.view.bounds.midY )

        baseView.addSubview(contentView)

        headView.frame = CGRect(x: 0, y: 0, width: contentView.bounds.width, height: contentView.bounds.height / 2)
        headView.backgroundColor = UIColor.yellow
        contentView.addSubview(headView)

        headImageView.image = UIImage(named: "patternsPlaceholder")
        headImageView.contentMode = .center
        headImageView.frame.size = headImageView.image!.size
        headImageView.center = CGPoint(x: headView.bounds.midX, y: headView.bounds.midY)
        headView.addSubview(headImageView)

    }

    func setVisible(){
        let rootView = UIApplication.shared.keyWindow! as UIWindow
        rootView.addSubview(self.view)

    }

    func animateView(view: UIView){
        view.center = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.minY - view.bounds.midY)
        UIView.animate(withDuration: 0.2, animations: {
            view.center = CGPoint(x: self.view.bounds.midX , y: self.view.bounds.midY + 50)
        }, completion: {(finished) -> Void in
            UIView.animate(withDuration: 0.1, animations: {
                view.center = CGPoint(x: self.view.bounds.midX , y: self.view.bounds.midY )

            })

        })
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

And below is the my baseviewController code.
import UIKit

class ViewController: UIViewController {

    var popView = PopView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func popViewButtonAction(_ sender: Any) {

//        let popView = PopView()
        popView.setVisible()
        popView.animateView(view: popView.contentView)

        let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.hide(_: )))
        recognizer.numberOfTapsRequired = 1
        popView.view.addGestureRecognizer(recognizer)
        print(String(describing: popView.view.gestureRecognizers))

    }

    func hide(_ recognizer: UITapGestureRecognizer){
        self.popView.view.removeFromSuperview()

        let rootView = UIApplication.shared.keyWindow! as UIWindow
        rootView.addSubview(self.view)

    }

}

I hope it will give you Idea.
Thanks,
Shankar


text:
Q: working with nested object I think this is silly question and simple but I can't find any result in google and other resource
I have array of object like this
 const myArr = [
     [{
         id: 1,
         price: 200,
     }, {
         id: 2,
         price: 900,
     }, {
         id: 3,
         price: 100,
     }],
     [{
         id: 5,
         price: 100,
     }]
 ];

In other word I have an array and my array contain some array and each of inner array contain some object inside them
 arr [ [ {},{},{} ] ,   [ {} ]    ]

now I want get two thing

*

*count of all products ?

*sum of all products ?

*(each object = one product)

A: Flatten to a single array by spreading into Array.concat().
Use Array.reduce() to get the sum.
The count is flattened array's length.

const myArr = [[{"id":1,"price":200},{"id":2,"price":900},{"id":3,"price":100}],[{"id":5,"price":100}]];

const flattened = [].concat(...myArr);
const count = flattened.length;
const sum = flattened.reduce((s, o) => s + o.price, 0);

console.log('count', count);
console.log('sum', sum);

A: You can use concat to wrap all objects within one single array.
Apply length property in order to find out the number of objects in the array and then reduce method to get the sum.

const myArr = [ [ { id:1, price:200, }, { id:2, price:900, }, { id:3, price:100, } ], [ { id:5, price:100, } ] ];

arr = myArr.reduce((acc, arr) => acc.concat(arr), []);
sum = arr.reduce((acc, item) => acc + item.price, 0);
console.log('count ' + arr.length);
console.log('sum ' + sum)

A: You can use spread to flat the array:

var myArr = [
 [
   {
     id:1,
     price:200,
   },

   {
     id:2,
     price:900,
   },

   {
     id:3,
     price:100,
   }
 ],

[
  {
     id:5,
     price:100,
   }
]
];

var arr = [].concat(...myArr);
console.log('Length: ', arr.length);
var sum = arr.reduce((m, o) => m + o.price, 0);
console.log('Sum: ', sum);

A: ES6
You can also use reduce method of array to get the required result

reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.

DEMO

const myArr = [[{id: 1,price: 200,}, {id: 2,price: 900,}, {id: 3,price: 100,}],[{id: 5,price: 100,}]];

let result = myArr.reduce((r,v)=>{
  r.count += v.length;
  r.sum += v.reduce((total,{price}) => total+price,0);
  return r;
},{count:0,sum:0})

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}


text:
Q: What is physically irreducible representation? When I use bilbao crystallographic server recently, I noticed a notation called physically irreducible representation.
Paper says it is a direct sum of two complex conjugate representations (if $\Delta$ is a complex irreducible representation, then a physical irreps is $\Delta \oplus \Delta^*$). (http://journals.aps.org/prb/pdf/10.1103/PhysRevB.18.2391)
For example, in this article http://www.bgcryst.com/symp10/proceeding/02_Aroyo_183-197.pdf (see section 4.1.1 full group irreps part (pg 13)), they gave an example on space group no. 135 for k = T(0.37, 1/2, 1/2). It has 4 allowable irreps while its full group irreps characters are listed after those.
e.g.
The little group of the k-vector has  4  allowed irreps.
The matrices, corresponding to all of the little group elements are :

Irrep T_1 ,  dimension 1
      1               2               3               4
(1.000,  0.0)   (1.000,113.4)   (1.000,  0.0)   (1.000,113.4)

 Irrep T_2 ,  dimension 1
      1               2               3               4
(1.000,  0.0)   (1.000,113.4)   (1.000,180.0)   (1.000,293.4)

 Irrep T_4 ,  dimension 1
  1               2               3               4
(1.000,  0.0)   (1.000,293.4)   (1.000,  0.0)   (1.000,293.4)

 Irrep T_3 ,  dimension 1
      1               2               3               4
(1.000,  0.0)   (1.000,293.4)   (1.000,180.0)   (1.000,113.4)

General position characters:
Gen Pos:      1             2             3             4             5           6             7             8             9             10             11             12             13             14             15             16
T_1      (4.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836, 90.0) (1.836, 90.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836, 90.0) (1.836,270.0) (0.000,  0.0) (0.000,  0.0)
T_2      (4.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836, 90.0) (1.836, 90.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836,270.0) (1.836, 90.0) (0.000,  0.0) (0.000,  0.0)
T_4      (4.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836,270.0) (1.836,270.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836,270.0) (1.836, 90.0) (0.000,  0.0) (0.000,  0.0)
T_3      (4.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836,270.0) (1.836,270.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (0.000,  0.0) (1.836, 90.0) (1.836,270.0) (0.000,  0.0)    (0.000,  0.0)

Then it shows:
Physically-irreducible representations:
  *T_1+*T_4  *T_2+*T_3

Can anyone give me some instructions what it means or some references about its definition and physical meaning?

A: This means this representation cannot be reduced in real numbers. But it can be split into two irreducible represenations if complex numbers are allowed.