text:
Q: Way to check which pointers were not freed in C My code is already written in C, and I'm getting memory leak errors.
I'm using malloc and realloc in many places, is there a way to check which pointers weren't freed?
Is there any report that could point me into the right direction?
This code involves array of pointers which holds pointer to structs, and linked list of structs. There are some other dynamic allocations in the code as well.
This is the declaration:
user **arrMen = NULL;
int menSize = 5;
womanUser *womHead = NULL;

This is how I call the function :
freeAll(arrMen, womHead, &menSize);

And this is the way I'm freeing the arrays:
void freeAll(user **arrMen, womanUser *womHead,int *menSize)
{
    womanUser *current = womHead;
    womanUser *previous = current;
    int i;
    //free all pointers in woman list
    while (current != NULL)
    {
        if (current->womData->name != NULL)
            free(current->womData->name);
        if (current->womData->lastName != NULL)
            free(current->womData->lastName);
        if (current->womData->age != NULL)
            free(current->womData->age);
        if (current->womData->userName != NULL)
            free(current->womData->userName);
        if (current->womData->pass != NULL)
            free(current->womData->pass);
        if (current->womData->desc != NULL)
            free(current->womData->desc);
        previous = current;
        current = current->next;
        free(previous);
    }
    //free all pointer in men array
    for (i = 0; i < *menSize; i++)
    {
        if (arrMen[i]->name != NULL)
            free(arrMen[i]->name);
        if (arrMen[i]->lastName != NULL)
            free(arrMen[i]->lastName);
        if (arrMen[i]->age != NULL)
            free(arrMen[i]->age);
        if (arrMen[i]->userName != NULL)
            free(arrMen[i]->userName);
        if (arrMen[i]->pass != NULL)
            free(arrMen[i]->pass);
        if (arrMen[i]->desc!= NULL)
            free(arrMen[i]->desc);
    }
    if (arrMen != NULL)
        free(arrMen);
}

The program is running and functioning as expected, but it is suffering from memory leak, and I just can't find what I'm doing wrong, or where are the pointer I didn't not free.

A: A tool such as Valgrind (on Linux) is your best bet for leak detection and debugging, second to straightforward careful programming - every time you make an allocation, code the matching deallocation at the same time.  The debugger in recent versions of VC++ will also report memory leaks on termination I think.
In this specific case however it seems likely that @jamesdlin has spotted it.  You free arrMen without first freeing its elements:
for (i = 0; i < *menSize; i++)
{
    free(arrMen[i]->name);
    free(arrMen[i]->lastName);
    free(arrMen[i]->age);
    free(arrMen[i]->userName);
    free(arrMen[i]->pass);
    free(arrMen[i]->desc);

    free( arrMen[i] ) ;  // <<< Free the structure
                         //     after its members
}

free(arrMen);

Note that freeing a null pointer is defined and safe, so checking for NULL every time serves no purpose.  What you might do is set each pointer to NULL, so that if any code later attempts to dereference it, it will at least cause a run-time error.  For example you might have:
for (i = 0; i < *menSize; i++)
{
    free(arrMen[i]->name);
    free(arrMen[i]->lastName);
    free(arrMen[i]->age);
    free(arrMen[i]->userName);
    free(arrMen[i]->pass);
    free(arrMen[i]->desc);

    memset( arrMen[i], sizeof(*arrMen[i]), 0 ) ;
    free( arrMen[i] ) ;  // <<< Free the structure
                         //     after its members
    arrMen[i] = NULL ;
}

free(arrMen);
arrMen = NULL ;


text:
Q: How do I setup Testling-CI with QUnit + QUnit-TAP? Problem
We are trying to setup Testling to run our QUnit (with QUnit-TAP) tests following the "Custom Libraries" instructions: https://ci.testling.com/guide/custom_libraries
Our testling configuration (in package.json file) is:
"testling": {
  "html": "test.html",
  "browsers": [
    "ie/6..latest",
    "chrome/22..latest",
    "firefox/16..latest",
    "safari/latest",
    "opera/11.0..latest",
    "iphone/6",
    "ipad/6",
    "android-browser/latest"
  ]
}

Full package.json: http://git.io/vT3s7
and we setup the WebHook as per the quick start instructions:

But when we push to the repo the WebHook fails.
The payload is quite long. see: http://git.io/vT33D
Our tests work in the browser. See: https://learn-testling.herokuapp.com
(open devtools/console to) see the the Valid TAP output:

Any help much appreciated!

Background + Links

*

*We followed the instructions in the quick start guide: https://ci.testling.com/guide/quick_start

*But we are using QUnit in our project(s) so we followed the "Custom Libraries" instructions: https://ci.testling.com/guide/custom_libraries

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to correctly get timestamps in each stage of the ELK cluster? I have this pipeline up running on AWS:
Webserver+rsyslog->Kafka (3 servers: 1xZK, 2xKafka Brokers)->Logstash (2 servers: Both acting as indexers)->ES+Kibana (both on the one server).
Here is the log I send from rsyslog:
{"rsyslog_timestamp":"2016-05-19T03:00:55.586137+00:00", "message":"<IP_REMOVED> - - 2016-05-19T03:00:55:586082 \"GET \/investing\/property\/national-diversified-property?user=user361 HTTP\/1.1\" 301 681"}

Here is an example of a log when viewed in Kibana:
rsyslog_timestamp:May 19th 2016, 13:15:27.023 message:<IP_REMOVED> - - 2016-05-19T03:15:27:023436 "GET /banking/savings-account/netbank-saver?user=user559 HTTP/1.1" 301 659 @version:1 @timestamp:May 19th 2016, 13:17:32.591 category:banking subcategory:savings-account product:netbank-saver user:user559 _id:<REMOVED> _type:logs _index:logstash-2016.05.19 _score:

So I have a timestamps on:
1. Apache log
2. Rsyslog (but somewhere this is being modified, maybe logstash?)
3. I don't know where the others come from is it LS or ES?
I want to clearly have the timestamps on Kafka (I have installed the RC4 but I can't see timestamps), LS, ES. That way I can see the time it takes to get through each part.
How can I do this in the remaining parts? And what is messing with my rsyslog timestamp and modifing it?


text:
Q: Get user's location at a specific time and date in iOS I have an app where I create events. I need to get user's location when the event is ending automatically (set by user while creating event). I tried local notification but in that case, you need to wait for user's interaction and that can cause delay as user might not click right away.
I want user's exact location at a specific time regardless of the state of the app (foreground, background or not running). Let me know if you need any further clarification. Also, any document, tutorial or code will be highly appreciated. Thanks.


text:
Q: Arduino bluetooth on android My application :
  /**
 * Connect bluetooth smarphone.
 * auto on bluetooth and button turn off bluetooth
 */
package com.Iris;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.util.Set;

public class IrisActivity extends Activity
{
Button button1;
// button Off bluettooch
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.button1);
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// ac
bluetoothAdapter.enable();

Toast.makeText(IrisActivity.this, "Bluetooth Activé", Toast.LENGTH_SHORT).show();

Set<BluetoothDevice> devices;
devices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice blueDevice : devices)
{
Toast.makeText(IrisActivity.this, "Réseau : " + blueDevice.getName(), Toast.LENGTH_SHORT).show();
}

button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
bluetoothAdapter.disable();
Toast.makeText(IrisActivity.this, "Bluetooth Désactivé", Toast.LENGTH_SHORT).show();
}
});

}

My application is Good, but I want connect at "blueDevice.getName"  and send ASCI letter "H" with my application
Can you help me?

A: Take a look at the BluetoothChat sample. Basically, you'll need to do the following on transmit side:
BluetoothSocket socket = blueDevice.connect();
OutputStream os = socket.getOutputStream();
os.write("H");

You'll need a server socket on the receive side shown in sample.


text:
Q: list and string - what is the subtle difference After some frustrating debug, I realize that my understanding of string and list is superficial. Here is the code dragging me down:
1   set a1 "set a 1"
2    set l1 {}
3    lappend l1 [list $a1]
4    puts "l1=$l1"
5    foreach e $l1 { puts $e; eval $e}

The error is at line 5, it needs to be
5    foreach e $l1 { puts $e; set e2 [join $e]; eval $e2}

Basically I need to use a join to convert the list to a string, otherwise the script to eval is "{set a 1}" instead of "set a 1".
I cooked the following test script during the debug:
set li {{set a 1} {set b 2}}
foreach l $li { puts $l; eval $l}

It works fine, I do not need "join".
Yes, I read the on-line doc about list and string. But still cannot wrap my hands around head. Still something not lighting up.
Could you shed some light? I am not sure where I am stuck why cannot appreciate the difference.

A: Well, the 'culprit' in your initial code is that you are using lappend l1 [list $a1]. You should be getting:
l1={{set a 1}}

When you use puts "l1=$l1" and what the above means is that you have a list within another list, which is itself in yet another list! (you lose the outermost braces when you print a list)
Indeed, when you do [list $a1], you are appending a list containing the list/element {set a 1} (i.e. {{set a 1}}) to the list $l1 while if you did lappend l1 $a1, you would be adding the string/list {set a 1} to the list $l1.
I think what you actually meant to use is something a bit more like this:
set a1 [list set a 1]
# Where you get a list containing the 3 elements "set" "a" and "1"
set l1 {}
lappend l1 $a1
foreach e $l1 {puts $e; eval $e}

Maybe another way to look at it:
set a1 [list set a 1]
puts $a1
# => set a 1

set a1 {set a 1}
puts $a1
# => set a 1

set a [list $a1]
puts $a
# => {set a 1}  -- A list within a list

set l {}
lappend l $a1
puts $l
# => {set a 1}

lappend l $a
puts $l
# => {set a 1} {{set a 1}}
#      list    list in list  -- and $l is the list containing those two.


text:
Q: How to convert 64 bits integer represented as decimal string into hex string How to convert 64 bits integer represented as decimal string into hex string?
I need to do it in Perl on system that doesn't support Quads.

A: use Math::BigInt;
my $decimal_string = '123456789123456789';
$hex_string = Math::BigInt->new($decimal_string)->as_hex();

A: use bignum;


text:
Q: CSS how to style the actual text in an input I know that I can do add color, padding... by styling the input. Are there vendor pseudo elements to style the text itself like there are for placeholder? I want to like translateY the text in the input but not using vertical-align or affecting input's height.

