text:
Q: How to log user input to use in a later embed with discordjs I am making a commission bot so people open a ticket and then choose what category it is for but then I want it to ask for a budget wait for a response then store that input budget to be used in an embed to post to freelancers.
I've already tried storing as a constant and then calling it later but it doesn't want to work as I'm storing it in a different function.
msg.channel.awaitMessages(filter, { time: 60000, maxMatches: 1, errors: ['time'] })
        .then(messages => {
            msg.channel.send(`You've entered: ${messages.first().content}`);
            const budget = messages.first().content;
        })
        .catch(() => {
            msg.channel.send('You did not enter any input!');
        });
});

    if (messageReaction.emoji.name === reactions.one) {

        let web = new Discord.RichEmbed()
        .setDescription("Press the check to claim the comission")
        .setColor("#15f153")
        .addField("Client", `${message.author} with ID: ${message.author.id}`)
        .addField("Budget", `${budget}`)
        .addField("Time", message.createdAt)
        .addField("Requested Freelancer",`<@&603466765594525716>`)

        let tickets = message.guild.channels.find('name', "tickets")
        if(!tickets) return message.channel.send(`${message.author} Can't find tickets channel.`)

I want it to post the budget in the .addField budget section but instead, it just says the budget is not defined

A: You are defining the const budget in a scope different than the global scope (see this page for scope).
This answer explains how the declaration, variable and scope work together.
Here, you're making budget available only in the awaitMessages.then scope, ie
.then(messages => {
  msg.channel.send(`You've entered: ${messages.first().content}`);
  const budget = messages.first().content;
  // the const is only know there
})

However, the then block will return a value. Because there isn't anymore chained promise (except if there's an error because it will trigger the chained catch).
Learn more on promise here.
What will be useful is, once the promise is resolved, msg.channel.awaitMessages will return a value.
You can then do 2 things:

*

*await the response of msg.channel.awaitMessages, assign it to a variable and use it later

*chain another promise

awaiting:
let budget = await msg.channel.awaitMessages(filter, { time: 60000, maxMatches: 1, errors: ['time'] })
  .then(messages => {
    msg.channel.send(`You've entered: ${messages.first().content}`);
    return messages.first().content;
  })
  .catch(() => {
    msg.channel.send('You did not enter any input!');
  });
});

if (messageReaction.emoji.name === reactions.one) {
  let web = new Discord.RichEmbed()
    .setDescription("Press the check to claim the comission")
    .setColor("#15f153")
    .addField("Client", `${message.author} with ID: ${message.author.id}`)
    .addField("Budget", `${budget}`)
    .addField("Time", message.createdAt)
    .addField("Requested Freelancer",`<@&603466765594525716>`)
 let tickets = message.guild.channels.find('name', "tickets")
 if(!tickets) return message.channel.send(`${message.author} Can't find tickets channel.`)
// ...
}

chaining:
msg.channel.awaitMessages(filter, { time: 60000, maxMatches: 1, errors: ['time'] })
  .then(messages => {
    msg.channel.send(`You've entered: ${messages.first().content}`);
    return messages.first().content;
  })
  .then((budget) => {
    if (messageReaction.emoji.name === reactions.one) {
      let web = new Discord.RichEmbed()
        .setDescription("Press the check to claim the comission")
        .setColor("#15f153")
        .addField("Client", `${message.author} with ID: ${message.author.id}`)
        .addField("Budget", `${budget}`)
        .addField("Time", message.createdAt)
        .addField("Requested Freelancer",`<@&603466765594525716>`)
      let tickets = message.guild.channels.find('name', "tickets")
      if(!tickets) return message.channel.send(`${message.author} Can't find tickets channel.`)
      // ...
    }
  })
  .catch(() => {
    msg.channel.send('You did not enter any input!');
  });

A: let response = await  msg.channel.awaitMessages(filter, { time: 60000, maxMatches: 1, errors: ['time'] })
        .then(messages => {
            msg.channel.send(`You've entered: ${messages.first().content}`);
        })
        .catch(() => {
            msg.channel.send('You did not enter any input!');
        });
});

 if (messageReaction.emoji.name === reactions.one) {

        let web = new Discord.RichEmbed()
        .setDescription("Press the check to claim the comission")
        .setColor("#15f153")
        .addField("Client", `${message.author} with ID: ${message.author.id}`)
        .addField("Budget", `${response.first().content}`)
        .addField("Time", message.createdAt)
        .addField("Requested Freelancer",`<@&603466765594525716>`)

        let tickets = message.guild.channels.find('name', "tickets")
        if(!tickets) return message.channel.send(`${message.author} Can't find tickets channel.`)

Maybe it will fix the problem, because you can't access that block where the const budget is located.


text:
Q: How can I delete a particular row from the table in a SQLquery How can I delete a particular row from the table in a SQLquery. I used primary key and Foreign key in this table. I am using Oracle 11G.

A: its very simple,
may be you need some reference:
http://psoug.org/reference/delete.html
DELETE FROM table_name
WHERE columnname= 'value';

A: you asking to delete column Right?
     update employee set city_name = '' where empid = '12'
Try this...
This will make the column to NULL

A: Consider this example

You are having a table named cars
       columns are car_id, car_model, car_colour

car_id           car_model         car_colour
 234              hyundai           red
 345              Nano              white
 565              Maruthi           black
 888              BMW               brown
 895              Audi              Blue
 234              hyundai           red_blue
 345              Nano              white_yellow
 565              Maruthi           black_shade
 888              BMW               brown_king
 895              Audi              Blue_red

now here you want to delete the brown_king colour row, then you want to type the below query

delete from table_name where column_name = 'condition'
delete from cars where car_colour ='brown_king'

This will delete that particular row in this table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stanford NLP Precision & Recall Calculation in CRFClassifier I am trying to reconcile the Precision & Recall scores output by the Stanford CRFClassifier with the results I get by manually assessing the stdout output.
I note from this answer that the results are calculated on an all-or-nothing basis for entities with no partial credit given for correct labels within an incorrectly labelled entity. However, when I try to calculate an all-or-nothing score from the output on this basis, my result is still reasonably different to the score output by the CRFClassifier.
When I calculate an all-or-nothing score from the output I get 0.6870 precision and 0.4520 recall. This is in contrast to average scores over 4 folds of 0.6090 precision and 0.3987 recall returned by the Classifier.
To manually calculate entity scores, I take the stdout output from the Classifier and iterate through each word. To get the number of relevant entities, I take any sequence of words with the same correct label and call that an entity. I check the returned label for each of these words and if any of them are a mismatch then the entity is marked as incorrectly labelled.
To get the number of returned entitites I iterate through the words and similarly group up sequences that have the same returned labels. This gives me the total number of relevant entities, the number of correctly labelled entities and the total number of returned entities, and I use these to calculate precision and recall on an entity basis.
Comparing the total number of entities in the .ann files (2,169) and the total number of relevant entities calculated above (2,146) suggests that this way of counting entities is reasonably accurate.
The problem is getting the precision and recall scores this way gives results that are not very close to what the Classifier returns. I am not considering Other labels in the calculation. Is there any other factors I should be considering when calculating the scores? Is there a way to have the Classifier output what it considers as entities to compare with what I have?


text:
Q: OCAML : Converting a List (Int*Float) to a Float List What i wanna do is to convert a list like [1,3.0,5,5.5,8] to [1.0,3.0,5.0,5.5,8.0].
The problem is I don't know the list, and so I can't use float_of_int, because it wont work for elements that are already floats.

A: Your title says (in essence) (int * float) list. However your example lists (correcting for OCaml syntax) are impossible. There is no list in OCaml that contains some floats and some ints. All elements of a list must be the same type.
If you really have (int * float) list, they look like this:
[(1, 1.5); (2, 3.8); (3, 8.9)]

Every element is a pair with an int and a float. So it's easy to handle them all with the same code.


text:
Q: heroku Error: Cannot find module '/app/index.js' I am hosting a university project on heroku and i need to host a django app which also needs an npm library but i searched alot on how to do this and eventualy i thought i got the hand of it but now i am getting this error:
2018-06-14T10:19:22.798022+00:00 app[web.1]:     throw err;

2018-06-14T10:19:22.798023+00:00 app[web.1]:     ^

2018-06-14T10:19:22.798024+00:00 app[web.1]:

2018-06-14T10:19:22.798026+00:00 app[web.1]: Error: Cannot find module '/app/server.js'

2018-06-14T10:19:22.798028+00:00 app[web.1]:     at Function.Module._resolveFilename (module.js:547:15)

2018-06-14T10:19:22.798029+00:00 app[web.1]:     at Function.Module._load (module.js:474:25)

2018-06-14T10:19:22.798030+00:00 app[web.1]:     at Function.Module.runMain (module.js:693:10)

2018-06-14T10:19:22.798031+00:00 app[web.1]:     at startup (bootstrap_node.js:191:16)

2018-06-14T10:19:22.798033+00:00 app[web.1]:     at bootstrap_node.js:612:3

this is my package.json:
{
  "name": "dpl-webtech",
  "version": "1.0.0",
  "description": "DBL - Webtech Group D24",
  "main": "index.js",
  "scripts": {
    "start": "nf start"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/spiderangel123/DPL-WebTech.git"
  },
  "author": "Ahmad Alsarakbi",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/spiderangel123/DPL-WebTech/issues"
  },
  "homepage": "https://github.com/spiderangel123/DPL-WebTech#readme",
  "engines": {
    "node": "8.11.2",
    "npm": "6.1.0"
  },
  "dependencies": {
    "npm": "^6.1.0",
    "phantomjs-prebuilt": "^2.1.16"
  }
}[![enter image description here][1]][1]

