text:
Q: Not able to build react native project getting server returned response error 500 in react native? Why I am getting above error while doing react-native run-android. I am not able to do react-native run-android.
I tried cleaning Gradle but not working:
I tried this -> cd android and then Gradlew clean
Note: I am using windows 10.
Screenshot:

package.json:

.babelrc:

A: Did you try to close terminal and re-run the "react-native run-android"? to do more steps: first close cmd terminal, then "npm i" or "yarn" , then kill the app from emulator/phone, finally: "react-native run-android".

A: It seems that the bundler could not find babel preset metro-react-native-babel-preset. So you could either install it manually by
yarn add metro-react-native-babel-preset --dev
If this does not work, then delete the node_modules directory and run yarn to re-install all the packages.

A: I think you need clear node_modules, install again, and restart dev server with --reset-cache.
Command:
install metro-react-native-babel-preset
npm i metro-react-native-babel-preset --save-dev
rmdir node_modules (Windows)
npm install
npm start --reset-cache

and open other terminal/command window to run
react-native run-android
Edit: add final solution
First: in .babelrc replace { "presets": ["module:metro-react-native-babel-preset"] } to { "presets": ["react-native"] }. And remove node_modules and run again by commands in my answer.


text:
Q: Cantor set and triadic expansions I'm trying to prove that the Cantor set is equal to a certain set of 'escape points' for a mathematical feedback system.
In this proof I'm going to need the fact that every element of the Cantor set has a base-3 representation in which only 0's and 2's occur. However, I'm having a hard time with these triadic expansions. Can you help me by working out an easier problem (also using triadic expansions)?

If $x$ is in the Cantor set, then so is $1-x$.

I don't know if there is an easier way to prove this, but I'm specifically looking for a proof using the fact that x can be written as $0.a_1a_2a_3...$ where $a_i$ is either $0$ or $2$.

A: Let $x=0.a_1a_2a_3\ldots$, where the expansion is ternary and each $a_k$ is $0$ or $2$. For $k\in\Bbb Z^+$ let $b_k=2-a_k$; clearly $b_k\in\{0,2\}$. Let $y=0.b_1b_2b_3\ldots\;$; then $x+y=0.222\ldots=1$, so $y=1-x$ is in the Cantor set.
(I can recast this in terms of infinite series if you like, but this should be sufficient.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Limitar quantidade de caracteres digitados baseado na largura da view Tenho o seguinte EditText com largura definida como match_parent, basicamente ocupando a largura total independente do dispositivo:
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="end"
    android:maxLines="1"/>

Esse EditText possui no máximo 1 linha e está com propriedade gravity como end, como podem ver.
Gostaria de limitar a quantidade de caracteres deste EditText baseado no seu tamanho. Seria algo como:
android:maxLength="largura_total_ocupada_pelo_edit_text"

É possível fazer isso, limitar quantidade de caracteres digitados baseado na largura do EditText?

A: Como foi dito nos comentários da pergunta, para fazer isto você teria que medir o tamanho de cada caractere inserido no EditText, e isto não é tão difícil quanto parece.
Fiz em Kotlin, pois já que estou utilizando ela em meus projetos, seria mais rápido e fácil. A conversão para Java também estará disponível logo abaixo.
Primeiro, e mais importante, devemos saber qual é o tamanho que o EditText presente na tela do dispositivo, você pode fazer essa medição utilizando o método OnGlobalLayoutListener, pois ele espera que a view seja renderizada e então você terá o tamanho correto dela, em pixels. Se caso você tentar acessar o tamanho dela diretamente, o valor retornado será 0.

Isto retorna zero

int inputSize = ((EditText) findViewById(R.id.inputExample)).getWidth();

Isto retorna a largura do componente

((EditText) findViewById(R.id.inputExample)).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        inputSize = ((EditText) findViewById(R.id.inputExample)).getWidth();
    }
});

O mesmo vale para a linguagem Kotlin, você também terá que utilizar o mesmo método acima, mas o código pode ficar um pouco mais bonito com algumas implementações da linguagem, como:
// https://antonioleiva.com/kotlin-ongloballayoutlistener/
inline fun <T: View> T.waitForMeasure(crossinline measure: T.() -> Unit) {
    viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            if (measuredWidth > 0 && measuredHeight > 0) {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                measure()
            }
        }
    })
}

// .. MainActivity()
inputExample.waitForMeasure { // inputExample = é uma bind pra view com o kotlin-android-extensions
    inputWidth = inputExample.measuredWidth
    println("Edittext width (PX) is: $inputWidth")
}

Pronto, agora nós temos o tamanho que o componente está ocupando na tela do dispositivo, no exemplo acima, eu testei em um Nexus 5X 1080x1920 e o valor retornado foi 1080.
Sendo assim, podemos ir para a segunda parte, que é calcular o espaço que o caractere inserido ocupa na tela. Para fazermos isto, temos que utilizar a classe Paint do próprio componente para medirmos o caractere com o método Paint#MeasureText(String).

Java

int inputWidth = 0
float inputSize = 0.0
int maxCharCount = 0

// O tamanho do EditText primeiro :)
((EditText) findViewById(R.id.inputExample)).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        inputSize = ((EditText) findViewById(R.id.inputExample)).getWidth();
    }
});

// A brincadeira começa aqui
((EditText) findViewById(R.id.inputExample)).addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence input, int start, int before, int count) {
            Paint paint = inputExample.getPaint() // EditText ID: inputExample...
            inputSize = paint.measureText(input.toString())

            if (!TextUtils.isEmpty(inputExample.getText().toString())) {
                // Pegar último caractere inserido
                Char char = input[input.length - 1]

               // Pega o espaço restante no EditText
               // Isso depende do tamanho da EditText e do tamanho do TEXTO dela, em pixels.
               // Ex: texto www = 90.0 (w = 30.0) | tela = 1080
               // Espaço restante = 1080-90 = 990
               float spaceLeft = (float) inputWidth - inputSize

               // Pega o tamanho que a letra atual ocupa
               // Ex: letra w = 30.0 ou a = 26
               // Letras maiúsculas e minúsculas diferenciam-se em tamanhos
               // w = 30 | W = 35
               float charSpace = (float) paint.measureText(char.toString())

               if (spaceLeft < charSpace * 1.75) {
                  println("no space left")

                   if (input.length() != maxCharCount) {
                        maxCharCount = input.length()
                   }

               } else {
                   println("hm, there's some space")
                   int charCount = (int) spaceLeft / charSpace
                   maxCharCount = input.length
                   maxCharCount += charCount - (charCount - 1)
               }

               println("Space left: " + spaceLeft)
               println("length: " + maxCharCount)

               // Altera o limite da view de acordo com o espaço restante + tamanho do ultimo caractere inserido (ou o que ainda vai ser inserido)
               // Se tiver espaço: o caractere consegue ser inserido
               inputExample.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxCharCount) } );
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

Kotlin

var inputWidth: Int = 0
var inputSize: Float
var maxCharCount: Int = 0

inputExample.waitForMeasure {
    inputWidth = inputExample.measuredWidth
    println("Edittext width (PX) is: $inputWidth")
}

val listener = object : TextWatcher {
    override fun afterTextChanged(input: Editable?) {}

    override fun beforeTextChanged(input: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(input: CharSequence?, start: Int, before: Int, count: Int) {
        val paint = inputExample.paint
        inputSize = paint.measureText(input.toString())

        if (input!!.isNotEmpty()) {
            val char = input[input.length - 1]
            val spaceLeft = inputWidth - inputSize
            val charSpace = paint.measureText(char.toString())

            if (spaceLeft < charSpace * 1.75) {
                println("no space left")
                println("Max char count: $maxCharCount")

                if (input.length != maxCharCount) {
                    maxCharCount = input.length
                }

            } else {
                println("hm, there's some space")
                val charCount = (spaceLeft / charSpace).toInt()
                maxCharCount = input.length
                maxCharCount += charCount - (charCount - 1)
            }

            println("Space left: $spaceLeft")
            println("length: $maxCharCount")

            inputExample.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(maxCharCount))
        }
    }

}

inputExample.addTextChangedListener(listener)

Demonstração

Observações

*

*O código foi, inicialmente, feito em Kotlin, não em Java. Então, quaisquer erros que vocês encontrarem, sintam-se livres para corrigir/adicionar um comentário.

*Em Kotlin, eu utilizei a referência ao componente EditText utilizando o Kotlin-android-extensions, onde eu não preciso ficar utilizando findViewById.


text:
Q: jQuery Flot: Switch between day, week, and month dates I have data points for every day between January 1 to December 31.
What I'd like to do is let users switch been Day, Week, and Month views of that data.
Is there a way to do this with jQuery Flot?

A: Flot can't automatically re-sample your data; you'll need to do that either in JS using your original input, or server-side.


text:
Q: syntax error, unexpected ';', expecting '[' Выбивает ошибку: "  syntax error, unexpected ';', expecting '['  "
public function store(Request $request)
    {
        $path => public_path().'\upload\\';
        $file = $request->file('file');

        foreach ($file as $f) {
            $filename = str_random(20) .'.' . $f->getClientOriginalExtension() ?: 'png';
            $img = ImageInt::make($f);
            $img->resize(200,200)->save($path . $filename);
            Image::create(['title' => $request->title, 'img' => $filename]);
        }

        return redirect()->route('images.index');
    }

A: Вы не обернули > в строку
$path ='>'.public_path().'\upload\\';


text:
Q: HttpWebRequest with client certificate fails I am using Visual Studio Mac (latest version) and need to fetch data from an IIs server (vaersion 10) with a GET request and by passing a client certificate.
Unfortunately the IIs answers with an RST packet and shows the error:
The I/O operation has been aborted becourse of either a thread exit or an application request.

I know apple uses ATS (I am using iOS 10.3.3).
I guess this has something to do with the client certificate and IIS not accepting it.
Can someone point me to a differnt mono api where I can append the client cert to a GET request?
My code so far is as follows (with request.GetResponse() waiting until timeout...):
X509Certificate2Collection certificates = new X509Certificate2Collection (certificate);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.uriString);
request.ClientCertificates = certificates;

request.Method = "GET";
request.ContentType = "application/json";
request.Accept = "application/json";
request.UserAgent = UserAgentString;
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version11;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse ())
{
  this.webResponse = response;
  stream = response.GetResponseStream ();
}


text:
Q: undelete row from QTableView I am new to PyQt5, I am working with a QTableView. After successfuly knew how te delete selected rows..
I have googled a lot to know ho to undelete a selected deleted row from the table (& by sequence from the TableModel) with no result...
So far, I could know if the row is marked deleted based on the header data:
if self.items_Model.itemsModel.headerData(row.row(), QtCore.Qt.Vertical) == "!":
    # self.items_Model.itemsModel.revertRow(row.row())
    self.items_Model.itemsModel.selectRow(row.row())