A: I've searched before, and just now searched again, but I don't believe there are any vendor pseudo elements targeting the values of text inputs like there are for placeholder text.
Being able to apply CSS transform properties to text input values is, to the best of my knowledge, not currently possible with CSS only. There may be some way to achieve what you want with JS, but I haven't seen it done before.
This post delves into the issue, offers some creative workarounds, and may provide you with useful guidance: Is there a way to style part of an input field's value?


text:
Q: How to stop a while with a button on a user interface I'm trying to make a user interface simple with 2 buttons 1 starts a loop and the other one stops it
The only thing I could come up with is to create a global variable that changes depending on which button is pressed and that's the condition for the loop however the stop button won't work while the loop is running and therefore i can't stop the loop
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public StartStop As Integer
Public para As Integer

Sub AutoClick(x)

Do While StartStop = 1
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    Sleep (x * 1000)
    If para = 0 Then
        Exit Do
    End If
Loop

End Sub

Private Sub CommandButton1_Click() 'this is the start button

StartStop = 1
para = 1
AutoClick (Segundos)

End Sub

Private Sub CommandButton2_Click() 'this is the stop button
para = 0
End Sub

Id just like for the stop button to stop the loop, but I haven't come up with an answer yet, don't wanna overcomplicate the code for this

A: You should add a DoEvents function invocation inside your loop, as described in this answer
Do While StartStop = 1
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    Sleep (x * 1000)
    DoEvents
    If para = 0 Then
        Exit Do
    End If
Loop

A: Check this:
Dim i As Long
Dim doloop As Boolean

Private Sub CommandButton1_Click()
    doloop = True
    StartCicle
End Sub

Private Sub CommandButton2_Click()
    doloop = False
End Sub

Sub StartCicle()

    i = 0
    While doloop

        Label1.Caption = CStr(i)
        i = i + 1
        DoEvents

    Wend
End Sub

Put this code on a UserForm and add 2 commandbuttons and a label.
Click on commandbutton1 to start cicle
Click on commandbutton2 to stop cicle
You can see label 2 being incremented
That code do what you want.


text:
Q: How to format double in Salesforce Apex I want to display double in format such as "12.30" but it display "12.0" in salesforce apex.
can any one help me?

A: VisualForce uses the java.text.MessageFormat conventions for formatting. Here's an example. Replace the MyDouble variable with your own.
<apex:outputText value="{0,number,0.00}" >
    <apex:param value="{!MyDouble}" />
</apex:outputText>

A: You can cast the 12.30 as an int and then cast it back to double. Casting it to an int truncates the fraction.
double i = 10.345;
system.debug('this is i '+ i);
system.debug('this is i after fixing '+ (double)(integer)i);

gives:
10:04:26.129 (129990000)|USER_DEBUG|[16]|DEBUG|this is i 10.345
10:04:26.130 (130080000)|USER_DEBUG|[17]|DEBUG|this is i after fixing 10.0

A: When you are creating a field then we have to define it's decimal places. Try specifying that decimal number to 2. It will work.


text:
Q: How to make irregular table in PHP? I have all the data in one table in database and I need to display it like in the picture given (example made in excel).
The table in database has all the students and their mentors (named profesors in the picture). So,I have to display every mentor and students they are mentoring, but like in the example.

A: Unfortunately you don't explain how is data layouted in database, so I need to guess and create example based on fiction.
If you have data in following layout:
professor:            professor_id | name
student:              student_id   | name
professor_x_student:  professor_id | student_id

... then you'd first create 2-dimensional array in PHP (readable but untested pseudo-spaghetti code follows, use your favorite dialect / template / code style):
$resultarray = array();
$sth = query("select p.professor_id, s.student_id,
  p.name professor_name, s.name student_name from professor p
  inner join professor_x_student pxs on p.professor_id = pxs.professor_id
  inner join student s on pxs.student_id = s.student_id");

$maxstudents = 0;
while ($row = $sth->fetch_assoc()) {
  if (empty($resultarray[$row['professor_id']])) {
    $resultarray[$row['professor_id']] = array('id' => $row['id'], 'name' => $row['professor_name'], 'students' => array());
  }
  $resultarray[$row['professor_id']]['students'][$row['student_id'] = array('id' => $row['student_id'], 'name' => $row['student_name']);
  $maxstudents = count($resultarray[$row['professor_id']]['students']) > $maxstudents ? count($resultarray[$row['professor_id']]['students']) : $maxstudents;
}
$resultarray = array_values($resultarray); // Reset array keys!!
foreach ($resultarray as &$professor) {
  $professor['students'] = array_values($professor['students']); // Reset array keys !!
}

Now, in your template, you just need to iterate over results and draw some nested lists:
echo '
';
foreach ($resultarray as $professor) {
  echo '
'.$professor['name'];
  echo '
';
  foreach ($professor['students'] as $student) {
    echo '
'.$student['name'].'
';
  }
  echo '
';
  echo '
';
}
echo '
';

In CSS it probably should be something like:
.firstlevel {
  float: left;
}
.secondlevel {
  padding-left: 20px;
}

Updated: In case you are sure you want to use tables, you need some add-on, you need to know what is the max number of students to professor (update in previous fetch code, variable $maxstudents). Also you can't have assoc arrays with this scheme so I changed example on that aspect also.
And then draw table like this:
echo '
';
echo '
';
foreach ($resultarray as $professor) {
  echo ''.$professor['name'].'	';
}
echo '
';
for ($i = 0; $i < $maxstudents; $i++) {
  echo '
';
  foreach ($resultarray as $professor) {
    if (!empty($professor['students'][$i])) {
      echo ''.$professor['students'][$i]['name'].'	'; // echo n-th student
    } else {
      echo ' 	'; // empty cell
  }
  echo '
';
}
echo '
';

A: // insert all data in a friendly structured array
// order by here determines horizontal and vertical order. May be other if you want.
$rs = $db->query("select profesor, student from table order by profesor, student");
$out = [];
$counter_by_prof = [];
while($row = $rs->fetchAsoc()) {
    $counter_by_prof[$row['profesor']]++;                                               // works even on not inicialiced values
    $out[$counter_by_prof[$row['profesor']]][$row['profesor']] = $row['student'];       // stack by row by profesor
}
// output the table from the array
echo '
';                                                                         //  /tr /td /th (missing later) are optional
// output header row
echo '
';
foreach($counter_by_prof as $prof=>$tot) echo ''.htmlspecialchars($prof);
// output each row
foreach($out as $row){
    echo '
';
    foreach($counter_by_prof as $prof=>$tot) {
        echo '';
        if(array_key_exists($prof, $row) echo htmlspecialchars($row[$prof]);
        else                             echo ' ';
    }
}
// bonus line: totals
echo '
';
foreach($counter_by_prof as $prof=>$tot) echo ''.$tot;
echo '
';

Side note: if two profesors have the same name, you will need a similar script but ID oriented.


text:
Q: Proper Replacement of Fragments I have one Activity Called A. The activity has 1 Frame Layout in which Fragments are used. I have two Fragments, Fragment1 and Fragment2. When the Activity is launched, Fragment 1 fills the Frame Layout.
Fragment1 also contains a button that when clicked replaces it with Fragment2 within that same Frame Layout. My question is this, when I click that Button in Fragment1 should I implement that code so that
A) Activity A gets notified of the onClick in the Fragment through an interface using some type of Boolean value and then proceeds to replace it with Fragment2.
OR
B)Implement the code that replaces Fragment1 with Fragment2 within Fragment1 itself For example:
private FragmentTransaction ft;
private Button registerButton, resetButton;
private Fragment fragment;

public LoginFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_login, container, false);

    registerButton = (Button)view.findViewById(R.id.register_button);
    resetButton = (Button) view.findViewById(R.id.reset_button);
    registerButton.setOnClickListener(this);
    resetButton.setOnClickListener(this);

    return view;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.register_button: {
            fragment = new RegisterFragment();
            ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, fragment);
            ft.addToBackStack(null);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft.commit();
            break;
        }
    }
}

Could someone explain why one over the other? Thanks so much!

A: Generally, what I do is use an interface of some sort that lives in the fragment being replaced (in this case Fragment 1). Your parent activity then would implement this interface, and thus building a contract between the activities that are the parent of that particular fragment.
When you press your button (or whatever event happens to signal replace), you grab your activity casting it to that interface, and call the particular method.
e.g. Signaling event within the fragment
( (MyFragmentListener) getActivity()).onActionHappens();

Where MyFragmentListener is the inner class of your Fragment and onActionHappens() is the method that sends the signal. This effectively creates a contract between your fragment and any Activity that hosts the fragment. When your action happens, you let the activity know and the activity then overrides the appropriate method to handle the event.
There are other ways to do this, but at the simplest level this is how it can be done.
Why not option B
Option B creates a tight coupling between fragments, which you don't necessarily want. In practice you want the coupling to be between the fragment, and it's host (or parent) which is the Activity. Also, there could be many activities that use that fragment so you abstract away details about the particular activity that uses it by just calling getActivity(). In this case, coupling the fragment and the Activity is acceptable, since of course the two are coupled anyways. We know this because a fragment cannot live without an associated Activity, so it is okay to take advantage of the that tight coupling.
Summary
Pick option A. It is the cleanest route, and avoids assuming implementation details that you have to do in option B.
It is also the basic solution you have without any external libraries or details required. If you want a more advanced solution, checkout Otto (made by Square) Link to the library here


text:
Q: qbxml QuickBooks XML BillAddress invalid according to DTD Version 13.0 of qbxml.  Why is the validator listing XML elements that are not in my XML and are not required as something it's expecting?
In all the references I've seen it lists Memo after BillAddress for InvoiceAdd.
https://developer-static.intuit.com/qbSDK-current/Common/newOSR/index.html
Line: 20
LinePos: 22
Src Text: <BillAddress>
Reason: Element content is invalid according to the DTD/Schema.
Expecting: ItemSalesTaxRef, Memo, CustomerMsgRef, IsToBePrinted, IsToBeEmailed, IsTaxIncluded, CustomerSalesTaxCodeRef, Other, Exchange....