and here is my procfile:
web: gunicorn DBL.wsgi
web: node ./index.js

g

A: I had the same issue recently, although the build was successful.
The problem does not come from your project repositories structure where an app folder would be missing.
Heroku apps include a Procfile that specifies the commands that are executed by the app's dynos. When you load your app, Heroku will start a web process type.
My guess is you don't have a Procfile, and you don't have a web process defined.
The easiest way to do is to add a Procfile at the root of your project. The Procfile has no extension to its name. Inside of it, you add a web process with the following structure : <process type>: <command>
For a NodeJS app, you can typically have the following instruction :
web: node dist/server/index.js

You only need to customize it to your app.

A: Can you please share the file structure.
This error occurs when the file path to the server.js is not correct, So check once if the file path that heroku is taking is correct or not.

A: I was getting this error, in my case, it was because my server starter file was index.ts and not index.js as I'm using typescript.

A: You don't need to include web: node index.js if you just need to include packages but it was mentioned to add it to Procfile everywhere i read about how to use npm with heroku so i had the misconception that it wont work unless i add it.


text:
Q: Dynamically update FormBuilder group inputs When FormGroup instance is created it creates a FormGroup object that has controls and values.
I have one form that has different controls, they activate depending on what type of form was chosen.
The problem is that formGroup instance stays same, so my controls are not read, and I am getting an error that controls are not found.

I will include task.component.ts file where i update a task and read values into input fields:
upateTaskForm(taskBody, taskType) {
    this.formActive = true;
    if (this.task === 'medication') {
      console.log(this.formGroup + "MEDICATION FORMGROUP");
      this.formGroup = this.formBuilder.group({
        title: taskBody.title,
        instructions: taskBody.instructions,
        repeatWeekDay: [null],
        medication: this.formBuilder.group({
          name: taskBody.medication[0].name,
          dose: this.formBuilder.group({
            quantity: taskBody.medication[0].quantity,
            unit: taskBody.medication[0].dose.unit
          }),
          method: taskBody.medication[0].method,
          notes: taskBody.medication[0].notes
        })
      });
      // Reading Form populates from the formbuilder
    } if (this.task === 'reading') {
      console.log(this.formGroup + "READING FORMGROUP");
      this.formBuilder.group({
        title: taskBody.title,
        reading: this.formBuilder.group({
          measureType: taskBody.reading[0].measureType,
          measureValue: taskBody.reading[0].measureValue,
          measureUnits: taskBody.reading[0].measureUnits,
        }),
        instructions: taskBody.instructions,
      });
    } else if (this.task === 'symptoms') {
      this.formGroup = this.formBuilder.group({
        title: [null, Validators.required],
        instructions: [null]
      });
    }
  }

This is HTML code for the task.component.html
formGroup is an instance of the form and, once its submited values are stored in formGroup.value
formGroup is

                  Copy from library

                    Search Tasks in Library

                  Name

                  Event

                       Medication

                  <input type="radio" class="form-check-input" (click)="setTask('reading')" name="event" [checked]='task==="reading"' value="measurement"> Measurement

                  <input type="radio" class="form-check-input" (click)="setTask('record-symptoms')" name="event" [checked]='task==="symptoms"'
                    value="symptoms"> Record Syptoms

                Dose
                <input type="number" name="number" class="form-contol col-md-6 mr-4" placeholder="Quantity" formControlName="quantity">
                <select class="col" formControlName="unit">
                  <option default>Tablet(s)</option>
                  <option>Pill</option>
                  <option>Liquid</option>
                </select>

                <input type="text" class="form-contol col-md-6 mr-4" placeholder="Unit / eg Melformin 500mg" formControlName="name">
                <select class="col" formControlName="method">
                  <option default>Oral</option>
                  <option>IV</option>
                  <option>Tropical</option>
                  <option>ophthalmic</option>
                </select>

                Notes
                <input type="text" name="notes" class="form-control col-md-9 ml-auto" placeholder="Take before bed, take before eating" formControlName="notes">

                Measurement Type
                <input type="text" class="form-contol col" placeholder="Heart_rate, Systolic, Diastolic, Weight" formControlName="measureType">

                Measurement Value
                <input type="number" class="form-contol col-md-6 mr-4" placeholder="Value of the measurement" formControlName="measureValue">
                <select class="col" formControlName="measureUnits">
                  <option default>KG</option>
                  <option>LBS</option>
                  <option>mmHg</option>
                  <option>MG/DL</option>
                  <option>MMOL</option>
                  <option>STEPS</option>
                </select>

              Instructions
              <input class="form-control col-md-9 ml-auto" type="text" formControlName="instructions" placeholder="Anything to say to the patient">

              <button class="d-none d-md-block btn btn-secondary btn-sm btn-md-lg mr-auto ml-md-4" data-dismiss="modal">CANCEL</button>
              <button class="d-md-none btn btn-secondary btn-sm btn-md-lg mr-auto ml-md-4" data-dismiss="modal">×</button>
              <button type="submit" class="d-none d-md-block btn btn-primary btn-sm btn-md-lg mr-md-4">CREATE TASK</button>
              <button class="d-md-none btn btn-primary btn-sm btn-md-lg mr-md-4">OK</button>

          </form>

enter image description here

A: You only need to use the FormBuilder class once, to get an instance of FormGroup. After that, if you need to dynamically add or remove FormControls, you can use the addControl and removeControl methods.


text:
Q: Get Access Token from Facebook PHP SDK is not working properly I'm trying to retrieve an Access Token from Facebook using PHP SDK 3.2.2, being the code below what I placed in the redirect url after a sucessfull user login in Facebook. My problem is that $this->facebook->getAccessToken() is not giving back the user access token after the user gives access to the APP, just a string with the form: 'AppId|AppSecret', and I have to include code to manually get the User Access Token. This work, but I don't know WHY when I use getAccessToken is not giving back the right Token. I would also like to know how if there is any better way to retrieve User Access Token than with $code, because I don't feel this is a good way of doing it.
NOTE: I use $this->facebook because I load it as a Codeigniter library.
  $access_token  = $this->facebook->getAccessToken();

  //-------------------------------------------------------------------------
  //echo '
Access Token: ' . $access_token;
  // Generare Token if not created:
  $code = $_REQUEST["code"];

  if ( isset($code) ) {
     //echo '
Code Enviado: ' . $code;
     //exit();
     $appId     = $this->facebook->getAppId();
     $appSecret = $this->facebook->getAppSecret();

     $redirectTo = base_url('asociar/acc_facebook/step2/');

     $token_url="https://graph.facebook.com/oauth/access_token?client_id="
        . $appId . "&redirect_uri=" . urlencode($redirectTo)
        . "&client_secret=" . $appSecret
        . "&code=" . $code . "&display=popup";
     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);
     $access_token = $params['access_token'];

     //echo '
Repitiendo el Token';

     $this->facebook->setAccessToken($access_token);
     //echo '
Second Access Token Fijado: ' . $access_token;
  }
  //-----------------------------------------------------------------------

UPDATE:
This issue is due to I used CI with PHP SDK (check my own answer for that), but the answer is valid to anyone that have this issue with Facebook PHP SDK (Check @Imbru answer)

A: @Imbru pointed me in the solution, if any credit, give it to him.
Take this into account: when using Codeigniter, it saves all the session data in the cookie and send it to the browser, not storing it in the server. Yes, they do it, and it leads to many other problems (as losing of session when you store a lot of data, and the browser only sends you back part of them, but that is another history).
With CI, the solution is overwrite the session core class, with another session class which manages the session with PHP $_SESSION, as for example, https://bitbucket.org/xperez/core-session-storage-for-codeigniter (I use it in my projects, and work like a charm). In that way, when using PHP-sdk you'll save the values in the session, and when Facebook class will try to retrieve them back, it'll be able of doing it.
And of course, if you're having issues with the Facebook PHP SDK, check if $_SESSION is storing the values you want, as the problem is you don't have the value in the server when you want to retrieve it, leading you to an error of not authentication.

A: The response is little late, but may be it will help for other users.
I have got the same issue today.
My access_token was not correctly store in $_SESSION. Apparently, client side send juste one time the access_token. You have to store it in memory (SESSION) and reused it.
In normal time, Facebook PHP SDK do it...
EDIT : See @Chococroc response for more explanations


text:
Q: my Graphic User Interface (GUI) is unable to produce my results from my coordinator VIA Zigbee (Wireless Connection) Basically, I'm given a task to continue from the previous student. I have several sensors that will detect the Temperature, Humidity and Luminosity of the lab. These data from sensors will need to transmit to the Coordinator. I'm able to debug the program but unable to achieve the result as shown in GUI. The reading values are not able to transmit. Below is the code given by the previous student which they are able to achieve it.
What could be the problem?? I suspect that it could be the Serial Port Problem.
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Windows.Forms.DataGridView

Public Class frmGUI

Dim FromSerialPort
Dim dSet As New DataSet
Dim COORDINATOR0 = 0
Dim strData(0 To 1)
Dim data As String
Dim count As Integer = 0
Dim number As Integer
Dim data2 As String
Dim x As Integer = 0

Dim txt1 As Integer = 0
Dim txt2 As Integer = 0
Dim txt3 As Integer = 0
Dim txt4 As Integer = 0

Dim hour As String = 0
Dim min As String = 0
Dim sec As String = 0
Dim hour2 As String = 0
Dim min2 As String = 0
Dim sec2 As String = 0