I tried revertRow(rowIndex) and selectRow() but these methods repopulate the row from the database and does not remove the flag "!"; meaning - as I supposed - that on Submit, it will be deleted.
Please, any help.

A: It's weird that nobody here had answered my question...
After several tries... Including closing the editor and relaunching it...
It appears that to return the row to its previous state - in this case "not marked deleted"- we must use the "revert" method. But the mark "!" does not change unless we remove focus of the row to be undeleted i.e. select another row.
this is the whole code of my delete method:
def _deleteSelectedRows(self):
    select = self.mainForm.tblItems.selectionModel()

    if select.hasSelection():
        selectedRows = select.selectedRows()

        for r in selectedRows:
            rowFlag = self.items_Model.itemsModel.headerData(r.row(), QtCore.Qt.Vertical)
            if rowFlag == "!":
                self.items_Model.itemsModel.revertRow(r.row())
            else:
                self.items_Model._deleteRowByIndex(r.row())


text:
Q: How to have find recurse into subdirectories when using -prune option I see that the find command does not descend into subdirectories when you're using the -prune option.  How do I tell find to recurse into the sub directories, but also ignore some stuff?
Specifically, I want to search the /var/lib/foo directory, but exclude any directories with the name .snapshot/.
sudo find /var/lib/foo -prune -name '.snapshot'

With the above, it properly ignores .snapshot, but doesn't go into the sub dirs. FYI, I'm working in bash on a CentOS 6.3 host.

A: You need to do:
sudo find /var/lib/foo -name '.snapshot' -prune -o -print

it will print whatever is not named ".snapshot", and if ".snapshot" is a directory it will also not descend into it.
why ?  because "-prune" is an action (as '-print' is also another action), doing nothing except preventing to go further down in the subdir. And it always return "true", so here,  ( -name ... -prune ) is true if and only if the file or dir is named "...", and you you want everything else, hence the -o ( -print ).


text:
Q: Dynalic listview builder flutter I am trying to develop a function where the listview is refreshed/rerun whenever a button is clicked.I have tried it with setState but haven't got the desired output.

A: You can use ListView under RefreshIndicator.
On your RefreshIndicator, add a function called onRefresh():
void onRefresh(){
...
}
RefreshIndicator(
onRefresh: onRefresh,
child: ListView.separated(
...
),
),
You can then call the function by adding it on your button.


text:
Q: Warning Illegal string offset in PHP I have this chunk of PHP code which is giving me the error:

Warning: Illegal string offset 'mod_modulecode' in C:\xampp\htdocs\MP\multi\functions.php on line 29