<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="13.0"?>
<QBXML>
  <QBXMLMsgsRq onError="continueOnError">
    <InvoiceAddRq requestID="43">
      <InvoiceAdd>
        <CustomerRef>
          <FullName>GORILLA SPRAY FOAM LLC</FullName>
        </CustomerRef>
        <ARAccountRef>
          <FullName>Accounts Receivable</FullName>
        </ARAccountRef>
        <TxnDate>2017-12-01</TxnDate>
        <RefNumber>9690</RefNumber>
        <PONumber>JN 102317</PONumber>
        <ShipDate>2017-10-23</ShipDate>
        <ShipMethodRef>
          <FullName>x</FullName>
        </ShipMethodRef>
        <BillAddress>
          <Addr1>GORILLA SPRAY FOAM LLC</Addr1>
          <Addr2>2332 HIGHWAY 65</Addr2>
          <City>MORA</City>
          <State>MN</State>
          <PostalCode>55051</PostalCode>
        </BillAddress>
        <InvoiceLineAdd>
          <ItemRef>
            <FullName>S 8000</FullName>
          </ItemRef>
          <Desc>x</Desc>
          <Quantity>2</Quantity>
          <Amount>x</Amount>
        </InvoiceLineAdd>
        <InvoiceLineAdd>
          <ItemRef>
            <FullName>S 8020</FullName>
          </ItemRef>
          <Desc>x</Desc>
          <Quantity>2</Quantity>
          <Amount>x</Amount>
        </InvoiceLineAdd>
        <InvoiceLineAdd>
          <ItemRef>
            <FullName>Delivery Charge</FullName>
          </ItemRef>
          <Desc>Delivery Charge</Desc>
          <Amount>75.00</Amount>
        </InvoiceLineAdd>
        <InvoiceLineAdd>
          <ItemRef>
            <FullName>Sales Tax</FullName>
          </ItemRef>
          <Desc>Minnesota Sales Tax</Desc>
          <Amount>2.58</Amount>
        </InvoiceLineAdd>
      </InvoiceAdd>
    </InvoiceAddRq>
  </QBXMLMsgsRq>
</QBXML>

A: The order of the tags in qbXML is important.
If the OSR shows, for example, that the ShipMethod, ShipDate, and PONumber tags come AFTER the BillAddress tag, then you MUST follow that order.
Refer to the OSR:
https://developer-static.intuit.com/qbSDK-current/Common/newOSR/index.html
Make sure your tags are in the correct order. Currently they are not due to the ShipDate, ShipMethodRef, and PONumber tags being prior to BillAddress.


text:
Q: Angularjs display message with /n Im trying to get angularjs to read my new lines properly, in this case /n is a new line.
here is my acual response from my variable message with the info i would like to display:
jeg\n\nlurer\npaa hva

when i display the variable in the view with {{ message }}i get:
Jeg lurer paa hva

while it really should be:
Jeg

lurer
paa hva

how can i make angular read the /n as new line?

A: Use some css styling

{{message}}

n in CSS
 div.pre-line {
      white-space: pre-line;
 }

A: Put your {{message}} inside a
 tag like,

{{message}}

which will take care of the link breaks.
Hope this helps!

A: Are you looking for ng-bind-html?

A: Adding
 tag around of your {{ message }} will resolve your problem.
You can add this feature of the pre tag with css.


text:
Q: HtmlAgilityPack remove node (thead) not working Want to remove a complete thead (including th's). Why this doesn't work?
I've tried other tags and nothing happens, result text is the same. like there were no changes.

        Hora
        Estado
        Motivo
         Local
         Recetor

c# code
doc.LoadHtml("

Hora	Estado	Motivo	Local	Recetor

");

var nodes = doc.DocumentNode.SelectNodes("//thead").ToList();

foreach (var node in nodes) {
  node.Remove();
}

txtResults.Text=doc.Text;

A: HtmlDocument.Text property has very unclear description:

The HtmlDocument Text. Careful if you modify it.

From observed behavior it looks like this property is not updated when you modify html document. So use doc.DocumentNode.OuterHtml instead.

Update: From ParsedText property implementation it looks like Text supposed to hold original unmodified parsed text:
public string ParsedText
{
    get { return Text; }
}

But this is not even a read-only property - it's a public field that can be modified anytime by anyone. So I would not trust the HtmlDocument.Text as its description says.


text:
Q: Opencart check if guest checkout I am making some modifications to an Opencart installation and one is to show a step 1 of x etc.
Is there a way to check if the user is using the guest checkout as this seems to have one less step than the registered user checkout. I think because they combine payment and shipping address into one page. So what I would like is that if using guest checkout show 1 of 3, 2 of 3 etc otherwise show 1 of 4, 2 of 4 etc.
Thanks

A: To find out if a user is logged in (registered) you can use
$this->customer->isLogged()

which will return true if they're logged in (registered) or false if it's a guest


text:
Q: How to create a Wordpress Post Filter that users can use to filter posts by year? I am looking to have a drop down menu at the top of the archive page or other pages with post loop that will allow the users to filter posts by date (year)
There will be a drop down with all the years posts are published. Eg: 2017, 2018, 2019
My Loop:
<?php
    $args = array(
        'cat' => $FeaturedNewsCat,
        'posts_per_page' => 2,
        'order' => DSC
    );
    $the_query = new WP_Query($args);
    while ( $the_query->have_posts() ) : $the_query->the_post();
?>

        <!--Post Template Comes Here-->

<?php
    endwhile;
    wp_reset_postdata();
?>

Please tell me what I have to do to implement the filter function. Any help is appreciated.

A: I'm pretty sure you haven't even try to search for solution... If you did, then I'm pretty sure you would came to this Codex page, where you can find this code:
<select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
  <option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
  <?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option', 'show_post_count' => 1 ) ); ?>
</select>

Which displays a drop-down box of monthly archives, in select tags, with the post count displayed.
All you have to do is to change 'monthly' to 'yearly' and start using archive template and global wp_query and not your own custom one.


text:
Q: What stripe payment charge information should be stored by the application? When integrating stripe payments (or stripe connect), stripe returns a Stripe::Charge object to the application after a payment has been attempted.
What is best practice for storing this information, that is, what fields should the application store in its database?
I think at an absolute minimum, the application should store:

*

*the payment's id (so it can be looked up in the future),

*the payment's status (so the app can know if the payment went through)

*the app should obviously record which purchase the payment corresponds to

But there are many other fields in the Stripe::Charge object which seem quite important. However, storing everything could simply be completely unnecessary (overkill).
Here is an example of a Stripe::Charge object returned after a payment intent has been created:
{
  "id": "ch_1HwISYGtUKse83O9n9LJ5DK1",
  "object": "charge",
  "amount": 30000,
  "amount_captured": 30000,
  "amount_refunded": 0,
  "application": null,
  "application_fee": "fee_1HwISY2fgYVxT5fZTsciNPKg",
  "application_fee_amount": 4500,
  "balance_transaction": "txn_1HwISZGtUKse83O9kkrHTynB",
  "billing_details": {"address":{"city":null,"country":null,"line1":null,"line2":null,"postal_code":"41234","state":null},"email":null,"name":"Ben Johnson","phone":null},
  "calculated_statement_descriptor": "JOE SMITH",
  "captured": true,
  "created": 1607481078,
  "currency": "usd",
  "customer": null,
  "description": null,
  "destination": "acct_1HtSLp2fgYVxT5fZ",
  "dispute": null,
  "disputed": false,
  "failure_code": null,
  "failure_message": null,
  "fraud_details": {},
  "invoice": null,
  "livemode": false,
  "metadata": {},
  "on_behalf_of": "acct_1HtSLp2fgYVxT5fZ",
  "order": null,
  "outcome": {"network_status":"approved_by_network","reason":null,"risk_level":"normal","risk_score":63,"seller_message":"Payment complete.","type":"authorized"},
  "paid": true,
  "payment_intent": "pi_1HwIQwGtUKse83O9R4k7NiUa",
  "payment_method": "pm_1HwISXGtUKse83O9ua95HqYJ",
  "payment_method_details": {"card":{"brand":"visa","checks":{"address_line1_check":null,"address_postal_code_check":"pass","cvc_check":"pass"},"country":"US","exp_month":12,"exp_year":2034,"fingerprint":"W0rYzPMfZtx74C5u","funding":"credit","installments":null,"last4":"4242","network":"visa","three_d_secure":null,"wallet":null},"type":"card"},
  "receipt_email": null,
  "receipt_number": null,
  "receipt_url": "https://pay.stripe.com/receipts/acct_1HYHSFGtUKse83O9/ch_1HwISYGtUKse83O9n9LJ5DK1/rcpt_IXNCchkcmv9fndlQPRCjh4mEtdNtTn0",
  "refunded": false,
  "refunds": {"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/charges/ch_1HwISYGtUKse83O9n9LJ5DK1/refunds"},
  "review": null,
  "shipping": null,
  "source": null,
  "source_transfer": null,
  "statement_descriptor": null,
  "statement_descriptor_suffix": null,
  "status": "succeeded",
  "transfer": "tr_1HwISYGtUKse83O9q9ZEE4Gq",
  "transfer_data": {"amount":null,"destination":"acct_1HtSLp2fgYVxT5fZ"},
  "transfer_group": "group_pi_1HwIQwGtUKse83O9R4k7NiUa"
}

So the simple, practical question: out of the above info, which fields should be stored in the application's database?

A: This entirely depends on the needs of your application and there is no universal answer. You can store all of it, none of it, or select fields.
The id is a good place to start, sure. If you were using Customers, you might want to store the associated customer id too. If you were using destination charges, you might want to store the related account. If you wanted to do some custom accounting you might store the amount and the fees.
It depends. Store whatever you like.


text:
Q: Django app for user/account settings Im prepping for developing one project and am in process of mapping out stuff i can use for it. This project is going to need different group/user based model & object permissions and settings.
I know i can use django-objectpermissions (https://github.com/washingtontimes/django-objectpermissions) and djangos own model permissions. But there are some cases, when you dont really need to set object/model permissions, but rather a setting - can this account/user do something, which is not related to certain object or model. Has someone developed app for this? Or what kind of approach do people take when they have such need? Perhaps create dummy django model and let djangos model permissions handle the rest?
I also know, that this does something similar - https://github.com/danielroseman/django-dbsettings. But when i skimmed through the code i got impression, that those settings are all user based - i need also group based settings.
Edit: People keep offering me permissions apps. What i am looking for is not permissions app, but settings app. Those settings/permissions are not related to any objects.
Basically. In my project i need to answer questions - Can this user see/do this thing?. That "thing" is most likely a view. So one of the answers almost works. But the check i do at view, is not if user has permission to some model/object. Its rather, if the user has this setting turned on, of if users group has this setting turned on.
Alan

A: You're probably going to need to create your own system for this. It shouldn't be very difficult.
class Setting(models.Model):
    name = models.CharField(..)
    value = models.CharField(..)
    users = models.ManyToManyField(User)
    groups = models.ManyToManyField(Group)

    @classmethod
    def has_setting(cls, name, user):
        user_settings = cls.objects.filter(name=name, users__in=[user]).count()
        group_settings = cls.objects.filter(name=name, groups__in=user.groups.all()).count()
        return user_settings or group_settings

    @classmethod
    def get_settings(cls, name, user, priority=User):
        user_settings = list(cls.objects.filter(name=name, users__in=[user]))
        group_settings = list(cls.objects.filter(name=name, groups__in=user.groups.all()))
        if user_settings and not group_settings:
            return user_settings
        elif group_settings and not user_settings:
            return group_settings
        else:
            return (group_settings, user_settings)[priority==User]

Then you can do something like this in your views:
def display_frob(request):
    if Setting.has_setting('display_frob', request.user):
         settings = Setting.get_setting('display_from', request.user, priority=Group)
         values = [setting.value for setting in settings]
         # if the User was in many groups, we now have a list of values, for the setting
         # `display_frob`, that aligns with each of those groups

You can easy build a decorator which will do the check, and provide a list (or a single item) of values to the view.

A: For permissions for "actions" (where an action is typically implemented by a view) I commonly use decorators.
The user_passes_test decorator is great for this kind of purpose.
You could create user permissions not linked to models.

A: Maybe this is what you looking for : django-guardian


text:
Q: Upgrading to kernel 3.1 from 3.0.0-15 I've tried this instruction to install kernel 3.1
but when I checked my kernel version with uname -r command (after rebooting), there was no change and my kernel version was still shown as 3.0.0-15.

A: Follow this instructions to upgrade to kernel 3.2. Works like a charm and you can have 3.2 in your current ubuntu installation.
http://www.liberiangeek.net/2012/01/install-upgrade-to-linux-kernel-3-2-in-ubuntu-11-10-oneiric-ocelot/

A: Upgrading to latest kernel is not always risky, if something does not work properly, you can always get back to previous versions of kernel installed on your computer.


text:
Q: Convert Array of DataFrames to Single DataFrame TLDR: I don't know how to take an array of DataFrames and build a MultiIndex around it.
TLDR 2: From my research, it is recommended to deal with the return result than to try to work off of a global/single/shared DataFrame in Pool().Map(). If somebody has a way to share it, I'm all for it.

I am trying to merge an array of MultiIndex Pandas DataFrames that have been returned by a Pool().Map() function.
p = Pool()
results = p.map(run_experiment, experiment_collection)

Pool().map() returns as an array. Let's say the process returns the array with 1000 DataFrame with a first index of [0:5] and second [0:50].
What I want is to create a final output that is a single DataFrame that would separate each experiment so [0:1000] / [0:5] /[0:50].

I know how to create the MultiIndex using np.zeros_like and then fill the DataFrame, but I don't know how to take an array of DataFrames and build a MultiIndex around it.
rounds = range(0,1000)
levels = [... some set of levels ...]
labels = [... some set of labels ...]
iterables = [rounds, labels, levels]

names = ['round', 'label', 'values']
index = pd.MultiIndex.from_product(iterables, names=names)

index_names = [... some set of index names...]
empty_df = pd.DataFrame(
              np.zeros_like(np.random.randn(5, 50000)),
              index=index_names,
              columns=index
             )
             .sort_index()
             .sort_index(axis=1)

In my first example, results is an array of MultiIndex DataFrame of levels / labels. What I am trying to do is create a final DataFrame that replaces the top level (an array holding all these DataFrames) as just a new index.
When I try
p = Pool()
results = pd.DataFrame(
              p.map(run_experiment, experiment_collection),
              index=index_names,
              columns=index
             )
             .sort_index()
             .sort_index(axis=1)

I am getting ValueError: Shape of passed values is (1, 1000), indices imply (shape of intended index), which makes sense because it is an array of 1000 DataFrames.
If I concatenate (which feels like the better way to go)
results = pd.concat(p.map(run_experiment, experiment_collection))

I get a DataFrame with levels / labels, but no round.
iterables = [rounds, labels, levels]

pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
       keys=None, levels=None, names=None, verify_integrity=False)

I'm not sure what of the options (keys, levels, names) I should be manipulating here to get my rounds back into the DataFrame.
results = pd.concat(
              p.map(run_experiment, experiment_collection),
              levels=iterables,
              names=names,
              axis=1
          )

Gets me really close to the format I want, but no round.

I can get more specific if I need to, but not entirely sure what else would be helpful in getting to the answer.

A: Lacking a better answer, I am recreating my original DataFrame, and iterating through the returned result from Pool().Map(), inserting each list position into the DataFrame. Seems there has to be a better way, but I can't think of it.
p = Pool()
results = p.map(run_experiment, experiment_collection)

final_df = pd.DataFrame(
            np.zeros_like(np.random.randn(5, 50000)),
            index=index_names,
            columns=index
           )
           .sort_index()
           .sort_index(axis=1)

for result in results:
  final_df[increment_value] = result

A: There are several good ways to do this:
1) If you are starting with a bunch of Series objects :
    You set the series objects name parameter to be a tuple. Then use pd.concat([series list], axis=1)
2) If you have a single level map of dataframes, you can use the fact that pd.concat can accept a dict as its first argument. E.g.
pd.concat({A:df1, B:df2}, axis=1)