Dim LumVal1 As Integer

Delegate Sub SetTextCallback(ByVal [text] As String)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    If SerialPort1.IsOpen Then
        SerialPort1.Close()
    End If

    System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\Welcome.vbs")

    strData(0) = "ZED02"

    TSSL1.Text = Format(Now, "Short Date")
    TSSL2.Text = "Welcome"
    TSSL3.Text = Format(Now, "Long Time")

    PictureBox1.Image = System.Drawing.Bitmap.FromFile( _
  My.Application.Info.DirectoryPath & "\Capture.PNG")

    txtCOM.Focus()

End Sub

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click

    Dim intResponse As Integer
    intResponse = MsgBox(" Are u sure u want to QUIT ??!!", vbYesNo + vbExclamation, "Quit")
    If intResponse = vbYes Then
        End

    End If

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles myTimer.Tick

    TSSL3.Text = Format(Now, "Long Time")

End Sub

Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles myTimer.Tick

    If count = 1 Then
        sec = sec + 1
        If sec = 10 Then
            sec = 0
            sec2 = sec2 + 1
            If sec2 = 6 Then
                sec2 = 0
                min = min + 1
                If min = 10 Then
                    min = 0
                    min2 = min2 + 1
                    If min2 = 6 Then
                        min2 = 0
                        hour = hour + 1
                        If hour = 10 Then
                            hour = 0
                            hour2 = 1
                            If hour = 4 And hour2 = 2 Then
                                hour = 0
                                hour2 = 0
                            End If
                        End If
                    End If
                End If
            End If
        End If
        TSSL2.Text = ("Connected : " + hour2 + hour + ":" + min2 + min + ":" + sec2 + sec)
    End If

End Sub

Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click

    If txtCOM.Text = "" Then
        'MsgBox("Please enter a COM port value", vbOKOnly & vbExclamation, "Error")
        txtCOM.Text = "34"
    Else
        count = count + 1

    End If
    If (count = 1) Then

        System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\Connected.vbs")

        txtCOM.Enabled = False

        If SerialPort1.IsOpen Then
            SerialPort1.Close()
        End If

        SerialPort1.PortName = "COM" & txtCOM.Text ' for the coordinator
        SerialPort1.BaudRate = 38400
        SerialPort1.Parity = System.IO.Ports.Parity.None
        SerialPort1.DataBits = 8
        SerialPort1.StopBits = System.IO.Ports.StopBits.One
        SerialPort1.RtsEnable = True
        SerialPort1.Open()

        hour = 0
        min = 0
        sec = 0

        hour2 = 0
        min2 = 0
        sec2 = 0

        lbl1.Text = " Reading Data . . ."
        TextBox5.Text &= "Connected at: " + Format(Now, "Short Time") + vbNewLine + vbNewLine
        btnConnect.Text = "Disconnect"
    End If

    If count = 2 Then

        System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\Disconnected.vbs")

        txtCOM.Enabled = True

        count = 0

        btnConnect.Text = " Connect "
        SerialPort1.Close()             'Close our Serial Port

        lbl1.Text = " Not Connected "
        TSSL2.Text = "Disconnected"

        TextBox5.Text &= "Disconnected at: " + Format(Now, "Short Time") + vbNewLine + vbNewLine

    End If

End Sub

Private Sub ReceivedText(ByVal [text] As String)

    If Me.TextBox5.InvokeRequired Then
        Dim x As New SetTextCallback(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})
    Else

        data &= [text]

        If InStr(data, "Data not received") Then
            data = ""
            TextBox5.Text = "Data lost" + vbNewLine
        End If

        If InStr(data, "Lab Location: S.429") Then
            If InStr(data, "TemperatureValue:") Then
                If InStr(data, "Humidityvalue:") Then
                    If InStr(data, "LuminosityValue:") Then
                        txt1 = 1

                        txt2 = 0
                        txt3 = 0
                        txt4 = 0

                        data2 = data
                    End If
                End If
            End If
        End If

        If InStr(data, "Lab Location: S.434") Then
            If InStr(data, "Temperaturevalue:") Then
                If InStr(data, "HumidityValue:") Then
                    If InStr(data, "LuminosityValue:") Then
                        txt2 = 1

                        txt1 = 0
                        txt3 = 0
                        txt4 = 0

                        data2 = data
                    End If
                End If
            End If
        End If

        If InStr(data, "Lab Location: S.439") Then
            If InStr(data, "TemperatureValue:") Then
                If InStr(data, "HumidityValue:") Then
                    If InStr(data, "LuminosityValue:") Then
                        txt3 = 1

                        txt1 = 0
                        txt2 = 0
                        txt4 = 0

                        data2 = data
                    End If
                End If
            End If
        End If

        If InStr(data, "Lab Location: S.449") Then
            If InStr(data, "TemperatureValue:") Then
                If InStr(data, "HumidityValue:") Then
                    If InStr(data, "LuminosityValue:") Then
                        txt4 = 1

                        txt1 = 0
                        txt2 = 0
                        txt3 = 0

                        data2 = data
                    End If
                End If
            End If
        End If

        If txt1 = 1 Then
            TextBox1.Text &= data2
            TextBox5.Text &= "Data received from S.429 at: " + Format(Now, "Short Time") + vbNewLine + vbNewLine
            System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\data429.vbs")
            txt1 = txt1 + 1

            If txt1 = 2 Then
                txt1 = 0
                data = ""
            End If
        End If

        If txt2 = 1 Then
            TextBox2.Text &= data2
            TextBox5.Text &= "Data received from S.434 at: " + Format(Now, "Short Time") + vbNewLine + vbNewLine
            System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\data434.vbs")
            txt2 = txt2 + 1

            If txt2 = 2 Then
                txt2 = 0
                data = ""
            End If
        End If

        If txt3 = 1 Then
            TextBox3.Text &= data2
            TextBox5.Text &= "Data received from S.439 at: " + Format(Now, "Short Time") + vbNewLine + vbNewLine
            System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\data439.vbs")
            txt3 = txt3 + 1

            If txt3 = 2 Then
                txt3 = 0
                data = ""
            End If
        End If

        If txt4 = 1 Then
            TextBox4.Text &= data2
            TextBox5.Text &= "Data received from S.449 at: " + Format(Now, "Short Time") + vbNewLine + vbNewLine
            System.Diagnostics.Process.Start(My.Application.Info.DirectoryPath & "\data449.vbs")
            txt4 = txt4 + 1

            If txt4 = 2 Then
                txt4 = 0
                data = ""
            End If
        End If

    End If

End Sub

Private Sub TextBox1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox1.Clear()
End Sub

Private Sub TextBox2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox2.Clear()
End Sub

Private Sub TextBox3ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox3.Clear()
End Sub

Private Sub TextBox4ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox4.Clear()
End Sub

Private Sub TextBox5ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox5.Clear()
End Sub

Private Sub AllToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    TextBox1.Clear()
    TextBox2.Clear()
    TextBox3.Clear()
    TextBox4.Clear()
    TextBox5.Clear()
End Sub

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    TextBox1.Select(TextBox1.Text.Length, 0)
    TextBox1.ScrollToCaret()
End Sub

Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
    TextBox2.Select(TextBox2.Text.Length, 0)
    TextBox2.ScrollToCaret()
End Sub

Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
    TextBox3.Select(TextBox3.Text.Length, 0)
    TextBox3.ScrollToCaret()
End Sub

Private Sub TextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox4.TextChanged
    TextBox4.Select(TextBox4.Text.Length, 0)
    TextBox4.ScrollToCaret()
End Sub

Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged
    TextBox5.Select(TextBox5.Text.Length, 0)
    TextBox5.ScrollToCaret()
End Sub

Private Sub S429ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles S429ToolStripMenuItem.Click
    TextBox1.Clear()
End Sub

Private Sub SToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SToolStripMenuItem.Click
    TextBox2.Clear()
End Sub

Private Sub S439ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles S439ToolStripMenuItem.Click
    TextBox3.Clear()
End Sub

Private Sub S449ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles S449ToolStripMenuItem.Click
    TextBox4.Clear()
End Sub

Private Sub BackLogToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BackLogToolStripMenuItem.Click
    TextBox5.Clear()
End Sub

Private Sub AllToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AllToolStripMenuItem1.Click
    TextBox1.Clear()
    TextBox2.Clear()
    TextBox3.Clear()
    TextBox4.Clear()
    TextBox5.Clear()
End Sub

Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
    MsgBox(" NYP SMART LAB " + vbNewLine + " By: Daniel and Mikaris ", vbQuestion, " About ")
End Sub

Private Sub HowToReadValuesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HowToReadValuesToolStripMenuItem.Click
    MsgBox("Temperature value < 26*C = Aircon is on" + vbNewLine + "Luminosity value > 1 = Lights are on" + vbNewLine, vbQuestion, "How to read values")
End Sub
End Class


text:
Q: Why do I get an exception when I pass a std::string to printf? #include<iostream>
#include<string.h>
#include<stdio.h>

using namespace std;

int main()
{
    char a[10] = "asd asd";
    char b[10] ="bsd bsd";
    string str(a);
    str.append(b);
    printf("\n--------%s--------\n", str);
    return 0;
}

I can't understand why this produces an exception? This program mainly tries to append strings. I get the desired output when using std::cout but not when using printf.

A: Because std::string is not the same as char const *, which is what the %s format specifies.  You need to use the c_str() method to return the pointer expected by printf():
printf("\n--------%s--------\n", str.c_str());