This is the code that the warning is relating to:
function set_rights($menus, $menuRights) {
    $data = array();
    for ($i = 0, $c = count($menus); $i < $c; $i++) {
        $row = array();
        for ($j = 0, $c2 = count($menuRights); $j < $c2; $j++) {
            if ($menuRights[$j]["rr_modulecode"] == $menus[$i]["mod_modulecode"]) {
                if (authorize($menuRights[$j]["rr_create"]) || authorize($menuRights[$j]["rr_edit"]) ||
                        authorize($menuRights[$j]["rr_delete"]) || authorize($menuRights[$j]["rr_view"])
                ) {...................'

Any help would be greatly appreciated.

A: What PHP is saying is that at some iteration in
if ($menuRights[$j]["rr_modulecode"] == $menus[$i]["mod_modulecode"]) {
$menus[$i] is a string, not an array, and you're trying to access it like an array containing the key mod_modulecode.
To help track down this bug, I'd suggest:
if(is_string($menus[$i]) {
    var_dump('string bug','i',$i,'j',$j,'$menus[$i]',$menus[$i]);
}
if ($menuRights[$j]["rr_modulecode"] == $menus[$i]["mod_modulecode"]) {

Or even better yet, if you have xdebug installed, which will show local variables when an uncaught exception is thrown: throw new Exception('string bug');


text:
Q: How to locate the js code and php code of Wordpress website for certain function? For example, I want to debug the code for uploading an image when composing a post in Wordpress backend. I click the "Add Media" button, right-click on the "Media Library" tab, click the "Inspect" item on the context menu(Firefox). Then I click the "event" button at the end of a <div id="__wp-uploader-id-2...> element, and find several drop event handlers,one of which is tagged with jQuery, the others are tagged with "Bubbling DOM2". I click the event handlers and get these code:
//for jQuery event handler
function() {
  t = setTimeout(function() {
    r = !1, i.trigger("dropzone:leave").removeClass("drag-over")
  }, 0)
}

//Bubbling DOM2 handler
function(a) {
  return void 0 === n || a && n.event.triggered === a.type ? void 0 : n.event.dispatch.apply(k.elem, arguments)
}

//another Bubbling DOM2 handler
function(t) {
  e(t) && (t.preventDefault(), f = [], t.dataTransfer.items && t.dataTransfer.items[0].webkitGetAsEntry ? c(t.dataTransfer.items, function() {
    i.files = f, i.trigger("drop")
  }) : (n.each(t.dataTransfer.files, function(e) {
    a(e)
  }), i.files = f, i.trigger("drop")))
}

But none of the code brings me to the real js code to handle the upload event. How can I locate the js code that really copes with the upload event? Eventually, I want to locate the php code on the server side that deals with the upload.

A: The Initiator column within the Network Monitor provides the JavaScript file that caused the network request.
And when you click the request there's a Stack Trace tab. shown for it providing the complete JavaScript stack trace related to it.


text:
Q: How to set up cloud with application and connected IoT devices via 3G/LTE I am a beginner at cloud computing, and I'm hoping to get some guidance or advice as to how I can set up a cloud connected to IoT devices and a running application to control the behavior of these devices.
Firstly, there are 5 devices that have to connected via 3G or LTE because of the distance among the devices, so the way I am thinking of is connecting them to the internet using dynamic public ip addresses and using a dynamic DNS server. It seems like I should be using AWS-IoT service to manage these devices. How should I go about doing that, or is there a better approach? The devices all use MQTT and/or REST API.
The next step is to write an application and I was suggested to use AWS Lambda, am I heading towards the correct direction? How do I link the connected devices on AWS-IoT to AWS Lambda?
I know the question may sound vague but I am still new and exploring different solutions. Any guidance or recommendations for the right step forward is appreciated.

A: I assume your devices (or, one of them) has 64-bit CPU (x86 or Arm) that run Linux.

It's a kind of 70:30 balance where:
  - 70% of the work needs to focus on building and testing edge-logic.
  - 30% of the work on the rest (IoT Cloud, Lambda etc).

Here is what I suggest.
1/ Code your edge-logic first! (the piece of code that you want to execute ultimately on your devices).
2/ Test it on-the-edge by logging on to the devices (if you can) via SSH and running it.
3/ Once you have that done, 70% of the job is over.
4/ Rest 30% is to complete the jigsaw in cloud. Best place to start: Lambda and Greengrass.
5/ To summarize it all, you will create greengrass components on cloud, install AWS Greengrass Core software on your device, followed by deploying your configuration on your device over-the-air (OTA).
Now, you can use any MQTT client (or) biult-in MQTTTester of AWS IoT -> Test wizard to send a message to your topic to trigger your edge-logic on the device!
Good luck!
cheers,
ram


text:
Q: Calling upon Variables/dataframes from a reactive dataframe Let's say I have the following reactive portion of my shiny app:
    data1 <- reactive({

        if(input$plotbutton == 0){return()}
        inFile <- input$file1
        if (is.null(inFile)){return(NULL)}

          # Read CSV
          df <- read.csv(inFile$datapath, header = TRUE, sep = ",")
          df <- df[, c(1, 28:29)]

          # Convert df[1] from Factor to Character
          i <- sapply(df, is.factor)
          df[i] <- lapply(df[i], as.character)

          # Extract Depth From df[1]
          readingdepth <- c(word(df[,1],-1))
          readingdepth = as.numeric(readingdepth)

})

Let's say that I want to use readingdepth later in a renderPlot. How would I go about calling upon this from data1() to make it usable? Is it something like data1()$readingdepth[]?

A: In that case i would put: return(readingdepth) at the final of the reactive function and then when u make the renderplot just call the function data1() and assign a variable like x <- data1() (inside the renderplot function).
Then u will be able to use it. Otherwise you can make another reactive function and put the code to do the readingdepth again and also put the return(readingdepth).
Hope it helps.


text:
Q: How do I split up a search string to allow for quoted text? I want to make a list of strings from the text of a search field.
I want to make anything that is in double quotes be split out.
ex.
sample' "string's are, more "text" making" 12.34,hello"pineapple sundays
Produces
sample'
string's are, more_  //underscore shown to display space
text
 making
12.34
hello
pineapple
sundays

Edit: Here is my (somewhat) elegant solution, thanks for the help everyone!
Private Function GetSearchTerms(ByVal searchText As String) As String()
    'Clean search string of unwanted characters'
    searchText = System.Text.RegularExpressions.Regex.Replace(searchText, "[^a-zA-Z0-9""'.,= ]", "")

    'Guarantees the first entry will not be an entry in quotes if the searchkeywords starts with double quotes'
    Dim searches As String() = searchText.Replace("""", " "" ").Split("""")
    Dim myWords As System.Collections.Generic.List(Of String) = New System.Collections.Generic.List(Of String)
    Dim delimiters As String() = New String() {" ", ","}

    For index As Integer = 0 To searches.Length - 1
        'even is regular text, split up into individual search terms'
        If (index Mod 2 = 0) Then
            myWords.AddRange(searches(index).Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
        Else
            'check for unclosed double quote, if so, split it up and add, space we added earlier will get split out'
            If (searches.Length Mod 2 = 0 And index = searches.Length - 1) Then
                myWords.AddRange(searches(index).Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
            Else
                '2 double quotes found'
                'remove the 2 spaces that we added earlier'
                Dim myQuotedString As String = searches(index).Substring(1, searches(index).Length - 2)
                If (myQuotedString.Length > 0) Then
                    myWords.Add(myQuotedString)
                End If
            End If
        End If
    Next
    Return myWords.ToArray()
End Function

Oi, vb commenting is ugly, anyone know how to clean this up?

A: This is a more complex parsing problem than you fully appreciate. I suggest you look at the TextFieldParser class  and the FileHelpers library: http://www.filehelpers.com/

A: This is not THE COMPLETE solution since it is missing few validation checks, but it has everything you need.
My CharOccurs() finds occurrences of '"' and stores them into list in order.
public static List<int> CharOccurs(string stringToSearch, char charToFind)
        {
            List<int> count = new List<int>();
            int  chr = 0;
            while (chr != -1)
            {
                chr = stringToSearch.IndexOf(charToFind, chr);
                if (chr != -1)
                {
                    count.Add(chr);
                    chr++;
                }
                else
                {
                    chr = -1;
                }
            }
            return count;
        }

This below code is pretty much explanatory iteself. I take the string which is within quoted and split them differently with only '"' character. Then I do SubStrings on outside quotes string and split them on ",", space and '"' charaters. Please add your validations checks wherever needed to make it generic.
string input = "sample' \"string's are, more \"text\" making\" 12.34,hello\"pineapple sundays";

            List<int> positions = CharOccurs(input, '\"');

            string within_quotes, outside_quotes;
            string[] arr_within_quotes;
            List<string> output = new List<string>();

            output.AddRange(input.Substring(0, positions[0]-1).Split(new char[] { ' ', ',', '"' }));

            if (positions.Count % 2 == 0)
            {
                within_quotes = input.Substring(positions[0]+1, positions[positions.Count - 1] - positions[0]-1);
                arr_within_quotes = within_quotes.Split('"');
                output.AddRange(arr_within_quotes);
                output.AddRange(input.Substring(positions[positions.Count - 1] + 1).Split(new char[] { ' ', ',' }));
            }
            else
            {
                within_quotes = input.Substring(positions[0]+1, positions[positions.Count - 2] - positions[0]-1);
                arr_within_quotes = within_quotes.Split('"');
                output.AddRange(arr_within_quotes);
                output.AddRange(input.Substring(positions[positions.Count - 2] + 1).Split(new char[] { ' ', ',', '"' }));
            }

A: I Wrote this Parse Line function a few months ago for VB.NET, it may be of some use to you, it works out if there are Text Qualifiers and will split based on the Text, ill try to convert it to C# for you in the coming few minutes if you want me to.
You Would have your line of Text:
sample' "string's are, more "text" making" 12.34,hello"pineapple sundays
and you would have that as your strLine
and you would set your strDataDelimeters = ","
and you would set you strTextQualifier = """"
Hope this helps you out.
Public Function ParseLine(ByVal strLine As String, Optional ByVal strDataDelimiter As String = "", Optional ByVal strTextQualifier As String = "", Optional ByVal strQualifierSplitter As Char = vbTab) As String()
        Try
            Dim strField As String = Nothing
            Dim strNewLine As String = Nothing
            Dim lngChrPos As Integer = 0
            Dim bUseQualifier As Boolean = False
            Dim bRemobedLastDel As Boolean = False
            Dim bEmptyLast As Boolean = False   ' Take into account where the line ends in a field delimiter, the ParseLine function should keep that empty field as well.

            Dim strList As String()

            'TEST,23479234,Just Right 950g,02/04/2006,1234,5678,9999,0000
            'TEST,23479234,Just Right 950g,02/04/2006,1234,5678,9999,0000,
            'TEST,23479234,Just Right 950g,02/04/2006,1234,,,0000,
            'TEST,23479234,Just Right 950g,02/04/2006,1234,5678,9999,,
            'TEST,23479234,"Just Right 950g, BO",02/04/2006,,5678,9999,,
            'TEST,23479234,"Just Right"" 950g, BO",02/04/2006,,5678,9999,1111,
            'TEST23479234 'Kellogg''s Just Right 950g' 02/04/2006 1234 5678 0000 9999
            'TEST23479234 '' 02/04/2006 1234 5678 0000 9999

            bUseQualifier = strTextQualifier.Length()

            'split data based on options..
            If bUseQualifier Then
                'replace double qualifiers for ease of parsing..
                'strLine = strLine.Replace(New String(strTextQualifier, 2), vbTab)

                'loop and find each field..
                Do Until strLine = Nothing

                    If strLine.Substring(0, 1) = strTextQualifier Then

                        'find closing qualifier
                        lngChrPos = strLine.IndexOf(strTextQualifier, 1)

                        'check for missing double qualifiers, unclosed qualifiers
                        Do Until (strLine.Length() - 1) = lngChrPos OrElse lngChrPos = -1 OrElse _
                          strLine.Substring(lngChrPos + 1, 1) = strDataDelimiter

                            lngChrPos = strLine.IndexOf(strTextQualifier, lngChrPos + 1)
                        Loop

                        'get field from line..
                        If lngChrPos = -1 Then
                            strField = strLine.Substring(1)
                            strLine = vbNullString
                        Else
                            strField = strLine.Substring(1, lngChrPos - 1)
                            If (strLine.Length() - 1) = lngChrPos Then
                                strLine = vbNullString
                            Else
                                strLine = strLine.Substring(lngChrPos + 2)
                                If strLine = "" Then
                                    bEmptyLast = True
                                End If
                            End If

                            'strField = String.Format("{0}{1}{2}", strTextQualifier, strField, strTextQualifier)
                        End If

                    Else
                        'find next delimiter..
                        'lngChrPos = InStr(1, strLine, strDataDelimiter)
                        lngChrPos = strLine.IndexOf(strDataDelimiter)

                        'get field from line..
                        If lngChrPos = -1 Then
                            strField = strLine
                            strLine = vbNullString
                        Else
                            strField = strLine.Substring(0, lngChrPos)
                            strLine = strLine.Substring(lngChrPos + 1)
                            If strLine = "" Then
                                bEmptyLast = True
                            End If
                        End If
                    End If

                    ' Now replace double qualifiers with a single qualifier in the "corrected" string
                    strField = strField.Replace(New String(strTextQualifier, 2), strTextQualifier)

                    'restore double qualifiers..
                    'strField = IIf(strField = vbNullChar, vbNullString, strField)
                    'strField = Replace$(strField, vbTab, strTextQualifier)
                    'strField = IIf(strField = vbTab, vbNullString, strField)
                    'strField = strField.Replace(vbTab, strTextQualifier)

                    'save field to array..
                    strNewLine = String.Format("{0}{1}{2}", strNewLine, strQualifierSplitter, strField)

                Loop

                If bEmptyLast = True Then
                    strNewLine = String.Format("{0}{1}", strNewLine, strQualifierSplitter)
                End If

                'trim off first nullchar..
                strNewLine = strNewLine.Substring(1)

                'split new line..
                strList = strNewLine.Split(strQualifierSplitter)
            Else
                If strLine.Substring(strLine.Length - 1, 1) = strDataDelimiter Then
                    strLine = strLine.Substring(0)
                End If
                'no qualifier.. do a simply split..
                strList = strLine.Split(strDataDelimiter)
            End If

            'return result..
            Return strList

        Catch ex As Exception
            Throw New Exception(String.Format("Error Splitting Special String - {0}", ex.Message.ToString()))
        End Try
    End Function

A: If you wanted to display an underscore to indicate a space as before the ", like you show in your question you can use:
string[] splitString = t.Replace(" \"", "_\"").Split('"');

A: Regular expressions for this sort of thing get complicated fast as you start to add all sorts of exceptions.
None the less, if more for the sake of interest and completeness than anything else:
(?<term>[a-zA-Z0-9'.=]+)|("(?<term>[^"]+)")


text:
Q: bootstrap modal content does not show on specific platforms I have an odd issue that has been driving me crazy, for a flask web app. I have the following button that opens a modal called addincident
<button data-toggle="modal" data-target="#addincident" class="btn btn-default">Add New</button>

Which is supposed to open this modal:

                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Escalate an incident

                           < removed for brevity >

                                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
                                    <button id="submit" type="Button" class="btn btn-primary pull-right">Submit</button>

Now, this works on Fedora 22 and 24 on Chrome 52 and Firefox 46 and newer. However, some users on Fedora 23 report that the modal never appears on any of those browsers - all they get is the darkening screen for the overlay, but not the actual modal.
I have just today had the first report of this behavior on Fedora 24 with Chrome 52. The users reporting this problem say there are no errors in the browser console, and on the webserver side all I see are the standard GETs coming in - no errors or anything from flask or gunicorn.
Most of what I've seen from Google-ing this problem say it's an issue with having a fade in the modal, but as you can see I don't have one.
Thoughts?


text:
Q: fetching data and show them in proper place in backbone I have an issue in backbone, I want to render 100 rows of data from backend ( fetched by url) and show between of button element and pagination. I have created two templates, and have two views one for the whole page and the other for individual items. But when I fetch the data they do not go between the button and pagination div, all the 100 rows go under that. How can I put them in proper place? These are my templates:
the list template:

        <select>
          <option value="0">Bulk Actions</option>
          <option value="1">Delete</option>
          <option value="2">Mark As Read</option>
        </select>
        <button class="grey">OK</button>

        <select>
          <option value="0">All</option>
          <option value="1">Unread Messages</option>
          <option value="2">Read Messages</option>
        </select>
        <button class="grey">OK</button>

          <form>
            Results pr. page
            <select name="results">
              <option value="25">25</option>
              <option value="50">50</option>
              <option value="100">100</option>
              <option value="500">500</option>
            </select>
          </form>

          <input type="checkbox" name="type"/>
          CHECK ALL

          Date

          Message

          <input type="checkbox" class="type">

Previous

1

2

3

4

…

12

13

Next

other template:

          <input type="checkbox" class="type">

<%= created !== undefined ? created : "not available" %>

<%= name %>

<%= title %>

<%= id %>

//view for message:
define([
    "jquery",
    "underscore",
    "backbone",
    "js/collections/messagesCollection",
    "js/models/messagesModel",
    "text!templates/messageView.html",
    "text!templates/messageList.html",
    "text!templates/messageDetails.html"
    ], function($, _ , Backbone,
        MessagesCollection,
        MessagesModel,
         UserEditTemplate, UserViewTemplate, UserSelfEditTemplate, ResetPasswordTemplate, ChangePasswordTemplate){
        MessageViewTemplate, MessageListTemplate, MessageDetailsTemplate){

    var MessageView = Backbone.View.extend({

        tagName : "div",
        messageViewTemplate : _.template(MessageViewTemplate),

        messageDetailsTemplate : _.template(MessageDetailsTemplate),
        template : _.template(MessageDetailsTemplate),

        collection : MessagesCollection,

        initialize : function(){
            this.model.on("change", this.render, this);
            this.model.on("update", this.render, this);
        },

        render : function(){
            //this.$el.html(this.userTemplate(this.model.toJSON()));
            this.$el.html(this.messageViewTemplate(this.model.toJSON()));
            return this;

         }

    });
    return MessageView;
});

View for list of message:
define([
    "jquery",
    "underscore",
    "backbone",
    "js/models/loggedInUserModel",
    "js/models/currentTabModel",
    "js/models/messagesModel",
    "js/collections/messagesCollection",
    "js/views/messageView",
    "text!templates/messageList.html",
    "text!templates/messageDetails.html",
    "text!templates/header.html",
    "text!templates/breadcrumbs.html",
    "text!templates/footer.html"
    ], function($, _, Backbone,

        MessagesModel,
        MessagesCollection,
        MessageView,
        MessageListTemplate, MessageDetailsTemplate, HeaderTemplate, BreadCrumbTemplate, FooterTemplate
        ){

        var MessagesView = Backbone.View.extend({
            el : $("#maincontent"),
            messageListTemplate : MessageListTemplate,
            messageDetailsTemplate : _.template(MessageDetailsTemplate),
            collection : MessagesCollection,

            initialize : function(){
                console.log("initialize messages");
                this.collection = new MessagesCollection();

                this.collection.on("add", this.renderMessage, this);
                this.collection.on("reset", this.render, this);
                this.collection.on("update", this.render, this);
                if(this.options.selfEdit === false || _.isUndefined(this.options.selfEdit)){
                    this.start();
                }
                else{
                    console.log("options", this.options);
                    this.currentUserModel.fetch();
                }

            },

            start : function(){
                this.collection.fetch();
                this.currentUserModel.fetch();

                this.renderFooter();

            },
            render : function(){

                this.$el.html(this.messageListTemplate);
                _.each(this.collection.models, function(item){
                    this.renderMessage(item);
                }, this);
            },

            renderMessage : function(item){
                var messageView = new MessageView({
                    model : item
                });
                this.$el.append(messageView.render().el);
            },

            renderMessageDetails : function(item){
                var messageView = new MessagesView({
                    model : item
                });
                this.$el.append(messageView.renderSelfView().el);
            }

        });
    return MessagesView;
    });

//Model
define([
    "jquery",
    "underscore",
    "backbone"
    ], function($, _ , Backbone){

        var MessagesModel = Backbone.Model.extend({
            defaults : {
                id : null,
                created : null,
                timestamp : null,
                severity : null

            },

            parse : function(response){
                response.id = response._id.$oid;
                response.created = response.created.$date;
                response.timestamp = response.timestamp.$date;
                response.severity = response.severity;

                return response;
            },

            clear : function(){
                this.destroy();
                this.view.remove();
            },

            // Convert regular JSON into MongoDB extended one.
            toExtendedJSON: function() {
                var attrs = this.attributes;
                attrs = _.omit(attrs, ["created", "timestamp"]);

                if (_.isUndefined(attrs.created))  {
                    // console.log("this", this["this.created"]);
                    attrs.created = { $date: this.get("created") };
                }

                if (_.isUndefined(attrs.timestamp))  {
                    attrs.timestamp = { $date: this.get("timestamp") };
                }
                console.dir(attrs);
                return attrs;
            },

            // Substute toJSON method when performing synchronization.
            sync : function(method, model, options) {
                /*
                * If we are performing an update we need to call the extendedJSON method
                * By calling this, we guarantee that we comply to the MongoDB model.
                * After applying that model, we then call Backbone .sync protoryp and then set the model.toJSON method
                * back to its original definition.
                */
                if(method === "update" && !model.isNew()){
                    var toJSON = this.toJSON;
                    this.toJSON = this.toExtendedJSON;
                    var ret = Backbone.sync.apply(this, arguments);
                    this.toJSON = toJSON;
                    return ret;
                }
                else{
                    return Backbone.sync.call(this, method, this, options);
                }
            },

            formatDate : function(dateString) {

                return new Date(dateString).toUTCString();

            }

        });
    return MessagesModel;
});

Collection
define([
    "jquery",
    "underscore",
    "backbone",
    "js/models/messagesModel"
    ],function($,_, Backbone, MessagesModel){

        var MessagesCollection = Backbone.Collection.extend({

            model : MessagesModel,
            url : "/api/v1/message",

            parse : function(response, xhr){
                return response.list;
            }
});
        return MessagesCollection;
    });

A: Try following for renderMessage():
       renderMessage : function(item){
            var messageView = new MessageView({
                model : item
            });
            this.$el.find('div.message-list').append(messageView.render().el);
        },

Also update the code in a similar way for renderMessageDetails().


text:
Q: Determine UIWebView height based on dynamic local content, within a variable height TableViewCell Okay, so I know this question has been asked and asked. There are many good suggestions, but I cannot get this to work as expected. I am trying to create a tableview cell that can dynamically set its height on load based on different html. What everyone suggests is to use the following method.
-(void)webViewDidFinishLoad:(UIWebView *)webView

They say to calculate the height either using javascript as below:
NSString *output = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];

Or doing something like this (I created this):
self.webView = webView;
CGRect frame = webView.frame;
frame.size.height = 1;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;

Both of these methods return the correct height of the webview, but they happen after the tableview is initialized. This webViewDidFinishLoad gets called after heightForRowAtIndexPath method. So when the table is being built I dont have the height of the cell. So then everyone says well then just do a tableview reload inside your webViewDidFinishLoad which yet again does work, but I dont like this because there is a lag and it makes the scrolling of the tableview choppy when you get to that part. How can I fix this? And make it smooth? I was thinking of maybe somehow determining the webview height before loading the view, but not sure how I would do that. Also tried converting the html into a plain text string, but this results in a false height because the html has spaces and stuff while the plain text doesn't. Any help would be appreciated!

A: My suggestion is very similar to @Timothy Moose, by rendering the webview off screen.
The approach I would take here would be...
-(void)viewDidLoad
{
     //Create a UIWebView and store it in a property
     //Hook the delegate to the view controller.
     //Load the html string to the UIWebView.

     //The rest of your initialization
}

In this case, your heightForRowAtIndexPath: will still probably get called prior to the completion of the web view.
You can handle that in a couple of ways.  Here's one suggestion.
In the delegate method of the UIWebView's webViewDidFinishLoading, check to make sure that the webview making the call is the webview stored in your property.  If so, call to reload the section (or row) that your webview is contained in.  This should call the heightForRowAtIndexPath: method to get called again, in which this case, you can store the height of the webview in the webViewDidFinishLoading callback.
If the cell is off screen when the view first shows, the cell that is created in cellForRowAtIndexPath:, should have the UIWebView that you created in your viewDidLoad.  Do this by adding the UIWebView to the cell's content view.
If the cell is on screen when the view first shows, I would suggest an activity spinner the first time the cell is loaded, and then once the webview is done loading, reload the cell with the webview.

A: At the end of the day you can't know the height of a webview's content until it loads.  And if the same bit of code is setting up the table and loading the webview, the webview is always going to complete it's load after the table is already displayed.
If you repeatedly load the same HTML you could cache the height, but you're still going to have a problem the first time.
So the only way you're going to be able to display the scrolling tableview without being choppy is to have a default cell height until the webview has loaded. Then change it. But you've tried that, using reload. And that was choppy.
But what about it the cell height animates between the default hight and the true height?  Maybe that would be more acceptable.
If you're only doing height changes, I believe you can do this rather than reload, in order to animate the resizing.
[tableView beginUpdates];
[tableView endUpdates];

Nothing needed between the two lines.
Maybe you could combine this with caching the true height of the HTML for next time the user scrolls it into view.

A: In your case you have webview in tableviewcell, so in heightForRowAtIndexPath set the height of cell to height of NSAttributedString size as following.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSAttributedString *attributedText = [NSString  getHTMLAttributedString:@"HTML Content"];
    CGSize size = CGSizeMake(300, CGFLOAT_MAX);
    CGRect paragraphRect =     [attributedText boundingRectWithSize:size
                                 options:(NSStringDrawingUsesLineFragmentOrigin)
                                 context:nil];
    return paragraphRect.size.height;
}

+(NSAttributedString *) getHTMLAttributedString:(NSString *) string{
    NSError *errorFees=nil;
    NSString *sourceFees = [NSString stringWithFormat:
                            @"%@",string];
    NSMutableAttributedString* strFees = [[NSMutableAttributedString alloc] initWithData:[sourceFees dataUsingEncoding:NSUTF8StringEncoding]
                                                                                options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                                NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
                                                                      documentAttributes:nil error:&errorFees];
    return strFees;

}


text:
Q: Calculate result of formula Can someone help me solve this problem in Assembly language in signed and unsigned representation?
My task is to calculate the result of the following term:
(a*a+b)/(b+b)+c

where a is a word, b is a byte , and c a doubleword
I tried this:
assume CS:code, DS:data
data segment
    a dw 1
    b db 2
    c dd 3
    x dd ?
data ends
code segment
    start:
        mov ax, data
        mov ds, ax

        mov ax, a   ; AX = a
        mul a       ; AX = a*a
        add ax, 2   ; AX = a*a + 2

        mov bl, b   ; BX = b
        add bl, b   ; BX = b*b
        div bl      ; a*a+b/b+b
        mov ax, word ptr c+2
        mov dx, word ptr c
        add ax, word ptr c
        mov word ptr x+2, dx
        mov word ptr x, ax

        mov ax, 4c00h
        int 21h
    code ends
end start

A: mov ax, a   ; AX = a
mul a       ; AX = a*a

Wrong comment: The result of this mul is in DX:AX
add ax, 2   ; AX = a*a + 2

I don't think you're supposed to add b as an immediate!
mov bl, b   ; BX = b
add bl, b   ; BX = b*b

Wrong comment: It's an addition.
div bl      ; a*a+b/b+b

You would better make this a word division by zeroing the BH register prior to div bx. Also where have the brackets gone in your comment?
mov ax, word ptr c+2
mov dx, word ptr c
add ax, word ptr c

Here you're doing it all wrong. The result of the new word division will be in AX. So add the low word of c to AX and add with carry the high word of c to an empty DX register.
mov word ptr x+2, dx
mov word ptr x, ax

Seems OK.


text:
Q: Lua: what scope do variables in "required" modules go to? After spending the week learning Lua, I was a bit shocked to encounter this weird scenario, since I had previously imagined that the "require" command worked just like a #include in C/C++ (i.e., it's copy/pasted in by the preprocessor).
Obviously that's not the case.
Here's what stumped me:
-- a.lua
this_is_global = "I'm a global var!!"
require "b"
print(global_in_b) -- error??!! globals in b aren't truly global?

-- b.lua
print(this_is_global) -- prints "I'm a global var!"
-- so b can see globals from a
global_in_b = "Am I global too?"

For productivity reasons I've just been creating my own table to act as a scope in b, adding everything I want to access to that table, and then returning the table in b so that I can write:
-- a.lua
stuff_from_b = require "b"
print(stuff_from_b.global_in_b)  -- does what we want, in a weird way

I know I can also manually add stuff in b.lua to the _G table to force them to be global, but that feels ugly.
So my questions:

*

*What's exactly happening with "globals" in required files?  What table do they end up in if not _G?

*What're the commonly accepted ways of accessing scopes of required files?

A: Neither require nor dofile are equivalent to include: both run code at run time, not textually add source code during compilation.
The globals that a required file sees are the same as the globals in the file that required it.
To avoid pollution and to allow privacy and hiding, it is good practice that Lua modules create and return a table with what they want to export to the external world. It is up to the designer of the module to decide what can be seen from the outside.


text:
Q: Zend: Action Helper Pre-Dispatch Conditional on Route I have two Action Helpers, one for Auth, and one for ACL.  For my default route, I am using the helpers' pre-dispatch hooks to fire them on every request (Auth first, then ACL).  I have a second route however, and for this route I only want Auth to fire.  (ACL is a non-issue for the second route).
What's the easiest way to get the ACL Action Helper to fire only on the default route?  I was thinking of putting an "if route = ..., then ..." in the action helper.  But is there a more elegant method?
Thanks!

A: OK. I had wondered if there was a way to configure the Action Helper on a per-route basis, but I'm happy with the consensus in the comments above.  I'll put an if-then in the ACL Action Heper.  Thanks!


text:
Q: Can we search Algolia Places and on of our Indices at the same time? Here's an example of what I would like to do based on this example in Algolia docs: https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/
var algolia = algoliasearch(app_id,  search_only_key);
var regionIndex = algolia.initIndex("Global");
var algoliaPlaces = algoliasearch.initPlaces(app_id, search_only_key)

algolia.search([
  {
    index: algoliaPlaces,
    query: "211 Solti St"
  }, {
    index: regionIndex,
    query: "211 Solti St"
  }
])

A: You cannot use multiple-queries to query Places since it is a service API and not a simple index.
You can query both separately and combine results, or take a look at the following example that does what you want!
https://community.algolia.com/places/examples.html#autocompletejs


text:
Q: Find Asterisk and change to red color in form label [Meteor JS Way] Consider SimpleSchema,
ClientsSchema = new SimpleSchema({
  "firstName": {
    type: String,
    label: "First Name *",
    max: 20
  }
});

On UI it appears as below,

We mostly write javascript in below peice of code,
Template.Name.onRendered(function(){});

View Source looks like below,

        First Name *
        <input type="text" name="firstName" id="8fmieRFmLkqYQ5XFF" required="" data-schema-key="firstName"
            maxlength="20" class="form-control">

How can I change the color of asterisk? I tried various other articles on same query but I could not resolve it.

A: You'll likely want to append the asterisk using a pseudo-element in CSS. For example,
ClientsSchema = new SimpleSchema({
  "firstName": {
    type: String,
    label: "First Name", // remove asterisk from here
    max: 20
  }
});

Then style it:
.form-group[data-required="true"] .control-label::after {
  content: '*';
  display: inline-block;
  color: red;
}

No need for anything Meteor-specific here!


text:
Q: How do I use a get request AJAX call to my php function? sorry if this seems like a ridiculous question, however, I've been pulling my hair out for 3 days trying to work out how to do this...
I essentially want to pull out this (query var?) and use the parameters in my current function...
?vote=up&comment_id=8

Here is my current function:
<?php
// This file is used for buildimng the custom comment upvote and downvote functionality.

add_action( 'wp_enqueue_scripts', 'ajax_enqueue' );
function ajax_enqueue() {
// Enqueue File from 'inc' folder.
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/inc/ajax/comment_vote_ajax.js', array('jquery') );

// in JavaScript, object properties are accessed as
ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
    array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'user_id' => get_current_user_id()
    )
);
}

// Same handler function...
function ajax_action() {
global $wpdb;

if ( ! is_user_logged_in() ) {
    return;
}

if ( ! isset( $_GET[ 'vote' ] ) && ! isset( $_GET[ 'comment_id' ] ) ) {
    return;
}

$up_or_down = esc_attr( $_GET[ 'vote' ]) ;
if ( ! in_array( $up_or_down, [ 'up', 'down' ] ) ) {
    return;
}

$comment_id = (int) esc_attr( $_GET[ 'comment_id' ] );
if ( $comment_id < 1 ) {
    return;
}

// Retreive the existing comment up/down vote ID's - we don't know who did what at this point..
$vote_user_ids = get_comment_meta( $comment_id, '_vote_user_ids', true );

// If the comment upvote count isn't set, create an empty array.
// This will always be the case on the first instance of a user "upvoting" a comment
if ( ! is_array( $vote_user_ids ) ) {
    $vote_user_ids = [];
}

// Check if the user has already "voted"
if ( array_key_exists( get_current_user_id(), $vote_user_ids ) ) {

    // If the user HAS voted and they are repeating themselves (e.g. the voted up and are trying to do this again) ignore them..
    if ( $up_or_down === $vote_user_ids[ $user_id ] ) {
        return;
    } else {
        // The user voted already but have changed their vote - update this
        //$vote_user_ids[ get_current_user_id() ] = $up_or_down;
        unset ( $vote_user_ids[ get_current_user_id() ] );
    }

} else {

    // The user HAS NOT voted, add them
    $vote_user_ids[ get_current_user_id() ] = $up_or_down;
}

// Whatever the results of ^^ we need to update now
$update_result = update_comment_meta( $comment_id, '_vote_user_ids', $vote_user_ids );
delete_transient( "comment_vote_count_comment_{$comment_id}" );

if ( ! $update_result ) {
    error_log( "Error updating comment meta to update $comment_id to set user ID $user_id $up_or_down." );
}

wp_die();
}

add_action( 'wp_ajax_my_action', 'ajax_action' );
add_action( 'wp_ajax_nopriv_my_action', 'ajax_action' );

// End of the ajax call.
Here is the current script I have...
var $ = jQuery.noConflict();

function getParameterByName(name, url) {
if (!url) url = $(this).attr('href');
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}

$(document).ready(function(){

$("a.upvote").click(function(e) {
    e.preventDefault();
    var comment_id = getParameterByName('comment_id', $(this).attr('href'));

    filters_get = {
        'vote': 'up',
        'comment_id': comment_id
    };

    $.ajax({
      url: ajax_object.ajax_url,
      type: "post", //send it through get method
      data: filters_get,
      cache: false,
      success: function(data) {
        console.log( 'comment_id' + ' = ' + comment_id );
        console.dir(data);
        console.log(data);
        $('.comment p').after(data);
      },
      error: function(xhr) {
      }
    });
});
});


text:
Q: Can I add text to page-source dynamically in Ruby on Rails I would like to add text dynamically to the page source in a particular view. I checked the IO streams, but couldn't find anything. Could you please provide some pointers.
Edit:
Thanks for the reply. I was trying to know how much time each part/component in a particular view takes to render and log it as part of the page-source. Please let me know if I am not clear enough.

A: You can use JavaScript to modify the Document Object Model (DOM) of a page after Rails has rendered the view. If you edit your question to make it more specific then we can give more specific answers.


text:
Q: Some words on QueryInterface magic many times I have had an issue and post for help and so many times QueryInterface is the solution. I have been addon programming for a long time now but never understood QueryInterface. It seems like magic, like it holds the solution to everything.
like:
window.QueryInterface(Ci.nsIInterfaceRequestor)
                         .getInterface(Ci.nsIWebNavigation)
                         .QueryInterface(Ci.nsIDocShellTreeItem)
                         .rootTreeItem
                         .QueryInterface(Ci.nsIInterfaceRequestor)
                         .getInterface(Ci.nsIDOMWindow);

So my question is I see a QueryInterface chain, I don't get why the chain, and I definitely don't get how to create my own chain. I don't get how do you know to chain from nsiInterfaceRequester to nsiWebNavigation and not from nsiInterfaceRequester straight to nsiDOMWindow

A: There is really nothing special here. DOM windows implement the nsIInterfaceRequestor interface that allows getting related objects. One such object is the docshell that is associated with the window - you get it by asking for the nsIWebNavigation interface but it also implements the nsIDocShell and nsIDocShellTreeItem interfaces - and nsIInterfaceRequestor. The docshell for the current window lets you get to the docshell for the top window, despite the security boundary between chrome and content. And there you can use the nsIInterfaceRequestor interface again to ask the docshell for the window associated with it.
You can simply implement the nsIInterfaceRequestor interface in your XPCOM component just like any other interface. I don't see any reason to ever do that however, it's an ugly hack to hide internal window-related interfaces from the DOM.


text:
Q: Converting byte array or String value to float in P5.js (javascript based) I have been successful in getting serial data in P5.js sketch using this - GitHub - p5-serial/p5.serialport: Serial Port API and Server for p5.js library as either byte array or string values.
When I tried converting string to float type using float() – I get a lot of NaN values which shouldn't be coming since data is numerical.
Alternatively, I then tried getting data from serial port as byte array. I can't find a way to convert this array to my original float value in P5.js.
Any ideas on how to convert byte array to float or avoid getting NaN when converting string to float?
Appreciate your time and help. Thanks.
Codes I have tried for conversion:

*

*From String to float, I used
let incomingData;

let dataValue;

incomingData = serial.readStringUntil('\n');

dataValue = float(incomingData);  //standard method in P5.js -- returns NaN values

I also tried parseFloat() -- https://www.geeksforgeeks.org/javascript-parsefloat-function/
  dataValue = parseFloat(incomingData);
  //again returns maximum values as NaN

*From byte array to float
let incomingBytes = [];

let dataValue;

incomingBytes = serial.readBytesUntil('\n');

dataValue = dataView.getFloat64(bytebuffer);
// This javascript method is not supported by P5.js it seems

A: As seen in the last image, there were empty strings or null values coming. I just had to put a check for it before doing the conversion.
Thanks to all the commenters.
 let incomingData;                    //incoming serial value is stored in this variable

 let temparray = [1000];              //temporary array used in updating final array

 let plot_from_here = [1000];         //final array of values to plot
 function setup(){}
 function draw(){}

 function serialEvent() {

  if(serial.available()>0){

   incomingData = serial.readStringUntil('\n');    //read string until next line

    if(incomingData != ""){

     incomingData = trim(incomingData);            //trim white spaces

     arrayCopy(temparray,0, temparray,1,999);      //Copy value from index 0 to index 1

     temparray[0]= float(incomingData);            //Update index 0 of temparray for the incoming value -- the value is converted to float from string type

     plot_from_here = temparray;                   //update values in final array

    print(plot_from_here);

     }
   }
  }


text:
Q: CodeIgniter - Delete data from multiple table I want to delete data from 3 table,i have table user,pemohon,peserta where all table is connected each other with foreign key.
this query work,I've tried on mysql
DELETE user,pemohon,peserta
FROM user,pemohon,peserta
WHERE user.id_user=pemohon.id_pemohon AND
pemohon.id_pemohon=peserta.id_peserta AND pemohon.id_pemohon=1

so i convert to CodeIgniter like this
function delete_data($id)
{
    $this->db->where('pemohon.id_pemohon=user.id_user');
    $this->db->where('pemohon.id_pemohon=peserta.id_peserta');
    $this->db->where('pemohon.id_pemohon',$id);
    $this->db->delete('pemohon','user','peserta');
}

but this code not work, can you fix my code? Thanks

A: In delete function you must be provide array of tables:
function delete_data($id)
{
    $this->db->where('pemohon.id_pemohon=user.id_user');
    $this->db->where('pemohon.id_pemohon=peserta.id_peserta');
    $this->db->where('pemohon.id_pemohon',$id);
    $this->db->delete(array('pemohon','user','peserta'));
}

If it not worked, execute with query function ($id escaped):
function delete_data($id)
{
    $sql = "DELETE user,pemohon,peserta
        FROM user,pemohon,peserta
        WHERE user.id_user=pemohon.id_pemohon
        AND pemohon.id_pemohon=peserta.id_peserta
        AND pemohon.id_pemohon= ?";

    $this->db->query($sql, array($id));
}

And without escaping $id:
function delete_data($id)
{
    $this->db->query("DELETE user,pemohon,peserta
        FROM user,pemohon,peserta
        WHERE user.id_user=pemohon.id_pemohon
        AND pemohon.id_pemohon=peserta.id_peserta
        AND pemohon.id_pemohon= $id";
}

A: you can try this process
function delete_data($id)
{
   $this->db->delete('user', array('id_user' => $id));
   $this->db->delete('pemohon', array('id_pemohon' => $id));
   $this->db->delete('peserta', array('id_peserta' => $id));
}

A: You can save table name within an array and pass that array as parameter in delete(). As you can read full example : https://tutorialpace.com/CodeIgniter-Tutorials/CodeIgniter-Database-Delete


text:
Q: Find the sum of two numbers which are in the separate line? So there is a problem on SPOJ as mentioned below:

Given two natural numbers (both not greater than 200), each number in the separate line, please print the sum of them.

Example Input:
2
3

    Output: 5

So I wrote a program to this problem. Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int input1, input2, sum;
    printf("Enter two natural numbers\n");
    scanf("%d", &input1);
    scanf("\n%d", &input2);
    if ((input1>0&&input1<=200) && (input2>0&&input2<=200))
    {
        sum = input1 + input2;
        printf("%d", sum);
    }
    return 0;
}

But SPOJ rejected this answer as a wrong answer.
Later I checked this on idone.
But I'm unable to detect, what's wrong with this answer, as expected it gives the same output given in above question.
Please correct if I'm wrong.

A: The first print statement
printf("enter two natural numbers\n");

The Second
scanf("%d",&input1);//Press Enter

The Third
scanf("%d",&input2);//Press Enter

And finally
printf("\n%d",sum);

A: First of all, remove the printf statement as it is not needed and will mess up the expected I/O as given by SPOJ.
Next, there is no need of the newline character in scanf. You can directly write scanf("%d %d", &input1, &input2);. Another way would be to write the scanf statement twice as:
scanf("%d", &input1);
scanf("%d", &input2);

Lastly, you can also remove the if statement, if input bounds are given by SPOJ.


text:
Q: SQL Query How to Find Data for Last Few Months in January (mixed years) SQL Server 2008 I'm creating a query to pull records for the Last 3 Months. The problem I am having is when the last x months cross over to the previous year. I think I have a solution, but I feel like there's a better way?
Field: asiplayer.date_used is a DateTime field.
The below code seems to be working (but how do I test for January in July?)
Is there a better way? What if it was the last 6 months, would I just continue this code?
WHERE
-- ACTIVE LIST (LAST 3 MONTHS)
(

(   --Current Month is Not January or February, so all 3 months are in current year

        MONTH(CURRENT_TIMESTAMP) NOT IN (1,2)
        AND MONTH(asiplayer.date_used) >= MONTH(DateAdd(month,-2,CURRENT_TIMESTAMP))
        AND YEAR(asiplayer.date_used) = YEAR(CURRENT_TIMESTAMP)
)

    OR  --It's January so some of the months are last year

(
        --Get November and December of the Previous Year
        (MONTH(CURRENT_TIMESTAMP) = 1 AND   (MONTH(asiplayer.date_used) = MONTH(DateAdd(month,-2,CURRENT_TIMESTAMP)) OR MONTH(asiplayer.date_used) = MONTH(DateAdd(month,-1,CURRENT_TIMESTAMP)))
            AND YEAR(asiplayer.date_used) = YEAR(DateAdd(year,-1,CURRENT_TIMESTAMP))
        )

        OR
            --Get January of the Current Year
            (MONTH(CURRENT_TIMESTAMP) = 1
            AND MONTH(asiplayer.date_used) = 1
            AND YEAR(asiplayer.date_used) = YEAR(CURRENT_TIMESTAMP)
            )

)

    OR --It's February so some of the months are last year

(
        --Get December of the Previous Year
        (MONTH(CURRENT_TIMESTAMP) = 2 AND MONTH(asiplayer.date_used) = MONTH(DateAdd(month,-2,CURRENT_TIMESTAMP))
            AND YEAR(asiplayer.date_used) = YEAR(DateAdd(year,-1,CURRENT_TIMESTAMP))
        )

        OR
            --Get January & February of the Current Year
            (MONTH(CURRENT_TIMESTAMP) = 2
            AND MONTH(asiplayer.date_used) IN (1,2)
            AND YEAR(asiplayer.date_used) = YEAR(CURRENT_TIMESTAMP)
            )

)

)

A: Serg provided the answer:
DATEDIFF(MONTH, asiplayer.date_used, CURRENT_TIMESTAMP) <=3


text:
Q: Why isn't my .NET garbage being collected? I have a data intense application where a user can select between different accounts.  Only one account can be selected at a time and this forces data to be loaded from the database.  I can see in Windows Task Manager the memory allocated to my application is increasing when I load an account to approximately half a gig.
We also have the ability to "unload" an account whereby we delete all of the objects (or at least we think we do) in memory.  However long I leave the application running dormant on my PC it never seems to decrease the allocated memory back to pre-loading account state even though if I look at the object states using WeakReference is says its not ALIVE.
If I explicitly call GC.Collect() at the end of the unload method then I can see the memory being unallocated or at least the size of the program in Windows Task Manager going down.  This is what we'd really like to accomplish in terms of memory as some users have experienced out-of-memory exceptions.
I know the garbage collector is doing some management because if I load subsequent accounts the memory never really increases much past half a gig so I think the GC has collected the previous account's data just like it should have done when unloading the account.
Should I continue to use GC.Collect considering the cost of running this relative to loading an account from the DB is minimal even though it is considered "bad practice" to explicitly call this?

A: The GC collection is only triggered under certain events (eg the allocated memory for the hosting process is all used and it needs to allocate more, so it first check if it can collect some garbage).
The OM exception is probably not caused by this, but that either you have a memory leak somewhere else, or certain users are trying to load more than one account (or even a bigger than 0.5GB one). Consider doing some memory profiling on your application. (I have used YourKit profiler for this and its pretty easy to use)
Think that if your process is x86 it has a maximum of 2GB available, so with such big data is not uncommon you get to the limit.

A: From what you describe it seems that you are somehow keeping hard references from items that you load from db. If you are using Entity framework or NHibernate, please check that you are disposing the context that you are using to load the data from your database as it will hold references for everything that you load in order to provide change tracking capabilities. Generally make sure that you are not keeping a reference somehow and be aware that sometimes this can be tricky; a good example of a tricky hard reference is loading some stuff in a lamda method which uses a method-scope variable, which gets auto-promoted to class variable because of being referenced inside the lamda method.

A: I can't tell if you did this in your code but a using statement will call the Dispose() method of the command that you are using.  It might help with the GC that you are having an issue with. Otherwise you are letting the system handle it.  The only issue is that the class you are using has to implement IDisposable.
    using (SqlCommand cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "sp_SaveSomething";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@x", xxx));
    cmd.Parameters.Add(new SqlParameter("@ORG", ORG));
    cmd.ExecuteNonQuery();
}


text:
Q: How to declare a class with constructor and child objects? I want to create a class called Shapes that contains different shapes(objects), which has a constructor and then i want to add the different objects with their variables. At the end of all i want to display in the console the object's angles.
So i wrote this code but something is missing..any ideas?

class Shapes {
  constructor(){
    var angles = 0;
  }
    Triangle(){
      angles = 3;
      return angles;
}
    Square(){
      angles = 4;
      return angles;
  }
  console.log(Triangle)
}

A: You have completely misunderstood the class declaration and its usage. You first need to define a class with name Shapes so that the constructor will initialize the angles value. Then you can create different shapes(objects) with those angle values.

class Shapes {
  constructor(angles){
    this.angles = angles;
  }
}

var Triangle = new Shapes(3);
console.log(Triangle.angles);

var Square = new Shapes(4);
console.log(Square.angles);

A: This is another way :

function shapes(angle) {
  this.angles = angle;
}

var Triangle = new shapes(3);
var Square = new shapes(4);

console.log( Triangle.angles );
console.log( Square.angles );


text:
Q: Can't find SttpBackends + "Error occurred in an application involving default arguments." I'm trying to create a extremely simple Telegram bot in Scala using bot4s. I'm pretty much following the example there. Here's the code:
package info.jjmerelo.BoBot

import cats.instances.future._
import cats.syntax.functor._

import com.bot4s.telegram.api.RequestHandler
import com.bot4s.telegram.api.declarative.Commands
import com.bot4s.telegram.clients.{FutureSttpClient, ScalajHttpClient}
import com.bot4s.telegram.future.{Polling, TelegramBot}

import scala.util.Try
import scala.concurrent.Future

import com.typesafe.scalalogging.Logger

object BoBot extends TelegramBot
    with Polling
    with Commands[Future] {

  implicit val backend = SttpBackends.default
  def token = sys.env("BOBOT_TOKEN")
  override val client: RequestHandler[Future] = new FutureSttpClient(token)
  val log = Logger("BoBot")
//  val lines = scala.io.Source.fromFile("hitos.json").mkString
//  val hitos = JSON.parseFull( lines )
//  val solo_hitos = hitos.getOrElse( hitos )

  onCommand("hey") { implicit msg =>
    log.info("Hello")
    reply("Conseguí que funcionara").void
  }
}

And here's the build.sbt
name := "bobot"

version := "0.0.1"

organization := "info.jjmerelo"

libraryDependencies += "com.bot4s" %% "telegram-core" % "4.4.0-RC2"

val circeVersion = "0.12.3"

libraryDependencies ++= Seq(
  "io.circe" %% "circe-core",
  "io.circe" %% "circe-generic",
  "io.circe" %% "circe-parser"
).map(_ % circeVersion)

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.9.2"
retrieveManaged := true

Circe is for later

Anyway, I managed to compile most of it, but I still get these two errors:
[info] compiling 2 Scala sources to /home/jmerelo/Asignaturas/cloud-computing/BoBot/target/scala-2.12/classes ...
[error] /home/jmerelo/Asignaturas/cloud-computing/BoBot/src/main/scala/info/jjmerelo/BoBot.scala:21:26: not found: value SttpBackends
[error]   implicit val backend = SttpBackends.default
[error]                          ^
[error] /home/jmerelo/Asignaturas/cloud-computing/BoBot/src/main/scala/info/jjmerelo/BoBot.scala:23:49: could not find implicit value for parameter backend: com.softwaremill.sttp.SttpBackend[scala.concurrent.Future,Nothing]
[error] Error occurred in an application involving default arguments.
[error]   override val client: RequestHandler[Future] = new FutureSttpClient(token)
[error]                                                 ^
[error] two errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 5 s, completed 11 nov. 2020 8:19:38

I can't figure out either of the two. SttpBackends is missing, that's clear, but there's nothing in the example that indicates it's needed, or, for that matter, what library should be included. The second one about the default arguments I simply can't figure it out, even if I define token as String or if I change def to val. Any idea?

A: Your error messages is associated with each other.
First error tells us that compiler couldn't find object SttpBackends which has field of SttpBackend.
The second one tells us that compiler couldn't find implicit backend: SttpBackend for constructing FutureSttpClient. It requires two implicits: SttpBackend and ExecutionContext.
class FutureSttpClient(token : _root_.scala.Predef.String,
  telegramHost : _root_.scala.Predef.String = { /* compiled code */ })
  (implicit backend : com.softwaremill.sttp.SttpBackend[scala.concurrent.Future, scala.Nothing],
    ec : scala.concurrent.ExecutionContext)
  extends com.bot4s.telegram.clients.SttpClient[scala.concurrent.Future] {...}

You can create it by yourself as in bot4s examples.
If you will try to find SttpBackends object in bot4s library you would found this code in bot4s examples:
import com.softwaremill.sttp.okhttp._

object SttpBackends {
  val default: SttpBackend[Future, Nothing] = OkHttpFutureBackend()
}

add this object to your project to make it compilable.


text:
Q: Почему в лямбда выражении не получается поставить фигурные скобки? Есть работающий код:
bExchColumn.setCellFactory(column -> EditCell.createStringEditCell());

При попытке вставить фигурные скобки в лямбда-выражение ...
bExchColumn.setCellFactory(column -> {EditCell.createStringEditCell();});

eclipse ругается:

The method setCellFactory(CallBack<TableColumn<Bread,String>,TableCell<Bread,String>>)
  in the type TableColumn<Bread,String> is not applicable for the
  arguments ((<no type> column) -> {})"

В чем ошибка и как исправить?

A: Цитаты из урока Oracle по лямбдам (расставил акценты и перевёл).
В разделе "из чего состоит лямбда":

A body, which consists of a single expression or a statement block.
Тело, состоящее из единственного выражения или блока инструкций.

Обращаю внимание, что "блок инструкций" это набор инструкций в {}. Далее:

If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively, you can use a return statement
Если указать единственное выражение, рантайм Java вычислит это выражение и вернёт его значение. Или же можно использовать инструкцию return

Посему, вот два равноценных примера:
p -> выражение
p -> { return выражение; }

Вы же написали p -> { выражение; }, которое им не эквивалентно и ничего не возвращает.

A: До полноценной лямбды не хватает return:
{return EditCell.createStringEditCell();}

A: Метод bExchColumn.setCellFactory() ожидает какой-то аргумент, который должно вернуть лямбда-выражение. В вашем работающем варианте в качестве аргумента используется значение, возвращенное методом EditCell.createStringEditCell() (потому что лямбда состоит из него одного), а во втором варианте этот метод - часть тела лямбда-выражения, а его результат не возвращается из лямбды, а игнорируется (не присваивается ничему и не возвращается).


text:
Q: What mistake am I making when creating a constraint in generics? In asp.net 2.0 I have several "dropdowns" defined using generics (examples eye color, hair color, etc). The fields are all typical; id, text, etc. All are defined as their own classes which must implement an interface I created called ILookup. However, when I try to return a List<> of this class using:
ddlEyeColor.DataSource = luMgt.GetLookUpItemList(Of EyeColor)()

which calls the BC layer:
  Public Function GetLookUpItemList(Of t As {ILookup, New})() As List(Of t)
    Dim luMgt As New LookupMgt
    Return luMgt.GetLookUpItemList(Of t)()
End Function

Which calls the DBC layer which, in part is....
    Public Function GetLookUpItemList(Of t As {ILookup, New})() As List(Of t)

    Dim lstGenericList As New List(Of t)
    'rest of code to populate the list here
    end function

the error message claims EyeColor does not implement ILookup.
Error   21  Type argument 'EyeColor' does not inherit from or implement the constraint type 'ILookup'.
But here is the beginning of the EyeColor class....
Public Class EyeColor
Implements ILookup

Here is the complete Interface....
Public Interface ILookup
Property ID() As Int32
Property Text() As String
Property Description() As String
Property Status() As Status
Property OrderID() As Int32
ReadOnly Property LookUpType() As LookUpType

End Interface
And here, in the EyeColor class, I am implementing the properies of the interface
Public Overrides Property Description() As String Implements ILookup.Description
    Get
        Return MyBase.Description
    End Get
    Set(ByVal value As String)
        MyBase.Description = value
    End Set
End Property

Public Overrides Property ID() As Integer Implements ILookup.ID
    Get
        Return MyBase.ID
    End Get
    Set(ByVal value As Integer)
        MyBase.ID = value
    End Set
End Property

Public Overrides Property OrderID() As Integer Implements ILookup.OrderID
    Get
        Return MyBase.OrderID
    End Get
    Set(ByVal value As Integer)
        MyBase.OrderID = value
    End Set
End Property

Public Overrides Property Status() As Status Implements ILookup.Status
    Get
        Return MyBase.Status
    End Get
    Set(ByVal value As Status)
        MyBase.Status = value
    End Set
End Property

Public Property EyeColor() As String Implements ILookup.Text
    Get
        Return _eyeColor
    End Get
    Set(ByVal value As String)
        _eyeColor = value
    End Set
End Property

Public ReadOnly Property LookUpType() As LookUpType Implements ILookup.LookUpType
    Get
        Return BE.LookUpType.EyeColor
    End Get
End Property

A: I upvoted Jay's comment. He's absolutely right. Simply adding Implements ILookup to your class definition doesn't actually implement the interface.
You need to create the actual methods that the interface dictates.

A: I think you need to change your method signature to:
Public Function GetLookUpItemList(Of T As {ILookup, New})() As List(Of ILookup)


text:
Q: Coordinate system - ArcMap and Mapinfo I am not sure if someone already asked this question, but I am having trouble to understanding MapInfo and I only recently started working with ArcMap.
I have done a map (different shp files) in a coordinate system MGI Balkan 6 (the coordinate system I need), but when the client opens this map (shp.files) in MAPInfo the coordinate system they see is not in the "fitting" coordinate system.
How can I solve this problem in ArcMap so when I send it to them they could see it appropriately?

A: When you add data to an ArcMap project the data are contained within a data frame.  This data frame can have a defined coordinate reference system (CRS) - in your case you either set it to MGI Balkan 6 or the first shapefile you added was referencing was using MGI Balkan 6 and ArcMap defined the CRS for the data frame for you.  Any shapefile can have its own CRS but ArcMap will do 'projection on the fly' for you so even if different shapefiles reference different CRSs ArcMap will sort out the issues and display them in the same place for you.
I have not used MapInfo but I am guessing that either MapInfo is not doing 'projection on the fly' or there is a setting that is not set to do projection on the fly.  MapInfo is making some assumption about the CRS and displaying the data where it thinks it should go - in this case Africa.  The solution would be to reproject all of your data to MGI Balkan 6 before sharing.  Tell the MapInfo user to ensure her MapInfo project is referencing MGI Balkan 6 and everything should line up for her as well.


text:
Q: pexpect Prompt with new line I am automating application configuration on the CentOS with pexpect. My prompt is new line as below,
Please enter command below.

On the Next line (which is blank/new line line), i need to enter necessary commands,
i tried couple of things to match r'\b below.\b' to check for the new line r'\r\n(\w+)' , white space (\s) and so on but none of them is matching the expect prompt.
eg.
child.sendline('a')
child.expect([pexpect.TIMEOUT,r'\b below.\b'])
print child.before

it would be great help if any one can provide any suggestion for this ..

A: (I realize this is old, but it may help someone)
This works for me with pxssh, which is basically a wrapper around this:
expect_string = 'below.'
child.expect(expect_string)
child.sendline('a')
print(child.before)

If I'm reading your code right, you have your sendline before you expect. You need to switch that.


text:
Q: soldering a 12V plug cathode I cant seem to properly solder a stranded wire to that cathode terminal. Checked the answer https://electronics.stackexchange.com/a/90605/35737 - fluxing it did not help and solder does not adhere to it. Perhaps I am not applying flux correctly. I just put on some tacky flux I have got, then touch the fluxed cathode with the hot iron and immediately touch the iron + cathode terminal with solder. it barely sticks to it. Afterwards I bring that copper knot over it and apply the iron + more solder to the assembly. It just comes off in small balls. Any hints ?

A: Most likely, not enough heat.  Both the terminal and the wire need to be heated to the melting point of solder for the solder to flow properly.  But that spring terminal is acting as a very effective heat sink.
The only real answer is a more powerful soldering iron, or an alternative method of making the joint, such as spot welding.

A: The electrical contact seems to be a nickel-plated spring, in which case normal electrical solder (tin/silver or tin/lead) will adhere, but some
electrical solder fluxes (rosin, RMA) may not work.   If you can
find an acid flux (normal for steel, stainless steel, or nickel
alloys), use that to prepare the surface.   After soldering to the
nickel, rinse excess flux off, then you can solder to that tinned
surface using electrical solder and flux.
Alpha Metals 51022 flux is one suitable product for this task.
Either acid flux and solder, or welding, are suitable for connecting
wire to nickel, but 'electrical solder' with rosin flux is not.


text:
Q: Where do I find refined classes? I'm somewhat new to TeX I have made a few documents using the article class in LaTeX but I don't have any other experience. I was reading through the TeX FAQ when I found this entry: http://www.texfaq.org/FAQ-clsvpkg.
When I searched in CTAN I didn't get any results for refined classes.
Where exactly am I supposed to look for refined classes?

A: I got my own answer from here: What are the available "documentclass" types and their uses?.
I've decided to use the KOMA script bundle


text:
Q: In a text that part of the characters are in Hebrew, how to delete spaces before and after a comma using regex? I need to remove the spaces that are before and after the commas in a csv file that contains Hebrew characters. The solution to this problem would be quite simple when the csv file contains only English characters using sed and regex. But in my case, I can't get the desired result because of the Hebrew characters.
example of a line in the csv file:
file1, file2, קובץ 3, קובץ 4, קובץ 5, סוף
this command works only when all characters are in english: sed 's/(\s+,)?(,\s+)?/,/' -i file_path

A: You may use
sed 's/[[:space:]]*,[[:space:]]*/,/g' file > otufile
sed -i 's/\s*,\s*/,/g' file

See online demo
Details

*

*[[:space:]]*,[[:space:]]* - any 0 or more whitespace, comma,  any 0 or more whitespace

*g - global flag, matches and replaces all occurrences in the string.


text:
Q: make sure + subjunctive I'm wondering if "make sure" can take the subjunctive mood of a verb. Take this sentence for example:

Loki would be disappointed in me if I did not make sure this was the
  true casket.

What if I said:

Loki would be disappointed in me if I did not make sure this were the
  true casket.

There surely is a feeling of uncertainty, it could, hypothetically, not be the real casket, that's why he has to "make sure", although I'll be the first one to admit it sounds weird, but most constructions with the subjunctive sound weird.

A: No: if you are to use what may conveniently be called the subjunctive, it comes in the if clause.

Loki would be disappointed in me if I were to lose it.

The make sure this was the true casket should be indicative.

A: Forget the subjunctive (most native speakers of British English already have). Where is the difference between these two sentences?

Loki would be disappointed in me if I did not make sure these were the
  true caskets.
Loki would be disappointed in me if I did not make sure these were the
  true caskets.

Exactly.

A: I believe there are two kinds of subjunctives, the first one concerns hypothetical situation (past tense and would), the second concerns subjectivity, kind of subjective judgement with uncertainty ((should) be, except for the verb "wish"). In the case of "make sure", the latter usage is supposed to apply, as "make sure" involves an effort stemming from a subjective judgement that doing something is necessary or important even if it is not sure that the result can be achieved. By using subjuctive, the utterer concedes that "make sure" is a subjective effort and that the result is not always within control.
However, the "(should) be" usage has fallen into complete obsolescence in the case of "make sure". And in the clause following "make sure", it is established practice to use indicative. Therefore I'd say "Loki would be disappointed in me if I did not make sure this was the true casket".


text:
Q: How to express pattern matching for independent combinations of data values? data Foo = Bar1
         | Bar2 Foo Foo
         | Bar3 Foo
         | Bar4 Foo Foo Foo

Now, assume someone built a Foo tree and I want to check if the arguments of a Foo value are valid. The rules on the constructor arguments are:

*

*Bar2 Bar1 Foo

*Bar3 (Bar2|Bar3|Bar4)

*Bar4 Bar1 Bar1 (Bar1|Bar4)
I know the constructor of the value and only want to check the immediate arguments, nothing recursive. Like this:
bar2 Bar1 Bar1      = True
bar2 Bar1 (Bar2 {}) = True
bar2 Bar1 (Bar3 _)  = True
bar2 Bar1 (Bar4 {}) = True
bar2 _ _ = False

And e.g. similarly for Bar4:
bar4 Bar1 Bar1 Bar1      = True
bar4 Bar1 Bar1 (Bar4 {}) = True
bar4 _ _ _ = False

How can I express these conditions most concisely? Listing all combinations is in some cases a bit too much. And to my knowledge an "OR"-syntax for pattern matching doesn't exist.
UPDATE
I adapted Daniel's solution and have come to this:
data Foo = Bar1
         | Bar2 Foo Foo
         | Bar3 Foo
         | Bar4 Foo Foo Foo
         deriving (Data, Typeable)

bar2 a b = a `isOf` [Bar1] && b `isOf` [Bar1,Bar2{},Bar3{},Bar4{}]
bar4 a b c = [a,b] `areOf` [Bar1] && c `isOf` [Bar1,Bar4{}]

isOf l r = toConstr l `elem` map toConstr r
areOf l r = all (`isOf` r) l

What I like about this is that I don't have to change my data type, except adding the deriving clause, and that it's readable. The disadvantage of course is that these are dynamic checks. In my case this is fine though as it's just for assert-like checks to discover programming errors.

A: I think the only way how to check that on the type system level is splitting it into several data types. Something like:
data Foo = Foo1 Bar1 | Foo2 Bar2 | Foo3 Bar3 | Foo4 Bar4
data Bar1 = Bar1
data Bar2 = Bar2a Bar1 Foo
data Bar3 = Bar3a Bar2 | Bar3b Bar3 | Bar3c Bar4
data Bar4 = Bar4a Bar1 Bar1 Bar1 | Bar4b Bar1 Bar1 Bar4

You cannot say you want to limit some type variable to certain constructors, so you need to create a new data type for that.
The drawback is that you'll have much more constructors/patterns to type, but that can be solved at least partially by having a few helper functions.

Edit: Perhaps another solution would be to use a phantom type for tagging the constructors using GADTs:
{-# LANGUAGE GADTs #-}

data FBar1
data FBar2
data FBar3
data FBar4

data Foo a where
    Bar1 :: Foo FBar1
    Bar2 :: Foo FBar1 -> Foo b -> Foo FBar2
    Bar3a :: Foo FBar2 -> Foo FBar3
    Bar3b :: Foo FBar3 -> Foo FBar3
    Bar3c :: Foo FBar4 -> Foo FBar3
    Bar4a :: Foo FBar1 -> Foo FBar1 -> Foo FBar4
    Bar4b :: Foo FBar1 -> Foo FBar4 -> Foo FBar4

I'm not sure if this solution wouldn't create more problems than it solves. For example it's not possible to write a function like this:
construct :: Int -> FooAny X
construct 0 = Bar1
construct 1 = Bar2 Bar1 Bar1

since X would have to be both FBar1 and FBar2. You'd need existentials for that, for example to wrap it as
data FooAny where
    FooAny :: Foo a -> FooAny

construct :: Int -> FooAny
construct 0 = FooAny $ Bar1
construct 1 = FooAny $ Bar2 Bar1 Bar1

A: There is a fine static-checking solution posted; here's a suggestion for a dynamic-checking solution. The key idea is to shy away from pattern-matching and use all the tools we have for writing compact code instead. There's a couple choices for doing this; I'll discuss two. The first is to write isBarX functions for each constructor:
isBar1 (Bar1 {}) = True
isBar1 _ = False

-- ...

isBar4 (Bar4 {}) = True
isBar4 _ = False

valid (Bar1)       = True
valid (Bar2 a b)   = isBar1 a
valid (Bar3 a)     = not (isBar1 a)
valid (Bar4 a b c) = isBar1 a && isBar1 b && (isBar1 c || isBar4 c)

Another option is to write a function that returns some data telling which constructor was used -- say, a custom type like data Constructor = CBar1 | CBar2 | CBar3 | CBar4, or, as I'll do below, something a little hackier, like Int.
constr (Bar1 {}) = 1
constr (Bar2 {}) = 2
constr (Bar3 {}) = 3
constr (Bar4 {}) = 4

valid (Bar1)       = True
valid (Bar2 a b)   = constr a == 1
valid (Bar3 a)     = constr a /= 1
valid (Bar4 a b c) = constr a == 1 && constr b == 1 && constr c `elem` [1,4]


text:
Q: Why is this line of regex capturing white spaces? I'm using the following line of regex which I found from this SO answer:

(?:[\w[a-z]-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.-]+[.??][a-z]{2,4}/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))))+(?:(([^\s()<>]+|(([^\s()<>]+))))|[^\s`!()[]{};:'".,<>?«»""''])

I am testing it on the following string:

"Quattro Amici in Concert Mar. 3, 2014. Long-time collaborators Lun Jiang, violin; Roberta Zalkind, viola; Pegsoon Whang, cello; and Karlyn Bond, piano, will perform works by Franz Joseph Haydn, Wolfgang Amadeus Mozart, Ludwig van Beethoven and Gabriel Faure. To purchase tickets visit westminstercollege.edu/culturalevents or call 801-832-2457. - See more at: http://entertainment.sltrib.com/events/view/quattro_amici_in_concert#sthash.QRsLXXiA.dpuf"

I'm simply attempting to extract urls from strings and based on a bunch of SO answers, I've found that regex is the recommended tool for that job.  I'm not a regex expert (or even intermediate in my understanding), so I'm baffled by the empty strings my re.findall() keeps returning.  I've stepped through the regex line using regex buddy and still no luck.  Any help would be hugely appreciated.

A: I'm not sure that a big regex like that is entirely necessary - if you're just looking to get links, you could use a much simpler regex, like this:
/(https?:\/\/[\w\d\$-_\.\+!\*'\(\),\/#]+)/ig

According to RFC 1738, urls are only allowed to use the characters specified in the class above, so it should cover any valid url, without such a gigantic mess of a regex.
You can also use a tool like regexpal.com to validate regexes, which helps find issues. That said, I pasted your regex in there and it crashed chrome, so it may not be a great help for a beast like that :)


text:
Q: What really is "A fixed size hard disk" in virtualbox? When you create a virtual machine with VirtualBox, you are greeted with two options while creating the virtual disk:

*

*Dynamically allocated

*Fixed size

The dynamically allocated just creates a sparse file that grows when the requirements expand.
But the fixed size creates a file that consumes the allocated disk space.
Creating both dynamically allocated and fixed-sized partitions will not take a long amount of time.
What kind of file does the fixed size create? Is it gets written to the disk and increases the total terabytes written SMART count? Can I create such a file that consumes a huge space but takes no time to get created?
Edit:
I noticed that a newly created very small disk worth 194M has 5 lines of binary data.
I also created a 12G file, which also is mostly empty. But it takes no time to create the 12G file.

A: File data is stored in blocks on the hard drive. Information on which blocks make up a file is stored in meta data about the file.  This is what we call a file system.
So to create a 1TB file, the OS only needs to allocate 1TB of worth of blocks.  This makes those blocks unavailable to any other file.  But the OS does not need to write 1TB unless it is actually given 1TB of data to write.  You can see this behaviour with the truncate command.

To extend a file this way, you can either do this at the command line with truncate or programmatically with truncate()