will create a multilevel index with A, B as the top level and the columns of your df as the second level.Although you cannot nest dicts, you can do this multiple times to build an index of arbitary depth.
3) You can use the Dataframe constructor on a DF but pass a list of tuples as the column names. E.f. if you have a df with columns A,B and you do df_new = pd.DataFrame(df, columns=[("Foo","A"), ("Foo","B")]) and this will create a new df with a multilevel index, you can do this for your df's individually and then concatenate them. Pandas will appropriately concatenate two dataframes with indexes with the same number of levels.


text:
Q: What projection is this geoTIF and how do I convert it? I am working with viewing weather data online and the website I use (University of Oklahoma) provides a link to the data displayed as a geoTIF, for research purposes.  This is a direct link to the geoTIF that I am requesting help with.
I am trying to use the image in a Mapbox map, but there seems to be an issue with projection. I use GDAL tools (though I am a novice) and I can't even figure out what projection it is in to start with. When I use gdalinfo, I get the following result :
Warning 1: RowsPerStrip not defined ... assuming all one strip.
Raster dataset parameters:
  Projection:
  RasterCount: 1
  RasterSize (7000,3500)
Using driver GeoTIFF
  Image Structure Metadata:
    0:  COMPRESSION=DEFLATE
    1:  INTERLEAVE=BAND

Corner Coordinates:
  Upper Left (-130, 55)
  Lower Left (-130, 20)
  Upper Right (-60, 55)
  Lower Right (-60, 20)
  Center (-95, 37.5)

Coordinate System is:

Band 1 :
   DataType: Float32
   ColorInterpretation: Gray
   Description:
   Size (7000,3500)
   BlockSize (7000,3500)
   NoDataValue: -999
   Offset: 0
   Scale: 1

I have been converting other geoTIF files for Mapbox use with the following command successfully :
gdalwarp -t_srs EPSG:3857 example.tif example-projected.tif

... The above code always works except with the file I am needing help with. I am very new with GDAL and though I have been trying it is difficult for me. What am I not doing right and how would I do this the correct way?

A: Your geotiff has no embedded coordinate system associated although the corners are obviously geographic coordinates (unprojected). WGS84 is my guess.
My suggestion is defining a source coordinate system in your command [-s_srs srs_def] and see the result,
-s_srs EPSG:4326
If that doesn't work you'd better ask OU. They should know better.


text: Q: rs-232 communication parameters is up to us or the device? I have a data sheet for rs-232 device but only baud rate parameter is given in it. Is that mean I can put other parameters (Flow control, parity etc…) as I wish ?


text:
Q: Output of xrandr in NVIDIA TwinView I don't have a machine which is running with NVIDIA card. My machine is using
Intel® HD Graphics 4400
One Mini DisplayPort*1 1.2 supporting ultra-high definition
4K displays and multiple monitor functionality
One Mini HDMI* 1.4a port

I can attach two monitors and they works fine, but when I print out xrandr
Screen 0: minimum 320 x 200, current 1920 x 2160, maximum 32767 x 32767
HDMI1 connected 1920x1080+0+1080 (normal left inverted right x axis y axis) 477mm x 268mm
   1920x1080      60.0*+   59.9
   1280x1024      75.0
   1280x720       60.0     59.9
   1024x768       75.1     60.0
   800x600        72.2     75.0     60.3     56.2
   720x480        60.0     59.9
   640x480        75.0     60.0     59.9
   720x400        70.1
DP1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 480mm x 270mm
   1920x1080      60.0*+
   1680x1050      60.0
   1400x1050      60.0
   1600x900       60.0
   1280x1024      75.0     60.0
   1440x900       59.9
   1280x800       59.8
   1152x864       75.0
   1280x720       60.0
   1024x768       75.1     60.0
   832x624        74.6
   800x600        75.0     60.3     56.2
   640x480        75.0     60.0
   720x400        70.1
HDMI2 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

They are in same screen 0 while I want them to be in  two separate screen0 and screen1.
I have heard the NVIDIA TwinView which supports dual head vga, is able to do that but I don't make sure.
Short question: Could anyone use the TwinView and please paste your output of the command xrandr here?
 I just want to know whether there are more than once a screen0. Thank you.

A: The word "screen" is used in the meaning the X11 system uses, which is not intuitive. Rather than a physical screen, it means the logical abstraction for a single framebuffer. A display can have multiple screens, which can have multiple monitors each. Different monitors can then display different, possibly overlapping portions of the same screen.
So rather than "screen 0" and "screen 1", you want a larger "screen 0", with the monitors displaying different portions. You'd set that up with (e.g.)
xrandr --output DP1 --right-of HDMI1

After that, DP1 should report as
DP1 connected primary 1920x1080+1920+0

You'd use a setup with multiple "screen"s if you have multiple graphics cards, which have separate video memory, because in such a setup, rendering commands need to be distributed over separate GPUs, which has significant complexity, while in your case, it is sufficient to simply generate two different output signals.