To be more technical, printf() is a function imported from the C world and it expects a "C-style string" (a pointer to a sequence of characters terminated by a null character).  std::string::c_str() returns such a pointer so that C++ strings can be used with existing C functions.

A: c_str(). Have to use style string using this function..

A: printf() handles c strings (char *), you are using a c++-style string and therefore need to convert between them.
Simply use the c_str() method like so
printf("%s", str.c_str());

A: printfs %s format specifier is expecting a C style string not a std::string, so you need to use c_str() which return a const char*:
printf("\n--------%s--------\n", str.c_str());

Basically you have undefined behavior since printf will try to access your argument as if it was a pointer to a null terminated C style string. Although, since this is C++ you should just use std::cout is safer.


text:
Q: How can I clear my cache? I'm running a live CD linux distro and I'm getting out of memory exceptions.
>java -version
#Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x0000000646e00000, 264241152, 0) failed; error='Cannot allocate memory' (errno=12)
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 264241152 bytes for committing reserved memory.
# An error report file with more information is saved as:
# /tmp/hs_err_pid50274.log

I ran free -m  command and it shows ~250Mb of free RAM and 19Gb used for cache.
>free -m
            total       used       free     shared    buffers     cached
Mem:        24128      23827        301          0         15      18929
-/+ buffers/cache:      4881      19247
Swap:            0          0          0

Here is the memory dump:
---------------  S Y S T E M  ---------------

OS:RapidLinux 20151103

uname:Linux 3.18.22 #1 SMP Fri Oct 9 19:28:11 UTC 2015 x86_64
libc:glibc 2.21 NPTL 2.21
rlimit: STACK 8192k, CORE infinity, NPROC 96487, NOFILE 4096, AS infinity
load average:2.08 1.73 1.30

/proc/meminfo:
MemTotal:       24708040 kB
MemFree:          307572 kB
MemAvailable:     173696 kB
Buffers:           15612 kB
Cached:         19383916 kB
SwapCached:            0 kB
Active:          3784768 kB
Inactive:       19327244 kB
Active(anon):    3742084 kB
Inactive(anon): 19303520 kB
Active(file):      42684 kB
Inactive(file):    23724 kB
Unevictable:       15016 kB
Mlocked:           15016 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:                96 kB
Writeback:             0 kB
AnonPages:       3727472 kB
Mapped:            55972 kB
Shmem:          19327344 kB
Slab:             671580 kB
SReclaimable:     116376 kB
SUnreclaim:       555204 kB
KernelStack:       23664 kB
PageTables:        24588 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    12354020 kB
Committed_AS:   28666748 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      738156 kB
VmallocChunk:   34346400260 kB
HardwareCorrupted:     0 kB
AnonHugePages:         0 kB
DirectMap4k:       11748 kB
DirectMap2M:     2072576 kB
DirectMap1G:    23068672 kB

Memory: 4k page, physical 24708040k(307572k free), swap 0k(0k free)

I tried to clear the cache by running sync ; echo 3 | sudo tee /proc/sys/vm/drop_caches as a sanity check and surprise surprise the cache did not go down at all, but the command completed successfully.
There was a ton of old logs that I deleted (from the aufs / which should be in RAM), ran the command to clear the cache - still nothing.
The rest of the file system takes only ~9Gb. How can I force my cache to clear?

A: You have 19GB of RAM free for programs to use. There is no need to clear the disk cache: the system will reclaim it if it needs the memory for some other purpose such as running a program. The only thing you can do by clearing the disk cache is make your machine slower.
Disk space is irrelevant. Deleting files won't help you.
You have 19GB of RAM and the program claims to fail to allocate 26MB. Do the math: 26MB < 19GB. This is a bug in the program, either in the way it allocates memory or in the way it reports errors. Check /tmp/hs_err_pid50274.log to see if it holds more clues.

A: Shmem:          19327344 kB
You have 19GB in tmpfs, or some other shared memory object.
It's often tmpfs. Check df -h -t tmpfs.
System V shared memory can be shown by ipcs -m.
Some, but not all, other shared memory can be found by scanning /proc.  There is a small python script in my answer here: Can I see the amount of memory which is allocated as GEM buffers?
EDIT: in your case, you might have something holding open a deleted file.  This would mean the space usage would show up in df, but not in du.  It is possible to scan /proc/ for deleted files... I don't have such a handy script for this, but maybe you can do ls -lR /proc | less, and search for the string (deleted) using the / command of less.  It seems possible you would see your deleted log files were still being held open by some process.


text:
Q: Identical Geodesics implies scalar multiple of metric? Suppose $(M,g^1)$ and $(M,g^2)$ are two intrinsic metric spaces with the same underlying set $M$.
Assume that for every $p,q\in M$, for each geodesic $\gamma^1_{[p,q]}$ connecting $p$ to $q$ under $g^1$ there exist a geodesic and $\gamma^2_{[p,q]}$ connecting p and q and $g^2$ identical to it, and visa-versa.
Does this imply that $g^1$ is a multiple of $g^2$?

A: No. Consider as your model set $M$ a tripod. (A tripod is a graph with one vertex of degree three and three vertices of degree one attached to it.)
For your different length metrics, just assign the edges of the tripods various different lengths, and equip the space with the length metric induced by those edge lengths (making each edge into an isometric copy of $[0,L]$ where $L$ is its length.)
Any two such tripods have the same setwise geodesics, but need not have the same metrics, even up to scaling.

A: Your notation suggested another alternative:  Let $g^2 = (g^1)^2$ -- a local extremum of $g^1$ is also a local extremum of its square.  In fact, let $\phi$ be strictly increasing on $[ 0, \infty )$, then $g^2 = \phi(g^1)$ replicates the extrema of $g^1$.  So geodesics (paths whose length is first order stationary under perturbation, hence correspond to local extrema) are preserved under any such $\phi$.

A: While Anon's answer is correct, here is an example from Riemannian geometry. Start with $(M,g)$ equal to the projective plane with the standard metric of constant curvature, so that geodesics are projective lines. Let $f: M\to M$ be a generic projective transformation and $g'=f^*(g)$ be the pull-back of $g$. Then the two Riemannian manifolds $(M,g), (M,g')$ have exactly the same set of geodesics but are not even conformal to each other.


text:
Q: udev rules are not working after kernel downgrade from 4.4.0-83 to 4.4.0-75 We need the persistent network interface names, but after kernel downgrade from 4.4.0-83 to 4.4.0-75 udev rules are not working anymore.
udev rules like below for each interface are already present on the system.
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="02:01:02:03:04:05", ATTR{dev_id}=="0x0", ATTR{type}=="1", NAME="eth0

Also we tried giving the following steps
Changing Network Interfaces name Ubuntu 16.04


text:
Q: PreBuild for PreBuild Event Command in csproj Can I specify in csproj file that the exe being executed in prebuild events should be built before executing it?

A: You can do it through Visual Studio which will actually edit your .csproj file in fact.
Right click on the project and select Project Dependencies and select the project which you need to build before this project. Verify it by selecting the Build order tab.


text:
Q: Enunciate: In my wadl, why do all my resources path attributes get prefixed with "/rest"? The resource class is defined like this:
@Path("v1")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public class RestApi {

And I have a method defined like this:
@GET
@Path("patients")
public String patients(

When I run the maven command to run the enunciate doc goal, the generated wadl looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<wadl:application xmlns:wadl="http://wadl.dev.java.net/2009/02" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <wadl:doc xmlns:enunciate="http://enunciate.codehaus.org/" enunciate:generatedBy="Enunciate-1.27"/>
  <wadl:grammars>
    <wadl:include href="ns0.xsd"/>
  </wadl:grammars>
  <wadl:resources base="http://localhost:8888/app/api">
...
    <wadl:resource path="/rest/v1/patients">
      <wadl:method name="GET">

Where is this "/rest/" coming from in the resource path?  I've searched everywhere in my project and there's no reference to it.
Here's my enunciate.xml config file:
<enunciate label="Rest API"
           xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.28.xsd"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <deployment host="localhost:8888" context="/app/api"/>

</enunciate>

A: Apparently "/rest" is just a default value.  You can change it to nothing by adding this to your enunciate.xml file:
<services>
     <rest defaultRestSubcontext="/" />
</services>


text:
Q: Class 'QueryDocumentSnapshot' has no instance method '[]' I am new to flutter and developing a social media app. Every time I want to get data from firebase I got the error
QueryDocumentSnapshot has no instance method '[]'
Here's my code where I am getting the error
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/progress.dart';

final usersRef = FirebaseFirestore.instance.collection('users');

class Timeline extends StatefulWidget {
  @override
  _TimelineState createState() => _TimelineState();
}

class _TimelineState extends State<Timeline> {
  List<dynamic> users = [];

  @override
  void initState() {
    // TODO: implement initState
   getUsers();
    //getUserById();
    super.initState();
  }
  getUsers() async{
    final QuerySnapshot snapshot = await usersRef.get();
    setState(() {
      users = snapshot.docs;
    });
    /*snapshot.docs.forEach((DocumentSnapshot doc){
      print(doc.data());
      print(doc.id);
      print(doc.exists);
    });*/
  }
    /*usersRef.get().then((QuerySnapshot snapshot){
      snapshot.docs.forEach((DocumentSnapshot doc) {
        print(doc.data());
      });
    });
  }*/
  /*getUserById() async{
    final String id = "Hw75UQLfZPAZosI2O2Nu";
    final DocumentSnapshot doc = await usersRef.doc(id).get();
      print(doc.data());
      print(doc.id);
      print(doc.exists);
  }*/
  @override
  Widget build(context) {
    return Scaffold(
      appBar: header(context, isAppTitle: true),
      body: FutureBuilder(future: usersRef.get(),
      builder: (context, snapshot) {
        if (!snapshot.hasData){
          return circularProgress();
        }
        final List<Text> children = snapshot.data.documents.map((doc) => Text(doc['username'])).toList();
        return Container(
          child: ListView(
            children: children,
          ),
        );
      }
      ),
    );
  }
}

Error Log
Performing hot restart...
Syncing files to device sdk gphone x86 arm...
Restarted application in 706ms.
I/flutter ( 6385): User signed in!!!: GoogleSignInAccount:{displayName: Rinkumoni Khanikar, email: derekfrost621@gmail.com, id: 116999770966093637702, photoUrl: https://lh3.googleusercontent.com/a-/AOh14Gj1tc8cASVYMqeP-7NfiuWkfRQ5dnDHqNC2mhPNXA=s96-c}
I/flutter ( 6385): User signed in!!!: GoogleSignInAccount:{displayName: Rinkumoni Khanikar, email: derekfrost621@gmail.com, id: 116999770966093637702, photoUrl: https://lh3.googleusercontent.com/a-/AOh14Gj1tc8cASVYMqeP-7NfiuWkfRQ5dnDHqNC2mhPNXA=s96-c}
W/DynamiteModule( 6385): Local module descriptor class for providerinstaller not found.
I/DynamiteModule( 6385): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller( 6385): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<QuerySnapshot>(dirty, state:
_FutureBuilderState<QuerySnapshot>#a405e):
Class 'QueryDocumentSnapshot' has no instance method '[]'.
Receiver: Instance of 'QueryDocumentSnapshot'
Tried calling: []("username")

When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _TimelineState.build.<anonymous closure>.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:82)
#2      MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
#3      ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
#4      new List.from (dart:core-patch/array_patch.dart:38:29)
#5      new List.of (dart:core-patch/array_patch.dart:68:17)
#6      ListIterable.toList (dart:_internal/iterable.dart:211:44)
#7      _TimelineState.build.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:97)
#8      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:740:55)
#9      StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
#10     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
#11     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#12     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#13     StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#14     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#15     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#16     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#17     StatelessElement.update (package:flutter/src/widgets/framework.dart:4627:5)
#18     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#19     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#20     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#21     ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#22     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#23     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#24     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#25     ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#26     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#27     RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:5566:32)
#28     MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:6001:17)
#29     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#30     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#31     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#32     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#33     StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#34     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#35     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#36     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#37     ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#38     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#39     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#40     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#41     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#42     StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#43     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#44     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5881:14)
#45     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#46     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#47     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#48     StatelessElement.update (package:flutter/src/widgets/framework.dart:4627:5)
#49     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#50     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:5881:14)
#51     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#52     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#53     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#54     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#55     StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#56     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#57     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#58     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#59     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#60     StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#61     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#62     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#63     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#64     ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#65     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#66     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#67     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#68     ProxyElement.update (package:flutter/src/widgets/framework.dart:4906:5)
#69     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#70     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#71     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#72     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#73     StatefulElement.update (package:flutter/src/widgets/framework.dart:4751:5)
#74     Element.updateChild (package:flutter/src/widgets/framework.dart:3245:15)
#75     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
#76     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
#77     Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#78     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:33)
#79     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:866:20)
#80     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
#81     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
#82     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1056:9)
#83     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:972:5)
#87     _invoke (dart:ui/hooks.dart:253:10)
#88     _drawFrame (dart:ui/hooks.dart:211:3)
(elided 3 frames from dart:async)

════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<QuerySnapshot>(dirty, state: _FutureBuilderState<QuerySnapshot>#a405e):
Class 'QueryDocumentSnapshot' has no instance method '[]'.
Receiver: Instance of 'QueryDocumentSnapshot'
Tried calling: []("username")

When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _TimelineState.build.<anonymous closure>.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:82)
#2      MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
#3      ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
#4      new List.from (dart:core-patch/array_patch.dart:38:29)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

Another exception was thrown: NoSuchMethodError: Class 'QueryDocumentSnapshot' has no instance method '[]'.

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<QuerySnapshot>(dirty, state: _FutureBuilderState<QuerySnapshot>#a405e):
Class 'QueryDocumentSnapshot' has no instance method '[]'.
Receiver: Instance of 'QueryDocumentSnapshot'
Tried calling: []("username")

When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _TimelineState.build.<anonymous closure>.<anonymous closure> (package:fluttershare/pages/timeline.dart:57:82)
#2      MappedListIterable.elementAt (dart:_internal/iterable.dart:417:31)
#3      ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
#4      new List.from (dart:core-patch/array_patch.dart:38:29)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

pubspec.yaml
environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: 0.14.0+2
  image_picker: ^0.6.0+2
  firebase_storage: 4.0.0
  firebase_auth: 0.18.0+1
  google_sign_in: ^4.0.1+1
  geolocator: 6.0.0+4
  uuid: ^2.0.0
  image: ^2.0.7
  animator: 2.0.1
  cupertino_icons: 1.0.0
  path_provider: 1.6.14
  firebase_messaging: 7.0.0
  timeago: 2.0.27
  cached_network_image: 2.3.2+1
  firebase_core: ^0.5.0
  flutter_svg:

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:
  uses-material-design: true
  fonts:
    - family: Signatra
      fonts:
        - asset: assets/fonts/Signatra.ttf
  assets:
    - assets/images/google_signin_button.png
    - assets/images/upload.svg
    - assets/images/search.svg
    - assets/images/activity_feed.svg
    - assets/images/no_content.svg

main.dart
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:firebase_core/firebase_core.dart';

    void main() async{
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'FriendsHive',
          debugShowCheckedModeBanner: false,
          theme: ThemeData(
            primarySwatch: Colors.deepPurple,
            accentColor: Colors.teal,

          ),
          home: Home(),
        );
      }
    }

Cloud Firestore

I know I have made some mistakes, please can anyone point out my mistakes.
Thank You!!!

A: Just a couple of stuff that needs fixing.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/progress.dart';

final usersRef = FirebaseFirestore.instance.collection('users');

class Timeline extends StatefulWidget {
  @override
  _TimelineState createState() => _TimelineState();
}

class _TimelineState extends State<Timeline> {

/// What you're going to be getting back from your query is a QuerySnapshot, which will contain a List of DocumentSnapshots
Future<QuerySnapshot> querySnapshot;

  @override
  void initState() {
    /// Here you set your querySnapshot to what you get from your database call
   querySnapshot = getUsers();
    super.initState();
  }

  Future<QuerySnapshot> getUsers() async {

    return await usersRef.get();

  }

  @override
  Widget build(context) {
    return Scaffold(
      appBar: header(context, isAppTitle: true),
      body: FutureBuilder(
        future: querySnapshot, // This is what you return in your future builder
      builder: (context, snapshot) {
        if ((snapshot.connectionState == ConnectionState.done) && (snapshot.hasData)){

          List<dynamic> usernames = []; // This is where the usernames you get from Firebase will be saved

          List<DocumentSnapshot> documentSnapshot = snapshot.documents; // Putting the snapshot into a List of DocumentSnapshot

          for(DocumentSnapshot doc in documentSnapshot) {
            Map<String, dynamic> mappedData = doc.data;
            String un = mappedData["username"]; // Extracting every username in the document snapshot
            usernames.add(un);
          }

          final List<Text> children = usernames.map((user) => Text(user)).toList(); /// Mapping the username into a Text Widget, I don't know if I did this part right

            return Container (
              child: ListView(
                children: children,
              ),
            );

        } else {
          return circularProgress(); // Check that you got this part right
        }
      }
      ),
    );
  }
}

This should work for you. Let me know if it works! :)


text:
Q: Evolution of the Win32 API Has the Windows 32 API changed much over time? Does the Charles Petzold book "Programming Windows, 5th Edition" from 1998 still contain relevant information, or is most of it obsolete/outdated?
What are some prominent examples of recent additions to the Windows 32 API (if there are any)?

A: The new Thread Pool API in Windows Vista is a serious improvement and aid to well-written multiple thread programs, for a simple example of how WinAPI has evolved. However, the need to maintain compatibility has been a driving factor to keeping the basics of the Windows API the same and has resulted in some non-ideal things, like the predominance of Ex functions like CreateWindowEx. There are still functions compilable against 64bit Windows that are for compatibility with 16bit programs.
That book is still going to be of use if you want to write WinAPI-based programs that perform functions that were common in 1998, as it's unlikely that the API has changed. Of course, the best practices in the originating language may well be leagues ahead, especially if the book is written for C or C++, since a book from 1998 almost certainly was written against pre-Standard C++.
Also, the correct reference is Windows API, not Windows 32 API, as the same API governs both Windows 32 and Windows 64.

A: I've found Programming Windows to still be useful.  Thanks to Microsoft's emphasis on backwards compatibility, all of the core stuff (window handles, messages, GDI, etc.) seems to still be relevant and is covered well in Petzold.  (If anything changed too drastically, it would break too many existing Windows programs, and the huge number of existing Windows programs is a big part of Windows' advantage in the marketplace.)
There are specific new APIs, like Setup API, the Thread Pool API, and GDI+, and there are new topics such as working within the context of Vista's and 7's UAC.  There are also several individual new functions, that Petzold doesn't cover, but it's easy enough to look up newer topics on MSDN as needed.  Programming Windows also doesn't cover COM, which can be a big part of Windows programming.
Keep in mind that the API that Petzold covers is all low-level and C-based.  (There are a few newer APIs, like GDI+ and some of the COM stuff, that are object-oriented.)  Virtually any modern development will be object-oriented and will often use a framework like .NET or Qt or Delphi's VCL, so you'll rarely write complete applications that look like the example code in Programming Windows; however, it's still great for explaining what's going on under the hood.
I looked around a while ago and couldn't find any newer API references.  I suspect this is because of the sheer size of the current Windows APIs; Programming Windows, 5th Edition is already almost 1500 pages long, a book that covered anything new would be too huge.  I did find a couple of interesting-looking supplements to Programming Windows, although I haven't read them yet:

*

*Essential COM, by Don Box - Several of Vista's new APIs are COM-based, and Petzold doesn't cover COM.

*Windows System Programming, by Johnson M. Hart - seems to entirely skip the GUI and GDI stuff that Petzold covers so well, but it has much more detail on modern approaches top multithreading, IPC, etc.

*Windows Internals, by Russonovich, Solomon, and Ionescu - less about APIs and more about how Windows works under the hood.  Russonovich possibly knows more about this than anyone inside or outside of Microsoft.

A: The Windows API has changed over the years.  It's added entirely new sets of functions (ex: TaskDialog and family), and replacements for existing functions (ex: CreateWindowEx).
I'd recommend consulting a newer reference.

A: The Task Scheduler is also new, a lot of new objects & interfaces have been added. Prior to Task Scheduler 2.0, there was around 5 objects involved in scheduling tasks. In 2.0 (introduced when Vista came out), there are 20, no kidding, 20. This is one is the not so great things about win32 programming but its not that bad.
I love programming in win32 you learn so much about how Windows & other OS's operate at a lower level & it makes you a better programmer I believe. If you program in python, you dont learn about how directories are organised, just use os.listdir(""). But when using FindFirstFile() & FindNextFile in win32 you discover how directories are organised, discover the hidden ".." & "." directories & from that can come up with more efficient ways to catalog & search directories.
For win32 resources go to http://groups.google.com/group/comp.os.ms-windows.programmer.win32/topics


text:
Q: emacs --daemon starting with corrupted color scheme When I'm starting emacs as daemon I can not read comments (their color like background). But when I'm using emacs without --daemon switch everything is ok.
How to fix that weird issue?
;;; Custom color scheme related configurations
(if (< emacs-major-version 24)
  (unless (eq system-type 'windows-nt)
    (add-to-list 'load-path "/usr/share/emacs/site-lisp/emacs-goodies-el/")
    (require 'color-theme)
    (eval-after-load "color-theme"
      '(progn
         (color-theme-initialize)
         (color-theme-hober)
         )
      )
    (add-to-list 'load-path (concat dotfiles-dir "color-theme-solarized"))
    (require 'color-theme-solarized)
    )
  (progn
    (add-to-list 'custom-theme-load-path (concat dotfiles-dir "color-theme-solarized"))
    (load-theme 'solarized-dark t)
    )
)

just run emacs

run emacs -Q

run emacs --daemon

as you can see - totally different results.
and line numbers are also gone in emacs -Q and emacs --daemon cases.
To enable line numbers:
(global-linum-mode 1)

emacs version: GNU Emacs 24.4.1


text:
Q: How to round an int number to the nearest power of 10 I am trying to make a program that rounds a number to the nearest power of 10, for example if the input is 25378 the output should be 25000, or if the input is 438864 the output should be 438000. My code is working fine for the first case but not for the second, can anyone help me?
#include <stdio.h>
#include <math.h>

int b(int x)
{
    int k;
    int m;
    //int resultado;
    k = log10(x); //4 //5
    m = pow(10, k-1); //1000
    resultado = (x/m)*m;
    return resultado;
}

int test_b()
{
    int x;
    while(scanf("%d", &x) !=EOF)
    {
    int z = b(x);
    printf("%d\n", z);
    }
    return 0;
}

int main()
{
    test_b();
    return 0;
}

A: You're not rounding to the nearest power of 10. You're always rounding down, not to nearest, and it's always a multiple of 1000 (so you don't need to use log10() to get the number of digits).
Divide by 1000 then multiply by 1000. Integer division will simply discard the fraction.
int b(int x)
{
    return (x/1000) * 1000;
}

A: You talked about powers, maybe you also wanted to round numbers like 24 or 105 for example to the nearest "power" (as you say), in this case I think it is noticeable by the code that you are not rounding to a power but "to the number"(I will say it like this to make it easier to understand) that is multiplying and dividing as it is in the code.
As someone already say it you can do like this but maybe you need something more:
    int b(int x)
{
return (x/1000) * 1000;
}

I think you maybe want to round number like 24 or 106 too so i think this is the best solution (but im not sure :) )
 int b(int x)
{
    int num;
    if(x<=100)
    {
        num = (x/10)*10;
    }
    else if(x>100 && x<1000)
    {
        num = (x/100)*100;
    }
    else if (x>=1000)
    {
    num = (x/1000)*1000;
    }
    return num;
}

I dont know if you need that but in the case you need its here :)


text:
Q: Different definitions of a valid argument? I have some serious problems understanding what counts as a valid argument and what does not. I have read some different definitions of what a valid argument is:
(Sorry if this post is missplaced, I did not know if this apply to mathematics or philosophy or both. I did, however, first encounter my problems in a book about mathematics)
An argument is valid if
(1.) The premises cannot all be true without the conclusion being true as well
(2.) The truth of the premises guarantees the truth of the conclusion.
(3.) It is impossible for the premises all to be true and the conclusion not be true.
Ok so I've included a bunch of them just because I think it is good to hear it in different wordings. Personally, I would like to say that:
(4.) If the premises are all true then the conclusion is always true.
My confusion began when I was supposed to answer the following question:
What can you say about the validity of an argument if:
a) The conclusion is a tautology
b) The conclusion is a contradiction.
c) One premise is a contradiction
My thoughts on a)
It is not possible to say anything because one cannot know if it is possible for all premises to be true and therefore one cannot check if the argument is valid or not valid based on the definition for a valid argument, since it just says that if the premises are all true then the conclusion is always true. That is, since the condition "if the premises is all true" can never be met in the first place, there is no way to use the definition. I would like to say that the argument is undefined.
My thoughts on b) Reasoning same as in a)
My thoughts on c) Kind of the same thing, the definition cannot be used because all premises can never be true.
I read somewhere that the answer to c) should be that the argument is always valid since there is no way that all premises are true and at the same time, the conclusion false. Now, that kind of makes sense, there is certainly no scenario where all premises are true and the conclusion is false, so by (3.) it holds since it was the exact thing that cannot be possible if an argument is valid. If, however, I think about definitions (1.), (2.) and (4.), this does not make sense, I again think that there is no possible way to use these definitions to say anything about the argument, because the premises are not all true from the first place.
So, now I have come to the point where I think the definitions say different things. I feel like (3.) is about the possibility of a scenario and the other definitions are about implication. At the same time I feel like (3.) implies the other definitions and the other definitions implies (3.), but I have a hard time to see the equivalence.
One final thing that adds to my puzzlement is this example :
John is happy and John is not happy
Alice is happy or George is happy
George is X
Therefore Alice is Y
Edit
For example, if X = "not happy" and Y = "not happy", the argument does not makes sense structurally I think. And if it does not make sense structurally, what is the point of a valid argument in the first place?
Sorry for the excessively long post, but I am desperate for someone to help me make this
illogical logic logical.