text:
Q: CraftyJS: I can't destroy an entity with .onHit I am having a problem with craftyJS. I made a ship that shoots lasers, but I want the lasers to destroy an entity when it collides with it. I already tried to do this, but it don't work. Here is my code:
Crafty.init(1340,650, document.getElementById('game'));
Crafty.defineScene("gameStart", function() {
function newAlien(){
    var random = Math.floor(Math.random() * 4) + 1;
    switch(random){
        case 1:
            var alien = Crafty.e("2D, DOM, Image, Collision")
                .image("alien1.png");
            alien.x = ship.x;
            alien.y = 20
            break;
        case 2:
            var alien = Crafty.e("2D, DOM, Image, Collision")
                .image("alien2.png");
            alien.x = ship.x;
            alien.y = 20;
            break;
        case 3:
            var alien = Crafty.e("2D, DOM, Image, Collision")
                .image("alien3.png");
            alien.x = ship.x;
            alien.y = 20;
            break;
        case 4:
            var alien = Crafty.e("2D, DOM, Image, Collision")
                .image("alien4.png");
            alien.x = ship.x;
            alien.y = 20;
            break;
        }
}
function newLaser(){
    var laser = Crafty.e("2D, DOM, Image, Collision")
    .image("laser.png")
    .collision()
    .onHit("alien", function(){
        laser.destroy();
        alien.destroy();
    });
    laser.y = 510;
    laser.x = ship.x + 40;
    var moveLaser = setInterval(function(){
        if(laser.y < 1){
            clearInterval(moveLaser);
            laser.destroy();
        } else {
            laser.y = laser.y - 4;
        }
    }, 1);
}

function checkBorder(){
    if(ship.x < 0 || ship.x > 1250){
        Crafty.enterScene("gameStart");
    }
}
function goLeft(){
    var goLeftCount = 65;
    var goLeftInterval = setInterval(function(){
        if(goLeftCount === 0){
            clearInterval(goLeftInterval);
            checkBorder();
        } else {
        ship.x = ship.x - 1;
        goLeftCount -= 1;
        }
    }, 1);
}
function goRight(){
    var goRightCount = 65;
    var goRightInterval = setInterval(function(){
        if(goRightCount === 0){
            clearInterval(goRightInterval);
            checkBorder();
        } else {
            ship.x = ship.x + 1;
            goRightCount -= 1;
        }
    }, 1);
}
var ship = Crafty.e("2D, DOM, Image, Bind")
    .image("ship.png")
    .bind('KeyDown', function(e) {
            if(e.key == Crafty.keys['LEFT_ARROW']) {
              goLeft();
              } else if (e.key == Crafty.keys['RIGHT_ARROW']) {
              goRight();
              } else if(e.key == Crafty.keys['SPACE']) {
              newLaser();
              }
          });
ship.y = 520;
ship.x = 600;
newAlien();
});
Crafty.enterScene("gameStart");

Can anyone please tell me what are the problems with my code?

A: One problem: when you try to destroy the alien, the alien variable isn't actually in scope.  (You've declared it in a different function.)  So there's no way alien.destroy(); will work.
Second problem: the function you pass to .onHit("alien", callback) will only be run when the laser hits an entity with the "alien" component.  It has no idea what variable name you assigned the entity.  However, the callback function will be passed information about what entities it's colliding with, and you can use that to resolve the collision.


text:
Q: Delphi 2007 - Error handling, not hitting the 'except' section I wrote a primitively simple code where I tried to debug the situation that arose in my project. I'm trying to get into an exception when creating a new window, but I don't get there, why is this? Tell me what's wrong? or what to read for understanding.
So I get to the 'except' section!
procedure TForm1.Button1Click(Sender: TObject);
var
  Local: TForm2;
begin
  try
    //Local := TForm2.Create(nil);
    //Local.Show;

    raise Exception.Create('not implement');
  except
    on E: Exception do
    begin

    end;
  end;
end;

I need to handle this situation. I don't get into the 'except' section like that
Module Form1.pas
procedure TForm1.Button1Click(Sender: TObject);
var
  Local: TForm2;
begin
  try
    Local := TForm2.Create(nil);
    Local.Show;
  except
    on E: Exception do
    begin

    end;
  end;
end;

Module Form2.pas
procedure TForm2.FormCreate(Sender: TObject);
begin
  raise Exception.Create('not implement');
end;

A: You will see that DoCreate that is called from TCustomForm.Create has OnCreate inside a try and its exception passes the exception to TApplication.HandleException which will pass it to TApplication.OnException if one is assigned.
If think if you override your form's HandleCreateException you can return a result of False which will allow the exception to passthrough


text:
Q: How To Change TypeScript Import Type's Font Color in Visual Studio I'm using AMD, and would like to be able to change the font color for imported types:

Currently this is the default color, is there anyway to configure this color?  Not seeing any way to configure this in the Font/Colors section.


text:
Q: Do/While loop not looping I am a beginner in C++ and I was doing a do/while loop exercise and I am having trouble with it recognising the condition let alone it not looping properly. Can you guys give me a good foundation on how a simple problem like this is solved? I want to try and use a string to fulfill the condition of the do/while loop.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
    double mean = 0;
    string continuer;
    do
    {
        cout << "Do you want to proceed?" << endl;
        getline (cin, continuer);
        cout << "something" << endl;
        cin >> mean;
    }
    while (continuer == "Y" || continuer == "y");

    return 0;
}

A: What I gather from your question and comment, you want to iterate through the loop at user's will.
You just want a char variable for that, like this.
string input ;
int number = 0 ;

do
{
  cout << "Please enter a number" << endl ;
  cin >> number ;
  cout << "If you want to continue, Press Y" << endl ;
  cin >> input ;

} while (input == "Y" || input == "y") ;

This do-while loop will execute at least one time, because the condition gets checked at the end of the loop execution. So even if the user does not press Y when asked the first time, this loop would have been executed once. After that, it will go on as long as the condition is fulfilled.
Learn more about the do-while loop here.
http://www.cplusplus.com/doc/tutorial/control/

A: What do you see? The body of the loop should be executed at least once. Does that happen?
Also, Continuer can be longer than one character, for instance "Y\n". Do test for that.
Here is what I would do:
#include <string>
#include <sstream>
using namespace std;

    int main ()
    {
        double number = 0;
        string continuer;
        int loop = 0
        do
        {

            cout << "Do you want to proceed?" << endl;
            getline (cin, number);
            cout << "something" << endl;
            cin>> mean;
            getline (cin, continuer);

            cout << "Your answer was '" << continuer << "'." << endl;
            loop = strcmp("Y", continuer);
            if (loop != 0) strcmp("y", continuer);
            if (loop == 0) cout << "Your choice is to stop." << endl;
            else cout << "Your choice is to continue." << endl;
        } while (loop == 0);
        cout << "Bye" << endl;
        return 0;
    }

Be as explicit as you can untill you are confident enough in the language and the algorithm you are working with. It is easier to see what is happening and when it works it is easy to remove the 'cout' lines.


text:
Q: How to find the average of all the values that are output by a while loop? I'm trying to get the average value of all the r,g,bs that are output by this while loop. Can any one tell me how?
  #include <iostream>
  #include <windows.h>
   using namespace std;

  int main()

     {
    int a = 20, c = 20 , loop=0;

            HDC dc = GetDC(NULL);
            COLORREF color = GetPixel(dc, a, c);
            ReleaseDC(NULL, dc);
            int r1 = GetRValue(color);
            int g1 = GetGValue(color);
            int b1 = GetBValue(color);

            cout << r1 << " " << g1 << " " << b1 << "\n";

            HDC dc = GetDC(NULL);
            COLORREF color = GetPixel(dc, 70, 20);
            ReleaseDC(NULL, dc);
            int r2 = GetRValue(color);
            int g2 = GetGValue(color);
            int b2 = GetBValue(color);

            HDC dc = GetDC(NULL);
            COLORREF color = GetPixel(dc, 120, 20);
            ReleaseDC(NULL, dc);
            int r3 = GetRValue(color);
            int g3 = GetGValue(color);
            int b3 = GetBValue(color);

            HDC dc = GetDC(NULL);
            COLORREF color = GetPixel(dc, 170, 20);
            ReleaseDC(NULL, dc);
            int r4 = GetRValue(color);
            int g4 = GetGValue(color);
            int b4 = GetBValue(color);
            .
                .
                .
                .
                .
                .
                .
                .
                .
                .
                till r35 g35 b35

            HDC dc = GetDC(NULL);
            COLORREF color = GetPixel(dc, 170, 20);
            ReleaseDC(NULL, dc);
            int r35 = GetRValue(color);
            int g35 = GetGValue(color);
            int b35 = GetBValue(color);

          int metaavg = r1 + g1 + b1 + r2 + g2 + b2 + r3 + g3 + b3 +.....
          ...............................................+ r35 + g35 + b35
                cout << metaavg / 105 ;

system("pause");
   }

this is what i want
iam working on "adaptive brightness"
this is a program to calculate white colour of what is being displayed on the screen.........
i dont want to write 600 lines of code.......iam noob.....they dont teach priogramming for doctors here......
everything is done except"wiiting this crap again and again"
is there a better way other than "writing 600 lines of code" or shud i stick with "600 lines of code"
i dont know what.... shadowing..
thank u for the replies....


text:
Q: How to make this function do this in an interval I'm trying to get the first function, to run repeatedly. Like it does in the second function. Where should I take a look?
     (function printLetterByLetter() {
    var i = 0;
    var destination = "comment";
    var RandomComment = [
    "Did you choose that outfit?"
    , "I like trains."];
    var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
    var typewriter = function () {
        document.getElementById(destination).innerHTML += message.charAt(i);
        i++;
        if (i > message.length) {
            clearInterval(typespeed);
        }
    }
    var speed = 60;
    var typespeed = setInterval(typewriter, speed)
}());

(function printLetterByLetter() {
     var destination = "comment";
     var frequency = 1000;
     var RandomComment = [
        "Did you choose that outfit?"
        , "I like trains."];
     var RandomCommentTimer = setInterval(function () {
        var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];

    }, frequency)
}());

So what i'm trying to do is to make one function/module that types out a random comment at a set speed(first function). And after a set time the comment will disappear and a new comment will be typed out(second function). And like the second function this will go on.
So far I haven't made it work myself so I thought: let's see if anyone can help me on stackoverflow.
If anyone can give a tip on where to take a look, that is also most welcome.

A: You could set and alter the function parameters outside of the function then access them inside. Caveat is that you can't put var in front when setting them. Not putting var in front makes it accessible outside of the current scope.
destination = "comment";
frequency = 6000;
(function printLetterByLetter() {
//now you have access to destination and frequency as they are defined before the function is called
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var RandomCommentTimer = setInterval(function () {
    var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
    document.getElementById(destination).innerHTML = message;
}, frequency)
}());


text:
Q: Calculate average packet travel speed in NS2 using AWK
I need to calculate average packet travel speed in ns2. I have to write this formula in awk program. But I have no idea how to do it.
n is the number of received packet, and s is the distance when the packet is transmitted. Any answer will be very helpfull. Thanks.