A: Ok, lets try to untangle this.
Logical Consequence
You are pondering about logical consequence, the relation that holds between the premises and conclusion of a valid argument.
Your definitions (1)-(3) are the usual/historical conception of what logical consequence is, they are all equivalent. Also, let me emphasize their modal nature:

*

*The premises cannot all be true without the conclusion being
true as well.

*The truth of the premises guarantees the truth of the
conclusion.

*It is impossible for the premises all to be true and the
conclusion not be true.

Your suggestion (4) is also equivalent to 1.-3., if you take 'always' in a modal sense: Whenever the premises are true, the conclusion is necessarily true. But modal talk is vague. By e.g. 'impossible', do we mean metaphysically impossible/epistemically impossible, or just the absence of a counterexample? How can we put those definitions to use?
Luckily, Tarski came along and offered the now prevailing account of logical consequence. He neatly replaced the modal talk above with more transparent concepts: Formulas are interpreted in set-theoretic models. In a model (or, if you prefer, possible world) every formula is either true or false. Logical consequence is then defined as truth-preservation across interpretations: A formula $a$ is a logical consequence of a set of premises $B$, iff in every model in which all $B$ are true, $a$ is also true. In familiar formal terms: $$B\models a \iff \text{ for every model } \mathfrak M \text{ with } \mathfrak M\models B \text{, also } \mathfrak M\models a$$
(where $B\models a$ is read as ''$a$ is a logical consequence of $B$'', and $\mathfrak M\models a$ means ''$a$ is true in model $\mathfrak M$''.) The modal component of the first definitions was thus replaced by quantification over models.
The Stanford Encyclopedia of Philosophy has a helpful entry on logical consequence.
But that's enough for now, let's apply the Tarskian definition of logical consequence:
Your Examples
a) The conclusion is a tautology.
This means that the conclusion is true in all models, so it is the logical consequence of any set of premises. The argument is trivially valid.
b) The conclusion is a contradiction.
This means that the conclusion is false in every model. So it won't be the logical consequence of any set of premises, unless that set of premises is already inconsistent. If the premises are contraditory themselves, then the argument is valid (because, vacuously, in every model in which the premises are true (none!) the conclusion is true).
c) One premise is a contradiction.
Any conclusion follows from contradictory premises. Contradictory premises aren't true in any model, so the definition of consequence is again vacuously satisfied. The argument is trivially valid.
(I couldn't follow your final concrete example of an invalid argument with contradictory premises, so I don't comment on that)

Two more notes: (i) In addition to the Tarskian semantic account of consequence sketched above, there are also accounts starting from proof-theory. There, a sentence is said to follow logically if it can be formally derived from the premises using only valid rules of inference.
(ii) Logical consequence additionally depends on which rules of inference you consider valid. There is e.g. classical consequence and intuitionist consequence. But both notions can be captured in a Tarskian model-theoretic framework (intuitionist logic just requires more involved models).


text: Q: How to draw route line from start location to end location in xamarin forms I am new in Xamarin. I wanted to draw a route / path / road line (and not a straight line) from start location to end location. I followed this documentation, but this results in straight lines between locations and not the path. After searching for more info, I got a sample for Xamarin.iOS. I am looking for similar solution in Xamarin.forms which can run on both Android and iOS. I used xamarin.forms.maps nuget package manager.


text:
Q: Simple search function return always 0 results I have this php code
if(isset($_POST['submit'])){

$likeString = '%' . $_POST['search'] . '%';
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$query->bind_param('s', $likeString);
$query->execute();

    var_dump($likeString);
    if (!$query) {
      printf("Query failed: %s\n", $mysqli->error);
      exit;
    }
    if($res->num_rows > 0) {
       while ($row = $res->fetch_assoc()) {
             echo "
Title: " . $row['image_caption'];
       }
    } else {
          echo "
 0 results";
    }

}

var_dump($likeString) shows the word which I've posted via search form correctly. Also I've tried in phpmyadmin directly to run this query

SELECT *
  FROM images
  WHERE image_caption LIKE  "%Volvo%"

And I've received 1 result which is correct. On page I see 0 results. Tried to play with fetch:
$res->fetch_assoc()
$res->fetchAll()
$res->fetch()

none of them show any result. I'm sure is something very silly and simple mistake but can't see it. Please help on this.
I don't have Call to a member function bind_param() on a non-object It was my mistake while I've made proposed changes from one of the answer. Problem still remains - 0 Results
UPDATE: Current code
$likeString = "%{$_POST['search']}%";
$query = $conn->prepare("SELECT * FROM images WHERE image_caption LIKE ? ");
$query->bind_param('s', $likeString);
$query->execute();

    if($query->num_rows > 0) {
       while ($row = $query->fetch()) {
             echo "
Title: " . $row['image_caption'];
       }
    } else {
          echo "
 0 results";
    }

}

UPDATE 2: DB connection checked-> result is Connected successfully
$servername = "localhost";
$username = "mydbUsername"; // it's changed for the question
$password = "myPass"; // it's changed for the question
$dbname = "myDbName"; // it's changed for the question

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

A: You are using $res while it is not defined... You must use $query instead.
Next time turn on error reporting to see such silly bugs

A: try this : (update your code)
$likeString= "%{$_POST['search']}%";
$stmt = $db->prepare("SELECT * FROM images WHERE image_caption LIKE ?");
$stmt->bind_param('s', $likeString);
$stmt->execute();

$result = $stmt->get_result();
    while ($row = $result->fetch_array(MYSQLI_NUM))
    {
        foreach ($row as $r)
        {
           echo "
Title: " . $r['image_caption'];
        }
        print "\n";
    }

OR
<?php
  $conn = new mysqli("localhost","mydbUsername","myPass","myDbName");
  /* check connection */
  if ($conn->connect_errno) {
    printf("Connect failed: %s\n", $conn->connect_error);
    exit();
  }

  $query = "SELECT * FROM images WHERE image_caption LIKE %".$_POST['search']."%";

  if ($result = $conn->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        echo "
 Title: ". $row["image_caption"]);
    }print "\n";

    /* free result set */
    $result->free();
  }

  /* close connection */
  $conn->close();
?>


text:
Q: How to upload multiple files from Vuejs and Vuex to Laravel? Im a using Vuetifyjs, and im trying to create a message system with attachments.
i use the Vuex async await for state management and sending http request.
however im sending json format request not multipart/form-data, would it be possible?
 //html input

<input type="file" multiple ref="attachments" @change="fileOnChange" />

data() {
   return {
      form: new Form({
          receiver: "",
          subject: "",
          content: "",
          attachments: []
      })
  }
}

//method

fileOnChange() {
      let files = this.$refs.attachments.files;

      if (!files.length) {
        return false;
      }

      for (let i = 0; i < files.length; i++) {
        this.form.attachments.push(files[i]);
      }

    },

sendMessage() {
   this.addMessage(this.form)
}

and when the action is triggered this is the Vuex code

async addMessage({ commit }, message) {
        const config = { headers: { "Content-Type": "multipart/form-data" } };
        const response = await axios.post("api/message", message, config);
    },

what is the best approach on this to store the files in the LARAVEL storage and save it in the database?


text:
Q: Separate date in the format {day-month-year} I have a code that print the date in this format
Sun, 09 Mar 2014 08:31:14 GMT
I want to take the Date and shorten it so I can print

*

*the day

*the month

*the year

but I want to print each separately and I want to print the month in numbers
Here is the code I tried
$Date = $item->pubDate;
echo '.$Date.';

A: You should make use of createFromFormat of the DateTimeClass
<?php
$dt='Sun, 09 Mar 2014 08:31:14 GMT';
$date = DateTime::createFromFormat('D, d M Y G:i:s O', $dt);
echo "Day : ".$date->format('d'); // 09
echo "Month : ".$date->format('m'); //03
echo "Year : ".$date->format('Y'); //2014

Demo

A: Try using date function
echo date('d-m-Y', strtotime($Date));

And if you want to echo one by one
$date_to_time = strtotime($Date);

//Day
echo date('d', $date_to_time);
//Month
echo date('m', $date_to_time);
//Year
echo date('Y', $date_to_time);

A: Try
$date = '08/02/2014';
list($month, $day, $year) = explode('/', $date);


text:
Q: How to decompile Java class files which jd-gui decompiler is unable to decompile? We accidently got some JAVA source files deleted from the system.
This happened when We checked out a folder from repository directly as an eclipse project and then tried to copy a folder from another eclipse project into this one.Strangely all those folder files have vanished from local system (and obviously they never made it to SVN repository).
Somehow We have obtained .svn-base files for some CLASS files.Now We are trying to decompile class files to obtain the source code back. However some of the class files are giving error "invalid input file" when jd compiler is trying to process them.
Is there any other solution to this ?

A: From what I can tell, "jd-gui" is closed source, so you may need to contact the developer to find out what that message means.  (If it was open source, we could just look at the source code to figure out what the likely problem was!)
However, one thing is clear from various questions that Google shows up, and that is that "jd-gui" doesn't understand how to decompile archives (JAR, EAR, etc).  So maybe you just need to un-JAR something to make it work.
The other thing you could try (first) is to see what "javap" makes of the class files that "jd-gui" doesn't like.

A: Try using JAD to decompile your files.
www.varaneckas.com/jad/
You may need to unzip your jar files and then run something like the following to decompile them all
find <srcdirectory> -name *.class -exec jad -s .java -r -ff -clear -debug -d <dest directory> {} \;

I havent tested the above command but hopefully it is almost there...

A: I also had the error "invalid input file" with a certain class file. I was using version 0.3.6 of jd-gui. After downloading the newest version of jd-gui (which was 1.6.6 at the moment of writing this) I could decompile the class file which previously failed.
So if someone still has this problem it makes sense to check the version and upgrade if it is an older one. Here is a link to the "Latest-Release"-download page:
http://java-decompiler.github.io/


text:
Q: test for significance of interaction in linear mixed models in nlme in R I use lme function in the nlme R package to test if levels of factor items has significant interaction with levels of factor condition. The factor condition has two levels: Control and Treatment, and the factor items has 3 levels: E1,...,E3. I use the following code:
f.lme = lme(response ~ 0 + factor(condition) * factor(items), random = ~1|subject)

where subject is the random effect. In this way, when I run:
summary(f.lme)$tTable

I will get the following output:
factor(condition)Control
factor(condition)Treatment
factor(items)E2
factor(items)E3
factor(condition)Treatment:factor(items)E2
factor(condition)Treatment:factor(items)E3

together with Value, Std.Error, DF, t-value, p-value columns. I have two questions:

*

*If I want to compare Control vs. Treatment, shall I just use estimable() function in gmodels and make a contrast of (-1,1,0,0,0,0)?

*I am interested in whether levels of items, i.e. E1, E2, E3 are different across condition, so I am interested in whether the interaction terms are significant (by just checking the p-value column??):
factor(condition)Treatment:factor(items)E2
factor(condition)Treatment:factor(items)E3
However, how can I tell if factor(condition)Treatment:factor(items)E1 is significant or not? It is not shown in the summary output and I think it has something to do with the contrast used in R... Thanks a lot!

A: I respectfully disagree with @sven-hohenstein

In R, the default coding for categorial variables is treatment contrast coding. In treatment contrasts, the first level is the reference level. All remaining factor levels are compared with the reference level.

First, the fixed effects are specified here with a zero intercept, ... ~ 0 + .... This means that the condition coding is no longer contr.treatment. If I'm not mistaken, the main effects of Control and Treatment are now interpretable as their respective deviations from the group mean...