A: function topla( array ) {sum=0; for (i in array) {sum=sum+250/array[i];}return sum;}

BEGIN {
total_packets_sent = 0;
total_packets_received = 0;
total_packets_dropped = 0;
first_packet_sent = 0;
last_packet_sent = 0;
last_packet_received = 0;}

{event = $1; time = $2; node = $3; type = $4; reason = $5; packetid = $6;

if ( time < simulation_start || simulation_start == 0 )
    simulation_start = time;
if ( time > simulation_end )
    simulation_end = time;

if ( type == "AGT" ) {
    nodes[node] = node; # to count number of nodes
    if ( time < node_start_time[node] || node_start_time[node] == 0 )
        node_start_time[node] = time;

    if ( time > node_end_time[node] )
        node_end_time[node] = time;

    if ( event == "s" ) {
        flows[node] = node; # to count number of flows
        if ( time < first_packet_sent || first_packet_sent == 0 )
            first_packet_sent = time;
        if ( time > last_packet_sent )
            last_packet_sent = time;
        # rate
        packets_sent[node]++;
        total_packets_sent++;

        # delay
        pkt_start_time[packetid] = time;
    }
    else if ( event == "r" ) {
        if ( time > last_packet_received )
            last_packet_received = time;
        # throughput
        packets_received[node]++;
        total_packets_received++;

        # delay
        pkt_end_time[packetid] = time;
    }
}}`

END {

# delay
for ( pkt in pkt_end_time) {
    end = pkt_end_time[pkt];
    start = pkt_start_time[pkt];
    delta = end - start;
    if ( delta > 0 ) {
        delay[pkt] = delta;

    }
}

result=topla(delay)/total_packets_received;

printf(result)

}
I write this awk program. But it gives the division by zero attempted error.And I wrote the transmission range in the topla function as 250, but I did not get the results I wanted.How should I write the transmission range?


text:
Q: Upgrade from Magento 1.5 to 1.9 I actually want a clean magento 1.9, without any modules/extensions/themes, but would like to keep at least products and customers. Orders are good to keep, but not necessary.
Now I tried:

*

*A fresh install. Trying to use Magento's built-in import/export customers and products, but errors were there. Something like "field value not valid" or "field value empty." Seems Magento 1.5 and 1.9 import/export not compatible?

*Download Magento full package to my server and then run initial setup with the old 1.5 database, hoping that it would upgrade my database automatically. At some point there was a server 500 error. The old Magento does have some extensions/modules/custom themes.
Any advise? What would be the best way to achieve my goal? Thank you.

A: We don't know how your database looks. Modules could have put extra keys, dependencies, etc.
I would suggest using a clean install like you are doing and you are going to have to debug these errors. Magento 1.5 can be upgraded to Magento 1.9.
I would suggest the following steps.

*

*Make sure you are using version control and a staging environment.

*Get your Magento working on a clean version of V1.5, set the theme to base/default, and verify everything is working.

*Set your server memory_limit to at least 512MB and max_execution_time to 180000

*Delete your V1.5 code from the directory (keep the app/etc/local.xml)

*Push the V1.9 code into your directory (re-add the app/etc/local.xml), and hit your site once.

*The upgrade will take some time, depending on the power of your server

Make sure to delete the V1.5 code and then migrate the V1.9 code in as Magento did remove some files.
From Magento directly:

Do not upgrade Magento in the same directory on the same server because post-upgrade errors are likely to occur.

Source: http://www.magentocommerce.com/knowledge-base/entry/ee11302-ce18-install-upgrade

A: I just went through this. Moving from a very bloated 1.7 to 1.9, but junking a lot of the old extensions/scripts.
For future visitors, here's what I did.

*

*Copied old DB, call it site_new_db.

*Installed 1.9 in a sub folder, pointed at site_new_db, hit site, upgraded tables etc.

*Applied new theme. Got everything looking how I wanted.

*

*in the interim the production site took more orders and new customers, so:

*I exported all customer, invoices etc tables per here and here. You may have trouble with foreign key checks, so disable those, and if it persists, I just kyboshed (truncated or dropped) the tables I was trying to import then imported.
[Note: this might be terribly poor practise and hacky but it worked, and I am by no means a DB dev or coder]

*Then I imported all the inventory tables to the new site to get the stock levels right.

*Lastly I merged (downloaded, then uploaded via Transmit and MERGED) the catalog folder to make sure all images worked.

It should be noted we moved from having an old 1.7 site in html root, into a sub folder with some rewrites to root so the domain.com/subfolder looks like domain.com.
Now I've read that I'm sure I am underpaid at $25/hr. :)

A: Over such big version changes most people prefer to do an product and customer export and import, like you already tried. Thats sure the best solution, to avoid problems with once installed modules.
But the export part is a problem here, because I think its even partially broken inside magento.
So my suggested solution would be to use for example https://github.com/avstudnitz/AvS_FastSimpleImport as a tool for import, but write your own export script

A: Instead of upgrading directly from 1.5.x to 1.9.x, you may want to consider upgrading gradually from 1.5.x to 1.6.x to 1.7.x to 1.8.x to 1.9.x. By doing so, you will be able to catch any bugs and fix them before you move on to the next version.
I do highly recommend that you first try this on a staging store and you take multiple backups before you proceed to allow you to roll back easily.


text:
Q: Arrow function to callback function for IE support Since IE won't accept my arrow function, I am trying to convert the below function to a callback-function instead:
Origional function:
function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}

Callback function:
function getKeyByValue(object, value) {
  Object.keys(object).find( function(key) {
      return object[key] === value;
  })
}

However, the new function is not returning anything. What am I missing?


text:
Q: Github API error "Problems parsing JSON" when using curl but works fine with Postman I am trying to create a release using Github's API.
My request works fine in Postman but no matter what I've tried it always fails with curl, including if I just translate my Postman request into curl using Postman.
This is the body of my Postman POST request:
{
    "tag_name": "4.2.0",
    "target_commitish": "master",
    "name": "4.2.0",
    "body": "test"
}

I've included an authorization header of type "Basic", where I input my username and a token I have created for this purpose.
I am executing the request against https://api.github.com/repos/<myUsername>/<myRepo>/releases.
As I said - it works fine, but when I translate it into curl I get the error "Problems parsing JSON".
The translated curl command is:
curl --location --request POST 'https://api.github.com/repos/<myUsername>/<myRepo>/releases' \
--header 'Authorization: Basic <someHashOrSomething>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "tag_name": "4.2.0",
    "target_commitish": "master",
    "name": "4.2.0",
    "body": "test"
}'

which I reformat into curl --location --request POST 'https://api.github.com/repos/<myUsername>/<myRepo>/releases' --header 'Authorization: Basic <someHashOrSomething>' --header 'Content-Type: application/json' --data-raw '{   "tag_name": "4.2.0",    "target_commitish": "master",   "name": "4.2.0",    "body": "test"}' to be on one line.
I also tried (since only the "tag_name" parameter is required):
curl -i -H 'Authorization: token <myToken>' -d '{"tag_name":"4.2.0"}' https://api.github.com/repos/<myUsername>/<myRepo>/releases
curl -i -H 'Authorization: token <myToken>' -d '{"tag_name":"4.2.0"}' https://api.github.com/repos/<myUsername>/<myRepo>/releases --header Content-Type:application/json
curl -d '{"tag_name":"4.2.0"}' -u <myUsername>:<myToken> https://api.github.com/repos/<myUsername>/<myRepo>/releases --header "Content-Type:application/json"
curl -d "tag_name=4.2.0" -u <myUsername>:<myToken> https://api.github.com/repos/<myUsername>/<myRepo>/releases --header "Content-Type:application/json"
Every curl request fails with the "Problems parsing JSON" error.

A: If you are doing this from the windows cmd prompt, you need to change
--data-raw '{   "tag_name": "4.2.0",    "target_commitish": "master",   "name": "4.2.0",    "body": "test"}'

to
--data-raw "{   \"tag_name\": \"4.2.0\",    \"target_commitish\": \"master\",   \"name\": \"4.2.0\",    \"body\": \"test\"}"

cmd prompt appears to not like single quotes for the data.

A: How to debug:

*

*Add "-v --trace-ascii -" to the curl command to see log for command.

*Use  echo or write-host for your data in cmd or PowerShell

Remember that It is so important to make sure that curl receives valid JSON data.
See an example of Powershell here:

A: The problem could be your API key.
Check if it has the sufficient permissions or try and create a new one.


text:
Q: Swift problem with dismissing view and then present new one I have TabBarViewController, when I click on his children, view is presented, which is called SettingsVC, inside SettingsVC I have tableview, which at the bottom has logout, when I click on logout, I would like to dismiss SettingsVC and present LoginVC, but I can't manage to implement this. I know I should use delegate, protocol, but I am doing something wrong. Code is below, thanks.
Code below is from SettingsVC
protocol PresentViewControllerDelegate: class {
    func presentViewController(vc: LogInViewController)
}

class SettingsVC: UIViewController, UITabBarDelegate, UITabBarControllerDelegate {

    public var presentDelegate: PresentViewControllerDelegate?

    func present() {
        presentDelegate?.presentViewController(vc: LogInViewController())
    }

    func logoutUser() {
    networkManager.logout(endpoint: "/v1/auth/logout") { (session) in
        switch session {
        case .success:
            print(session)
            self.dismiss(animated: true, completion: nil)
            self.present()
        case .failure(let error):
            print(error.localizedDescription)
        }
     }
 }

extension SettingsVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let settings = SettingsEnums(rawValue: indexPath.row)

    switch settings {
    case .passcode:
        print("passcode")
    case .about:
        print("about")
    case .termsAndConditions:
        print("terms and conditions")
    case .privacyPolicy:
        print("privacy policy")
    case .visit:
        print("visit")
    case .logout:
        logoutUser()
        print("logout clicked")

    default:
        print("default")
    }
  }
}

And then I tried this in TabBarVC
extension TabBarViewController: PresentViewControllerDelegate {
    func presentViewController(vc: LogInViewController) {
      self.present(self, animated: true, completion: nil)
   }
}

class TabBarViewController: UITabBarController, UINavigationControllerDelegate {

var settingsVC: SettingsVC!

override func viewDidLoad() {
    super.viewDidLoad()
    settingsVC.presentDelegate = self
  }
}

I do have success in logout, and I manage to dismiss SettingsVC, but cannot manage to present LogInVC. If you think that this would have a delay and it could be visible that "exchange", please can you suggest some other solution?
I have hard time understanding delegates..
Thanks in advance.


text:
Q: Unhappy Sweave engine in Texshop I am working on setting up a new M1 Silicon Monterey OS Mac and my handy-dandy Sweave engine that I like to add to Texshop does not work. I have a Sweave.engine file in my Engines folder with the following:
#!/bin/bash

export PATH=$PATH:/usr/texbin:/usr/local/bin
R CMD Sweave "$1"
pdflatex "${1%.*}"

It creates the drop down menu, but it seems unhappy about the path (as best I can guess) as it says it cannot find the file. Similarly running line by line in Terminal I get:
Mecomputerhere:~ lizzie$ R CMD Sweave "$1"
Error in (function (file, dir = ".", weave = TRUE, latex = TRUE, tangle = TRUE,  :
  file '""' not found
Calls: <Anonymous> -> do.call -> <Anonymous>
Execution halted

Here's the error in the tex console:
`Error in (function (file, dir =".", weave = TRUE, latex = TRUE, tangle = TRUE, :
file `"test.Rnw"' not found
Calls: <Anonymous> -> do. call -> <Anonymous>
Execution halted
This is pdfTeX, Version 3.141592653-2.6-1.40.24 (Tex Live 2022)
(preloaded format=pdflatex)
restricted \write18 enabled.
entering extended mode
! I can't find file `"test"'.
<*>"test"

I suspect this is a basic path issue (I am bad at paths) so any help would be much appreciated. Thanks in advance.
Update: This version of the engine code works:
#!/bin/bash
export PATH=$PATH:/usr/texbin:/usr/local/bin
R CMD Sweave "$1"
pdflatex "${1%.*}"


text:
Q: Boolean value assignment in Java Apologies for the total noob question, but can anyone explain what's happening to the value of match after the for-each loop has finished in the following method?
Attempts to compile produce the warning: variable match might not have been initialised.
public void listMatching(String searchString) {
boolean match;

for(String filename : files) {
    if(filename.contains(searchString)) {
        System.out.println(filename);
        match = true;
    }
    else {
        match = false;
    }
}

if(match == false) {
    System.out.println("No matches found for " + searchString);
}
}

A: First you need to define boolean match = false;
Also,you need to break from the loop once you found the match , other-wise match status will be over-ridden.
 if(filename.contains(searchString)) {
        System.out.println(filename);
        match = true;
        break;
    } // this wil help whether a match is found or not

If you are interested in finding number of matches
 int counter = 0;
 if(filename.contains(searchString)) {
            System.out.println(filename);
            match = true;
            counter++;
        } // this wil help to find number of matches
finally System.out.println("number of matches for"+searchString+" : "+counter);

A: Here's a fix that will do what you want it to:
public void listMatching(String searchString) {
    boolean match = false; // initialize local variable
    for(String filename : files) {
        if(filename.contains(searchString)) {
            System.out.println(filename);
            match = true;
        }
    }
    if(!match) { // same as 'match == false', just without comparison
        System.out.println("No matches found for " + searchString);
    }
}

Local variables have to be initialized. Only fields get the default value of their type.
If you reassign match to false in the else block, it would be false after the loop, even if every filename contained searchString except the last one.

A: *

*You need to break the loop when you found your match.

*you need to initialize your found variable, you could also never run your loop, and then your if condition would look at a non initialized variable, thats what your compiler wants to tell you

A: Initialise the variable to false to avoid the warning in your program.
Also, match is a single variable and depending upon the contents of various files (searching for the same string), you are assigning true or false to the same variable.
The final boolean value of match is just the result of the search for the string in the last file of the list of files.

A: It may files array is empty, so you should set default value for match variable;
boolean match=false;

for(String filename : files) {
    if(filename.contains(searchString)) {
        System.out.println(filename);
        match = true;
        break;
    }
}

if you need to check that all of files has this search string U can use this code :
boolean match=files.lenght!=0;

for(String filename : files) {
    if(!filename.contains(searchString)) {
        System.out.println(filename);
        match = false;
        break;
    }
}


text:
Q: Abs[x] not recognized in symja math parser I have imported the .jar files, but
DoubleEvaluator engine = new DoubleEvaluator();
engine.defineVariable("x", -1);
engine.evaluate("Abs[x]");

throws me an error: org.matheclipse.parser.client.math.ArithmeticMathException: EvalDouble#evaluateFunction(FunctionNode) not possible for: Abs(x)
and
engine.evaluate("Sin[x]");

does not. What could be the reason for this?
Exception in thread "main" org.matheclipse.parser.client.math.ArithmeticMathException: EvalDouble#evaluateFunction(FunctionNode) not possible for: Abs(x)
at org.matheclipse.parser.client.eval.DoubleEvaluator.evaluateFunction(DoubleEvaluator.java:563)
at org.matheclipse.parser.client.eval.DoubleEvaluator.evaluateNode(DoubleEvaluator.java:493)
at org.matheclipse.parser.client.eval.DoubleEvaluator.evaluate(DoubleEvaluator.java:460)
at javaapplication14.JavaApplication14.main(JavaApplication14.java:24)
Java Result: 1

and the example run
import org.matheclipse.parser.client.eval.DoubleEvaluator;

public class application {

public static void main(String[] args) {

    DoubleEvaluator engine = new DoubleEvaluator();

    engine.defineVariable("x",-1);
    engine.evaluate("Abs[x]");

}

}

A: (Thanks for the stacktrace and the download address)
This issue has been fixed some hours ago, the newest version should solve the problem:
https://bitbucket.org/axelclk/symja_android_library/downloads/symjaMMA2016-01-09.zip
The missing function Abs was added:
FUNCTION_DOUBLE_MAP.put("Abs", new IDouble1Function() {
   public double evaluate(double arg1) {
      return Math.abs(arg1);
   }
 });

See the difference:
https://bitbucket.org/axelclk/symja_android_library/diff/symja_android_library/matheclipse-parser/src/main/java/org/matheclipse/parser/client/eval/DoubleEvaluator.java?diff2=c84fa1c92f83&at=master


text:
Q: Error: Type object has no attribute 'Query' I am trying to create my first website using Python + flask and am now having issues trying to add data to SQLite database using Flask-SQLAlchemy.
This is part where I am trying to add user to database but it fails:
@app.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('registracija.html')
    elif request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        user = User.Query(filter_by=username)
        if user.count() == 0:
            user = User(username=username, password=password)
            db.session.add(user)
            db.session.commit()

            flash('You have registered the username {0}. Please login'.format(username))
            return redirect(url_for('login'))
        else:
            flash('The username {0} is already in use.  Please try a new username.'.format(username))
            return redirect(url_for('register'))
    else:
        abort(405)

And my register.html page:
<form method="post" >

    Username:

    Password:

    Please repeat password:

   <input type="text" name="username" />

   <input type="password" name="password" />

   <input type="password" name="repeatpassword" />

   <input type="submit" name="register" value="Registruotis" />

</form>

When I fill form and press register button I get:

AttributeError: type object 'User' has no attribute 'Query'

Would be nice if someone could point me what I am doing wrong. I am running Python 3.5 On Windows 10.

A: user = User.Query(filter_by=username)

should be
user = User.query.filter_by(username=username).first()

All names in Python are case-sensitive: variable names, function names, class names, module names, exception names. If you can get it, set it, call it, construct it, import it, or raise it, it's case-sensitive. Hence the error you are receiving about user not having any attribute 'Query' when it does have an attribute 'query'.


text:
Q: Query LIKE on date type I am doing queries on the free DB of W3School and I have to do a query where I print every record that has year = 1996, month = 07 and any day.
I searched and I tried this form:
SELECT Customers.Country
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID
AND (DATEPART(yy, OrderDate) = 1996
AND DATEPART(mm, OrderDate) = 07);

But it doesn't work...
I can use this form:
SELECT *
FROM Orders
WHERE OrderDate BETWEEN #07/15/1996# AND #07/31/1996#;

but this still don't know why other forms don't work!

A: The thing is, this learning platform seems to be running a vendor-agnostic SQL system. Apparently you only have access to the most basic functions like SELECT, UPDATE, that is the standard commands that work on every system.
The functions available, including date functions vary depending on the DBMS.
Either clarify the DBMS in use, or find another platform.
Of course, to extract months, years from dates they should be stored as date, or datetime and not as strings.
There is another downside to using functions like DATEPART: you will not be able to use indexes and the queries will take a long time on large tables because they will require a full table scan.
Assuming there is an index on OrderDate, a clause like this could take advantage of the index:
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31'

or:
WHERE OrderDate >= '1996-07-01' AND OrderDate <= '1996-07-31'

To sum up, you need to know what you are working on. Only then, you will be able to establish what functions are available to you. Again, it seems to be a trimmed-down environment where you won't be able to achieve much.

A: I believe that w3schools actually uses SQL-lite for their editor and then this would work:
SELECT c.Country
FROM Customers c
join Orders o on c.CustomerID = o.CustomerID
where strftime('%Y', o.OrderDate) = '1996'
and strftime('%m', o.OrderDate) = '07'

I would like to give you few advice's with this code:

*

*Use aliases for your tables (aliases are this letters c and o and they are used so the code can be more readable. If you can use something with more sense than one letter do it like that, for example cust for customers or ord for orders table).

*Use modern join like this:
FROM Customers c
join Orders o on c.CustomerID = o.CustomerID

and not like this:
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID

*You do not need to put this two AND conditions inside brackets.

*To make this work result of strftime function needs to be compared with values between single quotes. This is tested and works here https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

I have also installed Firefox on my PC (Firefox is under "WebSQL Browser Support") and this is the code that works on Firefox:
SELECT c.Country
FROM Customers c, Orders o
where c.CustomerID = o.CustomerID
and year(o.OrderDate) = 1996
and month(o.OrderDate) = 7

A: You can use the strfttime() function for this. Pass '%m' for a monthly search or '%y' for a yearly search.
SELECT Customers.Country
FROM Customers, Orders
WHERE Customers.CustomerID = Orders.CustomerID
AND strfttime('%y', OrderDate) = 1996
AND strfttime('%m', OrderDate) = 07;


text:
Q: Cypress to get only href in a page that contains specific path inside I am trying to make a test that actually look into all the href in a page, and ONLY if the path url contains /example (mywebsite.com/example/anotherPage) inside the href, I want to test the url.
describe('VerifyProductsLinks', () => {
  it('passes', () => {
    cy.visit('/')
    cy.get('a').each((page) => {
      if (page.prop('href').should('contains', '/example')) {
        cy.request(page.prop('href'))
      }
    })
  })
})

This is what I tried, but I get the error page.prop is not a function. What I am doing wrong?

A: You can apply a filter function on the <a> elements.  IMO me this is the tidiest way.
Also note page.prop() is not always the same as page.attr(), which is the preferred way of extracting an attribute value.
cy.get('a')
  .filter('[href*="/example"]')
  .each((page) => {
    cy.request(page.attr('href'))
  })

A: Alternatively, you can use jquery attribute contains selector to only return anchors with the matching value.
In your example it would look like this
cy.get('a[href*="/example"]')
  .should('have.length.gte', 1)
  // map out only hrefs
  .then(h => Cypress._.map(h, el => el.href))
  .each(href => {
    cy.request(href)
    // any other code
  })

Here is an example for getting hrefs containing a value.

A: You don't need an .each() and if().
Instead you could change the Cypress subject from the element to the attribute using .invoke()
cy.get('a[href*="/example"]')
  .invoke('attr', 'href')
  .then(href => {
    cy.request(href)
  })

A: You can use Cypress to collect all a elements (assuming those are the ones with hrefs), iterate through them with cy.each(), and then only take actions if the element's href contains a certain value (by using the yielded element, JQuery's .prop() function, and JavaScript String .includes().
cy.get('a').each(($a) => {
  if ($a.prop('href').includes('/example') {
    // cypress code here
    cy.request($a.prop('href'));
  }
});

Attempting to do an if/else on a Cypress command directly will not work as expected, as these commands do not yield a boolean value to be evaluated.


text:
Q: c++ argument of type x is incompatible with parameter of type with atexit I get this error when I try to run a function with theatexti() in std. I don't understand the error.
Here is the error:
 IntelliSense: argument of type "void (Demo3Main::*)()" is incompatible with parameter of type "void (__cdecl *)()"

and here is the code:
Demo3Main::Demo3Main(void)
: BaseEngine( 50 )
{
    atexit(RestorScore);
}

void Demo3Main::RestorScore(){
    std::ofstream outfile("old_score.txt");
    int num1 = 0;
    outfile << num1;
    outfile.close();
}

A: ELI5 version
The specifications for atexit's callback is
void (*function)(void)

This means you have to pass a function on the form:
void my_function()
{
}

But, you passed a class member function which has a different type. Its type is:
 void (Demo3Main::*)()

You can get your program to work by writing the function outside of a class. For example:
void RestorScore(){
   std::ofstream outfile("old_score.txt");
   int num1 = 0;
   outfile << num1;
}
atexit(RestoreScore);


text:
Q: In Django how to render hello.html in base.html? I am new to django and I misunderstand how to use templates.
I have a a file called base.html which I see as a parent to hello.html.
In hello.html I have this syntax:
{% extends "base.html" %}
{% block hello %}

hello

I should see this template. This is the hello.html template.
{% endblock %}

In base.html I have this syntax:
{% block hello %}{% endblock %}

It is my understanding that django should render hello.html inside of base.html
When I deploy my two html files, django ignores my syntax.
Question: How to render hello.html in base.html?
The files are visible inside of github:
https://github.com/danbikle/sof1231/blob/master/hello/templates/base.html
https://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html
Also I deployed them to heroku with these commands:
heroku create sof1231
git push heroku master

You can see base.html deployed to https://sof1231.herokuapp.com
Again,
How to render hello.html in base.html?

A: To render a template in another template, you use include:
base.html
{% include 'hello.html' %}

A: Your templates are designed to work with inheritance, and there is nothing wrong with the simplified templates that you show in your question (I didn't check those on github).
I think that your problem might be caused by your view rendering the base.html template, when it should instead be rendering the hello.html template. You should add your view code to your question so that this can be verified. Your view code should be something like this, which renders the child template hello.html:
def hello(request):
    template_variables = {'a': 1, 'b': 2}
    return render(request, 'hello.html', template_variables)

Another answer (which you have accepted) recommends using include. I don't think that include is the correct approach.
There is a difference between inheriting from a base template and simple inclusion of content from another file. One important benefit of template inheritance is that you can add common content (e.g. menu, side bars, footers, etc.) to a "base" template and then inherit from that base in child templates without duplicating the common content for each page. Another benefit is that the child templates can override content in the base templates, e.g. <title>. This allows you to markup areas of your layout in the base template (using block) and then override the content of the block with other content. This is not possible with a simple include.


text:
Q: How to place divs one next to another without floatant? I managed to place two divs one next to the other using float: left, but the div below doesn't display properly : http://jsfiddle.net/N4kE3/2/
And with this css for each div :
display: inline-block;
width: 50%;

see: http://jsfiddle.net/N4kE3/3/
They are one above the other. I have to put width: 49% to make them be one next to the other.
How is that possible ?

A: If you wish to keep your floats you could use a clearfix on the container:
Working demo
#action:after {
    content: "";
    display: table;
    clear: both;
}

If you wish to useinline-block you need to remove the white space in your markup:
Working demo
This..

Buy

Sell

Becomes...

Buy

Sell

.. otherwise the white space will be taken into account when calculating the widths making 50% + 50% + whitespace = more than 100%. Thats just how inline-block works.

A: The space between elements is displayed. Imagine Hello world. This is displayed as "Hello world". See the space between Hello and World.
An enter and multiple spaces are collapsed to a single space.
  Hello
  world

becomes "Hello world".
The same is happening with your divs. They are both 50% of the screen, but the space also takes up 10 pixels, pushing the 2nd div to the next line.
There are several ways of solving this. Using float, using display: table-cell or (as I usually prefer) by eliminating the space between the divs using XML comments .

Buy

Sell

test

See the fiddle


text:
Q: Is it possible to force use of overflow menu to the right of software button? I have an action bar with many options and a menu.
On devices that don't have menu button, the overflow menu is added to my action bar.
I want to add this overflow menu button to the right of the software buttons, just like application that don't have an action bar, like this :

Is it possible, and, if it's possible, how to do this ?

A:
Is it possible

Yes, if you do not mind your app looking like you are no longer maintaining it, thereby reducing your prospective user base.
Please read Say Goodbye to the Menu Button, particularly this passage:

However, this button doesn't provide an ideal user experience. In fact, in apps that don't use an options menu anyway, this action overflow button does nothing and creates user confusion. So you should update your legacy apps to remove the action overflow from the navigation bar when running on Android 3.0+ and begin using the action bar if necessary. You can do so all while remaining backward compatible with the devices your apps currently support.

Talented developers, therefore, are trying to avoid putting that affordance in the system/navigation bar, not adding that affordance.

how to do this ?

Set your android:targetSdkVersion and your android:minSdkVersion to something less than 11.

A: This button is automatically added by Android if your minSdkVersion and targetSdkVersion are less than API 11. The only exception is that if you set minSdkVersion to 10 or lower, set targetSdkVersion to 11, 12, or 13, and you do not use ActionBar, the system will add the legacy overflow button when running your app on a handset with Android 4.0 or higher.
If your targetSdkVersion and/or minimumSdkVersion are at or over API 11, then you cannot use this button.


text:
Q: Finding the dimension of the reward matrix in an inverse reinforcement learning problem In one of the easy cases of inverse reinforcement learning, we try to derive the unknown reward function assuming that an optimal policy is known and MDP is completely known.
Let $P_{a_1}$ be the probability transition matrix from one state to another, following the optimal policy $\pi(s) = a_1$. Assuming $n$ states, then this matrix is $n \times n$. On the other hand, $P_a$ is the transition matrix of all other policies that are not $a_1$. Still $n \times n$.
If $I$ is the identity matrix and $\gamma$ is the reward discount factor (scalar), what is the dimension of $R$ in the follow rule? (from Algorithms for inverse reinforcement learning, by Ng and Russell, 2000)
$$(P_{a_1} - P_a)(I - \gamma P_{a_1})^{-1}R \geq 0 $$
Is $R$ a vector? or $n \times n$ matrix? And what would this mean?

A: As the paper of Ng and Russell (2000) indicates in section 2.1, the reinforcement function $R$, takes as input a state, and as output has the reward, a real number. Therefore $R$ should be a vector of $n$ items. The result of equation (4) of the paper:
$$(P_{a_1} - P_a)(I - \gamma P_{a_1})^{-1}R$$
therefore also is a vector of $n$ items.

Note that the reward function can also be defined with the parameters state ($s$), next state ($s'$), and action ($a$): $R_{ss'}^a$ as done by Sutto and Barto (1998, section 3.6).


text:
Q: NSJSONSerialization dataWithJSONObject: options:NSJSONWritingPrettyPrinted error: method adding extra "/" In my method, I need to call a web service. I have used the following
[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&parseError]

where jsonDictionary is
{
  "timeStamp" : "",
  "listOfScratchNotes" : [
    {
      "id" : "13",
      "location" : "reqw",
      "dateOfMeeting" : "23/12/2012",
      "dealers" : "fr"
    }
  ]
}

After using the dataWithJSONObject: method, my dateOfMeeting: gets converted to 23\/12\/2012
How can I avoid this?

A: Try this:
NSDictionary *dict =      // Dictionary here..

NSData *dataRecvd = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
if(!dataRecvd && error){
    NSLog(@"Error creating JSON: %@", [error localizedDescription]);
    return;
}

//NSJSONSerialization converts a URL string from http://... to http:\/\/... remove the extra escapes
Str = [[NSString alloc] initWithData:dataRecvd encoding:NSUTF8StringEncoding];
Str = [Str stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
dataRecvd = [policyStr dataUsingEncoding:NSUTF8StringEncoding];


text:
Q: Is there a way to display/print the attribute of variable/member in C++ I am working on someone else project in C++. There are many variables which are created based on other classes. For example:
Class_C newVariable;
which Class_C is created based on Class_B and may be inherit from Class_A and so on, thus newVariable may contain many class members.
Is there anyway or easy to print or display all members of newVariable in C++?

ps. I am using Visual Studio for coding and debugging.

A: I recently asked myself the same question. Take a look at the following discussions:
how-can-i-add-reflection-to-a-c-application
generic-way-to-print-out-variable-name-in-c
Meta Classes
"Reflection" Visual Studio
To sum it up, C++ is built for speed, there is no way to get the info about your classes (during the runtime), at least not using a core feature of C++ (as we have reflection in Java). There are different tricks and extensions to do that (as you can find in the links posted above), but they are still... tricks and extensions.