In your model, the factor items has three levels: E1, E2, and E3. The two contrasts test the difference between (a) E2 and E1, and (b) E3 and E1. The main effects of these contrasts are estimated for the level Control of the factor condition, since this is the reference category of this factor.

...when the value of items is at its reference level of E1! Therefore:

*

*Main effect Control = how much Control:E1 observations deviate from the mean of item E1.

*Main effect Treatment = how much Treatment:E1 observations deviate from the mean of item E1.

*Main effect E2 = how much Control:E2 observations deviate from the mean of item E2.

*Main effect E3 = how much Control observations deviate from the mean of item E3.

*Interaction Treatment:E2 = how much Treatment:E2 observations deviate from the mean of item E2

*Interaction Treatment:E3 = how much Treatment:E3 observations deviate from the mean of item E3.

Thanks for the pointer to estimable, I haven't tried it before. For custom contrasts, I've been (ab)using glht from the multcomp package.

A: You'll need to address your second question about the interaction first.  You can certainly set up the likelihood ratio test as in Jan van der Laan's answer.  You can also use anova directly on a fitted lme object.  See the help page for anova.lme for more information.
In terms of interpreting your coefficients, I often find that it sometimes takes making a summary table of the group means in order to appropriately figure out which linear combination of coefficients in the model represents each group.  I will show an example with the intercept removal like in your question, although I find this rarely helps me figure out my coefficients once I have two factors in a model.  Here is an example of what I mean with the Orthodont dataset (which I decided to make balanced):
require(nlme)

# Make dataset balanced
Orthodont2 = Orthodont[-c(45:64),]
# Factor age
Orthodont2$fage = factor(Orthodont2$age)

# Create a model with an interaction using lme; remove the intercept
fit1 = lme(distance ~ Sex*fage - 1, random = ~1|Subject, data = Orthodont2)
summary(fit1)

Here are the estimated fixed effects.  But what do each of these coefficients represent?
Fixed effects: distance ~ Sex * fage - 1
                     Value Std.Error DF  t-value p-value
SexMale          23.636364 0.7108225 20 33.25213  0.0000
SexFemale        21.181818 0.7108225 20 29.79903  0.0000
fage10            0.136364 0.5283622 61  0.25809  0.7972
fage12            2.409091 0.5283622 61  4.55954  0.0000
fage14            3.727273 0.5283622 61  7.05439  0.0000
SexFemale:fage10  0.909091 0.7472171 61  1.21664  0.2284
SexFemale:fage12 -0.500000 0.7472171 61 -0.66915  0.5059
SexFemale:fage14 -0.818182 0.7472171 61 -1.09497  0.2778

Making a summary of group means helps figure this out.
require(plyr)
ddply(Orthodont2, .(Sex, age), summarise, dist = mean(distance) )

     Sex fage     dist
1   Male    8 23.63636
2   Male   10 23.77273
3   Male   12 26.04545
4   Male   14 27.36364
5 Female    8 21.18182
6 Female   10 22.22727
7 Female   12 23.09091
8 Female   14 24.09091

Notice that the first fixed effect coefficient, called SexMale, is the mean distance for the age 8 males.  The fixed effect SexFemale is the age 8 female mean distance.  Those are the easiest to see (I always start with the easy ones), but the rest aren't too bad to figure out.  The mean distance for age 10 males is the first coefficient plus the third coefficient (fage10).  The mean distance for age 10 females is the sum of the coefficients SexFemale, fage10, and SexFemale:fage10.  The rest follow along the same lines.
Once you know how to create linear combinations of coefficients for the group means, you can use estimable to calculate any comparisons of interest.  Of course there are a bunch of caveats here about main effects, statistical evidence of an interactions, theoretical reasons to leave interactions in, etc.  That is for you to decide.  But if I was leaving the interaction in the model (note there is no statistical evidence of an interaction, see anova(fit1)) and yet wanted to compare the overall mean of Male to Female, I would write out the following linear combinations of coefficients:
# male/age group means
male8 = c(1, 0, 0, 0, 0, 0, 0, 0)
male10 = c(1, 0, 1, 0, 0, 0, 0, 0)
male12 = c(1, 0, 0, 1, 0, 0, 0, 0)
male14 = c(1, 0, 0, 0, 1, 0, 0, 0)

# female/age group means
female8 = c(0, 1, 0, 0, 0, 0, 0, 0)
female10 = c(0, 1, 1, 0, 0, 1, 0, 0)
female12 = c(0, 1, 0, 1, 0, 0, 1, 0)
female14 = c(0, 1, 0, 0, 1, 0, 0, 1)

# overall male group mean
male = (male8 + male10 + male12 +male14)/4
# overall female group mean
female = (female8 + female10 + female12 + female14)/4

require(gmodels)
estimable(fit1, rbind(male - female))

You can check your overall group means to make sure you made your linear combinations of coefficients correctly.
ddply(Orthodont2, .(Sex), summarise, dist = mean(distance) )

     Sex     dist
1   Male 25.20455
2 Female 22.64773

A: The usual way to test if the interaction is significant is to do a likelihood ratio test (e.g. see discussion on R-Sig-ME).
To do that you have to also estimate a model without interaction and you'll also have to use method="ML":
f0 = lme(response ~ 0 + factor(condition) * factor(items),
    random = ~1|subject, method="ML")
f1 = lme(response ~ 0 + factor(condition) + factor(items),
    random = ~1|subject, method="ML")

You can then compare using anova:
anova(f0, f1)

Also see this blog post


text:
Q: Transitioning to Higher Level Mathematics I am just finishing grade 12 pre-calculus at my school and have strong interest in math. The problem is, it seems some important elements of higher level math are not in my schools curriculum that are sometimes taught in pre-calculus.
My school offers Calculus and uses Stewarts text. I am planning to take it but what I can't decide is whether or not I should be self studying logic / set theory / proofs before studying calculus at a post secondary level to be able to handle rigorous texts in post secondary like Spivak.
If I was to just go ahead and take the Calculus that my school offers would I be adequately prepared for first year post secondary calculus / linear algebra courses or would most of the proofs / set theory be taught in first year p.s. courses?

A: I highly recommend these $3$ introductory books, in this order. They cover basic undergrad level math that you will definitely encounter in many undergraduate/graduate courses.
Mathematical Proofs: A Transition to Advanced Mathematics
The Higher Arithmetic: An Introduction to the Theory of Numbers
Discrete Mathematics and Its Applications

A: You'll probably end up taking an intro to proofs class if you major in math. I studied a lot of the stuff before hand, so I thought it was easy, but then I got to higher math, and I was screwed, because I didn't know how to adjust to not knowing anything. I really struggled/continue to struggle with more heavy theoretical math.
It just depends on you, though. I didn't really know anything about proofs either going into it, and yes, you will be at a disadvantage, but it's possible to learn. Just don't expect it to be as easy as it is now, because I promise, it gets a lot harder later.


text:
Q: Without removing i would like to subset the rows in the dataframe and run an ifelse through the subset? {df %>% filter(value %in% list)}$GOOD_Outcome<-ifelse(
                           df$column1 =="Y"&
                           df$column2 !="N"&
                           df$column3!=""&
                           df$column4 !="N"&
                           df$column5 !="",
                         "Yes", "No")

I get an error message
 Error in `$<-.data.frame`(`*tmp*`, GOOD_OUTCOME, value = c("No", "No", "No",  :

replacement has 977 rows, data has 33
I want the script to disregard the 944 other rows and run the ifelse within the confines of the 33 rows. Is there a way to do this?


text:
Q: Debug Typescript in Chrome bundled by Webpack Visual Studio 2017 .NET Core 2.2 There are a couple questions out there but most of the answers seem to be "it should be default now if you have VS 2017". My debugger isn't working, so I'd like to give my specific case to get some help. I'm also new to Typescript & Webpack to give some context.
Project Hiearchy
./wwwroot/bundles/bundle.js <- this is the final bundled file
./Scripts/ <- various directories where all the separate Typescript files live

When the project builds, it goes through these steps:

*

*Core project builds

*gulp task is kicked off

*Inside the gulp task, I use webpack stream to build the typescript files into the bundle.js

Contents of my tsconfig.json file
{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "strict": true,
    "noImplicitReturns": true,
    "target": "es2015",
    "moduleResolution": "node",
    "module": "es2015"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

Contents of the webpack.config.js file
module.exports = {
    mode: 'development',
    entry: './Scripts/index.ts',
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js'
        }
    },
    output: {
        filename: 'bundle.js'
    }
};

Gulp task that compiles the typescript and puts it in it's final destination.
gulp.task("compile-typescript", function () {
    return gulp.src("./Scripts/index.ts")
        .pipe(webpack(require("./webpack.config.js")))
        .pipe(gulp.dest("./wwwroot/bundles"));
});

After everything is compiled and running, when I put a break point in the Visual Studio IDE I get the "breakpoint not bound" problem. However, when looking at the debugger in Chrome, it seems like the TypeScript mapping files are being created in the webpack directory correctly.

A: By adding the lines from this answer: https://stackoverflow.com/a/56512126/5245385 to my webpack.config.js I was able to get it working!! Pasted below for visibility:
devtool: false,
plugins: [
    new webpack.SourceMapDevToolPlugin({
        filename: "[file].map",
        fallbackModuleFilenameTemplate: '[absolute-resource-path]',
        moduleFilenameTemplate: '[absolute-resource-path]'
    })
]